three.core.js 1.3 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432
  1. /**
  2. * @license
  3. * Copyright 2010-2025 Three.js Authors
  4. * SPDX-License-Identifier: MIT
  5. */
  6. const REVISION = '175dev';
  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. * Discards the red, green and blue components and reads just the alpha component.
  643. *
  644. * @type {number}
  645. * @constant
  646. */
  647. const AlphaFormat = 1021;
  648. /**
  649. * Discards the alpha component and reads the red, green and blue component.
  650. *
  651. * @type {number}
  652. * @constant
  653. */
  654. const RGBFormat = 1022;
  655. /**
  656. * Reads the red, green, blue and alpha components.
  657. *
  658. * @type {number}
  659. * @constant
  660. */
  661. const RGBAFormat = 1023;
  662. /**
  663. * reads each element as a single luminance component. This is then converted to a floating point,
  664. * clamped to the range `[0,1]`, and then assembled into an RGBA element by placing the luminance value
  665. * in the red, green and blue channels, and attaching 1.0 to the alpha channel.
  666. *
  667. * @type {number}
  668. * @constant
  669. */
  670. const LuminanceFormat = 1024;
  671. /**
  672. * Reads each element as a luminance/alpha double. The same process occurs as for the `LuminanceFormat`,
  673. * except that the alpha channel may have values other than `1.0`.
  674. *
  675. * @type {number}
  676. * @constant
  677. */
  678. const LuminanceAlphaFormat = 1025;
  679. /**
  680. * Reads each element as a single depth value, converts it to floating point, and clamps to the range `[0,1]`.
  681. *
  682. * @type {number}
  683. * @constant
  684. */
  685. const DepthFormat = 1026;
  686. /**
  687. * Reads each element is a pair of depth and stencil values. The depth component of the pair is interpreted as
  688. * in `DepthFormat`. The stencil component is interpreted based on the depth + stencil internal format.
  689. *
  690. * @type {number}
  691. * @constant
  692. */
  693. const DepthStencilFormat = 1027;
  694. /**
  695. * Discards the green, blue and alpha components and reads just the red component.
  696. *
  697. * @type {number}
  698. * @constant
  699. */
  700. const RedFormat = 1028;
  701. /**
  702. * Discards the green, blue and alpha components and reads just the red component. The texels are read as integers instead of floating point.
  703. *
  704. * @type {number}
  705. * @constant
  706. */
  707. const RedIntegerFormat = 1029;
  708. /**
  709. * Discards the alpha, and blue components and reads the red, and green components.
  710. *
  711. * @type {number}
  712. * @constant
  713. */
  714. const RGFormat = 1030;
  715. /**
  716. * Discards the alpha, and blue components and reads the red, and green components. The texels are read as integers instead of floating point.
  717. *
  718. * @type {number}
  719. * @constant
  720. */
  721. const RGIntegerFormat = 1031;
  722. /**
  723. * Discards the alpha component and reads the red, green and blue component. The texels are read as integers instead of floating point.
  724. *
  725. * @type {number}
  726. * @constant
  727. */
  728. const RGBIntegerFormat = 1032;
  729. /**
  730. * Reads the red, green, blue and alpha components. The texels are read as integers instead of floating point.
  731. *
  732. * @type {number}
  733. * @constant
  734. */
  735. const RGBAIntegerFormat = 1033;
  736. /**
  737. * A DXT1-compressed image in an RGB image format.
  738. *
  739. * @type {number}
  740. * @constant
  741. */
  742. const RGB_S3TC_DXT1_Format = 33776;
  743. /**
  744. * A DXT1-compressed image in an RGB image format with a simple on/off alpha value.
  745. *
  746. * @type {number}
  747. * @constant
  748. */
  749. const RGBA_S3TC_DXT1_Format = 33777;
  750. /**
  751. * A DXT3-compressed image in an RGBA image format. Compared to a 32-bit RGBA texture, it offers 4:1 compression.
  752. *
  753. * @type {number}
  754. * @constant
  755. */
  756. const RGBA_S3TC_DXT3_Format = 33778;
  757. /**
  758. * A DXT5-compressed image in an RGBA image format. It also provides a 4:1 compression, but differs to the DXT3
  759. * compression in how the alpha compression is done.
  760. *
  761. * @type {number}
  762. * @constant
  763. */
  764. const RGBA_S3TC_DXT5_Format = 33779;
  765. /**
  766. * PVRTC RGB compression in 4-bit mode. One block for each 4×4 pixels.
  767. *
  768. * @type {number}
  769. * @constant
  770. */
  771. const RGB_PVRTC_4BPPV1_Format = 35840;
  772. /**
  773. * PVRTC RGB compression in 2-bit mode. One block for each 8×4 pixels.
  774. *
  775. * @type {number}
  776. * @constant
  777. */
  778. const RGB_PVRTC_2BPPV1_Format = 35841;
  779. /**
  780. * PVRTC RGBA compression in 4-bit mode. One block for each 4×4 pixels.
  781. *
  782. * @type {number}
  783. * @constant
  784. */
  785. const RGBA_PVRTC_4BPPV1_Format = 35842;
  786. /**
  787. * PVRTC RGBA compression in 2-bit mode. One block for each 8×4 pixels.
  788. *
  789. * @type {number}
  790. * @constant
  791. */
  792. const RGBA_PVRTC_2BPPV1_Format = 35843;
  793. /**
  794. * ETC1 RGB format.
  795. *
  796. * @type {number}
  797. * @constant
  798. */
  799. const RGB_ETC1_Format = 36196;
  800. /**
  801. * ETC2 RGB format.
  802. *
  803. * @type {number}
  804. * @constant
  805. */
  806. const RGB_ETC2_Format = 37492;
  807. /**
  808. * ETC2 RGBA format.
  809. *
  810. * @type {number}
  811. * @constant
  812. */
  813. const RGBA_ETC2_EAC_Format = 37496;
  814. /**
  815. * ASTC RGBA 4x4 format.
  816. *
  817. * @type {number}
  818. * @constant
  819. */
  820. const RGBA_ASTC_4x4_Format = 37808;
  821. /**
  822. * ASTC RGBA 5x4 format.
  823. *
  824. * @type {number}
  825. * @constant
  826. */
  827. const RGBA_ASTC_5x4_Format = 37809;
  828. /**
  829. * ASTC RGBA 5x5 format.
  830. *
  831. * @type {number}
  832. * @constant
  833. */
  834. const RGBA_ASTC_5x5_Format = 37810;
  835. /**
  836. * ASTC RGBA 6x5 format.
  837. *
  838. * @type {number}
  839. * @constant
  840. */
  841. const RGBA_ASTC_6x5_Format = 37811;
  842. /**
  843. * ASTC RGBA 6x6 format.
  844. *
  845. * @type {number}
  846. * @constant
  847. */
  848. const RGBA_ASTC_6x6_Format = 37812;
  849. /**
  850. * ASTC RGBA 8x5 format.
  851. *
  852. * @type {number}
  853. * @constant
  854. */
  855. const RGBA_ASTC_8x5_Format = 37813;
  856. /**
  857. * ASTC RGBA 8x6 format.
  858. *
  859. * @type {number}
  860. * @constant
  861. */
  862. const RGBA_ASTC_8x6_Format = 37814;
  863. /**
  864. * ASTC RGBA 8x8 format.
  865. *
  866. * @type {number}
  867. * @constant
  868. */
  869. const RGBA_ASTC_8x8_Format = 37815;
  870. /**
  871. * ASTC RGBA 10x5 format.
  872. *
  873. * @type {number}
  874. * @constant
  875. */
  876. const RGBA_ASTC_10x5_Format = 37816;
  877. /**
  878. * ASTC RGBA 10x6 format.
  879. *
  880. * @type {number}
  881. * @constant
  882. */
  883. const RGBA_ASTC_10x6_Format = 37817;
  884. /**
  885. * ASTC RGBA 10x8 format.
  886. *
  887. * @type {number}
  888. * @constant
  889. */
  890. const RGBA_ASTC_10x8_Format = 37818;
  891. /**
  892. * ASTC RGBA 10x10 format.
  893. *
  894. * @type {number}
  895. * @constant
  896. */
  897. const RGBA_ASTC_10x10_Format = 37819;
  898. /**
  899. * ASTC RGBA 12x10 format.
  900. *
  901. * @type {number}
  902. * @constant
  903. */
  904. const RGBA_ASTC_12x10_Format = 37820;
  905. /**
  906. * ASTC RGBA 12x12 format.
  907. *
  908. * @type {number}
  909. * @constant
  910. */
  911. const RGBA_ASTC_12x12_Format = 37821;
  912. /**
  913. * BPTC RGBA format.
  914. *
  915. * @type {number}
  916. * @constant
  917. */
  918. const RGBA_BPTC_Format = 36492;
  919. /**
  920. * BPTC Signed RGB format.
  921. *
  922. * @type {number}
  923. * @constant
  924. */
  925. const RGB_BPTC_SIGNED_Format = 36494;
  926. /**
  927. * BPTC Unsigned RGB format.
  928. *
  929. * @type {number}
  930. * @constant
  931. */
  932. const RGB_BPTC_UNSIGNED_Format = 36495;
  933. /**
  934. * RGTC1 Red format.
  935. *
  936. * @type {number}
  937. * @constant
  938. */
  939. const RED_RGTC1_Format = 36283;
  940. /**
  941. * RGTC1 Signed Red format.
  942. *
  943. * @type {number}
  944. * @constant
  945. */
  946. const SIGNED_RED_RGTC1_Format = 36284;
  947. /**
  948. * RGTC2 Red Green format.
  949. *
  950. * @type {number}
  951. * @constant
  952. */
  953. const RED_GREEN_RGTC2_Format = 36285;
  954. /**
  955. * RGTC2 Signed Red Green format.
  956. *
  957. * @type {number}
  958. * @constant
  959. */
  960. const SIGNED_RED_GREEN_RGTC2_Format = 36286;
  961. /**
  962. * Animations are played once.
  963. *
  964. * @type {number}
  965. * @constant
  966. */
  967. const LoopOnce = 2200;
  968. /**
  969. * Animations are played with a chosen number of repetitions, each time jumping from
  970. * the end of the clip directly to its beginning.
  971. *
  972. * @type {number}
  973. * @constant
  974. */
  975. const LoopRepeat = 2201;
  976. /**
  977. * Animations are played with a chosen number of repetitions, alternately playing forward
  978. * and backward.
  979. *
  980. * @type {number}
  981. * @constant
  982. */
  983. const LoopPingPong = 2202;
  984. /**
  985. * Discrete interpolation mode for keyframe tracks.
  986. *
  987. * @type {number}
  988. * @constant
  989. */
  990. const InterpolateDiscrete = 2300;
  991. /**
  992. * Linear interpolation mode for keyframe tracks.
  993. *
  994. * @type {number}
  995. * @constant
  996. */
  997. const InterpolateLinear = 2301;
  998. /**
  999. * Smooth interpolation mode for keyframe tracks.
  1000. *
  1001. * @type {number}
  1002. * @constant
  1003. */
  1004. const InterpolateSmooth = 2302;
  1005. /**
  1006. * Zero curvature ending for animations.
  1007. *
  1008. * @type {number}
  1009. * @constant
  1010. */
  1011. const ZeroCurvatureEnding = 2400;
  1012. /**
  1013. * Zero slope ending for animations.
  1014. *
  1015. * @type {number}
  1016. * @constant
  1017. */
  1018. const ZeroSlopeEnding = 2401;
  1019. /**
  1020. * Wrap around ending for animations.
  1021. *
  1022. * @type {number}
  1023. * @constant
  1024. */
  1025. const WrapAroundEnding = 2402;
  1026. /**
  1027. * Default animation blend mode.
  1028. *
  1029. * @type {number}
  1030. * @constant
  1031. */
  1032. const NormalAnimationBlendMode = 2500;
  1033. /**
  1034. * Additive animation blend mode. Can be used to layer motions on top of
  1035. * each other to build complex performances from smaller re-usable assets.
  1036. *
  1037. * @type {number}
  1038. * @constant
  1039. */
  1040. const AdditiveAnimationBlendMode = 2501;
  1041. /**
  1042. * For every three vertices draw a single triangle.
  1043. *
  1044. * @type {number}
  1045. * @constant
  1046. */
  1047. const TrianglesDrawMode = 0;
  1048. /**
  1049. * For each vertex draw a triangle from the last three vertices.
  1050. *
  1051. * @type {number}
  1052. * @constant
  1053. */
  1054. const TriangleStripDrawMode = 1;
  1055. /**
  1056. * For each vertex draw a triangle from the first vertex and the last two vertices.
  1057. *
  1058. * @type {number}
  1059. * @constant
  1060. */
  1061. const TriangleFanDrawMode = 2;
  1062. /**
  1063. * Basic depth packing.
  1064. *
  1065. * @type {number}
  1066. * @constant
  1067. */
  1068. const BasicDepthPacking = 3200;
  1069. /**
  1070. * A depth value is packed into 32 bit RGBA.
  1071. *
  1072. * @type {number}
  1073. * @constant
  1074. */
  1075. const RGBADepthPacking = 3201;
  1076. /**
  1077. * A depth value is packed into 24 bit RGB.
  1078. *
  1079. * @type {number}
  1080. * @constant
  1081. */
  1082. const RGBDepthPacking = 3202;
  1083. /**
  1084. * A depth value is packed into 16 bit RG.
  1085. *
  1086. * @type {number}
  1087. * @constant
  1088. */
  1089. const RGDepthPacking = 3203;
  1090. /**
  1091. * Normal information is relative to the underlying surface.
  1092. *
  1093. * @type {number}
  1094. * @constant
  1095. */
  1096. const TangentSpaceNormalMap = 0;
  1097. /**
  1098. * Normal information is relative to the object orientation.
  1099. *
  1100. * @type {number}
  1101. * @constant
  1102. */
  1103. const ObjectSpaceNormalMap = 1;
  1104. // Color space string identifiers, matching CSS Color Module Level 4 and WebGPU names where available.
  1105. /**
  1106. * No color space.
  1107. *
  1108. * @type {string}
  1109. * @constant
  1110. */
  1111. const NoColorSpace = '';
  1112. /**
  1113. * sRGB color space.
  1114. *
  1115. * @type {string}
  1116. * @constant
  1117. */
  1118. const SRGBColorSpace = 'srgb';
  1119. /**
  1120. * sRGB-linear color space.
  1121. *
  1122. * @type {string}
  1123. * @constant
  1124. */
  1125. const LinearSRGBColorSpace = 'srgb-linear';
  1126. /**
  1127. * Linear transfer function.
  1128. *
  1129. * @type {string}
  1130. * @constant
  1131. */
  1132. const LinearTransfer = 'linear';
  1133. /**
  1134. * sRGB transfer function.
  1135. *
  1136. * @type {string}
  1137. * @constant
  1138. */
  1139. const SRGBTransfer = 'srgb';
  1140. /**
  1141. * Sets the stencil buffer value to `0`.
  1142. *
  1143. * @type {number}
  1144. * @constant
  1145. */
  1146. const ZeroStencilOp = 0;
  1147. /**
  1148. * Keeps the current value.
  1149. *
  1150. * @type {number}
  1151. * @constant
  1152. */
  1153. const KeepStencilOp = 7680;
  1154. /**
  1155. * Sets the stencil buffer value to the specified reference value.
  1156. *
  1157. * @type {number}
  1158. * @constant
  1159. */
  1160. const ReplaceStencilOp = 7681;
  1161. /**
  1162. * Increments the current stencil buffer value. Clamps to the maximum representable unsigned value.
  1163. *
  1164. * @type {number}
  1165. * @constant
  1166. */
  1167. const IncrementStencilOp = 7682;
  1168. /**
  1169. * Decrements the current stencil buffer value. Clamps to `0`.
  1170. *
  1171. * @type {number}
  1172. * @constant
  1173. */
  1174. const DecrementStencilOp = 7683;
  1175. /**
  1176. * Increments the current stencil buffer value. Wraps stencil buffer value to zero when incrementing
  1177. * the maximum representable unsigned value.
  1178. *
  1179. * @type {number}
  1180. * @constant
  1181. */
  1182. const IncrementWrapStencilOp = 34055;
  1183. /**
  1184. * Decrements the current stencil buffer value. Wraps stencil buffer value to the maximum representable
  1185. * unsigned value when decrementing a stencil buffer value of `0`.
  1186. *
  1187. * @type {number}
  1188. * @constant
  1189. */
  1190. const DecrementWrapStencilOp = 34056;
  1191. /**
  1192. * Inverts the current stencil buffer value bitwise.
  1193. *
  1194. * @type {number}
  1195. * @constant
  1196. */
  1197. const InvertStencilOp = 5386;
  1198. /**
  1199. * Will never return true.
  1200. *
  1201. * @type {number}
  1202. * @constant
  1203. */
  1204. const NeverStencilFunc = 512;
  1205. /**
  1206. * Will return true if the stencil reference value is less than the current stencil value.
  1207. *
  1208. * @type {number}
  1209. * @constant
  1210. */
  1211. const LessStencilFunc = 513;
  1212. /**
  1213. * Will return true if the stencil reference value is equal to the current stencil value.
  1214. *
  1215. * @type {number}
  1216. * @constant
  1217. */
  1218. const EqualStencilFunc = 514;
  1219. /**
  1220. * Will return true if the stencil reference value is less than or equal to the current stencil value.
  1221. *
  1222. * @type {number}
  1223. * @constant
  1224. */
  1225. const LessEqualStencilFunc = 515;
  1226. /**
  1227. * Will return true if the stencil reference value is greater than the current stencil value.
  1228. *
  1229. * @type {number}
  1230. * @constant
  1231. */
  1232. const GreaterStencilFunc = 516;
  1233. /**
  1234. * Will return true if the stencil reference value is not equal to the current stencil value.
  1235. *
  1236. * @type {number}
  1237. * @constant
  1238. */
  1239. const NotEqualStencilFunc = 517;
  1240. /**
  1241. * Will return true if the stencil reference value is greater than or equal to the current stencil value.
  1242. *
  1243. * @type {number}
  1244. * @constant
  1245. */
  1246. const GreaterEqualStencilFunc = 518;
  1247. /**
  1248. * Will always return true.
  1249. *
  1250. * @type {number}
  1251. * @constant
  1252. */
  1253. const AlwaysStencilFunc = 519;
  1254. /**
  1255. * Never pass.
  1256. *
  1257. * @type {number}
  1258. * @constant
  1259. */
  1260. const NeverCompare = 512;
  1261. /**
  1262. * Pass if the incoming value is less than the texture value.
  1263. *
  1264. * @type {number}
  1265. * @constant
  1266. */
  1267. const LessCompare = 513;
  1268. /**
  1269. * Pass if the incoming value equals the texture value.
  1270. *
  1271. * @type {number}
  1272. * @constant
  1273. */
  1274. const EqualCompare = 514;
  1275. /**
  1276. * Pass if the incoming value is less than or equal to the texture value.
  1277. *
  1278. * @type {number}
  1279. * @constant
  1280. */
  1281. const LessEqualCompare = 515;
  1282. /**
  1283. * Pass if the incoming value is greater than the texture value.
  1284. *
  1285. * @type {number}
  1286. * @constant
  1287. */
  1288. const GreaterCompare = 516;
  1289. /**
  1290. * Pass if the incoming value is not equal to the texture value.
  1291. *
  1292. * @type {number}
  1293. * @constant
  1294. */
  1295. const NotEqualCompare = 517;
  1296. /**
  1297. * Pass if the incoming value is greater than or equal to the texture value.
  1298. *
  1299. * @type {number}
  1300. * @constant
  1301. */
  1302. const GreaterEqualCompare = 518;
  1303. /**
  1304. * Always pass.
  1305. *
  1306. * @type {number}
  1307. * @constant
  1308. */
  1309. const AlwaysCompare = 519;
  1310. /**
  1311. * The contents are intended to be specified once by the application, and used many
  1312. * times as the source for drawing and image specification commands.
  1313. *
  1314. * @type {number}
  1315. * @constant
  1316. */
  1317. const StaticDrawUsage = 35044;
  1318. /**
  1319. * The contents are intended to be respecified repeatedly by the application, and
  1320. * used many times as the source for drawing and image specification commands.
  1321. *
  1322. * @type {number}
  1323. * @constant
  1324. */
  1325. const DynamicDrawUsage = 35048;
  1326. /**
  1327. * The contents are intended to be specified once by the application, and used at most
  1328. * a few times as the source for drawing and image specification commands.
  1329. *
  1330. * @type {number}
  1331. * @constant
  1332. */
  1333. const StreamDrawUsage = 35040;
  1334. /**
  1335. * The contents are intended to be specified once by reading data from the 3D API, and queried
  1336. * many times by the application.
  1337. *
  1338. * @type {number}
  1339. * @constant
  1340. */
  1341. const StaticReadUsage = 35045;
  1342. /**
  1343. * The contents are intended to be respecified repeatedly by reading data from the 3D API, and queried
  1344. * many times by the application.
  1345. *
  1346. * @type {number}
  1347. * @constant
  1348. */
  1349. const DynamicReadUsage = 35049;
  1350. /**
  1351. * The contents are intended to be specified once by reading data from the 3D API, and queried at most
  1352. * a few times by the application
  1353. *
  1354. * @type {number}
  1355. * @constant
  1356. */
  1357. const StreamReadUsage = 35041;
  1358. /**
  1359. * The contents are intended to be specified once by reading data from the 3D API, and used many times as
  1360. * the source for WebGL drawing and image specification commands.
  1361. *
  1362. * @type {number}
  1363. * @constant
  1364. */
  1365. const StaticCopyUsage = 35046;
  1366. /**
  1367. * The contents are intended to be respecified repeatedly by reading data from the 3D API, and used many times
  1368. * as the source for WebGL drawing and image specification commands.
  1369. *
  1370. * @type {number}
  1371. * @constant
  1372. */
  1373. const DynamicCopyUsage = 35050;
  1374. /**
  1375. * The contents are intended to be specified once by reading data from the 3D API, and used at most a few times
  1376. * as the source for WebGL drawing and image specification commands.
  1377. *
  1378. * @type {number}
  1379. * @constant
  1380. */
  1381. const StreamCopyUsage = 35042;
  1382. /**
  1383. * GLSL 1 shader code.
  1384. *
  1385. * @type {string}
  1386. * @constant
  1387. */
  1388. const GLSL1 = '100';
  1389. /**
  1390. * GLSL 3 shader code.
  1391. *
  1392. * @type {string}
  1393. * @constant
  1394. */
  1395. const GLSL3 = '300 es';
  1396. /**
  1397. * WebGL coordinate system.
  1398. *
  1399. * @type {number}
  1400. * @constant
  1401. */
  1402. const WebGLCoordinateSystem = 2000;
  1403. /**
  1404. * WebGPU coordinate system.
  1405. *
  1406. * @type {number}
  1407. * @constant
  1408. */
  1409. const WebGPUCoordinateSystem = 2001;
  1410. /**
  1411. * Represents the different timestamp query types.
  1412. *
  1413. * @type {ConstantsTimestampQuery}
  1414. * @constant
  1415. */
  1416. const TimestampQuery = {
  1417. COMPUTE: 'compute',
  1418. RENDER: 'render'
  1419. };
  1420. /**
  1421. * This type represents mouse buttons and interaction types in context of controls.
  1422. *
  1423. * @typedef {Object} ConstantsMouse
  1424. * @property {number} MIDDLE - The left mouse button.
  1425. * @property {number} LEFT - The middle mouse button.
  1426. * @property {number} RIGHT - The right mouse button.
  1427. * @property {number} ROTATE - A rotate interaction.
  1428. * @property {number} DOLLY - A dolly interaction.
  1429. * @property {number} PAN - A pan interaction.
  1430. **/
  1431. /**
  1432. * This type represents touch interaction types in context of controls.
  1433. *
  1434. * @typedef {Object} ConstantsTouch
  1435. * @property {number} ROTATE - A rotate interaction.
  1436. * @property {number} PAN - A pan interaction.
  1437. * @property {number} DOLLY_PAN - The dolly-pan interaction.
  1438. * @property {number} DOLLY_ROTATE - A dolly-rotate interaction.
  1439. **/
  1440. /**
  1441. * This type represents the different timestamp query types.
  1442. *
  1443. * @typedef {Object} ConstantsTimestampQuery
  1444. * @property {string} COMPUTE - A `compute` timestamp query.
  1445. * @property {string} RENDER - A `render` timestamp query.
  1446. **/
  1447. /**
  1448. * This modules allows to dispatch event objects on custom JavaScript objects.
  1449. *
  1450. * Main repository: [eventdispatcher.js]{@link https://github.com/mrdoob/eventdispatcher.js/}
  1451. *
  1452. * Code Example:
  1453. * ```js
  1454. * class Car extends EventDispatcher {
  1455. * start() {
  1456. * this.dispatchEvent( { type: 'start', message: 'vroom vroom!' } );
  1457. * }
  1458. *};
  1459. *
  1460. * // Using events with the custom object
  1461. * const car = new Car();
  1462. * car.addEventListener( 'start', function ( event ) {
  1463. * alert( event.message );
  1464. * } );
  1465. *
  1466. * car.start();
  1467. * ```
  1468. */
  1469. class EventDispatcher {
  1470. /**
  1471. * Adds the given event listener to the given event type.
  1472. *
  1473. * @param {string} type - The type of event to listen to.
  1474. * @param {Function} listener - The function that gets called when the event is fired.
  1475. */
  1476. addEventListener( type, listener ) {
  1477. if ( this._listeners === undefined ) this._listeners = {};
  1478. const listeners = this._listeners;
  1479. if ( listeners[ type ] === undefined ) {
  1480. listeners[ type ] = [];
  1481. }
  1482. if ( listeners[ type ].indexOf( listener ) === -1 ) {
  1483. listeners[ type ].push( listener );
  1484. }
  1485. }
  1486. /**
  1487. * Returns `true` if the given event listener has been added to the given event type.
  1488. *
  1489. * @param {string} type - The type of event.
  1490. * @param {Function} listener - The listener to check.
  1491. * @return {boolean} Whether the given event listener has been added to the given event type.
  1492. */
  1493. hasEventListener( type, listener ) {
  1494. const listeners = this._listeners;
  1495. if ( listeners === undefined ) return false;
  1496. return listeners[ type ] !== undefined && listeners[ type ].indexOf( listener ) !== -1;
  1497. }
  1498. /**
  1499. * Removes the given event listener from the given event type.
  1500. *
  1501. * @param {string} type - The type of event.
  1502. * @param {Function} listener - The listener to remove.
  1503. */
  1504. removeEventListener( type, listener ) {
  1505. const listeners = this._listeners;
  1506. if ( listeners === undefined ) return;
  1507. const listenerArray = listeners[ type ];
  1508. if ( listenerArray !== undefined ) {
  1509. const index = listenerArray.indexOf( listener );
  1510. if ( index !== -1 ) {
  1511. listenerArray.splice( index, 1 );
  1512. }
  1513. }
  1514. }
  1515. /**
  1516. * Dispatches an event object.
  1517. *
  1518. * @param {Object} event - The event that gets fired.
  1519. */
  1520. dispatchEvent( event ) {
  1521. const listeners = this._listeners;
  1522. if ( listeners === undefined ) return;
  1523. const listenerArray = listeners[ event.type ];
  1524. if ( listenerArray !== undefined ) {
  1525. event.target = this;
  1526. // Make a copy, in case listeners are removed while iterating.
  1527. const array = listenerArray.slice( 0 );
  1528. for ( let i = 0, l = array.length; i < l; i ++ ) {
  1529. array[ i ].call( this, event );
  1530. }
  1531. event.target = null;
  1532. }
  1533. }
  1534. }
  1535. 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' ];
  1536. let _seed = 1234567;
  1537. const DEG2RAD = Math.PI / 180;
  1538. const RAD2DEG = 180 / Math.PI;
  1539. /**
  1540. * Generate a [UUID]{@link https://en.wikipedia.org/wiki/Universally_unique_identifier}
  1541. * (universally unique identifier).
  1542. *
  1543. * @return {string} The UUID.
  1544. */
  1545. function generateUUID() {
  1546. // http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/21963136#21963136
  1547. const d0 = Math.random() * 0xffffffff | 0;
  1548. const d1 = Math.random() * 0xffffffff | 0;
  1549. const d2 = Math.random() * 0xffffffff | 0;
  1550. const d3 = Math.random() * 0xffffffff | 0;
  1551. const uuid = _lut[ d0 & 0xff ] + _lut[ d0 >> 8 & 0xff ] + _lut[ d0 >> 16 & 0xff ] + _lut[ d0 >> 24 & 0xff ] + '-' +
  1552. _lut[ d1 & 0xff ] + _lut[ d1 >> 8 & 0xff ] + '-' + _lut[ d1 >> 16 & 0x0f | 0x40 ] + _lut[ d1 >> 24 & 0xff ] + '-' +
  1553. _lut[ d2 & 0x3f | 0x80 ] + _lut[ d2 >> 8 & 0xff ] + '-' + _lut[ d2 >> 16 & 0xff ] + _lut[ d2 >> 24 & 0xff ] +
  1554. _lut[ d3 & 0xff ] + _lut[ d3 >> 8 & 0xff ] + _lut[ d3 >> 16 & 0xff ] + _lut[ d3 >> 24 & 0xff ];
  1555. // .toLowerCase() here flattens concatenated strings to save heap memory space.
  1556. return uuid.toLowerCase();
  1557. }
  1558. /**
  1559. * Clamps the given value between min and max.
  1560. *
  1561. * @param {number} value - The value to clamp.
  1562. * @param {number} min - The min value.
  1563. * @param {number} max - The max value.
  1564. * @return {number} The clamped value.
  1565. */
  1566. function clamp( value, min, max ) {
  1567. return Math.max( min, Math.min( max, value ) );
  1568. }
  1569. /**
  1570. * Computes the Euclidean modulo of the given parameters that
  1571. * is `( ( n % m ) + m ) % m`.
  1572. *
  1573. * @param {number} n - The first parameter.
  1574. * @param {number} m - The second parameter.
  1575. * @return {number} The Euclidean modulo.
  1576. */
  1577. function euclideanModulo( n, m ) {
  1578. // https://en.wikipedia.org/wiki/Modulo_operation
  1579. return ( ( n % m ) + m ) % m;
  1580. }
  1581. /**
  1582. * Performs a linear mapping from range `<a1, a2>` to range `<b1, b2>`
  1583. * for the given value.
  1584. *
  1585. * @param {number} x - The value to be mapped.
  1586. * @param {number} a1 - Minimum value for range A.
  1587. * @param {number} a2 - Maximum value for range A.
  1588. * @param {number} b1 - Minimum value for range B.
  1589. * @param {number} b2 - Maximum value for range B.
  1590. * @return {number} The mapped value.
  1591. */
  1592. function mapLinear( x, a1, a2, b1, b2 ) {
  1593. return b1 + ( x - a1 ) * ( b2 - b1 ) / ( a2 - a1 );
  1594. }
  1595. /**
  1596. * Returns the percentage in the closed interval `[0, 1]` of the given value
  1597. * between the start and end point.
  1598. *
  1599. * @param {number} x - The start point
  1600. * @param {number} y - The end point.
  1601. * @param {number} value - A value between start and end.
  1602. * @return {number} The interpolation factor.
  1603. */
  1604. function inverseLerp( x, y, value ) {
  1605. // https://www.gamedev.net/tutorials/programming/general-and-gameplay-programming/inverse-lerp-a-super-useful-yet-often-overlooked-function-r5230/
  1606. if ( x !== y ) {
  1607. return ( value - x ) / ( y - x );
  1608. } else {
  1609. return 0;
  1610. }
  1611. }
  1612. /**
  1613. * Returns a value linearly interpolated from two known points based on the given interval -
  1614. * `t = 0` will return `x` and `t = 1` will return `y`.
  1615. *
  1616. * @param {number} x - The start point
  1617. * @param {number} y - The end point.
  1618. * @param {number} t - The interpolation factor in the closed interval `[0, 1]`.
  1619. * @return {number} The interpolated value.
  1620. */
  1621. function lerp( x, y, t ) {
  1622. return ( 1 - t ) * x + t * y;
  1623. }
  1624. /**
  1625. * Smoothly interpolate a number from `x` to `y` in a spring-like manner using a delta
  1626. * time to maintain frame rate independent movement. For details, see
  1627. * [Frame rate independent damping using lerp]{@link http://www.rorydriscoll.com/2016/03/07/frame-rate-independent-damping-using-lerp/}.
  1628. *
  1629. * @param {number} x - The current point.
  1630. * @param {number} y - The target point.
  1631. * @param {number} lambda - A higher lambda value will make the movement more sudden,
  1632. * and a lower value will make the movement more gradual.
  1633. * @param {number} dt - Delta time in seconds.
  1634. * @return {number} The interpolated value.
  1635. */
  1636. function damp( x, y, lambda, dt ) {
  1637. return lerp( x, y, 1 - Math.exp( - lambda * dt ) );
  1638. }
  1639. /**
  1640. * Returns a value that alternates between `0` and the given `length` parameter.
  1641. *
  1642. * @param {number} x - The value to pingpong.
  1643. * @param {number} [length=1] - The positive value the function will pingpong to.
  1644. * @return {number} The alternated value.
  1645. */
  1646. function pingpong( x, length = 1 ) {
  1647. // https://www.desmos.com/calculator/vcsjnyz7x4
  1648. return length - Math.abs( euclideanModulo( x, length * 2 ) - length );
  1649. }
  1650. /**
  1651. * Returns a value in the range `[0,1]` that represents the percentage that `x` has
  1652. * moved between `min` and `max`, but smoothed or slowed down the closer `x` is to
  1653. * the `min` and `max`.
  1654. *
  1655. * See [Smoothstep]{@link http://en.wikipedia.org/wiki/Smoothstep} for more details.
  1656. *
  1657. * @param {number} x - The value to evaluate based on its position between min and max.
  1658. * @param {number} min - The min value. Any x value below min will be `0`.
  1659. * @param {number} max - The max value. Any x value above max will be `1`.
  1660. * @return {number} The alternated value.
  1661. */
  1662. function smoothstep( x, min, max ) {
  1663. if ( x <= min ) return 0;
  1664. if ( x >= max ) return 1;
  1665. x = ( x - min ) / ( max - min );
  1666. return x * x * ( 3 - 2 * x );
  1667. }
  1668. /**
  1669. * A [variation on smoothstep]{@link https://en.wikipedia.org/wiki/Smoothstep#Variations}
  1670. * that has zero 1st and 2nd order derivatives at x=0 and x=1.
  1671. *
  1672. * @param {number} x - The value to evaluate based on its position between min and max.
  1673. * @param {number} min - The min value. Any x value below min will be `0`.
  1674. * @param {number} max - The max value. Any x value above max will be `1`.
  1675. * @return {number} The alternated value.
  1676. */
  1677. function smootherstep( x, min, max ) {
  1678. if ( x <= min ) return 0;
  1679. if ( x >= max ) return 1;
  1680. x = ( x - min ) / ( max - min );
  1681. return x * x * x * ( x * ( x * 6 - 15 ) + 10 );
  1682. }
  1683. /**
  1684. * Returns a random integer from `<low, high>` interval.
  1685. *
  1686. * @param {number} low - The lower value boundary.
  1687. * @param {number} high - The upper value boundary
  1688. * @return {number} A random integer.
  1689. */
  1690. function randInt( low, high ) {
  1691. return low + Math.floor( Math.random() * ( high - low + 1 ) );
  1692. }
  1693. /**
  1694. * Returns a random float from `<low, high>` interval.
  1695. *
  1696. * @param {number} low - The lower value boundary.
  1697. * @param {number} high - The upper value boundary
  1698. * @return {number} A random float.
  1699. */
  1700. function randFloat( low, high ) {
  1701. return low + Math.random() * ( high - low );
  1702. }
  1703. /**
  1704. * Returns a random integer from `<-range/2, range/2>` interval.
  1705. *
  1706. * @param {number} range - Defines the value range.
  1707. * @return {number} A random float.
  1708. */
  1709. function randFloatSpread( range ) {
  1710. return range * ( 0.5 - Math.random() );
  1711. }
  1712. /**
  1713. * Returns a deterministic pseudo-random float in the interval `[0, 1]`.
  1714. *
  1715. * @param {number} [s] - The integer seed.
  1716. * @return {number} A random float.
  1717. */
  1718. function seededRandom( s ) {
  1719. if ( s !== undefined ) _seed = s;
  1720. // Mulberry32 generator
  1721. let t = _seed += 0x6D2B79F5;
  1722. t = Math.imul( t ^ t >>> 15, t | 1 );
  1723. t ^= t + Math.imul( t ^ t >>> 7, t | 61 );
  1724. return ( ( t ^ t >>> 14 ) >>> 0 ) / 4294967296;
  1725. }
  1726. /**
  1727. * Converts degrees to radians.
  1728. *
  1729. * @param {number} degrees - A value in degrees.
  1730. * @return {number} The converted value in radians.
  1731. */
  1732. function degToRad( degrees ) {
  1733. return degrees * DEG2RAD;
  1734. }
  1735. /**
  1736. * Converts radians to degrees.
  1737. *
  1738. * @param {number} radians - A value in radians.
  1739. * @return {number} The converted value in degrees.
  1740. */
  1741. function radToDeg( radians ) {
  1742. return radians * RAD2DEG;
  1743. }
  1744. /**
  1745. * Returns `true` if the given number is a power of two.
  1746. *
  1747. * @param {number} value - The value to check.
  1748. * @return {boolean} Whether the given number is a power of two or not.
  1749. */
  1750. function isPowerOfTwo( value ) {
  1751. return ( value & ( value - 1 ) ) === 0 && value !== 0;
  1752. }
  1753. /**
  1754. * Returns the smallest power of two that is greater than or equal to the given number.
  1755. *
  1756. * @param {number} value - The value to find a POT for.
  1757. * @return {number} The smallest power of two that is greater than or equal to the given number.
  1758. */
  1759. function ceilPowerOfTwo( value ) {
  1760. return Math.pow( 2, Math.ceil( Math.log( value ) / Math.LN2 ) );
  1761. }
  1762. /**
  1763. * Returns the largest power of two that is less than or equal to the given number.
  1764. *
  1765. * @param {number} value - The value to find a POT for.
  1766. * @return {number} The largest power of two that is less than or equal to the given number.
  1767. */
  1768. function floorPowerOfTwo( value ) {
  1769. return Math.pow( 2, Math.floor( Math.log( value ) / Math.LN2 ) );
  1770. }
  1771. /**
  1772. * Sets the given quaternion from the [Intrinsic Proper Euler Angles]{@link https://en.wikipedia.org/wiki/Euler_angles}
  1773. * defined by the given angles and order.
  1774. *
  1775. * Rotations are applied to the axes in the order specified by order:
  1776. * rotation by angle `a` is applied first, then by angle `b`, then by angle `c`.
  1777. *
  1778. * @param {Quaternion} q - The quaternion to set.
  1779. * @param {number} a - The rotation applied to the first axis, in radians.
  1780. * @param {number} b - The rotation applied to the second axis, in radians.
  1781. * @param {number} c - The rotation applied to the third axis, in radians.
  1782. * @param {('XYX'|'XZX'|'YXY'|'YZY'|'ZXZ'|'ZYZ')} order - A string specifying the axes order.
  1783. */
  1784. function setQuaternionFromProperEuler( q, a, b, c, order ) {
  1785. const cos = Math.cos;
  1786. const sin = Math.sin;
  1787. const c2 = cos( b / 2 );
  1788. const s2 = sin( b / 2 );
  1789. const c13 = cos( ( a + c ) / 2 );
  1790. const s13 = sin( ( a + c ) / 2 );
  1791. const c1_3 = cos( ( a - c ) / 2 );
  1792. const s1_3 = sin( ( a - c ) / 2 );
  1793. const c3_1 = cos( ( c - a ) / 2 );
  1794. const s3_1 = sin( ( c - a ) / 2 );
  1795. switch ( order ) {
  1796. case 'XYX':
  1797. q.set( c2 * s13, s2 * c1_3, s2 * s1_3, c2 * c13 );
  1798. break;
  1799. case 'YZY':
  1800. q.set( s2 * s1_3, c2 * s13, s2 * c1_3, c2 * c13 );
  1801. break;
  1802. case 'ZXZ':
  1803. q.set( s2 * c1_3, s2 * s1_3, c2 * s13, c2 * c13 );
  1804. break;
  1805. case 'XZX':
  1806. q.set( c2 * s13, s2 * s3_1, s2 * c3_1, c2 * c13 );
  1807. break;
  1808. case 'YXY':
  1809. q.set( s2 * c3_1, c2 * s13, s2 * s3_1, c2 * c13 );
  1810. break;
  1811. case 'ZYZ':
  1812. q.set( s2 * s3_1, s2 * c3_1, c2 * s13, c2 * c13 );
  1813. break;
  1814. default:
  1815. console.warn( 'THREE.MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: ' + order );
  1816. }
  1817. }
  1818. /**
  1819. * Denormalizes the given value according to the given typed array.
  1820. *
  1821. * @param {number} value - The value to denormalize.
  1822. * @param {TypedArray} array - The typed array that defines the data type of the value.
  1823. * @return {number} The denormalize (float) value in the range `[0,1]`.
  1824. */
  1825. function denormalize( value, array ) {
  1826. switch ( array.constructor ) {
  1827. case Float32Array:
  1828. return value;
  1829. case Uint32Array:
  1830. return value / 4294967295.0;
  1831. case Uint16Array:
  1832. return value / 65535.0;
  1833. case Uint8Array:
  1834. return value / 255.0;
  1835. case Int32Array:
  1836. return Math.max( value / 2147483647.0, -1 );
  1837. case Int16Array:
  1838. return Math.max( value / 32767.0, -1 );
  1839. case Int8Array:
  1840. return Math.max( value / 127.0, -1 );
  1841. default:
  1842. throw new Error( 'Invalid component type.' );
  1843. }
  1844. }
  1845. /**
  1846. * Normalizes the given value according to the given typed array.
  1847. *
  1848. * @param {number} value - The float value in the range `[0,1]` to normalize.
  1849. * @param {TypedArray} array - The typed array that defines the data type of the value.
  1850. * @return {number} The normalize value.
  1851. */
  1852. function normalize( value, array ) {
  1853. switch ( array.constructor ) {
  1854. case Float32Array:
  1855. return value;
  1856. case Uint32Array:
  1857. return Math.round( value * 4294967295.0 );
  1858. case Uint16Array:
  1859. return Math.round( value * 65535.0 );
  1860. case Uint8Array:
  1861. return Math.round( value * 255.0 );
  1862. case Int32Array:
  1863. return Math.round( value * 2147483647.0 );
  1864. case Int16Array:
  1865. return Math.round( value * 32767.0 );
  1866. case Int8Array:
  1867. return Math.round( value * 127.0 );
  1868. default:
  1869. throw new Error( 'Invalid component type.' );
  1870. }
  1871. }
  1872. /**
  1873. * @class
  1874. * @classdesc A collection of math utility functions.
  1875. * @hideconstructor
  1876. */
  1877. const MathUtils = {
  1878. DEG2RAD: DEG2RAD,
  1879. RAD2DEG: RAD2DEG,
  1880. /**
  1881. * Generate a [UUID]{@link https://en.wikipedia.org/wiki/Universally_unique_identifier}
  1882. * (universally unique identifier).
  1883. *
  1884. * @static
  1885. * @method
  1886. * @return {string} The UUID.
  1887. */
  1888. generateUUID: generateUUID,
  1889. /**
  1890. * Clamps the given value between min and max.
  1891. *
  1892. * @static
  1893. * @method
  1894. * @param {number} value - The value to clamp.
  1895. * @param {number} min - The min value.
  1896. * @param {number} max - The max value.
  1897. * @return {number} The clamped value.
  1898. */
  1899. clamp: clamp,
  1900. /**
  1901. * Computes the Euclidean modulo of the given parameters that
  1902. * is `( ( n % m ) + m ) % m`.
  1903. *
  1904. * @static
  1905. * @method
  1906. * @param {number} n - The first parameter.
  1907. * @param {number} m - The second parameter.
  1908. * @return {number} The Euclidean modulo.
  1909. */
  1910. euclideanModulo: euclideanModulo,
  1911. /**
  1912. * Performs a linear mapping from range `<a1, a2>` to range `<b1, b2>`
  1913. * for the given value.
  1914. *
  1915. * @static
  1916. * @method
  1917. * @param {number} x - The value to be mapped.
  1918. * @param {number} a1 - Minimum value for range A.
  1919. * @param {number} a2 - Maximum value for range A.
  1920. * @param {number} b1 - Minimum value for range B.
  1921. * @param {number} b2 - Maximum value for range B.
  1922. * @return {number} The mapped value.
  1923. */
  1924. mapLinear: mapLinear,
  1925. /**
  1926. * Returns the percentage in the closed interval `[0, 1]` of the given value
  1927. * between the start and end point.
  1928. *
  1929. * @static
  1930. * @method
  1931. * @param {number} x - The start point
  1932. * @param {number} y - The end point.
  1933. * @param {number} value - A value between start and end.
  1934. * @return {number} The interpolation factor.
  1935. */
  1936. inverseLerp: inverseLerp,
  1937. /**
  1938. * Returns a value linearly interpolated from two known points based on the given interval -
  1939. * `t = 0` will return `x` and `t = 1` will return `y`.
  1940. *
  1941. * @static
  1942. * @method
  1943. * @param {number} x - The start point
  1944. * @param {number} y - The end point.
  1945. * @param {number} t - The interpolation factor in the closed interval `[0, 1]`.
  1946. * @return {number} The interpolated value.
  1947. */
  1948. lerp: lerp,
  1949. /**
  1950. * Smoothly interpolate a number from `x` to `y` in a spring-like manner using a delta
  1951. * time to maintain frame rate independent movement. For details, see
  1952. * [Frame rate independent damping using lerp]{@link http://www.rorydriscoll.com/2016/03/07/frame-rate-independent-damping-using-lerp/}.
  1953. *
  1954. * @static
  1955. * @method
  1956. * @param {number} x - The current point.
  1957. * @param {number} y - The target point.
  1958. * @param {number} lambda - A higher lambda value will make the movement more sudden,
  1959. * and a lower value will make the movement more gradual.
  1960. * @param {number} dt - Delta time in seconds.
  1961. * @return {number} The interpolated value.
  1962. */
  1963. damp: damp,
  1964. /**
  1965. * Returns a value that alternates between `0` and the given `length` parameter.
  1966. *
  1967. * @static
  1968. * @method
  1969. * @param {number} x - The value to pingpong.
  1970. * @param {number} [length=1] - The positive value the function will pingpong to.
  1971. * @return {number} The alternated value.
  1972. */
  1973. pingpong: pingpong,
  1974. /**
  1975. * Returns a value in the range `[0,1]` that represents the percentage that `x` has
  1976. * moved between `min` and `max`, but smoothed or slowed down the closer `x` is to
  1977. * the `min` and `max`.
  1978. *
  1979. * See [Smoothstep]{@link http://en.wikipedia.org/wiki/Smoothstep} for more details.
  1980. *
  1981. * @static
  1982. * @method
  1983. * @param {number} x - The value to evaluate based on its position between min and max.
  1984. * @param {number} min - The min value. Any x value below min will be `0`.
  1985. * @param {number} max - The max value. Any x value above max will be `1`.
  1986. * @return {number} The alternated value.
  1987. */
  1988. smoothstep: smoothstep,
  1989. /**
  1990. * A [variation on smoothstep]{@link https://en.wikipedia.org/wiki/Smoothstep#Variations}
  1991. * that has zero 1st and 2nd order derivatives at x=0 and x=1.
  1992. *
  1993. * @static
  1994. * @method
  1995. * @param {number} x - The value to evaluate based on its position between min and max.
  1996. * @param {number} min - The min value. Any x value below min will be `0`.
  1997. * @param {number} max - The max value. Any x value above max will be `1`.
  1998. * @return {number} The alternated value.
  1999. */
  2000. smootherstep: smootherstep,
  2001. /**
  2002. * Returns a random integer from `<low, high>` interval.
  2003. *
  2004. * @static
  2005. * @method
  2006. * @param {number} low - The lower value boundary.
  2007. * @param {number} high - The upper value boundary
  2008. * @return {number} A random integer.
  2009. */
  2010. randInt: randInt,
  2011. /**
  2012. * Returns a random float from `<low, high>` interval.
  2013. *
  2014. * @static
  2015. * @method
  2016. * @param {number} low - The lower value boundary.
  2017. * @param {number} high - The upper value boundary
  2018. * @return {number} A random float.
  2019. */
  2020. randFloat: randFloat,
  2021. /**
  2022. * Returns a random integer from `<-range/2, range/2>` interval.
  2023. *
  2024. * @static
  2025. * @method
  2026. * @param {number} range - Defines the value range.
  2027. * @return {number} A random float.
  2028. */
  2029. randFloatSpread: randFloatSpread,
  2030. /**
  2031. * Returns a deterministic pseudo-random float in the interval `[0, 1]`.
  2032. *
  2033. * @static
  2034. * @method
  2035. * @param {number} [s] - The integer seed.
  2036. * @return {number} A random float.
  2037. */
  2038. seededRandom: seededRandom,
  2039. /**
  2040. * Converts degrees to radians.
  2041. *
  2042. * @static
  2043. * @method
  2044. * @param {number} degrees - A value in degrees.
  2045. * @return {number} The converted value in radians.
  2046. */
  2047. degToRad: degToRad,
  2048. /**
  2049. * Converts radians to degrees.
  2050. *
  2051. * @static
  2052. * @method
  2053. * @param {number} radians - A value in radians.
  2054. * @return {number} The converted value in degrees.
  2055. */
  2056. radToDeg: radToDeg,
  2057. /**
  2058. * Returns `true` if the given number is a power of two.
  2059. *
  2060. * @static
  2061. * @method
  2062. * @param {number} value - The value to check.
  2063. * @return {boolean} Whether the given number is a power of two or not.
  2064. */
  2065. isPowerOfTwo: isPowerOfTwo,
  2066. /**
  2067. * Returns the smallest power of two that is greater than or equal to the given number.
  2068. *
  2069. * @static
  2070. * @method
  2071. * @param {number} value - The value to find a POT for.
  2072. * @return {number} The smallest power of two that is greater than or equal to the given number.
  2073. */
  2074. ceilPowerOfTwo: ceilPowerOfTwo,
  2075. /**
  2076. * Returns the largest power of two that is less than or equal to the given number.
  2077. *
  2078. * @static
  2079. * @method
  2080. * @param {number} value - The value to find a POT for.
  2081. * @return {number} The largest power of two that is less than or equal to the given number.
  2082. */
  2083. floorPowerOfTwo: floorPowerOfTwo,
  2084. /**
  2085. * Sets the given quaternion from the [Intrinsic Proper Euler Angles]{@link https://en.wikipedia.org/wiki/Euler_angles}
  2086. * defined by the given angles and order.
  2087. *
  2088. * Rotations are applied to the axes in the order specified by order:
  2089. * rotation by angle `a` is applied first, then by angle `b`, then by angle `c`.
  2090. *
  2091. * @static
  2092. * @method
  2093. * @param {Quaternion} q - The quaternion to set.
  2094. * @param {number} a - The rotation applied to the first axis, in radians.
  2095. * @param {number} b - The rotation applied to the second axis, in radians.
  2096. * @param {number} c - The rotation applied to the third axis, in radians.
  2097. * @param {('XYX'|'XZX'|'YXY'|'YZY'|'ZXZ'|'ZYZ')} order - A string specifying the axes order.
  2098. */
  2099. setQuaternionFromProperEuler: setQuaternionFromProperEuler,
  2100. /**
  2101. * Normalizes the given value according to the given typed array.
  2102. *
  2103. * @static
  2104. * @method
  2105. * @param {number} value - The float value in the range `[0,1]` to normalize.
  2106. * @param {TypedArray} array - The typed array that defines the data type of the value.
  2107. * @return {number} The normalize value.
  2108. */
  2109. normalize: normalize,
  2110. /**
  2111. * Denormalizes the given value according to the given typed array.
  2112. *
  2113. * @static
  2114. * @method
  2115. * @param {number} value - The value to denormalize.
  2116. * @param {TypedArray} array - The typed array that defines the data type of the value.
  2117. * @return {number} The denormalize (float) value in the range `[0,1]`.
  2118. */
  2119. denormalize: denormalize
  2120. };
  2121. /**
  2122. * Class representing a 2D vector. A 2D vector is an ordered pair of numbers
  2123. * (labeled x and y), which can be used to represent a number of things, such as:
  2124. *
  2125. * - A point in 2D space (i.e. a position on a plane).
  2126. * - A direction and length across a plane. In three.js the length will
  2127. * always be the Euclidean distance(straight-line distance) from `(0, 0)` to `(x, y)`
  2128. * and the direction is also measured from `(0, 0)` towards `(x, y)`.
  2129. * - Any arbitrary ordered pair of numbers.
  2130. *
  2131. * There are other things a 2D vector can be used to represent, such as
  2132. * momentum vectors, complex numbers and so on, however these are the most
  2133. * common uses in three.js.
  2134. *
  2135. * Iterating through a vector instance will yield its components `(x, y)` in
  2136. * the corresponding order.
  2137. * ```js
  2138. * const a = new THREE.Vector2( 0, 1 );
  2139. *
  2140. * //no arguments; will be initialised to (0, 0)
  2141. * const b = new THREE.Vector2( );
  2142. *
  2143. * const d = a.distanceTo( b );
  2144. * ```
  2145. */
  2146. class Vector2 {
  2147. /**
  2148. * Constructs a new 2D vector.
  2149. *
  2150. * @param {number} [x=0] - The x value of this vector.
  2151. * @param {number} [y=0] - The y value of this vector.
  2152. */
  2153. constructor( x = 0, y = 0 ) {
  2154. /**
  2155. * This flag can be used for type testing.
  2156. *
  2157. * @type {boolean}
  2158. * @readonly
  2159. * @default true
  2160. */
  2161. Vector2.prototype.isVector2 = true;
  2162. /**
  2163. * The x value of this vector.
  2164. *
  2165. * @type {number}
  2166. */
  2167. this.x = x;
  2168. /**
  2169. * The y value of this vector.
  2170. *
  2171. * @type {number}
  2172. */
  2173. this.y = y;
  2174. }
  2175. /**
  2176. * Alias for {@link Vector2#x}.
  2177. *
  2178. * @type {number}
  2179. */
  2180. get width() {
  2181. return this.x;
  2182. }
  2183. set width( value ) {
  2184. this.x = value;
  2185. }
  2186. /**
  2187. * Alias for {@link Vector2#y}.
  2188. *
  2189. * @type {number}
  2190. */
  2191. get height() {
  2192. return this.y;
  2193. }
  2194. set height( value ) {
  2195. this.y = value;
  2196. }
  2197. /**
  2198. * Sets the vector components.
  2199. *
  2200. * @param {number} x - The value of the x component.
  2201. * @param {number} y - The value of the y component.
  2202. * @return {Vector2} A reference to this vector.
  2203. */
  2204. set( x, y ) {
  2205. this.x = x;
  2206. this.y = y;
  2207. return this;
  2208. }
  2209. /**
  2210. * Sets the vector components to the same value.
  2211. *
  2212. * @param {number} scalar - The value to set for all vector components.
  2213. * @return {Vector2} A reference to this vector.
  2214. */
  2215. setScalar( scalar ) {
  2216. this.x = scalar;
  2217. this.y = scalar;
  2218. return this;
  2219. }
  2220. /**
  2221. * Sets the vector's x component to the given value
  2222. *
  2223. * @param {number} x - The value to set.
  2224. * @return {Vector2} A reference to this vector.
  2225. */
  2226. setX( x ) {
  2227. this.x = x;
  2228. return this;
  2229. }
  2230. /**
  2231. * Sets the vector's y component to the given value
  2232. *
  2233. * @param {number} y - The value to set.
  2234. * @return {Vector2} A reference to this vector.
  2235. */
  2236. setY( y ) {
  2237. this.y = y;
  2238. return this;
  2239. }
  2240. /**
  2241. * Allows to set a vector component with an index.
  2242. *
  2243. * @param {number} index - The component index. `0` equals to x, `1` equals to y.
  2244. * @param {number} value - The value to set.
  2245. * @return {Vector2} A reference to this vector.
  2246. */
  2247. setComponent( index, value ) {
  2248. switch ( index ) {
  2249. case 0: this.x = value; break;
  2250. case 1: this.y = value; break;
  2251. default: throw new Error( 'index is out of range: ' + index );
  2252. }
  2253. return this;
  2254. }
  2255. /**
  2256. * Returns the value of the vector component which matches the given index.
  2257. *
  2258. * @param {number} index - The component index. `0` equals to x, `1` equals to y.
  2259. * @return {number} A vector component value.
  2260. */
  2261. getComponent( index ) {
  2262. switch ( index ) {
  2263. case 0: return this.x;
  2264. case 1: return this.y;
  2265. default: throw new Error( 'index is out of range: ' + index );
  2266. }
  2267. }
  2268. /**
  2269. * Returns a new vector with copied values from this instance.
  2270. *
  2271. * @return {Vector2} A clone of this instance.
  2272. */
  2273. clone() {
  2274. return new this.constructor( this.x, this.y );
  2275. }
  2276. /**
  2277. * Copies the values of the given vector to this instance.
  2278. *
  2279. * @param {Vector2} v - The vector to copy.
  2280. * @return {Vector2} A reference to this vector.
  2281. */
  2282. copy( v ) {
  2283. this.x = v.x;
  2284. this.y = v.y;
  2285. return this;
  2286. }
  2287. /**
  2288. * Adds the given vector to this instance.
  2289. *
  2290. * @param {Vector2} v - The vector to add.
  2291. * @return {Vector2} A reference to this vector.
  2292. */
  2293. add( v ) {
  2294. this.x += v.x;
  2295. this.y += v.y;
  2296. return this;
  2297. }
  2298. /**
  2299. * Adds the given scalar value to all components of this instance.
  2300. *
  2301. * @param {number} s - The scalar to add.
  2302. * @return {Vector2} A reference to this vector.
  2303. */
  2304. addScalar( s ) {
  2305. this.x += s;
  2306. this.y += s;
  2307. return this;
  2308. }
  2309. /**
  2310. * Adds the given vectors and stores the result in this instance.
  2311. *
  2312. * @param {Vector2} a - The first vector.
  2313. * @param {Vector2} b - The second vector.
  2314. * @return {Vector2} A reference to this vector.
  2315. */
  2316. addVectors( a, b ) {
  2317. this.x = a.x + b.x;
  2318. this.y = a.y + b.y;
  2319. return this;
  2320. }
  2321. /**
  2322. * Adds the given vector scaled by the given factor to this instance.
  2323. *
  2324. * @param {Vector2} v - The vector.
  2325. * @param {number} s - The factor that scales `v`.
  2326. * @return {Vector2} A reference to this vector.
  2327. */
  2328. addScaledVector( v, s ) {
  2329. this.x += v.x * s;
  2330. this.y += v.y * s;
  2331. return this;
  2332. }
  2333. /**
  2334. * Subtracts the given vector from this instance.
  2335. *
  2336. * @param {Vector2} v - The vector to subtract.
  2337. * @return {Vector2} A reference to this vector.
  2338. */
  2339. sub( v ) {
  2340. this.x -= v.x;
  2341. this.y -= v.y;
  2342. return this;
  2343. }
  2344. /**
  2345. * Subtracts the given scalar value from all components of this instance.
  2346. *
  2347. * @param {number} s - The scalar to subtract.
  2348. * @return {Vector2} A reference to this vector.
  2349. */
  2350. subScalar( s ) {
  2351. this.x -= s;
  2352. this.y -= s;
  2353. return this;
  2354. }
  2355. /**
  2356. * Subtracts the given vectors and stores the result in this instance.
  2357. *
  2358. * @param {Vector2} a - The first vector.
  2359. * @param {Vector2} b - The second vector.
  2360. * @return {Vector2} A reference to this vector.
  2361. */
  2362. subVectors( a, b ) {
  2363. this.x = a.x - b.x;
  2364. this.y = a.y - b.y;
  2365. return this;
  2366. }
  2367. /**
  2368. * Multiplies the given vector with this instance.
  2369. *
  2370. * @param {Vector2} v - The vector to multiply.
  2371. * @return {Vector2} A reference to this vector.
  2372. */
  2373. multiply( v ) {
  2374. this.x *= v.x;
  2375. this.y *= v.y;
  2376. return this;
  2377. }
  2378. /**
  2379. * Multiplies the given scalar value with all components of this instance.
  2380. *
  2381. * @param {number} scalar - The scalar to multiply.
  2382. * @return {Vector2} A reference to this vector.
  2383. */
  2384. multiplyScalar( scalar ) {
  2385. this.x *= scalar;
  2386. this.y *= scalar;
  2387. return this;
  2388. }
  2389. /**
  2390. * Divides this instance by the given vector.
  2391. *
  2392. * @param {Vector2} v - The vector to divide.
  2393. * @return {Vector2} A reference to this vector.
  2394. */
  2395. divide( v ) {
  2396. this.x /= v.x;
  2397. this.y /= v.y;
  2398. return this;
  2399. }
  2400. /**
  2401. * Divides this vector by the given scalar.
  2402. *
  2403. * @param {number} scalar - The scalar to divide.
  2404. * @return {Vector2} A reference to this vector.
  2405. */
  2406. divideScalar( scalar ) {
  2407. return this.multiplyScalar( 1 / scalar );
  2408. }
  2409. /**
  2410. * Multiplies this vector (with an implicit 1 as the 3rd component) by
  2411. * the given 3x3 matrix.
  2412. *
  2413. * @param {Matrix3} m - The matrix to apply.
  2414. * @return {Vector2} A reference to this vector.
  2415. */
  2416. applyMatrix3( m ) {
  2417. const x = this.x, y = this.y;
  2418. const e = m.elements;
  2419. this.x = e[ 0 ] * x + e[ 3 ] * y + e[ 6 ];
  2420. this.y = e[ 1 ] * x + e[ 4 ] * y + e[ 7 ];
  2421. return this;
  2422. }
  2423. /**
  2424. * If this vector's x or y value is greater than the given vector's x or y
  2425. * value, replace that value with the corresponding min value.
  2426. *
  2427. * @param {Vector2} v - The vector.
  2428. * @return {Vector2} A reference to this vector.
  2429. */
  2430. min( v ) {
  2431. this.x = Math.min( this.x, v.x );
  2432. this.y = Math.min( this.y, v.y );
  2433. return this;
  2434. }
  2435. /**
  2436. * If this vector's x or y value is less than the given vector's x or y
  2437. * value, replace that value with the corresponding max value.
  2438. *
  2439. * @param {Vector2} v - The vector.
  2440. * @return {Vector2} A reference to this vector.
  2441. */
  2442. max( v ) {
  2443. this.x = Math.max( this.x, v.x );
  2444. this.y = Math.max( this.y, v.y );
  2445. return this;
  2446. }
  2447. /**
  2448. * If this vector's x or y value is greater than the max vector's x or y
  2449. * value, it is replaced by the corresponding value.
  2450. * If this vector's x or y value is less than the min vector's x or y value,
  2451. * it is replaced by the corresponding value.
  2452. *
  2453. * @param {Vector2} min - The minimum x and y values.
  2454. * @param {Vector2} max - The maximum x and y values in the desired range.
  2455. * @return {Vector2} A reference to this vector.
  2456. */
  2457. clamp( min, max ) {
  2458. // assumes min < max, componentwise
  2459. this.x = clamp( this.x, min.x, max.x );
  2460. this.y = clamp( this.y, min.y, max.y );
  2461. return this;
  2462. }
  2463. /**
  2464. * If this vector's x or y values are greater than the max value, they are
  2465. * replaced by the max value.
  2466. * If this vector's x or y values are less than the min value, they are
  2467. * replaced by the min value.
  2468. *
  2469. * @param {number} minVal - The minimum value the components will be clamped to.
  2470. * @param {number} maxVal - The maximum value the components will be clamped to.
  2471. * @return {Vector2} A reference to this vector.
  2472. */
  2473. clampScalar( minVal, maxVal ) {
  2474. this.x = clamp( this.x, minVal, maxVal );
  2475. this.y = clamp( this.y, minVal, maxVal );
  2476. return this;
  2477. }
  2478. /**
  2479. * If this vector's length is greater than the max value, it is replaced by
  2480. * the max value.
  2481. * If this vector's length is less than the min value, it is replaced by the
  2482. * min value.
  2483. *
  2484. * @param {number} min - The minimum value the vector length will be clamped to.
  2485. * @param {number} max - The maximum value the vector length will be clamped to.
  2486. * @return {Vector2} A reference to this vector.
  2487. */
  2488. clampLength( min, max ) {
  2489. const length = this.length();
  2490. return this.divideScalar( length || 1 ).multiplyScalar( clamp( length, min, max ) );
  2491. }
  2492. /**
  2493. * The components of this vector are rounded down to the nearest integer value.
  2494. *
  2495. * @return {Vector2} A reference to this vector.
  2496. */
  2497. floor() {
  2498. this.x = Math.floor( this.x );
  2499. this.y = Math.floor( this.y );
  2500. return this;
  2501. }
  2502. /**
  2503. * The components of this vector are rounded up to the nearest integer value.
  2504. *
  2505. * @return {Vector2} A reference to this vector.
  2506. */
  2507. ceil() {
  2508. this.x = Math.ceil( this.x );
  2509. this.y = Math.ceil( this.y );
  2510. return this;
  2511. }
  2512. /**
  2513. * The components of this vector are rounded to the nearest integer value
  2514. *
  2515. * @return {Vector2} A reference to this vector.
  2516. */
  2517. round() {
  2518. this.x = Math.round( this.x );
  2519. this.y = Math.round( this.y );
  2520. return this;
  2521. }
  2522. /**
  2523. * The components of this vector are rounded towards zero (up if negative,
  2524. * down if positive) to an integer value.
  2525. *
  2526. * @return {Vector2} A reference to this vector.
  2527. */
  2528. roundToZero() {
  2529. this.x = Math.trunc( this.x );
  2530. this.y = Math.trunc( this.y );
  2531. return this;
  2532. }
  2533. /**
  2534. * Inverts this vector - i.e. sets x = -x and y = -y.
  2535. *
  2536. * @return {Vector2} A reference to this vector.
  2537. */
  2538. negate() {
  2539. this.x = - this.x;
  2540. this.y = - this.y;
  2541. return this;
  2542. }
  2543. /**
  2544. * Calculates the dot product of the given vector with this instance.
  2545. *
  2546. * @param {Vector2} v - The vector to compute the dot product with.
  2547. * @return {number} The result of the dot product.
  2548. */
  2549. dot( v ) {
  2550. return this.x * v.x + this.y * v.y;
  2551. }
  2552. /**
  2553. * Calculates the cross product of the given vector with this instance.
  2554. *
  2555. * @param {Vector2} v - The vector to compute the cross product with.
  2556. * @return {number} The result of the cross product.
  2557. */
  2558. cross( v ) {
  2559. return this.x * v.y - this.y * v.x;
  2560. }
  2561. /**
  2562. * Computes the square of the Euclidean length (straight-line length) from
  2563. * (0, 0) to (x, y). If you are comparing the lengths of vectors, you should
  2564. * compare the length squared instead as it is slightly more efficient to calculate.
  2565. *
  2566. * @return {number} The square length of this vector.
  2567. */
  2568. lengthSq() {
  2569. return this.x * this.x + this.y * this.y;
  2570. }
  2571. /**
  2572. * Computes the Euclidean length (straight-line length) from (0, 0) to (x, y).
  2573. *
  2574. * @return {number} The length of this vector.
  2575. */
  2576. length() {
  2577. return Math.sqrt( this.x * this.x + this.y * this.y );
  2578. }
  2579. /**
  2580. * Computes the Manhattan length of this vector.
  2581. *
  2582. * @return {number} The length of this vector.
  2583. */
  2584. manhattanLength() {
  2585. return Math.abs( this.x ) + Math.abs( this.y );
  2586. }
  2587. /**
  2588. * Converts this vector to a unit vector - that is, sets it equal to a vector
  2589. * with the same direction as this one, but with a vector length of `1`.
  2590. *
  2591. * @return {Vector2} A reference to this vector.
  2592. */
  2593. normalize() {
  2594. return this.divideScalar( this.length() || 1 );
  2595. }
  2596. /**
  2597. * Computes the angle in radians of this vector with respect to the positive x-axis.
  2598. *
  2599. * @return {number} The angle in radians.
  2600. */
  2601. angle() {
  2602. const angle = Math.atan2( - this.y, - this.x ) + Math.PI;
  2603. return angle;
  2604. }
  2605. /**
  2606. * Returns the angle between the given vector and this instance in radians.
  2607. *
  2608. * @param {Vector2} v - The vector to compute the angle with.
  2609. * @return {number} The angle in radians.
  2610. */
  2611. angleTo( v ) {
  2612. const denominator = Math.sqrt( this.lengthSq() * v.lengthSq() );
  2613. if ( denominator === 0 ) return Math.PI / 2;
  2614. const theta = this.dot( v ) / denominator;
  2615. // clamp, to handle numerical problems
  2616. return Math.acos( clamp( theta, -1, 1 ) );
  2617. }
  2618. /**
  2619. * Computes the distance from the given vector to this instance.
  2620. *
  2621. * @param {Vector2} v - The vector to compute the distance to.
  2622. * @return {number} The distance.
  2623. */
  2624. distanceTo( v ) {
  2625. return Math.sqrt( this.distanceToSquared( v ) );
  2626. }
  2627. /**
  2628. * Computes the squared distance from the given vector to this instance.
  2629. * If you are just comparing the distance with another distance, you should compare
  2630. * the distance squared instead as it is slightly more efficient to calculate.
  2631. *
  2632. * @param {Vector2} v - The vector to compute the squared distance to.
  2633. * @return {number} The squared distance.
  2634. */
  2635. distanceToSquared( v ) {
  2636. const dx = this.x - v.x, dy = this.y - v.y;
  2637. return dx * dx + dy * dy;
  2638. }
  2639. /**
  2640. * Computes the Manhattan distance from the given vector to this instance.
  2641. *
  2642. * @param {Vector2} v - The vector to compute the Manhattan distance to.
  2643. * @return {number} The Manhattan distance.
  2644. */
  2645. manhattanDistanceTo( v ) {
  2646. return Math.abs( this.x - v.x ) + Math.abs( this.y - v.y );
  2647. }
  2648. /**
  2649. * Sets this vector to a vector with the same direction as this one, but
  2650. * with the specified length.
  2651. *
  2652. * @param {number} length - The new length of this vector.
  2653. * @return {Vector2} A reference to this vector.
  2654. */
  2655. setLength( length ) {
  2656. return this.normalize().multiplyScalar( length );
  2657. }
  2658. /**
  2659. * Linearly interpolates between the given vector and this instance, where
  2660. * alpha is the percent distance along the line - alpha = 0 will be this
  2661. * vector, and alpha = 1 will be the given one.
  2662. *
  2663. * @param {Vector2} v - The vector to interpolate towards.
  2664. * @param {number} alpha - The interpolation factor, typically in the closed interval `[0, 1]`.
  2665. * @return {Vector2} A reference to this vector.
  2666. */
  2667. lerp( v, alpha ) {
  2668. this.x += ( v.x - this.x ) * alpha;
  2669. this.y += ( v.y - this.y ) * alpha;
  2670. return this;
  2671. }
  2672. /**
  2673. * Linearly interpolates between the given vectors, where alpha is the percent
  2674. * distance along the line - alpha = 0 will be first vector, and alpha = 1 will
  2675. * be the second one. The result is stored in this instance.
  2676. *
  2677. * @param {Vector2} v1 - The first vector.
  2678. * @param {Vector2} v2 - The second vector.
  2679. * @param {number} alpha - The interpolation factor, typically in the closed interval `[0, 1]`.
  2680. * @return {Vector2} A reference to this vector.
  2681. */
  2682. lerpVectors( v1, v2, alpha ) {
  2683. this.x = v1.x + ( v2.x - v1.x ) * alpha;
  2684. this.y = v1.y + ( v2.y - v1.y ) * alpha;
  2685. return this;
  2686. }
  2687. /**
  2688. * Returns `true` if this vector is equal with the given one.
  2689. *
  2690. * @param {Vector2} v - The vector to test for equality.
  2691. * @return {boolean} Whether this vector is equal with the given one.
  2692. */
  2693. equals( v ) {
  2694. return ( ( v.x === this.x ) && ( v.y === this.y ) );
  2695. }
  2696. /**
  2697. * Sets this vector's x value to be `array[ offset ]` and y
  2698. * value to be `array[ offset + 1 ]`.
  2699. *
  2700. * @param {Array<number>} array - An array holding the vector component values.
  2701. * @param {number} [offset=0] - The offset into the array.
  2702. * @return {Vector2} A reference to this vector.
  2703. */
  2704. fromArray( array, offset = 0 ) {
  2705. this.x = array[ offset ];
  2706. this.y = array[ offset + 1 ];
  2707. return this;
  2708. }
  2709. /**
  2710. * Writes the components of this vector to the given array. If no array is provided,
  2711. * the method returns a new instance.
  2712. *
  2713. * @param {Array<number>} [array=[]] - The target array holding the vector components.
  2714. * @param {number} [offset=0] - Index of the first element in the array.
  2715. * @return {Array<number>} The vector components.
  2716. */
  2717. toArray( array = [], offset = 0 ) {
  2718. array[ offset ] = this.x;
  2719. array[ offset + 1 ] = this.y;
  2720. return array;
  2721. }
  2722. /**
  2723. * Sets the components of this vector from the given buffer attribute.
  2724. *
  2725. * @param {BufferAttribute} attribute - The buffer attribute holding vector data.
  2726. * @param {number} index - The index into the attribute.
  2727. * @return {Vector2} A reference to this vector.
  2728. */
  2729. fromBufferAttribute( attribute, index ) {
  2730. this.x = attribute.getX( index );
  2731. this.y = attribute.getY( index );
  2732. return this;
  2733. }
  2734. /**
  2735. * Rotates this vector around the given center by the given angle.
  2736. *
  2737. * @param {Vector2} center - The point around which to rotate.
  2738. * @param {number} angle - The angle to rotate, in radians.
  2739. * @return {Vector2} A reference to this vector.
  2740. */
  2741. rotateAround( center, angle ) {
  2742. const c = Math.cos( angle ), s = Math.sin( angle );
  2743. const x = this.x - center.x;
  2744. const y = this.y - center.y;
  2745. this.x = x * c - y * s + center.x;
  2746. this.y = x * s + y * c + center.y;
  2747. return this;
  2748. }
  2749. /**
  2750. * Sets each component of this vector to a pseudo-random value between `0` and
  2751. * `1`, excluding `1`.
  2752. *
  2753. * @return {Vector2} A reference to this vector.
  2754. */
  2755. random() {
  2756. this.x = Math.random();
  2757. this.y = Math.random();
  2758. return this;
  2759. }
  2760. *[ Symbol.iterator ]() {
  2761. yield this.x;
  2762. yield this.y;
  2763. }
  2764. }
  2765. /**
  2766. * Represents a 3x3 matrix.
  2767. *
  2768. * A Note on Row-Major and Column-Major Ordering:
  2769. *
  2770. * The constructor and {@link Matrix3#set} method take arguments in
  2771. * [row-major]{@link https://en.wikipedia.org/wiki/Row-_and_column-major_order#Column-major_order}
  2772. * order, while internally they are stored in the {@link Matrix3#elements} array in column-major order.
  2773. * This means that calling:
  2774. * ```js
  2775. * const m = new THREE.Matrix();
  2776. * m.set( 11, 12, 13,
  2777. * 21, 22, 23,
  2778. * 31, 32, 33 );
  2779. * ```
  2780. * will result in the elements array containing:
  2781. * ```js
  2782. * m.elements = [ 11, 21, 31,
  2783. * 12, 22, 32,
  2784. * 13, 23, 33 ];
  2785. * ```
  2786. * and internally all calculations are performed using column-major ordering.
  2787. * However, as the actual ordering makes no difference mathematically and
  2788. * most people are used to thinking about matrices in row-major order, the
  2789. * three.js documentation shows matrices in row-major order. Just bear in
  2790. * mind that if you are reading the source code, you'll have to take the
  2791. * transpose of any matrices outlined here to make sense of the calculations.
  2792. */
  2793. class Matrix3 {
  2794. /**
  2795. * Constructs a new 3x3 matrix. The arguments are supposed to be
  2796. * in row-major order. If no arguments are provided, the constructor
  2797. * initializes the matrix as an identity matrix.
  2798. *
  2799. * @param {number} [n11] - 1-1 matrix element.
  2800. * @param {number} [n12] - 1-2 matrix element.
  2801. * @param {number} [n13] - 1-3 matrix element.
  2802. * @param {number} [n21] - 2-1 matrix element.
  2803. * @param {number} [n22] - 2-2 matrix element.
  2804. * @param {number} [n23] - 2-3 matrix element.
  2805. * @param {number} [n31] - 3-1 matrix element.
  2806. * @param {number} [n32] - 3-2 matrix element.
  2807. * @param {number} [n33] - 3-3 matrix element.
  2808. */
  2809. constructor( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) {
  2810. /**
  2811. * This flag can be used for type testing.
  2812. *
  2813. * @type {boolean}
  2814. * @readonly
  2815. * @default true
  2816. */
  2817. Matrix3.prototype.isMatrix3 = true;
  2818. /**
  2819. * A column-major list of matrix values.
  2820. *
  2821. * @type {Array<number>}
  2822. */
  2823. this.elements = [
  2824. 1, 0, 0,
  2825. 0, 1, 0,
  2826. 0, 0, 1
  2827. ];
  2828. if ( n11 !== undefined ) {
  2829. this.set( n11, n12, n13, n21, n22, n23, n31, n32, n33 );
  2830. }
  2831. }
  2832. /**
  2833. * Sets the elements of the matrix.The arguments are supposed to be
  2834. * in row-major order.
  2835. *
  2836. * @param {number} [n11] - 1-1 matrix element.
  2837. * @param {number} [n12] - 1-2 matrix element.
  2838. * @param {number} [n13] - 1-3 matrix element.
  2839. * @param {number} [n21] - 2-1 matrix element.
  2840. * @param {number} [n22] - 2-2 matrix element.
  2841. * @param {number} [n23] - 2-3 matrix element.
  2842. * @param {number} [n31] - 3-1 matrix element.
  2843. * @param {number} [n32] - 3-2 matrix element.
  2844. * @param {number} [n33] - 3-3 matrix element.
  2845. * @return {Matrix3} A reference to this matrix.
  2846. */
  2847. set( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) {
  2848. const te = this.elements;
  2849. te[ 0 ] = n11; te[ 1 ] = n21; te[ 2 ] = n31;
  2850. te[ 3 ] = n12; te[ 4 ] = n22; te[ 5 ] = n32;
  2851. te[ 6 ] = n13; te[ 7 ] = n23; te[ 8 ] = n33;
  2852. return this;
  2853. }
  2854. /**
  2855. * Sets this matrix to the 3x3 identity matrix.
  2856. *
  2857. * @return {Matrix3} A reference to this matrix.
  2858. */
  2859. identity() {
  2860. this.set(
  2861. 1, 0, 0,
  2862. 0, 1, 0,
  2863. 0, 0, 1
  2864. );
  2865. return this;
  2866. }
  2867. /**
  2868. * Copies the values of the given matrix to this instance.
  2869. *
  2870. * @param {Matrix3} m - The matrix to copy.
  2871. * @return {Matrix3} A reference to this matrix.
  2872. */
  2873. copy( m ) {
  2874. const te = this.elements;
  2875. const me = m.elements;
  2876. te[ 0 ] = me[ 0 ]; te[ 1 ] = me[ 1 ]; te[ 2 ] = me[ 2 ];
  2877. te[ 3 ] = me[ 3 ]; te[ 4 ] = me[ 4 ]; te[ 5 ] = me[ 5 ];
  2878. te[ 6 ] = me[ 6 ]; te[ 7 ] = me[ 7 ]; te[ 8 ] = me[ 8 ];
  2879. return this;
  2880. }
  2881. /**
  2882. * Extracts the basis of this matrix into the three axis vectors provided.
  2883. *
  2884. * @param {Vector3} xAxis - The basis's x axis.
  2885. * @param {Vector3} yAxis - The basis's y axis.
  2886. * @param {Vector3} zAxis - The basis's z axis.
  2887. * @return {Matrix3} A reference to this matrix.
  2888. */
  2889. extractBasis( xAxis, yAxis, zAxis ) {
  2890. xAxis.setFromMatrix3Column( this, 0 );
  2891. yAxis.setFromMatrix3Column( this, 1 );
  2892. zAxis.setFromMatrix3Column( this, 2 );
  2893. return this;
  2894. }
  2895. /**
  2896. * Set this matrix to the upper 3x3 matrix of the given 4x4 matrix.
  2897. *
  2898. * @param {Matrix4} m - The 4x4 matrix.
  2899. * @return {Matrix3} A reference to this matrix.
  2900. */
  2901. setFromMatrix4( m ) {
  2902. const me = m.elements;
  2903. this.set(
  2904. me[ 0 ], me[ 4 ], me[ 8 ],
  2905. me[ 1 ], me[ 5 ], me[ 9 ],
  2906. me[ 2 ], me[ 6 ], me[ 10 ]
  2907. );
  2908. return this;
  2909. }
  2910. /**
  2911. * Post-multiplies this matrix by the given 3x3 matrix.
  2912. *
  2913. * @param {Matrix3} m - The matrix to multiply with.
  2914. * @return {Matrix3} A reference to this matrix.
  2915. */
  2916. multiply( m ) {
  2917. return this.multiplyMatrices( this, m );
  2918. }
  2919. /**
  2920. * Pre-multiplies this matrix by the given 3x3 matrix.
  2921. *
  2922. * @param {Matrix3} m - The matrix to multiply with.
  2923. * @return {Matrix3} A reference to this matrix.
  2924. */
  2925. premultiply( m ) {
  2926. return this.multiplyMatrices( m, this );
  2927. }
  2928. /**
  2929. * Multiples the given 3x3 matrices and stores the result
  2930. * in this matrix.
  2931. *
  2932. * @param {Matrix3} a - The first matrix.
  2933. * @param {Matrix3} b - The second matrix.
  2934. * @return {Matrix3} A reference to this matrix.
  2935. */
  2936. multiplyMatrices( a, b ) {
  2937. const ae = a.elements;
  2938. const be = b.elements;
  2939. const te = this.elements;
  2940. const a11 = ae[ 0 ], a12 = ae[ 3 ], a13 = ae[ 6 ];
  2941. const a21 = ae[ 1 ], a22 = ae[ 4 ], a23 = ae[ 7 ];
  2942. const a31 = ae[ 2 ], a32 = ae[ 5 ], a33 = ae[ 8 ];
  2943. const b11 = be[ 0 ], b12 = be[ 3 ], b13 = be[ 6 ];
  2944. const b21 = be[ 1 ], b22 = be[ 4 ], b23 = be[ 7 ];
  2945. const b31 = be[ 2 ], b32 = be[ 5 ], b33 = be[ 8 ];
  2946. te[ 0 ] = a11 * b11 + a12 * b21 + a13 * b31;
  2947. te[ 3 ] = a11 * b12 + a12 * b22 + a13 * b32;
  2948. te[ 6 ] = a11 * b13 + a12 * b23 + a13 * b33;
  2949. te[ 1 ] = a21 * b11 + a22 * b21 + a23 * b31;
  2950. te[ 4 ] = a21 * b12 + a22 * b22 + a23 * b32;
  2951. te[ 7 ] = a21 * b13 + a22 * b23 + a23 * b33;
  2952. te[ 2 ] = a31 * b11 + a32 * b21 + a33 * b31;
  2953. te[ 5 ] = a31 * b12 + a32 * b22 + a33 * b32;
  2954. te[ 8 ] = a31 * b13 + a32 * b23 + a33 * b33;
  2955. return this;
  2956. }
  2957. /**
  2958. * Multiplies every component of the matrix by the given scalar.
  2959. *
  2960. * @param {number} s - The scalar.
  2961. * @return {Matrix3} A reference to this matrix.
  2962. */
  2963. multiplyScalar( s ) {
  2964. const te = this.elements;
  2965. te[ 0 ] *= s; te[ 3 ] *= s; te[ 6 ] *= s;
  2966. te[ 1 ] *= s; te[ 4 ] *= s; te[ 7 ] *= s;
  2967. te[ 2 ] *= s; te[ 5 ] *= s; te[ 8 ] *= s;
  2968. return this;
  2969. }
  2970. /**
  2971. * Computes and returns the determinant of this matrix.
  2972. *
  2973. * @return {number} The determinant.
  2974. */
  2975. determinant() {
  2976. const te = this.elements;
  2977. const a = te[ 0 ], b = te[ 1 ], c = te[ 2 ],
  2978. d = te[ 3 ], e = te[ 4 ], f = te[ 5 ],
  2979. g = te[ 6 ], h = te[ 7 ], i = te[ 8 ];
  2980. return a * e * i - a * f * h - b * d * i + b * f * g + c * d * h - c * e * g;
  2981. }
  2982. /**
  2983. * Inverts this matrix, using the [analytic method]{@link https://en.wikipedia.org/wiki/Invertible_matrix#Analytic_solution}.
  2984. * You can not invert with a determinant of zero. If you attempt this, the method produces
  2985. * a zero matrix instead.
  2986. *
  2987. * @return {Matrix3} A reference to this matrix.
  2988. */
  2989. invert() {
  2990. const te = this.elements,
  2991. n11 = te[ 0 ], n21 = te[ 1 ], n31 = te[ 2 ],
  2992. n12 = te[ 3 ], n22 = te[ 4 ], n32 = te[ 5 ],
  2993. n13 = te[ 6 ], n23 = te[ 7 ], n33 = te[ 8 ],
  2994. t11 = n33 * n22 - n32 * n23,
  2995. t12 = n32 * n13 - n33 * n12,
  2996. t13 = n23 * n12 - n22 * n13,
  2997. det = n11 * t11 + n21 * t12 + n31 * t13;
  2998. if ( det === 0 ) return this.set( 0, 0, 0, 0, 0, 0, 0, 0, 0 );
  2999. const detInv = 1 / det;
  3000. te[ 0 ] = t11 * detInv;
  3001. te[ 1 ] = ( n31 * n23 - n33 * n21 ) * detInv;
  3002. te[ 2 ] = ( n32 * n21 - n31 * n22 ) * detInv;
  3003. te[ 3 ] = t12 * detInv;
  3004. te[ 4 ] = ( n33 * n11 - n31 * n13 ) * detInv;
  3005. te[ 5 ] = ( n31 * n12 - n32 * n11 ) * detInv;
  3006. te[ 6 ] = t13 * detInv;
  3007. te[ 7 ] = ( n21 * n13 - n23 * n11 ) * detInv;
  3008. te[ 8 ] = ( n22 * n11 - n21 * n12 ) * detInv;
  3009. return this;
  3010. }
  3011. /**
  3012. * Transposes this matrix in place.
  3013. *
  3014. * @return {Matrix3} A reference to this matrix.
  3015. */
  3016. transpose() {
  3017. let tmp;
  3018. const m = this.elements;
  3019. tmp = m[ 1 ]; m[ 1 ] = m[ 3 ]; m[ 3 ] = tmp;
  3020. tmp = m[ 2 ]; m[ 2 ] = m[ 6 ]; m[ 6 ] = tmp;
  3021. tmp = m[ 5 ]; m[ 5 ] = m[ 7 ]; m[ 7 ] = tmp;
  3022. return this;
  3023. }
  3024. /**
  3025. * Computes the normal matrix which is the inverse transpose of the upper
  3026. * left 3x3 portion of the given 4x4 matrix.
  3027. *
  3028. * @param {Matrix4} matrix4 - The 4x4 matrix.
  3029. * @return {Matrix3} A reference to this matrix.
  3030. */
  3031. getNormalMatrix( matrix4 ) {
  3032. return this.setFromMatrix4( matrix4 ).invert().transpose();
  3033. }
  3034. /**
  3035. * Transposes this matrix into the supplied array, and returns itself unchanged.
  3036. *
  3037. * @param {Array<number>} r - An array to store the transposed matrix elements.
  3038. * @return {Matrix3} A reference to this matrix.
  3039. */
  3040. transposeIntoArray( r ) {
  3041. const m = this.elements;
  3042. r[ 0 ] = m[ 0 ];
  3043. r[ 1 ] = m[ 3 ];
  3044. r[ 2 ] = m[ 6 ];
  3045. r[ 3 ] = m[ 1 ];
  3046. r[ 4 ] = m[ 4 ];
  3047. r[ 5 ] = m[ 7 ];
  3048. r[ 6 ] = m[ 2 ];
  3049. r[ 7 ] = m[ 5 ];
  3050. r[ 8 ] = m[ 8 ];
  3051. return this;
  3052. }
  3053. /**
  3054. * Sets the UV transform matrix from offset, repeat, rotation, and center.
  3055. *
  3056. * @param {number} tx - Offset x.
  3057. * @param {number} ty - Offset y.
  3058. * @param {number} sx - Repeat x.
  3059. * @param {number} sy - Repeat y.
  3060. * @param {number} rotation - Rotation, in radians. Positive values rotate counterclockwise.
  3061. * @param {number} cx - Center x of rotation.
  3062. * @param {number} cy - Center y of rotation
  3063. * @return {Matrix3} A reference to this matrix.
  3064. */
  3065. setUvTransform( tx, ty, sx, sy, rotation, cx, cy ) {
  3066. const c = Math.cos( rotation );
  3067. const s = Math.sin( rotation );
  3068. this.set(
  3069. sx * c, sx * s, - sx * ( c * cx + s * cy ) + cx + tx,
  3070. - sy * s, sy * c, - sy * ( - s * cx + c * cy ) + cy + ty,
  3071. 0, 0, 1
  3072. );
  3073. return this;
  3074. }
  3075. /**
  3076. * Scales this matrix with the given scalar values.
  3077. *
  3078. * @param {number} sx - The amount to scale in the X axis.
  3079. * @param {number} sy - The amount to scale in the Y axis.
  3080. * @return {Matrix3} A reference to this matrix.
  3081. */
  3082. scale( sx, sy ) {
  3083. this.premultiply( _m3.makeScale( sx, sy ) );
  3084. return this;
  3085. }
  3086. /**
  3087. * Rotates this matrix by the given angle.
  3088. *
  3089. * @param {number} theta - The rotation in radians.
  3090. * @return {Matrix3} A reference to this matrix.
  3091. */
  3092. rotate( theta ) {
  3093. this.premultiply( _m3.makeRotation( - theta ) );
  3094. return this;
  3095. }
  3096. /**
  3097. * Translates this matrix by the given scalar values.
  3098. *
  3099. * @param {number} tx - The amount to translate in the X axis.
  3100. * @param {number} ty - The amount to translate in the Y axis.
  3101. * @return {Matrix3} A reference to this matrix.
  3102. */
  3103. translate( tx, ty ) {
  3104. this.premultiply( _m3.makeTranslation( tx, ty ) );
  3105. return this;
  3106. }
  3107. // for 2D Transforms
  3108. /**
  3109. * Sets this matrix as a 2D translation transform.
  3110. *
  3111. * @param {number|Vector2} x - The amount to translate in the X axis or alternatively a translation vector.
  3112. * @param {number} y - The amount to translate in the Y axis.
  3113. * @return {Matrix3} A reference to this matrix.
  3114. */
  3115. makeTranslation( x, y ) {
  3116. if ( x.isVector2 ) {
  3117. this.set(
  3118. 1, 0, x.x,
  3119. 0, 1, x.y,
  3120. 0, 0, 1
  3121. );
  3122. } else {
  3123. this.set(
  3124. 1, 0, x,
  3125. 0, 1, y,
  3126. 0, 0, 1
  3127. );
  3128. }
  3129. return this;
  3130. }
  3131. /**
  3132. * Sets this matrix as a 2D rotational transformation.
  3133. *
  3134. * @param {number} theta - The rotation in radians.
  3135. * @return {Matrix3} A reference to this matrix.
  3136. */
  3137. makeRotation( theta ) {
  3138. // counterclockwise
  3139. const c = Math.cos( theta );
  3140. const s = Math.sin( theta );
  3141. this.set(
  3142. c, - s, 0,
  3143. s, c, 0,
  3144. 0, 0, 1
  3145. );
  3146. return this;
  3147. }
  3148. /**
  3149. * Sets this matrix as a 2D scale transform.
  3150. *
  3151. * @param {number} x - The amount to scale in the X axis.
  3152. * @param {number} y - The amount to scale in the Y axis.
  3153. * @return {Matrix3} A reference to this matrix.
  3154. */
  3155. makeScale( x, y ) {
  3156. this.set(
  3157. x, 0, 0,
  3158. 0, y, 0,
  3159. 0, 0, 1
  3160. );
  3161. return this;
  3162. }
  3163. /**
  3164. * Returns `true` if this matrix is equal with the given one.
  3165. *
  3166. * @param {Matrix3} matrix - The matrix to test for equality.
  3167. * @return {boolean} Whether this matrix is equal with the given one.
  3168. */
  3169. equals( matrix ) {
  3170. const te = this.elements;
  3171. const me = matrix.elements;
  3172. for ( let i = 0; i < 9; i ++ ) {
  3173. if ( te[ i ] !== me[ i ] ) return false;
  3174. }
  3175. return true;
  3176. }
  3177. /**
  3178. * Sets the elements of the matrix from the given array.
  3179. *
  3180. * @param {Array<number>} array - The matrix elements in column-major order.
  3181. * @param {number} [offset=0] - Index of the first element in the array.
  3182. * @return {Matrix3} A reference to this matrix.
  3183. */
  3184. fromArray( array, offset = 0 ) {
  3185. for ( let i = 0; i < 9; i ++ ) {
  3186. this.elements[ i ] = array[ i + offset ];
  3187. }
  3188. return this;
  3189. }
  3190. /**
  3191. * Writes the elements of this matrix to the given array. If no array is provided,
  3192. * the method returns a new instance.
  3193. *
  3194. * @param {Array<number>} [array=[]] - The target array holding the matrix elements in column-major order.
  3195. * @param {number} [offset=0] - Index of the first element in the array.
  3196. * @return {Array<number>} The matrix elements in column-major order.
  3197. */
  3198. toArray( array = [], offset = 0 ) {
  3199. const te = this.elements;
  3200. array[ offset ] = te[ 0 ];
  3201. array[ offset + 1 ] = te[ 1 ];
  3202. array[ offset + 2 ] = te[ 2 ];
  3203. array[ offset + 3 ] = te[ 3 ];
  3204. array[ offset + 4 ] = te[ 4 ];
  3205. array[ offset + 5 ] = te[ 5 ];
  3206. array[ offset + 6 ] = te[ 6 ];
  3207. array[ offset + 7 ] = te[ 7 ];
  3208. array[ offset + 8 ] = te[ 8 ];
  3209. return array;
  3210. }
  3211. /**
  3212. * Returns a matrix with copied values from this instance.
  3213. *
  3214. * @return {Matrix3} A clone of this instance.
  3215. */
  3216. clone() {
  3217. return new this.constructor().fromArray( this.elements );
  3218. }
  3219. }
  3220. const _m3 = /*@__PURE__*/ new Matrix3();
  3221. function arrayNeedsUint32( array ) {
  3222. // assumes larger values usually on last
  3223. for ( let i = array.length - 1; i >= 0; -- i ) {
  3224. if ( array[ i ] >= 65535 ) return true; // account for PRIMITIVE_RESTART_FIXED_INDEX, #24565
  3225. }
  3226. return false;
  3227. }
  3228. const TYPED_ARRAYS = {
  3229. Int8Array: Int8Array,
  3230. Uint8Array: Uint8Array,
  3231. Uint8ClampedArray: Uint8ClampedArray,
  3232. Int16Array: Int16Array,
  3233. Uint16Array: Uint16Array,
  3234. Int32Array: Int32Array,
  3235. Uint32Array: Uint32Array,
  3236. Float32Array: Float32Array,
  3237. Float64Array: Float64Array
  3238. };
  3239. function getTypedArray( type, buffer ) {
  3240. return new TYPED_ARRAYS[ type ]( buffer );
  3241. }
  3242. function createElementNS( name ) {
  3243. return document.createElementNS( 'http://www.w3.org/1999/xhtml', name );
  3244. }
  3245. function createCanvasElement() {
  3246. const canvas = createElementNS( 'canvas' );
  3247. canvas.style.display = 'block';
  3248. return canvas;
  3249. }
  3250. const _cache = {};
  3251. function warnOnce( message ) {
  3252. if ( message in _cache ) return;
  3253. _cache[ message ] = true;
  3254. console.warn( message );
  3255. }
  3256. function probeAsync( gl, sync, interval ) {
  3257. return new Promise( function ( resolve, reject ) {
  3258. function probe() {
  3259. switch ( gl.clientWaitSync( sync, gl.SYNC_FLUSH_COMMANDS_BIT, 0 ) ) {
  3260. case gl.WAIT_FAILED:
  3261. reject();
  3262. break;
  3263. case gl.TIMEOUT_EXPIRED:
  3264. setTimeout( probe, interval );
  3265. break;
  3266. default:
  3267. resolve();
  3268. }
  3269. }
  3270. setTimeout( probe, interval );
  3271. } );
  3272. }
  3273. function toNormalizedProjectionMatrix( projectionMatrix ) {
  3274. const m = projectionMatrix.elements;
  3275. // Convert [-1, 1] to [0, 1] projection matrix
  3276. m[ 2 ] = 0.5 * m[ 2 ] + 0.5 * m[ 3 ];
  3277. m[ 6 ] = 0.5 * m[ 6 ] + 0.5 * m[ 7 ];
  3278. m[ 10 ] = 0.5 * m[ 10 ] + 0.5 * m[ 11 ];
  3279. m[ 14 ] = 0.5 * m[ 14 ] + 0.5 * m[ 15 ];
  3280. }
  3281. function toReversedProjectionMatrix( projectionMatrix ) {
  3282. const m = projectionMatrix.elements;
  3283. const isPerspectiveMatrix = m[ 11 ] === -1;
  3284. // Reverse [0, 1] projection matrix
  3285. if ( isPerspectiveMatrix ) {
  3286. m[ 10 ] = - m[ 10 ] - 1;
  3287. m[ 14 ] = - m[ 14 ];
  3288. } else {
  3289. m[ 10 ] = - m[ 10 ];
  3290. m[ 14 ] = - m[ 14 ] + 1;
  3291. }
  3292. }
  3293. const LINEAR_REC709_TO_XYZ = /*@__PURE__*/ new Matrix3().set(
  3294. 0.4123908, 0.3575843, 0.1804808,
  3295. 0.2126390, 0.7151687, 0.0721923,
  3296. 0.0193308, 0.1191948, 0.9505322
  3297. );
  3298. const XYZ_TO_LINEAR_REC709 = /*@__PURE__*/ new Matrix3().set(
  3299. 3.2409699, -1.5373832, -0.4986108,
  3300. -0.9692436, 1.8759675, 0.0415551,
  3301. 0.0556301, -0.203977, 1.0569715
  3302. );
  3303. function createColorManagement() {
  3304. const ColorManagement = {
  3305. enabled: true,
  3306. workingColorSpace: LinearSRGBColorSpace,
  3307. /**
  3308. * Implementations of supported color spaces.
  3309. *
  3310. * Required:
  3311. * - primaries: chromaticity coordinates [ rx ry gx gy bx by ]
  3312. * - whitePoint: reference white [ x y ]
  3313. * - transfer: transfer function (pre-defined)
  3314. * - toXYZ: Matrix3 RGB to XYZ transform
  3315. * - fromXYZ: Matrix3 XYZ to RGB transform
  3316. * - luminanceCoefficients: RGB luminance coefficients
  3317. *
  3318. * Optional:
  3319. * - outputColorSpaceConfig: { drawingBufferColorSpace: ColorSpace }
  3320. * - workingColorSpaceConfig: { unpackColorSpace: ColorSpace }
  3321. *
  3322. * Reference:
  3323. * - https://www.russellcottrell.com/photo/matrixCalculator.htm
  3324. */
  3325. spaces: {},
  3326. convert: function ( color, sourceColorSpace, targetColorSpace ) {
  3327. if ( this.enabled === false || sourceColorSpace === targetColorSpace || ! sourceColorSpace || ! targetColorSpace ) {
  3328. return color;
  3329. }
  3330. if ( this.spaces[ sourceColorSpace ].transfer === SRGBTransfer ) {
  3331. color.r = SRGBToLinear( color.r );
  3332. color.g = SRGBToLinear( color.g );
  3333. color.b = SRGBToLinear( color.b );
  3334. }
  3335. if ( this.spaces[ sourceColorSpace ].primaries !== this.spaces[ targetColorSpace ].primaries ) {
  3336. color.applyMatrix3( this.spaces[ sourceColorSpace ].toXYZ );
  3337. color.applyMatrix3( this.spaces[ targetColorSpace ].fromXYZ );
  3338. }
  3339. if ( this.spaces[ targetColorSpace ].transfer === SRGBTransfer ) {
  3340. color.r = LinearToSRGB( color.r );
  3341. color.g = LinearToSRGB( color.g );
  3342. color.b = LinearToSRGB( color.b );
  3343. }
  3344. return color;
  3345. },
  3346. fromWorkingColorSpace: function ( color, targetColorSpace ) {
  3347. return this.convert( color, this.workingColorSpace, targetColorSpace );
  3348. },
  3349. toWorkingColorSpace: function ( color, sourceColorSpace ) {
  3350. return this.convert( color, sourceColorSpace, this.workingColorSpace );
  3351. },
  3352. getPrimaries: function ( colorSpace ) {
  3353. return this.spaces[ colorSpace ].primaries;
  3354. },
  3355. getTransfer: function ( colorSpace ) {
  3356. if ( colorSpace === NoColorSpace ) return LinearTransfer;
  3357. return this.spaces[ colorSpace ].transfer;
  3358. },
  3359. getLuminanceCoefficients: function ( target, colorSpace = this.workingColorSpace ) {
  3360. return target.fromArray( this.spaces[ colorSpace ].luminanceCoefficients );
  3361. },
  3362. define: function ( colorSpaces ) {
  3363. Object.assign( this.spaces, colorSpaces );
  3364. },
  3365. // Internal APIs
  3366. _getMatrix: function ( targetMatrix, sourceColorSpace, targetColorSpace ) {
  3367. return targetMatrix
  3368. .copy( this.spaces[ sourceColorSpace ].toXYZ )
  3369. .multiply( this.spaces[ targetColorSpace ].fromXYZ );
  3370. },
  3371. _getDrawingBufferColorSpace: function ( colorSpace ) {
  3372. return this.spaces[ colorSpace ].outputColorSpaceConfig.drawingBufferColorSpace;
  3373. },
  3374. _getUnpackColorSpace: function ( colorSpace = this.workingColorSpace ) {
  3375. return this.spaces[ colorSpace ].workingColorSpaceConfig.unpackColorSpace;
  3376. }
  3377. };
  3378. /******************************************************************************
  3379. * sRGB definitions
  3380. */
  3381. const REC709_PRIMARIES = [ 0.640, 0.330, 0.300, 0.600, 0.150, 0.060 ];
  3382. const REC709_LUMINANCE_COEFFICIENTS = [ 0.2126, 0.7152, 0.0722 ];
  3383. const D65 = [ 0.3127, 0.3290 ];
  3384. ColorManagement.define( {
  3385. [ LinearSRGBColorSpace ]: {
  3386. primaries: REC709_PRIMARIES,
  3387. whitePoint: D65,
  3388. transfer: LinearTransfer,
  3389. toXYZ: LINEAR_REC709_TO_XYZ,
  3390. fromXYZ: XYZ_TO_LINEAR_REC709,
  3391. luminanceCoefficients: REC709_LUMINANCE_COEFFICIENTS,
  3392. workingColorSpaceConfig: { unpackColorSpace: SRGBColorSpace },
  3393. outputColorSpaceConfig: { drawingBufferColorSpace: SRGBColorSpace }
  3394. },
  3395. [ SRGBColorSpace ]: {
  3396. primaries: REC709_PRIMARIES,
  3397. whitePoint: D65,
  3398. transfer: SRGBTransfer,
  3399. toXYZ: LINEAR_REC709_TO_XYZ,
  3400. fromXYZ: XYZ_TO_LINEAR_REC709,
  3401. luminanceCoefficients: REC709_LUMINANCE_COEFFICIENTS,
  3402. outputColorSpaceConfig: { drawingBufferColorSpace: SRGBColorSpace }
  3403. },
  3404. } );
  3405. return ColorManagement;
  3406. }
  3407. const ColorManagement = /*@__PURE__*/ createColorManagement();
  3408. function SRGBToLinear( c ) {
  3409. return ( c < 0.04045 ) ? c * 0.0773993808 : Math.pow( c * 0.9478672986 + 0.0521327014, 2.4 );
  3410. }
  3411. function LinearToSRGB( c ) {
  3412. return ( c < 0.0031308 ) ? c * 12.92 : 1.055 * ( Math.pow( c, 0.41666 ) ) - 0.055;
  3413. }
  3414. let _canvas;
  3415. /**
  3416. * A class containing utility functions for images.
  3417. *
  3418. * @hideconstructor
  3419. */
  3420. class ImageUtils {
  3421. /**
  3422. * Returns a data URI containing a representation of the given image.
  3423. *
  3424. * @param {(HTMLImageElement|HTMLCanvasElement)} image - The image object.
  3425. * @return {string} The data URI.
  3426. */
  3427. static getDataURL( image ) {
  3428. if ( /^data:/i.test( image.src ) ) {
  3429. return image.src;
  3430. }
  3431. if ( typeof HTMLCanvasElement === 'undefined' ) {
  3432. return image.src;
  3433. }
  3434. let canvas;
  3435. if ( image instanceof HTMLCanvasElement ) {
  3436. canvas = image;
  3437. } else {
  3438. if ( _canvas === undefined ) _canvas = createElementNS( 'canvas' );
  3439. _canvas.width = image.width;
  3440. _canvas.height = image.height;
  3441. const context = _canvas.getContext( '2d' );
  3442. if ( image instanceof ImageData ) {
  3443. context.putImageData( image, 0, 0 );
  3444. } else {
  3445. context.drawImage( image, 0, 0, image.width, image.height );
  3446. }
  3447. canvas = _canvas;
  3448. }
  3449. return canvas.toDataURL( 'image/png' );
  3450. }
  3451. /**
  3452. * Converts the given sRGB image data to linear color space.
  3453. *
  3454. * @param {(HTMLImageElement|HTMLCanvasElement|ImageBitmap|Object)} image - The image object.
  3455. * @return {HTMLCanvasElement|Object} The converted image.
  3456. */
  3457. static sRGBToLinear( image ) {
  3458. if ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) ||
  3459. ( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) ||
  3460. ( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) ) {
  3461. const canvas = createElementNS( 'canvas' );
  3462. canvas.width = image.width;
  3463. canvas.height = image.height;
  3464. const context = canvas.getContext( '2d' );
  3465. context.drawImage( image, 0, 0, image.width, image.height );
  3466. const imageData = context.getImageData( 0, 0, image.width, image.height );
  3467. const data = imageData.data;
  3468. for ( let i = 0; i < data.length; i ++ ) {
  3469. data[ i ] = SRGBToLinear( data[ i ] / 255 ) * 255;
  3470. }
  3471. context.putImageData( imageData, 0, 0 );
  3472. return canvas;
  3473. } else if ( image.data ) {
  3474. const data = image.data.slice( 0 );
  3475. for ( let i = 0; i < data.length; i ++ ) {
  3476. if ( data instanceof Uint8Array || data instanceof Uint8ClampedArray ) {
  3477. data[ i ] = Math.floor( SRGBToLinear( data[ i ] / 255 ) * 255 );
  3478. } else {
  3479. // assuming float
  3480. data[ i ] = SRGBToLinear( data[ i ] );
  3481. }
  3482. }
  3483. return {
  3484. data: data,
  3485. width: image.width,
  3486. height: image.height
  3487. };
  3488. } else {
  3489. console.warn( 'THREE.ImageUtils.sRGBToLinear(): Unsupported image type. No color space conversion applied.' );
  3490. return image;
  3491. }
  3492. }
  3493. }
  3494. let _sourceId = 0;
  3495. /**
  3496. * Represents the data source of a texture.
  3497. *
  3498. * The main purpose of this class is to decouple the data definition from the texture
  3499. * definition so the same data can be used with multiple texture instances.
  3500. */
  3501. class Source {
  3502. /**
  3503. * Constructs a new video texture.
  3504. *
  3505. * @param {any} [data=null] - The data definition of a texture.
  3506. */
  3507. constructor( data = null ) {
  3508. /**
  3509. * This flag can be used for type testing.
  3510. *
  3511. * @type {boolean}
  3512. * @readonly
  3513. * @default true
  3514. */
  3515. this.isSource = true;
  3516. /**
  3517. * The ID of the source.
  3518. *
  3519. * @name Source#id
  3520. * @type {number}
  3521. * @readonly
  3522. */
  3523. Object.defineProperty( this, 'id', { value: _sourceId ++ } );
  3524. /**
  3525. * The UUID of the source.
  3526. *
  3527. * @type {string}
  3528. * @readonly
  3529. */
  3530. this.uuid = generateUUID();
  3531. /**
  3532. * The data definition of a texture.
  3533. *
  3534. * @type {any}
  3535. */
  3536. this.data = data;
  3537. /**
  3538. * This property is only relevant when {@link Source#needsUpdate} is set to `true` and
  3539. * provides more control on how texture data should be processed. When `dataReady` is set
  3540. * to `false`, the engine performs the memory allocation (if necessary) but does not transfer
  3541. * the data into the GPU memory.
  3542. *
  3543. * @type {boolean}
  3544. * @default true
  3545. */
  3546. this.dataReady = true;
  3547. /**
  3548. * This starts at `0` and counts how many times {@link Source#needsUpdate} is set to `true`.
  3549. *
  3550. * @type {number}
  3551. * @readonly
  3552. * @default 0
  3553. */
  3554. this.version = 0;
  3555. }
  3556. /**
  3557. * When the property is set to `true`, the engine allocates the memory
  3558. * for the texture (if necessary) and triggers the actual texture upload
  3559. * to the GPU next time the source is used.
  3560. *
  3561. * @type {boolean}
  3562. * @default false
  3563. * @param {boolean} value
  3564. */
  3565. set needsUpdate( value ) {
  3566. if ( value === true ) this.version ++;
  3567. }
  3568. /**
  3569. * Serializes the source into JSON.
  3570. *
  3571. * @param {?(Object|string)} meta - An optional value holding meta information about the serialization.
  3572. * @return {Object} A JSON object representing the serialized source.
  3573. * @see {@link ObjectLoader#parse}
  3574. */
  3575. toJSON( meta ) {
  3576. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  3577. if ( ! isRootObject && meta.images[ this.uuid ] !== undefined ) {
  3578. return meta.images[ this.uuid ];
  3579. }
  3580. const output = {
  3581. uuid: this.uuid,
  3582. url: ''
  3583. };
  3584. const data = this.data;
  3585. if ( data !== null ) {
  3586. let url;
  3587. if ( Array.isArray( data ) ) {
  3588. // cube texture
  3589. url = [];
  3590. for ( let i = 0, l = data.length; i < l; i ++ ) {
  3591. if ( data[ i ].isDataTexture ) {
  3592. url.push( serializeImage( data[ i ].image ) );
  3593. } else {
  3594. url.push( serializeImage( data[ i ] ) );
  3595. }
  3596. }
  3597. } else {
  3598. // texture
  3599. url = serializeImage( data );
  3600. }
  3601. output.url = url;
  3602. }
  3603. if ( ! isRootObject ) {
  3604. meta.images[ this.uuid ] = output;
  3605. }
  3606. return output;
  3607. }
  3608. }
  3609. function serializeImage( image ) {
  3610. if ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) ||
  3611. ( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) ||
  3612. ( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) ) {
  3613. // default images
  3614. return ImageUtils.getDataURL( image );
  3615. } else {
  3616. if ( image.data ) {
  3617. // images of DataTexture
  3618. return {
  3619. data: Array.from( image.data ),
  3620. width: image.width,
  3621. height: image.height,
  3622. type: image.data.constructor.name
  3623. };
  3624. } else {
  3625. console.warn( 'THREE.Texture: Unable to serialize Texture.' );
  3626. return {};
  3627. }
  3628. }
  3629. }
  3630. let _textureId = 0;
  3631. /**
  3632. * Base class for all textures.
  3633. *
  3634. * Note: After the initial use of a texture, its dimensions, format, and type
  3635. * cannot be changed. Instead, call {@link Texture#dispose} on the texture and instantiate a new one.
  3636. *
  3637. * @augments EventDispatcher
  3638. */
  3639. class Texture extends EventDispatcher {
  3640. /**
  3641. * Constructs a new texture.
  3642. *
  3643. * @param {?Object} [image=Texture.DEFAULT_IMAGE] - The image holding the texture data.
  3644. * @param {number} [mapping=Texture.DEFAULT_MAPPING] - The texture mapping.
  3645. * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value.
  3646. * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value.
  3647. * @param {number} [magFilter=LinearFilter] - The mag filter value.
  3648. * @param {number} [minFilter=LinearMipmapLinearFilter] - The min filter value.
  3649. * @param {number} [format=RGBAFormat] - The texture format.
  3650. * @param {number} [type=UnsignedByteType] - The texture type.
  3651. * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value.
  3652. * @param {string} [colorSpace=NoColorSpace] - The color space.
  3653. */
  3654. 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 ) {
  3655. super();
  3656. /**
  3657. * This flag can be used for type testing.
  3658. *
  3659. * @type {boolean}
  3660. * @readonly
  3661. * @default true
  3662. */
  3663. this.isTexture = true;
  3664. /**
  3665. * The ID of the texture.
  3666. *
  3667. * @name Texture#id
  3668. * @type {number}
  3669. * @readonly
  3670. */
  3671. Object.defineProperty( this, 'id', { value: _textureId ++ } );
  3672. /**
  3673. * The UUID of the material.
  3674. *
  3675. * @type {string}
  3676. * @readonly
  3677. */
  3678. this.uuid = generateUUID();
  3679. /**
  3680. * The name of the material.
  3681. *
  3682. * @type {string}
  3683. */
  3684. this.name = '';
  3685. /**
  3686. * The data definition of a texture. A reference to the data source can be
  3687. * shared across textures. This is often useful in context of spritesheets
  3688. * where multiple textures render the same data but with different texture
  3689. * transformations.
  3690. *
  3691. * @type {Source}
  3692. */
  3693. this.source = new Source( image );
  3694. /**
  3695. * An array holding user-defined mipmaps.
  3696. *
  3697. * @type {Array<Object>}
  3698. */
  3699. this.mipmaps = [];
  3700. /**
  3701. * How the texture is applied to the object. The value `UVMapping`
  3702. * is the default, where texture or uv coordinates are used to apply the map.
  3703. *
  3704. * @type {(UVMapping|CubeReflectionMapping|CubeRefractionMapping|EquirectangularReflectionMapping|EquirectangularRefractionMapping|CubeUVReflectionMapping)}
  3705. * @default UVMapping
  3706. */
  3707. this.mapping = mapping;
  3708. /**
  3709. * Lets you select the uv attribute to map the texture to. `0` for `uv`,
  3710. * `1` for `uv1`, `2` for `uv2` and `3` for `uv3`.
  3711. *
  3712. * @type {number}
  3713. * @default 0
  3714. */
  3715. this.channel = 0;
  3716. /**
  3717. * This defines how the texture is wrapped horizontally and corresponds to
  3718. * *U* in UV mapping.
  3719. *
  3720. * @type {(RepeatWrapping|ClampToEdgeWrapping|MirroredRepeatWrapping)}
  3721. * @default ClampToEdgeWrapping
  3722. */
  3723. this.wrapS = wrapS;
  3724. /**
  3725. * This defines how the texture is wrapped horizontally and corresponds to
  3726. * *V* in UV mapping.
  3727. *
  3728. * @type {(RepeatWrapping|ClampToEdgeWrapping|MirroredRepeatWrapping)}
  3729. * @default ClampToEdgeWrapping
  3730. */
  3731. this.wrapT = wrapT;
  3732. /**
  3733. * How the texture is sampled when a texel covers more than one pixel.
  3734. *
  3735. * @type {(NearestFilter|NearestMipmapNearestFilter|NearestMipmapLinearFilter|LinearFilter|LinearMipmapNearestFilter|LinearMipmapLinearFilter)}
  3736. * @default LinearFilter
  3737. */
  3738. this.magFilter = magFilter;
  3739. /**
  3740. * How the texture is sampled when a texel covers less than one pixel.
  3741. *
  3742. * @type {(NearestFilter|NearestMipmapNearestFilter|NearestMipmapLinearFilter|LinearFilter|LinearMipmapNearestFilter|LinearMipmapLinearFilter)}
  3743. * @default LinearMipmapLinearFilter
  3744. */
  3745. this.minFilter = minFilter;
  3746. /**
  3747. * The number of samples taken along the axis through the pixel that has the
  3748. * highest density of texels. By default, this value is `1`. A higher value
  3749. * gives a less blurry result than a basic mipmap, at the cost of more
  3750. * texture samples being used.
  3751. *
  3752. * @type {number}
  3753. * @default 0
  3754. */
  3755. this.anisotropy = anisotropy;
  3756. /**
  3757. * The format of the texture.
  3758. *
  3759. * @type {number}
  3760. * @default RGBAFormat
  3761. */
  3762. this.format = format;
  3763. /**
  3764. * The default internal format is derived from {@link Texture#format} and {@link Texture#type} and
  3765. * defines how the texture data is going to be stored on the GPU.
  3766. *
  3767. * This property allows to overwrite the default format.
  3768. *
  3769. * @type {?string}
  3770. * @default null
  3771. */
  3772. this.internalFormat = null;
  3773. /**
  3774. * The data type of the texture.
  3775. *
  3776. * @type {number}
  3777. * @default UnsignedByteType
  3778. */
  3779. this.type = type;
  3780. /**
  3781. * How much a single repetition of the texture is offset from the beginning,
  3782. * in each direction U and V. Typical range is `0.0` to `1.0`.
  3783. *
  3784. * @type {Vector2}
  3785. * @default (0,0)
  3786. */
  3787. this.offset = new Vector2( 0, 0 );
  3788. /**
  3789. * How many times the texture is repeated across the surface, in each
  3790. * direction U and V. If repeat is set greater than `1` in either direction,
  3791. * the corresponding wrap parameter should also be set to `RepeatWrapping`
  3792. * or `MirroredRepeatWrapping` to achieve the desired tiling effect.
  3793. *
  3794. * @type {Vector2}
  3795. * @default (1,1)
  3796. */
  3797. this.repeat = new Vector2( 1, 1 );
  3798. /**
  3799. * The point around which rotation occurs. A value of `(0.5, 0.5)` corresponds
  3800. * to the center of the texture. Default is `(0, 0)`, the lower left.
  3801. *
  3802. * @type {Vector2}
  3803. * @default (0,0)
  3804. */
  3805. this.center = new Vector2( 0, 0 );
  3806. /**
  3807. * How much the texture is rotated around the center point, in radians.
  3808. * Positive values are counter-clockwise.
  3809. *
  3810. * @type {number}
  3811. * @default 0
  3812. */
  3813. this.rotation = 0;
  3814. /**
  3815. * Whether to update the texture's uv-transformation {@link Texture#matrix}
  3816. * from the properties {@link Texture#offset}, {@link Texture#repeat},
  3817. * {@link Texture#rotation}, and {@link Texture#center}.
  3818. *
  3819. * Set this to `false` if you are specifying the uv-transform matrix directly.
  3820. *
  3821. * @type {boolean}
  3822. * @default true
  3823. */
  3824. this.matrixAutoUpdate = true;
  3825. /**
  3826. * The uv-transformation matrix of the texture.
  3827. *
  3828. * @type {Matrix3}
  3829. */
  3830. this.matrix = new Matrix3();
  3831. /**
  3832. * Whether to generate mipmaps (if possible) for a texture.
  3833. *
  3834. * Set this to `false` if you are creating mipmaps manually.
  3835. *
  3836. * @type {boolean}
  3837. * @default true
  3838. */
  3839. this.generateMipmaps = true;
  3840. /**
  3841. * If set to `true`, the alpha channel, if present, is multiplied into the
  3842. * color channels when the texture is uploaded to the GPU.
  3843. *
  3844. * Note that this property has no effect when using `ImageBitmap`. You need to
  3845. * configure premultiply alpha on bitmap creation instead.
  3846. *
  3847. * @type {boolean}
  3848. * @default false
  3849. */
  3850. this.premultiplyAlpha = false;
  3851. /**
  3852. * If set to `true`, the texture is flipped along the vertical axis when
  3853. * uploaded to the GPU.
  3854. *
  3855. * Note that this property has no effect when using `ImageBitmap`. You need to
  3856. * configure the flip on bitmap creation instead.
  3857. *
  3858. * @type {boolean}
  3859. * @default true
  3860. */
  3861. this.flipY = true;
  3862. /**
  3863. * Specifies the alignment requirements for the start of each pixel row in memory.
  3864. * The allowable values are `1` (byte-alignment), `2` (rows aligned to even-numbered bytes),
  3865. * `4` (word-alignment), and `8` (rows start on double-word boundaries).
  3866. *
  3867. * @type {number}
  3868. * @default 4
  3869. */
  3870. this.unpackAlignment = 4; // valid values: 1, 2, 4, 8 (see http://www.khronos.org/opengles/sdk/docs/man/xhtml/glPixelStorei.xml)
  3871. /**
  3872. * Textures containing color data should be annotated with `SRGBColorSpace` or `LinearSRGBColorSpace`.
  3873. *
  3874. * @type {string}
  3875. * @default NoColorSpace
  3876. */
  3877. this.colorSpace = colorSpace;
  3878. /**
  3879. * An object that can be used to store custom data about the texture. It
  3880. * should not hold references to functions as these will not be cloned.
  3881. *
  3882. * @type {Object}
  3883. */
  3884. this.userData = {};
  3885. /**
  3886. * This starts at `0` and counts how many times {@link Texture#needsUpdate} is set to `true`.
  3887. *
  3888. * @type {number}
  3889. * @readonly
  3890. * @default 0
  3891. */
  3892. this.version = 0;
  3893. /**
  3894. * A callback function, called when the texture is updated (e.g., when
  3895. * {@link Texture#needsUpdate} has been set to true and then the texture is used).
  3896. *
  3897. * @type {?Function}
  3898. * @default null
  3899. */
  3900. this.onUpdate = null;
  3901. /**
  3902. * An optional back reference to the textures render target.
  3903. *
  3904. * @type {?(RenderTarget|WebGLRenderTarget)}
  3905. * @default null
  3906. */
  3907. this.renderTarget = null;
  3908. /**
  3909. * Indicates whether a texture belongs to a render target or not.
  3910. *
  3911. * @type {boolean}
  3912. * @readonly
  3913. * @default false
  3914. */
  3915. this.isRenderTargetTexture = false;
  3916. /**
  3917. * Indicates whether this texture should be processed by `PMREMGenerator` or not
  3918. * (only relevant for render target textures).
  3919. *
  3920. * @type {number}
  3921. * @readonly
  3922. * @default 0
  3923. */
  3924. this.pmremVersion = 0;
  3925. }
  3926. /**
  3927. * The image object holding the texture data.
  3928. *
  3929. * @type {?Object}
  3930. */
  3931. get image() {
  3932. return this.source.data;
  3933. }
  3934. set image( value = null ) {
  3935. this.source.data = value;
  3936. }
  3937. /**
  3938. * Updates the texture transformation matrix from the from the properties {@link Texture#offset},
  3939. * {@link Texture#repeat}, {@link Texture#rotation}, and {@link Texture#center}.
  3940. */
  3941. updateMatrix() {
  3942. this.matrix.setUvTransform( this.offset.x, this.offset.y, this.repeat.x, this.repeat.y, this.rotation, this.center.x, this.center.y );
  3943. }
  3944. /**
  3945. * Returns a new texture with copied values from this instance.
  3946. *
  3947. * @return {Texture} A clone of this instance.
  3948. */
  3949. clone() {
  3950. return new this.constructor().copy( this );
  3951. }
  3952. /**
  3953. * Copies the values of the given texture to this instance.
  3954. *
  3955. * @param {Texture} source - The texture to copy.
  3956. * @return {Texture} A reference to this instance.
  3957. */
  3958. copy( source ) {
  3959. this.name = source.name;
  3960. this.source = source.source;
  3961. this.mipmaps = source.mipmaps.slice( 0 );
  3962. this.mapping = source.mapping;
  3963. this.channel = source.channel;
  3964. this.wrapS = source.wrapS;
  3965. this.wrapT = source.wrapT;
  3966. this.magFilter = source.magFilter;
  3967. this.minFilter = source.minFilter;
  3968. this.anisotropy = source.anisotropy;
  3969. this.format = source.format;
  3970. this.internalFormat = source.internalFormat;
  3971. this.type = source.type;
  3972. this.offset.copy( source.offset );
  3973. this.repeat.copy( source.repeat );
  3974. this.center.copy( source.center );
  3975. this.rotation = source.rotation;
  3976. this.matrixAutoUpdate = source.matrixAutoUpdate;
  3977. this.matrix.copy( source.matrix );
  3978. this.generateMipmaps = source.generateMipmaps;
  3979. this.premultiplyAlpha = source.premultiplyAlpha;
  3980. this.flipY = source.flipY;
  3981. this.unpackAlignment = source.unpackAlignment;
  3982. this.colorSpace = source.colorSpace;
  3983. this.renderTarget = source.renderTarget;
  3984. this.isRenderTargetTexture = source.isRenderTargetTexture;
  3985. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  3986. this.needsUpdate = true;
  3987. return this;
  3988. }
  3989. /**
  3990. * Serializes the texture into JSON.
  3991. *
  3992. * @param {?(Object|string)} meta - An optional value holding meta information about the serialization.
  3993. * @return {Object} A JSON object representing the serialized texture.
  3994. * @see {@link ObjectLoader#parse}
  3995. */
  3996. toJSON( meta ) {
  3997. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  3998. if ( ! isRootObject && meta.textures[ this.uuid ] !== undefined ) {
  3999. return meta.textures[ this.uuid ];
  4000. }
  4001. const output = {
  4002. metadata: {
  4003. version: 4.6,
  4004. type: 'Texture',
  4005. generator: 'Texture.toJSON'
  4006. },
  4007. uuid: this.uuid,
  4008. name: this.name,
  4009. image: this.source.toJSON( meta ).uuid,
  4010. mapping: this.mapping,
  4011. channel: this.channel,
  4012. repeat: [ this.repeat.x, this.repeat.y ],
  4013. offset: [ this.offset.x, this.offset.y ],
  4014. center: [ this.center.x, this.center.y ],
  4015. rotation: this.rotation,
  4016. wrap: [ this.wrapS, this.wrapT ],
  4017. format: this.format,
  4018. internalFormat: this.internalFormat,
  4019. type: this.type,
  4020. colorSpace: this.colorSpace,
  4021. minFilter: this.minFilter,
  4022. magFilter: this.magFilter,
  4023. anisotropy: this.anisotropy,
  4024. flipY: this.flipY,
  4025. generateMipmaps: this.generateMipmaps,
  4026. premultiplyAlpha: this.premultiplyAlpha,
  4027. unpackAlignment: this.unpackAlignment
  4028. };
  4029. if ( Object.keys( this.userData ).length > 0 ) output.userData = this.userData;
  4030. if ( ! isRootObject ) {
  4031. meta.textures[ this.uuid ] = output;
  4032. }
  4033. return output;
  4034. }
  4035. /**
  4036. * Frees the GPU-related resources allocated by this instance. Call this
  4037. * method whenever this instance is no longer used in your app.
  4038. *
  4039. * @fires Texture#dispose
  4040. */
  4041. dispose() {
  4042. /**
  4043. * Fires when the texture has been disposed of.
  4044. *
  4045. * @event Texture#dispose
  4046. * @type {Object}
  4047. */
  4048. this.dispatchEvent( { type: 'dispose' } );
  4049. }
  4050. /**
  4051. * Transforms the given uv vector with the textures uv transformation matrix.
  4052. *
  4053. * @param {Vector2} uv - The uv vector.
  4054. * @return {Vector2} The transformed uv vector.
  4055. */
  4056. transformUv( uv ) {
  4057. if ( this.mapping !== UVMapping ) return uv;
  4058. uv.applyMatrix3( this.matrix );
  4059. if ( uv.x < 0 || uv.x > 1 ) {
  4060. switch ( this.wrapS ) {
  4061. case RepeatWrapping:
  4062. uv.x = uv.x - Math.floor( uv.x );
  4063. break;
  4064. case ClampToEdgeWrapping:
  4065. uv.x = uv.x < 0 ? 0 : 1;
  4066. break;
  4067. case MirroredRepeatWrapping:
  4068. if ( Math.abs( Math.floor( uv.x ) % 2 ) === 1 ) {
  4069. uv.x = Math.ceil( uv.x ) - uv.x;
  4070. } else {
  4071. uv.x = uv.x - Math.floor( uv.x );
  4072. }
  4073. break;
  4074. }
  4075. }
  4076. if ( uv.y < 0 || uv.y > 1 ) {
  4077. switch ( this.wrapT ) {
  4078. case RepeatWrapping:
  4079. uv.y = uv.y - Math.floor( uv.y );
  4080. break;
  4081. case ClampToEdgeWrapping:
  4082. uv.y = uv.y < 0 ? 0 : 1;
  4083. break;
  4084. case MirroredRepeatWrapping:
  4085. if ( Math.abs( Math.floor( uv.y ) % 2 ) === 1 ) {
  4086. uv.y = Math.ceil( uv.y ) - uv.y;
  4087. } else {
  4088. uv.y = uv.y - Math.floor( uv.y );
  4089. }
  4090. break;
  4091. }
  4092. }
  4093. if ( this.flipY ) {
  4094. uv.y = 1 - uv.y;
  4095. }
  4096. return uv;
  4097. }
  4098. /**
  4099. * Setting this property to `true` indicates the engine the texture
  4100. * must be updated in the next render. This triggers a texture upload
  4101. * to the GPU and ensures correct texture parameter configuration.
  4102. *
  4103. * @type {boolean}
  4104. * @default false
  4105. * @param {boolean} value
  4106. */
  4107. set needsUpdate( value ) {
  4108. if ( value === true ) {
  4109. this.version ++;
  4110. this.source.needsUpdate = true;
  4111. }
  4112. }
  4113. /**
  4114. * Setting this property to `true` indicates the engine the PMREM
  4115. * must be regenerated.
  4116. *
  4117. * @type {boolean}
  4118. * @default false
  4119. * @param {boolean} value
  4120. */
  4121. set needsPMREMUpdate( value ) {
  4122. if ( value === true ) {
  4123. this.pmremVersion ++;
  4124. }
  4125. }
  4126. }
  4127. /**
  4128. * The default image for all textures.
  4129. *
  4130. * @static
  4131. * @type {?Image}
  4132. * @default null
  4133. */
  4134. Texture.DEFAULT_IMAGE = null;
  4135. /**
  4136. * The default mapping for all textures.
  4137. *
  4138. * @static
  4139. * @type {number}
  4140. * @default UVMapping
  4141. */
  4142. Texture.DEFAULT_MAPPING = UVMapping;
  4143. /**
  4144. * The default anisotropy value for all textures.
  4145. *
  4146. * @static
  4147. * @type {number}
  4148. * @default 1
  4149. */
  4150. Texture.DEFAULT_ANISOTROPY = 1;
  4151. /**
  4152. * Class representing a 4D vector. A 4D vector is an ordered quadruplet of numbers
  4153. * (labeled x, y, z and w), which can be used to represent a number of things, such as:
  4154. *
  4155. * - A point in 4D space.
  4156. * - A direction and length in 4D space. In three.js the length will
  4157. * always be the Euclidean distance(straight-line distance) from `(0, 0, 0, 0)` to `(x, y, z, w)`
  4158. * and the direction is also measured from `(0, 0, 0, 0)` towards `(x, y, z, w)`.
  4159. * - Any arbitrary ordered quadruplet of numbers.
  4160. *
  4161. * There are other things a 4D vector can be used to represent, however these
  4162. * are the most common uses in *three.js*.
  4163. *
  4164. * Iterating through a vector instance will yield its components `(x, y, z, w)` in
  4165. * the corresponding order.
  4166. * ```js
  4167. * const a = new THREE.Vector4( 0, 1, 0, 0 );
  4168. *
  4169. * //no arguments; will be initialised to (0, 0, 0, 1)
  4170. * const b = new THREE.Vector4( );
  4171. *
  4172. * const d = a.dot( b );
  4173. * ```
  4174. */
  4175. class Vector4 {
  4176. /**
  4177. * Constructs a new 4D vector.
  4178. *
  4179. * @param {number} [x=0] - The x value of this vector.
  4180. * @param {number} [y=0] - The y value of this vector.
  4181. * @param {number} [z=0] - The z value of this vector.
  4182. * @param {number} [w=1] - The w value of this vector.
  4183. */
  4184. constructor( x = 0, y = 0, z = 0, w = 1 ) {
  4185. /**
  4186. * This flag can be used for type testing.
  4187. *
  4188. * @type {boolean}
  4189. * @readonly
  4190. * @default true
  4191. */
  4192. Vector4.prototype.isVector4 = true;
  4193. /**
  4194. * The x value of this vector.
  4195. *
  4196. * @type {number}
  4197. */
  4198. this.x = x;
  4199. /**
  4200. * The y value of this vector.
  4201. *
  4202. * @type {number}
  4203. */
  4204. this.y = y;
  4205. /**
  4206. * The z value of this vector.
  4207. *
  4208. * @type {number}
  4209. */
  4210. this.z = z;
  4211. /**
  4212. * The w value of this vector.
  4213. *
  4214. * @type {number}
  4215. */
  4216. this.w = w;
  4217. }
  4218. /**
  4219. * Alias for {@link Vector4#z}.
  4220. *
  4221. * @type {number}
  4222. */
  4223. get width() {
  4224. return this.z;
  4225. }
  4226. set width( value ) {
  4227. this.z = value;
  4228. }
  4229. /**
  4230. * Alias for {@link Vector4#w}.
  4231. *
  4232. * @type {number}
  4233. */
  4234. get height() {
  4235. return this.w;
  4236. }
  4237. set height( value ) {
  4238. this.w = value;
  4239. }
  4240. /**
  4241. * Sets the vector components.
  4242. *
  4243. * @param {number} x - The value of the x component.
  4244. * @param {number} y - The value of the y component.
  4245. * @param {number} z - The value of the z component.
  4246. * @param {number} w - The value of the w component.
  4247. * @return {Vector4} A reference to this vector.
  4248. */
  4249. set( x, y, z, w ) {
  4250. this.x = x;
  4251. this.y = y;
  4252. this.z = z;
  4253. this.w = w;
  4254. return this;
  4255. }
  4256. /**
  4257. * Sets the vector components to the same value.
  4258. *
  4259. * @param {number} scalar - The value to set for all vector components.
  4260. * @return {Vector4} A reference to this vector.
  4261. */
  4262. setScalar( scalar ) {
  4263. this.x = scalar;
  4264. this.y = scalar;
  4265. this.z = scalar;
  4266. this.w = scalar;
  4267. return this;
  4268. }
  4269. /**
  4270. * Sets the vector's x component to the given value
  4271. *
  4272. * @param {number} x - The value to set.
  4273. * @return {Vector4} A reference to this vector.
  4274. */
  4275. setX( x ) {
  4276. this.x = x;
  4277. return this;
  4278. }
  4279. /**
  4280. * Sets the vector's y component to the given value
  4281. *
  4282. * @param {number} y - The value to set.
  4283. * @return {Vector4} A reference to this vector.
  4284. */
  4285. setY( y ) {
  4286. this.y = y;
  4287. return this;
  4288. }
  4289. /**
  4290. * Sets the vector's z component to the given value
  4291. *
  4292. * @param {number} z - The value to set.
  4293. * @return {Vector4} A reference to this vector.
  4294. */
  4295. setZ( z ) {
  4296. this.z = z;
  4297. return this;
  4298. }
  4299. /**
  4300. * Sets the vector's w component to the given value
  4301. *
  4302. * @param {number} w - The value to set.
  4303. * @return {Vector4} A reference to this vector.
  4304. */
  4305. setW( w ) {
  4306. this.w = w;
  4307. return this;
  4308. }
  4309. /**
  4310. * Allows to set a vector component with an index.
  4311. *
  4312. * @param {number} index - The component index. `0` equals to x, `1` equals to y,
  4313. * `2` equals to z, `3` equals to w.
  4314. * @param {number} value - The value to set.
  4315. * @return {Vector4} A reference to this vector.
  4316. */
  4317. setComponent( index, value ) {
  4318. switch ( index ) {
  4319. case 0: this.x = value; break;
  4320. case 1: this.y = value; break;
  4321. case 2: this.z = value; break;
  4322. case 3: this.w = value; break;
  4323. default: throw new Error( 'index is out of range: ' + index );
  4324. }
  4325. return this;
  4326. }
  4327. /**
  4328. * Returns the value of the vector component which matches the given index.
  4329. *
  4330. * @param {number} index - The component index. `0` equals to x, `1` equals to y,
  4331. * `2` equals to z, `3` equals to w.
  4332. * @return {number} A vector component value.
  4333. */
  4334. getComponent( index ) {
  4335. switch ( index ) {
  4336. case 0: return this.x;
  4337. case 1: return this.y;
  4338. case 2: return this.z;
  4339. case 3: return this.w;
  4340. default: throw new Error( 'index is out of range: ' + index );
  4341. }
  4342. }
  4343. /**
  4344. * Returns a new vector with copied values from this instance.
  4345. *
  4346. * @return {Vector4} A clone of this instance.
  4347. */
  4348. clone() {
  4349. return new this.constructor( this.x, this.y, this.z, this.w );
  4350. }
  4351. /**
  4352. * Copies the values of the given vector to this instance.
  4353. *
  4354. * @param {Vector3|Vector4} v - The vector to copy.
  4355. * @return {Vector4} A reference to this vector.
  4356. */
  4357. copy( v ) {
  4358. this.x = v.x;
  4359. this.y = v.y;
  4360. this.z = v.z;
  4361. this.w = ( v.w !== undefined ) ? v.w : 1;
  4362. return this;
  4363. }
  4364. /**
  4365. * Adds the given vector to this instance.
  4366. *
  4367. * @param {Vector4} v - The vector to add.
  4368. * @return {Vector4} A reference to this vector.
  4369. */
  4370. add( v ) {
  4371. this.x += v.x;
  4372. this.y += v.y;
  4373. this.z += v.z;
  4374. this.w += v.w;
  4375. return this;
  4376. }
  4377. /**
  4378. * Adds the given scalar value to all components of this instance.
  4379. *
  4380. * @param {number} s - The scalar to add.
  4381. * @return {Vector4} A reference to this vector.
  4382. */
  4383. addScalar( s ) {
  4384. this.x += s;
  4385. this.y += s;
  4386. this.z += s;
  4387. this.w += s;
  4388. return this;
  4389. }
  4390. /**
  4391. * Adds the given vectors and stores the result in this instance.
  4392. *
  4393. * @param {Vector4} a - The first vector.
  4394. * @param {Vector4} b - The second vector.
  4395. * @return {Vector4} A reference to this vector.
  4396. */
  4397. addVectors( a, b ) {
  4398. this.x = a.x + b.x;
  4399. this.y = a.y + b.y;
  4400. this.z = a.z + b.z;
  4401. this.w = a.w + b.w;
  4402. return this;
  4403. }
  4404. /**
  4405. * Adds the given vector scaled by the given factor to this instance.
  4406. *
  4407. * @param {Vector4} v - The vector.
  4408. * @param {number} s - The factor that scales `v`.
  4409. * @return {Vector4} A reference to this vector.
  4410. */
  4411. addScaledVector( v, s ) {
  4412. this.x += v.x * s;
  4413. this.y += v.y * s;
  4414. this.z += v.z * s;
  4415. this.w += v.w * s;
  4416. return this;
  4417. }
  4418. /**
  4419. * Subtracts the given vector from this instance.
  4420. *
  4421. * @param {Vector4} v - The vector to subtract.
  4422. * @return {Vector4} A reference to this vector.
  4423. */
  4424. sub( v ) {
  4425. this.x -= v.x;
  4426. this.y -= v.y;
  4427. this.z -= v.z;
  4428. this.w -= v.w;
  4429. return this;
  4430. }
  4431. /**
  4432. * Subtracts the given scalar value from all components of this instance.
  4433. *
  4434. * @param {number} s - The scalar to subtract.
  4435. * @return {Vector4} A reference to this vector.
  4436. */
  4437. subScalar( s ) {
  4438. this.x -= s;
  4439. this.y -= s;
  4440. this.z -= s;
  4441. this.w -= s;
  4442. return this;
  4443. }
  4444. /**
  4445. * Subtracts the given vectors and stores the result in this instance.
  4446. *
  4447. * @param {Vector4} a - The first vector.
  4448. * @param {Vector4} b - The second vector.
  4449. * @return {Vector4} A reference to this vector.
  4450. */
  4451. subVectors( a, b ) {
  4452. this.x = a.x - b.x;
  4453. this.y = a.y - b.y;
  4454. this.z = a.z - b.z;
  4455. this.w = a.w - b.w;
  4456. return this;
  4457. }
  4458. /**
  4459. * Multiplies the given vector with this instance.
  4460. *
  4461. * @param {Vector4} v - The vector to multiply.
  4462. * @return {Vector4} A reference to this vector.
  4463. */
  4464. multiply( v ) {
  4465. this.x *= v.x;
  4466. this.y *= v.y;
  4467. this.z *= v.z;
  4468. this.w *= v.w;
  4469. return this;
  4470. }
  4471. /**
  4472. * Multiplies the given scalar value with all components of this instance.
  4473. *
  4474. * @param {number} scalar - The scalar to multiply.
  4475. * @return {Vector4} A reference to this vector.
  4476. */
  4477. multiplyScalar( scalar ) {
  4478. this.x *= scalar;
  4479. this.y *= scalar;
  4480. this.z *= scalar;
  4481. this.w *= scalar;
  4482. return this;
  4483. }
  4484. /**
  4485. * Multiplies this vector with the given 4x4 matrix.
  4486. *
  4487. * @param {Matrix4} m - The 4x4 matrix.
  4488. * @return {Vector4} A reference to this vector.
  4489. */
  4490. applyMatrix4( m ) {
  4491. const x = this.x, y = this.y, z = this.z, w = this.w;
  4492. const e = m.elements;
  4493. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] * w;
  4494. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] * w;
  4495. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] * w;
  4496. this.w = e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] * w;
  4497. return this;
  4498. }
  4499. /**
  4500. * Divides this instance by the given vector.
  4501. *
  4502. * @param {Vector4} v - The vector to divide.
  4503. * @return {Vector4} A reference to this vector.
  4504. */
  4505. divide( v ) {
  4506. this.x /= v.x;
  4507. this.y /= v.y;
  4508. this.z /= v.z;
  4509. this.w /= v.w;
  4510. return this;
  4511. }
  4512. /**
  4513. * Divides this vector by the given scalar.
  4514. *
  4515. * @param {number} scalar - The scalar to divide.
  4516. * @return {Vector4} A reference to this vector.
  4517. */
  4518. divideScalar( scalar ) {
  4519. return this.multiplyScalar( 1 / scalar );
  4520. }
  4521. /**
  4522. * Sets the x, y and z components of this
  4523. * vector to the quaternion's axis and w to the angle.
  4524. *
  4525. * @param {Quaternion} q - The Quaternion to set.
  4526. * @return {Vector4} A reference to this vector.
  4527. */
  4528. setAxisAngleFromQuaternion( q ) {
  4529. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToAngle/index.htm
  4530. // q is assumed to be normalized
  4531. this.w = 2 * Math.acos( q.w );
  4532. const s = Math.sqrt( 1 - q.w * q.w );
  4533. if ( s < 0.0001 ) {
  4534. this.x = 1;
  4535. this.y = 0;
  4536. this.z = 0;
  4537. } else {
  4538. this.x = q.x / s;
  4539. this.y = q.y / s;
  4540. this.z = q.z / s;
  4541. }
  4542. return this;
  4543. }
  4544. /**
  4545. * Sets the x, y and z components of this
  4546. * vector to the axis of rotation and w to the angle.
  4547. *
  4548. * @param {Matrix4} m - A 4x4 matrix of which the upper left 3x3 matrix is a pure rotation matrix.
  4549. * @return {Vector4} A reference to this vector.
  4550. */
  4551. setAxisAngleFromRotationMatrix( m ) {
  4552. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToAngle/index.htm
  4553. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  4554. let angle, x, y, z; // variables for result
  4555. const epsilon = 0.01, // margin to allow for rounding errors
  4556. epsilon2 = 0.1, // margin to distinguish between 0 and 180 degrees
  4557. te = m.elements,
  4558. m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ],
  4559. m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ],
  4560. m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];
  4561. if ( ( Math.abs( m12 - m21 ) < epsilon ) &&
  4562. ( Math.abs( m13 - m31 ) < epsilon ) &&
  4563. ( Math.abs( m23 - m32 ) < epsilon ) ) {
  4564. // singularity found
  4565. // first check for identity matrix which must have +1 for all terms
  4566. // in leading diagonal and zero in other terms
  4567. if ( ( Math.abs( m12 + m21 ) < epsilon2 ) &&
  4568. ( Math.abs( m13 + m31 ) < epsilon2 ) &&
  4569. ( Math.abs( m23 + m32 ) < epsilon2 ) &&
  4570. ( Math.abs( m11 + m22 + m33 - 3 ) < epsilon2 ) ) {
  4571. // this singularity is identity matrix so angle = 0
  4572. this.set( 1, 0, 0, 0 );
  4573. return this; // zero angle, arbitrary axis
  4574. }
  4575. // otherwise this singularity is angle = 180
  4576. angle = Math.PI;
  4577. const xx = ( m11 + 1 ) / 2;
  4578. const yy = ( m22 + 1 ) / 2;
  4579. const zz = ( m33 + 1 ) / 2;
  4580. const xy = ( m12 + m21 ) / 4;
  4581. const xz = ( m13 + m31 ) / 4;
  4582. const yz = ( m23 + m32 ) / 4;
  4583. if ( ( xx > yy ) && ( xx > zz ) ) {
  4584. // m11 is the largest diagonal term
  4585. if ( xx < epsilon ) {
  4586. x = 0;
  4587. y = 0.707106781;
  4588. z = 0.707106781;
  4589. } else {
  4590. x = Math.sqrt( xx );
  4591. y = xy / x;
  4592. z = xz / x;
  4593. }
  4594. } else if ( yy > zz ) {
  4595. // m22 is the largest diagonal term
  4596. if ( yy < epsilon ) {
  4597. x = 0.707106781;
  4598. y = 0;
  4599. z = 0.707106781;
  4600. } else {
  4601. y = Math.sqrt( yy );
  4602. x = xy / y;
  4603. z = yz / y;
  4604. }
  4605. } else {
  4606. // m33 is the largest diagonal term so base result on this
  4607. if ( zz < epsilon ) {
  4608. x = 0.707106781;
  4609. y = 0.707106781;
  4610. z = 0;
  4611. } else {
  4612. z = Math.sqrt( zz );
  4613. x = xz / z;
  4614. y = yz / z;
  4615. }
  4616. }
  4617. this.set( x, y, z, angle );
  4618. return this; // return 180 deg rotation
  4619. }
  4620. // as we have reached here there are no singularities so we can handle normally
  4621. let s = Math.sqrt( ( m32 - m23 ) * ( m32 - m23 ) +
  4622. ( m13 - m31 ) * ( m13 - m31 ) +
  4623. ( m21 - m12 ) * ( m21 - m12 ) ); // used to normalize
  4624. if ( Math.abs( s ) < 0.001 ) s = 1;
  4625. // prevent divide by zero, should not happen if matrix is orthogonal and should be
  4626. // caught by singularity test above, but I've left it in just in case
  4627. this.x = ( m32 - m23 ) / s;
  4628. this.y = ( m13 - m31 ) / s;
  4629. this.z = ( m21 - m12 ) / s;
  4630. this.w = Math.acos( ( m11 + m22 + m33 - 1 ) / 2 );
  4631. return this;
  4632. }
  4633. /**
  4634. * Sets the vector components to the position elements of the
  4635. * given transformation matrix.
  4636. *
  4637. * @param {Matrix4} m - The 4x4 matrix.
  4638. * @return {Vector4} A reference to this vector.
  4639. */
  4640. setFromMatrixPosition( m ) {
  4641. const e = m.elements;
  4642. this.x = e[ 12 ];
  4643. this.y = e[ 13 ];
  4644. this.z = e[ 14 ];
  4645. this.w = e[ 15 ];
  4646. return this;
  4647. }
  4648. /**
  4649. * If this vector's x, y, z or w value is greater than the given vector's x, y, z or w
  4650. * value, replace that value with the corresponding min value.
  4651. *
  4652. * @param {Vector4} v - The vector.
  4653. * @return {Vector4} A reference to this vector.
  4654. */
  4655. min( v ) {
  4656. this.x = Math.min( this.x, v.x );
  4657. this.y = Math.min( this.y, v.y );
  4658. this.z = Math.min( this.z, v.z );
  4659. this.w = Math.min( this.w, v.w );
  4660. return this;
  4661. }
  4662. /**
  4663. * If this vector's x, y, z or w value is less than the given vector's x, y, z or w
  4664. * value, replace that value with the corresponding max value.
  4665. *
  4666. * @param {Vector4} v - The vector.
  4667. * @return {Vector4} A reference to this vector.
  4668. */
  4669. max( v ) {
  4670. this.x = Math.max( this.x, v.x );
  4671. this.y = Math.max( this.y, v.y );
  4672. this.z = Math.max( this.z, v.z );
  4673. this.w = Math.max( this.w, v.w );
  4674. return this;
  4675. }
  4676. /**
  4677. * If this vector's x, y, z or w value is greater than the max vector's x, y, z or w
  4678. * value, it is replaced by the corresponding value.
  4679. * If this vector's x, y, z or w value is less than the min vector's x, y, z or w value,
  4680. * it is replaced by the corresponding value.
  4681. *
  4682. * @param {Vector4} min - The minimum x, y and z values.
  4683. * @param {Vector4} max - The maximum x, y and z values in the desired range.
  4684. * @return {Vector4} A reference to this vector.
  4685. */
  4686. clamp( min, max ) {
  4687. // assumes min < max, componentwise
  4688. this.x = clamp( this.x, min.x, max.x );
  4689. this.y = clamp( this.y, min.y, max.y );
  4690. this.z = clamp( this.z, min.z, max.z );
  4691. this.w = clamp( this.w, min.w, max.w );
  4692. return this;
  4693. }
  4694. /**
  4695. * If this vector's x, y, z or w values are greater than the max value, they are
  4696. * replaced by the max value.
  4697. * If this vector's x, y, z or w values are less than the min value, they are
  4698. * replaced by the min value.
  4699. *
  4700. * @param {number} minVal - The minimum value the components will be clamped to.
  4701. * @param {number} maxVal - The maximum value the components will be clamped to.
  4702. * @return {Vector4} A reference to this vector.
  4703. */
  4704. clampScalar( minVal, maxVal ) {
  4705. this.x = clamp( this.x, minVal, maxVal );
  4706. this.y = clamp( this.y, minVal, maxVal );
  4707. this.z = clamp( this.z, minVal, maxVal );
  4708. this.w = clamp( this.w, minVal, maxVal );
  4709. return this;
  4710. }
  4711. /**
  4712. * If this vector's length is greater than the max value, it is replaced by
  4713. * the max value.
  4714. * If this vector's length is less than the min value, it is replaced by the
  4715. * min value.
  4716. *
  4717. * @param {number} min - The minimum value the vector length will be clamped to.
  4718. * @param {number} max - The maximum value the vector length will be clamped to.
  4719. * @return {Vector4} A reference to this vector.
  4720. */
  4721. clampLength( min, max ) {
  4722. const length = this.length();
  4723. return this.divideScalar( length || 1 ).multiplyScalar( clamp( length, min, max ) );
  4724. }
  4725. /**
  4726. * The components of this vector are rounded down to the nearest integer value.
  4727. *
  4728. * @return {Vector4} A reference to this vector.
  4729. */
  4730. floor() {
  4731. this.x = Math.floor( this.x );
  4732. this.y = Math.floor( this.y );
  4733. this.z = Math.floor( this.z );
  4734. this.w = Math.floor( this.w );
  4735. return this;
  4736. }
  4737. /**
  4738. * The components of this vector are rounded up to the nearest integer value.
  4739. *
  4740. * @return {Vector4} A reference to this vector.
  4741. */
  4742. ceil() {
  4743. this.x = Math.ceil( this.x );
  4744. this.y = Math.ceil( this.y );
  4745. this.z = Math.ceil( this.z );
  4746. this.w = Math.ceil( this.w );
  4747. return this;
  4748. }
  4749. /**
  4750. * The components of this vector are rounded to the nearest integer value
  4751. *
  4752. * @return {Vector4} A reference to this vector.
  4753. */
  4754. round() {
  4755. this.x = Math.round( this.x );
  4756. this.y = Math.round( this.y );
  4757. this.z = Math.round( this.z );
  4758. this.w = Math.round( this.w );
  4759. return this;
  4760. }
  4761. /**
  4762. * The components of this vector are rounded towards zero (up if negative,
  4763. * down if positive) to an integer value.
  4764. *
  4765. * @return {Vector4} A reference to this vector.
  4766. */
  4767. roundToZero() {
  4768. this.x = Math.trunc( this.x );
  4769. this.y = Math.trunc( this.y );
  4770. this.z = Math.trunc( this.z );
  4771. this.w = Math.trunc( this.w );
  4772. return this;
  4773. }
  4774. /**
  4775. * Inverts this vector - i.e. sets x = -x, y = -y, z = -z, w = -w.
  4776. *
  4777. * @return {Vector4} A reference to this vector.
  4778. */
  4779. negate() {
  4780. this.x = - this.x;
  4781. this.y = - this.y;
  4782. this.z = - this.z;
  4783. this.w = - this.w;
  4784. return this;
  4785. }
  4786. /**
  4787. * Calculates the dot product of the given vector with this instance.
  4788. *
  4789. * @param {Vector4} v - The vector to compute the dot product with.
  4790. * @return {number} The result of the dot product.
  4791. */
  4792. dot( v ) {
  4793. return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w;
  4794. }
  4795. /**
  4796. * Computes the square of the Euclidean length (straight-line length) from
  4797. * (0, 0, 0, 0) to (x, y, z, w). If you are comparing the lengths of vectors, you should
  4798. * compare the length squared instead as it is slightly more efficient to calculate.
  4799. *
  4800. * @return {number} The square length of this vector.
  4801. */
  4802. lengthSq() {
  4803. return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w;
  4804. }
  4805. /**
  4806. * Computes the Euclidean length (straight-line length) from (0, 0, 0, 0) to (x, y, z, w).
  4807. *
  4808. * @return {number} The length of this vector.
  4809. */
  4810. length() {
  4811. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w );
  4812. }
  4813. /**
  4814. * Computes the Manhattan length of this vector.
  4815. *
  4816. * @return {number} The length of this vector.
  4817. */
  4818. manhattanLength() {
  4819. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z ) + Math.abs( this.w );
  4820. }
  4821. /**
  4822. * Converts this vector to a unit vector - that is, sets it equal to a vector
  4823. * with the same direction as this one, but with a vector length of `1`.
  4824. *
  4825. * @return {Vector4} A reference to this vector.
  4826. */
  4827. normalize() {
  4828. return this.divideScalar( this.length() || 1 );
  4829. }
  4830. /**
  4831. * Sets this vector to a vector with the same direction as this one, but
  4832. * with the specified length.
  4833. *
  4834. * @param {number} length - The new length of this vector.
  4835. * @return {Vector4} A reference to this vector.
  4836. */
  4837. setLength( length ) {
  4838. return this.normalize().multiplyScalar( length );
  4839. }
  4840. /**
  4841. * Linearly interpolates between the given vector and this instance, where
  4842. * alpha is the percent distance along the line - alpha = 0 will be this
  4843. * vector, and alpha = 1 will be the given one.
  4844. *
  4845. * @param {Vector4} v - The vector to interpolate towards.
  4846. * @param {number} alpha - The interpolation factor, typically in the closed interval `[0, 1]`.
  4847. * @return {Vector4} A reference to this vector.
  4848. */
  4849. lerp( v, alpha ) {
  4850. this.x += ( v.x - this.x ) * alpha;
  4851. this.y += ( v.y - this.y ) * alpha;
  4852. this.z += ( v.z - this.z ) * alpha;
  4853. this.w += ( v.w - this.w ) * alpha;
  4854. return this;
  4855. }
  4856. /**
  4857. * Linearly interpolates between the given vectors, where alpha is the percent
  4858. * distance along the line - alpha = 0 will be first vector, and alpha = 1 will
  4859. * be the second one. The result is stored in this instance.
  4860. *
  4861. * @param {Vector4} v1 - The first vector.
  4862. * @param {Vector4} v2 - The second vector.
  4863. * @param {number} alpha - The interpolation factor, typically in the closed interval `[0, 1]`.
  4864. * @return {Vector4} A reference to this vector.
  4865. */
  4866. lerpVectors( v1, v2, alpha ) {
  4867. this.x = v1.x + ( v2.x - v1.x ) * alpha;
  4868. this.y = v1.y + ( v2.y - v1.y ) * alpha;
  4869. this.z = v1.z + ( v2.z - v1.z ) * alpha;
  4870. this.w = v1.w + ( v2.w - v1.w ) * alpha;
  4871. return this;
  4872. }
  4873. /**
  4874. * Returns `true` if this vector is equal with the given one.
  4875. *
  4876. * @param {Vector4} v - The vector to test for equality.
  4877. * @return {boolean} Whether this vector is equal with the given one.
  4878. */
  4879. equals( v ) {
  4880. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) && ( v.w === this.w ) );
  4881. }
  4882. /**
  4883. * Sets this vector's x value to be `array[ offset ]`, y value to be `array[ offset + 1 ]`,
  4884. * z value to be `array[ offset + 2 ]`, w value to be `array[ offset + 3 ]`.
  4885. *
  4886. * @param {Array<number>} array - An array holding the vector component values.
  4887. * @param {number} [offset=0] - The offset into the array.
  4888. * @return {Vector4} A reference to this vector.
  4889. */
  4890. fromArray( array, offset = 0 ) {
  4891. this.x = array[ offset ];
  4892. this.y = array[ offset + 1 ];
  4893. this.z = array[ offset + 2 ];
  4894. this.w = array[ offset + 3 ];
  4895. return this;
  4896. }
  4897. /**
  4898. * Writes the components of this vector to the given array. If no array is provided,
  4899. * the method returns a new instance.
  4900. *
  4901. * @param {Array<number>} [array=[]] - The target array holding the vector components.
  4902. * @param {number} [offset=0] - Index of the first element in the array.
  4903. * @return {Array<number>} The vector components.
  4904. */
  4905. toArray( array = [], offset = 0 ) {
  4906. array[ offset ] = this.x;
  4907. array[ offset + 1 ] = this.y;
  4908. array[ offset + 2 ] = this.z;
  4909. array[ offset + 3 ] = this.w;
  4910. return array;
  4911. }
  4912. /**
  4913. * Sets the components of this vector from the given buffer attribute.
  4914. *
  4915. * @param {BufferAttribute} attribute - The buffer attribute holding vector data.
  4916. * @param {number} index - The index into the attribute.
  4917. * @return {Vector4} A reference to this vector.
  4918. */
  4919. fromBufferAttribute( attribute, index ) {
  4920. this.x = attribute.getX( index );
  4921. this.y = attribute.getY( index );
  4922. this.z = attribute.getZ( index );
  4923. this.w = attribute.getW( index );
  4924. return this;
  4925. }
  4926. /**
  4927. * Sets each component of this vector to a pseudo-random value between `0` and
  4928. * `1`, excluding `1`.
  4929. *
  4930. * @return {Vector4} A reference to this vector.
  4931. */
  4932. random() {
  4933. this.x = Math.random();
  4934. this.y = Math.random();
  4935. this.z = Math.random();
  4936. this.w = Math.random();
  4937. return this;
  4938. }
  4939. *[ Symbol.iterator ]() {
  4940. yield this.x;
  4941. yield this.y;
  4942. yield this.z;
  4943. yield this.w;
  4944. }
  4945. }
  4946. /**
  4947. * A render target is a buffer where the video card draws pixels for a scene
  4948. * that is being rendered in the background. It is used in different effects,
  4949. * such as applying postprocessing to a rendered image before displaying it
  4950. * on the screen.
  4951. *
  4952. * @augments EventDispatcher
  4953. */
  4954. class RenderTarget extends EventDispatcher {
  4955. /**
  4956. * Render target options.
  4957. *
  4958. * @typedef {Object} RenderTarget~Options
  4959. * @property {boolean} [generateMipmaps=false] - Whether to generate mipmaps or not.
  4960. * @property {number} [magFilter=LinearFilter] - The mag filter.
  4961. * @property {number} [minFilter=LinearFilter] - The min filter.
  4962. * @property {number} [format=RGBAFormat] - The texture format.
  4963. * @property {number} [type=UnsignedByteType] - The texture type.
  4964. * @property {?string} [internalFormat=null] - The texture's internal format.
  4965. * @property {number} [wrapS=ClampToEdgeWrapping] - The texture's uv wrapping mode.
  4966. * @property {number} [wrapT=ClampToEdgeWrapping] - The texture's uv wrapping mode.
  4967. * @property {number} [anisotropy=1] - The texture's anisotropy value.
  4968. * @property {string} [colorSpace=NoColorSpace] - The texture's color space.
  4969. * @property {boolean} [depthBuffer=true] - Whether to allocate a depth buffer or not.
  4970. * @property {boolean} [stencilBuffer=false] - Whether to allocate a stencil buffer or not.
  4971. * @property {boolean} [resolveDepthBuffer=true] - Whether to resolve the depth buffer or not.
  4972. * @property {boolean} [resolveStencilBuffer=true] - Whether to resolve the stencil buffer or not.
  4973. * @property {?Texture} [depthTexture=null] - Reference to a depth texture.
  4974. * @property {number} [samples=0] - The MSAA samples count.
  4975. * @property {number} [count=1] - Defines the number of color attachments . Must be at least `1`.
  4976. */
  4977. /**
  4978. * Constructs a new render target.
  4979. *
  4980. * @param {number} [width=1] - The width of the render target.
  4981. * @param {number} [height=1] - The height of the render target.
  4982. * @param {RenderTarget~Options} [options] - The configuration object.
  4983. */
  4984. constructor( width = 1, height = 1, options = {} ) {
  4985. super();
  4986. /**
  4987. * This flag can be used for type testing.
  4988. *
  4989. * @type {boolean}
  4990. * @readonly
  4991. * @default true
  4992. */
  4993. this.isRenderTarget = true;
  4994. /**
  4995. * The width of the render target.
  4996. *
  4997. * @type {number}
  4998. * @default 1
  4999. */
  5000. this.width = width;
  5001. /**
  5002. * The height of the render target.
  5003. *
  5004. * @type {number}
  5005. * @default 1
  5006. */
  5007. this.height = height;
  5008. /**
  5009. * The depth of the render target.
  5010. *
  5011. * @type {number}
  5012. * @default 1
  5013. */
  5014. this.depth = 1;
  5015. /**
  5016. * A rectangular area inside the render target's viewport. Fragments that are
  5017. * outside the area will be discarded.
  5018. *
  5019. * @type {Vector4}
  5020. * @default (0,0,width,height)
  5021. */
  5022. this.scissor = new Vector4( 0, 0, width, height );
  5023. /**
  5024. * Indicates whether the scissor test should be enabled when rendering into
  5025. * this render target or not.
  5026. *
  5027. * @type {boolean}
  5028. * @default false
  5029. */
  5030. this.scissorTest = false;
  5031. /**
  5032. * A rectangular area representing the render target's viewport.
  5033. *
  5034. * @type {Vector4}
  5035. * @default (0,0,width,height)
  5036. */
  5037. this.viewport = new Vector4( 0, 0, width, height );
  5038. const image = { width: width, height: height, depth: 1 };
  5039. options = Object.assign( {
  5040. generateMipmaps: false,
  5041. internalFormat: null,
  5042. minFilter: LinearFilter,
  5043. depthBuffer: true,
  5044. stencilBuffer: false,
  5045. resolveDepthBuffer: true,
  5046. resolveStencilBuffer: true,
  5047. depthTexture: null,
  5048. samples: 0,
  5049. count: 1
  5050. }, options );
  5051. const texture = new Texture( image, options.mapping, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.colorSpace );
  5052. texture.flipY = false;
  5053. texture.generateMipmaps = options.generateMipmaps;
  5054. texture.internalFormat = options.internalFormat;
  5055. /**
  5056. * An array of textures. Each color attachment is represented as a separate texture.
  5057. * Has at least a single entry for the default color attachment.
  5058. *
  5059. * @type {Array<Texture>}
  5060. */
  5061. this.textures = [];
  5062. const count = options.count;
  5063. for ( let i = 0; i < count; i ++ ) {
  5064. this.textures[ i ] = texture.clone();
  5065. this.textures[ i ].isRenderTargetTexture = true;
  5066. this.textures[ i ].renderTarget = this;
  5067. }
  5068. /**
  5069. * Whether to allocate a depth buffer or not.
  5070. *
  5071. * @type {boolean}
  5072. * @default true
  5073. */
  5074. this.depthBuffer = options.depthBuffer;
  5075. /**
  5076. * Whether to allocate a stencil buffer or not.
  5077. *
  5078. * @type {boolean}
  5079. * @default false
  5080. */
  5081. this.stencilBuffer = options.stencilBuffer;
  5082. /**
  5083. * Whether to resolve the depth buffer or not.
  5084. *
  5085. * @type {boolean}
  5086. * @default true
  5087. */
  5088. this.resolveDepthBuffer = options.resolveDepthBuffer;
  5089. /**
  5090. * Whether to resolve the stencil buffer or not.
  5091. *
  5092. * @type {boolean}
  5093. * @default true
  5094. */
  5095. this.resolveStencilBuffer = options.resolveStencilBuffer;
  5096. this._depthTexture = options.depthTexture;
  5097. /**
  5098. * The number of MSAA samples.
  5099. *
  5100. * A value of `0` disables MSAA.
  5101. *
  5102. * @type {number}
  5103. * @default 0
  5104. */
  5105. this.samples = options.samples;
  5106. }
  5107. /**
  5108. * The texture representing the default color attachment.
  5109. *
  5110. * @type {Texture}
  5111. */
  5112. get texture() {
  5113. return this.textures[ 0 ];
  5114. }
  5115. set texture( value ) {
  5116. this.textures[ 0 ] = value;
  5117. }
  5118. set depthTexture( current ) {
  5119. if ( this._depthTexture !== null ) this._depthTexture.renderTarget = null;
  5120. if ( current !== null ) current.renderTarget = this;
  5121. this._depthTexture = current;
  5122. }
  5123. /**
  5124. * Instead of saving the depth in a renderbuffer, a texture
  5125. * can be used instead which is useful for further processing
  5126. * e.g. in context of post-processing.
  5127. *
  5128. * @type {?DepthTexture}
  5129. * @default null
  5130. */
  5131. get depthTexture() {
  5132. return this._depthTexture;
  5133. }
  5134. /**
  5135. * Sets the size of this render target.
  5136. *
  5137. * @param {number} width - The width.
  5138. * @param {number} height - The height.
  5139. * @param {number} [depth=1] - The depth.
  5140. */
  5141. setSize( width, height, depth = 1 ) {
  5142. if ( this.width !== width || this.height !== height || this.depth !== depth ) {
  5143. this.width = width;
  5144. this.height = height;
  5145. this.depth = depth;
  5146. for ( let i = 0, il = this.textures.length; i < il; i ++ ) {
  5147. this.textures[ i ].image.width = width;
  5148. this.textures[ i ].image.height = height;
  5149. this.textures[ i ].image.depth = depth;
  5150. }
  5151. this.dispose();
  5152. }
  5153. this.viewport.set( 0, 0, width, height );
  5154. this.scissor.set( 0, 0, width, height );
  5155. }
  5156. /**
  5157. * Returns a new render target with copied values from this instance.
  5158. *
  5159. * @return {RenderTarget} A clone of this instance.
  5160. */
  5161. clone() {
  5162. return new this.constructor().copy( this );
  5163. }
  5164. /**
  5165. * Copies the settings of the given render target. This is a structural copy so
  5166. * no resources are shared between render targets after the copy. That includes
  5167. * all MRT textures and the depth texture.
  5168. *
  5169. * @param {RenderTarget} source - The render target to copy.
  5170. * @return {RenderTarget} A reference to this instance.
  5171. */
  5172. copy( source ) {
  5173. this.width = source.width;
  5174. this.height = source.height;
  5175. this.depth = source.depth;
  5176. this.scissor.copy( source.scissor );
  5177. this.scissorTest = source.scissorTest;
  5178. this.viewport.copy( source.viewport );
  5179. this.textures.length = 0;
  5180. for ( let i = 0, il = source.textures.length; i < il; i ++ ) {
  5181. this.textures[ i ] = source.textures[ i ].clone();
  5182. this.textures[ i ].isRenderTargetTexture = true;
  5183. this.textures[ i ].renderTarget = this;
  5184. // ensure image object is not shared, see #20328
  5185. const image = Object.assign( {}, source.textures[ i ].image );
  5186. this.textures[ i ].source = new Source( image );
  5187. }
  5188. this.depthBuffer = source.depthBuffer;
  5189. this.stencilBuffer = source.stencilBuffer;
  5190. this.resolveDepthBuffer = source.resolveDepthBuffer;
  5191. this.resolveStencilBuffer = source.resolveStencilBuffer;
  5192. if ( source.depthTexture !== null ) this.depthTexture = source.depthTexture.clone();
  5193. this.samples = source.samples;
  5194. return this;
  5195. }
  5196. /**
  5197. * Frees the GPU-related resources allocated by this instance. Call this
  5198. * method whenever this instance is no longer used in your app.
  5199. *
  5200. * @fires RenderTarget#dispose
  5201. */
  5202. dispose() {
  5203. this.dispatchEvent( { type: 'dispose' } );
  5204. }
  5205. }
  5206. /**
  5207. * A render target used in context of {@link WebGLRenderer}.
  5208. *
  5209. * @augments RenderTarget
  5210. */
  5211. class WebGLRenderTarget extends RenderTarget {
  5212. /**
  5213. * Constructs a new 3D render target.
  5214. *
  5215. * @param {number} [width=1] - The width of the render target.
  5216. * @param {number} [height=1] - The height of the render target.
  5217. * @param {RenderTarget~Options} [options] - The configuration object.
  5218. */
  5219. constructor( width = 1, height = 1, options = {} ) {
  5220. super( width, height, options );
  5221. /**
  5222. * This flag can be used for type testing.
  5223. *
  5224. * @type {boolean}
  5225. * @readonly
  5226. * @default true
  5227. */
  5228. this.isWebGLRenderTarget = true;
  5229. }
  5230. }
  5231. /**
  5232. * Creates an array of textures directly from raw buffer data.
  5233. *
  5234. * @augments Texture
  5235. */
  5236. class DataArrayTexture extends Texture {
  5237. /**
  5238. * Constructs a new data array texture.
  5239. *
  5240. * @param {?TypedArray} [data=null] - The buffer data.
  5241. * @param {number} [width=1] - The width of the texture.
  5242. * @param {number} [height=1] - The height of the texture.
  5243. * @param {number} [depth=1] - The depth of the texture.
  5244. */
  5245. constructor( data = null, width = 1, height = 1, depth = 1 ) {
  5246. super( null );
  5247. /**
  5248. * This flag can be used for type testing.
  5249. *
  5250. * @type {boolean}
  5251. * @readonly
  5252. * @default true
  5253. */
  5254. this.isDataArrayTexture = true;
  5255. /**
  5256. * The image definition of a data texture.
  5257. *
  5258. * @type {{data:TypedArray,width:number,height:number,depth:number}}
  5259. */
  5260. this.image = { data, width, height, depth };
  5261. /**
  5262. * How the texture is sampled when a texel covers more than one pixel.
  5263. *
  5264. * Overwritten and set to `NearestFilter` by default.
  5265. *
  5266. * @type {(NearestFilter|NearestMipmapNearestFilter|NearestMipmapLinearFilter|LinearFilter|LinearMipmapNearestFilter|LinearMipmapLinearFilter)}
  5267. * @default NearestFilter
  5268. */
  5269. this.magFilter = NearestFilter;
  5270. /**
  5271. * How the texture is sampled when a texel covers less than one pixel.
  5272. *
  5273. * Overwritten and set to `NearestFilter` by default.
  5274. *
  5275. * @type {(NearestFilter|NearestMipmapNearestFilter|NearestMipmapLinearFilter|LinearFilter|LinearMipmapNearestFilter|LinearMipmapLinearFilter)}
  5276. * @default NearestFilter
  5277. */
  5278. this.minFilter = NearestFilter;
  5279. /**
  5280. * This defines how the texture is wrapped in the depth and corresponds to
  5281. * *W* in UVW mapping.
  5282. *
  5283. * @type {(RepeatWrapping|ClampToEdgeWrapping|MirroredRepeatWrapping)}
  5284. * @default ClampToEdgeWrapping
  5285. */
  5286. this.wrapR = ClampToEdgeWrapping;
  5287. /**
  5288. * Whether to generate mipmaps (if possible) for a texture.
  5289. *
  5290. * Overwritten and set to `false` by default.
  5291. *
  5292. * @type {boolean}
  5293. * @default false
  5294. */
  5295. this.generateMipmaps = false;
  5296. /**
  5297. * If set to `true`, the texture is flipped along the vertical axis when
  5298. * uploaded to the GPU.
  5299. *
  5300. * Overwritten and set to `false` by default.
  5301. *
  5302. * @type {boolean}
  5303. * @default false
  5304. */
  5305. this.flipY = false;
  5306. /**
  5307. * Specifies the alignment requirements for the start of each pixel row in memory.
  5308. *
  5309. * Overwritten and set to `1` by default.
  5310. *
  5311. * @type {boolean}
  5312. * @default 1
  5313. */
  5314. this.unpackAlignment = 1;
  5315. /**
  5316. * A set of all layers which need to be updated in the texture.
  5317. *
  5318. * @type {Set<number>}
  5319. */
  5320. this.layerUpdates = new Set();
  5321. }
  5322. /**
  5323. * Describes that a specific layer of the texture needs to be updated.
  5324. * Normally when {@link Texture#needsUpdate} is set to `true`, the
  5325. * entire data texture array is sent to the GPU. Marking specific
  5326. * layers will only transmit subsets of all mipmaps associated with a
  5327. * specific depth in the array which is often much more performant.
  5328. *
  5329. * @param {number} layerIndex - The layer index that should be updated.
  5330. */
  5331. addLayerUpdate( layerIndex ) {
  5332. this.layerUpdates.add( layerIndex );
  5333. }
  5334. /**
  5335. * Resets the layer updates registry.
  5336. */
  5337. clearLayerUpdates() {
  5338. this.layerUpdates.clear();
  5339. }
  5340. }
  5341. /**
  5342. * An array render target used in context of {@link WebGLRenderer}.
  5343. *
  5344. * @augments WebGLRenderTarget
  5345. */
  5346. class WebGLArrayRenderTarget extends WebGLRenderTarget {
  5347. /**
  5348. * Constructs a new array render target.
  5349. *
  5350. * @param {number} [width=1] - The width of the render target.
  5351. * @param {number} [height=1] - The height of the render target.
  5352. * @param {number} [depth=1] - The height of the render target.
  5353. * @param {RenderTarget~Options} [options] - The configuration object.
  5354. */
  5355. constructor( width = 1, height = 1, depth = 1, options = {} ) {
  5356. super( width, height, options );
  5357. /**
  5358. * This flag can be used for type testing.
  5359. *
  5360. * @type {boolean}
  5361. * @readonly
  5362. * @default true
  5363. */
  5364. this.isWebGLArrayRenderTarget = true;
  5365. this.depth = depth;
  5366. /**
  5367. * Overwritten with a different texture type.
  5368. *
  5369. * @type {DataArrayTexture}
  5370. */
  5371. this.texture = new DataArrayTexture( null, width, height, depth );
  5372. this.texture.isRenderTargetTexture = true;
  5373. }
  5374. }
  5375. /**
  5376. * Creates a three-dimensional texture from raw data, with parameters to
  5377. * divide it into width, height, and depth.
  5378. *
  5379. * @augments Texture
  5380. */
  5381. class Data3DTexture extends Texture {
  5382. /**
  5383. * Constructs a new data array texture.
  5384. *
  5385. * @param {?TypedArray} [data=null] - The buffer data.
  5386. * @param {number} [width=1] - The width of the texture.
  5387. * @param {number} [height=1] - The height of the texture.
  5388. * @param {number} [depth=1] - The depth of the texture.
  5389. */
  5390. constructor( data = null, width = 1, height = 1, depth = 1 ) {
  5391. // We're going to add .setXXX() methods for setting properties later.
  5392. // Users can still set in Data3DTexture directly.
  5393. //
  5394. // const texture = new THREE.Data3DTexture( data, width, height, depth );
  5395. // texture.anisotropy = 16;
  5396. //
  5397. // See #14839
  5398. super( null );
  5399. /**
  5400. * This flag can be used for type testing.
  5401. *
  5402. * @type {boolean}
  5403. * @readonly
  5404. * @default true
  5405. */
  5406. this.isData3DTexture = true;
  5407. /**
  5408. * The image definition of a data texture.
  5409. *
  5410. * @type {{data:TypedArray,width:number,height:number,depth:number}}
  5411. */
  5412. this.image = { data, width, height, depth };
  5413. /**
  5414. * How the texture is sampled when a texel covers more than one pixel.
  5415. *
  5416. * Overwritten and set to `NearestFilter` by default.
  5417. *
  5418. * @type {(NearestFilter|NearestMipmapNearestFilter|NearestMipmapLinearFilter|LinearFilter|LinearMipmapNearestFilter|LinearMipmapLinearFilter)}
  5419. * @default NearestFilter
  5420. */
  5421. this.magFilter = NearestFilter;
  5422. /**
  5423. * How the texture is sampled when a texel covers less than one pixel.
  5424. *
  5425. * Overwritten and set to `NearestFilter` by default.
  5426. *
  5427. * @type {(NearestFilter|NearestMipmapNearestFilter|NearestMipmapLinearFilter|LinearFilter|LinearMipmapNearestFilter|LinearMipmapLinearFilter)}
  5428. * @default NearestFilter
  5429. */
  5430. this.minFilter = NearestFilter;
  5431. /**
  5432. * This defines how the texture is wrapped in the depth and corresponds to
  5433. * *W* in UVW mapping.
  5434. *
  5435. * @type {(RepeatWrapping|ClampToEdgeWrapping|MirroredRepeatWrapping)}
  5436. * @default ClampToEdgeWrapping
  5437. */
  5438. this.wrapR = ClampToEdgeWrapping;
  5439. /**
  5440. * Whether to generate mipmaps (if possible) for a texture.
  5441. *
  5442. * Overwritten and set to `false` by default.
  5443. *
  5444. * @type {boolean}
  5445. * @default false
  5446. */
  5447. this.generateMipmaps = false;
  5448. /**
  5449. * If set to `true`, the texture is flipped along the vertical axis when
  5450. * uploaded to the GPU.
  5451. *
  5452. * Overwritten and set to `false` by default.
  5453. *
  5454. * @type {boolean}
  5455. * @default false
  5456. */
  5457. this.flipY = false;
  5458. /**
  5459. * Specifies the alignment requirements for the start of each pixel row in memory.
  5460. *
  5461. * Overwritten and set to `1` by default.
  5462. *
  5463. * @type {boolean}
  5464. * @default 1
  5465. */
  5466. this.unpackAlignment = 1;
  5467. }
  5468. }
  5469. /**
  5470. * A 3D render target used in context of {@link WebGLRenderer}.
  5471. *
  5472. * @augments WebGLRenderTarget
  5473. */
  5474. class WebGL3DRenderTarget extends WebGLRenderTarget {
  5475. /**
  5476. * Constructs a new 3D render target.
  5477. *
  5478. * @param {number} [width=1] - The width of the render target.
  5479. * @param {number} [height=1] - The height of the render target.
  5480. * @param {number} [depth=1] - The height of the render target.
  5481. * @param {RenderTarget~Options} [options] - The configuration object.
  5482. */
  5483. constructor( width = 1, height = 1, depth = 1, options = {} ) {
  5484. super( width, height, options );
  5485. /**
  5486. * This flag can be used for type testing.
  5487. *
  5488. * @type {boolean}
  5489. * @readonly
  5490. * @default true
  5491. */
  5492. this.isWebGL3DRenderTarget = true;
  5493. this.depth = depth;
  5494. /**
  5495. * Overwritten with a different texture type.
  5496. *
  5497. * @type {Data3DTexture}
  5498. */
  5499. this.texture = new Data3DTexture( null, width, height, depth );
  5500. this.texture.isRenderTargetTexture = true;
  5501. }
  5502. }
  5503. /**
  5504. * Class for representing a Quaternion. Quaternions are used in three.js to represent rotations.
  5505. *
  5506. * Iterating through a vector instance will yield its components `(x, y, z, w)` in
  5507. * the corresponding order.
  5508. *
  5509. * Note that three.js expects Quaternions to be normalized.
  5510. * ```js
  5511. * const quaternion = new THREE.Quaternion();
  5512. * quaternion.setFromAxisAngle( new THREE.Vector3( 0, 1, 0 ), Math.PI / 2 );
  5513. *
  5514. * const vector = new THREE.Vector3( 1, 0, 0 );
  5515. * vector.applyQuaternion( quaternion );
  5516. * ```
  5517. */
  5518. class Quaternion {
  5519. /**
  5520. * Constructs a new quaternion.
  5521. *
  5522. * @param {number} [x=0] - The x value of this quaternion.
  5523. * @param {number} [y=0] - The y value of this quaternion.
  5524. * @param {number} [z=0] - The z value of this quaternion.
  5525. * @param {number} [w=1] - The w value of this quaternion.
  5526. */
  5527. constructor( x = 0, y = 0, z = 0, w = 1 ) {
  5528. /**
  5529. * This flag can be used for type testing.
  5530. *
  5531. * @type {boolean}
  5532. * @readonly
  5533. * @default true
  5534. */
  5535. this.isQuaternion = true;
  5536. this._x = x;
  5537. this._y = y;
  5538. this._z = z;
  5539. this._w = w;
  5540. }
  5541. /**
  5542. * Interpolates between two quaternions via SLERP. This implementation assumes the
  5543. * quaternion data are managed in flat arrays.
  5544. *
  5545. * @param {Array<number>} dst - The destination array.
  5546. * @param {number} dstOffset - An offset into the destination array.
  5547. * @param {Array<number>} src0 - The source array of the first quaternion.
  5548. * @param {number} srcOffset0 - An offset into the first source array.
  5549. * @param {Array<number>} src1 - The source array of the second quaternion.
  5550. * @param {number} srcOffset1 - An offset into the second source array.
  5551. * @param {number} t - The interpolation factor in the range `[0,1]`.
  5552. * @see {@link Quaternion#slerp}
  5553. */
  5554. static slerpFlat( dst, dstOffset, src0, srcOffset0, src1, srcOffset1, t ) {
  5555. // fuzz-free, array-based Quaternion SLERP operation
  5556. let x0 = src0[ srcOffset0 + 0 ],
  5557. y0 = src0[ srcOffset0 + 1 ],
  5558. z0 = src0[ srcOffset0 + 2 ],
  5559. w0 = src0[ srcOffset0 + 3 ];
  5560. const x1 = src1[ srcOffset1 + 0 ],
  5561. y1 = src1[ srcOffset1 + 1 ],
  5562. z1 = src1[ srcOffset1 + 2 ],
  5563. w1 = src1[ srcOffset1 + 3 ];
  5564. if ( t === 0 ) {
  5565. dst[ dstOffset + 0 ] = x0;
  5566. dst[ dstOffset + 1 ] = y0;
  5567. dst[ dstOffset + 2 ] = z0;
  5568. dst[ dstOffset + 3 ] = w0;
  5569. return;
  5570. }
  5571. if ( t === 1 ) {
  5572. dst[ dstOffset + 0 ] = x1;
  5573. dst[ dstOffset + 1 ] = y1;
  5574. dst[ dstOffset + 2 ] = z1;
  5575. dst[ dstOffset + 3 ] = w1;
  5576. return;
  5577. }
  5578. if ( w0 !== w1 || x0 !== x1 || y0 !== y1 || z0 !== z1 ) {
  5579. let s = 1 - t;
  5580. const cos = x0 * x1 + y0 * y1 + z0 * z1 + w0 * w1,
  5581. dir = ( cos >= 0 ? 1 : -1 ),
  5582. sqrSin = 1 - cos * cos;
  5583. // Skip the Slerp for tiny steps to avoid numeric problems:
  5584. if ( sqrSin > Number.EPSILON ) {
  5585. const sin = Math.sqrt( sqrSin ),
  5586. len = Math.atan2( sin, cos * dir );
  5587. s = Math.sin( s * len ) / sin;
  5588. t = Math.sin( t * len ) / sin;
  5589. }
  5590. const tDir = t * dir;
  5591. x0 = x0 * s + x1 * tDir;
  5592. y0 = y0 * s + y1 * tDir;
  5593. z0 = z0 * s + z1 * tDir;
  5594. w0 = w0 * s + w1 * tDir;
  5595. // Normalize in case we just did a lerp:
  5596. if ( s === 1 - t ) {
  5597. const f = 1 / Math.sqrt( x0 * x0 + y0 * y0 + z0 * z0 + w0 * w0 );
  5598. x0 *= f;
  5599. y0 *= f;
  5600. z0 *= f;
  5601. w0 *= f;
  5602. }
  5603. }
  5604. dst[ dstOffset ] = x0;
  5605. dst[ dstOffset + 1 ] = y0;
  5606. dst[ dstOffset + 2 ] = z0;
  5607. dst[ dstOffset + 3 ] = w0;
  5608. }
  5609. /**
  5610. * Multiplies two quaternions. This implementation assumes the quaternion data are managed
  5611. * in flat arrays.
  5612. *
  5613. * @param {Array<number>} dst - The destination array.
  5614. * @param {number} dstOffset - An offset into the destination array.
  5615. * @param {Array<number>} src0 - The source array of the first quaternion.
  5616. * @param {number} srcOffset0 - An offset into the first source array.
  5617. * @param {Array<number>} src1 - The source array of the second quaternion.
  5618. * @param {number} srcOffset1 - An offset into the second source array.
  5619. * @return {Array<number>} The destination array.
  5620. * @see {@link Quaternion#multiplyQuaternions}.
  5621. */
  5622. static multiplyQuaternionsFlat( dst, dstOffset, src0, srcOffset0, src1, srcOffset1 ) {
  5623. const x0 = src0[ srcOffset0 ];
  5624. const y0 = src0[ srcOffset0 + 1 ];
  5625. const z0 = src0[ srcOffset0 + 2 ];
  5626. const w0 = src0[ srcOffset0 + 3 ];
  5627. const x1 = src1[ srcOffset1 ];
  5628. const y1 = src1[ srcOffset1 + 1 ];
  5629. const z1 = src1[ srcOffset1 + 2 ];
  5630. const w1 = src1[ srcOffset1 + 3 ];
  5631. dst[ dstOffset ] = x0 * w1 + w0 * x1 + y0 * z1 - z0 * y1;
  5632. dst[ dstOffset + 1 ] = y0 * w1 + w0 * y1 + z0 * x1 - x0 * z1;
  5633. dst[ dstOffset + 2 ] = z0 * w1 + w0 * z1 + x0 * y1 - y0 * x1;
  5634. dst[ dstOffset + 3 ] = w0 * w1 - x0 * x1 - y0 * y1 - z0 * z1;
  5635. return dst;
  5636. }
  5637. /**
  5638. * The x value of this quaternion.
  5639. *
  5640. * @type {number}
  5641. * @default 0
  5642. */
  5643. get x() {
  5644. return this._x;
  5645. }
  5646. set x( value ) {
  5647. this._x = value;
  5648. this._onChangeCallback();
  5649. }
  5650. /**
  5651. * The y value of this quaternion.
  5652. *
  5653. * @type {number}
  5654. * @default 0
  5655. */
  5656. get y() {
  5657. return this._y;
  5658. }
  5659. set y( value ) {
  5660. this._y = value;
  5661. this._onChangeCallback();
  5662. }
  5663. /**
  5664. * The z value of this quaternion.
  5665. *
  5666. * @type {number}
  5667. * @default 0
  5668. */
  5669. get z() {
  5670. return this._z;
  5671. }
  5672. set z( value ) {
  5673. this._z = value;
  5674. this._onChangeCallback();
  5675. }
  5676. /**
  5677. * The w value of this quaternion.
  5678. *
  5679. * @type {number}
  5680. * @default 1
  5681. */
  5682. get w() {
  5683. return this._w;
  5684. }
  5685. set w( value ) {
  5686. this._w = value;
  5687. this._onChangeCallback();
  5688. }
  5689. /**
  5690. * Sets the quaternion components.
  5691. *
  5692. * @param {number} x - The x value of this quaternion.
  5693. * @param {number} y - The y value of this quaternion.
  5694. * @param {number} z - The z value of this quaternion.
  5695. * @param {number} w - The w value of this quaternion.
  5696. * @return {Quaternion} A reference to this quaternion.
  5697. */
  5698. set( x, y, z, w ) {
  5699. this._x = x;
  5700. this._y = y;
  5701. this._z = z;
  5702. this._w = w;
  5703. this._onChangeCallback();
  5704. return this;
  5705. }
  5706. /**
  5707. * Returns a new quaternion with copied values from this instance.
  5708. *
  5709. * @return {Quaternion} A clone of this instance.
  5710. */
  5711. clone() {
  5712. return new this.constructor( this._x, this._y, this._z, this._w );
  5713. }
  5714. /**
  5715. * Copies the values of the given quaternion to this instance.
  5716. *
  5717. * @param {Quaternion} quaternion - The quaternion to copy.
  5718. * @return {Quaternion} A reference to this quaternion.
  5719. */
  5720. copy( quaternion ) {
  5721. this._x = quaternion.x;
  5722. this._y = quaternion.y;
  5723. this._z = quaternion.z;
  5724. this._w = quaternion.w;
  5725. this._onChangeCallback();
  5726. return this;
  5727. }
  5728. /**
  5729. * Sets this quaternion from the rotation specified by the given
  5730. * Euler angles.
  5731. *
  5732. * @param {Euler} euler - The Euler angles.
  5733. * @param {boolean} [update=true] - Whether the internal `onChange` callback should be executed or not.
  5734. * @return {Quaternion} A reference to this quaternion.
  5735. */
  5736. setFromEuler( euler, update = true ) {
  5737. const x = euler._x, y = euler._y, z = euler._z, order = euler._order;
  5738. // http://www.mathworks.com/matlabcentral/fileexchange/
  5739. // 20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/
  5740. // content/SpinCalc.m
  5741. const cos = Math.cos;
  5742. const sin = Math.sin;
  5743. const c1 = cos( x / 2 );
  5744. const c2 = cos( y / 2 );
  5745. const c3 = cos( z / 2 );
  5746. const s1 = sin( x / 2 );
  5747. const s2 = sin( y / 2 );
  5748. const s3 = sin( z / 2 );
  5749. switch ( order ) {
  5750. case 'XYZ':
  5751. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  5752. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  5753. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  5754. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  5755. break;
  5756. case 'YXZ':
  5757. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  5758. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  5759. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  5760. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  5761. break;
  5762. case 'ZXY':
  5763. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  5764. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  5765. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  5766. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  5767. break;
  5768. case 'ZYX':
  5769. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  5770. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  5771. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  5772. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  5773. break;
  5774. case 'YZX':
  5775. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  5776. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  5777. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  5778. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  5779. break;
  5780. case 'XZY':
  5781. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  5782. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  5783. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  5784. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  5785. break;
  5786. default:
  5787. console.warn( 'THREE.Quaternion: .setFromEuler() encountered an unknown order: ' + order );
  5788. }
  5789. if ( update === true ) this._onChangeCallback();
  5790. return this;
  5791. }
  5792. /**
  5793. * Sets this quaternion from the given axis and angle.
  5794. *
  5795. * @param {Vector3} axis - The normalized axis.
  5796. * @param {number} angle - The angle in radians.
  5797. * @return {Quaternion} A reference to this quaternion.
  5798. */
  5799. setFromAxisAngle( axis, angle ) {
  5800. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm
  5801. const halfAngle = angle / 2, s = Math.sin( halfAngle );
  5802. this._x = axis.x * s;
  5803. this._y = axis.y * s;
  5804. this._z = axis.z * s;
  5805. this._w = Math.cos( halfAngle );
  5806. this._onChangeCallback();
  5807. return this;
  5808. }
  5809. /**
  5810. * Sets this quaternion from the given rotation matrix.
  5811. *
  5812. * @param {Matrix4} m - A 4x4 matrix of which the upper 3x3 of matrix is a pure rotation matrix (i.e. unscaled).
  5813. * @return {Quaternion} A reference to this quaternion.
  5814. */
  5815. setFromRotationMatrix( m ) {
  5816. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm
  5817. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  5818. const te = m.elements,
  5819. m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ],
  5820. m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ],
  5821. m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ],
  5822. trace = m11 + m22 + m33;
  5823. if ( trace > 0 ) {
  5824. const s = 0.5 / Math.sqrt( trace + 1.0 );
  5825. this._w = 0.25 / s;
  5826. this._x = ( m32 - m23 ) * s;
  5827. this._y = ( m13 - m31 ) * s;
  5828. this._z = ( m21 - m12 ) * s;
  5829. } else if ( m11 > m22 && m11 > m33 ) {
  5830. const s = 2.0 * Math.sqrt( 1.0 + m11 - m22 - m33 );
  5831. this._w = ( m32 - m23 ) / s;
  5832. this._x = 0.25 * s;
  5833. this._y = ( m12 + m21 ) / s;
  5834. this._z = ( m13 + m31 ) / s;
  5835. } else if ( m22 > m33 ) {
  5836. const s = 2.0 * Math.sqrt( 1.0 + m22 - m11 - m33 );
  5837. this._w = ( m13 - m31 ) / s;
  5838. this._x = ( m12 + m21 ) / s;
  5839. this._y = 0.25 * s;
  5840. this._z = ( m23 + m32 ) / s;
  5841. } else {
  5842. const s = 2.0 * Math.sqrt( 1.0 + m33 - m11 - m22 );
  5843. this._w = ( m21 - m12 ) / s;
  5844. this._x = ( m13 + m31 ) / s;
  5845. this._y = ( m23 + m32 ) / s;
  5846. this._z = 0.25 * s;
  5847. }
  5848. this._onChangeCallback();
  5849. return this;
  5850. }
  5851. /**
  5852. * Sets this quaternion to the rotation required to rotate the direction vector
  5853. * `vFrom` to the direction vector `vTo`.
  5854. *
  5855. * @param {Vector3} vFrom - The first (normalized) direction vector.
  5856. * @param {Vector3} vTo - The second (normalized) direction vector.
  5857. * @return {Quaternion} A reference to this quaternion.
  5858. */
  5859. setFromUnitVectors( vFrom, vTo ) {
  5860. // assumes direction vectors vFrom and vTo are normalized
  5861. let r = vFrom.dot( vTo ) + 1;
  5862. if ( r < Number.EPSILON ) {
  5863. // vFrom and vTo point in opposite directions
  5864. r = 0;
  5865. if ( Math.abs( vFrom.x ) > Math.abs( vFrom.z ) ) {
  5866. this._x = - vFrom.y;
  5867. this._y = vFrom.x;
  5868. this._z = 0;
  5869. this._w = r;
  5870. } else {
  5871. this._x = 0;
  5872. this._y = - vFrom.z;
  5873. this._z = vFrom.y;
  5874. this._w = r;
  5875. }
  5876. } else {
  5877. // crossVectors( vFrom, vTo ); // inlined to avoid cyclic dependency on Vector3
  5878. this._x = vFrom.y * vTo.z - vFrom.z * vTo.y;
  5879. this._y = vFrom.z * vTo.x - vFrom.x * vTo.z;
  5880. this._z = vFrom.x * vTo.y - vFrom.y * vTo.x;
  5881. this._w = r;
  5882. }
  5883. return this.normalize();
  5884. }
  5885. /**
  5886. * Returns the angle between this quaternion and the given one in radians.
  5887. *
  5888. * @param {Quaternion} q - The quaternion to compute the angle with.
  5889. * @return {number} The angle in radians.
  5890. */
  5891. angleTo( q ) {
  5892. return 2 * Math.acos( Math.abs( clamp( this.dot( q ), -1, 1 ) ) );
  5893. }
  5894. /**
  5895. * Rotates this quaternion by a given angular step to the given quaternion.
  5896. * The method ensures that the final quaternion will not overshoot `q`.
  5897. *
  5898. * @param {Quaternion} q - The target quaternion.
  5899. * @param {number} step - The angular step in radians.
  5900. * @return {Quaternion} A reference to this quaternion.
  5901. */
  5902. rotateTowards( q, step ) {
  5903. const angle = this.angleTo( q );
  5904. if ( angle === 0 ) return this;
  5905. const t = Math.min( 1, step / angle );
  5906. this.slerp( q, t );
  5907. return this;
  5908. }
  5909. /**
  5910. * Sets this quaternion to the identity quaternion; that is, to the
  5911. * quaternion that represents "no rotation".
  5912. *
  5913. * @return {Quaternion} A reference to this quaternion.
  5914. */
  5915. identity() {
  5916. return this.set( 0, 0, 0, 1 );
  5917. }
  5918. /**
  5919. * Inverts this quaternion via {@link Quaternion#conjugate}. The
  5920. * quaternion is assumed to have unit length.
  5921. *
  5922. * @return {Quaternion} A reference to this quaternion.
  5923. */
  5924. invert() {
  5925. return this.conjugate();
  5926. }
  5927. /**
  5928. * Returns the rotational conjugate of this quaternion. The conjugate of a
  5929. * quaternion represents the same rotation in the opposite direction about
  5930. * the rotational axis.
  5931. *
  5932. * @return {Quaternion} A reference to this quaternion.
  5933. */
  5934. conjugate() {
  5935. this._x *= -1;
  5936. this._y *= -1;
  5937. this._z *= -1;
  5938. this._onChangeCallback();
  5939. return this;
  5940. }
  5941. /**
  5942. * Calculates the dot product of this quaternion and the given one.
  5943. *
  5944. * @param {Quaternion} v - The quaternion to compute the dot product with.
  5945. * @return {number} The result of the dot product.
  5946. */
  5947. dot( v ) {
  5948. return this._x * v._x + this._y * v._y + this._z * v._z + this._w * v._w;
  5949. }
  5950. /**
  5951. * Computes the squared Euclidean length (straight-line length) of this quaternion,
  5952. * considered as a 4 dimensional vector. This can be useful if you are comparing the
  5953. * lengths of two quaternions, as this is a slightly more efficient calculation than
  5954. * {@link Quaternion#length}.
  5955. *
  5956. * @return {number} The squared Euclidean length.
  5957. */
  5958. lengthSq() {
  5959. return this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w;
  5960. }
  5961. /**
  5962. * Computes the Euclidean length (straight-line length) of this quaternion,
  5963. * considered as a 4 dimensional vector.
  5964. *
  5965. * @return {number} The Euclidean length.
  5966. */
  5967. length() {
  5968. return Math.sqrt( this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w );
  5969. }
  5970. /**
  5971. * Normalizes this quaternion - that is, calculated the quaternion that performs
  5972. * the same rotation as this one, but has a length equal to `1`.
  5973. *
  5974. * @return {Quaternion} A reference to this quaternion.
  5975. */
  5976. normalize() {
  5977. let l = this.length();
  5978. if ( l === 0 ) {
  5979. this._x = 0;
  5980. this._y = 0;
  5981. this._z = 0;
  5982. this._w = 1;
  5983. } else {
  5984. l = 1 / l;
  5985. this._x = this._x * l;
  5986. this._y = this._y * l;
  5987. this._z = this._z * l;
  5988. this._w = this._w * l;
  5989. }
  5990. this._onChangeCallback();
  5991. return this;
  5992. }
  5993. /**
  5994. * Multiplies this quaternion by the given one.
  5995. *
  5996. * @param {Quaternion} q - The quaternion.
  5997. * @return {Quaternion} A reference to this quaternion.
  5998. */
  5999. multiply( q ) {
  6000. return this.multiplyQuaternions( this, q );
  6001. }
  6002. /**
  6003. * Pre-multiplies this quaternion by the given one.
  6004. *
  6005. * @param {Quaternion} q - The quaternion.
  6006. * @return {Quaternion} A reference to this quaternion.
  6007. */
  6008. premultiply( q ) {
  6009. return this.multiplyQuaternions( q, this );
  6010. }
  6011. /**
  6012. * Multiplies the given quaternions and stores the result in this instance.
  6013. *
  6014. * @param {Quaternion} a - The first quaternion.
  6015. * @param {Quaternion} b - The second quaternion.
  6016. * @return {Quaternion} A reference to this quaternion.
  6017. */
  6018. multiplyQuaternions( a, b ) {
  6019. // from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm
  6020. const qax = a._x, qay = a._y, qaz = a._z, qaw = a._w;
  6021. const qbx = b._x, qby = b._y, qbz = b._z, qbw = b._w;
  6022. this._x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby;
  6023. this._y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz;
  6024. this._z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx;
  6025. this._w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz;
  6026. this._onChangeCallback();
  6027. return this;
  6028. }
  6029. /**
  6030. * Performs a spherical linear interpolation between quaternions.
  6031. *
  6032. * @param {Quaternion} qb - The target quaternion.
  6033. * @param {number} t - The interpolation factor in the closed interval `[0, 1]`.
  6034. * @return {Quaternion} A reference to this quaternion.
  6035. */
  6036. slerp( qb, t ) {
  6037. if ( t === 0 ) return this;
  6038. if ( t === 1 ) return this.copy( qb );
  6039. const x = this._x, y = this._y, z = this._z, w = this._w;
  6040. // http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/
  6041. let cosHalfTheta = w * qb._w + x * qb._x + y * qb._y + z * qb._z;
  6042. if ( cosHalfTheta < 0 ) {
  6043. this._w = - qb._w;
  6044. this._x = - qb._x;
  6045. this._y = - qb._y;
  6046. this._z = - qb._z;
  6047. cosHalfTheta = - cosHalfTheta;
  6048. } else {
  6049. this.copy( qb );
  6050. }
  6051. if ( cosHalfTheta >= 1.0 ) {
  6052. this._w = w;
  6053. this._x = x;
  6054. this._y = y;
  6055. this._z = z;
  6056. return this;
  6057. }
  6058. const sqrSinHalfTheta = 1.0 - cosHalfTheta * cosHalfTheta;
  6059. if ( sqrSinHalfTheta <= Number.EPSILON ) {
  6060. const s = 1 - t;
  6061. this._w = s * w + t * this._w;
  6062. this._x = s * x + t * this._x;
  6063. this._y = s * y + t * this._y;
  6064. this._z = s * z + t * this._z;
  6065. this.normalize(); // normalize calls _onChangeCallback()
  6066. return this;
  6067. }
  6068. const sinHalfTheta = Math.sqrt( sqrSinHalfTheta );
  6069. const halfTheta = Math.atan2( sinHalfTheta, cosHalfTheta );
  6070. const ratioA = Math.sin( ( 1 - t ) * halfTheta ) / sinHalfTheta,
  6071. ratioB = Math.sin( t * halfTheta ) / sinHalfTheta;
  6072. this._w = ( w * ratioA + this._w * ratioB );
  6073. this._x = ( x * ratioA + this._x * ratioB );
  6074. this._y = ( y * ratioA + this._y * ratioB );
  6075. this._z = ( z * ratioA + this._z * ratioB );
  6076. this._onChangeCallback();
  6077. return this;
  6078. }
  6079. /**
  6080. * Performs a spherical linear interpolation between the given quaternions
  6081. * and stores the result in this quaternion.
  6082. *
  6083. * @param {Quaternion} qa - The source quaternion.
  6084. * @param {Quaternion} qb - The target quaternion.
  6085. * @param {number} t - The interpolation factor in the closed interval `[0, 1]`.
  6086. * @return {Quaternion} A reference to this quaternion.
  6087. */
  6088. slerpQuaternions( qa, qb, t ) {
  6089. return this.copy( qa ).slerp( qb, t );
  6090. }
  6091. /**
  6092. * Sets this quaternion to a uniformly random, normalized quaternion.
  6093. *
  6094. * @return {Quaternion} A reference to this quaternion.
  6095. */
  6096. random() {
  6097. // Ken Shoemake
  6098. // Uniform random rotations
  6099. // D. Kirk, editor, Graphics Gems III, pages 124-132. Academic Press, New York, 1992.
  6100. const theta1 = 2 * Math.PI * Math.random();
  6101. const theta2 = 2 * Math.PI * Math.random();
  6102. const x0 = Math.random();
  6103. const r1 = Math.sqrt( 1 - x0 );
  6104. const r2 = Math.sqrt( x0 );
  6105. return this.set(
  6106. r1 * Math.sin( theta1 ),
  6107. r1 * Math.cos( theta1 ),
  6108. r2 * Math.sin( theta2 ),
  6109. r2 * Math.cos( theta2 ),
  6110. );
  6111. }
  6112. /**
  6113. * Returns `true` if this quaternion is equal with the given one.
  6114. *
  6115. * @param {Quaternion} quaternion - The quaternion to test for equality.
  6116. * @return {boolean} Whether this quaternion is equal with the given one.
  6117. */
  6118. equals( quaternion ) {
  6119. return ( quaternion._x === this._x ) && ( quaternion._y === this._y ) && ( quaternion._z === this._z ) && ( quaternion._w === this._w );
  6120. }
  6121. /**
  6122. * Sets this quaternion's components from the given array.
  6123. *
  6124. * @param {Array<number>} array - An array holding the quaternion component values.
  6125. * @param {number} [offset=0] - The offset into the array.
  6126. * @return {Quaternion} A reference to this quaternion.
  6127. */
  6128. fromArray( array, offset = 0 ) {
  6129. this._x = array[ offset ];
  6130. this._y = array[ offset + 1 ];
  6131. this._z = array[ offset + 2 ];
  6132. this._w = array[ offset + 3 ];
  6133. this._onChangeCallback();
  6134. return this;
  6135. }
  6136. /**
  6137. * Writes the components of this quaternion to the given array. If no array is provided,
  6138. * the method returns a new instance.
  6139. *
  6140. * @param {Array<number>} [array=[]] - The target array holding the quaternion components.
  6141. * @param {number} [offset=0] - Index of the first element in the array.
  6142. * @return {Array<number>} The quaternion components.
  6143. */
  6144. toArray( array = [], offset = 0 ) {
  6145. array[ offset ] = this._x;
  6146. array[ offset + 1 ] = this._y;
  6147. array[ offset + 2 ] = this._z;
  6148. array[ offset + 3 ] = this._w;
  6149. return array;
  6150. }
  6151. /**
  6152. * Sets the components of this quaternion from the given buffer attribute.
  6153. *
  6154. * @param {BufferAttribute} attribute - The buffer attribute holding quaternion data.
  6155. * @param {number} index - The index into the attribute.
  6156. * @return {Quaternion} A reference to this quaternion.
  6157. */
  6158. fromBufferAttribute( attribute, index ) {
  6159. this._x = attribute.getX( index );
  6160. this._y = attribute.getY( index );
  6161. this._z = attribute.getZ( index );
  6162. this._w = attribute.getW( index );
  6163. this._onChangeCallback();
  6164. return this;
  6165. }
  6166. /**
  6167. * This methods defines the serialization result of this class. Returns the
  6168. * numerical elements of this quaternion in an array of format `[x, y, z, w]`.
  6169. *
  6170. * @return {Array<number>} The serialized quaternion.
  6171. */
  6172. toJSON() {
  6173. return this.toArray();
  6174. }
  6175. _onChange( callback ) {
  6176. this._onChangeCallback = callback;
  6177. return this;
  6178. }
  6179. _onChangeCallback() {}
  6180. *[ Symbol.iterator ]() {
  6181. yield this._x;
  6182. yield this._y;
  6183. yield this._z;
  6184. yield this._w;
  6185. }
  6186. }
  6187. /**
  6188. * Class representing a 3D vector. A 3D vector is an ordered triplet of numbers
  6189. * (labeled x, y and z), which can be used to represent a number of things, such as:
  6190. *
  6191. * - A point in 3D space.
  6192. * - A direction and length in 3D space. In three.js the length will
  6193. * always be the Euclidean distance(straight-line distance) from `(0, 0, 0)` to `(x, y, z)`
  6194. * and the direction is also measured from `(0, 0, 0)` towards `(x, y, z)`.
  6195. * - Any arbitrary ordered triplet of numbers.
  6196. *
  6197. * There are other things a 3D vector can be used to represent, such as
  6198. * momentum vectors and so on, however these are the most
  6199. * common uses in three.js.
  6200. *
  6201. * Iterating through a vector instance will yield its components `(x, y, z)` in
  6202. * the corresponding order.
  6203. * ```js
  6204. * const a = new THREE.Vector3( 0, 1, 0 );
  6205. *
  6206. * //no arguments; will be initialised to (0, 0, 0)
  6207. * const b = new THREE.Vector3( );
  6208. *
  6209. * const d = a.distanceTo( b );
  6210. * ```
  6211. */
  6212. class Vector3 {
  6213. /**
  6214. * Constructs a new 3D vector.
  6215. *
  6216. * @param {number} [x=0] - The x value of this vector.
  6217. * @param {number} [y=0] - The y value of this vector.
  6218. * @param {number} [z=0] - The z value of this vector.
  6219. */
  6220. constructor( x = 0, y = 0, z = 0 ) {
  6221. /**
  6222. * This flag can be used for type testing.
  6223. *
  6224. * @type {boolean}
  6225. * @readonly
  6226. * @default true
  6227. */
  6228. Vector3.prototype.isVector3 = true;
  6229. /**
  6230. * The x value of this vector.
  6231. *
  6232. * @type {number}
  6233. */
  6234. this.x = x;
  6235. /**
  6236. * The y value of this vector.
  6237. *
  6238. * @type {number}
  6239. */
  6240. this.y = y;
  6241. /**
  6242. * The z value of this vector.
  6243. *
  6244. * @type {number}
  6245. */
  6246. this.z = z;
  6247. }
  6248. /**
  6249. * Sets the vector components.
  6250. *
  6251. * @param {number} x - The value of the x component.
  6252. * @param {number} y - The value of the y component.
  6253. * @param {number} z - The value of the z component.
  6254. * @return {Vector3} A reference to this vector.
  6255. */
  6256. set( x, y, z ) {
  6257. if ( z === undefined ) z = this.z; // sprite.scale.set(x,y)
  6258. this.x = x;
  6259. this.y = y;
  6260. this.z = z;
  6261. return this;
  6262. }
  6263. /**
  6264. * Sets the vector components to the same value.
  6265. *
  6266. * @param {number} scalar - The value to set for all vector components.
  6267. * @return {Vector3} A reference to this vector.
  6268. */
  6269. setScalar( scalar ) {
  6270. this.x = scalar;
  6271. this.y = scalar;
  6272. this.z = scalar;
  6273. return this;
  6274. }
  6275. /**
  6276. * Sets the vector's x component to the given value
  6277. *
  6278. * @param {number} x - The value to set.
  6279. * @return {Vector3} A reference to this vector.
  6280. */
  6281. setX( x ) {
  6282. this.x = x;
  6283. return this;
  6284. }
  6285. /**
  6286. * Sets the vector's y component to the given value
  6287. *
  6288. * @param {number} y - The value to set.
  6289. * @return {Vector3} A reference to this vector.
  6290. */
  6291. setY( y ) {
  6292. this.y = y;
  6293. return this;
  6294. }
  6295. /**
  6296. * Sets the vector's z component to the given value
  6297. *
  6298. * @param {number} z - The value to set.
  6299. * @return {Vector3} A reference to this vector.
  6300. */
  6301. setZ( z ) {
  6302. this.z = z;
  6303. return this;
  6304. }
  6305. /**
  6306. * Allows to set a vector component with an index.
  6307. *
  6308. * @param {number} index - The component index. `0` equals to x, `1` equals to y, `2` equals to z.
  6309. * @param {number} value - The value to set.
  6310. * @return {Vector3} A reference to this vector.
  6311. */
  6312. setComponent( index, value ) {
  6313. switch ( index ) {
  6314. case 0: this.x = value; break;
  6315. case 1: this.y = value; break;
  6316. case 2: this.z = value; break;
  6317. default: throw new Error( 'index is out of range: ' + index );
  6318. }
  6319. return this;
  6320. }
  6321. /**
  6322. * Returns the value of the vector component which matches the given index.
  6323. *
  6324. * @param {number} index - The component index. `0` equals to x, `1` equals to y, `2` equals to z.
  6325. * @return {number} A vector component value.
  6326. */
  6327. getComponent( index ) {
  6328. switch ( index ) {
  6329. case 0: return this.x;
  6330. case 1: return this.y;
  6331. case 2: return this.z;
  6332. default: throw new Error( 'index is out of range: ' + index );
  6333. }
  6334. }
  6335. /**
  6336. * Returns a new vector with copied values from this instance.
  6337. *
  6338. * @return {Vector3} A clone of this instance.
  6339. */
  6340. clone() {
  6341. return new this.constructor( this.x, this.y, this.z );
  6342. }
  6343. /**
  6344. * Copies the values of the given vector to this instance.
  6345. *
  6346. * @param {Vector3} v - The vector to copy.
  6347. * @return {Vector3} A reference to this vector.
  6348. */
  6349. copy( v ) {
  6350. this.x = v.x;
  6351. this.y = v.y;
  6352. this.z = v.z;
  6353. return this;
  6354. }
  6355. /**
  6356. * Adds the given vector to this instance.
  6357. *
  6358. * @param {Vector3} v - The vector to add.
  6359. * @return {Vector3} A reference to this vector.
  6360. */
  6361. add( v ) {
  6362. this.x += v.x;
  6363. this.y += v.y;
  6364. this.z += v.z;
  6365. return this;
  6366. }
  6367. /**
  6368. * Adds the given scalar value to all components of this instance.
  6369. *
  6370. * @param {number} s - The scalar to add.
  6371. * @return {Vector3} A reference to this vector.
  6372. */
  6373. addScalar( s ) {
  6374. this.x += s;
  6375. this.y += s;
  6376. this.z += s;
  6377. return this;
  6378. }
  6379. /**
  6380. * Adds the given vectors and stores the result in this instance.
  6381. *
  6382. * @param {Vector3} a - The first vector.
  6383. * @param {Vector3} b - The second vector.
  6384. * @return {Vector3} A reference to this vector.
  6385. */
  6386. addVectors( a, b ) {
  6387. this.x = a.x + b.x;
  6388. this.y = a.y + b.y;
  6389. this.z = a.z + b.z;
  6390. return this;
  6391. }
  6392. /**
  6393. * Adds the given vector scaled by the given factor to this instance.
  6394. *
  6395. * @param {Vector3|Vector4} v - The vector.
  6396. * @param {number} s - The factor that scales `v`.
  6397. * @return {Vector3} A reference to this vector.
  6398. */
  6399. addScaledVector( v, s ) {
  6400. this.x += v.x * s;
  6401. this.y += v.y * s;
  6402. this.z += v.z * s;
  6403. return this;
  6404. }
  6405. /**
  6406. * Subtracts the given vector from this instance.
  6407. *
  6408. * @param {Vector3} v - The vector to subtract.
  6409. * @return {Vector3} A reference to this vector.
  6410. */
  6411. sub( v ) {
  6412. this.x -= v.x;
  6413. this.y -= v.y;
  6414. this.z -= v.z;
  6415. return this;
  6416. }
  6417. /**
  6418. * Subtracts the given scalar value from all components of this instance.
  6419. *
  6420. * @param {number} s - The scalar to subtract.
  6421. * @return {Vector3} A reference to this vector.
  6422. */
  6423. subScalar( s ) {
  6424. this.x -= s;
  6425. this.y -= s;
  6426. this.z -= s;
  6427. return this;
  6428. }
  6429. /**
  6430. * Subtracts the given vectors and stores the result in this instance.
  6431. *
  6432. * @param {Vector3} a - The first vector.
  6433. * @param {Vector3} b - The second vector.
  6434. * @return {Vector3} A reference to this vector.
  6435. */
  6436. subVectors( a, b ) {
  6437. this.x = a.x - b.x;
  6438. this.y = a.y - b.y;
  6439. this.z = a.z - b.z;
  6440. return this;
  6441. }
  6442. /**
  6443. * Multiplies the given vector with this instance.
  6444. *
  6445. * @param {Vector3} v - The vector to multiply.
  6446. * @return {Vector3} A reference to this vector.
  6447. */
  6448. multiply( v ) {
  6449. this.x *= v.x;
  6450. this.y *= v.y;
  6451. this.z *= v.z;
  6452. return this;
  6453. }
  6454. /**
  6455. * Multiplies the given scalar value with all components of this instance.
  6456. *
  6457. * @param {number} scalar - The scalar to multiply.
  6458. * @return {Vector3} A reference to this vector.
  6459. */
  6460. multiplyScalar( scalar ) {
  6461. this.x *= scalar;
  6462. this.y *= scalar;
  6463. this.z *= scalar;
  6464. return this;
  6465. }
  6466. /**
  6467. * Multiplies the given vectors and stores the result in this instance.
  6468. *
  6469. * @param {Vector3} a - The first vector.
  6470. * @param {Vector3} b - The second vector.
  6471. * @return {Vector3} A reference to this vector.
  6472. */
  6473. multiplyVectors( a, b ) {
  6474. this.x = a.x * b.x;
  6475. this.y = a.y * b.y;
  6476. this.z = a.z * b.z;
  6477. return this;
  6478. }
  6479. /**
  6480. * Applies the given Euler rotation to this vector.
  6481. *
  6482. * @param {Euler} euler - The Euler angles.
  6483. * @return {Vector3} A reference to this vector.
  6484. */
  6485. applyEuler( euler ) {
  6486. return this.applyQuaternion( _quaternion$4.setFromEuler( euler ) );
  6487. }
  6488. /**
  6489. * Applies a rotation specified by an axis and an angle to this vector.
  6490. *
  6491. * @param {Vector3} axis - A normalized vector representing the rotation axis.
  6492. * @param {number} angle - The angle in radians.
  6493. * @return {Vector3} A reference to this vector.
  6494. */
  6495. applyAxisAngle( axis, angle ) {
  6496. return this.applyQuaternion( _quaternion$4.setFromAxisAngle( axis, angle ) );
  6497. }
  6498. /**
  6499. * Multiplies this vector with the given 3x3 matrix.
  6500. *
  6501. * @param {Matrix3} m - The 3x3 matrix.
  6502. * @return {Vector3} A reference to this vector.
  6503. */
  6504. applyMatrix3( m ) {
  6505. const x = this.x, y = this.y, z = this.z;
  6506. const e = m.elements;
  6507. this.x = e[ 0 ] * x + e[ 3 ] * y + e[ 6 ] * z;
  6508. this.y = e[ 1 ] * x + e[ 4 ] * y + e[ 7 ] * z;
  6509. this.z = e[ 2 ] * x + e[ 5 ] * y + e[ 8 ] * z;
  6510. return this;
  6511. }
  6512. /**
  6513. * Multiplies this vector by the given normal matrix and normalizes
  6514. * the result.
  6515. *
  6516. * @param {Matrix3} m - The normal matrix.
  6517. * @return {Vector3} A reference to this vector.
  6518. */
  6519. applyNormalMatrix( m ) {
  6520. return this.applyMatrix3( m ).normalize();
  6521. }
  6522. /**
  6523. * Multiplies this vector (with an implicit 1 in the 4th dimension) by m, and
  6524. * divides by perspective.
  6525. *
  6526. * @param {Matrix4} m - The matrix to apply.
  6527. * @return {Vector3} A reference to this vector.
  6528. */
  6529. applyMatrix4( m ) {
  6530. const x = this.x, y = this.y, z = this.z;
  6531. const e = m.elements;
  6532. const w = 1 / ( e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] );
  6533. this.x = ( e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] ) * w;
  6534. this.y = ( e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] ) * w;
  6535. this.z = ( e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] ) * w;
  6536. return this;
  6537. }
  6538. /**
  6539. * Applies the given Quaternion to this vector.
  6540. *
  6541. * @param {Quaternion} q - The Quaternion.
  6542. * @return {Vector3} A reference to this vector.
  6543. */
  6544. applyQuaternion( q ) {
  6545. // quaternion q is assumed to have unit length
  6546. const vx = this.x, vy = this.y, vz = this.z;
  6547. const qx = q.x, qy = q.y, qz = q.z, qw = q.w;
  6548. // t = 2 * cross( q.xyz, v );
  6549. const tx = 2 * ( qy * vz - qz * vy );
  6550. const ty = 2 * ( qz * vx - qx * vz );
  6551. const tz = 2 * ( qx * vy - qy * vx );
  6552. // v + q.w * t + cross( q.xyz, t );
  6553. this.x = vx + qw * tx + qy * tz - qz * ty;
  6554. this.y = vy + qw * ty + qz * tx - qx * tz;
  6555. this.z = vz + qw * tz + qx * ty - qy * tx;
  6556. return this;
  6557. }
  6558. /**
  6559. * Projects this vector from world space into the camera's normalized
  6560. * device coordinate (NDC) space.
  6561. *
  6562. * @param {Camera} camera - The camera.
  6563. * @return {Vector3} A reference to this vector.
  6564. */
  6565. project( camera ) {
  6566. return this.applyMatrix4( camera.matrixWorldInverse ).applyMatrix4( camera.projectionMatrix );
  6567. }
  6568. /**
  6569. * Unprojects this vector from the camera's normalized device coordinate (NDC)
  6570. * space into world space.
  6571. *
  6572. * @param {Camera} camera - The camera.
  6573. * @return {Vector3} A reference to this vector.
  6574. */
  6575. unproject( camera ) {
  6576. return this.applyMatrix4( camera.projectionMatrixInverse ).applyMatrix4( camera.matrixWorld );
  6577. }
  6578. /**
  6579. * Transforms the direction of this vector by a matrix (the upper left 3 x 3
  6580. * subset of the given 4x4 matrix and then normalizes the result.
  6581. *
  6582. * @param {Matrix4} m - The matrix.
  6583. * @return {Vector3} A reference to this vector.
  6584. */
  6585. transformDirection( m ) {
  6586. // input: THREE.Matrix4 affine matrix
  6587. // vector interpreted as a direction
  6588. const x = this.x, y = this.y, z = this.z;
  6589. const e = m.elements;
  6590. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z;
  6591. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z;
  6592. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z;
  6593. return this.normalize();
  6594. }
  6595. /**
  6596. * Divides this instance by the given vector.
  6597. *
  6598. * @param {Vector3} v - The vector to divide.
  6599. * @return {Vector3} A reference to this vector.
  6600. */
  6601. divide( v ) {
  6602. this.x /= v.x;
  6603. this.y /= v.y;
  6604. this.z /= v.z;
  6605. return this;
  6606. }
  6607. /**
  6608. * Divides this vector by the given scalar.
  6609. *
  6610. * @param {number} scalar - The scalar to divide.
  6611. * @return {Vector3} A reference to this vector.
  6612. */
  6613. divideScalar( scalar ) {
  6614. return this.multiplyScalar( 1 / scalar );
  6615. }
  6616. /**
  6617. * If this vector's x, y or z value is greater than the given vector's x, y or z
  6618. * value, replace that value with the corresponding min value.
  6619. *
  6620. * @param {Vector3} v - The vector.
  6621. * @return {Vector3} A reference to this vector.
  6622. */
  6623. min( v ) {
  6624. this.x = Math.min( this.x, v.x );
  6625. this.y = Math.min( this.y, v.y );
  6626. this.z = Math.min( this.z, v.z );
  6627. return this;
  6628. }
  6629. /**
  6630. * If this vector's x, y or z value is less than the given vector's x, y or z
  6631. * value, replace that value with the corresponding max value.
  6632. *
  6633. * @param {Vector3} v - The vector.
  6634. * @return {Vector3} A reference to this vector.
  6635. */
  6636. max( v ) {
  6637. this.x = Math.max( this.x, v.x );
  6638. this.y = Math.max( this.y, v.y );
  6639. this.z = Math.max( this.z, v.z );
  6640. return this;
  6641. }
  6642. /**
  6643. * If this vector's x, y or z value is greater than the max vector's x, y or z
  6644. * value, it is replaced by the corresponding value.
  6645. * If this vector's x, y or z value is less than the min vector's x, y or z value,
  6646. * it is replaced by the corresponding value.
  6647. *
  6648. * @param {Vector3} min - The minimum x, y and z values.
  6649. * @param {Vector3} max - The maximum x, y and z values in the desired range.
  6650. * @return {Vector3} A reference to this vector.
  6651. */
  6652. clamp( min, max ) {
  6653. // assumes min < max, componentwise
  6654. this.x = clamp( this.x, min.x, max.x );
  6655. this.y = clamp( this.y, min.y, max.y );
  6656. this.z = clamp( this.z, min.z, max.z );
  6657. return this;
  6658. }
  6659. /**
  6660. * If this vector's x, y or z values are greater than the max value, they are
  6661. * replaced by the max value.
  6662. * If this vector's x, y or z values are less than the min value, they are
  6663. * replaced by the min value.
  6664. *
  6665. * @param {number} minVal - The minimum value the components will be clamped to.
  6666. * @param {number} maxVal - The maximum value the components will be clamped to.
  6667. * @return {Vector3} A reference to this vector.
  6668. */
  6669. clampScalar( minVal, maxVal ) {
  6670. this.x = clamp( this.x, minVal, maxVal );
  6671. this.y = clamp( this.y, minVal, maxVal );
  6672. this.z = clamp( this.z, minVal, maxVal );
  6673. return this;
  6674. }
  6675. /**
  6676. * If this vector's length is greater than the max value, it is replaced by
  6677. * the max value.
  6678. * If this vector's length is less than the min value, it is replaced by the
  6679. * min value.
  6680. *
  6681. * @param {number} min - The minimum value the vector length will be clamped to.
  6682. * @param {number} max - The maximum value the vector length will be clamped to.
  6683. * @return {Vector3} A reference to this vector.
  6684. */
  6685. clampLength( min, max ) {
  6686. const length = this.length();
  6687. return this.divideScalar( length || 1 ).multiplyScalar( clamp( length, min, max ) );
  6688. }
  6689. /**
  6690. * The components of this vector are rounded down to the nearest integer value.
  6691. *
  6692. * @return {Vector3} A reference to this vector.
  6693. */
  6694. floor() {
  6695. this.x = Math.floor( this.x );
  6696. this.y = Math.floor( this.y );
  6697. this.z = Math.floor( this.z );
  6698. return this;
  6699. }
  6700. /**
  6701. * The components of this vector are rounded up to the nearest integer value.
  6702. *
  6703. * @return {Vector3} A reference to this vector.
  6704. */
  6705. ceil() {
  6706. this.x = Math.ceil( this.x );
  6707. this.y = Math.ceil( this.y );
  6708. this.z = Math.ceil( this.z );
  6709. return this;
  6710. }
  6711. /**
  6712. * The components of this vector are rounded to the nearest integer value
  6713. *
  6714. * @return {Vector3} A reference to this vector.
  6715. */
  6716. round() {
  6717. this.x = Math.round( this.x );
  6718. this.y = Math.round( this.y );
  6719. this.z = Math.round( this.z );
  6720. return this;
  6721. }
  6722. /**
  6723. * The components of this vector are rounded towards zero (up if negative,
  6724. * down if positive) to an integer value.
  6725. *
  6726. * @return {Vector3} A reference to this vector.
  6727. */
  6728. roundToZero() {
  6729. this.x = Math.trunc( this.x );
  6730. this.y = Math.trunc( this.y );
  6731. this.z = Math.trunc( this.z );
  6732. return this;
  6733. }
  6734. /**
  6735. * Inverts this vector - i.e. sets x = -x, y = -y and z = -z.
  6736. *
  6737. * @return {Vector3} A reference to this vector.
  6738. */
  6739. negate() {
  6740. this.x = - this.x;
  6741. this.y = - this.y;
  6742. this.z = - this.z;
  6743. return this;
  6744. }
  6745. /**
  6746. * Calculates the dot product of the given vector with this instance.
  6747. *
  6748. * @param {Vector3} v - The vector to compute the dot product with.
  6749. * @return {number} The result of the dot product.
  6750. */
  6751. dot( v ) {
  6752. return this.x * v.x + this.y * v.y + this.z * v.z;
  6753. }
  6754. // TODO lengthSquared?
  6755. /**
  6756. * Computes the square of the Euclidean length (straight-line length) from
  6757. * (0, 0, 0) to (x, y, z). If you are comparing the lengths of vectors, you should
  6758. * compare the length squared instead as it is slightly more efficient to calculate.
  6759. *
  6760. * @return {number} The square length of this vector.
  6761. */
  6762. lengthSq() {
  6763. return this.x * this.x + this.y * this.y + this.z * this.z;
  6764. }
  6765. /**
  6766. * Computes the Euclidean length (straight-line length) from (0, 0, 0) to (x, y, z).
  6767. *
  6768. * @return {number} The length of this vector.
  6769. */
  6770. length() {
  6771. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z );
  6772. }
  6773. /**
  6774. * Computes the Manhattan length of this vector.
  6775. *
  6776. * @return {number} The length of this vector.
  6777. */
  6778. manhattanLength() {
  6779. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z );
  6780. }
  6781. /**
  6782. * Converts this vector to a unit vector - that is, sets it equal to a vector
  6783. * with the same direction as this one, but with a vector length of `1`.
  6784. *
  6785. * @return {Vector3} A reference to this vector.
  6786. */
  6787. normalize() {
  6788. return this.divideScalar( this.length() || 1 );
  6789. }
  6790. /**
  6791. * Sets this vector to a vector with the same direction as this one, but
  6792. * with the specified length.
  6793. *
  6794. * @param {number} length - The new length of this vector.
  6795. * @return {Vector3} A reference to this vector.
  6796. */
  6797. setLength( length ) {
  6798. return this.normalize().multiplyScalar( length );
  6799. }
  6800. /**
  6801. * Linearly interpolates between the given vector and this instance, where
  6802. * alpha is the percent distance along the line - alpha = 0 will be this
  6803. * vector, and alpha = 1 will be the given one.
  6804. *
  6805. * @param {Vector3} v - The vector to interpolate towards.
  6806. * @param {number} alpha - The interpolation factor, typically in the closed interval `[0, 1]`.
  6807. * @return {Vector3} A reference to this vector.
  6808. */
  6809. lerp( v, alpha ) {
  6810. this.x += ( v.x - this.x ) * alpha;
  6811. this.y += ( v.y - this.y ) * alpha;
  6812. this.z += ( v.z - this.z ) * alpha;
  6813. return this;
  6814. }
  6815. /**
  6816. * Linearly interpolates between the given vectors, where alpha is the percent
  6817. * distance along the line - alpha = 0 will be first vector, and alpha = 1 will
  6818. * be the second one. The result is stored in this instance.
  6819. *
  6820. * @param {Vector3} v1 - The first vector.
  6821. * @param {Vector3} v2 - The second vector.
  6822. * @param {number} alpha - The interpolation factor, typically in the closed interval `[0, 1]`.
  6823. * @return {Vector3} A reference to this vector.
  6824. */
  6825. lerpVectors( v1, v2, alpha ) {
  6826. this.x = v1.x + ( v2.x - v1.x ) * alpha;
  6827. this.y = v1.y + ( v2.y - v1.y ) * alpha;
  6828. this.z = v1.z + ( v2.z - v1.z ) * alpha;
  6829. return this;
  6830. }
  6831. /**
  6832. * Calculates the cross product of the given vector with this instance.
  6833. *
  6834. * @param {Vector3} v - The vector to compute the cross product with.
  6835. * @return {Vector3} The result of the cross product.
  6836. */
  6837. cross( v ) {
  6838. return this.crossVectors( this, v );
  6839. }
  6840. /**
  6841. * Calculates the cross product of the given vectors and stores the result
  6842. * in this instance.
  6843. *
  6844. * @param {Vector3} a - The first vector.
  6845. * @param {Vector3} b - The second vector.
  6846. * @return {Vector3} A reference to this vector.
  6847. */
  6848. crossVectors( a, b ) {
  6849. const ax = a.x, ay = a.y, az = a.z;
  6850. const bx = b.x, by = b.y, bz = b.z;
  6851. this.x = ay * bz - az * by;
  6852. this.y = az * bx - ax * bz;
  6853. this.z = ax * by - ay * bx;
  6854. return this;
  6855. }
  6856. /**
  6857. * Projects this vector onto the given one.
  6858. *
  6859. * @param {Vector3} v - The vector to project to.
  6860. * @return {Vector3} A reference to this vector.
  6861. */
  6862. projectOnVector( v ) {
  6863. const denominator = v.lengthSq();
  6864. if ( denominator === 0 ) return this.set( 0, 0, 0 );
  6865. const scalar = v.dot( this ) / denominator;
  6866. return this.copy( v ).multiplyScalar( scalar );
  6867. }
  6868. /**
  6869. * Projects this vector onto a plane by subtracting this
  6870. * vector projected onto the plane's normal from this vector.
  6871. *
  6872. * @param {Vector3} planeNormal - The plane normal.
  6873. * @return {Vector3} A reference to this vector.
  6874. */
  6875. projectOnPlane( planeNormal ) {
  6876. _vector$c.copy( this ).projectOnVector( planeNormal );
  6877. return this.sub( _vector$c );
  6878. }
  6879. /**
  6880. * Reflects this vector off a plane orthogonal to the given normal vector.
  6881. *
  6882. * @param {Vector3} normal - The (normalized) normal vector.
  6883. * @return {Vector3} A reference to this vector.
  6884. */
  6885. reflect( normal ) {
  6886. return this.sub( _vector$c.copy( normal ).multiplyScalar( 2 * this.dot( normal ) ) );
  6887. }
  6888. /**
  6889. * Returns the angle between the given vector and this instance in radians.
  6890. *
  6891. * @param {Vector3} v - The vector to compute the angle with.
  6892. * @return {number} The angle in radians.
  6893. */
  6894. angleTo( v ) {
  6895. const denominator = Math.sqrt( this.lengthSq() * v.lengthSq() );
  6896. if ( denominator === 0 ) return Math.PI / 2;
  6897. const theta = this.dot( v ) / denominator;
  6898. // clamp, to handle numerical problems
  6899. return Math.acos( clamp( theta, -1, 1 ) );
  6900. }
  6901. /**
  6902. * Computes the distance from the given vector to this instance.
  6903. *
  6904. * @param {Vector3} v - The vector to compute the distance to.
  6905. * @return {number} The distance.
  6906. */
  6907. distanceTo( v ) {
  6908. return Math.sqrt( this.distanceToSquared( v ) );
  6909. }
  6910. /**
  6911. * Computes the squared distance from the given vector to this instance.
  6912. * If you are just comparing the distance with another distance, you should compare
  6913. * the distance squared instead as it is slightly more efficient to calculate.
  6914. *
  6915. * @param {Vector3} v - The vector to compute the squared distance to.
  6916. * @return {number} The squared distance.
  6917. */
  6918. distanceToSquared( v ) {
  6919. const dx = this.x - v.x, dy = this.y - v.y, dz = this.z - v.z;
  6920. return dx * dx + dy * dy + dz * dz;
  6921. }
  6922. /**
  6923. * Computes the Manhattan distance from the given vector to this instance.
  6924. *
  6925. * @param {Vector3} v - The vector to compute the Manhattan distance to.
  6926. * @return {number} The Manhattan distance.
  6927. */
  6928. manhattanDistanceTo( v ) {
  6929. return Math.abs( this.x - v.x ) + Math.abs( this.y - v.y ) + Math.abs( this.z - v.z );
  6930. }
  6931. /**
  6932. * Sets the vector components from the given spherical coordinates.
  6933. *
  6934. * @param {Spherical} s - The spherical coordinates.
  6935. * @return {Vector3} A reference to this vector.
  6936. */
  6937. setFromSpherical( s ) {
  6938. return this.setFromSphericalCoords( s.radius, s.phi, s.theta );
  6939. }
  6940. /**
  6941. * Sets the vector components from the given spherical coordinates.
  6942. *
  6943. * @param {number} radius - The radius.
  6944. * @param {number} phi - The phi angle in radians.
  6945. * @param {number} theta - The theta angle in radians.
  6946. * @return {Vector3} A reference to this vector.
  6947. */
  6948. setFromSphericalCoords( radius, phi, theta ) {
  6949. const sinPhiRadius = Math.sin( phi ) * radius;
  6950. this.x = sinPhiRadius * Math.sin( theta );
  6951. this.y = Math.cos( phi ) * radius;
  6952. this.z = sinPhiRadius * Math.cos( theta );
  6953. return this;
  6954. }
  6955. /**
  6956. * Sets the vector components from the given cylindrical coordinates.
  6957. *
  6958. * @param {Cylindrical} c - The cylindrical coordinates.
  6959. * @return {Vector3} A reference to this vector.
  6960. */
  6961. setFromCylindrical( c ) {
  6962. return this.setFromCylindricalCoords( c.radius, c.theta, c.y );
  6963. }
  6964. /**
  6965. * Sets the vector components from the given cylindrical coordinates.
  6966. *
  6967. * @param {number} radius - The radius.
  6968. * @param {number} theta - The theta angle in radians.
  6969. * @param {number} y - The y value.
  6970. * @return {Vector3} A reference to this vector.
  6971. */
  6972. setFromCylindricalCoords( radius, theta, y ) {
  6973. this.x = radius * Math.sin( theta );
  6974. this.y = y;
  6975. this.z = radius * Math.cos( theta );
  6976. return this;
  6977. }
  6978. /**
  6979. * Sets the vector components to the position elements of the
  6980. * given transformation matrix.
  6981. *
  6982. * @param {Matrix4} m - The 4x4 matrix.
  6983. * @return {Vector3} A reference to this vector.
  6984. */
  6985. setFromMatrixPosition( m ) {
  6986. const e = m.elements;
  6987. this.x = e[ 12 ];
  6988. this.y = e[ 13 ];
  6989. this.z = e[ 14 ];
  6990. return this;
  6991. }
  6992. /**
  6993. * Sets the vector components to the scale elements of the
  6994. * given transformation matrix.
  6995. *
  6996. * @param {Matrix4} m - The 4x4 matrix.
  6997. * @return {Vector3} A reference to this vector.
  6998. */
  6999. setFromMatrixScale( m ) {
  7000. const sx = this.setFromMatrixColumn( m, 0 ).length();
  7001. const sy = this.setFromMatrixColumn( m, 1 ).length();
  7002. const sz = this.setFromMatrixColumn( m, 2 ).length();
  7003. this.x = sx;
  7004. this.y = sy;
  7005. this.z = sz;
  7006. return this;
  7007. }
  7008. /**
  7009. * Sets the vector components from the specified matrix column.
  7010. *
  7011. * @param {Matrix4} m - The 4x4 matrix.
  7012. * @param {number} index - The column index.
  7013. * @return {Vector3} A reference to this vector.
  7014. */
  7015. setFromMatrixColumn( m, index ) {
  7016. return this.fromArray( m.elements, index * 4 );
  7017. }
  7018. /**
  7019. * Sets the vector components from the specified matrix column.
  7020. *
  7021. * @param {Matrix3} m - The 3x3 matrix.
  7022. * @param {number} index - The column index.
  7023. * @return {Vector3} A reference to this vector.
  7024. */
  7025. setFromMatrix3Column( m, index ) {
  7026. return this.fromArray( m.elements, index * 3 );
  7027. }
  7028. /**
  7029. * Sets the vector components from the given Euler angles.
  7030. *
  7031. * @param {Euler} e - The Euler angles to set.
  7032. * @return {Vector3} A reference to this vector.
  7033. */
  7034. setFromEuler( e ) {
  7035. this.x = e._x;
  7036. this.y = e._y;
  7037. this.z = e._z;
  7038. return this;
  7039. }
  7040. /**
  7041. * Sets the vector components from the RGB components of the
  7042. * given color.
  7043. *
  7044. * @param {Color} c - The color to set.
  7045. * @return {Vector3} A reference to this vector.
  7046. */
  7047. setFromColor( c ) {
  7048. this.x = c.r;
  7049. this.y = c.g;
  7050. this.z = c.b;
  7051. return this;
  7052. }
  7053. /**
  7054. * Returns `true` if this vector is equal with the given one.
  7055. *
  7056. * @param {Vector3} v - The vector to test for equality.
  7057. * @return {boolean} Whether this vector is equal with the given one.
  7058. */
  7059. equals( v ) {
  7060. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) );
  7061. }
  7062. /**
  7063. * Sets this vector's x value to be `array[ offset ]`, y value to be `array[ offset + 1 ]`
  7064. * and z value to be `array[ offset + 2 ]`.
  7065. *
  7066. * @param {Array<number>} array - An array holding the vector component values.
  7067. * @param {number} [offset=0] - The offset into the array.
  7068. * @return {Vector3} A reference to this vector.
  7069. */
  7070. fromArray( array, offset = 0 ) {
  7071. this.x = array[ offset ];
  7072. this.y = array[ offset + 1 ];
  7073. this.z = array[ offset + 2 ];
  7074. return this;
  7075. }
  7076. /**
  7077. * Writes the components of this vector to the given array. If no array is provided,
  7078. * the method returns a new instance.
  7079. *
  7080. * @param {Array<number>} [array=[]] - The target array holding the vector components.
  7081. * @param {number} [offset=0] - Index of the first element in the array.
  7082. * @return {Array<number>} The vector components.
  7083. */
  7084. toArray( array = [], offset = 0 ) {
  7085. array[ offset ] = this.x;
  7086. array[ offset + 1 ] = this.y;
  7087. array[ offset + 2 ] = this.z;
  7088. return array;
  7089. }
  7090. /**
  7091. * Sets the components of this vector from the given buffer attribute.
  7092. *
  7093. * @param {BufferAttribute} attribute - The buffer attribute holding vector data.
  7094. * @param {number} index - The index into the attribute.
  7095. * @return {Vector3} A reference to this vector.
  7096. */
  7097. fromBufferAttribute( attribute, index ) {
  7098. this.x = attribute.getX( index );
  7099. this.y = attribute.getY( index );
  7100. this.z = attribute.getZ( index );
  7101. return this;
  7102. }
  7103. /**
  7104. * Sets each component of this vector to a pseudo-random value between `0` and
  7105. * `1`, excluding `1`.
  7106. *
  7107. * @return {Vector3} A reference to this vector.
  7108. */
  7109. random() {
  7110. this.x = Math.random();
  7111. this.y = Math.random();
  7112. this.z = Math.random();
  7113. return this;
  7114. }
  7115. /**
  7116. * Sets this vector to a uniformly random point on a unit sphere.
  7117. *
  7118. * @return {Vector3} A reference to this vector.
  7119. */
  7120. randomDirection() {
  7121. // https://mathworld.wolfram.com/SpherePointPicking.html
  7122. const theta = Math.random() * Math.PI * 2;
  7123. const u = Math.random() * 2 - 1;
  7124. const c = Math.sqrt( 1 - u * u );
  7125. this.x = c * Math.cos( theta );
  7126. this.y = u;
  7127. this.z = c * Math.sin( theta );
  7128. return this;
  7129. }
  7130. *[ Symbol.iterator ]() {
  7131. yield this.x;
  7132. yield this.y;
  7133. yield this.z;
  7134. }
  7135. }
  7136. const _vector$c = /*@__PURE__*/ new Vector3();
  7137. const _quaternion$4 = /*@__PURE__*/ new Quaternion();
  7138. /**
  7139. * Represents an axis-aligned bounding box (AABB) in 3D space.
  7140. */
  7141. class Box3 {
  7142. /**
  7143. * Constructs a new bounding box.
  7144. *
  7145. * @param {Vector3} [min=(Infinity,Infinity,Infinity)] - A vector representing the lower boundary of the box.
  7146. * @param {Vector3} [max=(-Infinity,-Infinity,-Infinity)] - A vector representing the upper boundary of the box.
  7147. */
  7148. constructor( min = new Vector3( + Infinity, + Infinity, + Infinity ), max = new Vector3( - Infinity, - Infinity, - Infinity ) ) {
  7149. /**
  7150. * This flag can be used for type testing.
  7151. *
  7152. * @type {boolean}
  7153. * @readonly
  7154. * @default true
  7155. */
  7156. this.isBox3 = true;
  7157. /**
  7158. * The lower boundary of the box.
  7159. *
  7160. * @type {Vector3}
  7161. */
  7162. this.min = min;
  7163. /**
  7164. * The upper boundary of the box.
  7165. *
  7166. * @type {Vector3}
  7167. */
  7168. this.max = max;
  7169. }
  7170. /**
  7171. * Sets the lower and upper boundaries of this box.
  7172. * Please note that this method only copies the values from the given objects.
  7173. *
  7174. * @param {Vector3} min - The lower boundary of the box.
  7175. * @param {Vector3} max - The upper boundary of the box.
  7176. * @return {Box3} A reference to this bounding box.
  7177. */
  7178. set( min, max ) {
  7179. this.min.copy( min );
  7180. this.max.copy( max );
  7181. return this;
  7182. }
  7183. /**
  7184. * Sets the upper and lower bounds of this box so it encloses the position data
  7185. * in the given array.
  7186. *
  7187. * @param {Array<number>} array - An array holding 3D position data.
  7188. * @return {Box3} A reference to this bounding box.
  7189. */
  7190. setFromArray( array ) {
  7191. this.makeEmpty();
  7192. for ( let i = 0, il = array.length; i < il; i += 3 ) {
  7193. this.expandByPoint( _vector$b.fromArray( array, i ) );
  7194. }
  7195. return this;
  7196. }
  7197. /**
  7198. * Sets the upper and lower bounds of this box so it encloses the position data
  7199. * in the given buffer attribute.
  7200. *
  7201. * @param {BufferAttribute} attribute - A buffer attribute holding 3D position data.
  7202. * @return {Box3} A reference to this bounding box.
  7203. */
  7204. setFromBufferAttribute( attribute ) {
  7205. this.makeEmpty();
  7206. for ( let i = 0, il = attribute.count; i < il; i ++ ) {
  7207. this.expandByPoint( _vector$b.fromBufferAttribute( attribute, i ) );
  7208. }
  7209. return this;
  7210. }
  7211. /**
  7212. * Sets the upper and lower bounds of this box so it encloses the position data
  7213. * in the given array.
  7214. *
  7215. * @param {Array<Vector3>} points - An array holding 3D position data as instances of {@link Vector3}.
  7216. * @return {Box3} A reference to this bounding box.
  7217. */
  7218. setFromPoints( points ) {
  7219. this.makeEmpty();
  7220. for ( let i = 0, il = points.length; i < il; i ++ ) {
  7221. this.expandByPoint( points[ i ] );
  7222. }
  7223. return this;
  7224. }
  7225. /**
  7226. * Centers this box on the given center vector and sets this box's width, height and
  7227. * depth to the given size values.
  7228. *
  7229. * @param {Vector3} center - The center of the box.
  7230. * @param {Vector3} size - The x, y and z dimensions of the box.
  7231. * @return {Box3} A reference to this bounding box.
  7232. */
  7233. setFromCenterAndSize( center, size ) {
  7234. const halfSize = _vector$b.copy( size ).multiplyScalar( 0.5 );
  7235. this.min.copy( center ).sub( halfSize );
  7236. this.max.copy( center ).add( halfSize );
  7237. return this;
  7238. }
  7239. /**
  7240. * Computes the world-axis-aligned bounding box for the given 3D object
  7241. * (including its children), accounting for the object's, and children's,
  7242. * world transforms. The function may result in a larger box than strictly necessary.
  7243. *
  7244. * @param {Object3D} object - The 3D object to compute the bounding box for.
  7245. * @param {boolean} [precise=false] - If set to `true`, the method computes the smallest
  7246. * world-axis-aligned bounding box at the expense of more computation.
  7247. * @return {Box3} A reference to this bounding box.
  7248. */
  7249. setFromObject( object, precise = false ) {
  7250. this.makeEmpty();
  7251. return this.expandByObject( object, precise );
  7252. }
  7253. /**
  7254. * Returns a new box with copied values from this instance.
  7255. *
  7256. * @return {Box3} A clone of this instance.
  7257. */
  7258. clone() {
  7259. return new this.constructor().copy( this );
  7260. }
  7261. /**
  7262. * Copies the values of the given box to this instance.
  7263. *
  7264. * @param {Box3} box - The box to copy.
  7265. * @return {Box3} A reference to this bounding box.
  7266. */
  7267. copy( box ) {
  7268. this.min.copy( box.min );
  7269. this.max.copy( box.max );
  7270. return this;
  7271. }
  7272. /**
  7273. * Makes this box empty which means in encloses a zero space in 3D.
  7274. *
  7275. * @return {Box3} A reference to this bounding box.
  7276. */
  7277. makeEmpty() {
  7278. this.min.x = this.min.y = this.min.z = + Infinity;
  7279. this.max.x = this.max.y = this.max.z = - Infinity;
  7280. return this;
  7281. }
  7282. /**
  7283. * Returns true if this box includes zero points within its bounds.
  7284. * Note that a box with equal lower and upper bounds still includes one
  7285. * point, the one both bounds share.
  7286. *
  7287. * @return {boolean} Whether this box is empty or not.
  7288. */
  7289. isEmpty() {
  7290. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  7291. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y ) || ( this.max.z < this.min.z );
  7292. }
  7293. /**
  7294. * Returns the center point of this box.
  7295. *
  7296. * @param {Vector3} target - The target vector that is used to store the method's result.
  7297. * @return {Vector3} The center point.
  7298. */
  7299. getCenter( target ) {
  7300. return this.isEmpty() ? target.set( 0, 0, 0 ) : target.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  7301. }
  7302. /**
  7303. * Returns the dimensions of this box.
  7304. *
  7305. * @param {Vector3} target - The target vector that is used to store the method's result.
  7306. * @return {Vector3} The size.
  7307. */
  7308. getSize( target ) {
  7309. return this.isEmpty() ? target.set( 0, 0, 0 ) : target.subVectors( this.max, this.min );
  7310. }
  7311. /**
  7312. * Expands the boundaries of this box to include the given point.
  7313. *
  7314. * @param {Vector3} point - The point that should be included by the bounding box.
  7315. * @return {Box3} A reference to this bounding box.
  7316. */
  7317. expandByPoint( point ) {
  7318. this.min.min( point );
  7319. this.max.max( point );
  7320. return this;
  7321. }
  7322. /**
  7323. * Expands this box equilaterally by the given vector. The width of this
  7324. * box will be expanded by the x component of the vector in both
  7325. * directions. The height of this box will be expanded by the y component of
  7326. * the vector in both directions. The depth of this box will be
  7327. * expanded by the z component of the vector in both directions.
  7328. *
  7329. * @param {Vector3} vector - The vector that should expand the bounding box.
  7330. * @return {Box3} A reference to this bounding box.
  7331. */
  7332. expandByVector( vector ) {
  7333. this.min.sub( vector );
  7334. this.max.add( vector );
  7335. return this;
  7336. }
  7337. /**
  7338. * Expands each dimension of the box by the given scalar. If negative, the
  7339. * dimensions of the box will be contracted.
  7340. *
  7341. * @param {number} scalar - The scalar value that should expand the bounding box.
  7342. * @return {Box3} A reference to this bounding box.
  7343. */
  7344. expandByScalar( scalar ) {
  7345. this.min.addScalar( - scalar );
  7346. this.max.addScalar( scalar );
  7347. return this;
  7348. }
  7349. /**
  7350. * Expands the boundaries of this box to include the given 3D object and
  7351. * its children, accounting for the object's, and children's, world
  7352. * transforms. The function may result in a larger box than strictly
  7353. * necessary (unless the precise parameter is set to true).
  7354. *
  7355. * @param {Object3D} object - The 3D object that should expand the bounding box.
  7356. * @param {boolean} precise - If set to `true`, the method expands the bounding box
  7357. * as little as necessary at the expense of more computation.
  7358. * @return {Box3} A reference to this bounding box.
  7359. */
  7360. expandByObject( object, precise = false ) {
  7361. // Computes the world-axis-aligned bounding box of an object (including its children),
  7362. // accounting for both the object's, and children's, world transforms
  7363. object.updateWorldMatrix( false, false );
  7364. const geometry = object.geometry;
  7365. if ( geometry !== undefined ) {
  7366. const positionAttribute = geometry.getAttribute( 'position' );
  7367. // precise AABB computation based on vertex data requires at least a position attribute.
  7368. // instancing isn't supported so far and uses the normal (conservative) code path.
  7369. if ( precise === true && positionAttribute !== undefined && object.isInstancedMesh !== true ) {
  7370. for ( let i = 0, l = positionAttribute.count; i < l; i ++ ) {
  7371. if ( object.isMesh === true ) {
  7372. object.getVertexPosition( i, _vector$b );
  7373. } else {
  7374. _vector$b.fromBufferAttribute( positionAttribute, i );
  7375. }
  7376. _vector$b.applyMatrix4( object.matrixWorld );
  7377. this.expandByPoint( _vector$b );
  7378. }
  7379. } else {
  7380. if ( object.boundingBox !== undefined ) {
  7381. // object-level bounding box
  7382. if ( object.boundingBox === null ) {
  7383. object.computeBoundingBox();
  7384. }
  7385. _box$4.copy( object.boundingBox );
  7386. } else {
  7387. // geometry-level bounding box
  7388. if ( geometry.boundingBox === null ) {
  7389. geometry.computeBoundingBox();
  7390. }
  7391. _box$4.copy( geometry.boundingBox );
  7392. }
  7393. _box$4.applyMatrix4( object.matrixWorld );
  7394. this.union( _box$4 );
  7395. }
  7396. }
  7397. const children = object.children;
  7398. for ( let i = 0, l = children.length; i < l; i ++ ) {
  7399. this.expandByObject( children[ i ], precise );
  7400. }
  7401. return this;
  7402. }
  7403. /**
  7404. * Returns `true` if the given point lies within or on the boundaries of this box.
  7405. *
  7406. * @param {Vector3} point - The point to test.
  7407. * @return {boolean} Whether the bounding box contains the given point or not.
  7408. */
  7409. containsPoint( point ) {
  7410. return point.x >= this.min.x && point.x <= this.max.x &&
  7411. point.y >= this.min.y && point.y <= this.max.y &&
  7412. point.z >= this.min.z && point.z <= this.max.z;
  7413. }
  7414. /**
  7415. * Returns `true` if this bounding box includes the entirety of the given bounding box.
  7416. * If this box and the given one are identical, this function also returns `true`.
  7417. *
  7418. * @param {Box3} box - The bounding box to test.
  7419. * @return {boolean} Whether the bounding box contains the given bounding box or not.
  7420. */
  7421. containsBox( box ) {
  7422. return this.min.x <= box.min.x && box.max.x <= this.max.x &&
  7423. this.min.y <= box.min.y && box.max.y <= this.max.y &&
  7424. this.min.z <= box.min.z && box.max.z <= this.max.z;
  7425. }
  7426. /**
  7427. * Returns a point as a proportion of this box's width, height and depth.
  7428. *
  7429. * @param {Vector3} point - A point in 3D space.
  7430. * @param {Vector3} target - The target vector that is used to store the method's result.
  7431. * @return {Vector3} A point as a proportion of this box's width, height and depth.
  7432. */
  7433. getParameter( point, target ) {
  7434. // This can potentially have a divide by zero if the box
  7435. // has a size dimension of 0.
  7436. return target.set(
  7437. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  7438. ( point.y - this.min.y ) / ( this.max.y - this.min.y ),
  7439. ( point.z - this.min.z ) / ( this.max.z - this.min.z )
  7440. );
  7441. }
  7442. /**
  7443. * Returns `true` if the given bounding box intersects with this bounding box.
  7444. *
  7445. * @param {Box3} box - The bounding box to test.
  7446. * @return {boolean} Whether the given bounding box intersects with this bounding box.
  7447. */
  7448. intersectsBox( box ) {
  7449. // using 6 splitting planes to rule out intersections.
  7450. return box.max.x >= this.min.x && box.min.x <= this.max.x &&
  7451. box.max.y >= this.min.y && box.min.y <= this.max.y &&
  7452. box.max.z >= this.min.z && box.min.z <= this.max.z;
  7453. }
  7454. /**
  7455. * Returns `true` if the given bounding sphere intersects with this bounding box.
  7456. *
  7457. * @param {Sphere} sphere - The bounding sphere to test.
  7458. * @return {boolean} Whether the given bounding sphere intersects with this bounding box.
  7459. */
  7460. intersectsSphere( sphere ) {
  7461. // Find the point on the AABB closest to the sphere center.
  7462. this.clampPoint( sphere.center, _vector$b );
  7463. // If that point is inside the sphere, the AABB and sphere intersect.
  7464. return _vector$b.distanceToSquared( sphere.center ) <= ( sphere.radius * sphere.radius );
  7465. }
  7466. /**
  7467. * Returns `true` if the given plane intersects with this bounding box.
  7468. *
  7469. * @param {Plane} plane - The plane to test.
  7470. * @return {boolean} Whether the given plane intersects with this bounding box.
  7471. */
  7472. intersectsPlane( plane ) {
  7473. // We compute the minimum and maximum dot product values. If those values
  7474. // are on the same side (back or front) of the plane, then there is no intersection.
  7475. let min, max;
  7476. if ( plane.normal.x > 0 ) {
  7477. min = plane.normal.x * this.min.x;
  7478. max = plane.normal.x * this.max.x;
  7479. } else {
  7480. min = plane.normal.x * this.max.x;
  7481. max = plane.normal.x * this.min.x;
  7482. }
  7483. if ( plane.normal.y > 0 ) {
  7484. min += plane.normal.y * this.min.y;
  7485. max += plane.normal.y * this.max.y;
  7486. } else {
  7487. min += plane.normal.y * this.max.y;
  7488. max += plane.normal.y * this.min.y;
  7489. }
  7490. if ( plane.normal.z > 0 ) {
  7491. min += plane.normal.z * this.min.z;
  7492. max += plane.normal.z * this.max.z;
  7493. } else {
  7494. min += plane.normal.z * this.max.z;
  7495. max += plane.normal.z * this.min.z;
  7496. }
  7497. return ( min <= - plane.constant && max >= - plane.constant );
  7498. }
  7499. /**
  7500. * Returns `true` if the given triangle intersects with this bounding box.
  7501. *
  7502. * @param {Triangle} triangle - The triangle to test.
  7503. * @return {boolean} Whether the given triangle intersects with this bounding box.
  7504. */
  7505. intersectsTriangle( triangle ) {
  7506. if ( this.isEmpty() ) {
  7507. return false;
  7508. }
  7509. // compute box center and extents
  7510. this.getCenter( _center );
  7511. _extents.subVectors( this.max, _center );
  7512. // translate triangle to aabb origin
  7513. _v0$2.subVectors( triangle.a, _center );
  7514. _v1$7.subVectors( triangle.b, _center );
  7515. _v2$4.subVectors( triangle.c, _center );
  7516. // compute edge vectors for triangle
  7517. _f0.subVectors( _v1$7, _v0$2 );
  7518. _f1.subVectors( _v2$4, _v1$7 );
  7519. _f2.subVectors( _v0$2, _v2$4 );
  7520. // test against axes that are given by cross product combinations of the edges of the triangle and the edges of the aabb
  7521. // 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
  7522. // axis_ij = u_i x f_j (u0, u1, u2 = face normals of aabb = x,y,z axes vectors since aabb is axis aligned)
  7523. let axes = [
  7524. 0, - _f0.z, _f0.y, 0, - _f1.z, _f1.y, 0, - _f2.z, _f2.y,
  7525. _f0.z, 0, - _f0.x, _f1.z, 0, - _f1.x, _f2.z, 0, - _f2.x,
  7526. - _f0.y, _f0.x, 0, - _f1.y, _f1.x, 0, - _f2.y, _f2.x, 0
  7527. ];
  7528. if ( ! satForAxes( axes, _v0$2, _v1$7, _v2$4, _extents ) ) {
  7529. return false;
  7530. }
  7531. // test 3 face normals from the aabb
  7532. axes = [ 1, 0, 0, 0, 1, 0, 0, 0, 1 ];
  7533. if ( ! satForAxes( axes, _v0$2, _v1$7, _v2$4, _extents ) ) {
  7534. return false;
  7535. }
  7536. // finally testing the face normal of the triangle
  7537. // use already existing triangle edge vectors here
  7538. _triangleNormal.crossVectors( _f0, _f1 );
  7539. axes = [ _triangleNormal.x, _triangleNormal.y, _triangleNormal.z ];
  7540. return satForAxes( axes, _v0$2, _v1$7, _v2$4, _extents );
  7541. }
  7542. /**
  7543. * Clamps the given point within the bounds of this box.
  7544. *
  7545. * @param {Vector3} point - The point to clamp.
  7546. * @param {Vector3} target - The target vector that is used to store the method's result.
  7547. * @return {Vector3} The clamped point.
  7548. */
  7549. clampPoint( point, target ) {
  7550. return target.copy( point ).clamp( this.min, this.max );
  7551. }
  7552. /**
  7553. * Returns the euclidean distance from any edge of this box to the specified point. If
  7554. * the given point lies inside of this box, the distance will be `0`.
  7555. *
  7556. * @param {Vector3} point - The point to compute the distance to.
  7557. * @return {number} The euclidean distance.
  7558. */
  7559. distanceToPoint( point ) {
  7560. return this.clampPoint( point, _vector$b ).distanceTo( point );
  7561. }
  7562. /**
  7563. * Returns a bounding sphere that encloses this bounding box.
  7564. *
  7565. * @param {Sphere} target - The target sphere that is used to store the method's result.
  7566. * @return {Sphere} The bounding sphere that encloses this bounding box.
  7567. */
  7568. getBoundingSphere( target ) {
  7569. if ( this.isEmpty() ) {
  7570. target.makeEmpty();
  7571. } else {
  7572. this.getCenter( target.center );
  7573. target.radius = this.getSize( _vector$b ).length() * 0.5;
  7574. }
  7575. return target;
  7576. }
  7577. /**
  7578. * Computes the intersection of this bounding box and the given one, setting the upper
  7579. * bound of this box to the lesser of the two boxes' upper bounds and the
  7580. * lower bound of this box to the greater of the two boxes' lower bounds. If
  7581. * there's no overlap, makes this box empty.
  7582. *
  7583. * @param {Box3} box - The bounding box to intersect with.
  7584. * @return {Box3} A reference to this bounding box.
  7585. */
  7586. intersect( box ) {
  7587. this.min.max( box.min );
  7588. this.max.min( box.max );
  7589. // 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.
  7590. if ( this.isEmpty() ) this.makeEmpty();
  7591. return this;
  7592. }
  7593. /**
  7594. * Computes the union of this box and another and the given one, setting the upper
  7595. * bound of this box to the greater of the two boxes' upper bounds and the
  7596. * lower bound of this box to the lesser of the two boxes' lower bounds.
  7597. *
  7598. * @param {Box3} box - The bounding box that will be unioned with this instance.
  7599. * @return {Box3} A reference to this bounding box.
  7600. */
  7601. union( box ) {
  7602. this.min.min( box.min );
  7603. this.max.max( box.max );
  7604. return this;
  7605. }
  7606. /**
  7607. * Transforms this bounding box by the given 4x4 transformation matrix.
  7608. *
  7609. * @param {Matrix4} matrix - The transformation matrix.
  7610. * @return {Box3} A reference to this bounding box.
  7611. */
  7612. applyMatrix4( matrix ) {
  7613. // transform of empty box is an empty box.
  7614. if ( this.isEmpty() ) return this;
  7615. // NOTE: I am using a binary pattern to specify all 2^3 combinations below
  7616. _points[ 0 ].set( this.min.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 000
  7617. _points[ 1 ].set( this.min.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 001
  7618. _points[ 2 ].set( this.min.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 010
  7619. _points[ 3 ].set( this.min.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 011
  7620. _points[ 4 ].set( this.max.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 100
  7621. _points[ 5 ].set( this.max.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 101
  7622. _points[ 6 ].set( this.max.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 110
  7623. _points[ 7 ].set( this.max.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 111
  7624. this.setFromPoints( _points );
  7625. return this;
  7626. }
  7627. /**
  7628. * Adds the given offset to both the upper and lower bounds of this bounding box,
  7629. * effectively moving it in 3D space.
  7630. *
  7631. * @param {Vector3} offset - The offset that should be used to translate the bounding box.
  7632. * @return {Box3} A reference to this bounding box.
  7633. */
  7634. translate( offset ) {
  7635. this.min.add( offset );
  7636. this.max.add( offset );
  7637. return this;
  7638. }
  7639. /**
  7640. * Returns `true` if this bounding box is equal with the given one.
  7641. *
  7642. * @param {Box3} box - The box to test for equality.
  7643. * @return {boolean} Whether this bounding box is equal with the given one.
  7644. */
  7645. equals( box ) {
  7646. return box.min.equals( this.min ) && box.max.equals( this.max );
  7647. }
  7648. }
  7649. const _points = [
  7650. /*@__PURE__*/ new Vector3(),
  7651. /*@__PURE__*/ new Vector3(),
  7652. /*@__PURE__*/ new Vector3(),
  7653. /*@__PURE__*/ new Vector3(),
  7654. /*@__PURE__*/ new Vector3(),
  7655. /*@__PURE__*/ new Vector3(),
  7656. /*@__PURE__*/ new Vector3(),
  7657. /*@__PURE__*/ new Vector3()
  7658. ];
  7659. const _vector$b = /*@__PURE__*/ new Vector3();
  7660. const _box$4 = /*@__PURE__*/ new Box3();
  7661. // triangle centered vertices
  7662. const _v0$2 = /*@__PURE__*/ new Vector3();
  7663. const _v1$7 = /*@__PURE__*/ new Vector3();
  7664. const _v2$4 = /*@__PURE__*/ new Vector3();
  7665. // triangle edge vectors
  7666. const _f0 = /*@__PURE__*/ new Vector3();
  7667. const _f1 = /*@__PURE__*/ new Vector3();
  7668. const _f2 = /*@__PURE__*/ new Vector3();
  7669. const _center = /*@__PURE__*/ new Vector3();
  7670. const _extents = /*@__PURE__*/ new Vector3();
  7671. const _triangleNormal = /*@__PURE__*/ new Vector3();
  7672. const _testAxis = /*@__PURE__*/ new Vector3();
  7673. function satForAxes( axes, v0, v1, v2, extents ) {
  7674. for ( let i = 0, j = axes.length - 3; i <= j; i += 3 ) {
  7675. _testAxis.fromArray( axes, i );
  7676. // project the aabb onto the separating axis
  7677. const r = extents.x * Math.abs( _testAxis.x ) + extents.y * Math.abs( _testAxis.y ) + extents.z * Math.abs( _testAxis.z );
  7678. // project all 3 vertices of the triangle onto the separating axis
  7679. const p0 = v0.dot( _testAxis );
  7680. const p1 = v1.dot( _testAxis );
  7681. const p2 = v2.dot( _testAxis );
  7682. // actual test, basically see if either of the most extreme of the triangle points intersects r
  7683. if ( Math.max( - Math.max( p0, p1, p2 ), Math.min( p0, p1, p2 ) ) > r ) {
  7684. // points of the projected triangle are outside the projected half-length of the aabb
  7685. // the axis is separating and we can exit
  7686. return false;
  7687. }
  7688. }
  7689. return true;
  7690. }
  7691. const _box$3 = /*@__PURE__*/ new Box3();
  7692. const _v1$6 = /*@__PURE__*/ new Vector3();
  7693. const _v2$3 = /*@__PURE__*/ new Vector3();
  7694. /**
  7695. * An analytical 3D sphere defined by a center and radius. This class is mainly
  7696. * used as a Bounding Sphere for 3D objects.
  7697. */
  7698. class Sphere {
  7699. /**
  7700. * Constructs a new sphere.
  7701. *
  7702. * @param {Vector3} [center=(0,0,0)] - The center of the sphere
  7703. * @param {number} [radius=-1] - The radius of the sphere.
  7704. */
  7705. constructor( center = new Vector3(), radius = -1 ) {
  7706. /**
  7707. * This flag can be used for type testing.
  7708. *
  7709. * @type {boolean}
  7710. * @readonly
  7711. * @default true
  7712. */
  7713. this.isSphere = true;
  7714. /**
  7715. * The center of the sphere
  7716. *
  7717. * @type {Vector3}
  7718. */
  7719. this.center = center;
  7720. /**
  7721. * The radius of the sphere.
  7722. *
  7723. * @type {number}
  7724. */
  7725. this.radius = radius;
  7726. }
  7727. /**
  7728. * Sets the sphere's components by copying the given values.
  7729. *
  7730. * @param {Vector3} center - The center.
  7731. * @param {number} radius - The radius.
  7732. * @return {Sphere} A reference to this sphere.
  7733. */
  7734. set( center, radius ) {
  7735. this.center.copy( center );
  7736. this.radius = radius;
  7737. return this;
  7738. }
  7739. /**
  7740. * Computes the minimum bounding sphere for list of points.
  7741. * If the optional center point is given, it is used as the sphere's
  7742. * center. Otherwise, the center of the axis-aligned bounding box
  7743. * encompassing the points is calculated.
  7744. *
  7745. * @param {Array<Vector3>} points - A list of points in 3D space.
  7746. * @param {Vector3} [optionalCenter] - The center of the sphere.
  7747. * @return {Sphere} A reference to this sphere.
  7748. */
  7749. setFromPoints( points, optionalCenter ) {
  7750. const center = this.center;
  7751. if ( optionalCenter !== undefined ) {
  7752. center.copy( optionalCenter );
  7753. } else {
  7754. _box$3.setFromPoints( points ).getCenter( center );
  7755. }
  7756. let maxRadiusSq = 0;
  7757. for ( let i = 0, il = points.length; i < il; i ++ ) {
  7758. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( points[ i ] ) );
  7759. }
  7760. this.radius = Math.sqrt( maxRadiusSq );
  7761. return this;
  7762. }
  7763. /**
  7764. * Copies the values of the given sphere to this instance.
  7765. *
  7766. * @param {Sphere} sphere - The sphere to copy.
  7767. * @return {Sphere} A reference to this sphere.
  7768. */
  7769. copy( sphere ) {
  7770. this.center.copy( sphere.center );
  7771. this.radius = sphere.radius;
  7772. return this;
  7773. }
  7774. /**
  7775. * Returns `true` if the sphere is empty (the radius set to a negative number).
  7776. *
  7777. * Spheres with a radius of `0` contain only their center point and are not
  7778. * considered to be empty.
  7779. *
  7780. * @return {boolean} Whether this sphere is empty or not.
  7781. */
  7782. isEmpty() {
  7783. return ( this.radius < 0 );
  7784. }
  7785. /**
  7786. * Makes this sphere empty which means in encloses a zero space in 3D.
  7787. *
  7788. * @return {Sphere} A reference to this sphere.
  7789. */
  7790. makeEmpty() {
  7791. this.center.set( 0, 0, 0 );
  7792. this.radius = -1;
  7793. return this;
  7794. }
  7795. /**
  7796. * Returns `true` if this sphere contains the given point inclusive of
  7797. * the surface of the sphere.
  7798. *
  7799. * @param {Vector3} point - The point to check.
  7800. * @return {boolean} Whether this sphere contains the given point or not.
  7801. */
  7802. containsPoint( point ) {
  7803. return ( point.distanceToSquared( this.center ) <= ( this.radius * this.radius ) );
  7804. }
  7805. /**
  7806. * Returns the closest distance from the boundary of the sphere to the
  7807. * given point. If the sphere contains the point, the distance will
  7808. * be negative.
  7809. *
  7810. * @param {Vector3} point - The point to compute the distance to.
  7811. * @return {number} The distance to the point.
  7812. */
  7813. distanceToPoint( point ) {
  7814. return ( point.distanceTo( this.center ) - this.radius );
  7815. }
  7816. /**
  7817. * Returns `true` if this sphere intersects with the given one.
  7818. *
  7819. * @param {Sphere} sphere - The sphere to test.
  7820. * @return {boolean} Whether this sphere intersects with the given one or not.
  7821. */
  7822. intersectsSphere( sphere ) {
  7823. const radiusSum = this.radius + sphere.radius;
  7824. return sphere.center.distanceToSquared( this.center ) <= ( radiusSum * radiusSum );
  7825. }
  7826. /**
  7827. * Returns `true` if this sphere intersects with the given box.
  7828. *
  7829. * @param {Box3} box - The box to test.
  7830. * @return {boolean} Whether this sphere intersects with the given box or not.
  7831. */
  7832. intersectsBox( box ) {
  7833. return box.intersectsSphere( this );
  7834. }
  7835. /**
  7836. * Returns `true` if this sphere intersects with the given plane.
  7837. *
  7838. * @param {Plane} plane - The plane to test.
  7839. * @return {boolean} Whether this sphere intersects with the given plane or not.
  7840. */
  7841. intersectsPlane( plane ) {
  7842. return Math.abs( plane.distanceToPoint( this.center ) ) <= this.radius;
  7843. }
  7844. /**
  7845. * Clamps a point within the sphere. If the point is outside the sphere, it
  7846. * will clamp it to the closest point on the edge of the sphere. Points
  7847. * already inside the sphere will not be affected.
  7848. *
  7849. * @param {Vector3} point - The plane to clamp.
  7850. * @param {Vector3} target - The target vector that is used to store the method's result.
  7851. * @return {Vector3} The clamped point.
  7852. */
  7853. clampPoint( point, target ) {
  7854. const deltaLengthSq = this.center.distanceToSquared( point );
  7855. target.copy( point );
  7856. if ( deltaLengthSq > ( this.radius * this.radius ) ) {
  7857. target.sub( this.center ).normalize();
  7858. target.multiplyScalar( this.radius ).add( this.center );
  7859. }
  7860. return target;
  7861. }
  7862. /**
  7863. * Returns a bounding box that encloses this sphere.
  7864. *
  7865. * @param {Box3} target - The target box that is used to store the method's result.
  7866. * @return {Box3} The bounding box that encloses this sphere.
  7867. */
  7868. getBoundingBox( target ) {
  7869. if ( this.isEmpty() ) {
  7870. // Empty sphere produces empty bounding box
  7871. target.makeEmpty();
  7872. return target;
  7873. }
  7874. target.set( this.center, this.center );
  7875. target.expandByScalar( this.radius );
  7876. return target;
  7877. }
  7878. /**
  7879. * Transforms this sphere with the given 4x4 transformation matrix.
  7880. *
  7881. * @param {Matrix4} matrix - The transformation matrix.
  7882. * @return {Sphere} A reference to this sphere.
  7883. */
  7884. applyMatrix4( matrix ) {
  7885. this.center.applyMatrix4( matrix );
  7886. this.radius = this.radius * matrix.getMaxScaleOnAxis();
  7887. return this;
  7888. }
  7889. /**
  7890. * Translates the sphere's center by the given offset.
  7891. *
  7892. * @param {Vector3} offset - The offset.
  7893. * @return {Sphere} A reference to this sphere.
  7894. */
  7895. translate( offset ) {
  7896. this.center.add( offset );
  7897. return this;
  7898. }
  7899. /**
  7900. * Expands the boundaries of this sphere to include the given point.
  7901. *
  7902. * @param {Vector3} point - The point to include.
  7903. * @return {Sphere} A reference to this sphere.
  7904. */
  7905. expandByPoint( point ) {
  7906. if ( this.isEmpty() ) {
  7907. this.center.copy( point );
  7908. this.radius = 0;
  7909. return this;
  7910. }
  7911. _v1$6.subVectors( point, this.center );
  7912. const lengthSq = _v1$6.lengthSq();
  7913. if ( lengthSq > ( this.radius * this.radius ) ) {
  7914. // calculate the minimal sphere
  7915. const length = Math.sqrt( lengthSq );
  7916. const delta = ( length - this.radius ) * 0.5;
  7917. this.center.addScaledVector( _v1$6, delta / length );
  7918. this.radius += delta;
  7919. }
  7920. return this;
  7921. }
  7922. /**
  7923. * Expands this sphere to enclose both the original sphere and the given sphere.
  7924. *
  7925. * @param {Sphere} sphere - The sphere to include.
  7926. * @return {Sphere} A reference to this sphere.
  7927. */
  7928. union( sphere ) {
  7929. if ( sphere.isEmpty() ) {
  7930. return this;
  7931. }
  7932. if ( this.isEmpty() ) {
  7933. this.copy( sphere );
  7934. return this;
  7935. }
  7936. if ( this.center.equals( sphere.center ) === true ) {
  7937. this.radius = Math.max( this.radius, sphere.radius );
  7938. } else {
  7939. _v2$3.subVectors( sphere.center, this.center ).setLength( sphere.radius );
  7940. this.expandByPoint( _v1$6.copy( sphere.center ).add( _v2$3 ) );
  7941. this.expandByPoint( _v1$6.copy( sphere.center ).sub( _v2$3 ) );
  7942. }
  7943. return this;
  7944. }
  7945. /**
  7946. * Returns `true` if this sphere is equal with the given one.
  7947. *
  7948. * @param {Sphere} sphere - The sphere to test for equality.
  7949. * @return {boolean} Whether this bounding sphere is equal with the given one.
  7950. */
  7951. equals( sphere ) {
  7952. return sphere.center.equals( this.center ) && ( sphere.radius === this.radius );
  7953. }
  7954. /**
  7955. * Returns a new sphere with copied values from this instance.
  7956. *
  7957. * @return {Sphere} A clone of this instance.
  7958. */
  7959. clone() {
  7960. return new this.constructor().copy( this );
  7961. }
  7962. }
  7963. const _vector$a = /*@__PURE__*/ new Vector3();
  7964. const _segCenter = /*@__PURE__*/ new Vector3();
  7965. const _segDir = /*@__PURE__*/ new Vector3();
  7966. const _diff = /*@__PURE__*/ new Vector3();
  7967. const _edge1 = /*@__PURE__*/ new Vector3();
  7968. const _edge2 = /*@__PURE__*/ new Vector3();
  7969. const _normal$1 = /*@__PURE__*/ new Vector3();
  7970. /**
  7971. * A ray that emits from an origin in a certain direction. The class is used by
  7972. * {@link Raycaster} to assist with raycasting. Raycasting is used for
  7973. * mouse picking (working out what objects in the 3D space the mouse is over)
  7974. * amongst other things.
  7975. */
  7976. class Ray {
  7977. /**
  7978. * Constructs a new ray.
  7979. *
  7980. * @param {Vector3} [origin=(0,0,0)] - The origin of the ray.
  7981. * @param {Vector3} [direction=(0,0,-1)] - The (normalized) direction of the ray.
  7982. */
  7983. constructor( origin = new Vector3(), direction = new Vector3( 0, 0, -1 ) ) {
  7984. /**
  7985. * The origin of the ray.
  7986. *
  7987. * @type {Vector3}
  7988. */
  7989. this.origin = origin;
  7990. /**
  7991. * The (normalized) direction of the ray.
  7992. *
  7993. * @type {Vector3}
  7994. */
  7995. this.direction = direction;
  7996. }
  7997. /**
  7998. * Sets the ray's components by copying the given values.
  7999. *
  8000. * @param {Vector3} origin - The origin.
  8001. * @param {Vector3} direction - The direction.
  8002. * @return {Ray} A reference to this ray.
  8003. */
  8004. set( origin, direction ) {
  8005. this.origin.copy( origin );
  8006. this.direction.copy( direction );
  8007. return this;
  8008. }
  8009. /**
  8010. * Copies the values of the given ray to this instance.
  8011. *
  8012. * @param {Ray} ray - The ray to copy.
  8013. * @return {Ray} A reference to this ray.
  8014. */
  8015. copy( ray ) {
  8016. this.origin.copy( ray.origin );
  8017. this.direction.copy( ray.direction );
  8018. return this;
  8019. }
  8020. /**
  8021. * Returns a vector that is located at a given distance along this ray.
  8022. *
  8023. * @param {number} t - The distance along the ray to retrieve a position for.
  8024. * @param {Vector3} target - The target vector that is used to store the method's result.
  8025. * @return {Vector3} A position on the ray.
  8026. */
  8027. at( t, target ) {
  8028. return target.copy( this.origin ).addScaledVector( this.direction, t );
  8029. }
  8030. /**
  8031. * Adjusts the direction of the ray to point at the given vector in world space.
  8032. *
  8033. * @param {Vector3} v - The target position.
  8034. * @return {Ray} A reference to this ray.
  8035. */
  8036. lookAt( v ) {
  8037. this.direction.copy( v ).sub( this.origin ).normalize();
  8038. return this;
  8039. }
  8040. /**
  8041. * Shift the origin of this ray along its direction by the given distance.
  8042. *
  8043. * @param {number} t - The distance along the ray to interpolate.
  8044. * @return {Ray} A reference to this ray.
  8045. */
  8046. recast( t ) {
  8047. this.origin.copy( this.at( t, _vector$a ) );
  8048. return this;
  8049. }
  8050. /**
  8051. * Returns the point along this ray that is closest to the given point.
  8052. *
  8053. * @param {Vector3} point - A point in 3D space to get the closet location on the ray for.
  8054. * @param {Vector3} target - The target vector that is used to store the method's result.
  8055. * @return {Vector3} The closest point on this ray.
  8056. */
  8057. closestPointToPoint( point, target ) {
  8058. target.subVectors( point, this.origin );
  8059. const directionDistance = target.dot( this.direction );
  8060. if ( directionDistance < 0 ) {
  8061. return target.copy( this.origin );
  8062. }
  8063. return target.copy( this.origin ).addScaledVector( this.direction, directionDistance );
  8064. }
  8065. /**
  8066. * Returns the distance of the closest approach between this ray and the given point.
  8067. *
  8068. * @param {Vector3} point - A point in 3D space to compute the distance to.
  8069. * @return {number} The distance.
  8070. */
  8071. distanceToPoint( point ) {
  8072. return Math.sqrt( this.distanceSqToPoint( point ) );
  8073. }
  8074. /**
  8075. * Returns the squared distance of the closest approach between this ray and the given point.
  8076. *
  8077. * @param {Vector3} point - A point in 3D space to compute the distance to.
  8078. * @return {number} The squared distance.
  8079. */
  8080. distanceSqToPoint( point ) {
  8081. const directionDistance = _vector$a.subVectors( point, this.origin ).dot( this.direction );
  8082. // point behind the ray
  8083. if ( directionDistance < 0 ) {
  8084. return this.origin.distanceToSquared( point );
  8085. }
  8086. _vector$a.copy( this.origin ).addScaledVector( this.direction, directionDistance );
  8087. return _vector$a.distanceToSquared( point );
  8088. }
  8089. /**
  8090. * Returns the squared distance between this ray and the given line segment.
  8091. *
  8092. * @param {Vector3} v0 - The start point of the line segment.
  8093. * @param {Vector3} v1 - The end point of the line segment.
  8094. * @param {Vector3} [optionalPointOnRay] - When provided, it receives the point on this ray that is closest to the segment.
  8095. * @param {Vector3} [optionalPointOnSegment] - When provided, it receives the point on the line segment that is closest to this ray.
  8096. * @return {number} The squared distance.
  8097. */
  8098. distanceSqToSegment( v0, v1, optionalPointOnRay, optionalPointOnSegment ) {
  8099. // from https://github.com/pmjoniak/GeometricTools/blob/master/GTEngine/Include/Mathematics/GteDistRaySegment.h
  8100. // It returns the min distance between the ray and the segment
  8101. // defined by v0 and v1
  8102. // It can also set two optional targets :
  8103. // - The closest point on the ray
  8104. // - The closest point on the segment
  8105. _segCenter.copy( v0 ).add( v1 ).multiplyScalar( 0.5 );
  8106. _segDir.copy( v1 ).sub( v0 ).normalize();
  8107. _diff.copy( this.origin ).sub( _segCenter );
  8108. const segExtent = v0.distanceTo( v1 ) * 0.5;
  8109. const a01 = - this.direction.dot( _segDir );
  8110. const b0 = _diff.dot( this.direction );
  8111. const b1 = - _diff.dot( _segDir );
  8112. const c = _diff.lengthSq();
  8113. const det = Math.abs( 1 - a01 * a01 );
  8114. let s0, s1, sqrDist, extDet;
  8115. if ( det > 0 ) {
  8116. // The ray and segment are not parallel.
  8117. s0 = a01 * b1 - b0;
  8118. s1 = a01 * b0 - b1;
  8119. extDet = segExtent * det;
  8120. if ( s0 >= 0 ) {
  8121. if ( s1 >= - extDet ) {
  8122. if ( s1 <= extDet ) {
  8123. // region 0
  8124. // Minimum at interior points of ray and segment.
  8125. const invDet = 1 / det;
  8126. s0 *= invDet;
  8127. s1 *= invDet;
  8128. sqrDist = s0 * ( s0 + a01 * s1 + 2 * b0 ) + s1 * ( a01 * s0 + s1 + 2 * b1 ) + c;
  8129. } else {
  8130. // region 1
  8131. s1 = segExtent;
  8132. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  8133. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  8134. }
  8135. } else {
  8136. // region 5
  8137. s1 = - segExtent;
  8138. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  8139. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  8140. }
  8141. } else {
  8142. if ( s1 <= - extDet ) {
  8143. // region 4
  8144. s0 = Math.max( 0, - ( - a01 * segExtent + b0 ) );
  8145. s1 = ( s0 > 0 ) ? - segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  8146. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  8147. } else if ( s1 <= extDet ) {
  8148. // region 3
  8149. s0 = 0;
  8150. s1 = Math.min( Math.max( - segExtent, - b1 ), segExtent );
  8151. sqrDist = s1 * ( s1 + 2 * b1 ) + c;
  8152. } else {
  8153. // region 2
  8154. s0 = Math.max( 0, - ( a01 * segExtent + b0 ) );
  8155. s1 = ( s0 > 0 ) ? segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  8156. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  8157. }
  8158. }
  8159. } else {
  8160. // Ray and segment are parallel.
  8161. s1 = ( a01 > 0 ) ? - segExtent : segExtent;
  8162. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  8163. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  8164. }
  8165. if ( optionalPointOnRay ) {
  8166. optionalPointOnRay.copy( this.origin ).addScaledVector( this.direction, s0 );
  8167. }
  8168. if ( optionalPointOnSegment ) {
  8169. optionalPointOnSegment.copy( _segCenter ).addScaledVector( _segDir, s1 );
  8170. }
  8171. return sqrDist;
  8172. }
  8173. /**
  8174. * Intersects this ray with the given sphere, returning the intersection
  8175. * point or `null` if there is no intersection.
  8176. *
  8177. * @param {Sphere} sphere - The sphere to intersect.
  8178. * @param {Vector3} target - The target vector that is used to store the method's result.
  8179. * @return {?Vector3} The intersection point.
  8180. */
  8181. intersectSphere( sphere, target ) {
  8182. _vector$a.subVectors( sphere.center, this.origin );
  8183. const tca = _vector$a.dot( this.direction );
  8184. const d2 = _vector$a.dot( _vector$a ) - tca * tca;
  8185. const radius2 = sphere.radius * sphere.radius;
  8186. if ( d2 > radius2 ) return null;
  8187. const thc = Math.sqrt( radius2 - d2 );
  8188. // t0 = first intersect point - entrance on front of sphere
  8189. const t0 = tca - thc;
  8190. // t1 = second intersect point - exit point on back of sphere
  8191. const t1 = tca + thc;
  8192. // test to see if t1 is behind the ray - if so, return null
  8193. if ( t1 < 0 ) return null;
  8194. // test to see if t0 is behind the ray:
  8195. // if it is, the ray is inside the sphere, so return the second exit point scaled by t1,
  8196. // in order to always return an intersect point that is in front of the ray.
  8197. if ( t0 < 0 ) return this.at( t1, target );
  8198. // else t0 is in front of the ray, so return the first collision point scaled by t0
  8199. return this.at( t0, target );
  8200. }
  8201. /**
  8202. * Returns `true` if this ray intersects with the given sphere.
  8203. *
  8204. * @param {Sphere} sphere - The sphere to intersect.
  8205. * @return {boolean} Whether this ray intersects with the given sphere or not.
  8206. */
  8207. intersectsSphere( sphere ) {
  8208. return this.distanceSqToPoint( sphere.center ) <= ( sphere.radius * sphere.radius );
  8209. }
  8210. /**
  8211. * Computes the distance from the ray's origin to the given plane. Returns `null` if the ray
  8212. * does not intersect with the plane.
  8213. *
  8214. * @param {Plane} plane - The plane to compute the distance to.
  8215. * @return {?number} Whether this ray intersects with the given sphere or not.
  8216. */
  8217. distanceToPlane( plane ) {
  8218. const denominator = plane.normal.dot( this.direction );
  8219. if ( denominator === 0 ) {
  8220. // line is coplanar, return origin
  8221. if ( plane.distanceToPoint( this.origin ) === 0 ) {
  8222. return 0;
  8223. }
  8224. // Null is preferable to undefined since undefined means.... it is undefined
  8225. return null;
  8226. }
  8227. const t = - ( this.origin.dot( plane.normal ) + plane.constant ) / denominator;
  8228. // Return if the ray never intersects the plane
  8229. return t >= 0 ? t : null;
  8230. }
  8231. /**
  8232. * Intersects this ray with the given plane, returning the intersection
  8233. * point or `null` if there is no intersection.
  8234. *
  8235. * @param {Plane} plane - The plane to intersect.
  8236. * @param {Vector3} target - The target vector that is used to store the method's result.
  8237. * @return {?Vector3} The intersection point.
  8238. */
  8239. intersectPlane( plane, target ) {
  8240. const t = this.distanceToPlane( plane );
  8241. if ( t === null ) {
  8242. return null;
  8243. }
  8244. return this.at( t, target );
  8245. }
  8246. /**
  8247. * Returns `true` if this ray intersects with the given plane.
  8248. *
  8249. * @param {Plane} plane - The plane to intersect.
  8250. * @return {boolean} Whether this ray intersects with the given plane or not.
  8251. */
  8252. intersectsPlane( plane ) {
  8253. // check if the ray lies on the plane first
  8254. const distToPoint = plane.distanceToPoint( this.origin );
  8255. if ( distToPoint === 0 ) {
  8256. return true;
  8257. }
  8258. const denominator = plane.normal.dot( this.direction );
  8259. if ( denominator * distToPoint < 0 ) {
  8260. return true;
  8261. }
  8262. // ray origin is behind the plane (and is pointing behind it)
  8263. return false;
  8264. }
  8265. /**
  8266. * Intersects this ray with the given bounding box, returning the intersection
  8267. * point or `null` if there is no intersection.
  8268. *
  8269. * @param {Box3} box - The box to intersect.
  8270. * @param {Vector3} target - The target vector that is used to store the method's result.
  8271. * @return {?Vector3} The intersection point.
  8272. */
  8273. intersectBox( box, target ) {
  8274. let tmin, tmax, tymin, tymax, tzmin, tzmax;
  8275. const invdirx = 1 / this.direction.x,
  8276. invdiry = 1 / this.direction.y,
  8277. invdirz = 1 / this.direction.z;
  8278. const origin = this.origin;
  8279. if ( invdirx >= 0 ) {
  8280. tmin = ( box.min.x - origin.x ) * invdirx;
  8281. tmax = ( box.max.x - origin.x ) * invdirx;
  8282. } else {
  8283. tmin = ( box.max.x - origin.x ) * invdirx;
  8284. tmax = ( box.min.x - origin.x ) * invdirx;
  8285. }
  8286. if ( invdiry >= 0 ) {
  8287. tymin = ( box.min.y - origin.y ) * invdiry;
  8288. tymax = ( box.max.y - origin.y ) * invdiry;
  8289. } else {
  8290. tymin = ( box.max.y - origin.y ) * invdiry;
  8291. tymax = ( box.min.y - origin.y ) * invdiry;
  8292. }
  8293. if ( ( tmin > tymax ) || ( tymin > tmax ) ) return null;
  8294. if ( tymin > tmin || isNaN( tmin ) ) tmin = tymin;
  8295. if ( tymax < tmax || isNaN( tmax ) ) tmax = tymax;
  8296. if ( invdirz >= 0 ) {
  8297. tzmin = ( box.min.z - origin.z ) * invdirz;
  8298. tzmax = ( box.max.z - origin.z ) * invdirz;
  8299. } else {
  8300. tzmin = ( box.max.z - origin.z ) * invdirz;
  8301. tzmax = ( box.min.z - origin.z ) * invdirz;
  8302. }
  8303. if ( ( tmin > tzmax ) || ( tzmin > tmax ) ) return null;
  8304. if ( tzmin > tmin || tmin !== tmin ) tmin = tzmin;
  8305. if ( tzmax < tmax || tmax !== tmax ) tmax = tzmax;
  8306. //return point closest to the ray (positive side)
  8307. if ( tmax < 0 ) return null;
  8308. return this.at( tmin >= 0 ? tmin : tmax, target );
  8309. }
  8310. /**
  8311. * Returns `true` if this ray intersects with the given box.
  8312. *
  8313. * @param {Box3} box - The box to intersect.
  8314. * @return {boolean} Whether this ray intersects with the given box or not.
  8315. */
  8316. intersectsBox( box ) {
  8317. return this.intersectBox( box, _vector$a ) !== null;
  8318. }
  8319. /**
  8320. * Intersects this ray with the given triangle, returning the intersection
  8321. * point or `null` if there is no intersection.
  8322. *
  8323. * @param {Vector3} a - The first vertex of the triangle.
  8324. * @param {Vector3} b - The second vertex of the triangle.
  8325. * @param {Vector3} c - The third vertex of the triangle.
  8326. * @param {boolean} backfaceCulling - Whether to use backface culling or not.
  8327. * @param {Vector3} target - The target vector that is used to store the method's result.
  8328. * @return {?Vector3} The intersection point.
  8329. */
  8330. intersectTriangle( a, b, c, backfaceCulling, target ) {
  8331. // Compute the offset origin, edges, and normal.
  8332. // from https://github.com/pmjoniak/GeometricTools/blob/master/GTEngine/Include/Mathematics/GteIntrRay3Triangle3.h
  8333. _edge1.subVectors( b, a );
  8334. _edge2.subVectors( c, a );
  8335. _normal$1.crossVectors( _edge1, _edge2 );
  8336. // Solve Q + t*D = b1*E1 + b2*E2 (Q = kDiff, D = ray direction,
  8337. // E1 = kEdge1, E2 = kEdge2, N = Cross(E1,E2)) by
  8338. // |Dot(D,N)|*b1 = sign(Dot(D,N))*Dot(D,Cross(Q,E2))
  8339. // |Dot(D,N)|*b2 = sign(Dot(D,N))*Dot(D,Cross(E1,Q))
  8340. // |Dot(D,N)|*t = -sign(Dot(D,N))*Dot(Q,N)
  8341. let DdN = this.direction.dot( _normal$1 );
  8342. let sign;
  8343. if ( DdN > 0 ) {
  8344. if ( backfaceCulling ) return null;
  8345. sign = 1;
  8346. } else if ( DdN < 0 ) {
  8347. sign = -1;
  8348. DdN = - DdN;
  8349. } else {
  8350. return null;
  8351. }
  8352. _diff.subVectors( this.origin, a );
  8353. const DdQxE2 = sign * this.direction.dot( _edge2.crossVectors( _diff, _edge2 ) );
  8354. // b1 < 0, no intersection
  8355. if ( DdQxE2 < 0 ) {
  8356. return null;
  8357. }
  8358. const DdE1xQ = sign * this.direction.dot( _edge1.cross( _diff ) );
  8359. // b2 < 0, no intersection
  8360. if ( DdE1xQ < 0 ) {
  8361. return null;
  8362. }
  8363. // b1+b2 > 1, no intersection
  8364. if ( DdQxE2 + DdE1xQ > DdN ) {
  8365. return null;
  8366. }
  8367. // Line intersects triangle, check if ray does.
  8368. const QdN = - sign * _diff.dot( _normal$1 );
  8369. // t < 0, no intersection
  8370. if ( QdN < 0 ) {
  8371. return null;
  8372. }
  8373. // Ray intersects triangle.
  8374. return this.at( QdN / DdN, target );
  8375. }
  8376. /**
  8377. * Transforms this ray with the given 4x4 transformation matrix.
  8378. *
  8379. * @param {Matrix4} matrix4 - The transformation matrix.
  8380. * @return {Ray} A reference to this ray.
  8381. */
  8382. applyMatrix4( matrix4 ) {
  8383. this.origin.applyMatrix4( matrix4 );
  8384. this.direction.transformDirection( matrix4 );
  8385. return this;
  8386. }
  8387. /**
  8388. * Returns `true` if this ray is equal with the given one.
  8389. *
  8390. * @param {Ray} ray - The ray to test for equality.
  8391. * @return {boolean} Whether this ray is equal with the given one.
  8392. */
  8393. equals( ray ) {
  8394. return ray.origin.equals( this.origin ) && ray.direction.equals( this.direction );
  8395. }
  8396. /**
  8397. * Returns a new ray with copied values from this instance.
  8398. *
  8399. * @return {Ray} A clone of this instance.
  8400. */
  8401. clone() {
  8402. return new this.constructor().copy( this );
  8403. }
  8404. }
  8405. /**
  8406. * Represents a 4x4 matrix.
  8407. *
  8408. * The most common use of a 4x4 matrix in 3D computer graphics is as a transformation matrix.
  8409. * 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}
  8410. *
  8411. * This allows a 3D vector representing a point in 3D space to undergo
  8412. * transformations such as translation, rotation, shear, scale, reflection,
  8413. * orthogonal or perspective projection and so on, by being multiplied by the
  8414. * matrix. This is known as `applying` the matrix to the vector.
  8415. *
  8416. * A Note on Row-Major and Column-Major Ordering:
  8417. *
  8418. * The constructor and {@link Matrix3#set} method take arguments in
  8419. * [row-major]{@link https://en.wikipedia.org/wiki/Row-_and_column-major_order#Column-major_order}
  8420. * order, while internally they are stored in the {@link Matrix3#elements} array in column-major order.
  8421. * This means that calling:
  8422. * ```js
  8423. * const m = new THREE.Matrix4();
  8424. * m.set( 11, 12, 13, 14,
  8425. * 21, 22, 23, 24,
  8426. * 31, 32, 33, 34,
  8427. * 41, 42, 43, 44 );
  8428. * ```
  8429. * will result in the elements array containing:
  8430. * ```js
  8431. * m.elements = [ 11, 21, 31, 41,
  8432. * 12, 22, 32, 42,
  8433. * 13, 23, 33, 43,
  8434. * 14, 24, 34, 44 ];
  8435. * ```
  8436. * and internally all calculations are performed using column-major ordering.
  8437. * However, as the actual ordering makes no difference mathematically and
  8438. * most people are used to thinking about matrices in row-major order, the
  8439. * three.js documentation shows matrices in row-major order. Just bear in
  8440. * mind that if you are reading the source code, you'll have to take the
  8441. * transpose of any matrices outlined here to make sense of the calculations.
  8442. */
  8443. class Matrix4 {
  8444. /**
  8445. * Constructs a new 4x4 matrix. The arguments are supposed to be
  8446. * in row-major order. If no arguments are provided, the constructor
  8447. * initializes the matrix as an identity matrix.
  8448. *
  8449. * @param {number} [n11] - 1-1 matrix element.
  8450. * @param {number} [n12] - 1-2 matrix element.
  8451. * @param {number} [n13] - 1-3 matrix element.
  8452. * @param {number} [n14] - 1-4 matrix element.
  8453. * @param {number} [n21] - 2-1 matrix element.
  8454. * @param {number} [n22] - 2-2 matrix element.
  8455. * @param {number} [n23] - 2-3 matrix element.
  8456. * @param {number} [n24] - 2-4 matrix element.
  8457. * @param {number} [n31] - 3-1 matrix element.
  8458. * @param {number} [n32] - 3-2 matrix element.
  8459. * @param {number} [n33] - 3-3 matrix element.
  8460. * @param {number} [n34] - 3-4 matrix element.
  8461. * @param {number} [n41] - 4-1 matrix element.
  8462. * @param {number} [n42] - 4-2 matrix element.
  8463. * @param {number} [n43] - 4-3 matrix element.
  8464. * @param {number} [n44] - 4-4 matrix element.
  8465. */
  8466. constructor( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  8467. /**
  8468. * This flag can be used for type testing.
  8469. *
  8470. * @type {boolean}
  8471. * @readonly
  8472. * @default true
  8473. */
  8474. Matrix4.prototype.isMatrix4 = true;
  8475. /**
  8476. * A column-major list of matrix values.
  8477. *
  8478. * @type {Array<number>}
  8479. */
  8480. this.elements = [
  8481. 1, 0, 0, 0,
  8482. 0, 1, 0, 0,
  8483. 0, 0, 1, 0,
  8484. 0, 0, 0, 1
  8485. ];
  8486. if ( n11 !== undefined ) {
  8487. this.set( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 );
  8488. }
  8489. }
  8490. /**
  8491. * Sets the elements of the matrix.The arguments are supposed to be
  8492. * in row-major order.
  8493. *
  8494. * @param {number} [n11] - 1-1 matrix element.
  8495. * @param {number} [n12] - 1-2 matrix element.
  8496. * @param {number} [n13] - 1-3 matrix element.
  8497. * @param {number} [n14] - 1-4 matrix element.
  8498. * @param {number} [n21] - 2-1 matrix element.
  8499. * @param {number} [n22] - 2-2 matrix element.
  8500. * @param {number} [n23] - 2-3 matrix element.
  8501. * @param {number} [n24] - 2-4 matrix element.
  8502. * @param {number} [n31] - 3-1 matrix element.
  8503. * @param {number} [n32] - 3-2 matrix element.
  8504. * @param {number} [n33] - 3-3 matrix element.
  8505. * @param {number} [n34] - 3-4 matrix element.
  8506. * @param {number} [n41] - 4-1 matrix element.
  8507. * @param {number} [n42] - 4-2 matrix element.
  8508. * @param {number} [n43] - 4-3 matrix element.
  8509. * @param {number} [n44] - 4-4 matrix element.
  8510. * @return {Matrix4} A reference to this matrix.
  8511. */
  8512. set( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  8513. const te = this.elements;
  8514. te[ 0 ] = n11; te[ 4 ] = n12; te[ 8 ] = n13; te[ 12 ] = n14;
  8515. te[ 1 ] = n21; te[ 5 ] = n22; te[ 9 ] = n23; te[ 13 ] = n24;
  8516. te[ 2 ] = n31; te[ 6 ] = n32; te[ 10 ] = n33; te[ 14 ] = n34;
  8517. te[ 3 ] = n41; te[ 7 ] = n42; te[ 11 ] = n43; te[ 15 ] = n44;
  8518. return this;
  8519. }
  8520. /**
  8521. * Sets this matrix to the 4x4 identity matrix.
  8522. *
  8523. * @return {Matrix4} A reference to this matrix.
  8524. */
  8525. identity() {
  8526. this.set(
  8527. 1, 0, 0, 0,
  8528. 0, 1, 0, 0,
  8529. 0, 0, 1, 0,
  8530. 0, 0, 0, 1
  8531. );
  8532. return this;
  8533. }
  8534. /**
  8535. * Returns a matrix with copied values from this instance.
  8536. *
  8537. * @return {Matrix4} A clone of this instance.
  8538. */
  8539. clone() {
  8540. return new Matrix4().fromArray( this.elements );
  8541. }
  8542. /**
  8543. * Copies the values of the given matrix to this instance.
  8544. *
  8545. * @param {Matrix4} m - The matrix to copy.
  8546. * @return {Matrix4} A reference to this matrix.
  8547. */
  8548. copy( m ) {
  8549. const te = this.elements;
  8550. const me = m.elements;
  8551. te[ 0 ] = me[ 0 ]; te[ 1 ] = me[ 1 ]; te[ 2 ] = me[ 2 ]; te[ 3 ] = me[ 3 ];
  8552. te[ 4 ] = me[ 4 ]; te[ 5 ] = me[ 5 ]; te[ 6 ] = me[ 6 ]; te[ 7 ] = me[ 7 ];
  8553. te[ 8 ] = me[ 8 ]; te[ 9 ] = me[ 9 ]; te[ 10 ] = me[ 10 ]; te[ 11 ] = me[ 11 ];
  8554. te[ 12 ] = me[ 12 ]; te[ 13 ] = me[ 13 ]; te[ 14 ] = me[ 14 ]; te[ 15 ] = me[ 15 ];
  8555. return this;
  8556. }
  8557. /**
  8558. * Copies the translation component of the given matrix
  8559. * into this matrix's translation component.
  8560. *
  8561. * @param {Matrix4} m - The matrix to copy the translation component.
  8562. * @return {Matrix4} A reference to this matrix.
  8563. */
  8564. copyPosition( m ) {
  8565. const te = this.elements, me = m.elements;
  8566. te[ 12 ] = me[ 12 ];
  8567. te[ 13 ] = me[ 13 ];
  8568. te[ 14 ] = me[ 14 ];
  8569. return this;
  8570. }
  8571. /**
  8572. * Set the upper 3x3 elements of this matrix to the values of given 3x3 matrix.
  8573. *
  8574. * @param {Matrix3} m - The 3x3 matrix.
  8575. * @return {Matrix4} A reference to this matrix.
  8576. */
  8577. setFromMatrix3( m ) {
  8578. const me = m.elements;
  8579. this.set(
  8580. me[ 0 ], me[ 3 ], me[ 6 ], 0,
  8581. me[ 1 ], me[ 4 ], me[ 7 ], 0,
  8582. me[ 2 ], me[ 5 ], me[ 8 ], 0,
  8583. 0, 0, 0, 1
  8584. );
  8585. return this;
  8586. }
  8587. /**
  8588. * Extracts the basis of this matrix into the three axis vectors provided.
  8589. *
  8590. * @param {Vector3} xAxis - The basis's x axis.
  8591. * @param {Vector3} yAxis - The basis's y axis.
  8592. * @param {Vector3} zAxis - The basis's z axis.
  8593. * @return {Matrix4} A reference to this matrix.
  8594. */
  8595. extractBasis( xAxis, yAxis, zAxis ) {
  8596. xAxis.setFromMatrixColumn( this, 0 );
  8597. yAxis.setFromMatrixColumn( this, 1 );
  8598. zAxis.setFromMatrixColumn( this, 2 );
  8599. return this;
  8600. }
  8601. /**
  8602. * Sets the given basis vectors to this matrix.
  8603. *
  8604. * @param {Vector3} xAxis - The basis's x axis.
  8605. * @param {Vector3} yAxis - The basis's y axis.
  8606. * @param {Vector3} zAxis - The basis's z axis.
  8607. * @return {Matrix4} A reference to this matrix.
  8608. */
  8609. makeBasis( xAxis, yAxis, zAxis ) {
  8610. this.set(
  8611. xAxis.x, yAxis.x, zAxis.x, 0,
  8612. xAxis.y, yAxis.y, zAxis.y, 0,
  8613. xAxis.z, yAxis.z, zAxis.z, 0,
  8614. 0, 0, 0, 1
  8615. );
  8616. return this;
  8617. }
  8618. /**
  8619. * Extracts the rotation component of the given matrix
  8620. * into this matrix's rotation component.
  8621. *
  8622. * Note: This method does not support reflection matrices.
  8623. *
  8624. * @param {Matrix4} m - The matrix.
  8625. * @return {Matrix4} A reference to this matrix.
  8626. */
  8627. extractRotation( m ) {
  8628. const te = this.elements;
  8629. const me = m.elements;
  8630. const scaleX = 1 / _v1$5.setFromMatrixColumn( m, 0 ).length();
  8631. const scaleY = 1 / _v1$5.setFromMatrixColumn( m, 1 ).length();
  8632. const scaleZ = 1 / _v1$5.setFromMatrixColumn( m, 2 ).length();
  8633. te[ 0 ] = me[ 0 ] * scaleX;
  8634. te[ 1 ] = me[ 1 ] * scaleX;
  8635. te[ 2 ] = me[ 2 ] * scaleX;
  8636. te[ 3 ] = 0;
  8637. te[ 4 ] = me[ 4 ] * scaleY;
  8638. te[ 5 ] = me[ 5 ] * scaleY;
  8639. te[ 6 ] = me[ 6 ] * scaleY;
  8640. te[ 7 ] = 0;
  8641. te[ 8 ] = me[ 8 ] * scaleZ;
  8642. te[ 9 ] = me[ 9 ] * scaleZ;
  8643. te[ 10 ] = me[ 10 ] * scaleZ;
  8644. te[ 11 ] = 0;
  8645. te[ 12 ] = 0;
  8646. te[ 13 ] = 0;
  8647. te[ 14 ] = 0;
  8648. te[ 15 ] = 1;
  8649. return this;
  8650. }
  8651. /**
  8652. * Sets the rotation component (the upper left 3x3 matrix) of this matrix to
  8653. * the rotation specified by the given Euler angles. The rest of
  8654. * the matrix is set to the identity. Depending on the {@link Euler#order},
  8655. * there are six possible outcomes. See [this page]{@link https://en.wikipedia.org/wiki/Euler_angles#Rotation_matrix}
  8656. * for a complete list.
  8657. *
  8658. * @param {Euler} euler - The Euler angles.
  8659. * @return {Matrix4} A reference to this matrix.
  8660. */
  8661. makeRotationFromEuler( euler ) {
  8662. const te = this.elements;
  8663. const x = euler.x, y = euler.y, z = euler.z;
  8664. const a = Math.cos( x ), b = Math.sin( x );
  8665. const c = Math.cos( y ), d = Math.sin( y );
  8666. const e = Math.cos( z ), f = Math.sin( z );
  8667. if ( euler.order === 'XYZ' ) {
  8668. const ae = a * e, af = a * f, be = b * e, bf = b * f;
  8669. te[ 0 ] = c * e;
  8670. te[ 4 ] = - c * f;
  8671. te[ 8 ] = d;
  8672. te[ 1 ] = af + be * d;
  8673. te[ 5 ] = ae - bf * d;
  8674. te[ 9 ] = - b * c;
  8675. te[ 2 ] = bf - ae * d;
  8676. te[ 6 ] = be + af * d;
  8677. te[ 10 ] = a * c;
  8678. } else if ( euler.order === 'YXZ' ) {
  8679. const ce = c * e, cf = c * f, de = d * e, df = d * f;
  8680. te[ 0 ] = ce + df * b;
  8681. te[ 4 ] = de * b - cf;
  8682. te[ 8 ] = a * d;
  8683. te[ 1 ] = a * f;
  8684. te[ 5 ] = a * e;
  8685. te[ 9 ] = - b;
  8686. te[ 2 ] = cf * b - de;
  8687. te[ 6 ] = df + ce * b;
  8688. te[ 10 ] = a * c;
  8689. } else if ( euler.order === 'ZXY' ) {
  8690. const ce = c * e, cf = c * f, de = d * e, df = d * f;
  8691. te[ 0 ] = ce - df * b;
  8692. te[ 4 ] = - a * f;
  8693. te[ 8 ] = de + cf * b;
  8694. te[ 1 ] = cf + de * b;
  8695. te[ 5 ] = a * e;
  8696. te[ 9 ] = df - ce * b;
  8697. te[ 2 ] = - a * d;
  8698. te[ 6 ] = b;
  8699. te[ 10 ] = a * c;
  8700. } else if ( euler.order === 'ZYX' ) {
  8701. const ae = a * e, af = a * f, be = b * e, bf = b * f;
  8702. te[ 0 ] = c * e;
  8703. te[ 4 ] = be * d - af;
  8704. te[ 8 ] = ae * d + bf;
  8705. te[ 1 ] = c * f;
  8706. te[ 5 ] = bf * d + ae;
  8707. te[ 9 ] = af * d - be;
  8708. te[ 2 ] = - d;
  8709. te[ 6 ] = b * c;
  8710. te[ 10 ] = a * c;
  8711. } else if ( euler.order === 'YZX' ) {
  8712. const ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  8713. te[ 0 ] = c * e;
  8714. te[ 4 ] = bd - ac * f;
  8715. te[ 8 ] = bc * f + ad;
  8716. te[ 1 ] = f;
  8717. te[ 5 ] = a * e;
  8718. te[ 9 ] = - b * e;
  8719. te[ 2 ] = - d * e;
  8720. te[ 6 ] = ad * f + bc;
  8721. te[ 10 ] = ac - bd * f;
  8722. } else if ( euler.order === 'XZY' ) {
  8723. const ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  8724. te[ 0 ] = c * e;
  8725. te[ 4 ] = - f;
  8726. te[ 8 ] = d * e;
  8727. te[ 1 ] = ac * f + bd;
  8728. te[ 5 ] = a * e;
  8729. te[ 9 ] = ad * f - bc;
  8730. te[ 2 ] = bc * f - ad;
  8731. te[ 6 ] = b * e;
  8732. te[ 10 ] = bd * f + ac;
  8733. }
  8734. // bottom row
  8735. te[ 3 ] = 0;
  8736. te[ 7 ] = 0;
  8737. te[ 11 ] = 0;
  8738. // last column
  8739. te[ 12 ] = 0;
  8740. te[ 13 ] = 0;
  8741. te[ 14 ] = 0;
  8742. te[ 15 ] = 1;
  8743. return this;
  8744. }
  8745. /**
  8746. * Sets the rotation component of this matrix to the rotation specified by
  8747. * the given Quaternion as outlined [here]{@link https://en.wikipedia.org/wiki/Rotation_matrix#Quaternion}
  8748. * The rest of the matrix is set to the identity.
  8749. *
  8750. * @param {Quaternion} q - The Quaternion.
  8751. * @return {Matrix4} A reference to this matrix.
  8752. */
  8753. makeRotationFromQuaternion( q ) {
  8754. return this.compose( _zero, q, _one );
  8755. }
  8756. /**
  8757. * Sets the rotation component of the transformation matrix, looking from `eye` towards
  8758. * `target`, and oriented by the up-direction.
  8759. *
  8760. * @param {Vector3} eye - The eye vector.
  8761. * @param {Vector3} target - The target vector.
  8762. * @param {Vector3} up - The up vector.
  8763. * @return {Matrix4} A reference to this matrix.
  8764. */
  8765. lookAt( eye, target, up ) {
  8766. const te = this.elements;
  8767. _z.subVectors( eye, target );
  8768. if ( _z.lengthSq() === 0 ) {
  8769. // eye and target are in the same position
  8770. _z.z = 1;
  8771. }
  8772. _z.normalize();
  8773. _x.crossVectors( up, _z );
  8774. if ( _x.lengthSq() === 0 ) {
  8775. // up and z are parallel
  8776. if ( Math.abs( up.z ) === 1 ) {
  8777. _z.x += 0.0001;
  8778. } else {
  8779. _z.z += 0.0001;
  8780. }
  8781. _z.normalize();
  8782. _x.crossVectors( up, _z );
  8783. }
  8784. _x.normalize();
  8785. _y.crossVectors( _z, _x );
  8786. te[ 0 ] = _x.x; te[ 4 ] = _y.x; te[ 8 ] = _z.x;
  8787. te[ 1 ] = _x.y; te[ 5 ] = _y.y; te[ 9 ] = _z.y;
  8788. te[ 2 ] = _x.z; te[ 6 ] = _y.z; te[ 10 ] = _z.z;
  8789. return this;
  8790. }
  8791. /**
  8792. * Post-multiplies this matrix by the given 4x4 matrix.
  8793. *
  8794. * @param {Matrix4} m - The matrix to multiply with.
  8795. * @return {Matrix4} A reference to this matrix.
  8796. */
  8797. multiply( m ) {
  8798. return this.multiplyMatrices( this, m );
  8799. }
  8800. /**
  8801. * Pre-multiplies this matrix by the given 4x4 matrix.
  8802. *
  8803. * @param {Matrix4} m - The matrix to multiply with.
  8804. * @return {Matrix4} A reference to this matrix.
  8805. */
  8806. premultiply( m ) {
  8807. return this.multiplyMatrices( m, this );
  8808. }
  8809. /**
  8810. * Multiples the given 4x4 matrices and stores the result
  8811. * in this matrix.
  8812. *
  8813. * @param {Matrix4} a - The first matrix.
  8814. * @param {Matrix4} b - The second matrix.
  8815. * @return {Matrix4} A reference to this matrix.
  8816. */
  8817. multiplyMatrices( a, b ) {
  8818. const ae = a.elements;
  8819. const be = b.elements;
  8820. const te = this.elements;
  8821. const a11 = ae[ 0 ], a12 = ae[ 4 ], a13 = ae[ 8 ], a14 = ae[ 12 ];
  8822. const a21 = ae[ 1 ], a22 = ae[ 5 ], a23 = ae[ 9 ], a24 = ae[ 13 ];
  8823. const a31 = ae[ 2 ], a32 = ae[ 6 ], a33 = ae[ 10 ], a34 = ae[ 14 ];
  8824. const a41 = ae[ 3 ], a42 = ae[ 7 ], a43 = ae[ 11 ], a44 = ae[ 15 ];
  8825. const b11 = be[ 0 ], b12 = be[ 4 ], b13 = be[ 8 ], b14 = be[ 12 ];
  8826. const b21 = be[ 1 ], b22 = be[ 5 ], b23 = be[ 9 ], b24 = be[ 13 ];
  8827. const b31 = be[ 2 ], b32 = be[ 6 ], b33 = be[ 10 ], b34 = be[ 14 ];
  8828. const b41 = be[ 3 ], b42 = be[ 7 ], b43 = be[ 11 ], b44 = be[ 15 ];
  8829. te[ 0 ] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41;
  8830. te[ 4 ] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42;
  8831. te[ 8 ] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43;
  8832. te[ 12 ] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44;
  8833. te[ 1 ] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41;
  8834. te[ 5 ] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42;
  8835. te[ 9 ] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43;
  8836. te[ 13 ] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44;
  8837. te[ 2 ] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41;
  8838. te[ 6 ] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42;
  8839. te[ 10 ] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43;
  8840. te[ 14 ] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44;
  8841. te[ 3 ] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41;
  8842. te[ 7 ] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42;
  8843. te[ 11 ] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43;
  8844. te[ 15 ] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44;
  8845. return this;
  8846. }
  8847. /**
  8848. * Multiplies every component of the matrix by the given scalar.
  8849. *
  8850. * @param {number} s - The scalar.
  8851. * @return {Matrix4} A reference to this matrix.
  8852. */
  8853. multiplyScalar( s ) {
  8854. const te = this.elements;
  8855. te[ 0 ] *= s; te[ 4 ] *= s; te[ 8 ] *= s; te[ 12 ] *= s;
  8856. te[ 1 ] *= s; te[ 5 ] *= s; te[ 9 ] *= s; te[ 13 ] *= s;
  8857. te[ 2 ] *= s; te[ 6 ] *= s; te[ 10 ] *= s; te[ 14 ] *= s;
  8858. te[ 3 ] *= s; te[ 7 ] *= s; te[ 11 ] *= s; te[ 15 ] *= s;
  8859. return this;
  8860. }
  8861. /**
  8862. * Computes and returns the determinant of this matrix.
  8863. *
  8864. * Based on the method outlined [here]{@link http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.html}.
  8865. *
  8866. * @return {number} The determinant.
  8867. */
  8868. determinant() {
  8869. const te = this.elements;
  8870. const n11 = te[ 0 ], n12 = te[ 4 ], n13 = te[ 8 ], n14 = te[ 12 ];
  8871. const n21 = te[ 1 ], n22 = te[ 5 ], n23 = te[ 9 ], n24 = te[ 13 ];
  8872. const n31 = te[ 2 ], n32 = te[ 6 ], n33 = te[ 10 ], n34 = te[ 14 ];
  8873. const n41 = te[ 3 ], n42 = te[ 7 ], n43 = te[ 11 ], n44 = te[ 15 ];
  8874. //TODO: make this more efficient
  8875. return (
  8876. n41 * (
  8877. + n14 * n23 * n32
  8878. - n13 * n24 * n32
  8879. - n14 * n22 * n33
  8880. + n12 * n24 * n33
  8881. + n13 * n22 * n34
  8882. - n12 * n23 * n34
  8883. ) +
  8884. n42 * (
  8885. + n11 * n23 * n34
  8886. - n11 * n24 * n33
  8887. + n14 * n21 * n33
  8888. - n13 * n21 * n34
  8889. + n13 * n24 * n31
  8890. - n14 * n23 * n31
  8891. ) +
  8892. n43 * (
  8893. + n11 * n24 * n32
  8894. - n11 * n22 * n34
  8895. - n14 * n21 * n32
  8896. + n12 * n21 * n34
  8897. + n14 * n22 * n31
  8898. - n12 * n24 * n31
  8899. ) +
  8900. n44 * (
  8901. - n13 * n22 * n31
  8902. - n11 * n23 * n32
  8903. + n11 * n22 * n33
  8904. + n13 * n21 * n32
  8905. - n12 * n21 * n33
  8906. + n12 * n23 * n31
  8907. )
  8908. );
  8909. }
  8910. /**
  8911. * Transposes this matrix in place.
  8912. *
  8913. * @return {Matrix4} A reference to this matrix.
  8914. */
  8915. transpose() {
  8916. const te = this.elements;
  8917. let tmp;
  8918. tmp = te[ 1 ]; te[ 1 ] = te[ 4 ]; te[ 4 ] = tmp;
  8919. tmp = te[ 2 ]; te[ 2 ] = te[ 8 ]; te[ 8 ] = tmp;
  8920. tmp = te[ 6 ]; te[ 6 ] = te[ 9 ]; te[ 9 ] = tmp;
  8921. tmp = te[ 3 ]; te[ 3 ] = te[ 12 ]; te[ 12 ] = tmp;
  8922. tmp = te[ 7 ]; te[ 7 ] = te[ 13 ]; te[ 13 ] = tmp;
  8923. tmp = te[ 11 ]; te[ 11 ] = te[ 14 ]; te[ 14 ] = tmp;
  8924. return this;
  8925. }
  8926. /**
  8927. * Sets the position component for this matrix from the given vector,
  8928. * without affecting the rest of the matrix.
  8929. *
  8930. * @param {number|Vector3} x - The x component of the vector or alternatively the vector object.
  8931. * @param {number} y - The y component of the vector.
  8932. * @param {number} z - The z component of the vector.
  8933. * @return {Matrix4} A reference to this matrix.
  8934. */
  8935. setPosition( x, y, z ) {
  8936. const te = this.elements;
  8937. if ( x.isVector3 ) {
  8938. te[ 12 ] = x.x;
  8939. te[ 13 ] = x.y;
  8940. te[ 14 ] = x.z;
  8941. } else {
  8942. te[ 12 ] = x;
  8943. te[ 13 ] = y;
  8944. te[ 14 ] = z;
  8945. }
  8946. return this;
  8947. }
  8948. /**
  8949. * Inverts this matrix, using the [analytic method]{@link https://en.wikipedia.org/wiki/Invertible_matrix#Analytic_solution}.
  8950. * You can not invert with a determinant of zero. If you attempt this, the method produces
  8951. * a zero matrix instead.
  8952. *
  8953. * @return {Matrix4} A reference to this matrix.
  8954. */
  8955. invert() {
  8956. // based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm
  8957. const te = this.elements,
  8958. n11 = te[ 0 ], n21 = te[ 1 ], n31 = te[ 2 ], n41 = te[ 3 ],
  8959. n12 = te[ 4 ], n22 = te[ 5 ], n32 = te[ 6 ], n42 = te[ 7 ],
  8960. n13 = te[ 8 ], n23 = te[ 9 ], n33 = te[ 10 ], n43 = te[ 11 ],
  8961. n14 = te[ 12 ], n24 = te[ 13 ], n34 = te[ 14 ], n44 = te[ 15 ],
  8962. t11 = n23 * n34 * n42 - n24 * n33 * n42 + n24 * n32 * n43 - n22 * n34 * n43 - n23 * n32 * n44 + n22 * n33 * n44,
  8963. t12 = n14 * n33 * n42 - n13 * n34 * n42 - n14 * n32 * n43 + n12 * n34 * n43 + n13 * n32 * n44 - n12 * n33 * n44,
  8964. t13 = n13 * n24 * n42 - n14 * n23 * n42 + n14 * n22 * n43 - n12 * n24 * n43 - n13 * n22 * n44 + n12 * n23 * n44,
  8965. t14 = n14 * n23 * n32 - n13 * n24 * n32 - n14 * n22 * n33 + n12 * n24 * n33 + n13 * n22 * n34 - n12 * n23 * n34;
  8966. const det = n11 * t11 + n21 * t12 + n31 * t13 + n41 * t14;
  8967. if ( det === 0 ) return this.set( 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 );
  8968. const detInv = 1 / det;
  8969. te[ 0 ] = t11 * detInv;
  8970. te[ 1 ] = ( n24 * n33 * n41 - n23 * n34 * n41 - n24 * n31 * n43 + n21 * n34 * n43 + n23 * n31 * n44 - n21 * n33 * n44 ) * detInv;
  8971. te[ 2 ] = ( n22 * n34 * n41 - n24 * n32 * n41 + n24 * n31 * n42 - n21 * n34 * n42 - n22 * n31 * n44 + n21 * n32 * n44 ) * detInv;
  8972. te[ 3 ] = ( n23 * n32 * n41 - n22 * n33 * n41 - n23 * n31 * n42 + n21 * n33 * n42 + n22 * n31 * n43 - n21 * n32 * n43 ) * detInv;
  8973. te[ 4 ] = t12 * detInv;
  8974. te[ 5 ] = ( n13 * n34 * n41 - n14 * n33 * n41 + n14 * n31 * n43 - n11 * n34 * n43 - n13 * n31 * n44 + n11 * n33 * n44 ) * detInv;
  8975. te[ 6 ] = ( n14 * n32 * n41 - n12 * n34 * n41 - n14 * n31 * n42 + n11 * n34 * n42 + n12 * n31 * n44 - n11 * n32 * n44 ) * detInv;
  8976. te[ 7 ] = ( n12 * n33 * n41 - n13 * n32 * n41 + n13 * n31 * n42 - n11 * n33 * n42 - n12 * n31 * n43 + n11 * n32 * n43 ) * detInv;
  8977. te[ 8 ] = t13 * detInv;
  8978. te[ 9 ] = ( n14 * n23 * n41 - n13 * n24 * n41 - n14 * n21 * n43 + n11 * n24 * n43 + n13 * n21 * n44 - n11 * n23 * n44 ) * detInv;
  8979. te[ 10 ] = ( n12 * n24 * n41 - n14 * n22 * n41 + n14 * n21 * n42 - n11 * n24 * n42 - n12 * n21 * n44 + n11 * n22 * n44 ) * detInv;
  8980. te[ 11 ] = ( n13 * n22 * n41 - n12 * n23 * n41 - n13 * n21 * n42 + n11 * n23 * n42 + n12 * n21 * n43 - n11 * n22 * n43 ) * detInv;
  8981. te[ 12 ] = t14 * detInv;
  8982. te[ 13 ] = ( n13 * n24 * n31 - n14 * n23 * n31 + n14 * n21 * n33 - n11 * n24 * n33 - n13 * n21 * n34 + n11 * n23 * n34 ) * detInv;
  8983. te[ 14 ] = ( n14 * n22 * n31 - n12 * n24 * n31 - n14 * n21 * n32 + n11 * n24 * n32 + n12 * n21 * n34 - n11 * n22 * n34 ) * detInv;
  8984. te[ 15 ] = ( n12 * n23 * n31 - n13 * n22 * n31 + n13 * n21 * n32 - n11 * n23 * n32 - n12 * n21 * n33 + n11 * n22 * n33 ) * detInv;
  8985. return this;
  8986. }
  8987. /**
  8988. * Multiplies the columns of this matrix by the given vector.
  8989. *
  8990. * @param {Vector3} v - The scale vector.
  8991. * @return {Matrix4} A reference to this matrix.
  8992. */
  8993. scale( v ) {
  8994. const te = this.elements;
  8995. const x = v.x, y = v.y, z = v.z;
  8996. te[ 0 ] *= x; te[ 4 ] *= y; te[ 8 ] *= z;
  8997. te[ 1 ] *= x; te[ 5 ] *= y; te[ 9 ] *= z;
  8998. te[ 2 ] *= x; te[ 6 ] *= y; te[ 10 ] *= z;
  8999. te[ 3 ] *= x; te[ 7 ] *= y; te[ 11 ] *= z;
  9000. return this;
  9001. }
  9002. /**
  9003. * Gets the maximum scale value of the three axes.
  9004. *
  9005. * @return {number} The maximum scale.
  9006. */
  9007. getMaxScaleOnAxis() {
  9008. const te = this.elements;
  9009. const scaleXSq = te[ 0 ] * te[ 0 ] + te[ 1 ] * te[ 1 ] + te[ 2 ] * te[ 2 ];
  9010. const scaleYSq = te[ 4 ] * te[ 4 ] + te[ 5 ] * te[ 5 ] + te[ 6 ] * te[ 6 ];
  9011. const scaleZSq = te[ 8 ] * te[ 8 ] + te[ 9 ] * te[ 9 ] + te[ 10 ] * te[ 10 ];
  9012. return Math.sqrt( Math.max( scaleXSq, scaleYSq, scaleZSq ) );
  9013. }
  9014. /**
  9015. * Sets this matrix as a translation transform from the given vector.
  9016. *
  9017. * @param {number|Vector3} x - The amount to translate in the X axis or alternatively a translation vector.
  9018. * @param {number} y - The amount to translate in the Y axis.
  9019. * @param {number} z - The amount to translate in the z axis.
  9020. * @return {Matrix4} A reference to this matrix.
  9021. */
  9022. makeTranslation( x, y, z ) {
  9023. if ( x.isVector3 ) {
  9024. this.set(
  9025. 1, 0, 0, x.x,
  9026. 0, 1, 0, x.y,
  9027. 0, 0, 1, x.z,
  9028. 0, 0, 0, 1
  9029. );
  9030. } else {
  9031. this.set(
  9032. 1, 0, 0, x,
  9033. 0, 1, 0, y,
  9034. 0, 0, 1, z,
  9035. 0, 0, 0, 1
  9036. );
  9037. }
  9038. return this;
  9039. }
  9040. /**
  9041. * Sets this matrix as a rotational transformation around the X axis by
  9042. * the given angle.
  9043. *
  9044. * @param {number} theta - The rotation in radians.
  9045. * @return {Matrix4} A reference to this matrix.
  9046. */
  9047. makeRotationX( theta ) {
  9048. const c = Math.cos( theta ), s = Math.sin( theta );
  9049. this.set(
  9050. 1, 0, 0, 0,
  9051. 0, c, - s, 0,
  9052. 0, s, c, 0,
  9053. 0, 0, 0, 1
  9054. );
  9055. return this;
  9056. }
  9057. /**
  9058. * Sets this matrix as a rotational transformation around the Y axis by
  9059. * the given angle.
  9060. *
  9061. * @param {number} theta - The rotation in radians.
  9062. * @return {Matrix4} A reference to this matrix.
  9063. */
  9064. makeRotationY( theta ) {
  9065. const c = Math.cos( theta ), s = Math.sin( theta );
  9066. this.set(
  9067. c, 0, s, 0,
  9068. 0, 1, 0, 0,
  9069. - s, 0, c, 0,
  9070. 0, 0, 0, 1
  9071. );
  9072. return this;
  9073. }
  9074. /**
  9075. * Sets this matrix as a rotational transformation around the Z axis by
  9076. * the given angle.
  9077. *
  9078. * @param {number} theta - The rotation in radians.
  9079. * @return {Matrix4} A reference to this matrix.
  9080. */
  9081. makeRotationZ( theta ) {
  9082. const c = Math.cos( theta ), s = Math.sin( theta );
  9083. this.set(
  9084. c, - s, 0, 0,
  9085. s, c, 0, 0,
  9086. 0, 0, 1, 0,
  9087. 0, 0, 0, 1
  9088. );
  9089. return this;
  9090. }
  9091. /**
  9092. * Sets this matrix as a rotational transformation around the given axis by
  9093. * the given angle.
  9094. *
  9095. * This is a somewhat controversial but mathematically sound alternative to
  9096. * rotating via Quaternions. See the discussion [here]{@link https://www.gamedev.net/articles/programming/math-and-physics/do-we-really-need-quaternions-r1199}.
  9097. *
  9098. * @param {Vector3} axis - The normalized rotation axis.
  9099. * @param {number} angle - The rotation in radians.
  9100. * @return {Matrix4} A reference to this matrix.
  9101. */
  9102. makeRotationAxis( axis, angle ) {
  9103. // Based on http://www.gamedev.net/reference/articles/article1199.asp
  9104. const c = Math.cos( angle );
  9105. const s = Math.sin( angle );
  9106. const t = 1 - c;
  9107. const x = axis.x, y = axis.y, z = axis.z;
  9108. const tx = t * x, ty = t * y;
  9109. this.set(
  9110. tx * x + c, tx * y - s * z, tx * z + s * y, 0,
  9111. tx * y + s * z, ty * y + c, ty * z - s * x, 0,
  9112. tx * z - s * y, ty * z + s * x, t * z * z + c, 0,
  9113. 0, 0, 0, 1
  9114. );
  9115. return this;
  9116. }
  9117. /**
  9118. * Sets this matrix as a scale transformation.
  9119. *
  9120. * @param {number} x - The amount to scale in the X axis.
  9121. * @param {number} y - The amount to scale in the Y axis.
  9122. * @param {number} z - The amount to scale in the Z axis.
  9123. * @return {Matrix4} A reference to this matrix.
  9124. */
  9125. makeScale( x, y, z ) {
  9126. this.set(
  9127. x, 0, 0, 0,
  9128. 0, y, 0, 0,
  9129. 0, 0, z, 0,
  9130. 0, 0, 0, 1
  9131. );
  9132. return this;
  9133. }
  9134. /**
  9135. * Sets this matrix as a shear transformation.
  9136. *
  9137. * @param {number} xy - The amount to shear X by Y.
  9138. * @param {number} xz - The amount to shear X by Z.
  9139. * @param {number} yx - The amount to shear Y by X.
  9140. * @param {number} yz - The amount to shear Y by Z.
  9141. * @param {number} zx - The amount to shear Z by X.
  9142. * @param {number} zy - The amount to shear Z by Y.
  9143. * @return {Matrix4} A reference to this matrix.
  9144. */
  9145. makeShear( xy, xz, yx, yz, zx, zy ) {
  9146. this.set(
  9147. 1, yx, zx, 0,
  9148. xy, 1, zy, 0,
  9149. xz, yz, 1, 0,
  9150. 0, 0, 0, 1
  9151. );
  9152. return this;
  9153. }
  9154. /**
  9155. * Sets this matrix to the transformation composed of the given position,
  9156. * rotation (Quaternion) and scale.
  9157. *
  9158. * @param {Vector3} position - The position vector.
  9159. * @param {Quaternion} quaternion - The rotation as a Quaternion.
  9160. * @param {Vector3} scale - The scale vector.
  9161. * @return {Matrix4} A reference to this matrix.
  9162. */
  9163. compose( position, quaternion, scale ) {
  9164. const te = this.elements;
  9165. const x = quaternion._x, y = quaternion._y, z = quaternion._z, w = quaternion._w;
  9166. const x2 = x + x, y2 = y + y, z2 = z + z;
  9167. const xx = x * x2, xy = x * y2, xz = x * z2;
  9168. const yy = y * y2, yz = y * z2, zz = z * z2;
  9169. const wx = w * x2, wy = w * y2, wz = w * z2;
  9170. const sx = scale.x, sy = scale.y, sz = scale.z;
  9171. te[ 0 ] = ( 1 - ( yy + zz ) ) * sx;
  9172. te[ 1 ] = ( xy + wz ) * sx;
  9173. te[ 2 ] = ( xz - wy ) * sx;
  9174. te[ 3 ] = 0;
  9175. te[ 4 ] = ( xy - wz ) * sy;
  9176. te[ 5 ] = ( 1 - ( xx + zz ) ) * sy;
  9177. te[ 6 ] = ( yz + wx ) * sy;
  9178. te[ 7 ] = 0;
  9179. te[ 8 ] = ( xz + wy ) * sz;
  9180. te[ 9 ] = ( yz - wx ) * sz;
  9181. te[ 10 ] = ( 1 - ( xx + yy ) ) * sz;
  9182. te[ 11 ] = 0;
  9183. te[ 12 ] = position.x;
  9184. te[ 13 ] = position.y;
  9185. te[ 14 ] = position.z;
  9186. te[ 15 ] = 1;
  9187. return this;
  9188. }
  9189. /**
  9190. * Decomposes this matrix into its position, rotation and scale components
  9191. * and provides the result in the given objects.
  9192. *
  9193. * Note: Not all matrices are decomposable in this way. For example, if an
  9194. * object has a non-uniformly scaled parent, then the object's world matrix
  9195. * may not be decomposable, and this method may not be appropriate.
  9196. *
  9197. * @param {Vector3} position - The position vector.
  9198. * @param {Quaternion} quaternion - The rotation as a Quaternion.
  9199. * @param {Vector3} scale - The scale vector.
  9200. * @return {Matrix4} A reference to this matrix.
  9201. */
  9202. decompose( position, quaternion, scale ) {
  9203. const te = this.elements;
  9204. let sx = _v1$5.set( te[ 0 ], te[ 1 ], te[ 2 ] ).length();
  9205. const sy = _v1$5.set( te[ 4 ], te[ 5 ], te[ 6 ] ).length();
  9206. const sz = _v1$5.set( te[ 8 ], te[ 9 ], te[ 10 ] ).length();
  9207. // if determine is negative, we need to invert one scale
  9208. const det = this.determinant();
  9209. if ( det < 0 ) sx = - sx;
  9210. position.x = te[ 12 ];
  9211. position.y = te[ 13 ];
  9212. position.z = te[ 14 ];
  9213. // scale the rotation part
  9214. _m1$2.copy( this );
  9215. const invSX = 1 / sx;
  9216. const invSY = 1 / sy;
  9217. const invSZ = 1 / sz;
  9218. _m1$2.elements[ 0 ] *= invSX;
  9219. _m1$2.elements[ 1 ] *= invSX;
  9220. _m1$2.elements[ 2 ] *= invSX;
  9221. _m1$2.elements[ 4 ] *= invSY;
  9222. _m1$2.elements[ 5 ] *= invSY;
  9223. _m1$2.elements[ 6 ] *= invSY;
  9224. _m1$2.elements[ 8 ] *= invSZ;
  9225. _m1$2.elements[ 9 ] *= invSZ;
  9226. _m1$2.elements[ 10 ] *= invSZ;
  9227. quaternion.setFromRotationMatrix( _m1$2 );
  9228. scale.x = sx;
  9229. scale.y = sy;
  9230. scale.z = sz;
  9231. return this;
  9232. }
  9233. /**
  9234. * Creates a perspective projection matrix. This is used internally by
  9235. * {@link PerspectiveCamera#updateProjectionMatrix}.
  9236. * @param {number} left - Left boundary of the viewing frustum at the near plane.
  9237. * @param {number} right - Right boundary of the viewing frustum at the near plane.
  9238. * @param {number} top - Top boundary of the viewing frustum at the near plane.
  9239. * @param {number} bottom - Bottom boundary of the viewing frustum at the near plane.
  9240. * @param {number} near - The distance from the camera to the near plane.
  9241. * @param {number} far - The distance from the camera to the far plane.
  9242. * @param {(WebGLCoordinateSystem|WebGPUCoordinateSystem)} [coordinateSystem=WebGLCoordinateSystem] - The coordinate system.
  9243. * @return {Matrix4} A reference to this matrix.
  9244. */
  9245. makePerspective( left, right, top, bottom, near, far, coordinateSystem = WebGLCoordinateSystem ) {
  9246. const te = this.elements;
  9247. const x = 2 * near / ( right - left );
  9248. const y = 2 * near / ( top - bottom );
  9249. const a = ( right + left ) / ( right - left );
  9250. const b = ( top + bottom ) / ( top - bottom );
  9251. let c, d;
  9252. if ( coordinateSystem === WebGLCoordinateSystem ) {
  9253. c = - ( far + near ) / ( far - near );
  9254. d = ( -2 * far * near ) / ( far - near );
  9255. } else if ( coordinateSystem === WebGPUCoordinateSystem ) {
  9256. c = - far / ( far - near );
  9257. d = ( - far * near ) / ( far - near );
  9258. } else {
  9259. throw new Error( 'THREE.Matrix4.makePerspective(): Invalid coordinate system: ' + coordinateSystem );
  9260. }
  9261. te[ 0 ] = x; te[ 4 ] = 0; te[ 8 ] = a; te[ 12 ] = 0;
  9262. te[ 1 ] = 0; te[ 5 ] = y; te[ 9 ] = b; te[ 13 ] = 0;
  9263. te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = c; te[ 14 ] = d;
  9264. te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = -1; te[ 15 ] = 0;
  9265. return this;
  9266. }
  9267. /**
  9268. * Creates a orthographic projection matrix. This is used internally by
  9269. * {@link OrthographicCamera#updateProjectionMatrix}.
  9270. * @param {number} left - Left boundary of the viewing frustum at the near plane.
  9271. * @param {number} right - Right boundary of the viewing frustum at the near plane.
  9272. * @param {number} top - Top boundary of the viewing frustum at the near plane.
  9273. * @param {number} bottom - Bottom boundary of the viewing frustum at the near plane.
  9274. * @param {number} near - The distance from the camera to the near plane.
  9275. * @param {number} far - The distance from the camera to the far plane.
  9276. * @param {(WebGLCoordinateSystem|WebGPUCoordinateSystem)} [coordinateSystem=WebGLCoordinateSystem] - The coordinate system.
  9277. * @return {Matrix4} A reference to this matrix.
  9278. */
  9279. makeOrthographic( left, right, top, bottom, near, far, coordinateSystem = WebGLCoordinateSystem ) {
  9280. const te = this.elements;
  9281. const w = 1.0 / ( right - left );
  9282. const h = 1.0 / ( top - bottom );
  9283. const p = 1.0 / ( far - near );
  9284. const x = ( right + left ) * w;
  9285. const y = ( top + bottom ) * h;
  9286. let z, zInv;
  9287. if ( coordinateSystem === WebGLCoordinateSystem ) {
  9288. z = ( far + near ) * p;
  9289. zInv = -2 * p;
  9290. } else if ( coordinateSystem === WebGPUCoordinateSystem ) {
  9291. z = near * p;
  9292. zInv = -1 * p;
  9293. } else {
  9294. throw new Error( 'THREE.Matrix4.makeOrthographic(): Invalid coordinate system: ' + coordinateSystem );
  9295. }
  9296. te[ 0 ] = 2 * w; te[ 4 ] = 0; te[ 8 ] = 0; te[ 12 ] = - x;
  9297. te[ 1 ] = 0; te[ 5 ] = 2 * h; te[ 9 ] = 0; te[ 13 ] = - y;
  9298. te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = zInv; te[ 14 ] = - z;
  9299. te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = 0; te[ 15 ] = 1;
  9300. return this;
  9301. }
  9302. /**
  9303. * Returns `true` if this matrix is equal with the given one.
  9304. *
  9305. * @param {Matrix4} matrix - The matrix to test for equality.
  9306. * @return {boolean} Whether this matrix is equal with the given one.
  9307. */
  9308. equals( matrix ) {
  9309. const te = this.elements;
  9310. const me = matrix.elements;
  9311. for ( let i = 0; i < 16; i ++ ) {
  9312. if ( te[ i ] !== me[ i ] ) return false;
  9313. }
  9314. return true;
  9315. }
  9316. /**
  9317. * Sets the elements of the matrix from the given array.
  9318. *
  9319. * @param {Array<number>} array - The matrix elements in column-major order.
  9320. * @param {number} [offset=0] - Index of the first element in the array.
  9321. * @return {Matrix4} A reference to this matrix.
  9322. */
  9323. fromArray( array, offset = 0 ) {
  9324. for ( let i = 0; i < 16; i ++ ) {
  9325. this.elements[ i ] = array[ i + offset ];
  9326. }
  9327. return this;
  9328. }
  9329. /**
  9330. * Writes the elements of this matrix to the given array. If no array is provided,
  9331. * the method returns a new instance.
  9332. *
  9333. * @param {Array<number>} [array=[]] - The target array holding the matrix elements in column-major order.
  9334. * @param {number} [offset=0] - Index of the first element in the array.
  9335. * @return {Array<number>} The matrix elements in column-major order.
  9336. */
  9337. toArray( array = [], offset = 0 ) {
  9338. const te = this.elements;
  9339. array[ offset ] = te[ 0 ];
  9340. array[ offset + 1 ] = te[ 1 ];
  9341. array[ offset + 2 ] = te[ 2 ];
  9342. array[ offset + 3 ] = te[ 3 ];
  9343. array[ offset + 4 ] = te[ 4 ];
  9344. array[ offset + 5 ] = te[ 5 ];
  9345. array[ offset + 6 ] = te[ 6 ];
  9346. array[ offset + 7 ] = te[ 7 ];
  9347. array[ offset + 8 ] = te[ 8 ];
  9348. array[ offset + 9 ] = te[ 9 ];
  9349. array[ offset + 10 ] = te[ 10 ];
  9350. array[ offset + 11 ] = te[ 11 ];
  9351. array[ offset + 12 ] = te[ 12 ];
  9352. array[ offset + 13 ] = te[ 13 ];
  9353. array[ offset + 14 ] = te[ 14 ];
  9354. array[ offset + 15 ] = te[ 15 ];
  9355. return array;
  9356. }
  9357. }
  9358. const _v1$5 = /*@__PURE__*/ new Vector3();
  9359. const _m1$2 = /*@__PURE__*/ new Matrix4();
  9360. const _zero = /*@__PURE__*/ new Vector3( 0, 0, 0 );
  9361. const _one = /*@__PURE__*/ new Vector3( 1, 1, 1 );
  9362. const _x = /*@__PURE__*/ new Vector3();
  9363. const _y = /*@__PURE__*/ new Vector3();
  9364. const _z = /*@__PURE__*/ new Vector3();
  9365. const _matrix$2 = /*@__PURE__*/ new Matrix4();
  9366. const _quaternion$3 = /*@__PURE__*/ new Quaternion();
  9367. /**
  9368. * A class representing Euler angles.
  9369. *
  9370. * Euler angles describe a rotational transformation by rotating an object on
  9371. * its various axes in specified amounts per axis, and a specified axis
  9372. * order.
  9373. *
  9374. * Iterating through an instance will yield its components (x, y, z,
  9375. * order) in the corresponding order.
  9376. *
  9377. * ```js
  9378. * const a = new THREE.Euler( 0, 1, 1.57, 'XYZ' );
  9379. * const b = new THREE.Vector3( 1, 0, 1 );
  9380. * b.applyEuler(a);
  9381. * ```
  9382. */
  9383. class Euler {
  9384. /**
  9385. * Constructs a new euler instance.
  9386. *
  9387. * @param {number} [x=0] - The angle of the x axis in radians.
  9388. * @param {number} [y=0] - The angle of the y axis in radians.
  9389. * @param {number} [z=0] - The angle of the z axis in radians.
  9390. * @param {string} [order=Euler.DEFAULT_ORDER] - A string representing the order that the rotations are applied.
  9391. */
  9392. constructor( x = 0, y = 0, z = 0, order = Euler.DEFAULT_ORDER ) {
  9393. /**
  9394. * This flag can be used for type testing.
  9395. *
  9396. * @type {boolean}
  9397. * @readonly
  9398. * @default true
  9399. */
  9400. this.isEuler = true;
  9401. this._x = x;
  9402. this._y = y;
  9403. this._z = z;
  9404. this._order = order;
  9405. }
  9406. /**
  9407. * The angle of the x axis in radians.
  9408. *
  9409. * @type {number}
  9410. * @default 0
  9411. */
  9412. get x() {
  9413. return this._x;
  9414. }
  9415. set x( value ) {
  9416. this._x = value;
  9417. this._onChangeCallback();
  9418. }
  9419. /**
  9420. * The angle of the y axis in radians.
  9421. *
  9422. * @type {number}
  9423. * @default 0
  9424. */
  9425. get y() {
  9426. return this._y;
  9427. }
  9428. set y( value ) {
  9429. this._y = value;
  9430. this._onChangeCallback();
  9431. }
  9432. /**
  9433. * The angle of the z axis in radians.
  9434. *
  9435. * @type {number}
  9436. * @default 0
  9437. */
  9438. get z() {
  9439. return this._z;
  9440. }
  9441. set z( value ) {
  9442. this._z = value;
  9443. this._onChangeCallback();
  9444. }
  9445. /**
  9446. * A string representing the order that the rotations are applied.
  9447. *
  9448. * @type {string}
  9449. * @default 'XYZ'
  9450. */
  9451. get order() {
  9452. return this._order;
  9453. }
  9454. set order( value ) {
  9455. this._order = value;
  9456. this._onChangeCallback();
  9457. }
  9458. /**
  9459. * Sets the Euler components.
  9460. *
  9461. * @param {number} x - The angle of the x axis in radians.
  9462. * @param {number} y - The angle of the y axis in radians.
  9463. * @param {number} z - The angle of the z axis in radians.
  9464. * @param {string} [order] - A string representing the order that the rotations are applied.
  9465. * @return {Euler} A reference to this Euler instance.
  9466. */
  9467. set( x, y, z, order = this._order ) {
  9468. this._x = x;
  9469. this._y = y;
  9470. this._z = z;
  9471. this._order = order;
  9472. this._onChangeCallback();
  9473. return this;
  9474. }
  9475. /**
  9476. * Returns a new Euler instance with copied values from this instance.
  9477. *
  9478. * @return {Euler} A clone of this instance.
  9479. */
  9480. clone() {
  9481. return new this.constructor( this._x, this._y, this._z, this._order );
  9482. }
  9483. /**
  9484. * Copies the values of the given Euler instance to this instance.
  9485. *
  9486. * @param {Euler} euler - The Euler instance to copy.
  9487. * @return {Euler} A reference to this Euler instance.
  9488. */
  9489. copy( euler ) {
  9490. this._x = euler._x;
  9491. this._y = euler._y;
  9492. this._z = euler._z;
  9493. this._order = euler._order;
  9494. this._onChangeCallback();
  9495. return this;
  9496. }
  9497. /**
  9498. * Sets the angles of this Euler instance from a pure rotation matrix.
  9499. *
  9500. * @param {Matrix4} m - A 4x4 matrix of which the upper 3x3 of matrix is a pure rotation matrix (i.e. unscaled).
  9501. * @param {string} [order] - A string representing the order that the rotations are applied.
  9502. * @param {boolean} [update=true] - Whether the internal `onChange` callback should be executed or not.
  9503. * @return {Euler} A reference to this Euler instance.
  9504. */
  9505. setFromRotationMatrix( m, order = this._order, update = true ) {
  9506. const te = m.elements;
  9507. const m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ];
  9508. const m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ];
  9509. const m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];
  9510. switch ( order ) {
  9511. case 'XYZ':
  9512. this._y = Math.asin( clamp( m13, -1, 1 ) );
  9513. if ( Math.abs( m13 ) < 0.9999999 ) {
  9514. this._x = Math.atan2( - m23, m33 );
  9515. this._z = Math.atan2( - m12, m11 );
  9516. } else {
  9517. this._x = Math.atan2( m32, m22 );
  9518. this._z = 0;
  9519. }
  9520. break;
  9521. case 'YXZ':
  9522. this._x = Math.asin( - clamp( m23, -1, 1 ) );
  9523. if ( Math.abs( m23 ) < 0.9999999 ) {
  9524. this._y = Math.atan2( m13, m33 );
  9525. this._z = Math.atan2( m21, m22 );
  9526. } else {
  9527. this._y = Math.atan2( - m31, m11 );
  9528. this._z = 0;
  9529. }
  9530. break;
  9531. case 'ZXY':
  9532. this._x = Math.asin( clamp( m32, -1, 1 ) );
  9533. if ( Math.abs( m32 ) < 0.9999999 ) {
  9534. this._y = Math.atan2( - m31, m33 );
  9535. this._z = Math.atan2( - m12, m22 );
  9536. } else {
  9537. this._y = 0;
  9538. this._z = Math.atan2( m21, m11 );
  9539. }
  9540. break;
  9541. case 'ZYX':
  9542. this._y = Math.asin( - clamp( m31, -1, 1 ) );
  9543. if ( Math.abs( m31 ) < 0.9999999 ) {
  9544. this._x = Math.atan2( m32, m33 );
  9545. this._z = Math.atan2( m21, m11 );
  9546. } else {
  9547. this._x = 0;
  9548. this._z = Math.atan2( - m12, m22 );
  9549. }
  9550. break;
  9551. case 'YZX':
  9552. this._z = Math.asin( clamp( m21, -1, 1 ) );
  9553. if ( Math.abs( m21 ) < 0.9999999 ) {
  9554. this._x = Math.atan2( - m23, m22 );
  9555. this._y = Math.atan2( - m31, m11 );
  9556. } else {
  9557. this._x = 0;
  9558. this._y = Math.atan2( m13, m33 );
  9559. }
  9560. break;
  9561. case 'XZY':
  9562. this._z = Math.asin( - clamp( m12, -1, 1 ) );
  9563. if ( Math.abs( m12 ) < 0.9999999 ) {
  9564. this._x = Math.atan2( m32, m22 );
  9565. this._y = Math.atan2( m13, m11 );
  9566. } else {
  9567. this._x = Math.atan2( - m23, m33 );
  9568. this._y = 0;
  9569. }
  9570. break;
  9571. default:
  9572. console.warn( 'THREE.Euler: .setFromRotationMatrix() encountered an unknown order: ' + order );
  9573. }
  9574. this._order = order;
  9575. if ( update === true ) this._onChangeCallback();
  9576. return this;
  9577. }
  9578. /**
  9579. * Sets the angles of this Euler instance from a normalized quaternion.
  9580. *
  9581. * @param {Quaternion} q - A normalized Quaternion.
  9582. * @param {string} [order] - A string representing the order that the rotations are applied.
  9583. * @param {boolean} [update=true] - Whether the internal `onChange` callback should be executed or not.
  9584. * @return {Euler} A reference to this Euler instance.
  9585. */
  9586. setFromQuaternion( q, order, update ) {
  9587. _matrix$2.makeRotationFromQuaternion( q );
  9588. return this.setFromRotationMatrix( _matrix$2, order, update );
  9589. }
  9590. /**
  9591. * Sets the angles of this Euler instance from the given vector.
  9592. *
  9593. * @param {Vector3} v - The vector.
  9594. * @param {string} [order] - A string representing the order that the rotations are applied.
  9595. * @return {Euler} A reference to this Euler instance.
  9596. */
  9597. setFromVector3( v, order = this._order ) {
  9598. return this.set( v.x, v.y, v.z, order );
  9599. }
  9600. /**
  9601. * Resets the euler angle with a new order by creating a quaternion from this
  9602. * euler angle and then setting this euler angle with the quaternion and the
  9603. * new order.
  9604. *
  9605. * Warning: This discards revolution information.
  9606. *
  9607. * @param {string} [newOrder] - A string representing the new order that the rotations are applied.
  9608. * @return {Euler} A reference to this Euler instance.
  9609. */
  9610. reorder( newOrder ) {
  9611. _quaternion$3.setFromEuler( this );
  9612. return this.setFromQuaternion( _quaternion$3, newOrder );
  9613. }
  9614. /**
  9615. * Returns `true` if this Euler instance is equal with the given one.
  9616. *
  9617. * @param {Euler} euler - The Euler instance to test for equality.
  9618. * @return {boolean} Whether this Euler instance is equal with the given one.
  9619. */
  9620. equals( euler ) {
  9621. return ( euler._x === this._x ) && ( euler._y === this._y ) && ( euler._z === this._z ) && ( euler._order === this._order );
  9622. }
  9623. /**
  9624. * Sets this Euler instance's components to values from the given array. The first three
  9625. * entries of the array are assign to the x,y and z components. An optional fourth entry
  9626. * defines the Euler order.
  9627. *
  9628. * @param {Array<number,number,number,?string>} array - An array holding the Euler component values.
  9629. * @return {Euler} A reference to this Euler instance.
  9630. */
  9631. fromArray( array ) {
  9632. this._x = array[ 0 ];
  9633. this._y = array[ 1 ];
  9634. this._z = array[ 2 ];
  9635. if ( array[ 3 ] !== undefined ) this._order = array[ 3 ];
  9636. this._onChangeCallback();
  9637. return this;
  9638. }
  9639. /**
  9640. * Writes the components of this Euler instance to the given array. If no array is provided,
  9641. * the method returns a new instance.
  9642. *
  9643. * @param {Array<number,number,number,string>} [array=[]] - The target array holding the Euler components.
  9644. * @param {number} [offset=0] - Index of the first element in the array.
  9645. * @return {Array<number,number,number,string>} The Euler components.
  9646. */
  9647. toArray( array = [], offset = 0 ) {
  9648. array[ offset ] = this._x;
  9649. array[ offset + 1 ] = this._y;
  9650. array[ offset + 2 ] = this._z;
  9651. array[ offset + 3 ] = this._order;
  9652. return array;
  9653. }
  9654. _onChange( callback ) {
  9655. this._onChangeCallback = callback;
  9656. return this;
  9657. }
  9658. _onChangeCallback() {}
  9659. *[ Symbol.iterator ]() {
  9660. yield this._x;
  9661. yield this._y;
  9662. yield this._z;
  9663. yield this._order;
  9664. }
  9665. }
  9666. /**
  9667. * The default Euler angle order.
  9668. *
  9669. * @static
  9670. * @type {string}
  9671. * @default 'XYZ'
  9672. */
  9673. Euler.DEFAULT_ORDER = 'XYZ';
  9674. /**
  9675. * A layers object assigns an 3D object to 1 or more of 32
  9676. * layers numbered `0` to `31` - internally the layers are stored as a
  9677. * bit mask], and by default all 3D objects are a member of layer `0`.
  9678. *
  9679. * This can be used to control visibility - an object must share a layer with
  9680. * a camera to be visible when that camera's view is
  9681. * rendered.
  9682. *
  9683. * All classes that inherit from {@link Object3D} have an `layers` property which
  9684. * is an instance of this class.
  9685. */
  9686. class Layers {
  9687. /**
  9688. * Constructs a new layers instance, with membership
  9689. * initially set to layer `0`.
  9690. */
  9691. constructor() {
  9692. /**
  9693. * A bit mask storing which of the 32 layers this layers object is currently
  9694. * a member of.
  9695. *
  9696. * @type {number}
  9697. */
  9698. this.mask = 1 | 0;
  9699. }
  9700. /**
  9701. * Sets membership to the given layer, and remove membership all other layers.
  9702. *
  9703. * @param {number} layer - The layer to set.
  9704. */
  9705. set( layer ) {
  9706. this.mask = ( 1 << layer | 0 ) >>> 0;
  9707. }
  9708. /**
  9709. * Adds membership of the given layer.
  9710. *
  9711. * @param {number} layer - The layer to enable.
  9712. */
  9713. enable( layer ) {
  9714. this.mask |= 1 << layer | 0;
  9715. }
  9716. /**
  9717. * Adds membership to all layers.
  9718. */
  9719. enableAll() {
  9720. this.mask = 0xffffffff | 0;
  9721. }
  9722. /**
  9723. * Toggles the membership of the given layer.
  9724. *
  9725. * @param {number} layer - The layer to toggle.
  9726. */
  9727. toggle( layer ) {
  9728. this.mask ^= 1 << layer | 0;
  9729. }
  9730. /**
  9731. * Removes membership of the given layer.
  9732. *
  9733. * @param {number} layer - The layer to enable.
  9734. */
  9735. disable( layer ) {
  9736. this.mask &= ~ ( 1 << layer | 0 );
  9737. }
  9738. /**
  9739. * Removes the membership from all layers.
  9740. */
  9741. disableAll() {
  9742. this.mask = 0;
  9743. }
  9744. /**
  9745. * Returns `true` if this and the given layers object have at least one
  9746. * layer in common.
  9747. *
  9748. * @param {Layers} layers - The layers to test.
  9749. * @return {boolean } Whether this and the given layers object have at least one layer in common or not.
  9750. */
  9751. test( layers ) {
  9752. return ( this.mask & layers.mask ) !== 0;
  9753. }
  9754. /**
  9755. * Returns `true` if the given layer is enabled.
  9756. *
  9757. * @param {number} layer - The layer to test.
  9758. * @return {boolean } Whether the given layer is enabled or not.
  9759. */
  9760. isEnabled( layer ) {
  9761. return ( this.mask & ( 1 << layer | 0 ) ) !== 0;
  9762. }
  9763. }
  9764. let _object3DId = 0;
  9765. const _v1$4 = /*@__PURE__*/ new Vector3();
  9766. const _q1 = /*@__PURE__*/ new Quaternion();
  9767. const _m1$1 = /*@__PURE__*/ new Matrix4();
  9768. const _target = /*@__PURE__*/ new Vector3();
  9769. const _position$3 = /*@__PURE__*/ new Vector3();
  9770. const _scale$2 = /*@__PURE__*/ new Vector3();
  9771. const _quaternion$2 = /*@__PURE__*/ new Quaternion();
  9772. const _xAxis = /*@__PURE__*/ new Vector3( 1, 0, 0 );
  9773. const _yAxis = /*@__PURE__*/ new Vector3( 0, 1, 0 );
  9774. const _zAxis = /*@__PURE__*/ new Vector3( 0, 0, 1 );
  9775. /**
  9776. * Fires when the object has been added to its parent object.
  9777. *
  9778. * @event Object3D#added
  9779. * @type {Object}
  9780. */
  9781. const _addedEvent = { type: 'added' };
  9782. /**
  9783. * Fires when the object has been removed from its parent object.
  9784. *
  9785. * @event Object3D#removed
  9786. * @type {Object}
  9787. */
  9788. const _removedEvent = { type: 'removed' };
  9789. /**
  9790. * Fires when a new child object has been added.
  9791. *
  9792. * @event Object3D#childadded
  9793. * @type {Object}
  9794. */
  9795. const _childaddedEvent = { type: 'childadded', child: null };
  9796. /**
  9797. * Fires when a new child object has been added.
  9798. *
  9799. * @event Object3D#childremoved
  9800. * @type {Object}
  9801. */
  9802. const _childremovedEvent = { type: 'childremoved', child: null };
  9803. /**
  9804. * This is the base class for most objects in three.js and provides a set of
  9805. * properties and methods for manipulating objects in 3D space.
  9806. *
  9807. * @augments EventDispatcher
  9808. */
  9809. class Object3D extends EventDispatcher {
  9810. /**
  9811. * Constructs a new 3D object.
  9812. */
  9813. constructor() {
  9814. super();
  9815. /**
  9816. * This flag can be used for type testing.
  9817. *
  9818. * @type {boolean}
  9819. * @readonly
  9820. * @default true
  9821. */
  9822. this.isObject3D = true;
  9823. /**
  9824. * The ID of the 3D object.
  9825. *
  9826. * @name Object3D#id
  9827. * @type {number}
  9828. * @readonly
  9829. */
  9830. Object.defineProperty( this, 'id', { value: _object3DId ++ } );
  9831. /**
  9832. * The UUID of the 3D object.
  9833. *
  9834. * @type {string}
  9835. * @readonly
  9836. */
  9837. this.uuid = generateUUID();
  9838. /**
  9839. * The name of the 3D object.
  9840. *
  9841. * @type {string}
  9842. */
  9843. this.name = '';
  9844. /**
  9845. * The type property is used for detecting the object type
  9846. * in context of serialization/deserialization.
  9847. *
  9848. * @type {string}
  9849. * @readonly
  9850. */
  9851. this.type = 'Object3D';
  9852. /**
  9853. * A reference to the parent object.
  9854. *
  9855. * @type {?Object3D}
  9856. * @default null
  9857. */
  9858. this.parent = null;
  9859. /**
  9860. * An array holding the child 3D objects of this instance.
  9861. *
  9862. * @type {Array<Object3D>}
  9863. */
  9864. this.children = [];
  9865. /**
  9866. * Defines the `up` direction of the 3D object which influences
  9867. * the orientation via methods like {@link Object3D#lookAt}.
  9868. *
  9869. * The default values for all 3D objects is defined by `Object3D.DEFAULT_UP`.
  9870. *
  9871. * @type {Vector3}
  9872. */
  9873. this.up = Object3D.DEFAULT_UP.clone();
  9874. const position = new Vector3();
  9875. const rotation = new Euler();
  9876. const quaternion = new Quaternion();
  9877. const scale = new Vector3( 1, 1, 1 );
  9878. function onRotationChange() {
  9879. quaternion.setFromEuler( rotation, false );
  9880. }
  9881. function onQuaternionChange() {
  9882. rotation.setFromQuaternion( quaternion, undefined, false );
  9883. }
  9884. rotation._onChange( onRotationChange );
  9885. quaternion._onChange( onQuaternionChange );
  9886. Object.defineProperties( this, {
  9887. /**
  9888. * Represents the object's local position.
  9889. *
  9890. * @name Object3D#position
  9891. * @type {Vector3}
  9892. * @default (0,0,0)
  9893. */
  9894. position: {
  9895. configurable: true,
  9896. enumerable: true,
  9897. value: position
  9898. },
  9899. /**
  9900. * Represents the object's local rotation as Euler angles, in radians.
  9901. *
  9902. * @name Object3D#rotation
  9903. * @type {Euler}
  9904. * @default (0,0,0)
  9905. */
  9906. rotation: {
  9907. configurable: true,
  9908. enumerable: true,
  9909. value: rotation
  9910. },
  9911. /**
  9912. * Represents the object's local rotation as Quaternions.
  9913. *
  9914. * @name Object3D#quaternion
  9915. * @type {Quaternion}
  9916. */
  9917. quaternion: {
  9918. configurable: true,
  9919. enumerable: true,
  9920. value: quaternion
  9921. },
  9922. /**
  9923. * Represents the object's local scale.
  9924. *
  9925. * @name Object3D#scale
  9926. * @type {Vector3}
  9927. * @default (1,1,1)
  9928. */
  9929. scale: {
  9930. configurable: true,
  9931. enumerable: true,
  9932. value: scale
  9933. },
  9934. /**
  9935. * Represents the object's model-view matrix.
  9936. *
  9937. * @name Object3D#modelViewMatrix
  9938. * @type {Matrix4}
  9939. */
  9940. modelViewMatrix: {
  9941. value: new Matrix4()
  9942. },
  9943. /**
  9944. * Represents the object's normal matrix.
  9945. *
  9946. * @name Object3D#normalMatrix
  9947. * @type {Matrix3}
  9948. */
  9949. normalMatrix: {
  9950. value: new Matrix3()
  9951. }
  9952. } );
  9953. /**
  9954. * Represents the object's transformation matrix in local space.
  9955. *
  9956. * @type {Matrix4}
  9957. */
  9958. this.matrix = new Matrix4();
  9959. /**
  9960. * Represents the object's transformation matrix in world space.
  9961. * If the 3D object has no parent, then it's identical to the local transformation matrix
  9962. *
  9963. * @type {Matrix4}
  9964. */
  9965. this.matrixWorld = new Matrix4();
  9966. /**
  9967. * When set to `true`, the engine automatically computes the local matrix from position,
  9968. * rotation and scale every frame.
  9969. *
  9970. * The default values for all 3D objects is defined by `Object3D.DEFAULT_MATRIX_AUTO_UPDATE`.
  9971. *
  9972. * @type {boolean}
  9973. * @default true
  9974. */
  9975. this.matrixAutoUpdate = Object3D.DEFAULT_MATRIX_AUTO_UPDATE;
  9976. /**
  9977. * When set to `true`, the engine automatically computes the world matrix from the current local
  9978. * matrix and the object's transformation hierarchy.
  9979. *
  9980. * The default values for all 3D objects is defined by `Object3D.DEFAULT_MATRIX_WORLD_AUTO_UPDATE`.
  9981. *
  9982. * @type {boolean}
  9983. * @default true
  9984. */
  9985. this.matrixWorldAutoUpdate = Object3D.DEFAULT_MATRIX_WORLD_AUTO_UPDATE; // checked by the renderer
  9986. /**
  9987. * When set to `true`, it calculates the world matrix in that frame and resets this property
  9988. * to `false`.
  9989. *
  9990. * @type {boolean}
  9991. * @default false
  9992. */
  9993. this.matrixWorldNeedsUpdate = false;
  9994. /**
  9995. * The layer membership of the 3D object. The 3D object is only visible if it has
  9996. * at least one layer in common with the camera in use. This property can also be
  9997. * used to filter out unwanted objects in ray-intersection tests when using {@link Raycaster}.
  9998. *
  9999. * @type {Layers}
  10000. */
  10001. this.layers = new Layers();
  10002. /**
  10003. * When set to `true`, the 3D object gets rendered.
  10004. *
  10005. * @type {boolean}
  10006. * @default true
  10007. */
  10008. this.visible = true;
  10009. /**
  10010. * When set to `true`, the 3D object gets rendered into shadow maps.
  10011. *
  10012. * @type {boolean}
  10013. * @default false
  10014. */
  10015. this.castShadow = false;
  10016. /**
  10017. * When set to `true`, the 3D object is affected by shadows in the scene.
  10018. *
  10019. * @type {boolean}
  10020. * @default false
  10021. */
  10022. this.receiveShadow = false;
  10023. /**
  10024. * When set to `true`, the 3D object is honored by view frustum culling.
  10025. *
  10026. * @type {boolean}
  10027. * @default true
  10028. */
  10029. this.frustumCulled = true;
  10030. /**
  10031. * This value allows the default rendering order of scene graph objects to be
  10032. * overridden although opaque and transparent objects remain sorted independently.
  10033. * When this property is set for an instance of {@link Group},all descendants
  10034. * objects will be sorted and rendered together. Sorting is from lowest to highest
  10035. * render order.
  10036. *
  10037. * @type {number}
  10038. * @default 0
  10039. */
  10040. this.renderOrder = 0;
  10041. /**
  10042. * An array holding the animation clips of the 3D object.
  10043. *
  10044. * @type {Array<AnimationClip>}
  10045. */
  10046. this.animations = [];
  10047. /**
  10048. * Custom depth material to be used when rendering to the depth map. Can only be used
  10049. * in context of meshes. When shadow-casting with a {@link DirectionalLight} or {@link SpotLight},
  10050. * if you are modifying vertex positions in the vertex shader you must specify a custom depth
  10051. * material for proper shadows.
  10052. *
  10053. * Only relevant in context of {@link WebGLRenderer}.
  10054. *
  10055. * @type {(Material|undefined)}
  10056. * @default undefined
  10057. */
  10058. this.customDepthMaterial = undefined;
  10059. /**
  10060. * Same as {@link Object3D#customDepthMaterial}, but used with {@link PointLight}.
  10061. *
  10062. * Only relevant in context of {@link WebGLRenderer}.
  10063. *
  10064. * @type {(Material|undefined)}
  10065. * @default undefined
  10066. */
  10067. this.customDistanceMaterial = undefined;
  10068. /**
  10069. * An object that can be used to store custom data about the 3D object. It
  10070. * should not hold references to functions as these will not be cloned.
  10071. *
  10072. * @type {Object}
  10073. */
  10074. this.userData = {};
  10075. }
  10076. /**
  10077. * A callback that is executed immediately before a 3D object is rendered to a shadow map.
  10078. *
  10079. * @param {Renderer|WebGLRenderer} renderer - The renderer.
  10080. * @param {Object3D} object - The 3D object.
  10081. * @param {Camera} camera - The camera that is used to render the scene.
  10082. * @param {Camera} shadowCamera - The shadow camera.
  10083. * @param {BufferGeometry} geometry - The 3D object's geometry.
  10084. * @param {Material} depthMaterial - The depth material.
  10085. * @param {Object} group - The geometry group data.
  10086. */
  10087. onBeforeShadow( /* renderer, object, camera, shadowCamera, geometry, depthMaterial, group */ ) {}
  10088. /**
  10089. * A callback that is executed immediately after a 3D object is rendered to a shadow map.
  10090. *
  10091. * @param {Renderer|WebGLRenderer} renderer - The renderer.
  10092. * @param {Object3D} object - The 3D object.
  10093. * @param {Camera} camera - The camera that is used to render the scene.
  10094. * @param {Camera} shadowCamera - The shadow camera.
  10095. * @param {BufferGeometry} geometry - The 3D object's geometry.
  10096. * @param {Material} depthMaterial - The depth material.
  10097. * @param {Object} group - The geometry group data.
  10098. */
  10099. onAfterShadow( /* renderer, object, camera, shadowCamera, geometry, depthMaterial, group */ ) {}
  10100. /**
  10101. * A callback that is executed immediately before a 3D object is rendered.
  10102. *
  10103. * @param {Renderer|WebGLRenderer} renderer - The renderer.
  10104. * @param {Object3D} object - The 3D object.
  10105. * @param {Camera} camera - The camera that is used to render the scene.
  10106. * @param {BufferGeometry} geometry - The 3D object's geometry.
  10107. * @param {Material} material - The 3D object's material.
  10108. * @param {Object} group - The geometry group data.
  10109. */
  10110. onBeforeRender( /* renderer, scene, camera, geometry, material, group */ ) {}
  10111. /**
  10112. * A callback that is executed immediately after a 3D object is rendered.
  10113. *
  10114. * @param {Renderer|WebGLRenderer} renderer - The renderer.
  10115. * @param {Object3D} object - The 3D object.
  10116. * @param {Camera} camera - The camera that is used to render the scene.
  10117. * @param {BufferGeometry} geometry - The 3D object's geometry.
  10118. * @param {Material} material - The 3D object's material.
  10119. * @param {Object} group - The geometry group data.
  10120. */
  10121. onAfterRender( /* renderer, scene, camera, geometry, material, group */ ) {}
  10122. /**
  10123. * Applies the given transformation matrix to the object and updates the object's position,
  10124. * rotation and scale.
  10125. *
  10126. * @param {Matrix4} matrix - The transformation matrix.
  10127. */
  10128. applyMatrix4( matrix ) {
  10129. if ( this.matrixAutoUpdate ) this.updateMatrix();
  10130. this.matrix.premultiply( matrix );
  10131. this.matrix.decompose( this.position, this.quaternion, this.scale );
  10132. }
  10133. /**
  10134. * Applies a rotation represented by given the quaternion to the 3D object.
  10135. *
  10136. * @param {Quaternion} q - The quaternion.
  10137. * @return {Object3D} A reference to this instance.
  10138. */
  10139. applyQuaternion( q ) {
  10140. this.quaternion.premultiply( q );
  10141. return this;
  10142. }
  10143. /**
  10144. * Sets the given rotation represented as an axis/angle couple to the 3D object.
  10145. *
  10146. * @param {Vector3} axis - The (normalized) axis vector.
  10147. * @param {number} angle - The angle in radians.
  10148. */
  10149. setRotationFromAxisAngle( axis, angle ) {
  10150. // assumes axis is normalized
  10151. this.quaternion.setFromAxisAngle( axis, angle );
  10152. }
  10153. /**
  10154. * Sets the given rotation represented as Euler angles to the 3D object.
  10155. *
  10156. * @param {Euler} euler - The Euler angles.
  10157. */
  10158. setRotationFromEuler( euler ) {
  10159. this.quaternion.setFromEuler( euler, true );
  10160. }
  10161. /**
  10162. * Sets the given rotation represented as rotation matrix to the 3D object.
  10163. *
  10164. * @param {Matrix4} m - Although a 4x4 matrix is expected, the upper 3x3 portion must be
  10165. * a pure rotation matrix (i.e, unscaled).
  10166. */
  10167. setRotationFromMatrix( m ) {
  10168. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  10169. this.quaternion.setFromRotationMatrix( m );
  10170. }
  10171. /**
  10172. * Sets the given rotation represented as a Quaternion to the 3D object.
  10173. *
  10174. * @param {Quaternion} q - The Quaternion
  10175. */
  10176. setRotationFromQuaternion( q ) {
  10177. // assumes q is normalized
  10178. this.quaternion.copy( q );
  10179. }
  10180. /**
  10181. * Rotates the 3D object along an axis in local space.
  10182. *
  10183. * @param {Vector3} axis - The (normalized) axis vector.
  10184. * @param {number} angle - The angle in radians.
  10185. * @return {Object3D} A reference to this instance.
  10186. */
  10187. rotateOnAxis( axis, angle ) {
  10188. // rotate object on axis in object space
  10189. // axis is assumed to be normalized
  10190. _q1.setFromAxisAngle( axis, angle );
  10191. this.quaternion.multiply( _q1 );
  10192. return this;
  10193. }
  10194. /**
  10195. * Rotates the 3D object along an axis in world space.
  10196. *
  10197. * @param {Vector3} axis - The (normalized) axis vector.
  10198. * @param {number} angle - The angle in radians.
  10199. * @return {Object3D} A reference to this instance.
  10200. */
  10201. rotateOnWorldAxis( axis, angle ) {
  10202. // rotate object on axis in world space
  10203. // axis is assumed to be normalized
  10204. // method assumes no rotated parent
  10205. _q1.setFromAxisAngle( axis, angle );
  10206. this.quaternion.premultiply( _q1 );
  10207. return this;
  10208. }
  10209. /**
  10210. * Rotates the 3D object around its X axis in local space.
  10211. *
  10212. * @param {number} angle - The angle in radians.
  10213. * @return {Object3D} A reference to this instance.
  10214. */
  10215. rotateX( angle ) {
  10216. return this.rotateOnAxis( _xAxis, angle );
  10217. }
  10218. /**
  10219. * Rotates the 3D object around its Y axis in local space.
  10220. *
  10221. * @param {number} angle - The angle in radians.
  10222. * @return {Object3D} A reference to this instance.
  10223. */
  10224. rotateY( angle ) {
  10225. return this.rotateOnAxis( _yAxis, angle );
  10226. }
  10227. /**
  10228. * Rotates the 3D object around its Z axis in local space.
  10229. *
  10230. * @param {number} angle - The angle in radians.
  10231. * @return {Object3D} A reference to this instance.
  10232. */
  10233. rotateZ( angle ) {
  10234. return this.rotateOnAxis( _zAxis, angle );
  10235. }
  10236. /**
  10237. * Translate the 3D object by a distance along the given axis in local space.
  10238. *
  10239. * @param {Vector3} axis - The (normalized) axis vector.
  10240. * @param {number} distance - The distance in world units.
  10241. * @return {Object3D} A reference to this instance.
  10242. */
  10243. translateOnAxis( axis, distance ) {
  10244. // translate object by distance along axis in object space
  10245. // axis is assumed to be normalized
  10246. _v1$4.copy( axis ).applyQuaternion( this.quaternion );
  10247. this.position.add( _v1$4.multiplyScalar( distance ) );
  10248. return this;
  10249. }
  10250. /**
  10251. * Translate the 3D object by a distance along its X-axis in local space.
  10252. *
  10253. * @param {number} distance - The distance in world units.
  10254. * @return {Object3D} A reference to this instance.
  10255. */
  10256. translateX( distance ) {
  10257. return this.translateOnAxis( _xAxis, distance );
  10258. }
  10259. /**
  10260. * Translate the 3D object by a distance along its Y-axis in local space.
  10261. *
  10262. * @param {number} distance - The distance in world units.
  10263. * @return {Object3D} A reference to this instance.
  10264. */
  10265. translateY( distance ) {
  10266. return this.translateOnAxis( _yAxis, distance );
  10267. }
  10268. /**
  10269. * Translate the 3D object by a distance along its Z-axis in local space.
  10270. *
  10271. * @param {number} distance - The distance in world units.
  10272. * @return {Object3D} A reference to this instance.
  10273. */
  10274. translateZ( distance ) {
  10275. return this.translateOnAxis( _zAxis, distance );
  10276. }
  10277. /**
  10278. * Converts the given vector from this 3D object's local space to world space.
  10279. *
  10280. * @param {Vector3} vector - The vector to convert.
  10281. * @return {Vector3} The converted vector.
  10282. */
  10283. localToWorld( vector ) {
  10284. this.updateWorldMatrix( true, false );
  10285. return vector.applyMatrix4( this.matrixWorld );
  10286. }
  10287. /**
  10288. * Converts the given vector from this 3D object's word space to local space.
  10289. *
  10290. * @param {Vector3} vector - The vector to convert.
  10291. * @return {Vector3} The converted vector.
  10292. */
  10293. worldToLocal( vector ) {
  10294. this.updateWorldMatrix( true, false );
  10295. return vector.applyMatrix4( _m1$1.copy( this.matrixWorld ).invert() );
  10296. }
  10297. /**
  10298. * Rotates the object to face a point in world space.
  10299. *
  10300. * This method does not support objects having non-uniformly-scaled parent(s).
  10301. *
  10302. * @param {number|Vector3} x - The x coordinate in world space. Alternatively, a vector representing a position in world space
  10303. * @param {number} [y] - The y coordinate in world space.
  10304. * @param {number} [z] - The z coordinate in world space.
  10305. */
  10306. lookAt( x, y, z ) {
  10307. // This method does not support objects having non-uniformly-scaled parent(s)
  10308. if ( x.isVector3 ) {
  10309. _target.copy( x );
  10310. } else {
  10311. _target.set( x, y, z );
  10312. }
  10313. const parent = this.parent;
  10314. this.updateWorldMatrix( true, false );
  10315. _position$3.setFromMatrixPosition( this.matrixWorld );
  10316. if ( this.isCamera || this.isLight ) {
  10317. _m1$1.lookAt( _position$3, _target, this.up );
  10318. } else {
  10319. _m1$1.lookAt( _target, _position$3, this.up );
  10320. }
  10321. this.quaternion.setFromRotationMatrix( _m1$1 );
  10322. if ( parent ) {
  10323. _m1$1.extractRotation( parent.matrixWorld );
  10324. _q1.setFromRotationMatrix( _m1$1 );
  10325. this.quaternion.premultiply( _q1.invert() );
  10326. }
  10327. }
  10328. /**
  10329. * Adds the given 3D object as a child to this 3D object. An arbitrary number of
  10330. * objects may be added. Any current parent on an object passed in here will be
  10331. * removed, since an object can have at most one parent.
  10332. *
  10333. * @fires Object3D#added
  10334. * @fires Object3D#childadded
  10335. * @param {Object3D} object - The 3D object to add.
  10336. * @return {Object3D} A reference to this instance.
  10337. */
  10338. add( object ) {
  10339. if ( arguments.length > 1 ) {
  10340. for ( let i = 0; i < arguments.length; i ++ ) {
  10341. this.add( arguments[ i ] );
  10342. }
  10343. return this;
  10344. }
  10345. if ( object === this ) {
  10346. console.error( 'THREE.Object3D.add: object can\'t be added as a child of itself.', object );
  10347. return this;
  10348. }
  10349. if ( object && object.isObject3D ) {
  10350. object.removeFromParent();
  10351. object.parent = this;
  10352. this.children.push( object );
  10353. object.dispatchEvent( _addedEvent );
  10354. _childaddedEvent.child = object;
  10355. this.dispatchEvent( _childaddedEvent );
  10356. _childaddedEvent.child = null;
  10357. } else {
  10358. console.error( 'THREE.Object3D.add: object not an instance of THREE.Object3D.', object );
  10359. }
  10360. return this;
  10361. }
  10362. /**
  10363. * Removes the given 3D object as child from this 3D object.
  10364. * An arbitrary number of objects may be removed.
  10365. *
  10366. * @fires Object3D#removed
  10367. * @fires Object3D#childremoved
  10368. * @param {Object3D} object - The 3D object to remove.
  10369. * @return {Object3D} A reference to this instance.
  10370. */
  10371. remove( object ) {
  10372. if ( arguments.length > 1 ) {
  10373. for ( let i = 0; i < arguments.length; i ++ ) {
  10374. this.remove( arguments[ i ] );
  10375. }
  10376. return this;
  10377. }
  10378. const index = this.children.indexOf( object );
  10379. if ( index !== -1 ) {
  10380. object.parent = null;
  10381. this.children.splice( index, 1 );
  10382. object.dispatchEvent( _removedEvent );
  10383. _childremovedEvent.child = object;
  10384. this.dispatchEvent( _childremovedEvent );
  10385. _childremovedEvent.child = null;
  10386. }
  10387. return this;
  10388. }
  10389. /**
  10390. * Removes this 3D object from its current parent.
  10391. *
  10392. * @fires Object3D#removed
  10393. * @fires Object3D#childremoved
  10394. * @return {Object3D} A reference to this instance.
  10395. */
  10396. removeFromParent() {
  10397. const parent = this.parent;
  10398. if ( parent !== null ) {
  10399. parent.remove( this );
  10400. }
  10401. return this;
  10402. }
  10403. /**
  10404. * Removes all child objects.
  10405. *
  10406. * @fires Object3D#removed
  10407. * @fires Object3D#childremoved
  10408. * @return {Object3D} A reference to this instance.
  10409. */
  10410. clear() {
  10411. return this.remove( ... this.children );
  10412. }
  10413. /**
  10414. * Adds the given 3D object as a child of this 3D object, while maintaining the object's world
  10415. * transform. This method does not support scene graphs having non-uniformly-scaled nodes(s).
  10416. *
  10417. * @fires Object3D#added
  10418. * @fires Object3D#childadded
  10419. * @param {Object3D} object - The 3D object to attach.
  10420. * @return {Object3D} A reference to this instance.
  10421. */
  10422. attach( object ) {
  10423. // adds object as a child of this, while maintaining the object's world transform
  10424. // Note: This method does not support scene graphs having non-uniformly-scaled nodes(s)
  10425. this.updateWorldMatrix( true, false );
  10426. _m1$1.copy( this.matrixWorld ).invert();
  10427. if ( object.parent !== null ) {
  10428. object.parent.updateWorldMatrix( true, false );
  10429. _m1$1.multiply( object.parent.matrixWorld );
  10430. }
  10431. object.applyMatrix4( _m1$1 );
  10432. object.removeFromParent();
  10433. object.parent = this;
  10434. this.children.push( object );
  10435. object.updateWorldMatrix( false, true );
  10436. object.dispatchEvent( _addedEvent );
  10437. _childaddedEvent.child = object;
  10438. this.dispatchEvent( _childaddedEvent );
  10439. _childaddedEvent.child = null;
  10440. return this;
  10441. }
  10442. /**
  10443. * Searches through the 3D object and its children, starting with the 3D object
  10444. * itself, and returns the first with a matching ID.
  10445. *
  10446. * @param {number} id - The id.
  10447. * @return {Object3D|undefined} The found 3D object. Returns `undefined` if no 3D object has been found.
  10448. */
  10449. getObjectById( id ) {
  10450. return this.getObjectByProperty( 'id', id );
  10451. }
  10452. /**
  10453. * Searches through the 3D object and its children, starting with the 3D object
  10454. * itself, and returns the first with a matching name.
  10455. *
  10456. * @param {string} name - The name.
  10457. * @return {Object3D|undefined} The found 3D object. Returns `undefined` if no 3D object has been found.
  10458. */
  10459. getObjectByName( name ) {
  10460. return this.getObjectByProperty( 'name', name );
  10461. }
  10462. /**
  10463. * Searches through the 3D object and its children, starting with the 3D object
  10464. * itself, and returns the first with a matching property value.
  10465. *
  10466. * @param {string} name - The name of the property.
  10467. * @param {any} value - The value.
  10468. * @return {Object3D|undefined} The found 3D object. Returns `undefined` if no 3D object has been found.
  10469. */
  10470. getObjectByProperty( name, value ) {
  10471. if ( this[ name ] === value ) return this;
  10472. for ( let i = 0, l = this.children.length; i < l; i ++ ) {
  10473. const child = this.children[ i ];
  10474. const object = child.getObjectByProperty( name, value );
  10475. if ( object !== undefined ) {
  10476. return object;
  10477. }
  10478. }
  10479. return undefined;
  10480. }
  10481. /**
  10482. * Searches through the 3D object and its children, starting with the 3D object
  10483. * itself, and returns all 3D objects with a matching property value.
  10484. *
  10485. * @param {string} name - The name of the property.
  10486. * @param {any} value - The value.
  10487. * @param {Array<Object3D>} result - The method stores the result in this array.
  10488. * @return {Array<Object3D>} The found 3D objects.
  10489. */
  10490. getObjectsByProperty( name, value, result = [] ) {
  10491. if ( this[ name ] === value ) result.push( this );
  10492. const children = this.children;
  10493. for ( let i = 0, l = children.length; i < l; i ++ ) {
  10494. children[ i ].getObjectsByProperty( name, value, result );
  10495. }
  10496. return result;
  10497. }
  10498. /**
  10499. * Returns a vector representing the position of the 3D object in world space.
  10500. *
  10501. * @param {Vector3} target - The target vector the result is stored to.
  10502. * @return {Vector3} The 3D object's position in world space.
  10503. */
  10504. getWorldPosition( target ) {
  10505. this.updateWorldMatrix( true, false );
  10506. return target.setFromMatrixPosition( this.matrixWorld );
  10507. }
  10508. /**
  10509. * Returns a Quaternion representing the position of the 3D object in world space.
  10510. *
  10511. * @param {Quaternion} target - The target Quaternion the result is stored to.
  10512. * @return {Quaternion} The 3D object's rotation in world space.
  10513. */
  10514. getWorldQuaternion( target ) {
  10515. this.updateWorldMatrix( true, false );
  10516. this.matrixWorld.decompose( _position$3, target, _scale$2 );
  10517. return target;
  10518. }
  10519. /**
  10520. * Returns a vector representing the scale of the 3D object in world space.
  10521. *
  10522. * @param {Vector3} target - The target vector the result is stored to.
  10523. * @return {Vector3} The 3D object's scale in world space.
  10524. */
  10525. getWorldScale( target ) {
  10526. this.updateWorldMatrix( true, false );
  10527. this.matrixWorld.decompose( _position$3, _quaternion$2, target );
  10528. return target;
  10529. }
  10530. /**
  10531. * Returns a vector representing the ("look") direction of the 3D object in world space.
  10532. *
  10533. * @param {Vector3} target - The target vector the result is stored to.
  10534. * @return {Vector3} The 3D object's direction in world space.
  10535. */
  10536. getWorldDirection( target ) {
  10537. this.updateWorldMatrix( true, false );
  10538. const e = this.matrixWorld.elements;
  10539. return target.set( e[ 8 ], e[ 9 ], e[ 10 ] ).normalize();
  10540. }
  10541. /**
  10542. * Abstract method to get intersections between a casted ray and this
  10543. * 3D object. Renderable 3D objects such as {@link Mesh}, {@link Line} or {@link Points}
  10544. * implement this method in order to use raycasting.
  10545. *
  10546. * @abstract
  10547. * @param {Raycaster} raycaster - The raycaster.
  10548. * @param {Array<Object>} intersects - An array holding the result of the method.
  10549. */
  10550. raycast( /* raycaster, intersects */ ) {}
  10551. /**
  10552. * Executes the callback on this 3D object and all descendants.
  10553. *
  10554. * Note: Modifying the scene graph inside the callback is discouraged.
  10555. *
  10556. * @param {Function} callback - A callback function that allows to process the current 3D object.
  10557. */
  10558. traverse( callback ) {
  10559. callback( this );
  10560. const children = this.children;
  10561. for ( let i = 0, l = children.length; i < l; i ++ ) {
  10562. children[ i ].traverse( callback );
  10563. }
  10564. }
  10565. /**
  10566. * Like {@link Object3D#traverse}, but the callback will only be executed for visible 3D objects.
  10567. * Descendants of invisible 3D objects are not traversed.
  10568. *
  10569. * Note: Modifying the scene graph inside the callback is discouraged.
  10570. *
  10571. * @param {Function} callback - A callback function that allows to process the current 3D object.
  10572. */
  10573. traverseVisible( callback ) {
  10574. if ( this.visible === false ) return;
  10575. callback( this );
  10576. const children = this.children;
  10577. for ( let i = 0, l = children.length; i < l; i ++ ) {
  10578. children[ i ].traverseVisible( callback );
  10579. }
  10580. }
  10581. /**
  10582. * Like {@link Object3D#traverse}, but the callback will only be executed for all ancestors.
  10583. *
  10584. * Note: Modifying the scene graph inside the callback is discouraged.
  10585. *
  10586. * @param {Function} callback - A callback function that allows to process the current 3D object.
  10587. */
  10588. traverseAncestors( callback ) {
  10589. const parent = this.parent;
  10590. if ( parent !== null ) {
  10591. callback( parent );
  10592. parent.traverseAncestors( callback );
  10593. }
  10594. }
  10595. /**
  10596. * Updates the transformation matrix in local space by computing it from the current
  10597. * position, rotation and scale values.
  10598. */
  10599. updateMatrix() {
  10600. this.matrix.compose( this.position, this.quaternion, this.scale );
  10601. this.matrixWorldNeedsUpdate = true;
  10602. }
  10603. /**
  10604. * Updates the transformation matrix in world space of this 3D objects and its descendants.
  10605. *
  10606. * To ensure correct results, this method also recomputes the 3D object's transformation matrix in
  10607. * local space. The computation of the local and world matrix can be controlled with the
  10608. * {@link Object3D#matrixAutoUpdate} and {@link Object3D#matrixWorldAutoUpdate} flags which are both
  10609. * `true` by default. Set these flags to `false` if you need more control over the update matrix process.
  10610. *
  10611. * @param {boolean} [force=false] - When set to `true`, a recomputation of world matrices is forced even
  10612. * when {@link Object3D#matrixWorldAutoUpdate} is set to `false`.
  10613. */
  10614. updateMatrixWorld( force ) {
  10615. if ( this.matrixAutoUpdate ) this.updateMatrix();
  10616. if ( this.matrixWorldNeedsUpdate || force ) {
  10617. if ( this.matrixWorldAutoUpdate === true ) {
  10618. if ( this.parent === null ) {
  10619. this.matrixWorld.copy( this.matrix );
  10620. } else {
  10621. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  10622. }
  10623. }
  10624. this.matrixWorldNeedsUpdate = false;
  10625. force = true;
  10626. }
  10627. // make sure descendants are updated if required
  10628. const children = this.children;
  10629. for ( let i = 0, l = children.length; i < l; i ++ ) {
  10630. const child = children[ i ];
  10631. child.updateMatrixWorld( force );
  10632. }
  10633. }
  10634. /**
  10635. * An alternative version of {@link Object3D#updateMatrixWorld} with more control over the
  10636. * update of ancestor and descendant nodes.
  10637. *
  10638. * @param {boolean} [updateParents=false] Whether ancestor nodes should be updated or not.
  10639. * @param {boolean} [updateChildren=false] Whether descendant nodes should be updated or not.
  10640. */
  10641. updateWorldMatrix( updateParents, updateChildren ) {
  10642. const parent = this.parent;
  10643. if ( updateParents === true && parent !== null ) {
  10644. parent.updateWorldMatrix( true, false );
  10645. }
  10646. if ( this.matrixAutoUpdate ) this.updateMatrix();
  10647. if ( this.matrixWorldAutoUpdate === true ) {
  10648. if ( this.parent === null ) {
  10649. this.matrixWorld.copy( this.matrix );
  10650. } else {
  10651. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  10652. }
  10653. }
  10654. // make sure descendants are updated
  10655. if ( updateChildren === true ) {
  10656. const children = this.children;
  10657. for ( let i = 0, l = children.length; i < l; i ++ ) {
  10658. const child = children[ i ];
  10659. child.updateWorldMatrix( false, true );
  10660. }
  10661. }
  10662. }
  10663. /**
  10664. * Serializes the 3D object into JSON.
  10665. *
  10666. * @param {?(Object|string)} meta - An optional value holding meta information about the serialization.
  10667. * @return {Object} A JSON object representing the serialized 3D object.
  10668. * @see {@link ObjectLoader#parse}
  10669. */
  10670. toJSON( meta ) {
  10671. // meta is a string when called from JSON.stringify
  10672. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  10673. const output = {};
  10674. // meta is a hash used to collect geometries, materials.
  10675. // not providing it implies that this is the root object
  10676. // being serialized.
  10677. if ( isRootObject ) {
  10678. // initialize meta obj
  10679. meta = {
  10680. geometries: {},
  10681. materials: {},
  10682. textures: {},
  10683. images: {},
  10684. shapes: {},
  10685. skeletons: {},
  10686. animations: {},
  10687. nodes: {}
  10688. };
  10689. output.metadata = {
  10690. version: 4.6,
  10691. type: 'Object',
  10692. generator: 'Object3D.toJSON'
  10693. };
  10694. }
  10695. // standard Object3D serialization
  10696. const object = {};
  10697. object.uuid = this.uuid;
  10698. object.type = this.type;
  10699. if ( this.name !== '' ) object.name = this.name;
  10700. if ( this.castShadow === true ) object.castShadow = true;
  10701. if ( this.receiveShadow === true ) object.receiveShadow = true;
  10702. if ( this.visible === false ) object.visible = false;
  10703. if ( this.frustumCulled === false ) object.frustumCulled = false;
  10704. if ( this.renderOrder !== 0 ) object.renderOrder = this.renderOrder;
  10705. if ( Object.keys( this.userData ).length > 0 ) object.userData = this.userData;
  10706. object.layers = this.layers.mask;
  10707. object.matrix = this.matrix.toArray();
  10708. object.up = this.up.toArray();
  10709. if ( this.matrixAutoUpdate === false ) object.matrixAutoUpdate = false;
  10710. // object specific properties
  10711. if ( this.isInstancedMesh ) {
  10712. object.type = 'InstancedMesh';
  10713. object.count = this.count;
  10714. object.instanceMatrix = this.instanceMatrix.toJSON();
  10715. if ( this.instanceColor !== null ) object.instanceColor = this.instanceColor.toJSON();
  10716. }
  10717. if ( this.isBatchedMesh ) {
  10718. object.type = 'BatchedMesh';
  10719. object.perObjectFrustumCulled = this.perObjectFrustumCulled;
  10720. object.sortObjects = this.sortObjects;
  10721. object.drawRanges = this._drawRanges;
  10722. object.reservedRanges = this._reservedRanges;
  10723. object.visibility = this._visibility;
  10724. object.active = this._active;
  10725. object.bounds = this._bounds.map( bound => ( {
  10726. boxInitialized: bound.boxInitialized,
  10727. boxMin: bound.box.min.toArray(),
  10728. boxMax: bound.box.max.toArray(),
  10729. sphereInitialized: bound.sphereInitialized,
  10730. sphereRadius: bound.sphere.radius,
  10731. sphereCenter: bound.sphere.center.toArray()
  10732. } ) );
  10733. object.maxInstanceCount = this._maxInstanceCount;
  10734. object.maxVertexCount = this._maxVertexCount;
  10735. object.maxIndexCount = this._maxIndexCount;
  10736. object.geometryInitialized = this._geometryInitialized;
  10737. object.geometryCount = this._geometryCount;
  10738. object.matricesTexture = this._matricesTexture.toJSON( meta );
  10739. if ( this._colorsTexture !== null ) object.colorsTexture = this._colorsTexture.toJSON( meta );
  10740. if ( this.boundingSphere !== null ) {
  10741. object.boundingSphere = {
  10742. center: object.boundingSphere.center.toArray(),
  10743. radius: object.boundingSphere.radius
  10744. };
  10745. }
  10746. if ( this.boundingBox !== null ) {
  10747. object.boundingBox = {
  10748. min: object.boundingBox.min.toArray(),
  10749. max: object.boundingBox.max.toArray()
  10750. };
  10751. }
  10752. }
  10753. //
  10754. function serialize( library, element ) {
  10755. if ( library[ element.uuid ] === undefined ) {
  10756. library[ element.uuid ] = element.toJSON( meta );
  10757. }
  10758. return element.uuid;
  10759. }
  10760. if ( this.isScene ) {
  10761. if ( this.background ) {
  10762. if ( this.background.isColor ) {
  10763. object.background = this.background.toJSON();
  10764. } else if ( this.background.isTexture ) {
  10765. object.background = this.background.toJSON( meta ).uuid;
  10766. }
  10767. }
  10768. if ( this.environment && this.environment.isTexture && this.environment.isRenderTargetTexture !== true ) {
  10769. object.environment = this.environment.toJSON( meta ).uuid;
  10770. }
  10771. } else if ( this.isMesh || this.isLine || this.isPoints ) {
  10772. object.geometry = serialize( meta.geometries, this.geometry );
  10773. const parameters = this.geometry.parameters;
  10774. if ( parameters !== undefined && parameters.shapes !== undefined ) {
  10775. const shapes = parameters.shapes;
  10776. if ( Array.isArray( shapes ) ) {
  10777. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  10778. const shape = shapes[ i ];
  10779. serialize( meta.shapes, shape );
  10780. }
  10781. } else {
  10782. serialize( meta.shapes, shapes );
  10783. }
  10784. }
  10785. }
  10786. if ( this.isSkinnedMesh ) {
  10787. object.bindMode = this.bindMode;
  10788. object.bindMatrix = this.bindMatrix.toArray();
  10789. if ( this.skeleton !== undefined ) {
  10790. serialize( meta.skeletons, this.skeleton );
  10791. object.skeleton = this.skeleton.uuid;
  10792. }
  10793. }
  10794. if ( this.material !== undefined ) {
  10795. if ( Array.isArray( this.material ) ) {
  10796. const uuids = [];
  10797. for ( let i = 0, l = this.material.length; i < l; i ++ ) {
  10798. uuids.push( serialize( meta.materials, this.material[ i ] ) );
  10799. }
  10800. object.material = uuids;
  10801. } else {
  10802. object.material = serialize( meta.materials, this.material );
  10803. }
  10804. }
  10805. //
  10806. if ( this.children.length > 0 ) {
  10807. object.children = [];
  10808. for ( let i = 0; i < this.children.length; i ++ ) {
  10809. object.children.push( this.children[ i ].toJSON( meta ).object );
  10810. }
  10811. }
  10812. //
  10813. if ( this.animations.length > 0 ) {
  10814. object.animations = [];
  10815. for ( let i = 0; i < this.animations.length; i ++ ) {
  10816. const animation = this.animations[ i ];
  10817. object.animations.push( serialize( meta.animations, animation ) );
  10818. }
  10819. }
  10820. if ( isRootObject ) {
  10821. const geometries = extractFromCache( meta.geometries );
  10822. const materials = extractFromCache( meta.materials );
  10823. const textures = extractFromCache( meta.textures );
  10824. const images = extractFromCache( meta.images );
  10825. const shapes = extractFromCache( meta.shapes );
  10826. const skeletons = extractFromCache( meta.skeletons );
  10827. const animations = extractFromCache( meta.animations );
  10828. const nodes = extractFromCache( meta.nodes );
  10829. if ( geometries.length > 0 ) output.geometries = geometries;
  10830. if ( materials.length > 0 ) output.materials = materials;
  10831. if ( textures.length > 0 ) output.textures = textures;
  10832. if ( images.length > 0 ) output.images = images;
  10833. if ( shapes.length > 0 ) output.shapes = shapes;
  10834. if ( skeletons.length > 0 ) output.skeletons = skeletons;
  10835. if ( animations.length > 0 ) output.animations = animations;
  10836. if ( nodes.length > 0 ) output.nodes = nodes;
  10837. }
  10838. output.object = object;
  10839. return output;
  10840. // extract data from the cache hash
  10841. // remove metadata on each item
  10842. // and return as array
  10843. function extractFromCache( cache ) {
  10844. const values = [];
  10845. for ( const key in cache ) {
  10846. const data = cache[ key ];
  10847. delete data.metadata;
  10848. values.push( data );
  10849. }
  10850. return values;
  10851. }
  10852. }
  10853. /**
  10854. * Returns a new 3D object with copied values from this instance.
  10855. *
  10856. * @param {boolean} [recursive=true] - When set to `true`, descendants of the 3D object are also cloned.
  10857. * @return {Object3D} A clone of this instance.
  10858. */
  10859. clone( recursive ) {
  10860. return new this.constructor().copy( this, recursive );
  10861. }
  10862. /**
  10863. * Copies the values of the given 3D object to this instance.
  10864. *
  10865. * @param {Object3D} source - The 3D object to copy.
  10866. * @param {boolean} [recursive=true] - When set to `true`, descendants of the 3D object are cloned.
  10867. * @return {Object3D} A reference to this instance.
  10868. */
  10869. copy( source, recursive = true ) {
  10870. this.name = source.name;
  10871. this.up.copy( source.up );
  10872. this.position.copy( source.position );
  10873. this.rotation.order = source.rotation.order;
  10874. this.quaternion.copy( source.quaternion );
  10875. this.scale.copy( source.scale );
  10876. this.matrix.copy( source.matrix );
  10877. this.matrixWorld.copy( source.matrixWorld );
  10878. this.matrixAutoUpdate = source.matrixAutoUpdate;
  10879. this.matrixWorldAutoUpdate = source.matrixWorldAutoUpdate;
  10880. this.matrixWorldNeedsUpdate = source.matrixWorldNeedsUpdate;
  10881. this.layers.mask = source.layers.mask;
  10882. this.visible = source.visible;
  10883. this.castShadow = source.castShadow;
  10884. this.receiveShadow = source.receiveShadow;
  10885. this.frustumCulled = source.frustumCulled;
  10886. this.renderOrder = source.renderOrder;
  10887. this.animations = source.animations.slice();
  10888. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  10889. if ( recursive === true ) {
  10890. for ( let i = 0; i < source.children.length; i ++ ) {
  10891. const child = source.children[ i ];
  10892. this.add( child.clone() );
  10893. }
  10894. }
  10895. return this;
  10896. }
  10897. }
  10898. /**
  10899. * The default up direction for objects, also used as the default
  10900. * position for {@link DirectionalLight} and {@link HemisphereLight}.
  10901. *
  10902. * @static
  10903. * @type {Vector3}
  10904. * @default (0,1,0)
  10905. */
  10906. Object3D.DEFAULT_UP = /*@__PURE__*/ new Vector3( 0, 1, 0 );
  10907. /**
  10908. * The default setting for {@link Object3D#matrixAutoUpdate} for
  10909. * newly created 3D objects.
  10910. *
  10911. * @static
  10912. * @type {boolean}
  10913. * @default true
  10914. */
  10915. Object3D.DEFAULT_MATRIX_AUTO_UPDATE = true;
  10916. /**
  10917. * The default setting for {@link Object3D#matrixWorldAutoUpdate} for
  10918. * newly created 3D objects.
  10919. *
  10920. * @static
  10921. * @type {boolean}
  10922. * @default true
  10923. */
  10924. Object3D.DEFAULT_MATRIX_WORLD_AUTO_UPDATE = true;
  10925. const _v0$1 = /*@__PURE__*/ new Vector3();
  10926. const _v1$3 = /*@__PURE__*/ new Vector3();
  10927. const _v2$2 = /*@__PURE__*/ new Vector3();
  10928. const _v3$2 = /*@__PURE__*/ new Vector3();
  10929. const _vab = /*@__PURE__*/ new Vector3();
  10930. const _vac = /*@__PURE__*/ new Vector3();
  10931. const _vbc = /*@__PURE__*/ new Vector3();
  10932. const _vap = /*@__PURE__*/ new Vector3();
  10933. const _vbp = /*@__PURE__*/ new Vector3();
  10934. const _vcp = /*@__PURE__*/ new Vector3();
  10935. const _v40 = /*@__PURE__*/ new Vector4();
  10936. const _v41 = /*@__PURE__*/ new Vector4();
  10937. const _v42 = /*@__PURE__*/ new Vector4();
  10938. /**
  10939. * A geometric triangle as defined by three vectors representing its three corners.
  10940. */
  10941. class Triangle {
  10942. /**
  10943. * Constructs a new triangle.
  10944. *
  10945. * @param {Vector3} [a=(0,0,0)] - The first corner of the triangle.
  10946. * @param {Vector3} [b=(0,0,0)] - The second corner of the triangle.
  10947. * @param {Vector3} [c=(0,0,0)] - The third corner of the triangle.
  10948. */
  10949. constructor( a = new Vector3(), b = new Vector3(), c = new Vector3() ) {
  10950. /**
  10951. * The first corner of the triangle.
  10952. *
  10953. * @type {Vector3}
  10954. */
  10955. this.a = a;
  10956. /**
  10957. * The second corner of the triangle.
  10958. *
  10959. * @type {Vector3}
  10960. */
  10961. this.b = b;
  10962. /**
  10963. * The third corner of the triangle.
  10964. *
  10965. * @type {Vector3}
  10966. */
  10967. this.c = c;
  10968. }
  10969. /**
  10970. * Computes the normal vector of a triangle.
  10971. *
  10972. * @param {Vector3} a - The first corner of the triangle.
  10973. * @param {Vector3} b - The second corner of the triangle.
  10974. * @param {Vector3} c - The third corner of the triangle.
  10975. * @param {Vector3} target - The target vector that is used to store the method's result.
  10976. * @return {Vector3} The triangle's normal.
  10977. */
  10978. static getNormal( a, b, c, target ) {
  10979. target.subVectors( c, b );
  10980. _v0$1.subVectors( a, b );
  10981. target.cross( _v0$1 );
  10982. const targetLengthSq = target.lengthSq();
  10983. if ( targetLengthSq > 0 ) {
  10984. return target.multiplyScalar( 1 / Math.sqrt( targetLengthSq ) );
  10985. }
  10986. return target.set( 0, 0, 0 );
  10987. }
  10988. /**
  10989. * Computes a barycentric coordinates from the given vector.
  10990. * Returns `null` if the triangle is degenerate.
  10991. *
  10992. * @param {Vector3} point - A point in 3D space.
  10993. * @param {Vector3} a - The first corner of the triangle.
  10994. * @param {Vector3} b - The second corner of the triangle.
  10995. * @param {Vector3} c - The third corner of the triangle.
  10996. * @param {Vector3} target - The target vector that is used to store the method's result.
  10997. * @return {?Vector3} The barycentric coordinates for the given point
  10998. */
  10999. static getBarycoord( point, a, b, c, target ) {
  11000. // based on: http://www.blackpawn.com/texts/pointinpoly/default.html
  11001. _v0$1.subVectors( c, a );
  11002. _v1$3.subVectors( b, a );
  11003. _v2$2.subVectors( point, a );
  11004. const dot00 = _v0$1.dot( _v0$1 );
  11005. const dot01 = _v0$1.dot( _v1$3 );
  11006. const dot02 = _v0$1.dot( _v2$2 );
  11007. const dot11 = _v1$3.dot( _v1$3 );
  11008. const dot12 = _v1$3.dot( _v2$2 );
  11009. const denom = ( dot00 * dot11 - dot01 * dot01 );
  11010. // collinear or singular triangle
  11011. if ( denom === 0 ) {
  11012. target.set( 0, 0, 0 );
  11013. return null;
  11014. }
  11015. const invDenom = 1 / denom;
  11016. const u = ( dot11 * dot02 - dot01 * dot12 ) * invDenom;
  11017. const v = ( dot00 * dot12 - dot01 * dot02 ) * invDenom;
  11018. // barycentric coordinates must always sum to 1
  11019. return target.set( 1 - u - v, v, u );
  11020. }
  11021. /**
  11022. * Returns `true` if the given point, when projected onto the plane of the
  11023. * triangle, lies within the triangle.
  11024. *
  11025. * @param {Vector3} point - The point in 3D space to test.
  11026. * @param {Vector3} a - The first corner of the triangle.
  11027. * @param {Vector3} b - The second corner of the triangle.
  11028. * @param {Vector3} c - The third corner of the triangle.
  11029. * @return {boolean} Whether the given point, when projected onto the plane of the
  11030. * triangle, lies within the triangle or not.
  11031. */
  11032. static containsPoint( point, a, b, c ) {
  11033. // if the triangle is degenerate then we can't contain a point
  11034. if ( this.getBarycoord( point, a, b, c, _v3$2 ) === null ) {
  11035. return false;
  11036. }
  11037. return ( _v3$2.x >= 0 ) && ( _v3$2.y >= 0 ) && ( ( _v3$2.x + _v3$2.y ) <= 1 );
  11038. }
  11039. /**
  11040. * Computes the value barycentrically interpolated for the given point on the
  11041. * triangle. Returns `null` if the triangle is degenerate.
  11042. *
  11043. * @param {Vector3} point - Position of interpolated point.
  11044. * @param {Vector3} p1 - The first corner of the triangle.
  11045. * @param {Vector3} p2 - The second corner of the triangle.
  11046. * @param {Vector3} p3 - The third corner of the triangle.
  11047. * @param {Vector3} v1 - Value to interpolate of first vertex.
  11048. * @param {Vector3} v2 - Value to interpolate of second vertex.
  11049. * @param {Vector3} v3 - Value to interpolate of third vertex.
  11050. * @param {Vector3} target - The target vector that is used to store the method's result.
  11051. * @return {?Vector3} The interpolated value.
  11052. */
  11053. static getInterpolation( point, p1, p2, p3, v1, v2, v3, target ) {
  11054. if ( this.getBarycoord( point, p1, p2, p3, _v3$2 ) === null ) {
  11055. target.x = 0;
  11056. target.y = 0;
  11057. if ( 'z' in target ) target.z = 0;
  11058. if ( 'w' in target ) target.w = 0;
  11059. return null;
  11060. }
  11061. target.setScalar( 0 );
  11062. target.addScaledVector( v1, _v3$2.x );
  11063. target.addScaledVector( v2, _v3$2.y );
  11064. target.addScaledVector( v3, _v3$2.z );
  11065. return target;
  11066. }
  11067. /**
  11068. * Computes the value barycentrically interpolated for the given attribute and indices.
  11069. *
  11070. * @param {BufferAttribute} attr - The attribute to interpolate.
  11071. * @param {number} i1 - Index of first vertex.
  11072. * @param {number} i2 - Index of second vertex.
  11073. * @param {number} i3 - Index of third vertex.
  11074. * @param {Vector3} barycoord - The barycoordinate value to use to interpolate.
  11075. * @param {Vector3} target - The target vector that is used to store the method's result.
  11076. * @return {Vector3} The interpolated attribute value.
  11077. */
  11078. static getInterpolatedAttribute( attr, i1, i2, i3, barycoord, target ) {
  11079. _v40.setScalar( 0 );
  11080. _v41.setScalar( 0 );
  11081. _v42.setScalar( 0 );
  11082. _v40.fromBufferAttribute( attr, i1 );
  11083. _v41.fromBufferAttribute( attr, i2 );
  11084. _v42.fromBufferAttribute( attr, i3 );
  11085. target.setScalar( 0 );
  11086. target.addScaledVector( _v40, barycoord.x );
  11087. target.addScaledVector( _v41, barycoord.y );
  11088. target.addScaledVector( _v42, barycoord.z );
  11089. return target;
  11090. }
  11091. /**
  11092. * Returns `true` if the triangle is oriented towards the given direction.
  11093. *
  11094. * @param {Vector3} a - The first corner of the triangle.
  11095. * @param {Vector3} b - The second corner of the triangle.
  11096. * @param {Vector3} c - The third corner of the triangle.
  11097. * @param {Vector3} direction - The (normalized) direction vector.
  11098. * @return {boolean} Whether the triangle is oriented towards the given direction or not.
  11099. */
  11100. static isFrontFacing( a, b, c, direction ) {
  11101. _v0$1.subVectors( c, b );
  11102. _v1$3.subVectors( a, b );
  11103. // strictly front facing
  11104. return ( _v0$1.cross( _v1$3 ).dot( direction ) < 0 ) ? true : false;
  11105. }
  11106. /**
  11107. * Sets the triangle's vertices by copying the given values.
  11108. *
  11109. * @param {Vector3} a - The first corner of the triangle.
  11110. * @param {Vector3} b - The second corner of the triangle.
  11111. * @param {Vector3} c - The third corner of the triangle.
  11112. * @return {Triangle} A reference to this triangle.
  11113. */
  11114. set( a, b, c ) {
  11115. this.a.copy( a );
  11116. this.b.copy( b );
  11117. this.c.copy( c );
  11118. return this;
  11119. }
  11120. /**
  11121. * Sets the triangle's vertices by copying the given array values.
  11122. *
  11123. * @param {Array<Vector3>} points - An array with 3D points.
  11124. * @param {number} i0 - The array index representing the first corner of the triangle.
  11125. * @param {number} i1 - The array index representing the second corner of the triangle.
  11126. * @param {number} i2 - The array index representing the third corner of the triangle.
  11127. * @return {Triangle} A reference to this triangle.
  11128. */
  11129. setFromPointsAndIndices( points, i0, i1, i2 ) {
  11130. this.a.copy( points[ i0 ] );
  11131. this.b.copy( points[ i1 ] );
  11132. this.c.copy( points[ i2 ] );
  11133. return this;
  11134. }
  11135. /**
  11136. * Sets the triangle's vertices by copying the given attribute values.
  11137. *
  11138. * @param {BufferAttribute} attribute - A buffer attribute with 3D points data.
  11139. * @param {number} i0 - The attribute index representing the first corner of the triangle.
  11140. * @param {number} i1 - The attribute index representing the second corner of the triangle.
  11141. * @param {number} i2 - The attribute index representing the third corner of the triangle.
  11142. * @return {Triangle} A reference to this triangle.
  11143. */
  11144. setFromAttributeAndIndices( attribute, i0, i1, i2 ) {
  11145. this.a.fromBufferAttribute( attribute, i0 );
  11146. this.b.fromBufferAttribute( attribute, i1 );
  11147. this.c.fromBufferAttribute( attribute, i2 );
  11148. return this;
  11149. }
  11150. /**
  11151. * Returns a new triangle with copied values from this instance.
  11152. *
  11153. * @return {Triangle} A clone of this instance.
  11154. */
  11155. clone() {
  11156. return new this.constructor().copy( this );
  11157. }
  11158. /**
  11159. * Copies the values of the given triangle to this instance.
  11160. *
  11161. * @param {Triangle} triangle - The triangle to copy.
  11162. * @return {Triangle} A reference to this triangle.
  11163. */
  11164. copy( triangle ) {
  11165. this.a.copy( triangle.a );
  11166. this.b.copy( triangle.b );
  11167. this.c.copy( triangle.c );
  11168. return this;
  11169. }
  11170. /**
  11171. * Computes the area of the triangle.
  11172. *
  11173. * @return {number} The triangle's area.
  11174. */
  11175. getArea() {
  11176. _v0$1.subVectors( this.c, this.b );
  11177. _v1$3.subVectors( this.a, this.b );
  11178. return _v0$1.cross( _v1$3 ).length() * 0.5;
  11179. }
  11180. /**
  11181. * Computes the midpoint of the triangle.
  11182. *
  11183. * @param {Vector3} target - The target vector that is used to store the method's result.
  11184. * @return {Vector3} The triangle's midpoint.
  11185. */
  11186. getMidpoint( target ) {
  11187. return target.addVectors( this.a, this.b ).add( this.c ).multiplyScalar( 1 / 3 );
  11188. }
  11189. /**
  11190. * Computes the normal of the triangle.
  11191. *
  11192. * @param {Vector3} target - The target vector that is used to store the method's result.
  11193. * @return {Vector3} The triangle's normal.
  11194. */
  11195. getNormal( target ) {
  11196. return Triangle.getNormal( this.a, this.b, this.c, target );
  11197. }
  11198. /**
  11199. * Computes a plane the triangle lies within.
  11200. *
  11201. * @param {Plane} target - The target vector that is used to store the method's result.
  11202. * @return {Plane} The plane the triangle lies within.
  11203. */
  11204. getPlane( target ) {
  11205. return target.setFromCoplanarPoints( this.a, this.b, this.c );
  11206. }
  11207. /**
  11208. * Computes a barycentric coordinates from the given vector.
  11209. * Returns `null` if the triangle is degenerate.
  11210. *
  11211. * @param {Vector3} point - A point in 3D space.
  11212. * @param {Vector3} target - The target vector that is used to store the method's result.
  11213. * @return {?Vector3} The barycentric coordinates for the given point
  11214. */
  11215. getBarycoord( point, target ) {
  11216. return Triangle.getBarycoord( point, this.a, this.b, this.c, target );
  11217. }
  11218. /**
  11219. * Computes the value barycentrically interpolated for the given point on the
  11220. * triangle. Returns `null` if the triangle is degenerate.
  11221. *
  11222. * @param {Vector3} point - Position of interpolated point.
  11223. * @param {Vector3} v1 - Value to interpolate of first vertex.
  11224. * @param {Vector3} v2 - Value to interpolate of second vertex.
  11225. * @param {Vector3} v3 - Value to interpolate of third vertex.
  11226. * @param {Vector3} target - The target vector that is used to store the method's result.
  11227. * @return {?Vector3} The interpolated value.
  11228. */
  11229. getInterpolation( point, v1, v2, v3, target ) {
  11230. return Triangle.getInterpolation( point, this.a, this.b, this.c, v1, v2, v3, target );
  11231. }
  11232. /**
  11233. * Returns `true` if the given point, when projected onto the plane of the
  11234. * triangle, lies within the triangle.
  11235. *
  11236. * @param {Vector3} point - The point in 3D space to test.
  11237. * @return {boolean} Whether the given point, when projected onto the plane of the
  11238. * triangle, lies within the triangle or not.
  11239. */
  11240. containsPoint( point ) {
  11241. return Triangle.containsPoint( point, this.a, this.b, this.c );
  11242. }
  11243. /**
  11244. * Returns `true` if the triangle is oriented towards the given direction.
  11245. *
  11246. * @param {Vector3} direction - The (normalized) direction vector.
  11247. * @return {boolean} Whether the triangle is oriented towards the given direction or not.
  11248. */
  11249. isFrontFacing( direction ) {
  11250. return Triangle.isFrontFacing( this.a, this.b, this.c, direction );
  11251. }
  11252. /**
  11253. * Returns `true` if this triangle intersects with the given box.
  11254. *
  11255. * @param {Box3} box - The box to intersect.
  11256. * @return {boolean} Whether this triangle intersects with the given box or not.
  11257. */
  11258. intersectsBox( box ) {
  11259. return box.intersectsTriangle( this );
  11260. }
  11261. /**
  11262. * Returns the closest point on the triangle to the given point.
  11263. *
  11264. * @param {Vector3} p - The point to compute the closest point for.
  11265. * @param {Vector3} target - The target vector that is used to store the method's result.
  11266. * @return {Vector3} The closest point on the triangle.
  11267. */
  11268. closestPointToPoint( p, target ) {
  11269. const a = this.a, b = this.b, c = this.c;
  11270. let v, w;
  11271. // algorithm thanks to Real-Time Collision Detection by Christer Ericson,
  11272. // published by Morgan Kaufmann Publishers, (c) 2005 Elsevier Inc.,
  11273. // under the accompanying license; see chapter 5.1.5 for detailed explanation.
  11274. // basically, we're distinguishing which of the voronoi regions of the triangle
  11275. // the point lies in with the minimum amount of redundant computation.
  11276. _vab.subVectors( b, a );
  11277. _vac.subVectors( c, a );
  11278. _vap.subVectors( p, a );
  11279. const d1 = _vab.dot( _vap );
  11280. const d2 = _vac.dot( _vap );
  11281. if ( d1 <= 0 && d2 <= 0 ) {
  11282. // vertex region of A; barycentric coords (1, 0, 0)
  11283. return target.copy( a );
  11284. }
  11285. _vbp.subVectors( p, b );
  11286. const d3 = _vab.dot( _vbp );
  11287. const d4 = _vac.dot( _vbp );
  11288. if ( d3 >= 0 && d4 <= d3 ) {
  11289. // vertex region of B; barycentric coords (0, 1, 0)
  11290. return target.copy( b );
  11291. }
  11292. const vc = d1 * d4 - d3 * d2;
  11293. if ( vc <= 0 && d1 >= 0 && d3 <= 0 ) {
  11294. v = d1 / ( d1 - d3 );
  11295. // edge region of AB; barycentric coords (1-v, v, 0)
  11296. return target.copy( a ).addScaledVector( _vab, v );
  11297. }
  11298. _vcp.subVectors( p, c );
  11299. const d5 = _vab.dot( _vcp );
  11300. const d6 = _vac.dot( _vcp );
  11301. if ( d6 >= 0 && d5 <= d6 ) {
  11302. // vertex region of C; barycentric coords (0, 0, 1)
  11303. return target.copy( c );
  11304. }
  11305. const vb = d5 * d2 - d1 * d6;
  11306. if ( vb <= 0 && d2 >= 0 && d6 <= 0 ) {
  11307. w = d2 / ( d2 - d6 );
  11308. // edge region of AC; barycentric coords (1-w, 0, w)
  11309. return target.copy( a ).addScaledVector( _vac, w );
  11310. }
  11311. const va = d3 * d6 - d5 * d4;
  11312. if ( va <= 0 && ( d4 - d3 ) >= 0 && ( d5 - d6 ) >= 0 ) {
  11313. _vbc.subVectors( c, b );
  11314. w = ( d4 - d3 ) / ( ( d4 - d3 ) + ( d5 - d6 ) );
  11315. // edge region of BC; barycentric coords (0, 1-w, w)
  11316. return target.copy( b ).addScaledVector( _vbc, w ); // edge region of BC
  11317. }
  11318. // face region
  11319. const denom = 1 / ( va + vb + vc );
  11320. // u = va * denom
  11321. v = vb * denom;
  11322. w = vc * denom;
  11323. return target.copy( a ).addScaledVector( _vab, v ).addScaledVector( _vac, w );
  11324. }
  11325. /**
  11326. * Returns `true` if this triangle is equal with the given one.
  11327. *
  11328. * @param {Triangle} triangle - The triangle to test for equality.
  11329. * @return {boolean} Whether this triangle is equal with the given one.
  11330. */
  11331. equals( triangle ) {
  11332. return triangle.a.equals( this.a ) && triangle.b.equals( this.b ) && triangle.c.equals( this.c );
  11333. }
  11334. }
  11335. const _colorKeywords = { 'aliceblue': 0xF0F8FF, 'antiquewhite': 0xFAEBD7, 'aqua': 0x00FFFF, 'aquamarine': 0x7FFFD4, 'azure': 0xF0FFFF,
  11336. 'beige': 0xF5F5DC, 'bisque': 0xFFE4C4, 'black': 0x000000, 'blanchedalmond': 0xFFEBCD, 'blue': 0x0000FF, 'blueviolet': 0x8A2BE2,
  11337. 'brown': 0xA52A2A, 'burlywood': 0xDEB887, 'cadetblue': 0x5F9EA0, 'chartreuse': 0x7FFF00, 'chocolate': 0xD2691E, 'coral': 0xFF7F50,
  11338. 'cornflowerblue': 0x6495ED, 'cornsilk': 0xFFF8DC, 'crimson': 0xDC143C, 'cyan': 0x00FFFF, 'darkblue': 0x00008B, 'darkcyan': 0x008B8B,
  11339. 'darkgoldenrod': 0xB8860B, 'darkgray': 0xA9A9A9, 'darkgreen': 0x006400, 'darkgrey': 0xA9A9A9, 'darkkhaki': 0xBDB76B, 'darkmagenta': 0x8B008B,
  11340. 'darkolivegreen': 0x556B2F, 'darkorange': 0xFF8C00, 'darkorchid': 0x9932CC, 'darkred': 0x8B0000, 'darksalmon': 0xE9967A, 'darkseagreen': 0x8FBC8F,
  11341. 'darkslateblue': 0x483D8B, 'darkslategray': 0x2F4F4F, 'darkslategrey': 0x2F4F4F, 'darkturquoise': 0x00CED1, 'darkviolet': 0x9400D3,
  11342. 'deeppink': 0xFF1493, 'deepskyblue': 0x00BFFF, 'dimgray': 0x696969, 'dimgrey': 0x696969, 'dodgerblue': 0x1E90FF, 'firebrick': 0xB22222,
  11343. 'floralwhite': 0xFFFAF0, 'forestgreen': 0x228B22, 'fuchsia': 0xFF00FF, 'gainsboro': 0xDCDCDC, 'ghostwhite': 0xF8F8FF, 'gold': 0xFFD700,
  11344. 'goldenrod': 0xDAA520, 'gray': 0x808080, 'green': 0x008000, 'greenyellow': 0xADFF2F, 'grey': 0x808080, 'honeydew': 0xF0FFF0, 'hotpink': 0xFF69B4,
  11345. 'indianred': 0xCD5C5C, 'indigo': 0x4B0082, 'ivory': 0xFFFFF0, 'khaki': 0xF0E68C, 'lavender': 0xE6E6FA, 'lavenderblush': 0xFFF0F5, 'lawngreen': 0x7CFC00,
  11346. 'lemonchiffon': 0xFFFACD, 'lightblue': 0xADD8E6, 'lightcoral': 0xF08080, 'lightcyan': 0xE0FFFF, 'lightgoldenrodyellow': 0xFAFAD2, 'lightgray': 0xD3D3D3,
  11347. 'lightgreen': 0x90EE90, 'lightgrey': 0xD3D3D3, 'lightpink': 0xFFB6C1, 'lightsalmon': 0xFFA07A, 'lightseagreen': 0x20B2AA, 'lightskyblue': 0x87CEFA,
  11348. 'lightslategray': 0x778899, 'lightslategrey': 0x778899, 'lightsteelblue': 0xB0C4DE, 'lightyellow': 0xFFFFE0, 'lime': 0x00FF00, 'limegreen': 0x32CD32,
  11349. 'linen': 0xFAF0E6, 'magenta': 0xFF00FF, 'maroon': 0x800000, 'mediumaquamarine': 0x66CDAA, 'mediumblue': 0x0000CD, 'mediumorchid': 0xBA55D3,
  11350. 'mediumpurple': 0x9370DB, 'mediumseagreen': 0x3CB371, 'mediumslateblue': 0x7B68EE, 'mediumspringgreen': 0x00FA9A, 'mediumturquoise': 0x48D1CC,
  11351. 'mediumvioletred': 0xC71585, 'midnightblue': 0x191970, 'mintcream': 0xF5FFFA, 'mistyrose': 0xFFE4E1, 'moccasin': 0xFFE4B5, 'navajowhite': 0xFFDEAD,
  11352. 'navy': 0x000080, 'oldlace': 0xFDF5E6, 'olive': 0x808000, 'olivedrab': 0x6B8E23, 'orange': 0xFFA500, 'orangered': 0xFF4500, 'orchid': 0xDA70D6,
  11353. 'palegoldenrod': 0xEEE8AA, 'palegreen': 0x98FB98, 'paleturquoise': 0xAFEEEE, 'palevioletred': 0xDB7093, 'papayawhip': 0xFFEFD5, 'peachpuff': 0xFFDAB9,
  11354. 'peru': 0xCD853F, 'pink': 0xFFC0CB, 'plum': 0xDDA0DD, 'powderblue': 0xB0E0E6, 'purple': 0x800080, 'rebeccapurple': 0x663399, 'red': 0xFF0000, 'rosybrown': 0xBC8F8F,
  11355. 'royalblue': 0x4169E1, 'saddlebrown': 0x8B4513, 'salmon': 0xFA8072, 'sandybrown': 0xF4A460, 'seagreen': 0x2E8B57, 'seashell': 0xFFF5EE,
  11356. 'sienna': 0xA0522D, 'silver': 0xC0C0C0, 'skyblue': 0x87CEEB, 'slateblue': 0x6A5ACD, 'slategray': 0x708090, 'slategrey': 0x708090, 'snow': 0xFFFAFA,
  11357. 'springgreen': 0x00FF7F, 'steelblue': 0x4682B4, 'tan': 0xD2B48C, 'teal': 0x008080, 'thistle': 0xD8BFD8, 'tomato': 0xFF6347, 'turquoise': 0x40E0D0,
  11358. 'violet': 0xEE82EE, 'wheat': 0xF5DEB3, 'white': 0xFFFFFF, 'whitesmoke': 0xF5F5F5, 'yellow': 0xFFFF00, 'yellowgreen': 0x9ACD32 };
  11359. const _hslA = { h: 0, s: 0, l: 0 };
  11360. const _hslB = { h: 0, s: 0, l: 0 };
  11361. function hue2rgb( p, q, t ) {
  11362. if ( t < 0 ) t += 1;
  11363. if ( t > 1 ) t -= 1;
  11364. if ( t < 1 / 6 ) return p + ( q - p ) * 6 * t;
  11365. if ( t < 1 / 2 ) return q;
  11366. if ( t < 2 / 3 ) return p + ( q - p ) * 6 * ( 2 / 3 - t );
  11367. return p;
  11368. }
  11369. /**
  11370. * A Color instance is represented by RGB components in the linear <i>working
  11371. * color space</i>, which defaults to `LinearSRGBColorSpace`. Inputs
  11372. * conventionally using `SRGBColorSpace` (such as hexadecimals and CSS
  11373. * strings) are converted to the working color space automatically.
  11374. *
  11375. * ```js
  11376. * // converted automatically from SRGBColorSpace to LinearSRGBColorSpace
  11377. * const color = new THREE.Color().setHex( 0x112233 );
  11378. * ```
  11379. * Source color spaces may be specified explicitly, to ensure correct conversions.
  11380. * ```js
  11381. * // assumed already LinearSRGBColorSpace; no conversion
  11382. * const color = new THREE.Color().setRGB( 0.5, 0.5, 0.5 );
  11383. *
  11384. * // converted explicitly from SRGBColorSpace to LinearSRGBColorSpace
  11385. * const color = new THREE.Color().setRGB( 0.5, 0.5, 0.5, SRGBColorSpace );
  11386. * ```
  11387. * If THREE.ColorManagement is disabled, no conversions occur. For details,
  11388. * see <i>Color management</i>. Iterating through a Color instance will yield
  11389. * its components (r, g, b) in the corresponding order. A Color can be initialised
  11390. * in any of the following ways:
  11391. * ```js
  11392. * //empty constructor - will default white
  11393. * const color1 = new THREE.Color();
  11394. *
  11395. * //Hexadecimal color (recommended)
  11396. * const color2 = new THREE.Color( 0xff0000 );
  11397. *
  11398. * //RGB string
  11399. * const color3 = new THREE.Color("rgb(255, 0, 0)");
  11400. * const color4 = new THREE.Color("rgb(100%, 0%, 0%)");
  11401. *
  11402. * //X11 color name - all 140 color names are supported.
  11403. * //Note the lack of CamelCase in the name
  11404. * const color5 = new THREE.Color( 'skyblue' );
  11405. * //HSL string
  11406. * const color6 = new THREE.Color("hsl(0, 100%, 50%)");
  11407. *
  11408. * //Separate RGB values between 0 and 1
  11409. * const color7 = new THREE.Color( 1, 0, 0 );
  11410. * ```
  11411. */
  11412. class Color {
  11413. /**
  11414. * Constructs a new color.
  11415. *
  11416. * Note that standard method of specifying color in three.js is with a hexadecimal triplet,
  11417. * and that method is used throughout the rest of the documentation.
  11418. *
  11419. * @param {(number|string|Color)} [r] - The red component of the color. If `g` and `b` are
  11420. * not provided, it can be hexadecimal triplet, a CSS-style string or another `Color` instance.
  11421. * @param {number} [g] - The green component.
  11422. * @param {number} [b] - The blue component.
  11423. */
  11424. constructor( r, g, b ) {
  11425. /**
  11426. * This flag can be used for type testing.
  11427. *
  11428. * @type {boolean}
  11429. * @readonly
  11430. * @default true
  11431. */
  11432. this.isColor = true;
  11433. /**
  11434. * The red component.
  11435. *
  11436. * @type {number}
  11437. * @default 1
  11438. */
  11439. this.r = 1;
  11440. /**
  11441. * The green component.
  11442. *
  11443. * @type {number}
  11444. * @default 1
  11445. */
  11446. this.g = 1;
  11447. /**
  11448. * The blue component.
  11449. *
  11450. * @type {number}
  11451. * @default 1
  11452. */
  11453. this.b = 1;
  11454. return this.set( r, g, b );
  11455. }
  11456. /**
  11457. * Sets the colors's components from the given values.
  11458. *
  11459. * @param {(number|string|Color)} [r] - The red component of the color. If `g` and `b` are
  11460. * not provided, it can be hexadecimal triplet, a CSS-style string or another `Color` instance.
  11461. * @param {number} [g] - The green component.
  11462. * @param {number} [b] - The blue component.
  11463. * @return {Color} A reference to this color.
  11464. */
  11465. set( r, g, b ) {
  11466. if ( g === undefined && b === undefined ) {
  11467. // r is THREE.Color, hex or string
  11468. const value = r;
  11469. if ( value && value.isColor ) {
  11470. this.copy( value );
  11471. } else if ( typeof value === 'number' ) {
  11472. this.setHex( value );
  11473. } else if ( typeof value === 'string' ) {
  11474. this.setStyle( value );
  11475. }
  11476. } else {
  11477. this.setRGB( r, g, b );
  11478. }
  11479. return this;
  11480. }
  11481. /**
  11482. * Sets the colors's components to the given scalar value.
  11483. *
  11484. * @param {number} scalar - The scalar value.
  11485. * @return {Color} A reference to this color.
  11486. */
  11487. setScalar( scalar ) {
  11488. this.r = scalar;
  11489. this.g = scalar;
  11490. this.b = scalar;
  11491. return this;
  11492. }
  11493. /**
  11494. * Sets this color from a hexadecimal value.
  11495. *
  11496. * @param {number} hex - The hexadecimal value.
  11497. * @param {string} [colorSpace=SRGBColorSpace] - The color space.
  11498. * @return {Color} A reference to this color.
  11499. */
  11500. setHex( hex, colorSpace = SRGBColorSpace ) {
  11501. hex = Math.floor( hex );
  11502. this.r = ( hex >> 16 & 255 ) / 255;
  11503. this.g = ( hex >> 8 & 255 ) / 255;
  11504. this.b = ( hex & 255 ) / 255;
  11505. ColorManagement.toWorkingColorSpace( this, colorSpace );
  11506. return this;
  11507. }
  11508. /**
  11509. * Sets this color from RGB values.
  11510. *
  11511. * @param {number} r - Red channel value between `0.0` and `1.0`.
  11512. * @param {number} g - Green channel value between `0.0` and `1.0`.
  11513. * @param {number} b - Blue channel value between `0.0` and `1.0`.
  11514. * @param {string} [colorSpace=ColorManagement.workingColorSpace] - The color space.
  11515. * @return {Color} A reference to this color.
  11516. */
  11517. setRGB( r, g, b, colorSpace = ColorManagement.workingColorSpace ) {
  11518. this.r = r;
  11519. this.g = g;
  11520. this.b = b;
  11521. ColorManagement.toWorkingColorSpace( this, colorSpace );
  11522. return this;
  11523. }
  11524. /**
  11525. * Sets this color from RGB values.
  11526. *
  11527. * @param {number} h - Hue value between `0.0` and `1.0`.
  11528. * @param {number} s - Saturation value between `0.0` and `1.0`.
  11529. * @param {number} l - Lightness value between `0.0` and `1.0`.
  11530. * @param {string} [colorSpace=ColorManagement.workingColorSpace] - The color space.
  11531. * @return {Color} A reference to this color.
  11532. */
  11533. setHSL( h, s, l, colorSpace = ColorManagement.workingColorSpace ) {
  11534. // h,s,l ranges are in 0.0 - 1.0
  11535. h = euclideanModulo( h, 1 );
  11536. s = clamp( s, 0, 1 );
  11537. l = clamp( l, 0, 1 );
  11538. if ( s === 0 ) {
  11539. this.r = this.g = this.b = l;
  11540. } else {
  11541. const p = l <= 0.5 ? l * ( 1 + s ) : l + s - ( l * s );
  11542. const q = ( 2 * l ) - p;
  11543. this.r = hue2rgb( q, p, h + 1 / 3 );
  11544. this.g = hue2rgb( q, p, h );
  11545. this.b = hue2rgb( q, p, h - 1 / 3 );
  11546. }
  11547. ColorManagement.toWorkingColorSpace( this, colorSpace );
  11548. return this;
  11549. }
  11550. /**
  11551. * Sets this color from a CSS-style string. For example, `rgb(250, 0,0)`,
  11552. * `rgb(100%, 0%, 0%)`, `hsl(0, 100%, 50%)`, `#ff0000`, `#f00`, or `red` ( or
  11553. * any [X11 color name]{@link https://en.wikipedia.org/wiki/X11_color_names#Color_name_chart} -
  11554. * all 140 color names are supported).
  11555. *
  11556. * @param {string} style - Color as a CSS-style string.
  11557. * @param {string} [colorSpace=SRGBColorSpace] - The color space.
  11558. * @return {Color} A reference to this color.
  11559. */
  11560. setStyle( style, colorSpace = SRGBColorSpace ) {
  11561. function handleAlpha( string ) {
  11562. if ( string === undefined ) return;
  11563. if ( parseFloat( string ) < 1 ) {
  11564. console.warn( 'THREE.Color: Alpha component of ' + style + ' will be ignored.' );
  11565. }
  11566. }
  11567. let m;
  11568. if ( m = /^(\w+)\(([^\)]*)\)/.exec( style ) ) {
  11569. // rgb / hsl
  11570. let color;
  11571. const name = m[ 1 ];
  11572. const components = m[ 2 ];
  11573. switch ( name ) {
  11574. case 'rgb':
  11575. case 'rgba':
  11576. if ( color = /^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) {
  11577. // rgb(255,0,0) rgba(255,0,0,0.5)
  11578. handleAlpha( color[ 4 ] );
  11579. return this.setRGB(
  11580. Math.min( 255, parseInt( color[ 1 ], 10 ) ) / 255,
  11581. Math.min( 255, parseInt( color[ 2 ], 10 ) ) / 255,
  11582. Math.min( 255, parseInt( color[ 3 ], 10 ) ) / 255,
  11583. colorSpace
  11584. );
  11585. }
  11586. if ( color = /^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) {
  11587. // rgb(100%,0%,0%) rgba(100%,0%,0%,0.5)
  11588. handleAlpha( color[ 4 ] );
  11589. return this.setRGB(
  11590. Math.min( 100, parseInt( color[ 1 ], 10 ) ) / 100,
  11591. Math.min( 100, parseInt( color[ 2 ], 10 ) ) / 100,
  11592. Math.min( 100, parseInt( color[ 3 ], 10 ) ) / 100,
  11593. colorSpace
  11594. );
  11595. }
  11596. break;
  11597. case 'hsl':
  11598. case 'hsla':
  11599. if ( color = /^\s*(\d*\.?\d+)\s*,\s*(\d*\.?\d+)\%\s*,\s*(\d*\.?\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) {
  11600. // hsl(120,50%,50%) hsla(120,50%,50%,0.5)
  11601. handleAlpha( color[ 4 ] );
  11602. return this.setHSL(
  11603. parseFloat( color[ 1 ] ) / 360,
  11604. parseFloat( color[ 2 ] ) / 100,
  11605. parseFloat( color[ 3 ] ) / 100,
  11606. colorSpace
  11607. );
  11608. }
  11609. break;
  11610. default:
  11611. console.warn( 'THREE.Color: Unknown color model ' + style );
  11612. }
  11613. } else if ( m = /^\#([A-Fa-f\d]+)$/.exec( style ) ) {
  11614. // hex color
  11615. const hex = m[ 1 ];
  11616. const size = hex.length;
  11617. if ( size === 3 ) {
  11618. // #ff0
  11619. return this.setRGB(
  11620. parseInt( hex.charAt( 0 ), 16 ) / 15,
  11621. parseInt( hex.charAt( 1 ), 16 ) / 15,
  11622. parseInt( hex.charAt( 2 ), 16 ) / 15,
  11623. colorSpace
  11624. );
  11625. } else if ( size === 6 ) {
  11626. // #ff0000
  11627. return this.setHex( parseInt( hex, 16 ), colorSpace );
  11628. } else {
  11629. console.warn( 'THREE.Color: Invalid hex color ' + style );
  11630. }
  11631. } else if ( style && style.length > 0 ) {
  11632. return this.setColorName( style, colorSpace );
  11633. }
  11634. return this;
  11635. }
  11636. /**
  11637. * Sets this color from a color name. Faster than {@link Color#setStyle} if
  11638. * you don't need the other CSS-style formats.
  11639. *
  11640. * For convenience, the list of names is exposed in `Color.NAMES` as a hash.
  11641. * ```js
  11642. * Color.NAMES.aliceblue // returns 0xF0F8FF
  11643. * ```
  11644. *
  11645. * @param {string} style - The color name.
  11646. * @param {string} [colorSpace=SRGBColorSpace] - The color space.
  11647. * @return {Color} A reference to this color.
  11648. */
  11649. setColorName( style, colorSpace = SRGBColorSpace ) {
  11650. // color keywords
  11651. const hex = _colorKeywords[ style.toLowerCase() ];
  11652. if ( hex !== undefined ) {
  11653. // red
  11654. this.setHex( hex, colorSpace );
  11655. } else {
  11656. // unknown color
  11657. console.warn( 'THREE.Color: Unknown color ' + style );
  11658. }
  11659. return this;
  11660. }
  11661. /**
  11662. * Returns a new color with copied values from this instance.
  11663. *
  11664. * @return {Color} A clone of this instance.
  11665. */
  11666. clone() {
  11667. return new this.constructor( this.r, this.g, this.b );
  11668. }
  11669. /**
  11670. * Copies the values of the given color to this instance.
  11671. *
  11672. * @param {Color} color - The color to copy.
  11673. * @return {Color} A reference to this color.
  11674. */
  11675. copy( color ) {
  11676. this.r = color.r;
  11677. this.g = color.g;
  11678. this.b = color.b;
  11679. return this;
  11680. }
  11681. /**
  11682. * Copies the given color into this color, and then converts this color from
  11683. * `SRGBColorSpace` to `LinearSRGBColorSpace`.
  11684. *
  11685. * @param {Color} color - The color to copy/convert.
  11686. * @return {Color} A reference to this color.
  11687. */
  11688. copySRGBToLinear( color ) {
  11689. this.r = SRGBToLinear( color.r );
  11690. this.g = SRGBToLinear( color.g );
  11691. this.b = SRGBToLinear( color.b );
  11692. return this;
  11693. }
  11694. /**
  11695. * Copies the given color into this color, and then converts this color from
  11696. * `LinearSRGBColorSpace` to `SRGBColorSpace`.
  11697. *
  11698. * @param {Color} color - The color to copy/convert.
  11699. * @return {Color} A reference to this color.
  11700. */
  11701. copyLinearToSRGB( color ) {
  11702. this.r = LinearToSRGB( color.r );
  11703. this.g = LinearToSRGB( color.g );
  11704. this.b = LinearToSRGB( color.b );
  11705. return this;
  11706. }
  11707. /**
  11708. * Converts this color from `SRGBColorSpace` to `LinearSRGBColorSpace`.
  11709. *
  11710. * @return {Color} A reference to this color.
  11711. */
  11712. convertSRGBToLinear() {
  11713. this.copySRGBToLinear( this );
  11714. return this;
  11715. }
  11716. /**
  11717. * Converts this color from `LinearSRGBColorSpace` to `SRGBColorSpace`.
  11718. *
  11719. * @return {Color} A reference to this color.
  11720. */
  11721. convertLinearToSRGB() {
  11722. this.copyLinearToSRGB( this );
  11723. return this;
  11724. }
  11725. /**
  11726. * Returns the hexadecimal value of this color.
  11727. *
  11728. * @param {string} [colorSpace=SRGBColorSpace] - The color space.
  11729. * @return {number} The hexadecimal value.
  11730. */
  11731. getHex( colorSpace = SRGBColorSpace ) {
  11732. ColorManagement.fromWorkingColorSpace( _color.copy( this ), colorSpace );
  11733. 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 ) );
  11734. }
  11735. /**
  11736. * Returns the hexadecimal value of this color as a string (for example, 'FFFFFF').
  11737. *
  11738. * @param {string} [colorSpace=SRGBColorSpace] - The color space.
  11739. * @return {string} The hexadecimal value as a string.
  11740. */
  11741. getHexString( colorSpace = SRGBColorSpace ) {
  11742. return ( '000000' + this.getHex( colorSpace ).toString( 16 ) ).slice( -6 );
  11743. }
  11744. /**
  11745. * Converts the colors RGB values into the HSL format and stores them into the
  11746. * given target object.
  11747. *
  11748. * @param {{h:number,s:number,l:number}} target - The target object that is used to store the method's result.
  11749. * @param {string} [colorSpace=ColorManagement.workingColorSpace] - The color space.
  11750. * @return {{h:number,s:number,l:number}} The HSL representation of this color.
  11751. */
  11752. getHSL( target, colorSpace = ColorManagement.workingColorSpace ) {
  11753. // h,s,l ranges are in 0.0 - 1.0
  11754. ColorManagement.fromWorkingColorSpace( _color.copy( this ), colorSpace );
  11755. const r = _color.r, g = _color.g, b = _color.b;
  11756. const max = Math.max( r, g, b );
  11757. const min = Math.min( r, g, b );
  11758. let hue, saturation;
  11759. const lightness = ( min + max ) / 2.0;
  11760. if ( min === max ) {
  11761. hue = 0;
  11762. saturation = 0;
  11763. } else {
  11764. const delta = max - min;
  11765. saturation = lightness <= 0.5 ? delta / ( max + min ) : delta / ( 2 - max - min );
  11766. switch ( max ) {
  11767. case r: hue = ( g - b ) / delta + ( g < b ? 6 : 0 ); break;
  11768. case g: hue = ( b - r ) / delta + 2; break;
  11769. case b: hue = ( r - g ) / delta + 4; break;
  11770. }
  11771. hue /= 6;
  11772. }
  11773. target.h = hue;
  11774. target.s = saturation;
  11775. target.l = lightness;
  11776. return target;
  11777. }
  11778. /**
  11779. * Returns the RGB values of this color and stores them into the given target object.
  11780. *
  11781. * @param {Color} target - The target color that is used to store the method's result.
  11782. * @param {string} [colorSpace=ColorManagement.workingColorSpace] - The color space.
  11783. * @return {Color} The RGB representation of this color.
  11784. */
  11785. getRGB( target, colorSpace = ColorManagement.workingColorSpace ) {
  11786. ColorManagement.fromWorkingColorSpace( _color.copy( this ), colorSpace );
  11787. target.r = _color.r;
  11788. target.g = _color.g;
  11789. target.b = _color.b;
  11790. return target;
  11791. }
  11792. /**
  11793. * Returns the value of this color as a CSS style string. Example: `rgb(255,0,0)`.
  11794. *
  11795. * @param {string} [colorSpace=SRGBColorSpace] - The color space.
  11796. * @return {string} The CSS representation of this color.
  11797. */
  11798. getStyle( colorSpace = SRGBColorSpace ) {
  11799. ColorManagement.fromWorkingColorSpace( _color.copy( this ), colorSpace );
  11800. const r = _color.r, g = _color.g, b = _color.b;
  11801. if ( colorSpace !== SRGBColorSpace ) {
  11802. // Requires CSS Color Module Level 4 (https://www.w3.org/TR/css-color-4/).
  11803. return `color(${ colorSpace } ${ r.toFixed( 3 ) } ${ g.toFixed( 3 ) } ${ b.toFixed( 3 ) })`;
  11804. }
  11805. return `rgb(${ Math.round( r * 255 ) },${ Math.round( g * 255 ) },${ Math.round( b * 255 ) })`;
  11806. }
  11807. /**
  11808. * Adds the given HSL values to this color's values.
  11809. * Internally, this converts the color's RGB values to HSL, adds HSL
  11810. * and then converts the color back to RGB.
  11811. *
  11812. * @param {number} h - Hue value between `0.0` and `1.0`.
  11813. * @param {number} s - Saturation value between `0.0` and `1.0`.
  11814. * @param {number} l - Lightness value between `0.0` and `1.0`.
  11815. * @return {Color} A reference to this color.
  11816. */
  11817. offsetHSL( h, s, l ) {
  11818. this.getHSL( _hslA );
  11819. return this.setHSL( _hslA.h + h, _hslA.s + s, _hslA.l + l );
  11820. }
  11821. /**
  11822. * Adds the RGB values of the given color to the RGB values of this color.
  11823. *
  11824. * @param {Color} color - The color to add.
  11825. * @return {Color} A reference to this color.
  11826. */
  11827. add( color ) {
  11828. this.r += color.r;
  11829. this.g += color.g;
  11830. this.b += color.b;
  11831. return this;
  11832. }
  11833. /**
  11834. * Adds the RGB values of the given colors and stores the result in this instance.
  11835. *
  11836. * @param {Color} color1 - The first color.
  11837. * @param {Color} color2 - The second color.
  11838. * @return {Color} A reference to this color.
  11839. */
  11840. addColors( color1, color2 ) {
  11841. this.r = color1.r + color2.r;
  11842. this.g = color1.g + color2.g;
  11843. this.b = color1.b + color2.b;
  11844. return this;
  11845. }
  11846. /**
  11847. * Adds the given scalar value to the RGB values of this color.
  11848. *
  11849. * @param {number} s - The scalar to add.
  11850. * @return {Color} A reference to this color.
  11851. */
  11852. addScalar( s ) {
  11853. this.r += s;
  11854. this.g += s;
  11855. this.b += s;
  11856. return this;
  11857. }
  11858. /**
  11859. * Subtracts the RGB values of the given color from the RGB values of this color.
  11860. *
  11861. * @param {Color} color - The color to subtract.
  11862. * @return {Color} A reference to this color.
  11863. */
  11864. sub( color ) {
  11865. this.r = Math.max( 0, this.r - color.r );
  11866. this.g = Math.max( 0, this.g - color.g );
  11867. this.b = Math.max( 0, this.b - color.b );
  11868. return this;
  11869. }
  11870. /**
  11871. * Multiplies the RGB values of the given color with the RGB values of this color.
  11872. *
  11873. * @param {Color} color - The color to multiply.
  11874. * @return {Color} A reference to this color.
  11875. */
  11876. multiply( color ) {
  11877. this.r *= color.r;
  11878. this.g *= color.g;
  11879. this.b *= color.b;
  11880. return this;
  11881. }
  11882. /**
  11883. * Multiplies the given scalar value with the RGB values of this color.
  11884. *
  11885. * @param {number} s - The scalar to multiply.
  11886. * @return {Color} A reference to this color.
  11887. */
  11888. multiplyScalar( s ) {
  11889. this.r *= s;
  11890. this.g *= s;
  11891. this.b *= s;
  11892. return this;
  11893. }
  11894. /**
  11895. * Linearly interpolates this color's RGB values toward the RGB values of the
  11896. * given color. The alpha argument can be thought of as the ratio between
  11897. * the two colors, where `0.0` is this color and `1.0` is the first argument.
  11898. *
  11899. * @param {Color} color - The color to converge on.
  11900. * @param {number} alpha - The interpolation factor in the closed interval `[0,1]`.
  11901. * @return {Color} A reference to this color.
  11902. */
  11903. lerp( color, alpha ) {
  11904. this.r += ( color.r - this.r ) * alpha;
  11905. this.g += ( color.g - this.g ) * alpha;
  11906. this.b += ( color.b - this.b ) * alpha;
  11907. return this;
  11908. }
  11909. /**
  11910. * Linearly interpolates between the given colors and stores the result in this instance.
  11911. * The alpha argument can be thought of as the ratio between the two colors, where `0.0`
  11912. * is the first and `1.0` is the second color.
  11913. *
  11914. * @param {Color} color1 - The first color.
  11915. * @param {Color} color2 - The second color.
  11916. * @param {number} alpha - The interpolation factor in the closed interval `[0,1]`.
  11917. * @return {Color} A reference to this color.
  11918. */
  11919. lerpColors( color1, color2, alpha ) {
  11920. this.r = color1.r + ( color2.r - color1.r ) * alpha;
  11921. this.g = color1.g + ( color2.g - color1.g ) * alpha;
  11922. this.b = color1.b + ( color2.b - color1.b ) * alpha;
  11923. return this;
  11924. }
  11925. /**
  11926. * Linearly interpolates this color's HSL values toward the HSL values of the
  11927. * given color. It differs from {@link Color#lerp} by not interpolating straight
  11928. * from one color to the other, but instead going through all the hues in between
  11929. * those two colors. The alpha argument can be thought of as the ratio between
  11930. * the two colors, where 0.0 is this color and 1.0 is the first argument.
  11931. *
  11932. * @param {Color} color - The color to converge on.
  11933. * @param {number} alpha - The interpolation factor in the closed interval `[0,1]`.
  11934. * @return {Color} A reference to this color.
  11935. */
  11936. lerpHSL( color, alpha ) {
  11937. this.getHSL( _hslA );
  11938. color.getHSL( _hslB );
  11939. const h = lerp( _hslA.h, _hslB.h, alpha );
  11940. const s = lerp( _hslA.s, _hslB.s, alpha );
  11941. const l = lerp( _hslA.l, _hslB.l, alpha );
  11942. this.setHSL( h, s, l );
  11943. return this;
  11944. }
  11945. /**
  11946. * Sets the color's RGB components from the given 3D vector.
  11947. *
  11948. * @param {Vector3} v - The vector to set.
  11949. * @return {Color} A reference to this color.
  11950. */
  11951. setFromVector3( v ) {
  11952. this.r = v.x;
  11953. this.g = v.y;
  11954. this.b = v.z;
  11955. return this;
  11956. }
  11957. /**
  11958. * Transforms this color with the given 3x3 matrix.
  11959. *
  11960. * @param {Matrix3} m - The matrix.
  11961. * @return {Color} A reference to this color.
  11962. */
  11963. applyMatrix3( m ) {
  11964. const r = this.r, g = this.g, b = this.b;
  11965. const e = m.elements;
  11966. this.r = e[ 0 ] * r + e[ 3 ] * g + e[ 6 ] * b;
  11967. this.g = e[ 1 ] * r + e[ 4 ] * g + e[ 7 ] * b;
  11968. this.b = e[ 2 ] * r + e[ 5 ] * g + e[ 8 ] * b;
  11969. return this;
  11970. }
  11971. /**
  11972. * Returns `true` if this color is equal with the given one.
  11973. *
  11974. * @param {Color} c - The color to test for equality.
  11975. * @return {boolean} Whether this bounding color is equal with the given one.
  11976. */
  11977. equals( c ) {
  11978. return ( c.r === this.r ) && ( c.g === this.g ) && ( c.b === this.b );
  11979. }
  11980. /**
  11981. * Sets this color's RGB components from the given array.
  11982. *
  11983. * @param {Array<number>} array - An array holding the RGB values.
  11984. * @param {number} [offset=0] - The offset into the array.
  11985. * @return {Color} A reference to this color.
  11986. */
  11987. fromArray( array, offset = 0 ) {
  11988. this.r = array[ offset ];
  11989. this.g = array[ offset + 1 ];
  11990. this.b = array[ offset + 2 ];
  11991. return this;
  11992. }
  11993. /**
  11994. * Writes the RGB components of this color to the given array. If no array is provided,
  11995. * the method returns a new instance.
  11996. *
  11997. * @param {Array<number>} [array=[]] - The target array holding the color components.
  11998. * @param {number} [offset=0] - Index of the first element in the array.
  11999. * @return {Array<number>} The color components.
  12000. */
  12001. toArray( array = [], offset = 0 ) {
  12002. array[ offset ] = this.r;
  12003. array[ offset + 1 ] = this.g;
  12004. array[ offset + 2 ] = this.b;
  12005. return array;
  12006. }
  12007. /**
  12008. * Sets the components of this color from the given buffer attribute.
  12009. *
  12010. * @param {BufferAttribute} attribute - The buffer attribute holding color data.
  12011. * @param {number} index - The index into the attribute.
  12012. * @return {Color} A reference to this color.
  12013. */
  12014. fromBufferAttribute( attribute, index ) {
  12015. this.r = attribute.getX( index );
  12016. this.g = attribute.getY( index );
  12017. this.b = attribute.getZ( index );
  12018. return this;
  12019. }
  12020. /**
  12021. * This methods defines the serialization result of this class. Returns the color
  12022. * as a hexadecimal value.
  12023. *
  12024. * @return {number} The hexadecimal value.
  12025. */
  12026. toJSON() {
  12027. return this.getHex();
  12028. }
  12029. *[ Symbol.iterator ]() {
  12030. yield this.r;
  12031. yield this.g;
  12032. yield this.b;
  12033. }
  12034. }
  12035. const _color = /*@__PURE__*/ new Color();
  12036. /**
  12037. * A dictionary with X11 color names.
  12038. *
  12039. * Note that multiple words such as Dark Orange become the string 'darkorange'.
  12040. *
  12041. * @static
  12042. * @type {Object}
  12043. */
  12044. Color.NAMES = _colorKeywords;
  12045. let _materialId = 0;
  12046. /**
  12047. * Abstract base class for materials.
  12048. *
  12049. * Materials define the appearance of renderable 3D objects.
  12050. *
  12051. * @abstract
  12052. * @augments EventDispatcher
  12053. */
  12054. class Material extends EventDispatcher {
  12055. /**
  12056. * Constructs a new material.
  12057. */
  12058. constructor() {
  12059. super();
  12060. /**
  12061. * This flag can be used for type testing.
  12062. *
  12063. * @type {boolean}
  12064. * @readonly
  12065. * @default true
  12066. */
  12067. this.isMaterial = true;
  12068. /**
  12069. * The ID of the material.
  12070. *
  12071. * @name Material#id
  12072. * @type {number}
  12073. * @readonly
  12074. */
  12075. Object.defineProperty( this, 'id', { value: _materialId ++ } );
  12076. /**
  12077. * The UUID of the material.
  12078. *
  12079. * @type {string}
  12080. * @readonly
  12081. */
  12082. this.uuid = generateUUID();
  12083. /**
  12084. * The name of the material.
  12085. *
  12086. * @type {string}
  12087. */
  12088. this.name = '';
  12089. /**
  12090. * The type property is used for detecting the object type
  12091. * in context of serialization/deserialization.
  12092. *
  12093. * @type {string}
  12094. * @readonly
  12095. */
  12096. this.type = 'Material';
  12097. /**
  12098. * Defines the blending type of the material.
  12099. *
  12100. * It must be set to `CustomBlending` if custom blending properties like
  12101. * {@link Material#blendSrc}, {@link Material#blendDst} or {@link Material#blendEquation}
  12102. * should have any effect.
  12103. *
  12104. * @type {(NoBlending|NormalBlending|AdditiveBlending|SubtractiveBlending|MultiplyBlending|CustomBlending)}
  12105. * @default NormalBlending
  12106. */
  12107. this.blending = NormalBlending;
  12108. /**
  12109. * Defines which side of faces will be rendered - front, back or both.
  12110. *
  12111. * @type {(FrontSide|BackSide|DoubleSide)}
  12112. * @default FrontSide
  12113. */
  12114. this.side = FrontSide;
  12115. /**
  12116. * If set to `true`, vertex colors should be used.
  12117. *
  12118. * The engine supports RGB and RGBA vertex colors depending on whether a three (RGB) or
  12119. * four (RGBA) component color buffer attribute is used.
  12120. *
  12121. * @type {boolean}
  12122. * @default false
  12123. */
  12124. this.vertexColors = false;
  12125. /**
  12126. * Defines how transparent the material is.
  12127. * A value of `0.0` indicates fully transparent, `1.0` is fully opaque.
  12128. *
  12129. * If the {@link Material#transparent} is not set to `true`,
  12130. * the material will remain fully opaque and this value will only affect its color.
  12131. *
  12132. * @type {number}
  12133. * @default 1
  12134. */
  12135. this.opacity = 1;
  12136. /**
  12137. * Defines whether this material is transparent. This has an effect on
  12138. * rendering as transparent objects need special treatment and are rendered
  12139. * after non-transparent objects.
  12140. *
  12141. * When set to true, the extent to which the material is transparent is
  12142. * controlled by {@link Material#opacity}.
  12143. *
  12144. * @type {boolean}
  12145. * @default false
  12146. */
  12147. this.transparent = false;
  12148. /**
  12149. * Enables alpha hashed transparency, an alternative to {@link Material#transparent} or
  12150. * {@link Material#alphaTest}. The material will not be rendered if opacity is lower than
  12151. * a random threshold. Randomization introduces some grain or noise, but approximates alpha
  12152. * blending without the associated problems of sorting. Using TAA can reduce the resulting noise.
  12153. *
  12154. * @type {boolean}
  12155. * @default false
  12156. */
  12157. this.alphaHash = false;
  12158. /**
  12159. * Defines the blending source factor.
  12160. *
  12161. * @type {(ZeroFactor|OneFactor|SrcColorFactor|OneMinusSrcColorFactor|SrcAlphaFactor|OneMinusSrcAlphaFactor|DstAlphaFactor|OneMinusDstAlphaFactor|DstColorFactor|OneMinusDstColorFactor|SrcAlphaSaturateFactor|ConstantColorFactor|OneMinusConstantColorFactor|ConstantAlphaFactor|OneMinusConstantAlphaFactor)}
  12162. * @default SrcAlphaFactor
  12163. */
  12164. this.blendSrc = SrcAlphaFactor;
  12165. /**
  12166. * Defines the blending destination factor.
  12167. *
  12168. * @type {(ZeroFactor|OneFactor|SrcColorFactor|OneMinusSrcColorFactor|SrcAlphaFactor|OneMinusSrcAlphaFactor|DstAlphaFactor|OneMinusDstAlphaFactor|DstColorFactor|OneMinusDstColorFactor|SrcAlphaSaturateFactor|ConstantColorFactor|OneMinusConstantColorFactor|ConstantAlphaFactor|OneMinusConstantAlphaFactor)}
  12169. * @default OneMinusSrcAlphaFactor
  12170. */
  12171. this.blendDst = OneMinusSrcAlphaFactor;
  12172. /**
  12173. * Defines the blending equation.
  12174. *
  12175. * @type {(AddEquation|SubtractEquation|ReverseSubtractEquation|MinEquation|MaxEquation)}
  12176. * @default OneMinusSrcAlphaFactor
  12177. */
  12178. this.blendEquation = AddEquation;
  12179. /**
  12180. * Defines the blending source alpha factor.
  12181. *
  12182. * @type {?(ZeroFactor|OneFactor|SrcColorFactor|OneMinusSrcColorFactor|SrcAlphaFactor|OneMinusSrcAlphaFactor|DstAlphaFactor|OneMinusDstAlphaFactor|DstColorFactor|OneMinusDstColorFactor|SrcAlphaSaturateFactor|ConstantColorFactor|OneMinusConstantColorFactor|ConstantAlphaFactor|OneMinusConstantAlphaFactor)}
  12183. * @default null
  12184. */
  12185. this.blendSrcAlpha = null;
  12186. /**
  12187. * Defines the blending destination alpha factor.
  12188. *
  12189. * @type {?(ZeroFactor|OneFactor|SrcColorFactor|OneMinusSrcColorFactor|SrcAlphaFactor|OneMinusSrcAlphaFactor|DstAlphaFactor|OneMinusDstAlphaFactor|DstColorFactor|OneMinusDstColorFactor|SrcAlphaSaturateFactor|ConstantColorFactor|OneMinusConstantColorFactor|ConstantAlphaFactor|OneMinusConstantAlphaFactor)}
  12190. * @default null
  12191. */
  12192. this.blendDstAlpha = null;
  12193. /**
  12194. * Defines the blending equation of the alpha channel.
  12195. *
  12196. * @type {(AddEquation|SubtractEquation|ReverseSubtractEquation|MinEquation|MaxEquation)}
  12197. * @default OneMinusSrcAlphaFactor
  12198. */
  12199. this.blendEquationAlpha = null;
  12200. /**
  12201. * Represents the RGB values of the constant blend color.
  12202. *
  12203. * This property has only an effect when using custom blending with `ConstantColor` or `OneMinusConstantColor`.
  12204. *
  12205. * @type {Color}
  12206. * @default (0,0,0)
  12207. */
  12208. this.blendColor = new Color( 0, 0, 0 );
  12209. /**
  12210. * Represents the alpha value of the constant blend color.
  12211. *
  12212. * This property has only an effect when using custom blending with `ConstantAlpha` or `OneMinusConstantAlpha`.
  12213. *
  12214. * @type {number}
  12215. * @default 0
  12216. */
  12217. this.blendAlpha = 0;
  12218. /**
  12219. * Defines the depth function.
  12220. *
  12221. * @type {(NeverDepth|AlwaysDepth|LessDepth|LessEqualDepth|EqualDepth|GreaterEqualDepth|GreaterDepth|NotEqualDepth)}
  12222. * @default LessEqualDepth
  12223. */
  12224. this.depthFunc = LessEqualDepth;
  12225. /**
  12226. * Whether to have depth test enabled when rendering this material.
  12227. * When the depth test is disabled, the depth write will also be implicitly disabled.
  12228. *
  12229. * @type {boolean}
  12230. * @default true
  12231. */
  12232. this.depthTest = true;
  12233. /**
  12234. * Whether rendering this material has any effect on the depth buffer.
  12235. *
  12236. * When drawing 2D overlays it can be useful to disable the depth writing in
  12237. * order to layer several things together without creating z-index artifacts.
  12238. *
  12239. * @type {boolean}
  12240. * @default true
  12241. */
  12242. this.depthWrite = true;
  12243. /**
  12244. * The bit mask to use when writing to the stencil buffer.
  12245. *
  12246. * @type {number}
  12247. * @default 0xff
  12248. */
  12249. this.stencilWriteMask = 0xff;
  12250. /**
  12251. * The stencil comparison function to use.
  12252. *
  12253. * @type {NeverStencilFunc|LessStencilFunc|EqualStencilFunc|LessEqualStencilFunc|GreaterStencilFunc|NotEqualStencilFunc|GreaterEqualStencilFunc|AlwaysStencilFunc}
  12254. * @default AlwaysStencilFunc
  12255. */
  12256. this.stencilFunc = AlwaysStencilFunc;
  12257. /**
  12258. * The value to use when performing stencil comparisons or stencil operations.
  12259. *
  12260. * @type {number}
  12261. * @default 0
  12262. */
  12263. this.stencilRef = 0;
  12264. /**
  12265. * The bit mask to use when comparing against the stencil buffer.
  12266. *
  12267. * @type {number}
  12268. * @default 0xff
  12269. */
  12270. this.stencilFuncMask = 0xff;
  12271. /**
  12272. * Which stencil operation to perform when the comparison function returns `false`.
  12273. *
  12274. * @type {ZeroStencilOp|KeepStencilOp|ReplaceStencilOp|IncrementStencilOp|DecrementStencilOp|IncrementWrapStencilOp|DecrementWrapStencilOp|InvertStencilOp}
  12275. * @default KeepStencilOp
  12276. */
  12277. this.stencilFail = KeepStencilOp;
  12278. /**
  12279. * Which stencil operation to perform when the comparison function returns
  12280. * `true` but the depth test fails.
  12281. *
  12282. * @type {ZeroStencilOp|KeepStencilOp|ReplaceStencilOp|IncrementStencilOp|DecrementStencilOp|IncrementWrapStencilOp|DecrementWrapStencilOp|InvertStencilOp}
  12283. * @default KeepStencilOp
  12284. */
  12285. this.stencilZFail = KeepStencilOp;
  12286. /**
  12287. * Which stencil operation to perform when the comparison function returns
  12288. * `true` and the depth test passes.
  12289. *
  12290. * @type {ZeroStencilOp|KeepStencilOp|ReplaceStencilOp|IncrementStencilOp|DecrementStencilOp|IncrementWrapStencilOp|DecrementWrapStencilOp|InvertStencilOp}
  12291. * @default KeepStencilOp
  12292. */
  12293. this.stencilZPass = KeepStencilOp;
  12294. /**
  12295. * Whether stencil operations are performed against the stencil buffer. In
  12296. * order to perform writes or comparisons against the stencil buffer this
  12297. * value must be `true`.
  12298. *
  12299. * @type {boolean}
  12300. * @default false
  12301. */
  12302. this.stencilWrite = false;
  12303. /**
  12304. * User-defined clipping planes specified as THREE.Plane objects in world
  12305. * space. These planes apply to the objects this material is attached to.
  12306. * Points in space whose signed distance to the plane is negative are clipped
  12307. * (not rendered). This requires {@link WebGLRenderer#localClippingEnabled} to
  12308. * be `true`.
  12309. *
  12310. * @type {?Array<Plane>}
  12311. * @default null
  12312. */
  12313. this.clippingPlanes = null;
  12314. /**
  12315. * Changes the behavior of clipping planes so that only their intersection is
  12316. * clipped, rather than their union.
  12317. *
  12318. * @type {boolean}
  12319. * @default false
  12320. */
  12321. this.clipIntersection = false;
  12322. /**
  12323. * Defines whether to clip shadows according to the clipping planes specified
  12324. * on this material.
  12325. *
  12326. * @type {boolean}
  12327. * @default false
  12328. */
  12329. this.clipShadows = false;
  12330. /**
  12331. * Defines which side of faces cast shadows. If `null`, the side casting shadows
  12332. * is determined as follows:
  12333. *
  12334. * - When {@link Material#side} is set to `FrontSide`, the back side cast shadows.
  12335. * - When {@link Material#side} is set to `BackSide`, the front side cast shadows.
  12336. * - When {@link Material#side} is set to `DoubleSide`, both sides cast shadows.
  12337. *
  12338. * @type {?(FrontSide|BackSide|DoubleSide)}
  12339. * @default null
  12340. */
  12341. this.shadowSide = null;
  12342. /**
  12343. * Whether to render the material's color.
  12344. *
  12345. * This can be used in conjunction with {@link Object3D#renderOder} to create invisible
  12346. * objects that occlude other objects.
  12347. *
  12348. * @type {boolean}
  12349. * @default true
  12350. */
  12351. this.colorWrite = true;
  12352. /**
  12353. * Override the renderer's default precision for this material.
  12354. *
  12355. * @type {?('highp'|'mediump'|'lowp')}
  12356. * @default null
  12357. */
  12358. this.precision = null;
  12359. /**
  12360. * Whether to use polygon offset or not. When enabled, each fragment's depth value will
  12361. * be offset after it is interpolated from the depth values of the appropriate vertices.
  12362. * The offset is added before the depth test is performed and before the value is written
  12363. * into the depth buffer.
  12364. *
  12365. * Can be useful for rendering hidden-line images, for applying decals to surfaces, and for
  12366. * rendering solids with highlighted edges.
  12367. *
  12368. * @type {boolean}
  12369. * @default false
  12370. */
  12371. this.polygonOffset = false;
  12372. /**
  12373. * Specifies a scale factor that is used to create a variable depth offset for each polygon.
  12374. *
  12375. * @type {number}
  12376. * @default 0
  12377. */
  12378. this.polygonOffsetFactor = 0;
  12379. /**
  12380. * Is multiplied by an implementation-specific value to create a constant depth offset.
  12381. *
  12382. * @type {number}
  12383. * @default 0
  12384. */
  12385. this.polygonOffsetUnits = 0;
  12386. /**
  12387. * Whether to apply dithering to the color to remove the appearance of banding.
  12388. *
  12389. * @type {boolean}
  12390. * @default false
  12391. */
  12392. this.dithering = false;
  12393. /**
  12394. * Whether alpha to coverage should be enabled or not. Can only be used with MSAA-enabled contexts
  12395. * (meaning when the renderer was created with *antialias* parameter set to `true`). Enabling this
  12396. * will smooth aliasing on clip plane edges and alphaTest-clipped edges.
  12397. *
  12398. * @type {boolean}
  12399. * @default false
  12400. */
  12401. this.alphaToCoverage = false;
  12402. /**
  12403. * Whether to premultiply the alpha (transparency) value.
  12404. *
  12405. * @type {boolean}
  12406. * @default false
  12407. */
  12408. this.premultipliedAlpha = false;
  12409. /**
  12410. * Whether double-sided, transparent objects should be rendered with a single pass or not.
  12411. *
  12412. * The engine renders double-sided, transparent objects with two draw calls (back faces first,
  12413. * then front faces) to mitigate transparency artifacts. There are scenarios however where this
  12414. * approach produces no quality gains but still doubles draw calls e.g. when rendering flat
  12415. * vegetation like grass sprites. In these cases, set the `forceSinglePass` flag to `true` to
  12416. * disable the two pass rendering to avoid performance issues.
  12417. *
  12418. * @type {boolean}
  12419. * @default false
  12420. */
  12421. this.forceSinglePass = false;
  12422. /**
  12423. * Defines whether 3D objects using this material are visible.
  12424. *
  12425. * @type {boolean}
  12426. * @default true
  12427. */
  12428. this.visible = true;
  12429. /**
  12430. * Defines whether this material is tone mapped according to the renderer's tone mapping setting.
  12431. *
  12432. * It is ignored when rendering to a render target or using post processing or when using
  12433. * `WebGPURenderer`. In all these cases, all materials are honored by tone mapping.
  12434. *
  12435. * @type {boolean}
  12436. * @default true
  12437. */
  12438. this.toneMapped = true;
  12439. /**
  12440. * An object that can be used to store custom data about the Material. It
  12441. * should not hold references to functions as these will not be cloned.
  12442. *
  12443. * @type {Object}
  12444. */
  12445. this.userData = {};
  12446. /**
  12447. * This starts at `0` and counts how many times {@link Material#needsUpdate} is set to `true`.
  12448. *
  12449. * @type {number}
  12450. * @readonly
  12451. * @default 0
  12452. */
  12453. this.version = 0;
  12454. this._alphaTest = 0;
  12455. }
  12456. /**
  12457. * Sets the alpha value to be used when running an alpha test. The material
  12458. * will not be rendered if the opacity is lower than this value.
  12459. *
  12460. * @type {number}
  12461. * @readonly
  12462. * @default 0
  12463. */
  12464. get alphaTest() {
  12465. return this._alphaTest;
  12466. }
  12467. set alphaTest( value ) {
  12468. if ( this._alphaTest > 0 !== value > 0 ) {
  12469. this.version ++;
  12470. }
  12471. this._alphaTest = value;
  12472. }
  12473. /**
  12474. * An optional callback that is executed immediately before the material is used to render a 3D object.
  12475. *
  12476. * This method can only be used when rendering with {@link WebGLRenderer}.
  12477. *
  12478. * @param {WebGLRenderer} renderer - The renderer.
  12479. * @param {Scene} scene - The scene.
  12480. * @param {Camera} camera - The camera that is used to render the scene.
  12481. * @param {BufferGeometry} geometry - The 3D object's geometry.
  12482. * @param {Object3D} object - The 3D object.
  12483. * @param {Object} group - The geometry group data.
  12484. */
  12485. onBeforeRender( /* renderer, scene, camera, geometry, object, group */ ) {}
  12486. /**
  12487. * An optional callback that is executed immediately before the shader
  12488. * program is compiled. This function is called with the shader source code
  12489. * as a parameter. Useful for the modification of built-in materials.
  12490. *
  12491. * This method can only be used when rendering with {@link WebGLRenderer}. The
  12492. * recommended approach when customizing materials is to use `WebGPURenderer` with the new
  12493. * Node Material system and [TSL]{@link https://github.com/mrdoob/three.js/wiki/Three.js-Shading-Language}.
  12494. *
  12495. * @param {{vertexShader:string,fragmentShader:string,uniforms:Object}} shaderobject - The object holds the uniforms and the vertex and fragment shader source.
  12496. * @param {WebGLRenderer} renderer - A reference to the renderer.
  12497. */
  12498. onBeforeCompile( /* shaderobject, renderer */ ) {}
  12499. /**
  12500. * In case {@link Material#onBeforeCompile} is used, this callback can be used to identify
  12501. * values of settings used in `onBeforeCompile()`, so three.js can reuse a cached
  12502. * shader or recompile the shader for this material as needed.
  12503. *
  12504. * This method can only be used when rendering with {@link WebGLRenderer}.
  12505. *
  12506. * @return {string} The custom program cache key.
  12507. */
  12508. customProgramCacheKey() {
  12509. return this.onBeforeCompile.toString();
  12510. }
  12511. /**
  12512. * This method can be used to set default values from parameter objects.
  12513. * It is a generic implementation so it can be used with different types
  12514. * of materials.
  12515. *
  12516. * @param {Object} [values] - The material values to set.
  12517. */
  12518. setValues( values ) {
  12519. if ( values === undefined ) return;
  12520. for ( const key in values ) {
  12521. const newValue = values[ key ];
  12522. if ( newValue === undefined ) {
  12523. console.warn( `THREE.Material: parameter '${ key }' has value of undefined.` );
  12524. continue;
  12525. }
  12526. const currentValue = this[ key ];
  12527. if ( currentValue === undefined ) {
  12528. console.warn( `THREE.Material: '${ key }' is not a property of THREE.${ this.type }.` );
  12529. continue;
  12530. }
  12531. if ( currentValue && currentValue.isColor ) {
  12532. currentValue.set( newValue );
  12533. } else if ( ( currentValue && currentValue.isVector3 ) && ( newValue && newValue.isVector3 ) ) {
  12534. currentValue.copy( newValue );
  12535. } else {
  12536. this[ key ] = newValue;
  12537. }
  12538. }
  12539. }
  12540. /**
  12541. * Serializes the material into JSON.
  12542. *
  12543. * @param {?(Object|string)} meta - An optional value holding meta information about the serialization.
  12544. * @return {Object} A JSON object representing the serialized material.
  12545. * @see {@link ObjectLoader#parse}
  12546. */
  12547. toJSON( meta ) {
  12548. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  12549. if ( isRootObject ) {
  12550. meta = {
  12551. textures: {},
  12552. images: {}
  12553. };
  12554. }
  12555. const data = {
  12556. metadata: {
  12557. version: 4.6,
  12558. type: 'Material',
  12559. generator: 'Material.toJSON'
  12560. }
  12561. };
  12562. // standard Material serialization
  12563. data.uuid = this.uuid;
  12564. data.type = this.type;
  12565. if ( this.name !== '' ) data.name = this.name;
  12566. if ( this.color && this.color.isColor ) data.color = this.color.getHex();
  12567. if ( this.roughness !== undefined ) data.roughness = this.roughness;
  12568. if ( this.metalness !== undefined ) data.metalness = this.metalness;
  12569. if ( this.sheen !== undefined ) data.sheen = this.sheen;
  12570. if ( this.sheenColor && this.sheenColor.isColor ) data.sheenColor = this.sheenColor.getHex();
  12571. if ( this.sheenRoughness !== undefined ) data.sheenRoughness = this.sheenRoughness;
  12572. if ( this.emissive && this.emissive.isColor ) data.emissive = this.emissive.getHex();
  12573. if ( this.emissiveIntensity !== undefined && this.emissiveIntensity !== 1 ) data.emissiveIntensity = this.emissiveIntensity;
  12574. if ( this.specular && this.specular.isColor ) data.specular = this.specular.getHex();
  12575. if ( this.specularIntensity !== undefined ) data.specularIntensity = this.specularIntensity;
  12576. if ( this.specularColor && this.specularColor.isColor ) data.specularColor = this.specularColor.getHex();
  12577. if ( this.shininess !== undefined ) data.shininess = this.shininess;
  12578. if ( this.clearcoat !== undefined ) data.clearcoat = this.clearcoat;
  12579. if ( this.clearcoatRoughness !== undefined ) data.clearcoatRoughness = this.clearcoatRoughness;
  12580. if ( this.clearcoatMap && this.clearcoatMap.isTexture ) {
  12581. data.clearcoatMap = this.clearcoatMap.toJSON( meta ).uuid;
  12582. }
  12583. if ( this.clearcoatRoughnessMap && this.clearcoatRoughnessMap.isTexture ) {
  12584. data.clearcoatRoughnessMap = this.clearcoatRoughnessMap.toJSON( meta ).uuid;
  12585. }
  12586. if ( this.clearcoatNormalMap && this.clearcoatNormalMap.isTexture ) {
  12587. data.clearcoatNormalMap = this.clearcoatNormalMap.toJSON( meta ).uuid;
  12588. data.clearcoatNormalScale = this.clearcoatNormalScale.toArray();
  12589. }
  12590. if ( this.dispersion !== undefined ) data.dispersion = this.dispersion;
  12591. if ( this.iridescence !== undefined ) data.iridescence = this.iridescence;
  12592. if ( this.iridescenceIOR !== undefined ) data.iridescenceIOR = this.iridescenceIOR;
  12593. if ( this.iridescenceThicknessRange !== undefined ) data.iridescenceThicknessRange = this.iridescenceThicknessRange;
  12594. if ( this.iridescenceMap && this.iridescenceMap.isTexture ) {
  12595. data.iridescenceMap = this.iridescenceMap.toJSON( meta ).uuid;
  12596. }
  12597. if ( this.iridescenceThicknessMap && this.iridescenceThicknessMap.isTexture ) {
  12598. data.iridescenceThicknessMap = this.iridescenceThicknessMap.toJSON( meta ).uuid;
  12599. }
  12600. if ( this.anisotropy !== undefined ) data.anisotropy = this.anisotropy;
  12601. if ( this.anisotropyRotation !== undefined ) data.anisotropyRotation = this.anisotropyRotation;
  12602. if ( this.anisotropyMap && this.anisotropyMap.isTexture ) {
  12603. data.anisotropyMap = this.anisotropyMap.toJSON( meta ).uuid;
  12604. }
  12605. if ( this.map && this.map.isTexture ) data.map = this.map.toJSON( meta ).uuid;
  12606. if ( this.matcap && this.matcap.isTexture ) data.matcap = this.matcap.toJSON( meta ).uuid;
  12607. if ( this.alphaMap && this.alphaMap.isTexture ) data.alphaMap = this.alphaMap.toJSON( meta ).uuid;
  12608. if ( this.lightMap && this.lightMap.isTexture ) {
  12609. data.lightMap = this.lightMap.toJSON( meta ).uuid;
  12610. data.lightMapIntensity = this.lightMapIntensity;
  12611. }
  12612. if ( this.aoMap && this.aoMap.isTexture ) {
  12613. data.aoMap = this.aoMap.toJSON( meta ).uuid;
  12614. data.aoMapIntensity = this.aoMapIntensity;
  12615. }
  12616. if ( this.bumpMap && this.bumpMap.isTexture ) {
  12617. data.bumpMap = this.bumpMap.toJSON( meta ).uuid;
  12618. data.bumpScale = this.bumpScale;
  12619. }
  12620. if ( this.normalMap && this.normalMap.isTexture ) {
  12621. data.normalMap = this.normalMap.toJSON( meta ).uuid;
  12622. data.normalMapType = this.normalMapType;
  12623. data.normalScale = this.normalScale.toArray();
  12624. }
  12625. if ( this.displacementMap && this.displacementMap.isTexture ) {
  12626. data.displacementMap = this.displacementMap.toJSON( meta ).uuid;
  12627. data.displacementScale = this.displacementScale;
  12628. data.displacementBias = this.displacementBias;
  12629. }
  12630. if ( this.roughnessMap && this.roughnessMap.isTexture ) data.roughnessMap = this.roughnessMap.toJSON( meta ).uuid;
  12631. if ( this.metalnessMap && this.metalnessMap.isTexture ) data.metalnessMap = this.metalnessMap.toJSON( meta ).uuid;
  12632. if ( this.emissiveMap && this.emissiveMap.isTexture ) data.emissiveMap = this.emissiveMap.toJSON( meta ).uuid;
  12633. if ( this.specularMap && this.specularMap.isTexture ) data.specularMap = this.specularMap.toJSON( meta ).uuid;
  12634. if ( this.specularIntensityMap && this.specularIntensityMap.isTexture ) data.specularIntensityMap = this.specularIntensityMap.toJSON( meta ).uuid;
  12635. if ( this.specularColorMap && this.specularColorMap.isTexture ) data.specularColorMap = this.specularColorMap.toJSON( meta ).uuid;
  12636. if ( this.envMap && this.envMap.isTexture ) {
  12637. data.envMap = this.envMap.toJSON( meta ).uuid;
  12638. if ( this.combine !== undefined ) data.combine = this.combine;
  12639. }
  12640. if ( this.envMapRotation !== undefined ) data.envMapRotation = this.envMapRotation.toArray();
  12641. if ( this.envMapIntensity !== undefined ) data.envMapIntensity = this.envMapIntensity;
  12642. if ( this.reflectivity !== undefined ) data.reflectivity = this.reflectivity;
  12643. if ( this.refractionRatio !== undefined ) data.refractionRatio = this.refractionRatio;
  12644. if ( this.gradientMap && this.gradientMap.isTexture ) {
  12645. data.gradientMap = this.gradientMap.toJSON( meta ).uuid;
  12646. }
  12647. if ( this.transmission !== undefined ) data.transmission = this.transmission;
  12648. if ( this.transmissionMap && this.transmissionMap.isTexture ) data.transmissionMap = this.transmissionMap.toJSON( meta ).uuid;
  12649. if ( this.thickness !== undefined ) data.thickness = this.thickness;
  12650. if ( this.thicknessMap && this.thicknessMap.isTexture ) data.thicknessMap = this.thicknessMap.toJSON( meta ).uuid;
  12651. if ( this.attenuationDistance !== undefined && this.attenuationDistance !== Infinity ) data.attenuationDistance = this.attenuationDistance;
  12652. if ( this.attenuationColor !== undefined ) data.attenuationColor = this.attenuationColor.getHex();
  12653. if ( this.size !== undefined ) data.size = this.size;
  12654. if ( this.shadowSide !== null ) data.shadowSide = this.shadowSide;
  12655. if ( this.sizeAttenuation !== undefined ) data.sizeAttenuation = this.sizeAttenuation;
  12656. if ( this.blending !== NormalBlending ) data.blending = this.blending;
  12657. if ( this.side !== FrontSide ) data.side = this.side;
  12658. if ( this.vertexColors === true ) data.vertexColors = true;
  12659. if ( this.opacity < 1 ) data.opacity = this.opacity;
  12660. if ( this.transparent === true ) data.transparent = true;
  12661. if ( this.blendSrc !== SrcAlphaFactor ) data.blendSrc = this.blendSrc;
  12662. if ( this.blendDst !== OneMinusSrcAlphaFactor ) data.blendDst = this.blendDst;
  12663. if ( this.blendEquation !== AddEquation ) data.blendEquation = this.blendEquation;
  12664. if ( this.blendSrcAlpha !== null ) data.blendSrcAlpha = this.blendSrcAlpha;
  12665. if ( this.blendDstAlpha !== null ) data.blendDstAlpha = this.blendDstAlpha;
  12666. if ( this.blendEquationAlpha !== null ) data.blendEquationAlpha = this.blendEquationAlpha;
  12667. if ( this.blendColor && this.blendColor.isColor ) data.blendColor = this.blendColor.getHex();
  12668. if ( this.blendAlpha !== 0 ) data.blendAlpha = this.blendAlpha;
  12669. if ( this.depthFunc !== LessEqualDepth ) data.depthFunc = this.depthFunc;
  12670. if ( this.depthTest === false ) data.depthTest = this.depthTest;
  12671. if ( this.depthWrite === false ) data.depthWrite = this.depthWrite;
  12672. if ( this.colorWrite === false ) data.colorWrite = this.colorWrite;
  12673. if ( this.stencilWriteMask !== 0xff ) data.stencilWriteMask = this.stencilWriteMask;
  12674. if ( this.stencilFunc !== AlwaysStencilFunc ) data.stencilFunc = this.stencilFunc;
  12675. if ( this.stencilRef !== 0 ) data.stencilRef = this.stencilRef;
  12676. if ( this.stencilFuncMask !== 0xff ) data.stencilFuncMask = this.stencilFuncMask;
  12677. if ( this.stencilFail !== KeepStencilOp ) data.stencilFail = this.stencilFail;
  12678. if ( this.stencilZFail !== KeepStencilOp ) data.stencilZFail = this.stencilZFail;
  12679. if ( this.stencilZPass !== KeepStencilOp ) data.stencilZPass = this.stencilZPass;
  12680. if ( this.stencilWrite === true ) data.stencilWrite = this.stencilWrite;
  12681. // rotation (SpriteMaterial)
  12682. if ( this.rotation !== undefined && this.rotation !== 0 ) data.rotation = this.rotation;
  12683. if ( this.polygonOffset === true ) data.polygonOffset = true;
  12684. if ( this.polygonOffsetFactor !== 0 ) data.polygonOffsetFactor = this.polygonOffsetFactor;
  12685. if ( this.polygonOffsetUnits !== 0 ) data.polygonOffsetUnits = this.polygonOffsetUnits;
  12686. if ( this.linewidth !== undefined && this.linewidth !== 1 ) data.linewidth = this.linewidth;
  12687. if ( this.dashSize !== undefined ) data.dashSize = this.dashSize;
  12688. if ( this.gapSize !== undefined ) data.gapSize = this.gapSize;
  12689. if ( this.scale !== undefined ) data.scale = this.scale;
  12690. if ( this.dithering === true ) data.dithering = true;
  12691. if ( this.alphaTest > 0 ) data.alphaTest = this.alphaTest;
  12692. if ( this.alphaHash === true ) data.alphaHash = true;
  12693. if ( this.alphaToCoverage === true ) data.alphaToCoverage = true;
  12694. if ( this.premultipliedAlpha === true ) data.premultipliedAlpha = true;
  12695. if ( this.forceSinglePass === true ) data.forceSinglePass = true;
  12696. if ( this.wireframe === true ) data.wireframe = true;
  12697. if ( this.wireframeLinewidth > 1 ) data.wireframeLinewidth = this.wireframeLinewidth;
  12698. if ( this.wireframeLinecap !== 'round' ) data.wireframeLinecap = this.wireframeLinecap;
  12699. if ( this.wireframeLinejoin !== 'round' ) data.wireframeLinejoin = this.wireframeLinejoin;
  12700. if ( this.flatShading === true ) data.flatShading = true;
  12701. if ( this.visible === false ) data.visible = false;
  12702. if ( this.toneMapped === false ) data.toneMapped = false;
  12703. if ( this.fog === false ) data.fog = false;
  12704. if ( Object.keys( this.userData ).length > 0 ) data.userData = this.userData;
  12705. // TODO: Copied from Object3D.toJSON
  12706. function extractFromCache( cache ) {
  12707. const values = [];
  12708. for ( const key in cache ) {
  12709. const data = cache[ key ];
  12710. delete data.metadata;
  12711. values.push( data );
  12712. }
  12713. return values;
  12714. }
  12715. if ( isRootObject ) {
  12716. const textures = extractFromCache( meta.textures );
  12717. const images = extractFromCache( meta.images );
  12718. if ( textures.length > 0 ) data.textures = textures;
  12719. if ( images.length > 0 ) data.images = images;
  12720. }
  12721. return data;
  12722. }
  12723. /**
  12724. * Returns a new material with copied values from this instance.
  12725. *
  12726. * @return {Material} A clone of this instance.
  12727. */
  12728. clone() {
  12729. return new this.constructor().copy( this );
  12730. }
  12731. /**
  12732. * Copies the values of the given material to this instance.
  12733. *
  12734. * @param {Material} source - The material to copy.
  12735. * @return {Material} A reference to this instance.
  12736. */
  12737. copy( source ) {
  12738. this.name = source.name;
  12739. this.blending = source.blending;
  12740. this.side = source.side;
  12741. this.vertexColors = source.vertexColors;
  12742. this.opacity = source.opacity;
  12743. this.transparent = source.transparent;
  12744. this.blendSrc = source.blendSrc;
  12745. this.blendDst = source.blendDst;
  12746. this.blendEquation = source.blendEquation;
  12747. this.blendSrcAlpha = source.blendSrcAlpha;
  12748. this.blendDstAlpha = source.blendDstAlpha;
  12749. this.blendEquationAlpha = source.blendEquationAlpha;
  12750. this.blendColor.copy( source.blendColor );
  12751. this.blendAlpha = source.blendAlpha;
  12752. this.depthFunc = source.depthFunc;
  12753. this.depthTest = source.depthTest;
  12754. this.depthWrite = source.depthWrite;
  12755. this.stencilWriteMask = source.stencilWriteMask;
  12756. this.stencilFunc = source.stencilFunc;
  12757. this.stencilRef = source.stencilRef;
  12758. this.stencilFuncMask = source.stencilFuncMask;
  12759. this.stencilFail = source.stencilFail;
  12760. this.stencilZFail = source.stencilZFail;
  12761. this.stencilZPass = source.stencilZPass;
  12762. this.stencilWrite = source.stencilWrite;
  12763. const srcPlanes = source.clippingPlanes;
  12764. let dstPlanes = null;
  12765. if ( srcPlanes !== null ) {
  12766. const n = srcPlanes.length;
  12767. dstPlanes = new Array( n );
  12768. for ( let i = 0; i !== n; ++ i ) {
  12769. dstPlanes[ i ] = srcPlanes[ i ].clone();
  12770. }
  12771. }
  12772. this.clippingPlanes = dstPlanes;
  12773. this.clipIntersection = source.clipIntersection;
  12774. this.clipShadows = source.clipShadows;
  12775. this.shadowSide = source.shadowSide;
  12776. this.colorWrite = source.colorWrite;
  12777. this.precision = source.precision;
  12778. this.polygonOffset = source.polygonOffset;
  12779. this.polygonOffsetFactor = source.polygonOffsetFactor;
  12780. this.polygonOffsetUnits = source.polygonOffsetUnits;
  12781. this.dithering = source.dithering;
  12782. this.alphaTest = source.alphaTest;
  12783. this.alphaHash = source.alphaHash;
  12784. this.alphaToCoverage = source.alphaToCoverage;
  12785. this.premultipliedAlpha = source.premultipliedAlpha;
  12786. this.forceSinglePass = source.forceSinglePass;
  12787. this.visible = source.visible;
  12788. this.toneMapped = source.toneMapped;
  12789. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  12790. return this;
  12791. }
  12792. /**
  12793. * Frees the GPU-related resources allocated by this instance. Call this
  12794. * method whenever this instance is no longer used in your app.
  12795. *
  12796. * @fires Material#dispose
  12797. */
  12798. dispose() {
  12799. /**
  12800. * Fires when the material has been disposed of.
  12801. *
  12802. * @event Material#dispose
  12803. * @type {Object}
  12804. */
  12805. this.dispatchEvent( { type: 'dispose' } );
  12806. }
  12807. /**
  12808. * Setting this property to `true` indicates the engine the material
  12809. * needs to be recompiled.
  12810. *
  12811. * @type {boolean}
  12812. * @default false
  12813. * @param {boolean} value
  12814. */
  12815. set needsUpdate( value ) {
  12816. if ( value === true ) this.version ++;
  12817. }
  12818. onBuild( /* shaderobject, renderer */ ) {
  12819. console.warn( 'Material: onBuild() has been removed.' ); // @deprecated, r166
  12820. }
  12821. }
  12822. /**
  12823. * A material for drawing geometries in a simple shaded (flat or wireframe) way.
  12824. *
  12825. * This material is not affected by lights.
  12826. *
  12827. * @augments Material
  12828. */
  12829. class MeshBasicMaterial extends Material {
  12830. /**
  12831. * Constructs a new mesh basic material.
  12832. *
  12833. * @param {Object} [parameters] - An object with one or more properties
  12834. * defining the material's appearance. Any property of the material
  12835. * (including any property from inherited materials) can be passed
  12836. * in here. Color values can be passed any type of value accepted
  12837. * by {@link Color#set}.
  12838. */
  12839. constructor( parameters ) {
  12840. super();
  12841. /**
  12842. * This flag can be used for type testing.
  12843. *
  12844. * @type {boolean}
  12845. * @readonly
  12846. * @default true
  12847. */
  12848. this.isMeshBasicMaterial = true;
  12849. this.type = 'MeshBasicMaterial';
  12850. /**
  12851. * Color of the material.
  12852. *
  12853. * @type {Color}
  12854. * @default (1,1,1)
  12855. */
  12856. this.color = new Color( 0xffffff ); // emissive
  12857. /**
  12858. * The color map. May optionally include an alpha channel, typically combined
  12859. * with {@link Material#transparent} or {@link Material#alphaTest}. The texture map
  12860. * color is modulated by the diffuse `color`.
  12861. *
  12862. * @type {?Texture}
  12863. * @default null
  12864. */
  12865. this.map = null;
  12866. /**
  12867. * The light map. Requires a second set of UVs.
  12868. *
  12869. * @type {?Texture}
  12870. * @default null
  12871. */
  12872. this.lightMap = null;
  12873. /**
  12874. * Intensity of the baked light.
  12875. *
  12876. * @type {number}
  12877. * @default 1
  12878. */
  12879. this.lightMapIntensity = 1.0;
  12880. /**
  12881. * The red channel of this texture is used as the ambient occlusion map.
  12882. * Requires a second set of UVs.
  12883. *
  12884. * @type {?Texture}
  12885. * @default null
  12886. */
  12887. this.aoMap = null;
  12888. /**
  12889. * Intensity of the ambient occlusion effect. Range is `[0,1]`, where `0`
  12890. * disables ambient occlusion. Where intensity is `1` and the AO map's
  12891. * red channel is also `1`, ambient light is fully occluded on a surface.
  12892. *
  12893. * @type {number}
  12894. * @default 1
  12895. */
  12896. this.aoMapIntensity = 1.0;
  12897. /**
  12898. * Specular map used by the material.
  12899. *
  12900. * @type {?Texture}
  12901. * @default null
  12902. */
  12903. this.specularMap = null;
  12904. /**
  12905. * The alpha map is a grayscale texture that controls the opacity across the
  12906. * surface (black: fully transparent; white: fully opaque).
  12907. *
  12908. * Only the color of the texture is used, ignoring the alpha channel if one
  12909. * exists. For RGB and RGBA textures, the renderer will use the green channel
  12910. * when sampling this texture due to the extra bit of precision provided for
  12911. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  12912. * luminance/alpha textures will also still work as expected.
  12913. *
  12914. * @type {?Texture}
  12915. * @default null
  12916. */
  12917. this.alphaMap = null;
  12918. /**
  12919. * The environment map.
  12920. *
  12921. * @type {?Texture}
  12922. * @default null
  12923. */
  12924. this.envMap = null;
  12925. /**
  12926. * The rotation of the environment map in radians.
  12927. *
  12928. * @type {Euler}
  12929. * @default (0,0,0)
  12930. */
  12931. this.envMapRotation = new Euler();
  12932. /**
  12933. * How to combine the result of the surface's color with the environment map, if any.
  12934. *
  12935. * When set to `MixOperation`, the {@link MeshBasicMaterial#reflectivity} is used to
  12936. * blend between the two colors.
  12937. *
  12938. * @type {(MultiplyOperation|MixOperation|AddOperation)}
  12939. * @default MultiplyOperation
  12940. */
  12941. this.combine = MultiplyOperation;
  12942. /**
  12943. * How much the environment map affects the surface.
  12944. * The valid range is between `0` (no reflections) and `1` (full reflections).
  12945. *
  12946. * @type {number}
  12947. * @default 1
  12948. */
  12949. this.reflectivity = 1;
  12950. /**
  12951. * The index of refraction (IOR) of air (approximately 1) divided by the
  12952. * index of refraction of the material. It is used with environment mapping
  12953. * modes {@link CubeRefractionMapping} and {@link EquirectangularRefractionMapping}.
  12954. * The refraction ratio should not exceed `1`.
  12955. *
  12956. * @type {number}
  12957. * @default 0.98
  12958. */
  12959. this.refractionRatio = 0.98;
  12960. /**
  12961. * Renders the geometry as a wireframe.
  12962. *
  12963. * @type {boolean}
  12964. * @default false
  12965. */
  12966. this.wireframe = false;
  12967. /**
  12968. * Controls the thickness of the wireframe.
  12969. *
  12970. * Can only be used with {@link SVGRenderer}.
  12971. *
  12972. * @type {number}
  12973. * @default 1
  12974. */
  12975. this.wireframeLinewidth = 1;
  12976. /**
  12977. * Defines appearance of wireframe ends.
  12978. *
  12979. * Can only be used with {@link SVGRenderer}.
  12980. *
  12981. * @type {('round'|'bevel'|'miter')}
  12982. * @default 'round'
  12983. */
  12984. this.wireframeLinecap = 'round';
  12985. /**
  12986. * Defines appearance of wireframe joints.
  12987. *
  12988. * Can only be used with {@link SVGRenderer}.
  12989. *
  12990. * @type {('round'|'bevel'|'miter')}
  12991. * @default 'round'
  12992. */
  12993. this.wireframeLinejoin = 'round';
  12994. /**
  12995. * Whether the material is affected by fog or not.
  12996. *
  12997. * @type {boolean}
  12998. * @default true
  12999. */
  13000. this.fog = true;
  13001. this.setValues( parameters );
  13002. }
  13003. copy( source ) {
  13004. super.copy( source );
  13005. this.color.copy( source.color );
  13006. this.map = source.map;
  13007. this.lightMap = source.lightMap;
  13008. this.lightMapIntensity = source.lightMapIntensity;
  13009. this.aoMap = source.aoMap;
  13010. this.aoMapIntensity = source.aoMapIntensity;
  13011. this.specularMap = source.specularMap;
  13012. this.alphaMap = source.alphaMap;
  13013. this.envMap = source.envMap;
  13014. this.envMapRotation.copy( source.envMapRotation );
  13015. this.combine = source.combine;
  13016. this.reflectivity = source.reflectivity;
  13017. this.refractionRatio = source.refractionRatio;
  13018. this.wireframe = source.wireframe;
  13019. this.wireframeLinewidth = source.wireframeLinewidth;
  13020. this.wireframeLinecap = source.wireframeLinecap;
  13021. this.wireframeLinejoin = source.wireframeLinejoin;
  13022. this.fog = source.fog;
  13023. return this;
  13024. }
  13025. }
  13026. // Fast Half Float Conversions, http://www.fox-toolkit.org/ftp/fasthalffloatconversion.pdf
  13027. const _tables = /*@__PURE__*/ _generateTables();
  13028. function _generateTables() {
  13029. // float32 to float16 helpers
  13030. const buffer = new ArrayBuffer( 4 );
  13031. const floatView = new Float32Array( buffer );
  13032. const uint32View = new Uint32Array( buffer );
  13033. const baseTable = new Uint32Array( 512 );
  13034. const shiftTable = new Uint32Array( 512 );
  13035. for ( let i = 0; i < 256; ++ i ) {
  13036. const e = i - 127;
  13037. // very small number (0, -0)
  13038. if ( e < -27 ) {
  13039. baseTable[ i ] = 0x0000;
  13040. baseTable[ i | 0x100 ] = 0x8000;
  13041. shiftTable[ i ] = 24;
  13042. shiftTable[ i | 0x100 ] = 24;
  13043. // small number (denorm)
  13044. } else if ( e < -14 ) {
  13045. baseTable[ i ] = 0x0400 >> ( - e - 14 );
  13046. baseTable[ i | 0x100 ] = ( 0x0400 >> ( - e - 14 ) ) | 0x8000;
  13047. shiftTable[ i ] = - e - 1;
  13048. shiftTable[ i | 0x100 ] = - e - 1;
  13049. // normal number
  13050. } else if ( e <= 15 ) {
  13051. baseTable[ i ] = ( e + 15 ) << 10;
  13052. baseTable[ i | 0x100 ] = ( ( e + 15 ) << 10 ) | 0x8000;
  13053. shiftTable[ i ] = 13;
  13054. shiftTable[ i | 0x100 ] = 13;
  13055. // large number (Infinity, -Infinity)
  13056. } else if ( e < 128 ) {
  13057. baseTable[ i ] = 0x7c00;
  13058. baseTable[ i | 0x100 ] = 0xfc00;
  13059. shiftTable[ i ] = 24;
  13060. shiftTable[ i | 0x100 ] = 24;
  13061. // stay (NaN, Infinity, -Infinity)
  13062. } else {
  13063. baseTable[ i ] = 0x7c00;
  13064. baseTable[ i | 0x100 ] = 0xfc00;
  13065. shiftTable[ i ] = 13;
  13066. shiftTable[ i | 0x100 ] = 13;
  13067. }
  13068. }
  13069. // float16 to float32 helpers
  13070. const mantissaTable = new Uint32Array( 2048 );
  13071. const exponentTable = new Uint32Array( 64 );
  13072. const offsetTable = new Uint32Array( 64 );
  13073. for ( let i = 1; i < 1024; ++ i ) {
  13074. let m = i << 13; // zero pad mantissa bits
  13075. let e = 0; // zero exponent
  13076. // normalized
  13077. while ( ( m & 0x00800000 ) === 0 ) {
  13078. m <<= 1;
  13079. e -= 0x00800000; // decrement exponent
  13080. }
  13081. m &= -8388609; // clear leading 1 bit
  13082. e += 0x38800000; // adjust bias
  13083. mantissaTable[ i ] = m | e;
  13084. }
  13085. for ( let i = 1024; i < 2048; ++ i ) {
  13086. mantissaTable[ i ] = 0x38000000 + ( ( i - 1024 ) << 13 );
  13087. }
  13088. for ( let i = 1; i < 31; ++ i ) {
  13089. exponentTable[ i ] = i << 23;
  13090. }
  13091. exponentTable[ 31 ] = 0x47800000;
  13092. exponentTable[ 32 ] = 0x80000000;
  13093. for ( let i = 33; i < 63; ++ i ) {
  13094. exponentTable[ i ] = 0x80000000 + ( ( i - 32 ) << 23 );
  13095. }
  13096. exponentTable[ 63 ] = 0xc7800000;
  13097. for ( let i = 1; i < 64; ++ i ) {
  13098. if ( i !== 32 ) {
  13099. offsetTable[ i ] = 1024;
  13100. }
  13101. }
  13102. return {
  13103. floatView: floatView,
  13104. uint32View: uint32View,
  13105. baseTable: baseTable,
  13106. shiftTable: shiftTable,
  13107. mantissaTable: mantissaTable,
  13108. exponentTable: exponentTable,
  13109. offsetTable: offsetTable
  13110. };
  13111. }
  13112. /**
  13113. * Returns a half precision floating point value (FP16) from the given single
  13114. * precision floating point value (FP32).
  13115. *
  13116. * @param {number} val - A single precision floating point value.
  13117. * @return {number} The FP16 value.
  13118. */
  13119. function toHalfFloat( val ) {
  13120. if ( Math.abs( val ) > 65504 ) console.warn( 'THREE.DataUtils.toHalfFloat(): Value out of range.' );
  13121. val = clamp( val, -65504, 65504 );
  13122. _tables.floatView[ 0 ] = val;
  13123. const f = _tables.uint32View[ 0 ];
  13124. const e = ( f >> 23 ) & 0x1ff;
  13125. return _tables.baseTable[ e ] + ( ( f & 0x007fffff ) >> _tables.shiftTable[ e ] );
  13126. }
  13127. /**
  13128. * Returns a single precision floating point value (FP32) from the given half
  13129. * precision floating point value (FP16).
  13130. *
  13131. * @param {number} val - A half precision floating point value.
  13132. * @return {number} The FP32 value.
  13133. */
  13134. function fromHalfFloat( val ) {
  13135. const m = val >> 10;
  13136. _tables.uint32View[ 0 ] = _tables.mantissaTable[ _tables.offsetTable[ m ] + ( val & 0x3ff ) ] + _tables.exponentTable[ m ];
  13137. return _tables.floatView[ 0 ];
  13138. }
  13139. /**
  13140. * A class containing utility functions for data.
  13141. *
  13142. * @hideconstructor
  13143. */
  13144. class DataUtils {
  13145. /**
  13146. * Returns a half precision floating point value (FP16) from the given single
  13147. * precision floating point value (FP32).
  13148. *
  13149. * @param {number} val - A single precision floating point value.
  13150. * @return {number} The FP16 value.
  13151. */
  13152. static toHalfFloat( val ) {
  13153. return toHalfFloat( val );
  13154. }
  13155. /**
  13156. * Returns a single precision floating point value (FP32) from the given half
  13157. * precision floating point value (FP16).
  13158. *
  13159. * @param {number} val - A half precision floating point value.
  13160. * @return {number} The FP32 value.
  13161. */
  13162. static fromHalfFloat( val ) {
  13163. return fromHalfFloat( val );
  13164. }
  13165. }
  13166. const _vector$9 = /*@__PURE__*/ new Vector3();
  13167. const _vector2$1 = /*@__PURE__*/ new Vector2();
  13168. let _id$2 = 0;
  13169. /**
  13170. * This class stores data for an attribute (such as vertex positions, face
  13171. * indices, normals, colors, UVs, and any custom attributes ) associated with
  13172. * a geometry, which allows for more efficient passing of data to the GPU.
  13173. *
  13174. * When working with vector-like data, the `fromBufferAttribute( attribute, index )`
  13175. * helper methods on vector and color class might be helpful. E.g. {@link Vector3#fromBufferAttribute}.
  13176. */
  13177. class BufferAttribute {
  13178. /**
  13179. * Constructs a new buffer attribute.
  13180. *
  13181. * @param {TypedArray} array - The array holding the attribute data.
  13182. * @param {number} itemSize - The item size.
  13183. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  13184. */
  13185. constructor( array, itemSize, normalized = false ) {
  13186. if ( Array.isArray( array ) ) {
  13187. throw new TypeError( 'THREE.BufferAttribute: array should be a Typed Array.' );
  13188. }
  13189. /**
  13190. * This flag can be used for type testing.
  13191. *
  13192. * @type {boolean}
  13193. * @readonly
  13194. * @default true
  13195. */
  13196. this.isBufferAttribute = true;
  13197. /**
  13198. * The ID of the buffer attribute.
  13199. *
  13200. * @name BufferAttribute#id
  13201. * @type {number}
  13202. * @readonly
  13203. */
  13204. Object.defineProperty( this, 'id', { value: _id$2 ++ } );
  13205. /**
  13206. * The name of the buffer attribute.
  13207. *
  13208. * @type {string}
  13209. */
  13210. this.name = '';
  13211. /**
  13212. * The array holding the attribute data. It should have `itemSize * numVertices`
  13213. * elements, where `numVertices` is the number of vertices in the associated geometry.
  13214. *
  13215. * @type {TypedArray}
  13216. */
  13217. this.array = array;
  13218. /**
  13219. * The number of values of the array that should be associated with a particular vertex.
  13220. * For instance, if this attribute is storing a 3-component vector (such as a position,
  13221. * normal, or color), then the value should be `3`.
  13222. *
  13223. * @type {number}
  13224. */
  13225. this.itemSize = itemSize;
  13226. /**
  13227. * Represents the number of items this buffer attribute stores. It is internally computed
  13228. * by dividing the `array` length by the `itemSize`.
  13229. *
  13230. * @type {number}
  13231. * @readonly
  13232. */
  13233. this.count = array !== undefined ? array.length / itemSize : 0;
  13234. /**
  13235. * Applies to integer data only. Indicates how the underlying data in the buffer maps to
  13236. * the values in the GLSL code. For instance, if `array` is an instance of `UInt16Array`,
  13237. * and `normalized` is `true`, the values `0 -+65535` in the array data will be mapped to
  13238. * `0.0f - +1.0f` in the GLSL attribute. If `normalized` is `false`, the values will be converted
  13239. * to floats unmodified, i.e. `65535` becomes `65535.0f`.
  13240. *
  13241. * @type {boolean}
  13242. */
  13243. this.normalized = normalized;
  13244. /**
  13245. * Defines the intended usage pattern of the data store for optimization purposes.
  13246. *
  13247. * Note: After the initial use of a buffer, its usage cannot be changed. Instead,
  13248. * instantiate a new one and set the desired usage before the next render.
  13249. *
  13250. * @type {(StaticDrawUsage|DynamicDrawUsage|StreamDrawUsage|StaticReadUsage|DynamicReadUsage|StreamReadUsage|StaticCopyUsage|DynamicCopyUsage|StreamCopyUsage)}
  13251. * @default StaticDrawUsage
  13252. */
  13253. this.usage = StaticDrawUsage;
  13254. /**
  13255. * This can be used to only update some components of stored vectors (for example, just the
  13256. * component related to color). Use the `addUpdateRange()` function to add ranges to this array.
  13257. *
  13258. * @type {Array<Object>}
  13259. */
  13260. this.updateRanges = [];
  13261. /**
  13262. * Configures the bound GPU type for use in shaders.
  13263. *
  13264. * Note: this only has an effect for integer arrays and is not configurable for float arrays.
  13265. * For lower precision float types, use `Float16BufferAttribute`.
  13266. *
  13267. * @type {(FloatType|IntType)}
  13268. * @default FloatType
  13269. */
  13270. this.gpuType = FloatType;
  13271. /**
  13272. * A version number, incremented every time the `needsUpdate` is set to `true`.
  13273. *
  13274. * @type {number}
  13275. */
  13276. this.version = 0;
  13277. }
  13278. /**
  13279. * A callback function that is executed after the renderer has transferred the attribute
  13280. * array data to the GPU.
  13281. */
  13282. onUploadCallback() {}
  13283. /**
  13284. * Flag to indicate that this attribute has changed and should be re-sent to
  13285. * the GPU. Set this to `true` when you modify the value of the array.
  13286. *
  13287. * @type {number}
  13288. * @default false
  13289. * @param {boolean} value
  13290. */
  13291. set needsUpdate( value ) {
  13292. if ( value === true ) this.version ++;
  13293. }
  13294. /**
  13295. * Sets the usage of this buffer attribute.
  13296. *
  13297. * @param {(StaticDrawUsage|DynamicDrawUsage|StreamDrawUsage|StaticReadUsage|DynamicReadUsage|StreamReadUsage|StaticCopyUsage|DynamicCopyUsage|StreamCopyUsage)} value - The usage to set.
  13298. * @return {BufferAttribute} A reference to this buffer attribute.
  13299. */
  13300. setUsage( value ) {
  13301. this.usage = value;
  13302. return this;
  13303. }
  13304. /**
  13305. * Adds a range of data in the data array to be updated on the GPU.
  13306. *
  13307. * @param {number} start - Position at which to start update.
  13308. * @param {number} count - The number of components to update.
  13309. */
  13310. addUpdateRange( start, count ) {
  13311. this.updateRanges.push( { start, count } );
  13312. }
  13313. /**
  13314. * Clears the update ranges.
  13315. */
  13316. clearUpdateRanges() {
  13317. this.updateRanges.length = 0;
  13318. }
  13319. /**
  13320. * Copies the values of the given buffer attribute to this instance.
  13321. *
  13322. * @param {BufferAttribute} source - The buffer attribute to copy.
  13323. * @return {BufferAttribute} A reference to this instance.
  13324. */
  13325. copy( source ) {
  13326. this.name = source.name;
  13327. this.array = new source.array.constructor( source.array );
  13328. this.itemSize = source.itemSize;
  13329. this.count = source.count;
  13330. this.normalized = source.normalized;
  13331. this.usage = source.usage;
  13332. this.gpuType = source.gpuType;
  13333. return this;
  13334. }
  13335. /**
  13336. * Copies a vector from the given buffer attribute to this one. The start
  13337. * and destination position in the attribute buffers are represented by the
  13338. * given indices.
  13339. *
  13340. * @param {number} index1 - The destination index into this buffer attribute.
  13341. * @param {BufferAttribute} attribute - The buffer attribute to copy from.
  13342. * @param {number} index2 - The source index into the given buffer attribute.
  13343. * @return {BufferAttribute} A reference to this instance.
  13344. */
  13345. copyAt( index1, attribute, index2 ) {
  13346. index1 *= this.itemSize;
  13347. index2 *= attribute.itemSize;
  13348. for ( let i = 0, l = this.itemSize; i < l; i ++ ) {
  13349. this.array[ index1 + i ] = attribute.array[ index2 + i ];
  13350. }
  13351. return this;
  13352. }
  13353. /**
  13354. * Copies the given array data into this buffer attribute.
  13355. *
  13356. * @param {(TypedArray|Array)} array - The array to copy.
  13357. * @return {BufferAttribute} A reference to this instance.
  13358. */
  13359. copyArray( array ) {
  13360. this.array.set( array );
  13361. return this;
  13362. }
  13363. /**
  13364. * Applies the given 3x3 matrix to the given attribute. Works with
  13365. * item size `2` and `3`.
  13366. *
  13367. * @param {Matrix3} m - The matrix to apply.
  13368. * @return {BufferAttribute} A reference to this instance.
  13369. */
  13370. applyMatrix3( m ) {
  13371. if ( this.itemSize === 2 ) {
  13372. for ( let i = 0, l = this.count; i < l; i ++ ) {
  13373. _vector2$1.fromBufferAttribute( this, i );
  13374. _vector2$1.applyMatrix3( m );
  13375. this.setXY( i, _vector2$1.x, _vector2$1.y );
  13376. }
  13377. } else if ( this.itemSize === 3 ) {
  13378. for ( let i = 0, l = this.count; i < l; i ++ ) {
  13379. _vector$9.fromBufferAttribute( this, i );
  13380. _vector$9.applyMatrix3( m );
  13381. this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  13382. }
  13383. }
  13384. return this;
  13385. }
  13386. /**
  13387. * Applies the given 4x4 matrix to the given attribute. Only works with
  13388. * item size `3`.
  13389. *
  13390. * @param {Matrix4} m - The matrix to apply.
  13391. * @return {BufferAttribute} A reference to this instance.
  13392. */
  13393. applyMatrix4( m ) {
  13394. for ( let i = 0, l = this.count; i < l; i ++ ) {
  13395. _vector$9.fromBufferAttribute( this, i );
  13396. _vector$9.applyMatrix4( m );
  13397. this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  13398. }
  13399. return this;
  13400. }
  13401. /**
  13402. * Applies the given 3x3 normal matrix to the given attribute. Only works with
  13403. * item size `3`.
  13404. *
  13405. * @param {Matrix3} m - The normal matrix to apply.
  13406. * @return {BufferAttribute} A reference to this instance.
  13407. */
  13408. applyNormalMatrix( m ) {
  13409. for ( let i = 0, l = this.count; i < l; i ++ ) {
  13410. _vector$9.fromBufferAttribute( this, i );
  13411. _vector$9.applyNormalMatrix( m );
  13412. this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  13413. }
  13414. return this;
  13415. }
  13416. /**
  13417. * Applies the given 4x4 matrix to the given attribute. Only works with
  13418. * item size `3` and with direction vectors.
  13419. *
  13420. * @param {Matrix4} m - The matrix to apply.
  13421. * @return {BufferAttribute} A reference to this instance.
  13422. */
  13423. transformDirection( m ) {
  13424. for ( let i = 0, l = this.count; i < l; i ++ ) {
  13425. _vector$9.fromBufferAttribute( this, i );
  13426. _vector$9.transformDirection( m );
  13427. this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  13428. }
  13429. return this;
  13430. }
  13431. /**
  13432. * Sets the given array data in the buffer attribute.
  13433. *
  13434. * @param {(TypedArray|Array)} value - The array data to set.
  13435. * @param {number} [offset=0] - The offset in this buffer attribute's array.
  13436. * @return {BufferAttribute} A reference to this instance.
  13437. */
  13438. set( value, offset = 0 ) {
  13439. // Matching BufferAttribute constructor, do not normalize the array.
  13440. this.array.set( value, offset );
  13441. return this;
  13442. }
  13443. /**
  13444. * Returns the given component of the vector at the given index.
  13445. *
  13446. * @param {number} index - The index into the buffer attribute.
  13447. * @param {number} component - The component index.
  13448. * @return {number} The returned value.
  13449. */
  13450. getComponent( index, component ) {
  13451. let value = this.array[ index * this.itemSize + component ];
  13452. if ( this.normalized ) value = denormalize( value, this.array );
  13453. return value;
  13454. }
  13455. /**
  13456. * Sets the given value to the given component of the vector at the given index.
  13457. *
  13458. * @param {number} index - The index into the buffer attribute.
  13459. * @param {number} component - The component index.
  13460. * @param {number} value - The value to set.
  13461. * @return {BufferAttribute} A reference to this instance.
  13462. */
  13463. setComponent( index, component, value ) {
  13464. if ( this.normalized ) value = normalize( value, this.array );
  13465. this.array[ index * this.itemSize + component ] = value;
  13466. return this;
  13467. }
  13468. /**
  13469. * Returns the x component of the vector at the given index.
  13470. *
  13471. * @param {number} index - The index into the buffer attribute.
  13472. * @return {number} The x component.
  13473. */
  13474. getX( index ) {
  13475. let x = this.array[ index * this.itemSize ];
  13476. if ( this.normalized ) x = denormalize( x, this.array );
  13477. return x;
  13478. }
  13479. /**
  13480. * Sets the x component of the vector at the given index.
  13481. *
  13482. * @param {number} index - The index into the buffer attribute.
  13483. * @param {number} x - The value to set.
  13484. * @return {BufferAttribute} A reference to this instance.
  13485. */
  13486. setX( index, x ) {
  13487. if ( this.normalized ) x = normalize( x, this.array );
  13488. this.array[ index * this.itemSize ] = x;
  13489. return this;
  13490. }
  13491. /**
  13492. * Returns the y component of the vector at the given index.
  13493. *
  13494. * @param {number} index - The index into the buffer attribute.
  13495. * @return {number} The y component.
  13496. */
  13497. getY( index ) {
  13498. let y = this.array[ index * this.itemSize + 1 ];
  13499. if ( this.normalized ) y = denormalize( y, this.array );
  13500. return y;
  13501. }
  13502. /**
  13503. * Sets the y component of the vector at the given index.
  13504. *
  13505. * @param {number} index - The index into the buffer attribute.
  13506. * @param {number} y - The value to set.
  13507. * @return {BufferAttribute} A reference to this instance.
  13508. */
  13509. setY( index, y ) {
  13510. if ( this.normalized ) y = normalize( y, this.array );
  13511. this.array[ index * this.itemSize + 1 ] = y;
  13512. return this;
  13513. }
  13514. /**
  13515. * Returns the z component of the vector at the given index.
  13516. *
  13517. * @param {number} index - The index into the buffer attribute.
  13518. * @return {number} The z component.
  13519. */
  13520. getZ( index ) {
  13521. let z = this.array[ index * this.itemSize + 2 ];
  13522. if ( this.normalized ) z = denormalize( z, this.array );
  13523. return z;
  13524. }
  13525. /**
  13526. * Sets the z component of the vector at the given index.
  13527. *
  13528. * @param {number} index - The index into the buffer attribute.
  13529. * @param {number} z - The value to set.
  13530. * @return {BufferAttribute} A reference to this instance.
  13531. */
  13532. setZ( index, z ) {
  13533. if ( this.normalized ) z = normalize( z, this.array );
  13534. this.array[ index * this.itemSize + 2 ] = z;
  13535. return this;
  13536. }
  13537. /**
  13538. * Returns the w component of the vector at the given index.
  13539. *
  13540. * @param {number} index - The index into the buffer attribute.
  13541. * @return {number} The w component.
  13542. */
  13543. getW( index ) {
  13544. let w = this.array[ index * this.itemSize + 3 ];
  13545. if ( this.normalized ) w = denormalize( w, this.array );
  13546. return w;
  13547. }
  13548. /**
  13549. * Sets the w component of the vector at the given index.
  13550. *
  13551. * @param {number} index - The index into the buffer attribute.
  13552. * @param {number} w - The value to set.
  13553. * @return {BufferAttribute} A reference to this instance.
  13554. */
  13555. setW( index, w ) {
  13556. if ( this.normalized ) w = normalize( w, this.array );
  13557. this.array[ index * this.itemSize + 3 ] = w;
  13558. return this;
  13559. }
  13560. /**
  13561. * Sets the x and y component of the vector at the given index.
  13562. *
  13563. * @param {number} index - The index into the buffer attribute.
  13564. * @param {number} x - The value for the x component to set.
  13565. * @param {number} y - The value for the y component to set.
  13566. * @return {BufferAttribute} A reference to this instance.
  13567. */
  13568. setXY( index, x, y ) {
  13569. index *= this.itemSize;
  13570. if ( this.normalized ) {
  13571. x = normalize( x, this.array );
  13572. y = normalize( y, this.array );
  13573. }
  13574. this.array[ index + 0 ] = x;
  13575. this.array[ index + 1 ] = y;
  13576. return this;
  13577. }
  13578. /**
  13579. * Sets the x, y and z component of the vector at the given index.
  13580. *
  13581. * @param {number} index - The index into the buffer attribute.
  13582. * @param {number} x - The value for the x component to set.
  13583. * @param {number} y - The value for the y component to set.
  13584. * @param {number} z - The value for the z component to set.
  13585. * @return {BufferAttribute} A reference to this instance.
  13586. */
  13587. setXYZ( index, x, y, z ) {
  13588. index *= this.itemSize;
  13589. if ( this.normalized ) {
  13590. x = normalize( x, this.array );
  13591. y = normalize( y, this.array );
  13592. z = normalize( z, this.array );
  13593. }
  13594. this.array[ index + 0 ] = x;
  13595. this.array[ index + 1 ] = y;
  13596. this.array[ index + 2 ] = z;
  13597. return this;
  13598. }
  13599. /**
  13600. * Sets the x, y, z and w component of the vector at the given index.
  13601. *
  13602. * @param {number} index - The index into the buffer attribute.
  13603. * @param {number} x - The value for the x component to set.
  13604. * @param {number} y - The value for the y component to set.
  13605. * @param {number} z - The value for the z component to set.
  13606. * @param {number} w - The value for the w component to set.
  13607. * @return {BufferAttribute} A reference to this instance.
  13608. */
  13609. setXYZW( index, x, y, z, w ) {
  13610. index *= this.itemSize;
  13611. if ( this.normalized ) {
  13612. x = normalize( x, this.array );
  13613. y = normalize( y, this.array );
  13614. z = normalize( z, this.array );
  13615. w = normalize( w, this.array );
  13616. }
  13617. this.array[ index + 0 ] = x;
  13618. this.array[ index + 1 ] = y;
  13619. this.array[ index + 2 ] = z;
  13620. this.array[ index + 3 ] = w;
  13621. return this;
  13622. }
  13623. /**
  13624. * Sets the given callback function that is executed after the Renderer has transferred
  13625. * the attribute array data to the GPU. Can be used to perform clean-up operations after
  13626. * the upload when attribute data are not needed anymore on the CPU side.
  13627. *
  13628. * @param {Function} callback - The `onUpload()` callback.
  13629. * @return {BufferAttribute} A reference to this instance.
  13630. */
  13631. onUpload( callback ) {
  13632. this.onUploadCallback = callback;
  13633. return this;
  13634. }
  13635. /**
  13636. * Returns a new buffer attribute with copied values from this instance.
  13637. *
  13638. * @return {BufferAttribute} A clone of this instance.
  13639. */
  13640. clone() {
  13641. return new this.constructor( this.array, this.itemSize ).copy( this );
  13642. }
  13643. /**
  13644. * Serializes the buffer attribute into JSON.
  13645. *
  13646. * @return {Object} A JSON object representing the serialized buffer attribute.
  13647. */
  13648. toJSON() {
  13649. const data = {
  13650. itemSize: this.itemSize,
  13651. type: this.array.constructor.name,
  13652. array: Array.from( this.array ),
  13653. normalized: this.normalized
  13654. };
  13655. if ( this.name !== '' ) data.name = this.name;
  13656. if ( this.usage !== StaticDrawUsage ) data.usage = this.usage;
  13657. return data;
  13658. }
  13659. }
  13660. /**
  13661. * Convenient class that can be used when creating a `Int8` buffer attribute with
  13662. * a plain `Array` instance.
  13663. *
  13664. * @augments BufferAttribute
  13665. */
  13666. class Int8BufferAttribute extends BufferAttribute {
  13667. /**
  13668. * Constructs a new buffer attribute.
  13669. *
  13670. * @param {(Array<number>|Int8Array)} array - The array holding the attribute data.
  13671. * @param {number} itemSize - The item size.
  13672. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  13673. */
  13674. constructor( array, itemSize, normalized ) {
  13675. super( new Int8Array( array ), itemSize, normalized );
  13676. }
  13677. }
  13678. /**
  13679. * Convenient class that can be used when creating a `UInt8` buffer attribute with
  13680. * a plain `Array` instance.
  13681. *
  13682. * @augments BufferAttribute
  13683. */
  13684. class Uint8BufferAttribute extends BufferAttribute {
  13685. /**
  13686. * Constructs a new buffer attribute.
  13687. *
  13688. * @param {(Array<number>|Uint8Array)} array - The array holding the attribute data.
  13689. * @param {number} itemSize - The item size.
  13690. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  13691. */
  13692. constructor( array, itemSize, normalized ) {
  13693. super( new Uint8Array( array ), itemSize, normalized );
  13694. }
  13695. }
  13696. /**
  13697. * Convenient class that can be used when creating a `UInt8Clamped` buffer attribute with
  13698. * a plain `Array` instance.
  13699. *
  13700. * @augments BufferAttribute
  13701. */
  13702. class Uint8ClampedBufferAttribute extends BufferAttribute {
  13703. /**
  13704. * Constructs a new buffer attribute.
  13705. *
  13706. * @param {(Array<number>|Uint8ClampedArray)} array - The array holding the attribute data.
  13707. * @param {number} itemSize - The item size.
  13708. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  13709. */
  13710. constructor( array, itemSize, normalized ) {
  13711. super( new Uint8ClampedArray( array ), itemSize, normalized );
  13712. }
  13713. }
  13714. /**
  13715. * Convenient class that can be used when creating a `Int16` buffer attribute with
  13716. * a plain `Array` instance.
  13717. *
  13718. * @augments BufferAttribute
  13719. */
  13720. class Int16BufferAttribute extends BufferAttribute {
  13721. /**
  13722. * Constructs a new buffer attribute.
  13723. *
  13724. * @param {(Array<number>|Int16Array)} array - The array holding the attribute data.
  13725. * @param {number} itemSize - The item size.
  13726. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  13727. */
  13728. constructor( array, itemSize, normalized ) {
  13729. super( new Int16Array( array ), itemSize, normalized );
  13730. }
  13731. }
  13732. /**
  13733. * Convenient class that can be used when creating a `UInt16` buffer attribute with
  13734. * a plain `Array` instance.
  13735. *
  13736. * @augments BufferAttribute
  13737. */
  13738. class Uint16BufferAttribute extends BufferAttribute {
  13739. /**
  13740. * Constructs a new buffer attribute.
  13741. *
  13742. * @param {(Array<number>|Uint16Array)} array - The array holding the attribute data.
  13743. * @param {number} itemSize - The item size.
  13744. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  13745. */
  13746. constructor( array, itemSize, normalized ) {
  13747. super( new Uint16Array( array ), itemSize, normalized );
  13748. }
  13749. }
  13750. /**
  13751. * Convenient class that can be used when creating a `Int32` buffer attribute with
  13752. * a plain `Array` instance.
  13753. *
  13754. * @augments BufferAttribute
  13755. */
  13756. class Int32BufferAttribute extends BufferAttribute {
  13757. /**
  13758. * Constructs a new buffer attribute.
  13759. *
  13760. * @param {(Array<number>|Int32Array)} array - The array holding the attribute data.
  13761. * @param {number} itemSize - The item size.
  13762. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  13763. */
  13764. constructor( array, itemSize, normalized ) {
  13765. super( new Int32Array( array ), itemSize, normalized );
  13766. }
  13767. }
  13768. /**
  13769. * Convenient class that can be used when creating a `UInt32` buffer attribute with
  13770. * a plain `Array` instance.
  13771. *
  13772. * @augments BufferAttribute
  13773. */
  13774. class Uint32BufferAttribute extends BufferAttribute {
  13775. /**
  13776. * Constructs a new buffer attribute.
  13777. *
  13778. * @param {(Array<number>|Uint32Array)} array - The array holding the attribute data.
  13779. * @param {number} itemSize - The item size.
  13780. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  13781. */
  13782. constructor( array, itemSize, normalized ) {
  13783. super( new Uint32Array( array ), itemSize, normalized );
  13784. }
  13785. }
  13786. /**
  13787. * Convenient class that can be used when creating a `Float16` buffer attribute with
  13788. * a plain `Array` instance.
  13789. *
  13790. * This class automatically converts to to and from FP16 since `Float16Array` is not
  13791. * natively supported in JavaScript.
  13792. *
  13793. * @augments BufferAttribute
  13794. */
  13795. class Float16BufferAttribute extends BufferAttribute {
  13796. /**
  13797. * Constructs a new buffer attribute.
  13798. *
  13799. * @param {(Array<number>|Uint16Array)} array - The array holding the attribute data.
  13800. * @param {number} itemSize - The item size.
  13801. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  13802. */
  13803. constructor( array, itemSize, normalized ) {
  13804. super( new Uint16Array( array ), itemSize, normalized );
  13805. this.isFloat16BufferAttribute = true;
  13806. }
  13807. getX( index ) {
  13808. let x = fromHalfFloat( this.array[ index * this.itemSize ] );
  13809. if ( this.normalized ) x = denormalize( x, this.array );
  13810. return x;
  13811. }
  13812. setX( index, x ) {
  13813. if ( this.normalized ) x = normalize( x, this.array );
  13814. this.array[ index * this.itemSize ] = toHalfFloat( x );
  13815. return this;
  13816. }
  13817. getY( index ) {
  13818. let y = fromHalfFloat( this.array[ index * this.itemSize + 1 ] );
  13819. if ( this.normalized ) y = denormalize( y, this.array );
  13820. return y;
  13821. }
  13822. setY( index, y ) {
  13823. if ( this.normalized ) y = normalize( y, this.array );
  13824. this.array[ index * this.itemSize + 1 ] = toHalfFloat( y );
  13825. return this;
  13826. }
  13827. getZ( index ) {
  13828. let z = fromHalfFloat( this.array[ index * this.itemSize + 2 ] );
  13829. if ( this.normalized ) z = denormalize( z, this.array );
  13830. return z;
  13831. }
  13832. setZ( index, z ) {
  13833. if ( this.normalized ) z = normalize( z, this.array );
  13834. this.array[ index * this.itemSize + 2 ] = toHalfFloat( z );
  13835. return this;
  13836. }
  13837. getW( index ) {
  13838. let w = fromHalfFloat( this.array[ index * this.itemSize + 3 ] );
  13839. if ( this.normalized ) w = denormalize( w, this.array );
  13840. return w;
  13841. }
  13842. setW( index, w ) {
  13843. if ( this.normalized ) w = normalize( w, this.array );
  13844. this.array[ index * this.itemSize + 3 ] = toHalfFloat( w );
  13845. return this;
  13846. }
  13847. setXY( index, x, y ) {
  13848. index *= this.itemSize;
  13849. if ( this.normalized ) {
  13850. x = normalize( x, this.array );
  13851. y = normalize( y, this.array );
  13852. }
  13853. this.array[ index + 0 ] = toHalfFloat( x );
  13854. this.array[ index + 1 ] = toHalfFloat( y );
  13855. return this;
  13856. }
  13857. setXYZ( index, x, y, z ) {
  13858. index *= this.itemSize;
  13859. if ( this.normalized ) {
  13860. x = normalize( x, this.array );
  13861. y = normalize( y, this.array );
  13862. z = normalize( z, this.array );
  13863. }
  13864. this.array[ index + 0 ] = toHalfFloat( x );
  13865. this.array[ index + 1 ] = toHalfFloat( y );
  13866. this.array[ index + 2 ] = toHalfFloat( z );
  13867. return this;
  13868. }
  13869. setXYZW( index, x, y, z, w ) {
  13870. index *= this.itemSize;
  13871. if ( this.normalized ) {
  13872. x = normalize( x, this.array );
  13873. y = normalize( y, this.array );
  13874. z = normalize( z, this.array );
  13875. w = normalize( w, this.array );
  13876. }
  13877. this.array[ index + 0 ] = toHalfFloat( x );
  13878. this.array[ index + 1 ] = toHalfFloat( y );
  13879. this.array[ index + 2 ] = toHalfFloat( z );
  13880. this.array[ index + 3 ] = toHalfFloat( w );
  13881. return this;
  13882. }
  13883. }
  13884. /**
  13885. * Convenient class that can be used when creating a `Float32` buffer attribute with
  13886. * a plain `Array` instance.
  13887. *
  13888. * @augments BufferAttribute
  13889. */
  13890. class Float32BufferAttribute extends BufferAttribute {
  13891. /**
  13892. * Constructs a new buffer attribute.
  13893. *
  13894. * @param {(Array<number>|Float32Array)} array - The array holding the attribute data.
  13895. * @param {number} itemSize - The item size.
  13896. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  13897. */
  13898. constructor( array, itemSize, normalized ) {
  13899. super( new Float32Array( array ), itemSize, normalized );
  13900. }
  13901. }
  13902. let _id$1 = 0;
  13903. const _m1 = /*@__PURE__*/ new Matrix4();
  13904. const _obj = /*@__PURE__*/ new Object3D();
  13905. const _offset = /*@__PURE__*/ new Vector3();
  13906. const _box$2 = /*@__PURE__*/ new Box3();
  13907. const _boxMorphTargets = /*@__PURE__*/ new Box3();
  13908. const _vector$8 = /*@__PURE__*/ new Vector3();
  13909. /**
  13910. * A representation of mesh, line, or point geometry. Includes vertex
  13911. * positions, face indices, normals, colors, UVs, and custom attributes
  13912. * within buffers, reducing the cost of passing all this data to the GPU.
  13913. *
  13914. * ```js
  13915. * const geometry = new THREE.BufferGeometry();
  13916. * // create a simple square shape. We duplicate the top left and bottom right
  13917. * // vertices because each vertex needs to appear once per triangle.
  13918. * const vertices = new Float32Array( [
  13919. * -1.0, -1.0, 1.0, // v0
  13920. * 1.0, -1.0, 1.0, // v1
  13921. * 1.0, 1.0, 1.0, // v2
  13922. *
  13923. * 1.0, 1.0, 1.0, // v3
  13924. * -1.0, 1.0, 1.0, // v4
  13925. * -1.0, -1.0, 1.0 // v5
  13926. * ] );
  13927. * // itemSize = 3 because there are 3 values (components) per vertex
  13928. * geometry.setAttribute( 'position', new THREE.BufferAttribute( vertices, 3 ) );
  13929. * const material = new THREE.MeshBasicMaterial( { color: 0xff0000 } );
  13930. * const mesh = new THREE.Mesh( geometry, material );
  13931. * ```
  13932. *
  13933. * @augments EventDispatcher
  13934. */
  13935. class BufferGeometry extends EventDispatcher {
  13936. /**
  13937. * Constructs a new geometry.
  13938. */
  13939. constructor() {
  13940. super();
  13941. /**
  13942. * This flag can be used for type testing.
  13943. *
  13944. * @type {boolean}
  13945. * @readonly
  13946. * @default true
  13947. */
  13948. this.isBufferGeometry = true;
  13949. /**
  13950. * The ID of the geometry.
  13951. *
  13952. * @name BufferGeometry#id
  13953. * @type {number}
  13954. * @readonly
  13955. */
  13956. Object.defineProperty( this, 'id', { value: _id$1 ++ } );
  13957. /**
  13958. * The UUID of the geometry.
  13959. *
  13960. * @type {string}
  13961. * @readonly
  13962. */
  13963. this.uuid = generateUUID();
  13964. /**
  13965. * The name of the geometry.
  13966. *
  13967. * @type {string}
  13968. */
  13969. this.name = '';
  13970. this.type = 'BufferGeometry';
  13971. /**
  13972. * Allows for vertices to be re-used across multiple triangles; this is
  13973. * called using "indexed triangles". Each triangle is associated with the
  13974. * indices of three vertices. This attribute therefore stores the index of
  13975. * each vertex for each triangular face. If this attribute is not set, the
  13976. * renderer assumes that each three contiguous positions represent a single triangle.
  13977. *
  13978. * @type {?BufferAttribute}
  13979. * @default null
  13980. */
  13981. this.index = null;
  13982. /**
  13983. * A (storage) buffer attribute which was generated with a compute shader and
  13984. * now defines indirect draw calls.
  13985. *
  13986. * Can only be used with {@link WebGPURenderer} and a WebGPU backend.
  13987. *
  13988. * @type {?BufferAttribute}
  13989. * @default null
  13990. */
  13991. this.indirect = null;
  13992. /**
  13993. * This dictionary has as id the name of the attribute to be set and as value
  13994. * the buffer attribute to set it to. Rather than accessing this property directly,
  13995. * use `setAttribute()` and `getAttribute()` to access attributes of this geometry.
  13996. *
  13997. * @type {Object<string,(BufferAttribute|InterleavedBufferAttribute)>}
  13998. */
  13999. this.attributes = {};
  14000. /**
  14001. * This dictionary holds the morph targets of the geometry.
  14002. *
  14003. * Note: Once the geometry has been rendered, the morph attribute data cannot
  14004. * be changed. You will have to call `dispose()?, and create a new geometry instance.
  14005. *
  14006. * @type {Object}
  14007. */
  14008. this.morphAttributes = {};
  14009. /**
  14010. * Used to control the morph target behavior; when set to `true`, the morph
  14011. * target data is treated as relative offsets, rather than as absolute
  14012. * positions/normals.
  14013. *
  14014. * @type {boolean}
  14015. * @default false
  14016. */
  14017. this.morphTargetsRelative = false;
  14018. /**
  14019. * Split the geometry into groups, each of which will be rendered in a
  14020. * separate draw call. This allows an array of materials to be used with the geometry.
  14021. *
  14022. * Use `addGroup()` and `clearGroups()` to edit groups, rather than modifying this array directly.
  14023. *
  14024. * Every vertex and index must belong to exactly one group — groups must not share vertices or
  14025. * indices, and must not leave vertices or indices unused.
  14026. *
  14027. * @type {Array<Object>}
  14028. */
  14029. this.groups = [];
  14030. /**
  14031. * Bounding box for the geometry which can be calculated with `computeBoundingBox()`.
  14032. *
  14033. * @type {Box3}
  14034. * @default null
  14035. */
  14036. this.boundingBox = null;
  14037. /**
  14038. * Bounding sphere for the geometry which can be calculated with `computeBoundingSphere()`.
  14039. *
  14040. * @type {Sphere}
  14041. * @default null
  14042. */
  14043. this.boundingSphere = null;
  14044. /**
  14045. * Determines the part of the geometry to render. This should not be set directly,
  14046. * instead use `setDrawRange()`.
  14047. *
  14048. * @type {{start:number,count:number}}
  14049. */
  14050. this.drawRange = { start: 0, count: Infinity };
  14051. /**
  14052. * An object that can be used to store custom data about the geometry.
  14053. * It should not hold references to functions as these will not be cloned.
  14054. *
  14055. * @type {Object}
  14056. */
  14057. this.userData = {};
  14058. }
  14059. /**
  14060. * Returns the index of this geometry.
  14061. *
  14062. * @return {?BufferAttribute} The index. Returns `null` if no index is defined.
  14063. */
  14064. getIndex() {
  14065. return this.index;
  14066. }
  14067. /**
  14068. * Sets the given index to this geometry.
  14069. *
  14070. * @param {Array<number>|BufferAttribute} index - The index to set.
  14071. * @return {BufferGeometry} A reference to this instance.
  14072. */
  14073. setIndex( index ) {
  14074. if ( Array.isArray( index ) ) {
  14075. this.index = new ( arrayNeedsUint32( index ) ? Uint32BufferAttribute : Uint16BufferAttribute )( index, 1 );
  14076. } else {
  14077. this.index = index;
  14078. }
  14079. return this;
  14080. }
  14081. /**
  14082. * Sets the given indirect attribute to this geometry.
  14083. *
  14084. * @param {BufferAttribute} indirect - The attribute holding indirect draw calls.
  14085. * @return {BufferGeometry} A reference to this instance.
  14086. */
  14087. setIndirect( indirect ) {
  14088. this.indirect = indirect;
  14089. return this;
  14090. }
  14091. /**
  14092. * Returns the indirect attribute of this geometry.
  14093. *
  14094. * @return {?BufferAttribute} The indirect attribute. Returns `null` if no indirect attribute is defined.
  14095. */
  14096. getIndirect() {
  14097. return this.indirect;
  14098. }
  14099. /**
  14100. * Returns the buffer attribute for the given name.
  14101. *
  14102. * @param {string} name - The attribute name.
  14103. * @return {BufferAttribute|InterleavedBufferAttribute|undefined} The buffer attribute.
  14104. * Returns `undefined` if not attribute has been found.
  14105. */
  14106. getAttribute( name ) {
  14107. return this.attributes[ name ];
  14108. }
  14109. /**
  14110. * Sets the given attribute for the given name.
  14111. *
  14112. * @param {string} name - The attribute name.
  14113. * @param {BufferAttribute|InterleavedBufferAttribute} attribute - The attribute to set.
  14114. * @return {BufferGeometry} A reference to this instance.
  14115. */
  14116. setAttribute( name, attribute ) {
  14117. this.attributes[ name ] = attribute;
  14118. return this;
  14119. }
  14120. /**
  14121. * Deletes the attribute for the given name.
  14122. *
  14123. * @param {string} name - The attribute name to delete.
  14124. * @return {BufferGeometry} A reference to this instance.
  14125. */
  14126. deleteAttribute( name ) {
  14127. delete this.attributes[ name ];
  14128. return this;
  14129. }
  14130. /**
  14131. * Returns `true` if this geometry has an attribute for the given name.
  14132. *
  14133. * @param {string} name - The attribute name.
  14134. * @return {boolean} Whether this geometry has an attribute for the given name or not.
  14135. */
  14136. hasAttribute( name ) {
  14137. return this.attributes[ name ] !== undefined;
  14138. }
  14139. /**
  14140. * Adds a group to this geometry.
  14141. *
  14142. * @param {number} start - The first element in this draw call. That is the first
  14143. * vertex for non-indexed geometry, otherwise the first triangle index.
  14144. * @param {number} count - Specifies how many vertices (or indices) are part of this group.
  14145. * @param {number} [materialIndex=0] - The material array index to use.
  14146. */
  14147. addGroup( start, count, materialIndex = 0 ) {
  14148. this.groups.push( {
  14149. start: start,
  14150. count: count,
  14151. materialIndex: materialIndex
  14152. } );
  14153. }
  14154. /**
  14155. * Clears all groups.
  14156. */
  14157. clearGroups() {
  14158. this.groups = [];
  14159. }
  14160. /**
  14161. * Sets the draw range for this geometry.
  14162. *
  14163. * @param {number} start - The first vertex for non-indexed geometry, otherwise the first triangle index.
  14164. * @param {number} count - For non-indexed BufferGeometry, `count` is the number of vertices to render.
  14165. * For indexed BufferGeometry, `count` is the number of indices to render.
  14166. */
  14167. setDrawRange( start, count ) {
  14168. this.drawRange.start = start;
  14169. this.drawRange.count = count;
  14170. }
  14171. /**
  14172. * Applies the given 4x4 transformation matrix to the geometry.
  14173. *
  14174. * @param {Matrix4} matrix - The matrix to apply.
  14175. * @return {BufferGeometry} A reference to this instance.
  14176. */
  14177. applyMatrix4( matrix ) {
  14178. const position = this.attributes.position;
  14179. if ( position !== undefined ) {
  14180. position.applyMatrix4( matrix );
  14181. position.needsUpdate = true;
  14182. }
  14183. const normal = this.attributes.normal;
  14184. if ( normal !== undefined ) {
  14185. const normalMatrix = new Matrix3().getNormalMatrix( matrix );
  14186. normal.applyNormalMatrix( normalMatrix );
  14187. normal.needsUpdate = true;
  14188. }
  14189. const tangent = this.attributes.tangent;
  14190. if ( tangent !== undefined ) {
  14191. tangent.transformDirection( matrix );
  14192. tangent.needsUpdate = true;
  14193. }
  14194. if ( this.boundingBox !== null ) {
  14195. this.computeBoundingBox();
  14196. }
  14197. if ( this.boundingSphere !== null ) {
  14198. this.computeBoundingSphere();
  14199. }
  14200. return this;
  14201. }
  14202. /**
  14203. * Applies the rotation represented by the Quaternion to the geometry.
  14204. *
  14205. * @param {Quaternion} q - The Quaternion to apply.
  14206. * @return {BufferGeometry} A reference to this instance.
  14207. */
  14208. applyQuaternion( q ) {
  14209. _m1.makeRotationFromQuaternion( q );
  14210. this.applyMatrix4( _m1 );
  14211. return this;
  14212. }
  14213. /**
  14214. * Rotates the geometry about the X axis. This is typically done as a one time
  14215. * operation, and not during a loop. Use {@link Object3D#rotation} for typical
  14216. * real-time mesh rotation.
  14217. *
  14218. * @param {number} angle - The angle in radians.
  14219. * @return {BufferGeometry} A reference to this instance.
  14220. */
  14221. rotateX( angle ) {
  14222. // rotate geometry around world x-axis
  14223. _m1.makeRotationX( angle );
  14224. this.applyMatrix4( _m1 );
  14225. return this;
  14226. }
  14227. /**
  14228. * Rotates the geometry about the Y axis. This is typically done as a one time
  14229. * operation, and not during a loop. Use {@link Object3D#rotation} for typical
  14230. * real-time mesh rotation.
  14231. *
  14232. * @param {number} angle - The angle in radians.
  14233. * @return {BufferGeometry} A reference to this instance.
  14234. */
  14235. rotateY( angle ) {
  14236. // rotate geometry around world y-axis
  14237. _m1.makeRotationY( angle );
  14238. this.applyMatrix4( _m1 );
  14239. return this;
  14240. }
  14241. /**
  14242. * Rotates the geometry about the Z axis. This is typically done as a one time
  14243. * operation, and not during a loop. Use {@link Object3D#rotation} for typical
  14244. * real-time mesh rotation.
  14245. *
  14246. * @param {number} angle - The angle in radians.
  14247. * @return {BufferGeometry} A reference to this instance.
  14248. */
  14249. rotateZ( angle ) {
  14250. // rotate geometry around world z-axis
  14251. _m1.makeRotationZ( angle );
  14252. this.applyMatrix4( _m1 );
  14253. return this;
  14254. }
  14255. /**
  14256. * Translates the geometry. This is typically done as a one time
  14257. * operation, and not during a loop. Use {@link Object3D#position} for typical
  14258. * real-time mesh rotation.
  14259. *
  14260. * @param {number} x - The x offset.
  14261. * @param {number} y - The y offset.
  14262. * @param {number} z - The z offset.
  14263. * @return {BufferGeometry} A reference to this instance.
  14264. */
  14265. translate( x, y, z ) {
  14266. // translate geometry
  14267. _m1.makeTranslation( x, y, z );
  14268. this.applyMatrix4( _m1 );
  14269. return this;
  14270. }
  14271. /**
  14272. * Scales the geometry. This is typically done as a one time
  14273. * operation, and not during a loop. Use {@link Object3D#scale} for typical
  14274. * real-time mesh rotation.
  14275. *
  14276. * @param {number} x - The x scale.
  14277. * @param {number} y - The y scale.
  14278. * @param {number} z - The z scale.
  14279. * @return {BufferGeometry} A reference to this instance.
  14280. */
  14281. scale( x, y, z ) {
  14282. // scale geometry
  14283. _m1.makeScale( x, y, z );
  14284. this.applyMatrix4( _m1 );
  14285. return this;
  14286. }
  14287. /**
  14288. * Rotates the geometry to face a point in 3D space. This is typically done as a one time
  14289. * operation, and not during a loop. Use {@link Object3D#lookAt} for typical
  14290. * real-time mesh rotation.
  14291. *
  14292. * @param {Vector3} vector - The target point.
  14293. * @return {BufferGeometry} A reference to this instance.
  14294. */
  14295. lookAt( vector ) {
  14296. _obj.lookAt( vector );
  14297. _obj.updateMatrix();
  14298. this.applyMatrix4( _obj.matrix );
  14299. return this;
  14300. }
  14301. /**
  14302. * Center the geometry based on its bounding box.
  14303. *
  14304. * @return {BufferGeometry} A reference to this instance.
  14305. */
  14306. center() {
  14307. this.computeBoundingBox();
  14308. this.boundingBox.getCenter( _offset ).negate();
  14309. this.translate( _offset.x, _offset.y, _offset.z );
  14310. return this;
  14311. }
  14312. /**
  14313. * Defines a geometry by creating a `position` attribute based on the given array of points. The array
  14314. * can hold 2D or 3D vectors. When using two-dimensional data, the `z` coordinate for all vertices is
  14315. * set to `0`.
  14316. *
  14317. * If the method is used with an existing `position` attribute, the vertex data are overwritten with the
  14318. * data from the array. The length of the array must match the vertex count.
  14319. *
  14320. * @param {Array<Vector2>|Array<Vector3>} points - The points.
  14321. * @return {BufferGeometry} A reference to this instance.
  14322. */
  14323. setFromPoints( points ) {
  14324. const positionAttribute = this.getAttribute( 'position' );
  14325. if ( positionAttribute === undefined ) {
  14326. const position = [];
  14327. for ( let i = 0, l = points.length; i < l; i ++ ) {
  14328. const point = points[ i ];
  14329. position.push( point.x, point.y, point.z || 0 );
  14330. }
  14331. this.setAttribute( 'position', new Float32BufferAttribute( position, 3 ) );
  14332. } else {
  14333. const l = Math.min( points.length, positionAttribute.count ); // make sure data do not exceed buffer size
  14334. for ( let i = 0; i < l; i ++ ) {
  14335. const point = points[ i ];
  14336. positionAttribute.setXYZ( i, point.x, point.y, point.z || 0 );
  14337. }
  14338. if ( points.length > positionAttribute.count ) {
  14339. console.warn( 'THREE.BufferGeometry: Buffer size too small for points data. Use .dispose() and create a new geometry.' );
  14340. }
  14341. positionAttribute.needsUpdate = true;
  14342. }
  14343. return this;
  14344. }
  14345. /**
  14346. * Computes the bounding box of the geometry, and updates the `boundingBox` member.
  14347. * The bounding box is not computed by the engine; it must be computed by your app.
  14348. * You may need to recompute the bounding box if the geometry vertices are modified.
  14349. */
  14350. computeBoundingBox() {
  14351. if ( this.boundingBox === null ) {
  14352. this.boundingBox = new Box3();
  14353. }
  14354. const position = this.attributes.position;
  14355. const morphAttributesPosition = this.morphAttributes.position;
  14356. if ( position && position.isGLBufferAttribute ) {
  14357. console.error( 'THREE.BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box.', this );
  14358. this.boundingBox.set(
  14359. new Vector3( - Infinity, - Infinity, - Infinity ),
  14360. new Vector3( + Infinity, + Infinity, + Infinity )
  14361. );
  14362. return;
  14363. }
  14364. if ( position !== undefined ) {
  14365. this.boundingBox.setFromBufferAttribute( position );
  14366. // process morph attributes if present
  14367. if ( morphAttributesPosition ) {
  14368. for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  14369. const morphAttribute = morphAttributesPosition[ i ];
  14370. _box$2.setFromBufferAttribute( morphAttribute );
  14371. if ( this.morphTargetsRelative ) {
  14372. _vector$8.addVectors( this.boundingBox.min, _box$2.min );
  14373. this.boundingBox.expandByPoint( _vector$8 );
  14374. _vector$8.addVectors( this.boundingBox.max, _box$2.max );
  14375. this.boundingBox.expandByPoint( _vector$8 );
  14376. } else {
  14377. this.boundingBox.expandByPoint( _box$2.min );
  14378. this.boundingBox.expandByPoint( _box$2.max );
  14379. }
  14380. }
  14381. }
  14382. } else {
  14383. this.boundingBox.makeEmpty();
  14384. }
  14385. if ( isNaN( this.boundingBox.min.x ) || isNaN( this.boundingBox.min.y ) || isNaN( this.boundingBox.min.z ) ) {
  14386. console.error( 'THREE.BufferGeometry.computeBoundingBox(): Computed min/max have NaN values. The "position" attribute is likely to have NaN values.', this );
  14387. }
  14388. }
  14389. /**
  14390. * Computes the bounding sphere of the geometry, and updates the `boundingSphere` member.
  14391. * The engine automatically computes the bounding sphere when it is needed, e.g., for ray casting or view frustum culling.
  14392. * You may need to recompute the bounding sphere if the geometry vertices are modified.
  14393. */
  14394. computeBoundingSphere() {
  14395. if ( this.boundingSphere === null ) {
  14396. this.boundingSphere = new Sphere();
  14397. }
  14398. const position = this.attributes.position;
  14399. const morphAttributesPosition = this.morphAttributes.position;
  14400. if ( position && position.isGLBufferAttribute ) {
  14401. console.error( 'THREE.BufferGeometry.computeBoundingSphere(): GLBufferAttribute requires a manual bounding sphere.', this );
  14402. this.boundingSphere.set( new Vector3(), Infinity );
  14403. return;
  14404. }
  14405. if ( position ) {
  14406. // first, find the center of the bounding sphere
  14407. const center = this.boundingSphere.center;
  14408. _box$2.setFromBufferAttribute( position );
  14409. // process morph attributes if present
  14410. if ( morphAttributesPosition ) {
  14411. for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  14412. const morphAttribute = morphAttributesPosition[ i ];
  14413. _boxMorphTargets.setFromBufferAttribute( morphAttribute );
  14414. if ( this.morphTargetsRelative ) {
  14415. _vector$8.addVectors( _box$2.min, _boxMorphTargets.min );
  14416. _box$2.expandByPoint( _vector$8 );
  14417. _vector$8.addVectors( _box$2.max, _boxMorphTargets.max );
  14418. _box$2.expandByPoint( _vector$8 );
  14419. } else {
  14420. _box$2.expandByPoint( _boxMorphTargets.min );
  14421. _box$2.expandByPoint( _boxMorphTargets.max );
  14422. }
  14423. }
  14424. }
  14425. _box$2.getCenter( center );
  14426. // second, try to find a boundingSphere with a radius smaller than the
  14427. // boundingSphere of the boundingBox: sqrt(3) smaller in the best case
  14428. let maxRadiusSq = 0;
  14429. for ( let i = 0, il = position.count; i < il; i ++ ) {
  14430. _vector$8.fromBufferAttribute( position, i );
  14431. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( _vector$8 ) );
  14432. }
  14433. // process morph attributes if present
  14434. if ( morphAttributesPosition ) {
  14435. for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  14436. const morphAttribute = morphAttributesPosition[ i ];
  14437. const morphTargetsRelative = this.morphTargetsRelative;
  14438. for ( let j = 0, jl = morphAttribute.count; j < jl; j ++ ) {
  14439. _vector$8.fromBufferAttribute( morphAttribute, j );
  14440. if ( morphTargetsRelative ) {
  14441. _offset.fromBufferAttribute( position, j );
  14442. _vector$8.add( _offset );
  14443. }
  14444. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( _vector$8 ) );
  14445. }
  14446. }
  14447. }
  14448. this.boundingSphere.radius = Math.sqrt( maxRadiusSq );
  14449. if ( isNaN( this.boundingSphere.radius ) ) {
  14450. console.error( 'THREE.BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.', this );
  14451. }
  14452. }
  14453. }
  14454. /**
  14455. * Calculates and adds a tangent attribute to this geometry.
  14456. *
  14457. * The computation is only supported for indexed geometries and if position, normal, and uv attributes
  14458. * are defined. When using a tangent space normal map, prefer the MikkTSpace algorithm provided by
  14459. * {@link BufferGeometryUtils#computeMikkTSpaceTangents} instead.
  14460. */
  14461. computeTangents() {
  14462. const index = this.index;
  14463. const attributes = this.attributes;
  14464. // based on http://www.terathon.com/code/tangent.html
  14465. // (per vertex tangents)
  14466. if ( index === null ||
  14467. attributes.position === undefined ||
  14468. attributes.normal === undefined ||
  14469. attributes.uv === undefined ) {
  14470. console.error( 'THREE.BufferGeometry: .computeTangents() failed. Missing required attributes (index, position, normal or uv)' );
  14471. return;
  14472. }
  14473. const positionAttribute = attributes.position;
  14474. const normalAttribute = attributes.normal;
  14475. const uvAttribute = attributes.uv;
  14476. if ( this.hasAttribute( 'tangent' ) === false ) {
  14477. this.setAttribute( 'tangent', new BufferAttribute( new Float32Array( 4 * positionAttribute.count ), 4 ) );
  14478. }
  14479. const tangentAttribute = this.getAttribute( 'tangent' );
  14480. const tan1 = [], tan2 = [];
  14481. for ( let i = 0; i < positionAttribute.count; i ++ ) {
  14482. tan1[ i ] = new Vector3();
  14483. tan2[ i ] = new Vector3();
  14484. }
  14485. const vA = new Vector3(),
  14486. vB = new Vector3(),
  14487. vC = new Vector3(),
  14488. uvA = new Vector2(),
  14489. uvB = new Vector2(),
  14490. uvC = new Vector2(),
  14491. sdir = new Vector3(),
  14492. tdir = new Vector3();
  14493. function handleTriangle( a, b, c ) {
  14494. vA.fromBufferAttribute( positionAttribute, a );
  14495. vB.fromBufferAttribute( positionAttribute, b );
  14496. vC.fromBufferAttribute( positionAttribute, c );
  14497. uvA.fromBufferAttribute( uvAttribute, a );
  14498. uvB.fromBufferAttribute( uvAttribute, b );
  14499. uvC.fromBufferAttribute( uvAttribute, c );
  14500. vB.sub( vA );
  14501. vC.sub( vA );
  14502. uvB.sub( uvA );
  14503. uvC.sub( uvA );
  14504. const r = 1.0 / ( uvB.x * uvC.y - uvC.x * uvB.y );
  14505. // silently ignore degenerate uv triangles having coincident or colinear vertices
  14506. if ( ! isFinite( r ) ) return;
  14507. sdir.copy( vB ).multiplyScalar( uvC.y ).addScaledVector( vC, - uvB.y ).multiplyScalar( r );
  14508. tdir.copy( vC ).multiplyScalar( uvB.x ).addScaledVector( vB, - uvC.x ).multiplyScalar( r );
  14509. tan1[ a ].add( sdir );
  14510. tan1[ b ].add( sdir );
  14511. tan1[ c ].add( sdir );
  14512. tan2[ a ].add( tdir );
  14513. tan2[ b ].add( tdir );
  14514. tan2[ c ].add( tdir );
  14515. }
  14516. let groups = this.groups;
  14517. if ( groups.length === 0 ) {
  14518. groups = [ {
  14519. start: 0,
  14520. count: index.count
  14521. } ];
  14522. }
  14523. for ( let i = 0, il = groups.length; i < il; ++ i ) {
  14524. const group = groups[ i ];
  14525. const start = group.start;
  14526. const count = group.count;
  14527. for ( let j = start, jl = start + count; j < jl; j += 3 ) {
  14528. handleTriangle(
  14529. index.getX( j + 0 ),
  14530. index.getX( j + 1 ),
  14531. index.getX( j + 2 )
  14532. );
  14533. }
  14534. }
  14535. const tmp = new Vector3(), tmp2 = new Vector3();
  14536. const n = new Vector3(), n2 = new Vector3();
  14537. function handleVertex( v ) {
  14538. n.fromBufferAttribute( normalAttribute, v );
  14539. n2.copy( n );
  14540. const t = tan1[ v ];
  14541. // Gram-Schmidt orthogonalize
  14542. tmp.copy( t );
  14543. tmp.sub( n.multiplyScalar( n.dot( t ) ) ).normalize();
  14544. // Calculate handedness
  14545. tmp2.crossVectors( n2, t );
  14546. const test = tmp2.dot( tan2[ v ] );
  14547. const w = ( test < 0.0 ) ? -1 : 1.0;
  14548. tangentAttribute.setXYZW( v, tmp.x, tmp.y, tmp.z, w );
  14549. }
  14550. for ( let i = 0, il = groups.length; i < il; ++ i ) {
  14551. const group = groups[ i ];
  14552. const start = group.start;
  14553. const count = group.count;
  14554. for ( let j = start, jl = start + count; j < jl; j += 3 ) {
  14555. handleVertex( index.getX( j + 0 ) );
  14556. handleVertex( index.getX( j + 1 ) );
  14557. handleVertex( index.getX( j + 2 ) );
  14558. }
  14559. }
  14560. }
  14561. /**
  14562. * Computes vertex normals for the given vertex data. For indexed geometries, the method sets
  14563. * each vertex normal to be the average of the face normals of the faces that share that vertex.
  14564. * For non-indexed geometries, vertices are not shared, and the method sets each vertex normal
  14565. * to be the same as the face normal.
  14566. */
  14567. computeVertexNormals() {
  14568. const index = this.index;
  14569. const positionAttribute = this.getAttribute( 'position' );
  14570. if ( positionAttribute !== undefined ) {
  14571. let normalAttribute = this.getAttribute( 'normal' );
  14572. if ( normalAttribute === undefined ) {
  14573. normalAttribute = new BufferAttribute( new Float32Array( positionAttribute.count * 3 ), 3 );
  14574. this.setAttribute( 'normal', normalAttribute );
  14575. } else {
  14576. // reset existing normals to zero
  14577. for ( let i = 0, il = normalAttribute.count; i < il; i ++ ) {
  14578. normalAttribute.setXYZ( i, 0, 0, 0 );
  14579. }
  14580. }
  14581. const pA = new Vector3(), pB = new Vector3(), pC = new Vector3();
  14582. const nA = new Vector3(), nB = new Vector3(), nC = new Vector3();
  14583. const cb = new Vector3(), ab = new Vector3();
  14584. // indexed elements
  14585. if ( index ) {
  14586. for ( let i = 0, il = index.count; i < il; i += 3 ) {
  14587. const vA = index.getX( i + 0 );
  14588. const vB = index.getX( i + 1 );
  14589. const vC = index.getX( i + 2 );
  14590. pA.fromBufferAttribute( positionAttribute, vA );
  14591. pB.fromBufferAttribute( positionAttribute, vB );
  14592. pC.fromBufferAttribute( positionAttribute, vC );
  14593. cb.subVectors( pC, pB );
  14594. ab.subVectors( pA, pB );
  14595. cb.cross( ab );
  14596. nA.fromBufferAttribute( normalAttribute, vA );
  14597. nB.fromBufferAttribute( normalAttribute, vB );
  14598. nC.fromBufferAttribute( normalAttribute, vC );
  14599. nA.add( cb );
  14600. nB.add( cb );
  14601. nC.add( cb );
  14602. normalAttribute.setXYZ( vA, nA.x, nA.y, nA.z );
  14603. normalAttribute.setXYZ( vB, nB.x, nB.y, nB.z );
  14604. normalAttribute.setXYZ( vC, nC.x, nC.y, nC.z );
  14605. }
  14606. } else {
  14607. // non-indexed elements (unconnected triangle soup)
  14608. for ( let i = 0, il = positionAttribute.count; i < il; i += 3 ) {
  14609. pA.fromBufferAttribute( positionAttribute, i + 0 );
  14610. pB.fromBufferAttribute( positionAttribute, i + 1 );
  14611. pC.fromBufferAttribute( positionAttribute, i + 2 );
  14612. cb.subVectors( pC, pB );
  14613. ab.subVectors( pA, pB );
  14614. cb.cross( ab );
  14615. normalAttribute.setXYZ( i + 0, cb.x, cb.y, cb.z );
  14616. normalAttribute.setXYZ( i + 1, cb.x, cb.y, cb.z );
  14617. normalAttribute.setXYZ( i + 2, cb.x, cb.y, cb.z );
  14618. }
  14619. }
  14620. this.normalizeNormals();
  14621. normalAttribute.needsUpdate = true;
  14622. }
  14623. }
  14624. /**
  14625. * Ensures every normal vector in a geometry will have a magnitude of `1`. This will
  14626. * correct lighting on the geometry surfaces.
  14627. */
  14628. normalizeNormals() {
  14629. const normals = this.attributes.normal;
  14630. for ( let i = 0, il = normals.count; i < il; i ++ ) {
  14631. _vector$8.fromBufferAttribute( normals, i );
  14632. _vector$8.normalize();
  14633. normals.setXYZ( i, _vector$8.x, _vector$8.y, _vector$8.z );
  14634. }
  14635. }
  14636. /**
  14637. * Return a new non-index version of this indexed geometry. If the geometry
  14638. * is already non-indexed, the method is a NOOP.
  14639. *
  14640. * @return {BufferGeometry} The non-indexed version of this indexed geometry.
  14641. */
  14642. toNonIndexed() {
  14643. function convertBufferAttribute( attribute, indices ) {
  14644. const array = attribute.array;
  14645. const itemSize = attribute.itemSize;
  14646. const normalized = attribute.normalized;
  14647. const array2 = new array.constructor( indices.length * itemSize );
  14648. let index = 0, index2 = 0;
  14649. for ( let i = 0, l = indices.length; i < l; i ++ ) {
  14650. if ( attribute.isInterleavedBufferAttribute ) {
  14651. index = indices[ i ] * attribute.data.stride + attribute.offset;
  14652. } else {
  14653. index = indices[ i ] * itemSize;
  14654. }
  14655. for ( let j = 0; j < itemSize; j ++ ) {
  14656. array2[ index2 ++ ] = array[ index ++ ];
  14657. }
  14658. }
  14659. return new BufferAttribute( array2, itemSize, normalized );
  14660. }
  14661. //
  14662. if ( this.index === null ) {
  14663. console.warn( 'THREE.BufferGeometry.toNonIndexed(): BufferGeometry is already non-indexed.' );
  14664. return this;
  14665. }
  14666. const geometry2 = new BufferGeometry();
  14667. const indices = this.index.array;
  14668. const attributes = this.attributes;
  14669. // attributes
  14670. for ( const name in attributes ) {
  14671. const attribute = attributes[ name ];
  14672. const newAttribute = convertBufferAttribute( attribute, indices );
  14673. geometry2.setAttribute( name, newAttribute );
  14674. }
  14675. // morph attributes
  14676. const morphAttributes = this.morphAttributes;
  14677. for ( const name in morphAttributes ) {
  14678. const morphArray = [];
  14679. const morphAttribute = morphAttributes[ name ]; // morphAttribute: array of Float32BufferAttributes
  14680. for ( let i = 0, il = morphAttribute.length; i < il; i ++ ) {
  14681. const attribute = morphAttribute[ i ];
  14682. const newAttribute = convertBufferAttribute( attribute, indices );
  14683. morphArray.push( newAttribute );
  14684. }
  14685. geometry2.morphAttributes[ name ] = morphArray;
  14686. }
  14687. geometry2.morphTargetsRelative = this.morphTargetsRelative;
  14688. // groups
  14689. const groups = this.groups;
  14690. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  14691. const group = groups[ i ];
  14692. geometry2.addGroup( group.start, group.count, group.materialIndex );
  14693. }
  14694. return geometry2;
  14695. }
  14696. /**
  14697. * Serializes the geometry into JSON.
  14698. *
  14699. * @return {Object} A JSON object representing the serialized geometry.
  14700. */
  14701. toJSON() {
  14702. const data = {
  14703. metadata: {
  14704. version: 4.6,
  14705. type: 'BufferGeometry',
  14706. generator: 'BufferGeometry.toJSON'
  14707. }
  14708. };
  14709. // standard BufferGeometry serialization
  14710. data.uuid = this.uuid;
  14711. data.type = this.type;
  14712. if ( this.name !== '' ) data.name = this.name;
  14713. if ( Object.keys( this.userData ).length > 0 ) data.userData = this.userData;
  14714. if ( this.parameters !== undefined ) {
  14715. const parameters = this.parameters;
  14716. for ( const key in parameters ) {
  14717. if ( parameters[ key ] !== undefined ) data[ key ] = parameters[ key ];
  14718. }
  14719. return data;
  14720. }
  14721. // for simplicity the code assumes attributes are not shared across geometries, see #15811
  14722. data.data = { attributes: {} };
  14723. const index = this.index;
  14724. if ( index !== null ) {
  14725. data.data.index = {
  14726. type: index.array.constructor.name,
  14727. array: Array.prototype.slice.call( index.array )
  14728. };
  14729. }
  14730. const attributes = this.attributes;
  14731. for ( const key in attributes ) {
  14732. const attribute = attributes[ key ];
  14733. data.data.attributes[ key ] = attribute.toJSON( data.data );
  14734. }
  14735. const morphAttributes = {};
  14736. let hasMorphAttributes = false;
  14737. for ( const key in this.morphAttributes ) {
  14738. const attributeArray = this.morphAttributes[ key ];
  14739. const array = [];
  14740. for ( let i = 0, il = attributeArray.length; i < il; i ++ ) {
  14741. const attribute = attributeArray[ i ];
  14742. array.push( attribute.toJSON( data.data ) );
  14743. }
  14744. if ( array.length > 0 ) {
  14745. morphAttributes[ key ] = array;
  14746. hasMorphAttributes = true;
  14747. }
  14748. }
  14749. if ( hasMorphAttributes ) {
  14750. data.data.morphAttributes = morphAttributes;
  14751. data.data.morphTargetsRelative = this.morphTargetsRelative;
  14752. }
  14753. const groups = this.groups;
  14754. if ( groups.length > 0 ) {
  14755. data.data.groups = JSON.parse( JSON.stringify( groups ) );
  14756. }
  14757. const boundingSphere = this.boundingSphere;
  14758. if ( boundingSphere !== null ) {
  14759. data.data.boundingSphere = {
  14760. center: boundingSphere.center.toArray(),
  14761. radius: boundingSphere.radius
  14762. };
  14763. }
  14764. return data;
  14765. }
  14766. /**
  14767. * Returns a new geometry with copied values from this instance.
  14768. *
  14769. * @return {BufferGeometry} A clone of this instance.
  14770. */
  14771. clone() {
  14772. return new this.constructor().copy( this );
  14773. }
  14774. /**
  14775. * Copies the values of the given geometry to this instance.
  14776. *
  14777. * @param {BufferGeometry} source - The geometry to copy.
  14778. * @return {BufferGeometry} A reference to this instance.
  14779. */
  14780. copy( source ) {
  14781. // reset
  14782. this.index = null;
  14783. this.attributes = {};
  14784. this.morphAttributes = {};
  14785. this.groups = [];
  14786. this.boundingBox = null;
  14787. this.boundingSphere = null;
  14788. // used for storing cloned, shared data
  14789. const data = {};
  14790. // name
  14791. this.name = source.name;
  14792. // index
  14793. const index = source.index;
  14794. if ( index !== null ) {
  14795. this.setIndex( index.clone() );
  14796. }
  14797. // attributes
  14798. const attributes = source.attributes;
  14799. for ( const name in attributes ) {
  14800. const attribute = attributes[ name ];
  14801. this.setAttribute( name, attribute.clone( data ) );
  14802. }
  14803. // morph attributes
  14804. const morphAttributes = source.morphAttributes;
  14805. for ( const name in morphAttributes ) {
  14806. const array = [];
  14807. const morphAttribute = morphAttributes[ name ]; // morphAttribute: array of Float32BufferAttributes
  14808. for ( let i = 0, l = morphAttribute.length; i < l; i ++ ) {
  14809. array.push( morphAttribute[ i ].clone( data ) );
  14810. }
  14811. this.morphAttributes[ name ] = array;
  14812. }
  14813. this.morphTargetsRelative = source.morphTargetsRelative;
  14814. // groups
  14815. const groups = source.groups;
  14816. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  14817. const group = groups[ i ];
  14818. this.addGroup( group.start, group.count, group.materialIndex );
  14819. }
  14820. // bounding box
  14821. const boundingBox = source.boundingBox;
  14822. if ( boundingBox !== null ) {
  14823. this.boundingBox = boundingBox.clone();
  14824. }
  14825. // bounding sphere
  14826. const boundingSphere = source.boundingSphere;
  14827. if ( boundingSphere !== null ) {
  14828. this.boundingSphere = boundingSphere.clone();
  14829. }
  14830. // draw range
  14831. this.drawRange.start = source.drawRange.start;
  14832. this.drawRange.count = source.drawRange.count;
  14833. // user data
  14834. this.userData = source.userData;
  14835. return this;
  14836. }
  14837. /**
  14838. * Frees the GPU-related resources allocated by this instance. Call this
  14839. * method whenever this instance is no longer used in your app.
  14840. *
  14841. * @fires BufferGeometry#dispose
  14842. */
  14843. dispose() {
  14844. this.dispatchEvent( { type: 'dispose' } );
  14845. }
  14846. }
  14847. const _inverseMatrix$3 = /*@__PURE__*/ new Matrix4();
  14848. const _ray$3 = /*@__PURE__*/ new Ray();
  14849. const _sphere$6 = /*@__PURE__*/ new Sphere();
  14850. const _sphereHitAt = /*@__PURE__*/ new Vector3();
  14851. const _vA$1 = /*@__PURE__*/ new Vector3();
  14852. const _vB$1 = /*@__PURE__*/ new Vector3();
  14853. const _vC$1 = /*@__PURE__*/ new Vector3();
  14854. const _tempA = /*@__PURE__*/ new Vector3();
  14855. const _morphA = /*@__PURE__*/ new Vector3();
  14856. const _intersectionPoint = /*@__PURE__*/ new Vector3();
  14857. const _intersectionPointWorld = /*@__PURE__*/ new Vector3();
  14858. /**
  14859. * Class representing triangular polygon mesh based objects.
  14860. *
  14861. * ```js
  14862. * const geometry = new THREE.BoxGeometry( 1, 1, 1 );
  14863. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  14864. * const mesh = new THREE.Mesh( geometry, material );
  14865. * scene.add( mesh );
  14866. * ```
  14867. *
  14868. * @augments Object3D
  14869. */
  14870. class Mesh extends Object3D {
  14871. /**
  14872. * Constructs a new mesh.
  14873. *
  14874. * @param {BufferGeometry} [geometry] - The mesh geometry.
  14875. * @param {Material|Array<Material>} [material] - The mesh material.
  14876. */
  14877. constructor( geometry = new BufferGeometry(), material = new MeshBasicMaterial() ) {
  14878. super();
  14879. /**
  14880. * This flag can be used for type testing.
  14881. *
  14882. * @type {boolean}
  14883. * @readonly
  14884. * @default true
  14885. */
  14886. this.isMesh = true;
  14887. this.type = 'Mesh';
  14888. /**
  14889. * The mesh geometry.
  14890. *
  14891. * @type {BufferGeometry}
  14892. */
  14893. this.geometry = geometry;
  14894. /**
  14895. * The mesh material.
  14896. *
  14897. * @type {Material|Array<Material>}
  14898. * @default MeshBasicMaterial
  14899. */
  14900. this.material = material;
  14901. /**
  14902. * A dictionary representing the morph targets in the geometry. The key is the
  14903. * morph targets name, the value its attribute index. This member is `undefined`
  14904. * by default and only set when morph targets are detected in the geometry.
  14905. *
  14906. * @type {Object<String,number>|undefined}
  14907. * @default undefined
  14908. */
  14909. this.morphTargetDictionary = undefined;
  14910. /**
  14911. * An array of weights typically in the range `[0,1]` that specify how much of the morph
  14912. * is applied. This member is `undefined` by default and only set when morph targets are
  14913. * detected in the geometry.
  14914. *
  14915. * @type {Array<number>|undefined}
  14916. * @default undefined
  14917. */
  14918. this.morphTargetInfluences = undefined;
  14919. this.updateMorphTargets();
  14920. }
  14921. copy( source, recursive ) {
  14922. super.copy( source, recursive );
  14923. if ( source.morphTargetInfluences !== undefined ) {
  14924. this.morphTargetInfluences = source.morphTargetInfluences.slice();
  14925. }
  14926. if ( source.morphTargetDictionary !== undefined ) {
  14927. this.morphTargetDictionary = Object.assign( {}, source.morphTargetDictionary );
  14928. }
  14929. this.material = Array.isArray( source.material ) ? source.material.slice() : source.material;
  14930. this.geometry = source.geometry;
  14931. return this;
  14932. }
  14933. /**
  14934. * Sets the values of {@link Mesh#morphTargetDictionary} and {@link Mesh#morphTargetInfluences}
  14935. * to make sure existing morph targets can influence this 3D object.
  14936. */
  14937. updateMorphTargets() {
  14938. const geometry = this.geometry;
  14939. const morphAttributes = geometry.morphAttributes;
  14940. const keys = Object.keys( morphAttributes );
  14941. if ( keys.length > 0 ) {
  14942. const morphAttribute = morphAttributes[ keys[ 0 ] ];
  14943. if ( morphAttribute !== undefined ) {
  14944. this.morphTargetInfluences = [];
  14945. this.morphTargetDictionary = {};
  14946. for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  14947. const name = morphAttribute[ m ].name || String( m );
  14948. this.morphTargetInfluences.push( 0 );
  14949. this.morphTargetDictionary[ name ] = m;
  14950. }
  14951. }
  14952. }
  14953. }
  14954. /**
  14955. * Returns the local-space position of the vertex at the given index, taking into
  14956. * account the current animation state of both morph targets and skinning.
  14957. *
  14958. * @param {number} index - The vertex index.
  14959. * @param {Vector3} target - The target object that is used to store the method's result.
  14960. * @return {Vector3} The vertex position in local space.
  14961. */
  14962. getVertexPosition( index, target ) {
  14963. const geometry = this.geometry;
  14964. const position = geometry.attributes.position;
  14965. const morphPosition = geometry.morphAttributes.position;
  14966. const morphTargetsRelative = geometry.morphTargetsRelative;
  14967. target.fromBufferAttribute( position, index );
  14968. const morphInfluences = this.morphTargetInfluences;
  14969. if ( morphPosition && morphInfluences ) {
  14970. _morphA.set( 0, 0, 0 );
  14971. for ( let i = 0, il = morphPosition.length; i < il; i ++ ) {
  14972. const influence = morphInfluences[ i ];
  14973. const morphAttribute = morphPosition[ i ];
  14974. if ( influence === 0 ) continue;
  14975. _tempA.fromBufferAttribute( morphAttribute, index );
  14976. if ( morphTargetsRelative ) {
  14977. _morphA.addScaledVector( _tempA, influence );
  14978. } else {
  14979. _morphA.addScaledVector( _tempA.sub( target ), influence );
  14980. }
  14981. }
  14982. target.add( _morphA );
  14983. }
  14984. return target;
  14985. }
  14986. /**
  14987. * Computes intersection points between a casted ray and this line.
  14988. *
  14989. * @param {Raycaster} raycaster - The raycaster.
  14990. * @param {Array<Object>} intersects - The target array that holds the intersection points.
  14991. */
  14992. raycast( raycaster, intersects ) {
  14993. const geometry = this.geometry;
  14994. const material = this.material;
  14995. const matrixWorld = this.matrixWorld;
  14996. if ( material === undefined ) return;
  14997. // test with bounding sphere in world space
  14998. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  14999. _sphere$6.copy( geometry.boundingSphere );
  15000. _sphere$6.applyMatrix4( matrixWorld );
  15001. // check distance from ray origin to bounding sphere
  15002. _ray$3.copy( raycaster.ray ).recast( raycaster.near );
  15003. if ( _sphere$6.containsPoint( _ray$3.origin ) === false ) {
  15004. if ( _ray$3.intersectSphere( _sphere$6, _sphereHitAt ) === null ) return;
  15005. if ( _ray$3.origin.distanceToSquared( _sphereHitAt ) > ( raycaster.far - raycaster.near ) ** 2 ) return;
  15006. }
  15007. // convert ray to local space of mesh
  15008. _inverseMatrix$3.copy( matrixWorld ).invert();
  15009. _ray$3.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$3 );
  15010. // test with bounding box in local space
  15011. if ( geometry.boundingBox !== null ) {
  15012. if ( _ray$3.intersectsBox( geometry.boundingBox ) === false ) return;
  15013. }
  15014. // test for intersections with geometry
  15015. this._computeIntersections( raycaster, intersects, _ray$3 );
  15016. }
  15017. _computeIntersections( raycaster, intersects, rayLocalSpace ) {
  15018. let intersection;
  15019. const geometry = this.geometry;
  15020. const material = this.material;
  15021. const index = geometry.index;
  15022. const position = geometry.attributes.position;
  15023. const uv = geometry.attributes.uv;
  15024. const uv1 = geometry.attributes.uv1;
  15025. const normal = geometry.attributes.normal;
  15026. const groups = geometry.groups;
  15027. const drawRange = geometry.drawRange;
  15028. if ( index !== null ) {
  15029. // indexed buffer geometry
  15030. if ( Array.isArray( material ) ) {
  15031. for ( let i = 0, il = groups.length; i < il; i ++ ) {
  15032. const group = groups[ i ];
  15033. const groupMaterial = material[ group.materialIndex ];
  15034. const start = Math.max( group.start, drawRange.start );
  15035. const end = Math.min( index.count, Math.min( ( group.start + group.count ), ( drawRange.start + drawRange.count ) ) );
  15036. for ( let j = start, jl = end; j < jl; j += 3 ) {
  15037. const a = index.getX( j );
  15038. const b = index.getX( j + 1 );
  15039. const c = index.getX( j + 2 );
  15040. intersection = checkGeometryIntersection( this, groupMaterial, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c );
  15041. if ( intersection ) {
  15042. intersection.faceIndex = Math.floor( j / 3 ); // triangle number in indexed buffer semantics
  15043. intersection.face.materialIndex = group.materialIndex;
  15044. intersects.push( intersection );
  15045. }
  15046. }
  15047. }
  15048. } else {
  15049. const start = Math.max( 0, drawRange.start );
  15050. const end = Math.min( index.count, ( drawRange.start + drawRange.count ) );
  15051. for ( let i = start, il = end; i < il; i += 3 ) {
  15052. const a = index.getX( i );
  15053. const b = index.getX( i + 1 );
  15054. const c = index.getX( i + 2 );
  15055. intersection = checkGeometryIntersection( this, material, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c );
  15056. if ( intersection ) {
  15057. intersection.faceIndex = Math.floor( i / 3 ); // triangle number in indexed buffer semantics
  15058. intersects.push( intersection );
  15059. }
  15060. }
  15061. }
  15062. } else if ( position !== undefined ) {
  15063. // non-indexed buffer geometry
  15064. if ( Array.isArray( material ) ) {
  15065. for ( let i = 0, il = groups.length; i < il; i ++ ) {
  15066. const group = groups[ i ];
  15067. const groupMaterial = material[ group.materialIndex ];
  15068. const start = Math.max( group.start, drawRange.start );
  15069. const end = Math.min( position.count, Math.min( ( group.start + group.count ), ( drawRange.start + drawRange.count ) ) );
  15070. for ( let j = start, jl = end; j < jl; j += 3 ) {
  15071. const a = j;
  15072. const b = j + 1;
  15073. const c = j + 2;
  15074. intersection = checkGeometryIntersection( this, groupMaterial, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c );
  15075. if ( intersection ) {
  15076. intersection.faceIndex = Math.floor( j / 3 ); // triangle number in non-indexed buffer semantics
  15077. intersection.face.materialIndex = group.materialIndex;
  15078. intersects.push( intersection );
  15079. }
  15080. }
  15081. }
  15082. } else {
  15083. const start = Math.max( 0, drawRange.start );
  15084. const end = Math.min( position.count, ( drawRange.start + drawRange.count ) );
  15085. for ( let i = start, il = end; i < il; i += 3 ) {
  15086. const a = i;
  15087. const b = i + 1;
  15088. const c = i + 2;
  15089. intersection = checkGeometryIntersection( this, material, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c );
  15090. if ( intersection ) {
  15091. intersection.faceIndex = Math.floor( i / 3 ); // triangle number in non-indexed buffer semantics
  15092. intersects.push( intersection );
  15093. }
  15094. }
  15095. }
  15096. }
  15097. }
  15098. }
  15099. function checkIntersection$1( object, material, raycaster, ray, pA, pB, pC, point ) {
  15100. let intersect;
  15101. if ( material.side === BackSide ) {
  15102. intersect = ray.intersectTriangle( pC, pB, pA, true, point );
  15103. } else {
  15104. intersect = ray.intersectTriangle( pA, pB, pC, ( material.side === FrontSide ), point );
  15105. }
  15106. if ( intersect === null ) return null;
  15107. _intersectionPointWorld.copy( point );
  15108. _intersectionPointWorld.applyMatrix4( object.matrixWorld );
  15109. const distance = raycaster.ray.origin.distanceTo( _intersectionPointWorld );
  15110. if ( distance < raycaster.near || distance > raycaster.far ) return null;
  15111. return {
  15112. distance: distance,
  15113. point: _intersectionPointWorld.clone(),
  15114. object: object
  15115. };
  15116. }
  15117. function checkGeometryIntersection( object, material, raycaster, ray, uv, uv1, normal, a, b, c ) {
  15118. object.getVertexPosition( a, _vA$1 );
  15119. object.getVertexPosition( b, _vB$1 );
  15120. object.getVertexPosition( c, _vC$1 );
  15121. const intersection = checkIntersection$1( object, material, raycaster, ray, _vA$1, _vB$1, _vC$1, _intersectionPoint );
  15122. if ( intersection ) {
  15123. const barycoord = new Vector3();
  15124. Triangle.getBarycoord( _intersectionPoint, _vA$1, _vB$1, _vC$1, barycoord );
  15125. if ( uv ) {
  15126. intersection.uv = Triangle.getInterpolatedAttribute( uv, a, b, c, barycoord, new Vector2() );
  15127. }
  15128. if ( uv1 ) {
  15129. intersection.uv1 = Triangle.getInterpolatedAttribute( uv1, a, b, c, barycoord, new Vector2() );
  15130. }
  15131. if ( normal ) {
  15132. intersection.normal = Triangle.getInterpolatedAttribute( normal, a, b, c, barycoord, new Vector3() );
  15133. if ( intersection.normal.dot( ray.direction ) > 0 ) {
  15134. intersection.normal.multiplyScalar( -1 );
  15135. }
  15136. }
  15137. const face = {
  15138. a: a,
  15139. b: b,
  15140. c: c,
  15141. normal: new Vector3(),
  15142. materialIndex: 0
  15143. };
  15144. Triangle.getNormal( _vA$1, _vB$1, _vC$1, face.normal );
  15145. intersection.face = face;
  15146. intersection.barycoord = barycoord;
  15147. }
  15148. return intersection;
  15149. }
  15150. /**
  15151. * A geometry class for a rectangular cuboid with a given width, height, and depth.
  15152. * On creation, the cuboid is centred on the origin, with each edge parallel to one
  15153. * of the axes.
  15154. *
  15155. * ```js
  15156. * const geometry = new THREE.BoxGeometry( 1, 1, 1 );
  15157. * const material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } );
  15158. * const cube = new THREE.Mesh( geometry, material );
  15159. * scene.add( cube );
  15160. * ```
  15161. *
  15162. * @augments BufferGeometry
  15163. */
  15164. class BoxGeometry extends BufferGeometry {
  15165. /**
  15166. * Constructs a new box geometry.
  15167. *
  15168. * @param {number} [width=1] - The width. That is, the length of the edges parallel to the X axis.
  15169. * @param {number} [height=1] - The height. That is, the length of the edges parallel to the Y axis.
  15170. * @param {number} [depth=1] - The depth. That is, the length of the edges parallel to the Z axis.
  15171. * @param {number} [widthSegments=1] - Number of segmented rectangular faces along the width of the sides.
  15172. * @param {number} [heightSegments=1] - Number of segmented rectangular faces along the height of the sides.
  15173. * @param {number} [depthSegments=1] - Number of segmented rectangular faces along the depth of the sides.
  15174. */
  15175. constructor( width = 1, height = 1, depth = 1, widthSegments = 1, heightSegments = 1, depthSegments = 1 ) {
  15176. super();
  15177. this.type = 'BoxGeometry';
  15178. /**
  15179. * Holds the constructor parameters that have been
  15180. * used to generate the geometry. Any modification
  15181. * after instantiation does not change the geometry.
  15182. *
  15183. * @type {Object}
  15184. */
  15185. this.parameters = {
  15186. width: width,
  15187. height: height,
  15188. depth: depth,
  15189. widthSegments: widthSegments,
  15190. heightSegments: heightSegments,
  15191. depthSegments: depthSegments
  15192. };
  15193. const scope = this;
  15194. // segments
  15195. widthSegments = Math.floor( widthSegments );
  15196. heightSegments = Math.floor( heightSegments );
  15197. depthSegments = Math.floor( depthSegments );
  15198. // buffers
  15199. const indices = [];
  15200. const vertices = [];
  15201. const normals = [];
  15202. const uvs = [];
  15203. // helper variables
  15204. let numberOfVertices = 0;
  15205. let groupStart = 0;
  15206. // build each side of the box geometry
  15207. buildPlane( 'z', 'y', 'x', -1, -1, depth, height, width, depthSegments, heightSegments, 0 ); // px
  15208. buildPlane( 'z', 'y', 'x', 1, -1, depth, height, - width, depthSegments, heightSegments, 1 ); // nx
  15209. buildPlane( 'x', 'z', 'y', 1, 1, width, depth, height, widthSegments, depthSegments, 2 ); // py
  15210. buildPlane( 'x', 'z', 'y', 1, -1, width, depth, - height, widthSegments, depthSegments, 3 ); // ny
  15211. buildPlane( 'x', 'y', 'z', 1, -1, width, height, depth, widthSegments, heightSegments, 4 ); // pz
  15212. buildPlane( 'x', 'y', 'z', -1, -1, width, height, - depth, widthSegments, heightSegments, 5 ); // nz
  15213. // build geometry
  15214. this.setIndex( indices );
  15215. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  15216. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  15217. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  15218. function buildPlane( u, v, w, udir, vdir, width, height, depth, gridX, gridY, materialIndex ) {
  15219. const segmentWidth = width / gridX;
  15220. const segmentHeight = height / gridY;
  15221. const widthHalf = width / 2;
  15222. const heightHalf = height / 2;
  15223. const depthHalf = depth / 2;
  15224. const gridX1 = gridX + 1;
  15225. const gridY1 = gridY + 1;
  15226. let vertexCounter = 0;
  15227. let groupCount = 0;
  15228. const vector = new Vector3();
  15229. // generate vertices, normals and uvs
  15230. for ( let iy = 0; iy < gridY1; iy ++ ) {
  15231. const y = iy * segmentHeight - heightHalf;
  15232. for ( let ix = 0; ix < gridX1; ix ++ ) {
  15233. const x = ix * segmentWidth - widthHalf;
  15234. // set values to correct vector component
  15235. vector[ u ] = x * udir;
  15236. vector[ v ] = y * vdir;
  15237. vector[ w ] = depthHalf;
  15238. // now apply vector to vertex buffer
  15239. vertices.push( vector.x, vector.y, vector.z );
  15240. // set values to correct vector component
  15241. vector[ u ] = 0;
  15242. vector[ v ] = 0;
  15243. vector[ w ] = depth > 0 ? 1 : -1;
  15244. // now apply vector to normal buffer
  15245. normals.push( vector.x, vector.y, vector.z );
  15246. // uvs
  15247. uvs.push( ix / gridX );
  15248. uvs.push( 1 - ( iy / gridY ) );
  15249. // counters
  15250. vertexCounter += 1;
  15251. }
  15252. }
  15253. // indices
  15254. // 1. you need three indices to draw a single face
  15255. // 2. a single segment consists of two faces
  15256. // 3. so we need to generate six (2*3) indices per segment
  15257. for ( let iy = 0; iy < gridY; iy ++ ) {
  15258. for ( let ix = 0; ix < gridX; ix ++ ) {
  15259. const a = numberOfVertices + ix + gridX1 * iy;
  15260. const b = numberOfVertices + ix + gridX1 * ( iy + 1 );
  15261. const c = numberOfVertices + ( ix + 1 ) + gridX1 * ( iy + 1 );
  15262. const d = numberOfVertices + ( ix + 1 ) + gridX1 * iy;
  15263. // faces
  15264. indices.push( a, b, d );
  15265. indices.push( b, c, d );
  15266. // increase counter
  15267. groupCount += 6;
  15268. }
  15269. }
  15270. // add a group to the geometry. this will ensure multi material support
  15271. scope.addGroup( groupStart, groupCount, materialIndex );
  15272. // calculate new start value for groups
  15273. groupStart += groupCount;
  15274. // update total number of vertices
  15275. numberOfVertices += vertexCounter;
  15276. }
  15277. }
  15278. copy( source ) {
  15279. super.copy( source );
  15280. this.parameters = Object.assign( {}, source.parameters );
  15281. return this;
  15282. }
  15283. /**
  15284. * Factory method for creating an instance of this class from the given
  15285. * JSON object.
  15286. *
  15287. * @param {Object} data - A JSON object representing the serialized geometry.
  15288. * @return {BoxGeometry} A new instance.
  15289. */
  15290. static fromJSON( data ) {
  15291. return new BoxGeometry( data.width, data.height, data.depth, data.widthSegments, data.heightSegments, data.depthSegments );
  15292. }
  15293. }
  15294. // Uniform Utilities
  15295. function cloneUniforms( src ) {
  15296. const dst = {};
  15297. for ( const u in src ) {
  15298. dst[ u ] = {};
  15299. for ( const p in src[ u ] ) {
  15300. const property = src[ u ][ p ];
  15301. if ( property && ( property.isColor ||
  15302. property.isMatrix3 || property.isMatrix4 ||
  15303. property.isVector2 || property.isVector3 || property.isVector4 ||
  15304. property.isTexture || property.isQuaternion ) ) {
  15305. if ( property.isRenderTargetTexture ) {
  15306. console.warn( 'UniformsUtils: Textures of render targets cannot be cloned via cloneUniforms() or mergeUniforms().' );
  15307. dst[ u ][ p ] = null;
  15308. } else {
  15309. dst[ u ][ p ] = property.clone();
  15310. }
  15311. } else if ( Array.isArray( property ) ) {
  15312. dst[ u ][ p ] = property.slice();
  15313. } else {
  15314. dst[ u ][ p ] = property;
  15315. }
  15316. }
  15317. }
  15318. return dst;
  15319. }
  15320. function mergeUniforms( uniforms ) {
  15321. const merged = {};
  15322. for ( let u = 0; u < uniforms.length; u ++ ) {
  15323. const tmp = cloneUniforms( uniforms[ u ] );
  15324. for ( const p in tmp ) {
  15325. merged[ p ] = tmp[ p ];
  15326. }
  15327. }
  15328. return merged;
  15329. }
  15330. function cloneUniformsGroups( src ) {
  15331. const dst = [];
  15332. for ( let u = 0; u < src.length; u ++ ) {
  15333. dst.push( src[ u ].clone() );
  15334. }
  15335. return dst;
  15336. }
  15337. function getUnlitUniformColorSpace( renderer ) {
  15338. const currentRenderTarget = renderer.getRenderTarget();
  15339. if ( currentRenderTarget === null ) {
  15340. // https://github.com/mrdoob/three.js/pull/23937#issuecomment-1111067398
  15341. return renderer.outputColorSpace;
  15342. }
  15343. // https://github.com/mrdoob/three.js/issues/27868
  15344. if ( currentRenderTarget.isXRRenderTarget === true ) {
  15345. return currentRenderTarget.texture.colorSpace;
  15346. }
  15347. return ColorManagement.workingColorSpace;
  15348. }
  15349. // Legacy
  15350. const UniformsUtils = { clone: cloneUniforms, merge: mergeUniforms };
  15351. var default_vertex = "void main() {\n\tgl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n}";
  15352. var default_fragment = "void main() {\n\tgl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );\n}";
  15353. /**
  15354. * A material rendered with custom shaders. A shader is a small program written in GLSL.
  15355. * that runs on the GPU. You may want to use a custom shader if you need to implement an
  15356. * effect not included with any of the built-in materials.
  15357. *
  15358. * There are the following notes to bear in mind when using a `ShaderMaterial`:
  15359. *
  15360. * - `ShaderMaterial` can only be used with {@link WebGLRenderer}.
  15361. * - Built in attributes and uniforms are passed to the shaders along with your code. If
  15362. * you don't want that, use {@link RawShaderMaterial} instead.
  15363. * - You can use the directive `#pragma unroll_loop_start` and `#pragma unroll_loop_end`
  15364. * in order to unroll a `for` loop in GLSL by the shader preprocessor. The directive has
  15365. * to be placed right above the loop. The loop formatting has to correspond to a defined standard.
  15366. * - The loop has to be [normalized]{@link https://en.wikipedia.org/wiki/Normalized_loop}.
  15367. * - The loop variable has to be *i*.
  15368. * - The value `UNROLLED_LOOP_INDEX` will be replaced with the explicitly
  15369. * value of *i* for the given iteration and can be used in preprocessor
  15370. * statements.
  15371. *
  15372. * ```js
  15373. * const material = new THREE.ShaderMaterial( {
  15374. * uniforms: {
  15375. * time: { value: 1.0 },
  15376. * resolution: { value: new THREE.Vector2() }
  15377. * },
  15378. * vertexShader: document.getElementById( 'vertexShader' ).textContent,
  15379. * fragmentShader: document.getElementById( 'fragmentShader' ).textContent
  15380. * } );
  15381. * ```
  15382. *
  15383. * @augments Material
  15384. */
  15385. class ShaderMaterial extends Material {
  15386. /**
  15387. * Constructs a new shader material.
  15388. *
  15389. * @param {Object} [parameters] - An object with one or more properties
  15390. * defining the material's appearance. Any property of the material
  15391. * (including any property from inherited materials) can be passed
  15392. * in here. Color values can be passed any type of value accepted
  15393. * by {@link Color#set}.
  15394. */
  15395. constructor( parameters ) {
  15396. super();
  15397. /**
  15398. * This flag can be used for type testing.
  15399. *
  15400. * @type {boolean}
  15401. * @readonly
  15402. * @default true
  15403. */
  15404. this.isShaderMaterial = true;
  15405. this.type = 'ShaderMaterial';
  15406. /**
  15407. * Defines custom constants using `#define` directives within the GLSL code
  15408. * for both the vertex shader and the fragment shader; each key/value pair
  15409. * yields another directive.
  15410. * ```js
  15411. * defines: {
  15412. * FOO: 15,
  15413. * BAR: true
  15414. * }
  15415. * ```
  15416. * Yields the lines:
  15417. * ```
  15418. * #define FOO 15
  15419. * #define BAR true
  15420. * ```
  15421. *
  15422. * @type {Object}
  15423. */
  15424. this.defines = {};
  15425. /**
  15426. * An object of the form:
  15427. * ```js
  15428. * {
  15429. * "uniform1": { value: 1.0 },
  15430. * "uniform2": { value: 2 }
  15431. * }
  15432. * ```
  15433. * specifying the uniforms to be passed to the shader code; keys are uniform
  15434. * names, values are definitions of the form
  15435. * ```
  15436. * {
  15437. * value: 1.0
  15438. * }
  15439. * ```
  15440. * where `value` is the value of the uniform. Names must match the name of
  15441. * the uniform, as defined in the GLSL code. Note that uniforms are refreshed
  15442. * on every frame, so updating the value of the uniform will immediately
  15443. * update the value available to the GLSL code.
  15444. *
  15445. * @type {Object}
  15446. */
  15447. this.uniforms = {};
  15448. /**
  15449. * An array holding uniforms groups for configuring UBOs.
  15450. *
  15451. * @type {Array<UniformsGroup>}
  15452. */
  15453. this.uniformsGroups = [];
  15454. /**
  15455. * Vertex shader GLSL code. This is the actual code for the shader.
  15456. *
  15457. * @type {string}
  15458. */
  15459. this.vertexShader = default_vertex;
  15460. /**
  15461. * Fragment shader GLSL code. This is the actual code for the shader.
  15462. *
  15463. * @type {string}
  15464. */
  15465. this.fragmentShader = default_fragment;
  15466. /**
  15467. * Controls line thickness or lines.
  15468. *
  15469. * WebGL and WebGPU ignore this setting and always render line primitives with a
  15470. * width of one pixel.
  15471. *
  15472. * @type {number}
  15473. * @default 1
  15474. */
  15475. this.linewidth = 1;
  15476. /**
  15477. * Renders the geometry as a wireframe.
  15478. *
  15479. * @type {boolean}
  15480. * @default false
  15481. */
  15482. this.wireframe = false;
  15483. /**
  15484. * Controls the thickness of the wireframe.
  15485. *
  15486. * WebGL and WebGPU ignore this property and always render
  15487. * 1 pixel wide lines.
  15488. *
  15489. * @type {number}
  15490. * @default 1
  15491. */
  15492. this.wireframeLinewidth = 1;
  15493. /**
  15494. * Define whether the material color is affected by global fog settings; `true`
  15495. * to pass fog uniforms to the shader.
  15496. *
  15497. * @type {boolean}
  15498. * @default false
  15499. */
  15500. this.fog = false;
  15501. /**
  15502. * Defines whether this material uses lighting; `true` to pass uniform data
  15503. * related to lighting to this shader.
  15504. *
  15505. * @type {boolean}
  15506. * @default false
  15507. */
  15508. this.lights = false;
  15509. /**
  15510. * Defines whether this material supports clipping; `true` to let the renderer
  15511. * pass the clippingPlanes uniform.
  15512. *
  15513. * @type {boolean}
  15514. * @default false
  15515. */
  15516. this.clipping = false;
  15517. /**
  15518. * Overwritten and set to `true` by default.
  15519. *
  15520. * @type {boolean}
  15521. * @default true
  15522. */
  15523. this.forceSinglePass = true;
  15524. /**
  15525. * This object allows to enable certain WebGL 2 extensions.
  15526. *
  15527. * - clipCullDistance: set to `true` to use vertex shader clipping
  15528. * - multiDraw: set to `true` to use vertex shader multi_draw / enable gl_DrawID
  15529. *
  15530. * @type {{clipCullDistance:false,multiDraw:false}}
  15531. */
  15532. this.extensions = {
  15533. clipCullDistance: false, // set to use vertex shader clipping
  15534. multiDraw: false // set to use vertex shader multi_draw / enable gl_DrawID
  15535. };
  15536. /**
  15537. * When the rendered geometry doesn't include these attributes but the
  15538. * material does, these default values will be passed to the shaders. This
  15539. * avoids errors when buffer data is missing.
  15540. *
  15541. * - color: [ 1, 1, 1 ]
  15542. * - uv: [ 0, 0 ]
  15543. * - uv1: [ 0, 0 ]
  15544. *
  15545. * @type {Object}
  15546. */
  15547. this.defaultAttributeValues = {
  15548. 'color': [ 1, 1, 1 ],
  15549. 'uv': [ 0, 0 ],
  15550. 'uv1': [ 0, 0 ]
  15551. };
  15552. /**
  15553. * If set, this calls [gl.bindAttribLocation]{@link https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/bindAttribLocation}
  15554. * to bind a generic vertex index to an attribute variable.
  15555. *
  15556. * @type {string|undefined}
  15557. * @default undefined
  15558. */
  15559. this.index0AttributeName = undefined;
  15560. /**
  15561. * Can be used to force a uniform update while changing uniforms in
  15562. * {@link Object3D#onBeforeRender}.
  15563. *
  15564. * @type {boolean}
  15565. * @default false
  15566. */
  15567. this.uniformsNeedUpdate = false;
  15568. /**
  15569. * Defines the GLSL version of custom shader code.
  15570. *
  15571. * @type {?(GLSL1|GLSL3)}
  15572. * @default null
  15573. */
  15574. this.glslVersion = null;
  15575. if ( parameters !== undefined ) {
  15576. this.setValues( parameters );
  15577. }
  15578. }
  15579. copy( source ) {
  15580. super.copy( source );
  15581. this.fragmentShader = source.fragmentShader;
  15582. this.vertexShader = source.vertexShader;
  15583. this.uniforms = cloneUniforms( source.uniforms );
  15584. this.uniformsGroups = cloneUniformsGroups( source.uniformsGroups );
  15585. this.defines = Object.assign( {}, source.defines );
  15586. this.wireframe = source.wireframe;
  15587. this.wireframeLinewidth = source.wireframeLinewidth;
  15588. this.fog = source.fog;
  15589. this.lights = source.lights;
  15590. this.clipping = source.clipping;
  15591. this.extensions = Object.assign( {}, source.extensions );
  15592. this.glslVersion = source.glslVersion;
  15593. return this;
  15594. }
  15595. toJSON( meta ) {
  15596. const data = super.toJSON( meta );
  15597. data.glslVersion = this.glslVersion;
  15598. data.uniforms = {};
  15599. for ( const name in this.uniforms ) {
  15600. const uniform = this.uniforms[ name ];
  15601. const value = uniform.value;
  15602. if ( value && value.isTexture ) {
  15603. data.uniforms[ name ] = {
  15604. type: 't',
  15605. value: value.toJSON( meta ).uuid
  15606. };
  15607. } else if ( value && value.isColor ) {
  15608. data.uniforms[ name ] = {
  15609. type: 'c',
  15610. value: value.getHex()
  15611. };
  15612. } else if ( value && value.isVector2 ) {
  15613. data.uniforms[ name ] = {
  15614. type: 'v2',
  15615. value: value.toArray()
  15616. };
  15617. } else if ( value && value.isVector3 ) {
  15618. data.uniforms[ name ] = {
  15619. type: 'v3',
  15620. value: value.toArray()
  15621. };
  15622. } else if ( value && value.isVector4 ) {
  15623. data.uniforms[ name ] = {
  15624. type: 'v4',
  15625. value: value.toArray()
  15626. };
  15627. } else if ( value && value.isMatrix3 ) {
  15628. data.uniforms[ name ] = {
  15629. type: 'm3',
  15630. value: value.toArray()
  15631. };
  15632. } else if ( value && value.isMatrix4 ) {
  15633. data.uniforms[ name ] = {
  15634. type: 'm4',
  15635. value: value.toArray()
  15636. };
  15637. } else {
  15638. data.uniforms[ name ] = {
  15639. value: value
  15640. };
  15641. // note: the array variants v2v, v3v, v4v, m4v and tv are not supported so far
  15642. }
  15643. }
  15644. if ( Object.keys( this.defines ).length > 0 ) data.defines = this.defines;
  15645. data.vertexShader = this.vertexShader;
  15646. data.fragmentShader = this.fragmentShader;
  15647. data.lights = this.lights;
  15648. data.clipping = this.clipping;
  15649. const extensions = {};
  15650. for ( const key in this.extensions ) {
  15651. if ( this.extensions[ key ] === true ) extensions[ key ] = true;
  15652. }
  15653. if ( Object.keys( extensions ).length > 0 ) data.extensions = extensions;
  15654. return data;
  15655. }
  15656. }
  15657. /**
  15658. * Abstract base class for cameras. This class should always be inherited
  15659. * when you build a new camera.
  15660. *
  15661. * @abstract
  15662. * @augments Object3D
  15663. */
  15664. class Camera extends Object3D {
  15665. /**
  15666. * Constructs a new camera.
  15667. */
  15668. constructor() {
  15669. super();
  15670. /**
  15671. * This flag can be used for type testing.
  15672. *
  15673. * @type {boolean}
  15674. * @readonly
  15675. * @default true
  15676. */
  15677. this.isCamera = true;
  15678. this.type = 'Camera';
  15679. /**
  15680. * The inverse of the camera's world matrix.
  15681. *
  15682. * @type {Matrix4}
  15683. */
  15684. this.matrixWorldInverse = new Matrix4();
  15685. /**
  15686. * The camera's projection matrix.
  15687. *
  15688. * @type {Matrix4}
  15689. */
  15690. this.projectionMatrix = new Matrix4();
  15691. /**
  15692. * The inverse of the camera's projection matrix.
  15693. *
  15694. * @type {Matrix4}
  15695. */
  15696. this.projectionMatrixInverse = new Matrix4();
  15697. /**
  15698. * The coordinate system in which the camera is used.
  15699. *
  15700. * @type {(WebGLCoordinateSystem|WebGPUCoordinateSystem)}
  15701. */
  15702. this.coordinateSystem = WebGLCoordinateSystem;
  15703. }
  15704. copy( source, recursive ) {
  15705. super.copy( source, recursive );
  15706. this.matrixWorldInverse.copy( source.matrixWorldInverse );
  15707. this.projectionMatrix.copy( source.projectionMatrix );
  15708. this.projectionMatrixInverse.copy( source.projectionMatrixInverse );
  15709. this.coordinateSystem = source.coordinateSystem;
  15710. return this;
  15711. }
  15712. /**
  15713. * Returns a vector representing the ("look") direction of the 3D object in world space.
  15714. *
  15715. * This method is overwritten since cameras have a different forward vector compared to other
  15716. * 3D objects. A camera looks down its local, negative z-axis by default.
  15717. *
  15718. * @param {Vector3} target - The target vector the result is stored to.
  15719. * @return {Vector3} The 3D object's direction in world space.
  15720. */
  15721. getWorldDirection( target ) {
  15722. return super.getWorldDirection( target ).negate();
  15723. }
  15724. updateMatrixWorld( force ) {
  15725. super.updateMatrixWorld( force );
  15726. this.matrixWorldInverse.copy( this.matrixWorld ).invert();
  15727. }
  15728. updateWorldMatrix( updateParents, updateChildren ) {
  15729. super.updateWorldMatrix( updateParents, updateChildren );
  15730. this.matrixWorldInverse.copy( this.matrixWorld ).invert();
  15731. }
  15732. clone() {
  15733. return new this.constructor().copy( this );
  15734. }
  15735. }
  15736. const _v3$1 = /*@__PURE__*/ new Vector3();
  15737. const _minTarget = /*@__PURE__*/ new Vector2();
  15738. const _maxTarget = /*@__PURE__*/ new Vector2();
  15739. /**
  15740. * Camera that uses [perspective projection]{@link https://en.wikipedia.org/wiki/Perspective_(graphical)}.
  15741. *
  15742. * This projection mode is designed to mimic the way the human eye sees. It
  15743. * is the most common projection mode used for rendering a 3D scene.
  15744. *
  15745. * ```js
  15746. * const camera = new THREE.PerspectiveCamera( 45, width / height, 1, 1000 );
  15747. * scene.add( camera );
  15748. * ```
  15749. *
  15750. * @augments Camera
  15751. */
  15752. class PerspectiveCamera extends Camera {
  15753. /**
  15754. * Constructs a new perspective camera.
  15755. *
  15756. * @param {number} [fov=50] - The vertical field of view.
  15757. * @param {number} [aspect=1] - The aspect ratio.
  15758. * @param {number} [near=0.1] - The camera's near plane.
  15759. * @param {number} [far=2000] - The camera's far plane.
  15760. */
  15761. constructor( fov = 50, aspect = 1, near = 0.1, far = 2000 ) {
  15762. super();
  15763. /**
  15764. * This flag can be used for type testing.
  15765. *
  15766. * @type {boolean}
  15767. * @readonly
  15768. * @default true
  15769. */
  15770. this.isPerspectiveCamera = true;
  15771. this.type = 'PerspectiveCamera';
  15772. /**
  15773. * The vertical field of view, from bottom to top of view,
  15774. * in degrees.
  15775. *
  15776. * @type {number}
  15777. * @default 50
  15778. */
  15779. this.fov = fov;
  15780. /**
  15781. * The zoom factor of the camera.
  15782. *
  15783. * @type {number}
  15784. * @default 1
  15785. */
  15786. this.zoom = 1;
  15787. /**
  15788. * The camera's near plane. The valid range is greater than `0`
  15789. * and less than the current value of {@link PerspectiveCamera#far}.
  15790. *
  15791. * Note that, unlike for the {@link OrthographicCamera}, `0` is <em>not</em> a
  15792. * valid value for a perspective camera's near plane.
  15793. *
  15794. * @type {number}
  15795. * @default 0.1
  15796. */
  15797. this.near = near;
  15798. /**
  15799. * The camera's far plane. Must be greater than the
  15800. * current value of {@link PerspectiveCamera#near}.
  15801. *
  15802. * @type {number}
  15803. * @default 2000
  15804. */
  15805. this.far = far;
  15806. /**
  15807. * Object distance used for stereoscopy and depth-of-field effects. This
  15808. * parameter does not influence the projection matrix unless a
  15809. * {@link StereoCamera} is being used.
  15810. *
  15811. * @type {number}
  15812. * @default 10
  15813. */
  15814. this.focus = 10;
  15815. /**
  15816. * The aspect ratio, usually the canvas width / canvas height.
  15817. *
  15818. * @type {number}
  15819. * @default 1
  15820. */
  15821. this.aspect = aspect;
  15822. /**
  15823. * Represents the frustum window specification. This property should not be edited
  15824. * directly but via {@link PerspectiveCamera#setViewOffset} and {@link PerspectiveCamera#clearViewOffset}.
  15825. *
  15826. * @type {?Object}
  15827. * @default null
  15828. */
  15829. this.view = null;
  15830. /**
  15831. * Film size used for the larger axis. Default is `35` (millimeters). This
  15832. * parameter does not influence the projection matrix unless {@link PerspectiveCamera#filmOffset}
  15833. * is set to a nonzero value.
  15834. *
  15835. * @type {number}
  15836. * @default 35
  15837. */
  15838. this.filmGauge = 35;
  15839. /**
  15840. * Horizontal off-center offset in the same unit as {@link PerspectiveCamera#filmGauge}.
  15841. *
  15842. * @type {number}
  15843. * @default 0
  15844. */
  15845. this.filmOffset = 0;
  15846. this.updateProjectionMatrix();
  15847. }
  15848. copy( source, recursive ) {
  15849. super.copy( source, recursive );
  15850. this.fov = source.fov;
  15851. this.zoom = source.zoom;
  15852. this.near = source.near;
  15853. this.far = source.far;
  15854. this.focus = source.focus;
  15855. this.aspect = source.aspect;
  15856. this.view = source.view === null ? null : Object.assign( {}, source.view );
  15857. this.filmGauge = source.filmGauge;
  15858. this.filmOffset = source.filmOffset;
  15859. return this;
  15860. }
  15861. /**
  15862. * Sets the FOV by focal length in respect to the current {@link PerspectiveCamera#filmGauge}.
  15863. *
  15864. * The default film gauge is 35, so that the focal length can be specified for
  15865. * a 35mm (full frame) camera.
  15866. *
  15867. * @param {number} focalLength - Values for focal length and film gauge must have the same unit.
  15868. */
  15869. setFocalLength( focalLength ) {
  15870. /** see {@link http://www.bobatkins.com/photography/technical/field_of_view.html} */
  15871. const vExtentSlope = 0.5 * this.getFilmHeight() / focalLength;
  15872. this.fov = RAD2DEG * 2 * Math.atan( vExtentSlope );
  15873. this.updateProjectionMatrix();
  15874. }
  15875. /**
  15876. * Returns the focal length from the current {@link PerspectiveCamera#fov} and
  15877. * {@link PerspectiveCamera#filmGauge}.
  15878. *
  15879. * @return {number} The computed focal length.
  15880. */
  15881. getFocalLength() {
  15882. const vExtentSlope = Math.tan( DEG2RAD * 0.5 * this.fov );
  15883. return 0.5 * this.getFilmHeight() / vExtentSlope;
  15884. }
  15885. /**
  15886. * Returns the current vertical field of view angle in degrees considering {@link PerspectiveCamera#zoom}.
  15887. *
  15888. * @return {number} The effective FOV.
  15889. */
  15890. getEffectiveFOV() {
  15891. return RAD2DEG * 2 * Math.atan(
  15892. Math.tan( DEG2RAD * 0.5 * this.fov ) / this.zoom );
  15893. }
  15894. /**
  15895. * Returns the width of the image on the film. If {@link PerspectiveCamera#aspect} is greater than or
  15896. * equal to one (landscape format), the result equals {@link PerspectiveCamera#filmGauge}.
  15897. *
  15898. * @return {number} The film width.
  15899. */
  15900. getFilmWidth() {
  15901. // film not completely covered in portrait format (aspect < 1)
  15902. return this.filmGauge * Math.min( this.aspect, 1 );
  15903. }
  15904. /**
  15905. * Returns the height of the image on the film. If {@link PerspectiveCamera#aspect} is greater than or
  15906. * equal to one (landscape format), the result equals {@link PerspectiveCamera#filmGauge}.
  15907. *
  15908. * @return {number} The film width.
  15909. */
  15910. getFilmHeight() {
  15911. // film not completely covered in landscape format (aspect > 1)
  15912. return this.filmGauge / Math.max( this.aspect, 1 );
  15913. }
  15914. /**
  15915. * Computes the 2D bounds of the camera's viewable rectangle at a given distance along the viewing direction.
  15916. * Sets `minTarget` and `maxTarget` to the coordinates of the lower-left and upper-right corners of the view rectangle.
  15917. *
  15918. * @param {number} distance - The viewing distance.
  15919. * @param {Vector2} minTarget - The lower-left corner of the view rectangle is written into this vector.
  15920. * @param {Vector2} maxTarget - The upper-right corner of the view rectangle is written into this vector.
  15921. */
  15922. getViewBounds( distance, minTarget, maxTarget ) {
  15923. _v3$1.set( -1, -1, 0.5 ).applyMatrix4( this.projectionMatrixInverse );
  15924. minTarget.set( _v3$1.x, _v3$1.y ).multiplyScalar( - distance / _v3$1.z );
  15925. _v3$1.set( 1, 1, 0.5 ).applyMatrix4( this.projectionMatrixInverse );
  15926. maxTarget.set( _v3$1.x, _v3$1.y ).multiplyScalar( - distance / _v3$1.z );
  15927. }
  15928. /**
  15929. * Computes the width and height of the camera's viewable rectangle at a given distance along the viewing direction.
  15930. *
  15931. * @param {number} distance - The viewing distance.
  15932. * @param {Vector2} target - The target vector that is used to store result where x is width and y is height.
  15933. * @returns {Vector2} The view size.
  15934. */
  15935. getViewSize( distance, target ) {
  15936. this.getViewBounds( distance, _minTarget, _maxTarget );
  15937. return target.subVectors( _maxTarget, _minTarget );
  15938. }
  15939. /**
  15940. * Sets an offset in a larger frustum. This is useful for multi-window or
  15941. * multi-monitor/multi-machine setups.
  15942. *
  15943. * For example, if you have 3x2 monitors and each monitor is 1920x1080 and
  15944. * the monitors are in grid like this
  15945. *```
  15946. * +---+---+---+
  15947. * | A | B | C |
  15948. * +---+---+---+
  15949. * | D | E | F |
  15950. * +---+---+---+
  15951. *```
  15952. * then for each monitor you would call it like this:
  15953. *```js
  15954. * const w = 1920;
  15955. * const h = 1080;
  15956. * const fullWidth = w * 3;
  15957. * const fullHeight = h * 2;
  15958. *
  15959. * // --A--
  15960. * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 0, w, h );
  15961. * // --B--
  15962. * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 0, w, h );
  15963. * // --C--
  15964. * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 0, w, h );
  15965. * // --D--
  15966. * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 1, w, h );
  15967. * // --E--
  15968. * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 1, w, h );
  15969. * // --F--
  15970. * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 1, w, h );
  15971. * ```
  15972. *
  15973. * Note there is no reason monitors have to be the same size or in a grid.
  15974. *
  15975. * @param {number} fullWidth - The full width of multiview setup.
  15976. * @param {number} fullHeight - The full height of multiview setup.
  15977. * @param {number} x - The horizontal offset of the subcamera.
  15978. * @param {number} y - The vertical offset of the subcamera.
  15979. * @param {number} width - The width of subcamera.
  15980. * @param {number} height - The height of subcamera.
  15981. */
  15982. setViewOffset( fullWidth, fullHeight, x, y, width, height ) {
  15983. this.aspect = fullWidth / fullHeight;
  15984. if ( this.view === null ) {
  15985. this.view = {
  15986. enabled: true,
  15987. fullWidth: 1,
  15988. fullHeight: 1,
  15989. offsetX: 0,
  15990. offsetY: 0,
  15991. width: 1,
  15992. height: 1
  15993. };
  15994. }
  15995. this.view.enabled = true;
  15996. this.view.fullWidth = fullWidth;
  15997. this.view.fullHeight = fullHeight;
  15998. this.view.offsetX = x;
  15999. this.view.offsetY = y;
  16000. this.view.width = width;
  16001. this.view.height = height;
  16002. this.updateProjectionMatrix();
  16003. }
  16004. /**
  16005. * Removes the view offset from the projection matrix.
  16006. */
  16007. clearViewOffset() {
  16008. if ( this.view !== null ) {
  16009. this.view.enabled = false;
  16010. }
  16011. this.updateProjectionMatrix();
  16012. }
  16013. /**
  16014. * Updates the camera's projection matrix. Must be called after any change of
  16015. * camera properties.
  16016. */
  16017. updateProjectionMatrix() {
  16018. const near = this.near;
  16019. let top = near * Math.tan( DEG2RAD * 0.5 * this.fov ) / this.zoom;
  16020. let height = 2 * top;
  16021. let width = this.aspect * height;
  16022. let left = -0.5 * width;
  16023. const view = this.view;
  16024. if ( this.view !== null && this.view.enabled ) {
  16025. const fullWidth = view.fullWidth,
  16026. fullHeight = view.fullHeight;
  16027. left += view.offsetX * width / fullWidth;
  16028. top -= view.offsetY * height / fullHeight;
  16029. width *= view.width / fullWidth;
  16030. height *= view.height / fullHeight;
  16031. }
  16032. const skew = this.filmOffset;
  16033. if ( skew !== 0 ) left += near * skew / this.getFilmWidth();
  16034. this.projectionMatrix.makePerspective( left, left + width, top, top - height, near, this.far, this.coordinateSystem );
  16035. this.projectionMatrixInverse.copy( this.projectionMatrix ).invert();
  16036. }
  16037. toJSON( meta ) {
  16038. const data = super.toJSON( meta );
  16039. data.object.fov = this.fov;
  16040. data.object.zoom = this.zoom;
  16041. data.object.near = this.near;
  16042. data.object.far = this.far;
  16043. data.object.focus = this.focus;
  16044. data.object.aspect = this.aspect;
  16045. if ( this.view !== null ) data.object.view = Object.assign( {}, this.view );
  16046. data.object.filmGauge = this.filmGauge;
  16047. data.object.filmOffset = this.filmOffset;
  16048. return data;
  16049. }
  16050. }
  16051. const fov = -90; // negative fov is not an error
  16052. const aspect = 1;
  16053. /**
  16054. * A special type of camera that is positioned in 3D space to render its surroundings into a
  16055. * cube render target. The render target can then be used as an environment map for rendering
  16056. * realtime reflections in your scene.
  16057. *
  16058. * ```js
  16059. * // Create cube render target
  16060. * const cubeRenderTarget = new THREE.WebGLCubeRenderTarget( 256, { generateMipmaps: true, minFilter: THREE.LinearMipmapLinearFilter } );
  16061. *
  16062. * // Create cube camera
  16063. * const cubeCamera = new THREE.CubeCamera( 1, 100000, cubeRenderTarget );
  16064. * scene.add( cubeCamera );
  16065. *
  16066. * // Create car
  16067. * const chromeMaterial = new THREE.MeshLambertMaterial( { color: 0xffffff, envMap: cubeRenderTarget.texture } );
  16068. * const car = new THREE.Mesh( carGeometry, chromeMaterial );
  16069. * scene.add( car );
  16070. *
  16071. * // Update the render target cube
  16072. * car.visible = false;
  16073. * cubeCamera.position.copy( car.position );
  16074. * cubeCamera.update( renderer, scene );
  16075. *
  16076. * // Render the scene
  16077. * car.visible = true;
  16078. * renderer.render( scene, camera );
  16079. * ```
  16080. *
  16081. * @augments Object3D
  16082. */
  16083. class CubeCamera extends Object3D {
  16084. /**
  16085. * Constructs a new cube camera.
  16086. *
  16087. * @param {number} near - The camera's near plane.
  16088. * @param {number} far - The camera's far plane.
  16089. * @param {WebGLCubeRenderTarget} renderTarget - The cube render target.
  16090. */
  16091. constructor( near, far, renderTarget ) {
  16092. super();
  16093. this.type = 'CubeCamera';
  16094. /**
  16095. * A reference to the cube render target.
  16096. *
  16097. * @type {WebGLCubeRenderTarget}
  16098. */
  16099. this.renderTarget = renderTarget;
  16100. /**
  16101. * The current active coordinate system.
  16102. *
  16103. * @type {?(WebGLCoordinateSystem|WebGPUCoordinateSystem)}
  16104. * @default null
  16105. */
  16106. this.coordinateSystem = null;
  16107. /**
  16108. * The current active mipmap level
  16109. *
  16110. * @type {number}
  16111. * @default 0
  16112. */
  16113. this.activeMipmapLevel = 0;
  16114. const cameraPX = new PerspectiveCamera( fov, aspect, near, far );
  16115. cameraPX.layers = this.layers;
  16116. this.add( cameraPX );
  16117. const cameraNX = new PerspectiveCamera( fov, aspect, near, far );
  16118. cameraNX.layers = this.layers;
  16119. this.add( cameraNX );
  16120. const cameraPY = new PerspectiveCamera( fov, aspect, near, far );
  16121. cameraPY.layers = this.layers;
  16122. this.add( cameraPY );
  16123. const cameraNY = new PerspectiveCamera( fov, aspect, near, far );
  16124. cameraNY.layers = this.layers;
  16125. this.add( cameraNY );
  16126. const cameraPZ = new PerspectiveCamera( fov, aspect, near, far );
  16127. cameraPZ.layers = this.layers;
  16128. this.add( cameraPZ );
  16129. const cameraNZ = new PerspectiveCamera( fov, aspect, near, far );
  16130. cameraNZ.layers = this.layers;
  16131. this.add( cameraNZ );
  16132. }
  16133. /**
  16134. * Must be called when the coordinate system of the cube camera is changed.
  16135. */
  16136. updateCoordinateSystem() {
  16137. const coordinateSystem = this.coordinateSystem;
  16138. const cameras = this.children.concat();
  16139. const [ cameraPX, cameraNX, cameraPY, cameraNY, cameraPZ, cameraNZ ] = cameras;
  16140. for ( const camera of cameras ) this.remove( camera );
  16141. if ( coordinateSystem === WebGLCoordinateSystem ) {
  16142. cameraPX.up.set( 0, 1, 0 );
  16143. cameraPX.lookAt( 1, 0, 0 );
  16144. cameraNX.up.set( 0, 1, 0 );
  16145. cameraNX.lookAt( -1, 0, 0 );
  16146. cameraPY.up.set( 0, 0, -1 );
  16147. cameraPY.lookAt( 0, 1, 0 );
  16148. cameraNY.up.set( 0, 0, 1 );
  16149. cameraNY.lookAt( 0, -1, 0 );
  16150. cameraPZ.up.set( 0, 1, 0 );
  16151. cameraPZ.lookAt( 0, 0, 1 );
  16152. cameraNZ.up.set( 0, 1, 0 );
  16153. cameraNZ.lookAt( 0, 0, -1 );
  16154. } else if ( coordinateSystem === WebGPUCoordinateSystem ) {
  16155. cameraPX.up.set( 0, -1, 0 );
  16156. cameraPX.lookAt( -1, 0, 0 );
  16157. cameraNX.up.set( 0, -1, 0 );
  16158. cameraNX.lookAt( 1, 0, 0 );
  16159. cameraPY.up.set( 0, 0, 1 );
  16160. cameraPY.lookAt( 0, 1, 0 );
  16161. cameraNY.up.set( 0, 0, -1 );
  16162. cameraNY.lookAt( 0, -1, 0 );
  16163. cameraPZ.up.set( 0, -1, 0 );
  16164. cameraPZ.lookAt( 0, 0, 1 );
  16165. cameraNZ.up.set( 0, -1, 0 );
  16166. cameraNZ.lookAt( 0, 0, -1 );
  16167. } else {
  16168. throw new Error( 'THREE.CubeCamera.updateCoordinateSystem(): Invalid coordinate system: ' + coordinateSystem );
  16169. }
  16170. for ( const camera of cameras ) {
  16171. this.add( camera );
  16172. camera.updateMatrixWorld();
  16173. }
  16174. }
  16175. /**
  16176. * Calling this method will render the given scene with the given renderer
  16177. * into the cube render target of the camera.
  16178. *
  16179. * @param {(Renderer|WebGLRenderer)} renderer - The renderer.
  16180. * @param {Scene} scene - The scene to render.
  16181. */
  16182. update( renderer, scene ) {
  16183. if ( this.parent === null ) this.updateMatrixWorld();
  16184. const { renderTarget, activeMipmapLevel } = this;
  16185. if ( this.coordinateSystem !== renderer.coordinateSystem ) {
  16186. this.coordinateSystem = renderer.coordinateSystem;
  16187. this.updateCoordinateSystem();
  16188. }
  16189. const [ cameraPX, cameraNX, cameraPY, cameraNY, cameraPZ, cameraNZ ] = this.children;
  16190. const currentRenderTarget = renderer.getRenderTarget();
  16191. const currentActiveCubeFace = renderer.getActiveCubeFace();
  16192. const currentActiveMipmapLevel = renderer.getActiveMipmapLevel();
  16193. const currentXrEnabled = renderer.xr.enabled;
  16194. renderer.xr.enabled = false;
  16195. const generateMipmaps = renderTarget.texture.generateMipmaps;
  16196. renderTarget.texture.generateMipmaps = false;
  16197. renderer.setRenderTarget( renderTarget, 0, activeMipmapLevel );
  16198. renderer.render( scene, cameraPX );
  16199. renderer.setRenderTarget( renderTarget, 1, activeMipmapLevel );
  16200. renderer.render( scene, cameraNX );
  16201. renderer.setRenderTarget( renderTarget, 2, activeMipmapLevel );
  16202. renderer.render( scene, cameraPY );
  16203. renderer.setRenderTarget( renderTarget, 3, activeMipmapLevel );
  16204. renderer.render( scene, cameraNY );
  16205. renderer.setRenderTarget( renderTarget, 4, activeMipmapLevel );
  16206. renderer.render( scene, cameraPZ );
  16207. // mipmaps are generated during the last call of render()
  16208. // at this point, all sides of the cube render target are defined
  16209. renderTarget.texture.generateMipmaps = generateMipmaps;
  16210. renderer.setRenderTarget( renderTarget, 5, activeMipmapLevel );
  16211. renderer.render( scene, cameraNZ );
  16212. renderer.setRenderTarget( currentRenderTarget, currentActiveCubeFace, currentActiveMipmapLevel );
  16213. renderer.xr.enabled = currentXrEnabled;
  16214. renderTarget.texture.needsPMREMUpdate = true;
  16215. }
  16216. }
  16217. /**
  16218. * Creates a cube texture made up of six images.
  16219. *
  16220. * ```js
  16221. * const loader = new THREE.CubeTextureLoader();
  16222. * loader.setPath( 'textures/cube/pisa/' );
  16223. *
  16224. * const textureCube = loader.load( [
  16225. * 'px.png', 'nx.png', 'py.png', 'ny.png', 'pz.png', 'nz.png'
  16226. * ] );
  16227. *
  16228. * const material = new THREE.MeshBasicMaterial( { color: 0xffffff, envMap: textureCube } );
  16229. * ```
  16230. *
  16231. * @augments Texture
  16232. */
  16233. class CubeTexture extends Texture {
  16234. /**
  16235. * Constructs a new cube texture.
  16236. *
  16237. * @param {Array<Image>} [images=[]] - An array holding a image for each side of a cube.
  16238. * @param {number} [mapping=CubeReflectionMapping] - The texture mapping.
  16239. * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value.
  16240. * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value.
  16241. * @param {number} [magFilter=LinearFilter] - The mag filter value.
  16242. * @param {number} [minFilter=LinearMipmapLinearFilter] - The min filter value.
  16243. * @param {number} [format=RGBAFormat] - The texture format.
  16244. * @param {number} [type=UnsignedByteType] - The texture type.
  16245. * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value.
  16246. * @param {string} [colorSpace=NoColorSpace] - The color space value.
  16247. */
  16248. constructor( images = [], mapping = CubeReflectionMapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace ) {
  16249. super( images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace );
  16250. /**
  16251. * This flag can be used for type testing.
  16252. *
  16253. * @type {boolean}
  16254. * @readonly
  16255. * @default true
  16256. */
  16257. this.isCubeTexture = true;
  16258. /**
  16259. * If set to `true`, the texture is flipped along the vertical axis when
  16260. * uploaded to the GPU.
  16261. *
  16262. * Overwritten and set to `false` by default.
  16263. *
  16264. * @type {boolean}
  16265. * @default false
  16266. */
  16267. this.flipY = false;
  16268. }
  16269. /**
  16270. * Alias for {@link CubeTexture#image}.
  16271. *
  16272. * @type {Array<Image>}
  16273. */
  16274. get images() {
  16275. return this.image;
  16276. }
  16277. set images( value ) {
  16278. this.image = value;
  16279. }
  16280. }
  16281. /**
  16282. * A cube render target used in context of {@link WebGLRenderer}.
  16283. *
  16284. * @augments WebGLRenderTarget
  16285. */
  16286. class WebGLCubeRenderTarget extends WebGLRenderTarget {
  16287. /**
  16288. * Constructs a new cube render target.
  16289. *
  16290. * @param {number} [size=1] - The size of the render target.
  16291. * @param {RenderTarget~Options} [options] - The configuration object.
  16292. */
  16293. constructor( size = 1, options = {} ) {
  16294. super( size, size, options );
  16295. /**
  16296. * This flag can be used for type testing.
  16297. *
  16298. * @type {boolean}
  16299. * @readonly
  16300. * @default true
  16301. */
  16302. this.isWebGLCubeRenderTarget = true;
  16303. const image = { width: size, height: size, depth: 1 };
  16304. const images = [ image, image, image, image, image, image ];
  16305. /**
  16306. * Overwritten with a different texture type.
  16307. *
  16308. * @type {DataArrayTexture}
  16309. */
  16310. this.texture = new CubeTexture( images, options.mapping, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.colorSpace );
  16311. // By convention -- likely based on the RenderMan spec from the 1990's -- cube maps are specified by WebGL (and three.js)
  16312. // in a coordinate system in which positive-x is to the right when looking up the positive-z axis -- in other words,
  16313. // in a left-handed coordinate system. By continuing this convention, preexisting cube maps continued to render correctly.
  16314. // three.js uses a right-handed coordinate system. So environment maps used in three.js appear to have px and nx swapped
  16315. // and the flag isRenderTargetTexture controls this conversion. The flip is not required when using WebGLCubeRenderTarget.texture
  16316. // as a cube texture (this is detected when isRenderTargetTexture is set to true for cube textures).
  16317. this.texture.isRenderTargetTexture = true;
  16318. this.texture.generateMipmaps = options.generateMipmaps !== undefined ? options.generateMipmaps : false;
  16319. this.texture.minFilter = options.minFilter !== undefined ? options.minFilter : LinearFilter;
  16320. }
  16321. /**
  16322. * Converts the given equirectangular texture to a cube map.
  16323. *
  16324. * @param {WebGLRenderer} renderer - The renderer.
  16325. * @param {Texture} texture - The equirectangular texture.
  16326. * @return {WebGLCubeRenderTarget} A reference to this cube render target.
  16327. */
  16328. fromEquirectangularTexture( renderer, texture ) {
  16329. this.texture.type = texture.type;
  16330. this.texture.colorSpace = texture.colorSpace;
  16331. this.texture.generateMipmaps = texture.generateMipmaps;
  16332. this.texture.minFilter = texture.minFilter;
  16333. this.texture.magFilter = texture.magFilter;
  16334. const shader = {
  16335. uniforms: {
  16336. tEquirect: { value: null },
  16337. },
  16338. vertexShader: /* glsl */`
  16339. varying vec3 vWorldDirection;
  16340. vec3 transformDirection( in vec3 dir, in mat4 matrix ) {
  16341. return normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );
  16342. }
  16343. void main() {
  16344. vWorldDirection = transformDirection( position, modelMatrix );
  16345. #include <begin_vertex>
  16346. #include <project_vertex>
  16347. }
  16348. `,
  16349. fragmentShader: /* glsl */`
  16350. uniform sampler2D tEquirect;
  16351. varying vec3 vWorldDirection;
  16352. #include <common>
  16353. void main() {
  16354. vec3 direction = normalize( vWorldDirection );
  16355. vec2 sampleUV = equirectUv( direction );
  16356. gl_FragColor = texture2D( tEquirect, sampleUV );
  16357. }
  16358. `
  16359. };
  16360. const geometry = new BoxGeometry( 5, 5, 5 );
  16361. const material = new ShaderMaterial( {
  16362. name: 'CubemapFromEquirect',
  16363. uniforms: cloneUniforms( shader.uniforms ),
  16364. vertexShader: shader.vertexShader,
  16365. fragmentShader: shader.fragmentShader,
  16366. side: BackSide,
  16367. blending: NoBlending
  16368. } );
  16369. material.uniforms.tEquirect.value = texture;
  16370. const mesh = new Mesh( geometry, material );
  16371. const currentMinFilter = texture.minFilter;
  16372. // Avoid blurred poles
  16373. if ( texture.minFilter === LinearMipmapLinearFilter ) texture.minFilter = LinearFilter;
  16374. const camera = new CubeCamera( 1, 10, this );
  16375. camera.update( renderer, mesh );
  16376. texture.minFilter = currentMinFilter;
  16377. mesh.geometry.dispose();
  16378. mesh.material.dispose();
  16379. return this;
  16380. }
  16381. /**
  16382. * Clears this cube render target.
  16383. *
  16384. * @param {WebGLRenderer} renderer - The renderer.
  16385. * @param {boolean} [color=true] - Whether the color buffer should be cleared or not.
  16386. * @param {boolean} [depth=true] - Whether the depth buffer should be cleared or not.
  16387. * @param {boolean} [stencil=true] - Whether the stencil buffer should be cleared or not.
  16388. */
  16389. clear( renderer, color = true, depth = true, stencil = true ) {
  16390. const currentRenderTarget = renderer.getRenderTarget();
  16391. for ( let i = 0; i < 6; i ++ ) {
  16392. renderer.setRenderTarget( this, i );
  16393. renderer.clear( color, depth, stencil );
  16394. }
  16395. renderer.setRenderTarget( currentRenderTarget );
  16396. }
  16397. }
  16398. /**
  16399. * This is almost identical to an {@link Object3D}. Its purpose is to
  16400. * make working with groups of objects syntactically clearer.
  16401. *
  16402. * ```js
  16403. * // Create a group and add the two cubes.
  16404. * // These cubes can now be rotated / scaled etc as a group.
  16405. * const group = new THREE.Group();
  16406. *
  16407. * group.add( meshA );
  16408. * group.add( meshB );
  16409. *
  16410. * scene.add( group );
  16411. * ```
  16412. *
  16413. * @augments Object3D
  16414. */
  16415. class Group extends Object3D {
  16416. constructor() {
  16417. super();
  16418. /**
  16419. * This flag can be used for type testing.
  16420. *
  16421. * @type {boolean}
  16422. * @readonly
  16423. * @default true
  16424. */
  16425. this.isGroup = true;
  16426. this.type = 'Group';
  16427. }
  16428. }
  16429. const _moveEvent = { type: 'move' };
  16430. /**
  16431. * Class for representing a XR controller with its
  16432. * different coordinate systems.
  16433. *
  16434. * @private
  16435. */
  16436. class WebXRController {
  16437. /**
  16438. * Constructs a new XR controller.
  16439. */
  16440. constructor() {
  16441. /**
  16442. * A group representing the target ray space
  16443. * of the XR controller.
  16444. *
  16445. * @private
  16446. * @type {?Group}
  16447. * @default null
  16448. */
  16449. this._targetRay = null;
  16450. /**
  16451. * A group representing the grip space
  16452. * of the XR controller.
  16453. *
  16454. * @private
  16455. * @type {?Group}
  16456. * @default null
  16457. */
  16458. this._grip = null;
  16459. /**
  16460. * A group representing the hand space
  16461. * of the XR controller.
  16462. *
  16463. * @private
  16464. * @type {?Group}
  16465. * @default null
  16466. */
  16467. this._hand = null;
  16468. }
  16469. /**
  16470. * Returns a group representing the hand space of the XR controller.
  16471. *
  16472. * @return {Group} A group representing the hand space of the XR controller.
  16473. */
  16474. getHandSpace() {
  16475. if ( this._hand === null ) {
  16476. this._hand = new Group();
  16477. this._hand.matrixAutoUpdate = false;
  16478. this._hand.visible = false;
  16479. this._hand.joints = {};
  16480. this._hand.inputState = { pinching: false };
  16481. }
  16482. return this._hand;
  16483. }
  16484. /**
  16485. * Returns a group representing the target ray space of the XR controller.
  16486. *
  16487. * @return {Group} A group representing the target ray space of the XR controller.
  16488. */
  16489. getTargetRaySpace() {
  16490. if ( this._targetRay === null ) {
  16491. this._targetRay = new Group();
  16492. this._targetRay.matrixAutoUpdate = false;
  16493. this._targetRay.visible = false;
  16494. this._targetRay.hasLinearVelocity = false;
  16495. this._targetRay.linearVelocity = new Vector3();
  16496. this._targetRay.hasAngularVelocity = false;
  16497. this._targetRay.angularVelocity = new Vector3();
  16498. }
  16499. return this._targetRay;
  16500. }
  16501. /**
  16502. * Returns a group representing the grip space of the XR controller.
  16503. *
  16504. * @return {Group} A group representing the grip space of the XR controller.
  16505. */
  16506. getGripSpace() {
  16507. if ( this._grip === null ) {
  16508. this._grip = new Group();
  16509. this._grip.matrixAutoUpdate = false;
  16510. this._grip.visible = false;
  16511. this._grip.hasLinearVelocity = false;
  16512. this._grip.linearVelocity = new Vector3();
  16513. this._grip.hasAngularVelocity = false;
  16514. this._grip.angularVelocity = new Vector3();
  16515. }
  16516. return this._grip;
  16517. }
  16518. /**
  16519. * Dispatches the given event to the groups representing
  16520. * the different coordinate spaces of the XR controller.
  16521. *
  16522. * @param {Object} event - The event to dispatch.
  16523. * @return {WebXRController} A reference to this instance.
  16524. */
  16525. dispatchEvent( event ) {
  16526. if ( this._targetRay !== null ) {
  16527. this._targetRay.dispatchEvent( event );
  16528. }
  16529. if ( this._grip !== null ) {
  16530. this._grip.dispatchEvent( event );
  16531. }
  16532. if ( this._hand !== null ) {
  16533. this._hand.dispatchEvent( event );
  16534. }
  16535. return this;
  16536. }
  16537. /**
  16538. * Connects the controller with the given XR input source.
  16539. *
  16540. * @param {XRInputSource} inputSource - The input source.
  16541. * @return {WebXRController} A reference to this instance.
  16542. */
  16543. connect( inputSource ) {
  16544. if ( inputSource && inputSource.hand ) {
  16545. const hand = this._hand;
  16546. if ( hand ) {
  16547. for ( const inputjoint of inputSource.hand.values() ) {
  16548. // Initialize hand with joints when connected
  16549. this._getHandJoint( hand, inputjoint );
  16550. }
  16551. }
  16552. }
  16553. this.dispatchEvent( { type: 'connected', data: inputSource } );
  16554. return this;
  16555. }
  16556. /**
  16557. * Disconnects the controller from the given XR input source.
  16558. *
  16559. * @param {XRInputSource} inputSource - The input source.
  16560. * @return {WebXRController} A reference to this instance.
  16561. */
  16562. disconnect( inputSource ) {
  16563. this.dispatchEvent( { type: 'disconnected', data: inputSource } );
  16564. if ( this._targetRay !== null ) {
  16565. this._targetRay.visible = false;
  16566. }
  16567. if ( this._grip !== null ) {
  16568. this._grip.visible = false;
  16569. }
  16570. if ( this._hand !== null ) {
  16571. this._hand.visible = false;
  16572. }
  16573. return this;
  16574. }
  16575. /**
  16576. * Updates the controller with the given input source, XR frame and reference space.
  16577. * This updates the transformations of the groups that represent the different
  16578. * coordinate systems of the controller.
  16579. *
  16580. * @param {XRInputSource} inputSource - The input source.
  16581. * @param {XRFrame} frame - The XR frame.
  16582. * @param {XRReferenceSpace} referenceSpace - The reference space.
  16583. * @return {WebXRController} A reference to this instance.
  16584. */
  16585. update( inputSource, frame, referenceSpace ) {
  16586. let inputPose = null;
  16587. let gripPose = null;
  16588. let handPose = null;
  16589. const targetRay = this._targetRay;
  16590. const grip = this._grip;
  16591. const hand = this._hand;
  16592. if ( inputSource && frame.session.visibilityState !== 'visible-blurred' ) {
  16593. if ( hand && inputSource.hand ) {
  16594. handPose = true;
  16595. for ( const inputjoint of inputSource.hand.values() ) {
  16596. // Update the joints groups with the XRJoint poses
  16597. const jointPose = frame.getJointPose( inputjoint, referenceSpace );
  16598. // The transform of this joint will be updated with the joint pose on each frame
  16599. const joint = this._getHandJoint( hand, inputjoint );
  16600. if ( jointPose !== null ) {
  16601. joint.matrix.fromArray( jointPose.transform.matrix );
  16602. joint.matrix.decompose( joint.position, joint.rotation, joint.scale );
  16603. joint.matrixWorldNeedsUpdate = true;
  16604. joint.jointRadius = jointPose.radius;
  16605. }
  16606. joint.visible = jointPose !== null;
  16607. }
  16608. // Custom events
  16609. // Check pinchz
  16610. const indexTip = hand.joints[ 'index-finger-tip' ];
  16611. const thumbTip = hand.joints[ 'thumb-tip' ];
  16612. const distance = indexTip.position.distanceTo( thumbTip.position );
  16613. const distanceToPinch = 0.02;
  16614. const threshold = 0.005;
  16615. if ( hand.inputState.pinching && distance > distanceToPinch + threshold ) {
  16616. hand.inputState.pinching = false;
  16617. this.dispatchEvent( {
  16618. type: 'pinchend',
  16619. handedness: inputSource.handedness,
  16620. target: this
  16621. } );
  16622. } else if ( ! hand.inputState.pinching && distance <= distanceToPinch - threshold ) {
  16623. hand.inputState.pinching = true;
  16624. this.dispatchEvent( {
  16625. type: 'pinchstart',
  16626. handedness: inputSource.handedness,
  16627. target: this
  16628. } );
  16629. }
  16630. } else {
  16631. if ( grip !== null && inputSource.gripSpace ) {
  16632. gripPose = frame.getPose( inputSource.gripSpace, referenceSpace );
  16633. if ( gripPose !== null ) {
  16634. grip.matrix.fromArray( gripPose.transform.matrix );
  16635. grip.matrix.decompose( grip.position, grip.rotation, grip.scale );
  16636. grip.matrixWorldNeedsUpdate = true;
  16637. if ( gripPose.linearVelocity ) {
  16638. grip.hasLinearVelocity = true;
  16639. grip.linearVelocity.copy( gripPose.linearVelocity );
  16640. } else {
  16641. grip.hasLinearVelocity = false;
  16642. }
  16643. if ( gripPose.angularVelocity ) {
  16644. grip.hasAngularVelocity = true;
  16645. grip.angularVelocity.copy( gripPose.angularVelocity );
  16646. } else {
  16647. grip.hasAngularVelocity = false;
  16648. }
  16649. }
  16650. }
  16651. }
  16652. if ( targetRay !== null ) {
  16653. inputPose = frame.getPose( inputSource.targetRaySpace, referenceSpace );
  16654. // Some runtimes (namely Vive Cosmos with Vive OpenXR Runtime) have only grip space and ray space is equal to it
  16655. if ( inputPose === null && gripPose !== null ) {
  16656. inputPose = gripPose;
  16657. }
  16658. if ( inputPose !== null ) {
  16659. targetRay.matrix.fromArray( inputPose.transform.matrix );
  16660. targetRay.matrix.decompose( targetRay.position, targetRay.rotation, targetRay.scale );
  16661. targetRay.matrixWorldNeedsUpdate = true;
  16662. if ( inputPose.linearVelocity ) {
  16663. targetRay.hasLinearVelocity = true;
  16664. targetRay.linearVelocity.copy( inputPose.linearVelocity );
  16665. } else {
  16666. targetRay.hasLinearVelocity = false;
  16667. }
  16668. if ( inputPose.angularVelocity ) {
  16669. targetRay.hasAngularVelocity = true;
  16670. targetRay.angularVelocity.copy( inputPose.angularVelocity );
  16671. } else {
  16672. targetRay.hasAngularVelocity = false;
  16673. }
  16674. this.dispatchEvent( _moveEvent );
  16675. }
  16676. }
  16677. }
  16678. if ( targetRay !== null ) {
  16679. targetRay.visible = ( inputPose !== null );
  16680. }
  16681. if ( grip !== null ) {
  16682. grip.visible = ( gripPose !== null );
  16683. }
  16684. if ( hand !== null ) {
  16685. hand.visible = ( handPose !== null );
  16686. }
  16687. return this;
  16688. }
  16689. /**
  16690. * Returns a group representing the hand joint for the given input joint.
  16691. *
  16692. * @private
  16693. * @param {Group} hand - The group representing the hand space.
  16694. * @param {XRHandJoint} inputjoint - The XR frame.
  16695. * @return {Group} A group representing the hand joint for the given input joint.
  16696. */
  16697. _getHandJoint( hand, inputjoint ) {
  16698. if ( hand.joints[ inputjoint.jointName ] === undefined ) {
  16699. const joint = new Group();
  16700. joint.matrixAutoUpdate = false;
  16701. joint.visible = false;
  16702. hand.joints[ inputjoint.jointName ] = joint;
  16703. hand.add( joint );
  16704. }
  16705. return hand.joints[ inputjoint.jointName ];
  16706. }
  16707. }
  16708. /**
  16709. * This class can be used to define an exponential squared fog,
  16710. * which gives a clear view near the camera and a faster than exponentially
  16711. * densening fog farther from the camera.
  16712. *
  16713. * ```js
  16714. * const scene = new THREE.Scene();
  16715. * scene.fog = new THREE.FogExp2( 0xcccccc, 0.002 );
  16716. * ```
  16717. */
  16718. class FogExp2 {
  16719. /**
  16720. * Constructs a new fog.
  16721. *
  16722. * @param {number|Color} color - The fog's color.
  16723. * @param {number} [density=0.00025] - Defines how fast the fog will grow dense.
  16724. */
  16725. constructor( color, density = 0.00025 ) {
  16726. /**
  16727. * This flag can be used for type testing.
  16728. *
  16729. * @type {boolean}
  16730. * @readonly
  16731. * @default true
  16732. */
  16733. this.isFogExp2 = true;
  16734. /**
  16735. * The name of the fog.
  16736. *
  16737. * @type {string}
  16738. */
  16739. this.name = '';
  16740. /**
  16741. * The fog's color.
  16742. *
  16743. * @type {Color}
  16744. */
  16745. this.color = new Color( color );
  16746. /**
  16747. * Defines how fast the fog will grow dense.
  16748. *
  16749. * @type {number}
  16750. * @default 0.00025
  16751. */
  16752. this.density = density;
  16753. }
  16754. /**
  16755. * Returns a new fog with copied values from this instance.
  16756. *
  16757. * @return {FogExp2} A clone of this instance.
  16758. */
  16759. clone() {
  16760. return new FogExp2( this.color, this.density );
  16761. }
  16762. /**
  16763. * Serializes the fog into JSON.
  16764. *
  16765. * @param {?(Object|string)} meta - An optional value holding meta information about the serialization.
  16766. * @return {Object} A JSON object representing the serialized fog
  16767. */
  16768. toJSON( /* meta */ ) {
  16769. return {
  16770. type: 'FogExp2',
  16771. name: this.name,
  16772. color: this.color.getHex(),
  16773. density: this.density
  16774. };
  16775. }
  16776. }
  16777. /**
  16778. * This class can be used to define a linear fog that grows linearly denser
  16779. * with the distance.
  16780. *
  16781. * ```js
  16782. * const scene = new THREE.Scene();
  16783. * scene.fog = new THREE.Fog( 0xcccccc, 10, 15 );
  16784. * ```
  16785. */
  16786. class Fog {
  16787. /**
  16788. * Constructs a new fog.
  16789. *
  16790. * @param {number|Color} color - The fog's color.
  16791. * @param {number} [near=1] - The minimum distance to start applying fog.
  16792. * @param {number} [far=1000] - The maximum distance at which fog stops being calculated and applied.
  16793. */
  16794. constructor( color, near = 1, far = 1000 ) {
  16795. /**
  16796. * This flag can be used for type testing.
  16797. *
  16798. * @type {boolean}
  16799. * @readonly
  16800. * @default true
  16801. */
  16802. this.isFog = true;
  16803. /**
  16804. * The name of the fog.
  16805. *
  16806. * @type {string}
  16807. */
  16808. this.name = '';
  16809. /**
  16810. * The fog's color.
  16811. *
  16812. * @type {Color}
  16813. */
  16814. this.color = new Color( color );
  16815. /**
  16816. * The minimum distance to start applying fog. Objects that are less than
  16817. * `near` units from the active camera won't be affected by fog.
  16818. *
  16819. * @type {number}
  16820. * @default 1
  16821. */
  16822. this.near = near;
  16823. /**
  16824. * The maximum distance at which fog stops being calculated and applied.
  16825. * Objects that are more than `far` units away from the active camera won't
  16826. * be affected by fog.
  16827. *
  16828. * @type {number}
  16829. * @default 1000
  16830. */
  16831. this.far = far;
  16832. }
  16833. /**
  16834. * Returns a new fog with copied values from this instance.
  16835. *
  16836. * @return {Fog} A clone of this instance.
  16837. */
  16838. clone() {
  16839. return new Fog( this.color, this.near, this.far );
  16840. }
  16841. /**
  16842. * Serializes the fog into JSON.
  16843. *
  16844. * @param {?(Object|string)} meta - An optional value holding meta information about the serialization.
  16845. * @return {Object} A JSON object representing the serialized fog
  16846. */
  16847. toJSON( /* meta */ ) {
  16848. return {
  16849. type: 'Fog',
  16850. name: this.name,
  16851. color: this.color.getHex(),
  16852. near: this.near,
  16853. far: this.far
  16854. };
  16855. }
  16856. }
  16857. /**
  16858. * Scenes allow you to set up what is to be rendered and where by three.js.
  16859. * This is where you place 3D objects like meshes, lines or lights.
  16860. *
  16861. * @augments Object3D
  16862. */
  16863. class Scene extends Object3D {
  16864. /**
  16865. * Constructs a new scene.
  16866. */
  16867. constructor() {
  16868. super();
  16869. /**
  16870. * This flag can be used for type testing.
  16871. *
  16872. * @type {boolean}
  16873. * @readonly
  16874. * @default true
  16875. */
  16876. this.isScene = true;
  16877. this.type = 'Scene';
  16878. /**
  16879. * Defines the background of the scene. Valid inputs are:
  16880. *
  16881. * - A color for defining a uniform colored background.
  16882. * - A texture for defining a (flat) textured background.
  16883. * - Cube textures or equirectangular textures for defining a skybox.
  16884. *
  16885. * @type {?(Color|Texture)}
  16886. * @default null
  16887. */
  16888. this.background = null;
  16889. /**
  16890. * Sets the environment map for all physical materials in the scene. However,
  16891. * it's not possible to overwrite an existing texture assigned to the `envMap`
  16892. * material property.
  16893. *
  16894. * @type {?Texture}
  16895. * @default null
  16896. */
  16897. this.environment = null;
  16898. /**
  16899. * A fog instance defining the type of fog that affects everything
  16900. * rendered in the scene.
  16901. *
  16902. * @type {?(Fog|FogExp2)}
  16903. * @default null
  16904. */
  16905. this.fog = null;
  16906. /**
  16907. * Sets the blurriness of the background. Only influences environment maps
  16908. * assigned to {@link Scene#background}. Valid input is a float between `0`
  16909. * and `1`.
  16910. *
  16911. * @type {number}
  16912. * @default 0
  16913. */
  16914. this.backgroundBlurriness = 0;
  16915. /**
  16916. * Attenuates the color of the background. Only applies to background textures.
  16917. *
  16918. * @type {number}
  16919. * @default 1
  16920. */
  16921. this.backgroundIntensity = 1;
  16922. /**
  16923. * The rotation of the background in radians. Only influences environment maps
  16924. * assigned to {@link Scene#background}.
  16925. *
  16926. * @type {Euler}
  16927. * @default (0,0,0)
  16928. */
  16929. this.backgroundRotation = new Euler();
  16930. /**
  16931. * Attenuates the color of the environment. Only influences environment maps
  16932. * assigned to {@link Scene#environment}.
  16933. *
  16934. * @type {number}
  16935. * @default 1
  16936. */
  16937. this.environmentIntensity = 1;
  16938. /**
  16939. * The rotation of the environment map in radians. Only influences physical materials
  16940. * in the scene when {@link Scene#environment} is used.
  16941. *
  16942. * @type {Euler}
  16943. * @default (0,0,0)
  16944. */
  16945. this.environmentRotation = new Euler();
  16946. /**
  16947. * Forces everything in the scene to be rendered with the defined material.
  16948. *
  16949. * @type {?Material}
  16950. * @default null
  16951. */
  16952. this.overrideMaterial = null;
  16953. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  16954. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'observe', { detail: this } ) );
  16955. }
  16956. }
  16957. copy( source, recursive ) {
  16958. super.copy( source, recursive );
  16959. if ( source.background !== null ) this.background = source.background.clone();
  16960. if ( source.environment !== null ) this.environment = source.environment.clone();
  16961. if ( source.fog !== null ) this.fog = source.fog.clone();
  16962. this.backgroundBlurriness = source.backgroundBlurriness;
  16963. this.backgroundIntensity = source.backgroundIntensity;
  16964. this.backgroundRotation.copy( source.backgroundRotation );
  16965. this.environmentIntensity = source.environmentIntensity;
  16966. this.environmentRotation.copy( source.environmentRotation );
  16967. if ( source.overrideMaterial !== null ) this.overrideMaterial = source.overrideMaterial.clone();
  16968. this.matrixAutoUpdate = source.matrixAutoUpdate;
  16969. return this;
  16970. }
  16971. toJSON( meta ) {
  16972. const data = super.toJSON( meta );
  16973. if ( this.fog !== null ) data.object.fog = this.fog.toJSON();
  16974. if ( this.backgroundBlurriness > 0 ) data.object.backgroundBlurriness = this.backgroundBlurriness;
  16975. if ( this.backgroundIntensity !== 1 ) data.object.backgroundIntensity = this.backgroundIntensity;
  16976. data.object.backgroundRotation = this.backgroundRotation.toArray();
  16977. if ( this.environmentIntensity !== 1 ) data.object.environmentIntensity = this.environmentIntensity;
  16978. data.object.environmentRotation = this.environmentRotation.toArray();
  16979. return data;
  16980. }
  16981. }
  16982. /**
  16983. * "Interleaved" means that multiple attributes, possibly of different types,
  16984. * (e.g., position, normal, uv, color) are packed into a single array buffer.
  16985. *
  16986. * An introduction into interleaved arrays can be found here: [Interleaved array basics]{@link https://blog.tojicode.com/2011/05/interleaved-array-basics.html}
  16987. */
  16988. class InterleavedBuffer {
  16989. /**
  16990. * Constructs a new interleaved buffer.
  16991. *
  16992. * @param {TypedArray} array - A typed array with a shared buffer storing attribute data.
  16993. * @param {number} stride - The number of typed-array elements per vertex.
  16994. */
  16995. constructor( array, stride ) {
  16996. /**
  16997. * This flag can be used for type testing.
  16998. *
  16999. * @type {boolean}
  17000. * @readonly
  17001. * @default true
  17002. */
  17003. this.isInterleavedBuffer = true;
  17004. /**
  17005. * A typed array with a shared buffer storing attribute data.
  17006. *
  17007. * @type {TypedArray}
  17008. */
  17009. this.array = array;
  17010. /**
  17011. * The number of typed-array elements per vertex.
  17012. *
  17013. * @type {number}
  17014. */
  17015. this.stride = stride;
  17016. /**
  17017. * The total number of elements in the array
  17018. *
  17019. * @type {number}
  17020. * @readonly
  17021. */
  17022. this.count = array !== undefined ? array.length / stride : 0;
  17023. /**
  17024. * Defines the intended usage pattern of the data store for optimization purposes.
  17025. *
  17026. * Note: After the initial use of a buffer, its usage cannot be changed. Instead,
  17027. * instantiate a new one and set the desired usage before the next render.
  17028. *
  17029. * @type {(StaticDrawUsage|DynamicDrawUsage|StreamDrawUsage|StaticReadUsage|DynamicReadUsage|StreamReadUsage|StaticCopyUsage|DynamicCopyUsage|StreamCopyUsage)}
  17030. * @default StaticDrawUsage
  17031. */
  17032. this.usage = StaticDrawUsage;
  17033. /**
  17034. * This can be used to only update some components of stored vectors (for example, just the
  17035. * component related to color). Use the `addUpdateRange()` function to add ranges to this array.
  17036. *
  17037. * @type {Array<Object>}
  17038. */
  17039. this.updateRanges = [];
  17040. /**
  17041. * A version number, incremented every time the `needsUpdate` is set to `true`.
  17042. *
  17043. * @type {number}
  17044. */
  17045. this.version = 0;
  17046. /**
  17047. * The UUID of the interleaved buffer.
  17048. *
  17049. * @type {string}
  17050. * @readonly
  17051. */
  17052. this.uuid = generateUUID();
  17053. }
  17054. /**
  17055. * A callback function that is executed after the renderer has transferred the attribute array
  17056. * data to the GPU.
  17057. */
  17058. onUploadCallback() {}
  17059. /**
  17060. * Flag to indicate that this attribute has changed and should be re-sent to
  17061. * the GPU. Set this to `true` when you modify the value of the array.
  17062. *
  17063. * @type {number}
  17064. * @default false
  17065. * @param {boolean} value
  17066. */
  17067. set needsUpdate( value ) {
  17068. if ( value === true ) this.version ++;
  17069. }
  17070. /**
  17071. * Sets the usage of this interleaved buffer.
  17072. *
  17073. * @param {(StaticDrawUsage|DynamicDrawUsage|StreamDrawUsage|StaticReadUsage|DynamicReadUsage|StreamReadUsage|StaticCopyUsage|DynamicCopyUsage|StreamCopyUsage)} value - The usage to set.
  17074. * @return {InterleavedBuffer} A reference to this interleaved buffer.
  17075. */
  17076. setUsage( value ) {
  17077. this.usage = value;
  17078. return this;
  17079. }
  17080. /**
  17081. * Adds a range of data in the data array to be updated on the GPU.
  17082. *
  17083. * @param {number} start - Position at which to start update.
  17084. * @param {number} count - The number of components to update.
  17085. */
  17086. addUpdateRange( start, count ) {
  17087. this.updateRanges.push( { start, count } );
  17088. }
  17089. /**
  17090. * Clears the update ranges.
  17091. */
  17092. clearUpdateRanges() {
  17093. this.updateRanges.length = 0;
  17094. }
  17095. /**
  17096. * Copies the values of the given interleaved buffer to this instance.
  17097. *
  17098. * @param {InterleavedBuffer} source - The interleaved buffer to copy.
  17099. * @return {InterleavedBuffer} A reference to this instance.
  17100. */
  17101. copy( source ) {
  17102. this.array = new source.array.constructor( source.array );
  17103. this.count = source.count;
  17104. this.stride = source.stride;
  17105. this.usage = source.usage;
  17106. return this;
  17107. }
  17108. /**
  17109. * Copies a vector from the given interleaved buffer to this one. The start
  17110. * and destination position in the attribute buffers are represented by the
  17111. * given indices.
  17112. *
  17113. * @param {number} index1 - The destination index into this interleaved buffer.
  17114. * @param {InterleavedBuffer} interleavedBuffer - The interleaved buffer to copy from.
  17115. * @param {number} index2 - The source index into the given interleaved buffer.
  17116. * @return {InterleavedBuffer} A reference to this instance.
  17117. */
  17118. copyAt( index1, interleavedBuffer, index2 ) {
  17119. index1 *= this.stride;
  17120. index2 *= interleavedBuffer.stride;
  17121. for ( let i = 0, l = this.stride; i < l; i ++ ) {
  17122. this.array[ index1 + i ] = interleavedBuffer.array[ index2 + i ];
  17123. }
  17124. return this;
  17125. }
  17126. /**
  17127. * Sets the given array data in the interleaved buffer.
  17128. *
  17129. * @param {(TypedArray|Array)} value - The array data to set.
  17130. * @param {number} [offset=0] - The offset in this interleaved buffer's array.
  17131. * @return {InterleavedBuffer} A reference to this instance.
  17132. */
  17133. set( value, offset = 0 ) {
  17134. this.array.set( value, offset );
  17135. return this;
  17136. }
  17137. /**
  17138. * Returns a new interleaved buffer with copied values from this instance.
  17139. *
  17140. * @param {Object} [data] - An object with shared array buffers that allows to retain shared structures.
  17141. * @return {InterleavedBuffer} A clone of this instance.
  17142. */
  17143. clone( data ) {
  17144. if ( data.arrayBuffers === undefined ) {
  17145. data.arrayBuffers = {};
  17146. }
  17147. if ( this.array.buffer._uuid === undefined ) {
  17148. this.array.buffer._uuid = generateUUID();
  17149. }
  17150. if ( data.arrayBuffers[ this.array.buffer._uuid ] === undefined ) {
  17151. data.arrayBuffers[ this.array.buffer._uuid ] = this.array.slice( 0 ).buffer;
  17152. }
  17153. const array = new this.array.constructor( data.arrayBuffers[ this.array.buffer._uuid ] );
  17154. const ib = new this.constructor( array, this.stride );
  17155. ib.setUsage( this.usage );
  17156. return ib;
  17157. }
  17158. /**
  17159. * Sets the given callback function that is executed after the Renderer has transferred
  17160. * the array data to the GPU. Can be used to perform clean-up operations after
  17161. * the upload when data are not needed anymore on the CPU side.
  17162. *
  17163. * @param {Function} callback - The `onUpload()` callback.
  17164. * @return {InterleavedBuffer} A reference to this instance.
  17165. */
  17166. onUpload( callback ) {
  17167. this.onUploadCallback = callback;
  17168. return this;
  17169. }
  17170. /**
  17171. * Serializes the interleaved buffer into JSON.
  17172. *
  17173. * @param {Object} [data] - An optional value holding meta information about the serialization.
  17174. * @return {Object} A JSON object representing the serialized interleaved buffer.
  17175. */
  17176. toJSON( data ) {
  17177. if ( data.arrayBuffers === undefined ) {
  17178. data.arrayBuffers = {};
  17179. }
  17180. // generate UUID for array buffer if necessary
  17181. if ( this.array.buffer._uuid === undefined ) {
  17182. this.array.buffer._uuid = generateUUID();
  17183. }
  17184. if ( data.arrayBuffers[ this.array.buffer._uuid ] === undefined ) {
  17185. data.arrayBuffers[ this.array.buffer._uuid ] = Array.from( new Uint32Array( this.array.buffer ) );
  17186. }
  17187. //
  17188. return {
  17189. uuid: this.uuid,
  17190. buffer: this.array.buffer._uuid,
  17191. type: this.array.constructor.name,
  17192. stride: this.stride
  17193. };
  17194. }
  17195. }
  17196. const _vector$7 = /*@__PURE__*/ new Vector3();
  17197. /**
  17198. * An alternative version of a buffer attribute with interleaved data. Interleaved
  17199. * attributes share a common interleaved data storage ({@link InterleavedBuffer}) and refer with
  17200. * different offsets into the buffer.
  17201. */
  17202. class InterleavedBufferAttribute {
  17203. /**
  17204. * Constructs a new interleaved buffer attribute.
  17205. *
  17206. * @param {InterleavedBuffer} interleavedBuffer - The buffer holding the interleaved data.
  17207. * @param {number} itemSize - The item size.
  17208. * @param {number} offset - The attribute offset into the buffer.
  17209. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  17210. */
  17211. constructor( interleavedBuffer, itemSize, offset, normalized = false ) {
  17212. /**
  17213. * This flag can be used for type testing.
  17214. *
  17215. * @type {boolean}
  17216. * @readonly
  17217. * @default true
  17218. */
  17219. this.isInterleavedBufferAttribute = true;
  17220. /**
  17221. * The name of the buffer attribute.
  17222. *
  17223. * @type {string}
  17224. */
  17225. this.name = '';
  17226. /**
  17227. * The buffer holding the interleaved data.
  17228. *
  17229. * @type {InterleavedBuffer}
  17230. */
  17231. this.data = interleavedBuffer;
  17232. /**
  17233. * The item size, see {@link BufferAttribute#itemSize}.
  17234. *
  17235. * @type {number}
  17236. */
  17237. this.itemSize = itemSize;
  17238. /**
  17239. * The attribute offset into the buffer.
  17240. *
  17241. * @type {number}
  17242. */
  17243. this.offset = offset;
  17244. /**
  17245. * Whether the data are normalized or not, see {@link BufferAttribute#normalized}
  17246. *
  17247. * @type {InterleavedBuffer}
  17248. */
  17249. this.normalized = normalized;
  17250. }
  17251. /**
  17252. * The item count of this buffer attribute.
  17253. *
  17254. * @type {number}
  17255. * @readonly
  17256. */
  17257. get count() {
  17258. return this.data.count;
  17259. }
  17260. /**
  17261. * The array holding the interleaved buffer attribute data.
  17262. *
  17263. * @type {TypedArray}
  17264. */
  17265. get array() {
  17266. return this.data.array;
  17267. }
  17268. /**
  17269. * Flag to indicate that this attribute has changed and should be re-sent to
  17270. * the GPU. Set this to `true` when you modify the value of the array.
  17271. *
  17272. * @type {number}
  17273. * @default false
  17274. * @param {boolean} value
  17275. */
  17276. set needsUpdate( value ) {
  17277. this.data.needsUpdate = value;
  17278. }
  17279. /**
  17280. * Applies the given 4x4 matrix to the given attribute. Only works with
  17281. * item size `3`.
  17282. *
  17283. * @param {Matrix4} m - The matrix to apply.
  17284. * @return {InterleavedBufferAttribute} A reference to this instance.
  17285. */
  17286. applyMatrix4( m ) {
  17287. for ( let i = 0, l = this.data.count; i < l; i ++ ) {
  17288. _vector$7.fromBufferAttribute( this, i );
  17289. _vector$7.applyMatrix4( m );
  17290. this.setXYZ( i, _vector$7.x, _vector$7.y, _vector$7.z );
  17291. }
  17292. return this;
  17293. }
  17294. /**
  17295. * Applies the given 3x3 normal matrix to the given attribute. Only works with
  17296. * item size `3`.
  17297. *
  17298. * @param {Matrix3} m - The normal matrix to apply.
  17299. * @return {InterleavedBufferAttribute} A reference to this instance.
  17300. */
  17301. applyNormalMatrix( m ) {
  17302. for ( let i = 0, l = this.count; i < l; i ++ ) {
  17303. _vector$7.fromBufferAttribute( this, i );
  17304. _vector$7.applyNormalMatrix( m );
  17305. this.setXYZ( i, _vector$7.x, _vector$7.y, _vector$7.z );
  17306. }
  17307. return this;
  17308. }
  17309. /**
  17310. * Applies the given 4x4 matrix to the given attribute. Only works with
  17311. * item size `3` and with direction vectors.
  17312. *
  17313. * @param {Matrix4} m - The matrix to apply.
  17314. * @return {InterleavedBufferAttribute} A reference to this instance.
  17315. */
  17316. transformDirection( m ) {
  17317. for ( let i = 0, l = this.count; i < l; i ++ ) {
  17318. _vector$7.fromBufferAttribute( this, i );
  17319. _vector$7.transformDirection( m );
  17320. this.setXYZ( i, _vector$7.x, _vector$7.y, _vector$7.z );
  17321. }
  17322. return this;
  17323. }
  17324. /**
  17325. * Returns the given component of the vector at the given index.
  17326. *
  17327. * @param {number} index - The index into the buffer attribute.
  17328. * @param {number} component - The component index.
  17329. * @return {number} The returned value.
  17330. */
  17331. getComponent( index, component ) {
  17332. let value = this.array[ index * this.data.stride + this.offset + component ];
  17333. if ( this.normalized ) value = denormalize( value, this.array );
  17334. return value;
  17335. }
  17336. /**
  17337. * Sets the given value to the given component of the vector at the given index.
  17338. *
  17339. * @param {number} index - The index into the buffer attribute.
  17340. * @param {number} component - The component index.
  17341. * @param {number} value - The value to set.
  17342. * @return {InterleavedBufferAttribute} A reference to this instance.
  17343. */
  17344. setComponent( index, component, value ) {
  17345. if ( this.normalized ) value = normalize( value, this.array );
  17346. this.data.array[ index * this.data.stride + this.offset + component ] = value;
  17347. return this;
  17348. }
  17349. /**
  17350. * Sets the x component of the vector at the given index.
  17351. *
  17352. * @param {number} index - The index into the buffer attribute.
  17353. * @param {number} x - The value to set.
  17354. * @return {InterleavedBufferAttribute} A reference to this instance.
  17355. */
  17356. setX( index, x ) {
  17357. if ( this.normalized ) x = normalize( x, this.array );
  17358. this.data.array[ index * this.data.stride + this.offset ] = x;
  17359. return this;
  17360. }
  17361. /**
  17362. * Sets the y component of the vector at the given index.
  17363. *
  17364. * @param {number} index - The index into the buffer attribute.
  17365. * @param {number} y - The value to set.
  17366. * @return {InterleavedBufferAttribute} A reference to this instance.
  17367. */
  17368. setY( index, y ) {
  17369. if ( this.normalized ) y = normalize( y, this.array );
  17370. this.data.array[ index * this.data.stride + this.offset + 1 ] = y;
  17371. return this;
  17372. }
  17373. /**
  17374. * Sets the z component of the vector at the given index.
  17375. *
  17376. * @param {number} index - The index into the buffer attribute.
  17377. * @param {number} z - The value to set.
  17378. * @return {InterleavedBufferAttribute} A reference to this instance.
  17379. */
  17380. setZ( index, z ) {
  17381. if ( this.normalized ) z = normalize( z, this.array );
  17382. this.data.array[ index * this.data.stride + this.offset + 2 ] = z;
  17383. return this;
  17384. }
  17385. /**
  17386. * Sets the w component of the vector at the given index.
  17387. *
  17388. * @param {number} index - The index into the buffer attribute.
  17389. * @param {number} w - The value to set.
  17390. * @return {InterleavedBufferAttribute} A reference to this instance.
  17391. */
  17392. setW( index, w ) {
  17393. if ( this.normalized ) w = normalize( w, this.array );
  17394. this.data.array[ index * this.data.stride + this.offset + 3 ] = w;
  17395. return this;
  17396. }
  17397. /**
  17398. * Returns the x component of the vector at the given index.
  17399. *
  17400. * @param {number} index - The index into the buffer attribute.
  17401. * @return {number} The x component.
  17402. */
  17403. getX( index ) {
  17404. let x = this.data.array[ index * this.data.stride + this.offset ];
  17405. if ( this.normalized ) x = denormalize( x, this.array );
  17406. return x;
  17407. }
  17408. /**
  17409. * Returns the y component of the vector at the given index.
  17410. *
  17411. * @param {number} index - The index into the buffer attribute.
  17412. * @return {number} The y component.
  17413. */
  17414. getY( index ) {
  17415. let y = this.data.array[ index * this.data.stride + this.offset + 1 ];
  17416. if ( this.normalized ) y = denormalize( y, this.array );
  17417. return y;
  17418. }
  17419. /**
  17420. * Returns the z component of the vector at the given index.
  17421. *
  17422. * @param {number} index - The index into the buffer attribute.
  17423. * @return {number} The z component.
  17424. */
  17425. getZ( index ) {
  17426. let z = this.data.array[ index * this.data.stride + this.offset + 2 ];
  17427. if ( this.normalized ) z = denormalize( z, this.array );
  17428. return z;
  17429. }
  17430. /**
  17431. * Returns the w component of the vector at the given index.
  17432. *
  17433. * @param {number} index - The index into the buffer attribute.
  17434. * @return {number} The w component.
  17435. */
  17436. getW( index ) {
  17437. let w = this.data.array[ index * this.data.stride + this.offset + 3 ];
  17438. if ( this.normalized ) w = denormalize( w, this.array );
  17439. return w;
  17440. }
  17441. /**
  17442. * Sets the x and y component of the vector at the given index.
  17443. *
  17444. * @param {number} index - The index into the buffer attribute.
  17445. * @param {number} x - The value for the x component to set.
  17446. * @param {number} y - The value for the y component to set.
  17447. * @return {InterleavedBufferAttribute} A reference to this instance.
  17448. */
  17449. setXY( index, x, y ) {
  17450. index = index * this.data.stride + this.offset;
  17451. if ( this.normalized ) {
  17452. x = normalize( x, this.array );
  17453. y = normalize( y, this.array );
  17454. }
  17455. this.data.array[ index + 0 ] = x;
  17456. this.data.array[ index + 1 ] = y;
  17457. return this;
  17458. }
  17459. /**
  17460. * Sets the x, y and z component of the vector at the given index.
  17461. *
  17462. * @param {number} index - The index into the buffer attribute.
  17463. * @param {number} x - The value for the x component to set.
  17464. * @param {number} y - The value for the y component to set.
  17465. * @param {number} z - The value for the z component to set.
  17466. * @return {InterleavedBufferAttribute} A reference to this instance.
  17467. */
  17468. setXYZ( index, x, y, z ) {
  17469. index = index * this.data.stride + this.offset;
  17470. if ( this.normalized ) {
  17471. x = normalize( x, this.array );
  17472. y = normalize( y, this.array );
  17473. z = normalize( z, this.array );
  17474. }
  17475. this.data.array[ index + 0 ] = x;
  17476. this.data.array[ index + 1 ] = y;
  17477. this.data.array[ index + 2 ] = z;
  17478. return this;
  17479. }
  17480. /**
  17481. * Sets the x, y, z and w component of the vector at the given index.
  17482. *
  17483. * @param {number} index - The index into the buffer attribute.
  17484. * @param {number} x - The value for the x component to set.
  17485. * @param {number} y - The value for the y component to set.
  17486. * @param {number} z - The value for the z component to set.
  17487. * @param {number} w - The value for the w component to set.
  17488. * @return {InterleavedBufferAttribute} A reference to this instance.
  17489. */
  17490. setXYZW( index, x, y, z, w ) {
  17491. index = index * this.data.stride + this.offset;
  17492. if ( this.normalized ) {
  17493. x = normalize( x, this.array );
  17494. y = normalize( y, this.array );
  17495. z = normalize( z, this.array );
  17496. w = normalize( w, this.array );
  17497. }
  17498. this.data.array[ index + 0 ] = x;
  17499. this.data.array[ index + 1 ] = y;
  17500. this.data.array[ index + 2 ] = z;
  17501. this.data.array[ index + 3 ] = w;
  17502. return this;
  17503. }
  17504. /**
  17505. * Returns a new buffer attribute with copied values from this instance.
  17506. *
  17507. * If no parameter is provided, cloning an interleaved buffer attribute will de-interleave buffer data.
  17508. *
  17509. * @param {Object} [data] - An object with interleaved buffers that allows to retain the interleaved property.
  17510. * @return {BufferAttribute|InterleavedBufferAttribute} A clone of this instance.
  17511. */
  17512. clone( data ) {
  17513. if ( data === undefined ) {
  17514. console.log( 'THREE.InterleavedBufferAttribute.clone(): Cloning an interleaved buffer attribute will de-interleave buffer data.' );
  17515. const array = [];
  17516. for ( let i = 0; i < this.count; i ++ ) {
  17517. const index = i * this.data.stride + this.offset;
  17518. for ( let j = 0; j < this.itemSize; j ++ ) {
  17519. array.push( this.data.array[ index + j ] );
  17520. }
  17521. }
  17522. return new BufferAttribute( new this.array.constructor( array ), this.itemSize, this.normalized );
  17523. } else {
  17524. if ( data.interleavedBuffers === undefined ) {
  17525. data.interleavedBuffers = {};
  17526. }
  17527. if ( data.interleavedBuffers[ this.data.uuid ] === undefined ) {
  17528. data.interleavedBuffers[ this.data.uuid ] = this.data.clone( data );
  17529. }
  17530. return new InterleavedBufferAttribute( data.interleavedBuffers[ this.data.uuid ], this.itemSize, this.offset, this.normalized );
  17531. }
  17532. }
  17533. /**
  17534. * Serializes the buffer attribute into JSON.
  17535. *
  17536. * If no parameter is provided, cloning an interleaved buffer attribute will de-interleave buffer data.
  17537. *
  17538. * @param {Object} [data] - An optional value holding meta information about the serialization.
  17539. * @return {Object} A JSON object representing the serialized buffer attribute.
  17540. */
  17541. toJSON( data ) {
  17542. if ( data === undefined ) {
  17543. console.log( 'THREE.InterleavedBufferAttribute.toJSON(): Serializing an interleaved buffer attribute will de-interleave buffer data.' );
  17544. const array = [];
  17545. for ( let i = 0; i < this.count; i ++ ) {
  17546. const index = i * this.data.stride + this.offset;
  17547. for ( let j = 0; j < this.itemSize; j ++ ) {
  17548. array.push( this.data.array[ index + j ] );
  17549. }
  17550. }
  17551. // de-interleave data and save it as an ordinary buffer attribute for now
  17552. return {
  17553. itemSize: this.itemSize,
  17554. type: this.array.constructor.name,
  17555. array: array,
  17556. normalized: this.normalized
  17557. };
  17558. } else {
  17559. // save as true interleaved attribute
  17560. if ( data.interleavedBuffers === undefined ) {
  17561. data.interleavedBuffers = {};
  17562. }
  17563. if ( data.interleavedBuffers[ this.data.uuid ] === undefined ) {
  17564. data.interleavedBuffers[ this.data.uuid ] = this.data.toJSON( data );
  17565. }
  17566. return {
  17567. isInterleavedBufferAttribute: true,
  17568. itemSize: this.itemSize,
  17569. data: this.data.uuid,
  17570. offset: this.offset,
  17571. normalized: this.normalized
  17572. };
  17573. }
  17574. }
  17575. }
  17576. /**
  17577. * A material for rendering instances of {@link Sprite}.
  17578. *
  17579. * ```js
  17580. * const map = new THREE.TextureLoader().load( 'textures/sprite.png' );
  17581. * const material = new THREE.SpriteMaterial( { map: map, color: 0xffffff } );
  17582. *
  17583. * const sprite = new THREE.Sprite( material );
  17584. * sprite.scale.set(200, 200, 1)
  17585. * scene.add( sprite );
  17586. * ```
  17587. *
  17588. * @augments Material
  17589. */
  17590. class SpriteMaterial extends Material {
  17591. /**
  17592. * Constructs a new sprite material.
  17593. *
  17594. * @param {Object} [parameters] - An object with one or more properties
  17595. * defining the material's appearance. Any property of the material
  17596. * (including any property from inherited materials) can be passed
  17597. * in here. Color values can be passed any type of value accepted
  17598. * by {@link Color#set}.
  17599. */
  17600. constructor( parameters ) {
  17601. super();
  17602. /**
  17603. * This flag can be used for type testing.
  17604. *
  17605. * @type {boolean}
  17606. * @readonly
  17607. * @default true
  17608. */
  17609. this.isSpriteMaterial = true;
  17610. this.type = 'SpriteMaterial';
  17611. /**
  17612. * Color of the material.
  17613. *
  17614. * @type {Color}
  17615. * @default (1,1,1)
  17616. */
  17617. this.color = new Color( 0xffffff );
  17618. /**
  17619. * The color map. May optionally include an alpha channel, typically combined
  17620. * with {@link Material#transparent} or {@link Material#alphaTest}. The texture map
  17621. * color is modulated by the diffuse `color`.
  17622. *
  17623. * @type {?Texture}
  17624. * @default null
  17625. */
  17626. this.map = null;
  17627. /**
  17628. * The alpha map is a grayscale texture that controls the opacity across the
  17629. * surface (black: fully transparent; white: fully opaque).
  17630. *
  17631. * Only the color of the texture is used, ignoring the alpha channel if one
  17632. * exists. For RGB and RGBA textures, the renderer will use the green channel
  17633. * when sampling this texture due to the extra bit of precision provided for
  17634. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  17635. * luminance/alpha textures will also still work as expected.
  17636. *
  17637. * @type {?Texture}
  17638. * @default null
  17639. */
  17640. this.alphaMap = null;
  17641. /**
  17642. * The rotation of the sprite in radians.
  17643. *
  17644. * @type {number}
  17645. * @default 0
  17646. */
  17647. this.rotation = 0;
  17648. /**
  17649. * Specifies whether size of the sprite is attenuated by the camera depth (perspective camera only).
  17650. *
  17651. * @type {boolean}
  17652. * @default true
  17653. */
  17654. this.sizeAttenuation = true;
  17655. /**
  17656. * Overwritten since sprite materials are transparent
  17657. * by default.
  17658. *
  17659. * @type {boolean}
  17660. * @default true
  17661. */
  17662. this.transparent = true;
  17663. /**
  17664. * Whether the material is affected by fog or not.
  17665. *
  17666. * @type {boolean}
  17667. * @default true
  17668. */
  17669. this.fog = true;
  17670. this.setValues( parameters );
  17671. }
  17672. copy( source ) {
  17673. super.copy( source );
  17674. this.color.copy( source.color );
  17675. this.map = source.map;
  17676. this.alphaMap = source.alphaMap;
  17677. this.rotation = source.rotation;
  17678. this.sizeAttenuation = source.sizeAttenuation;
  17679. this.fog = source.fog;
  17680. return this;
  17681. }
  17682. }
  17683. let _geometry;
  17684. const _intersectPoint = /*@__PURE__*/ new Vector3();
  17685. const _worldScale = /*@__PURE__*/ new Vector3();
  17686. const _mvPosition = /*@__PURE__*/ new Vector3();
  17687. const _alignedPosition = /*@__PURE__*/ new Vector2();
  17688. const _rotatedPosition = /*@__PURE__*/ new Vector2();
  17689. const _viewWorldMatrix = /*@__PURE__*/ new Matrix4();
  17690. const _vA = /*@__PURE__*/ new Vector3();
  17691. const _vB = /*@__PURE__*/ new Vector3();
  17692. const _vC = /*@__PURE__*/ new Vector3();
  17693. const _uvA = /*@__PURE__*/ new Vector2();
  17694. const _uvB = /*@__PURE__*/ new Vector2();
  17695. const _uvC = /*@__PURE__*/ new Vector2();
  17696. /**
  17697. * A sprite is a plane that always faces towards the camera, generally with a
  17698. * partially transparent texture applied.
  17699. *
  17700. * Sprites do not cast shadows, setting {@link Object3D#castShadow} to `true` will
  17701. * have no effect.
  17702. *
  17703. * ```js
  17704. * const map = new THREE.TextureLoader().load( 'sprite.png' );
  17705. * const material = new THREE.SpriteMaterial( { map: map } );
  17706. *
  17707. * const sprite = new THREE.Sprite( material );
  17708. * scene.add( sprite );
  17709. * ```
  17710. *
  17711. * @augments Object3D
  17712. */
  17713. class Sprite extends Object3D {
  17714. /**
  17715. * Constructs a new sprite.
  17716. *
  17717. * @param {SpriteMaterial} [material] - The sprite material.
  17718. */
  17719. constructor( material = new SpriteMaterial() ) {
  17720. super();
  17721. /**
  17722. * This flag can be used for type testing.
  17723. *
  17724. * @type {boolean}
  17725. * @readonly
  17726. * @default true
  17727. */
  17728. this.isSprite = true;
  17729. this.type = 'Sprite';
  17730. if ( _geometry === undefined ) {
  17731. _geometry = new BufferGeometry();
  17732. const float32Array = new Float32Array( [
  17733. -0.5, -0.5, 0, 0, 0,
  17734. 0.5, -0.5, 0, 1, 0,
  17735. 0.5, 0.5, 0, 1, 1,
  17736. -0.5, 0.5, 0, 0, 1
  17737. ] );
  17738. const interleavedBuffer = new InterleavedBuffer( float32Array, 5 );
  17739. _geometry.setIndex( [ 0, 1, 2, 0, 2, 3 ] );
  17740. _geometry.setAttribute( 'position', new InterleavedBufferAttribute( interleavedBuffer, 3, 0, false ) );
  17741. _geometry.setAttribute( 'uv', new InterleavedBufferAttribute( interleavedBuffer, 2, 3, false ) );
  17742. }
  17743. /**
  17744. * The sprite geometry.
  17745. *
  17746. * @type {BufferGeometry}
  17747. */
  17748. this.geometry = _geometry;
  17749. /**
  17750. * The sprite material.
  17751. *
  17752. * @type {SpriteMaterial}
  17753. */
  17754. this.material = material;
  17755. /**
  17756. * The sprite's anchor point, and the point around which the sprite rotates.
  17757. * A value of `(0.5, 0.5)` corresponds to the midpoint of the sprite. A value
  17758. * of `(0, 0)` corresponds to the lower left corner of the sprite.
  17759. *
  17760. * @type {Vector2}
  17761. * @default (0.5,0.5)
  17762. */
  17763. this.center = new Vector2( 0.5, 0.5 );
  17764. }
  17765. /**
  17766. * Computes intersection points between a casted ray and this sprite.
  17767. *
  17768. * @param {Raycaster} raycaster - The raycaster.
  17769. * @param {Array<Object>} intersects - The target array that holds the intersection points.
  17770. */
  17771. raycast( raycaster, intersects ) {
  17772. if ( raycaster.camera === null ) {
  17773. console.error( 'THREE.Sprite: "Raycaster.camera" needs to be set in order to raycast against sprites.' );
  17774. }
  17775. _worldScale.setFromMatrixScale( this.matrixWorld );
  17776. _viewWorldMatrix.copy( raycaster.camera.matrixWorld );
  17777. this.modelViewMatrix.multiplyMatrices( raycaster.camera.matrixWorldInverse, this.matrixWorld );
  17778. _mvPosition.setFromMatrixPosition( this.modelViewMatrix );
  17779. if ( raycaster.camera.isPerspectiveCamera && this.material.sizeAttenuation === false ) {
  17780. _worldScale.multiplyScalar( - _mvPosition.z );
  17781. }
  17782. const rotation = this.material.rotation;
  17783. let sin, cos;
  17784. if ( rotation !== 0 ) {
  17785. cos = Math.cos( rotation );
  17786. sin = Math.sin( rotation );
  17787. }
  17788. const center = this.center;
  17789. transformVertex( _vA.set( -0.5, -0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  17790. transformVertex( _vB.set( 0.5, -0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  17791. transformVertex( _vC.set( 0.5, 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  17792. _uvA.set( 0, 0 );
  17793. _uvB.set( 1, 0 );
  17794. _uvC.set( 1, 1 );
  17795. // check first triangle
  17796. let intersect = raycaster.ray.intersectTriangle( _vA, _vB, _vC, false, _intersectPoint );
  17797. if ( intersect === null ) {
  17798. // check second triangle
  17799. transformVertex( _vB.set( -0.5, 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  17800. _uvB.set( 0, 1 );
  17801. intersect = raycaster.ray.intersectTriangle( _vA, _vC, _vB, false, _intersectPoint );
  17802. if ( intersect === null ) {
  17803. return;
  17804. }
  17805. }
  17806. const distance = raycaster.ray.origin.distanceTo( _intersectPoint );
  17807. if ( distance < raycaster.near || distance > raycaster.far ) return;
  17808. intersects.push( {
  17809. distance: distance,
  17810. point: _intersectPoint.clone(),
  17811. uv: Triangle.getInterpolation( _intersectPoint, _vA, _vB, _vC, _uvA, _uvB, _uvC, new Vector2() ),
  17812. face: null,
  17813. object: this
  17814. } );
  17815. }
  17816. copy( source, recursive ) {
  17817. super.copy( source, recursive );
  17818. if ( source.center !== undefined ) this.center.copy( source.center );
  17819. this.material = source.material;
  17820. return this;
  17821. }
  17822. }
  17823. function transformVertex( vertexPosition, mvPosition, center, scale, sin, cos ) {
  17824. // compute position in camera space
  17825. _alignedPosition.subVectors( vertexPosition, center ).addScalar( 0.5 ).multiply( scale );
  17826. // to check if rotation is not zero
  17827. if ( sin !== undefined ) {
  17828. _rotatedPosition.x = ( cos * _alignedPosition.x ) - ( sin * _alignedPosition.y );
  17829. _rotatedPosition.y = ( sin * _alignedPosition.x ) + ( cos * _alignedPosition.y );
  17830. } else {
  17831. _rotatedPosition.copy( _alignedPosition );
  17832. }
  17833. vertexPosition.copy( mvPosition );
  17834. vertexPosition.x += _rotatedPosition.x;
  17835. vertexPosition.y += _rotatedPosition.y;
  17836. // transform to world space
  17837. vertexPosition.applyMatrix4( _viewWorldMatrix );
  17838. }
  17839. const _v1$2 = /*@__PURE__*/ new Vector3();
  17840. const _v2$1 = /*@__PURE__*/ new Vector3();
  17841. /**
  17842. * A component for providing a basic Level of Detail (LOD) mechanism.
  17843. *
  17844. * Every LOD level is associated with an object, and rendering can be switched
  17845. * between them at the distances specified. Typically you would create, say,
  17846. * three meshes, one for far away (low detail), one for mid range (medium
  17847. * detail) and one for close up (high detail).
  17848. *
  17849. * ```js
  17850. * const lod = new THREE.LOD();
  17851. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  17852. *
  17853. * //Create spheres with 3 levels of detail and create new LOD levels for them
  17854. * for( let i = 0; i < 3; i++ ) {
  17855. *
  17856. * const geometry = new THREE.IcosahedronGeometry( 10, 3 - i );
  17857. * const mesh = new THREE.Mesh( geometry, material );
  17858. * lod.addLevel( mesh, i * 75 );
  17859. *
  17860. * }
  17861. *
  17862. * scene.add( lod );
  17863. * ```
  17864. *
  17865. * @augments Object3D
  17866. */
  17867. class LOD extends Object3D {
  17868. /**
  17869. * Constructs a new LOD.
  17870. */
  17871. constructor() {
  17872. super();
  17873. /**
  17874. * This flag can be used for type testing.
  17875. *
  17876. * @type {boolean}
  17877. * @readonly
  17878. * @default true
  17879. */
  17880. this.isLOD = true;
  17881. /**
  17882. * The current LOD index.
  17883. *
  17884. * @private
  17885. * @type {number}
  17886. * @default 0
  17887. */
  17888. this._currentLevel = 0;
  17889. this.type = 'LOD';
  17890. Object.defineProperties( this, {
  17891. /**
  17892. * This array holds the LOD levels.
  17893. *
  17894. * @name LOD#levels
  17895. * @type {Array<{object:Object3D,distance:number,hysteresis:number}>}
  17896. */
  17897. levels: {
  17898. enumerable: true,
  17899. value: []
  17900. }
  17901. } );
  17902. /**
  17903. * Whether the LOD object is updated automatically by the renderer per frame
  17904. * or not. If set to `false`, you have to call {@link LOD#update} in the
  17905. * render loop by yourself.
  17906. *
  17907. * @type {boolean}
  17908. * @default true
  17909. */
  17910. this.autoUpdate = true;
  17911. }
  17912. copy( source ) {
  17913. super.copy( source, false );
  17914. const levels = source.levels;
  17915. for ( let i = 0, l = levels.length; i < l; i ++ ) {
  17916. const level = levels[ i ];
  17917. this.addLevel( level.object.clone(), level.distance, level.hysteresis );
  17918. }
  17919. this.autoUpdate = source.autoUpdate;
  17920. return this;
  17921. }
  17922. /**
  17923. * Adds a mesh that will display at a certain distance and greater. Typically
  17924. * the further away the distance, the lower the detail on the mesh.
  17925. *
  17926. * @param {Object3D} object - The 3D object to display at this level.
  17927. * @param {number} [distance=0] - The distance at which to display this level of detail.
  17928. * @param {number} [hysteresis=0] - Threshold used to avoid flickering at LOD boundaries, as a fraction of distance.
  17929. * @return {LOD} A reference to this instance.
  17930. */
  17931. addLevel( object, distance = 0, hysteresis = 0 ) {
  17932. distance = Math.abs( distance );
  17933. const levels = this.levels;
  17934. let l;
  17935. for ( l = 0; l < levels.length; l ++ ) {
  17936. if ( distance < levels[ l ].distance ) {
  17937. break;
  17938. }
  17939. }
  17940. levels.splice( l, 0, { distance: distance, hysteresis: hysteresis, object: object } );
  17941. this.add( object );
  17942. return this;
  17943. }
  17944. /**
  17945. * Removes an existing level, based on the distance from the camera.
  17946. * Returns `true` when the level has been removed. Otherwise `false`.
  17947. *
  17948. * @param {number} distance - Distance of the level to remove.
  17949. * @return {boolean} Whether the level has been removed or not.
  17950. */
  17951. removeLevel( distance ) {
  17952. const levels = this.levels;
  17953. for ( let i = 0; i < levels.length; i ++ ) {
  17954. if ( levels[ i ].distance === distance ) {
  17955. const removedElements = levels.splice( i, 1 );
  17956. this.remove( removedElements[ 0 ].object );
  17957. return true;
  17958. }
  17959. }
  17960. return false;
  17961. }
  17962. /**
  17963. * Returns the currently active LOD level index.
  17964. *
  17965. * @return {number} The current active LOD level index.
  17966. */
  17967. getCurrentLevel() {
  17968. return this._currentLevel;
  17969. }
  17970. /**
  17971. * Returns a reference to the first 3D object that is greater than
  17972. * the given distance.
  17973. *
  17974. * @param {number} distance - The LOD distance.
  17975. * @return {Object3D|null} The found 3D object. `null` if no 3D object has been found.
  17976. */
  17977. getObjectForDistance( distance ) {
  17978. const levels = this.levels;
  17979. if ( levels.length > 0 ) {
  17980. let i, l;
  17981. for ( i = 1, l = levels.length; i < l; i ++ ) {
  17982. let levelDistance = levels[ i ].distance;
  17983. if ( levels[ i ].object.visible ) {
  17984. levelDistance -= levelDistance * levels[ i ].hysteresis;
  17985. }
  17986. if ( distance < levelDistance ) {
  17987. break;
  17988. }
  17989. }
  17990. return levels[ i - 1 ].object;
  17991. }
  17992. return null;
  17993. }
  17994. /**
  17995. * Computes intersection points between a casted ray and this LOD.
  17996. *
  17997. * @param {Raycaster} raycaster - The raycaster.
  17998. * @param {Array<Object>} intersects - The target array that holds the intersection points.
  17999. */
  18000. raycast( raycaster, intersects ) {
  18001. const levels = this.levels;
  18002. if ( levels.length > 0 ) {
  18003. _v1$2.setFromMatrixPosition( this.matrixWorld );
  18004. const distance = raycaster.ray.origin.distanceTo( _v1$2 );
  18005. this.getObjectForDistance( distance ).raycast( raycaster, intersects );
  18006. }
  18007. }
  18008. /**
  18009. * Updates the LOD by computing which LOD level should be visible according
  18010. * to the current distance of the given camera.
  18011. *
  18012. * @param {Camera} camera - The camera the scene is rendered with.
  18013. */
  18014. update( camera ) {
  18015. const levels = this.levels;
  18016. if ( levels.length > 1 ) {
  18017. _v1$2.setFromMatrixPosition( camera.matrixWorld );
  18018. _v2$1.setFromMatrixPosition( this.matrixWorld );
  18019. const distance = _v1$2.distanceTo( _v2$1 ) / camera.zoom;
  18020. levels[ 0 ].object.visible = true;
  18021. let i, l;
  18022. for ( i = 1, l = levels.length; i < l; i ++ ) {
  18023. let levelDistance = levels[ i ].distance;
  18024. if ( levels[ i ].object.visible ) {
  18025. levelDistance -= levelDistance * levels[ i ].hysteresis;
  18026. }
  18027. if ( distance >= levelDistance ) {
  18028. levels[ i - 1 ].object.visible = false;
  18029. levels[ i ].object.visible = true;
  18030. } else {
  18031. break;
  18032. }
  18033. }
  18034. this._currentLevel = i - 1;
  18035. for ( ; i < l; i ++ ) {
  18036. levels[ i ].object.visible = false;
  18037. }
  18038. }
  18039. }
  18040. toJSON( meta ) {
  18041. const data = super.toJSON( meta );
  18042. if ( this.autoUpdate === false ) data.object.autoUpdate = false;
  18043. data.object.levels = [];
  18044. const levels = this.levels;
  18045. for ( let i = 0, l = levels.length; i < l; i ++ ) {
  18046. const level = levels[ i ];
  18047. data.object.levels.push( {
  18048. object: level.object.uuid,
  18049. distance: level.distance,
  18050. hysteresis: level.hysteresis
  18051. } );
  18052. }
  18053. return data;
  18054. }
  18055. }
  18056. const _basePosition = /*@__PURE__*/ new Vector3();
  18057. const _skinIndex = /*@__PURE__*/ new Vector4();
  18058. const _skinWeight = /*@__PURE__*/ new Vector4();
  18059. const _vector3 = /*@__PURE__*/ new Vector3();
  18060. const _matrix4 = /*@__PURE__*/ new Matrix4();
  18061. const _vertex = /*@__PURE__*/ new Vector3();
  18062. const _sphere$5 = /*@__PURE__*/ new Sphere();
  18063. const _inverseMatrix$2 = /*@__PURE__*/ new Matrix4();
  18064. const _ray$2 = /*@__PURE__*/ new Ray();
  18065. /**
  18066. * A mesh that has a {@link Skeleton} that can then be used to animate the
  18067. * vertices of the geometry with skinning/skeleton animation.
  18068. *
  18069. * Next to a valid skeleton, the skinned mesh requires skin indices and weights
  18070. * as buffer attributes in its geometry. These attribute define which bones affect a single
  18071. * vertex to a certain extend.
  18072. *
  18073. * Typically skinned meshes are not created manually but loaders like {@link GLTFLoader}
  18074. * or {@link FBXLoader } import respective models.
  18075. *
  18076. * @augments Mesh
  18077. */
  18078. class SkinnedMesh extends Mesh {
  18079. /**
  18080. * Constructs a new skinned mesh.
  18081. *
  18082. * @param {BufferGeometry} [geometry] - The mesh geometry.
  18083. * @param {Material|Array<Material>} [material] - The mesh material.
  18084. */
  18085. constructor( geometry, material ) {
  18086. super( geometry, material );
  18087. /**
  18088. * This flag can be used for type testing.
  18089. *
  18090. * @type {boolean}
  18091. * @readonly
  18092. * @default true
  18093. */
  18094. this.isSkinnedMesh = true;
  18095. this.type = 'SkinnedMesh';
  18096. /**
  18097. * `AttachedBindMode` means the skinned mesh shares the same world space as the skeleton.
  18098. * This is not true when using `DetachedBindMode` which is useful when sharing a skeleton
  18099. * across multiple skinned meshes.
  18100. *
  18101. * @type {(AttachedBindMode|DetachedBindMode)}
  18102. * @default AttachedBindMode
  18103. */
  18104. this.bindMode = AttachedBindMode;
  18105. /**
  18106. * The base matrix that is used for the bound bone transforms.
  18107. *
  18108. * @type {Matrix4}
  18109. */
  18110. this.bindMatrix = new Matrix4();
  18111. /**
  18112. * The base matrix that is used for resetting the bound bone transforms.
  18113. *
  18114. * @type {Matrix4}
  18115. */
  18116. this.bindMatrixInverse = new Matrix4();
  18117. /**
  18118. * The bounding box of the skinned mesh. Can be computed via {@link SkinnedMesh#computeBoundingBox}.
  18119. *
  18120. * @type {?Box3}
  18121. * @default null
  18122. */
  18123. this.boundingBox = null;
  18124. /**
  18125. * The bounding sphere of the skinned mesh. Can be computed via {@link SkinnedMesh#computeBoundingSphere}.
  18126. *
  18127. * @type {?Sphere}
  18128. * @default null
  18129. */
  18130. this.boundingSphere = null;
  18131. }
  18132. /**
  18133. * Computes the bounding box of the skinned mesh, and updates {@link SkinnedMesh#boundingBox}.
  18134. * The bounding box is not automatically computed by the engine; this method must be called by your app.
  18135. * If the skinned mesh is animated, the bounding box should be recomputed per frame in order to reflect
  18136. * the current animation state.
  18137. */
  18138. computeBoundingBox() {
  18139. const geometry = this.geometry;
  18140. if ( this.boundingBox === null ) {
  18141. this.boundingBox = new Box3();
  18142. }
  18143. this.boundingBox.makeEmpty();
  18144. const positionAttribute = geometry.getAttribute( 'position' );
  18145. for ( let i = 0; i < positionAttribute.count; i ++ ) {
  18146. this.getVertexPosition( i, _vertex );
  18147. this.boundingBox.expandByPoint( _vertex );
  18148. }
  18149. }
  18150. /**
  18151. * Computes the bounding sphere of the skinned mesh, and updates {@link SkinnedMesh#boundingSphere}.
  18152. * The bounding sphere is automatically computed by the engine once when it is needed, e.g., for ray casting
  18153. * and view frustum culling. If the skinned mesh is animated, the bounding sphere should be recomputed
  18154. * per frame in order to reflect the current animation state.
  18155. */
  18156. computeBoundingSphere() {
  18157. const geometry = this.geometry;
  18158. if ( this.boundingSphere === null ) {
  18159. this.boundingSphere = new Sphere();
  18160. }
  18161. this.boundingSphere.makeEmpty();
  18162. const positionAttribute = geometry.getAttribute( 'position' );
  18163. for ( let i = 0; i < positionAttribute.count; i ++ ) {
  18164. this.getVertexPosition( i, _vertex );
  18165. this.boundingSphere.expandByPoint( _vertex );
  18166. }
  18167. }
  18168. copy( source, recursive ) {
  18169. super.copy( source, recursive );
  18170. this.bindMode = source.bindMode;
  18171. this.bindMatrix.copy( source.bindMatrix );
  18172. this.bindMatrixInverse.copy( source.bindMatrixInverse );
  18173. this.skeleton = source.skeleton;
  18174. if ( source.boundingBox !== null ) this.boundingBox = source.boundingBox.clone();
  18175. if ( source.boundingSphere !== null ) this.boundingSphere = source.boundingSphere.clone();
  18176. return this;
  18177. }
  18178. raycast( raycaster, intersects ) {
  18179. const material = this.material;
  18180. const matrixWorld = this.matrixWorld;
  18181. if ( material === undefined ) return;
  18182. // test with bounding sphere in world space
  18183. if ( this.boundingSphere === null ) this.computeBoundingSphere();
  18184. _sphere$5.copy( this.boundingSphere );
  18185. _sphere$5.applyMatrix4( matrixWorld );
  18186. if ( raycaster.ray.intersectsSphere( _sphere$5 ) === false ) return;
  18187. // convert ray to local space of skinned mesh
  18188. _inverseMatrix$2.copy( matrixWorld ).invert();
  18189. _ray$2.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$2 );
  18190. // test with bounding box in local space
  18191. if ( this.boundingBox !== null ) {
  18192. if ( _ray$2.intersectsBox( this.boundingBox ) === false ) return;
  18193. }
  18194. // test for intersections with geometry
  18195. this._computeIntersections( raycaster, intersects, _ray$2 );
  18196. }
  18197. getVertexPosition( index, target ) {
  18198. super.getVertexPosition( index, target );
  18199. this.applyBoneTransform( index, target );
  18200. return target;
  18201. }
  18202. /**
  18203. * Binds the given skeleton to the skinned mesh.
  18204. *
  18205. * @param {Skeleton} skeleton - The skeleton to bind.
  18206. * @param {Matrix4} [bindMatrix] - The bind matrix. If no bind matrix is provided,
  18207. * the skinned mesh's world matrix will be used instead.
  18208. */
  18209. bind( skeleton, bindMatrix ) {
  18210. this.skeleton = skeleton;
  18211. if ( bindMatrix === undefined ) {
  18212. this.updateMatrixWorld( true );
  18213. this.skeleton.calculateInverses();
  18214. bindMatrix = this.matrixWorld;
  18215. }
  18216. this.bindMatrix.copy( bindMatrix );
  18217. this.bindMatrixInverse.copy( bindMatrix ).invert();
  18218. }
  18219. /**
  18220. * This method sets the skinned mesh in the rest pose).
  18221. */
  18222. pose() {
  18223. this.skeleton.pose();
  18224. }
  18225. /**
  18226. * Normalizes the skin weights which are defined as a buffer attribute
  18227. * in the skinned mesh's geometry.
  18228. */
  18229. normalizeSkinWeights() {
  18230. const vector = new Vector4();
  18231. const skinWeight = this.geometry.attributes.skinWeight;
  18232. for ( let i = 0, l = skinWeight.count; i < l; i ++ ) {
  18233. vector.fromBufferAttribute( skinWeight, i );
  18234. const scale = 1.0 / vector.manhattanLength();
  18235. if ( scale !== Infinity ) {
  18236. vector.multiplyScalar( scale );
  18237. } else {
  18238. vector.set( 1, 0, 0, 0 ); // do something reasonable
  18239. }
  18240. skinWeight.setXYZW( i, vector.x, vector.y, vector.z, vector.w );
  18241. }
  18242. }
  18243. updateMatrixWorld( force ) {
  18244. super.updateMatrixWorld( force );
  18245. if ( this.bindMode === AttachedBindMode ) {
  18246. this.bindMatrixInverse.copy( this.matrixWorld ).invert();
  18247. } else if ( this.bindMode === DetachedBindMode ) {
  18248. this.bindMatrixInverse.copy( this.bindMatrix ).invert();
  18249. } else {
  18250. console.warn( 'THREE.SkinnedMesh: Unrecognized bindMode: ' + this.bindMode );
  18251. }
  18252. }
  18253. /**
  18254. * Applies the bone transform associated with the given index to the given
  18255. * vertex position. Returns the updated vector.
  18256. *
  18257. * @param {number} index - The vertex index.
  18258. * @param {Vector3} target - The target object that is used to store the method's result.
  18259. * the skinned mesh's world matrix will be used instead.
  18260. * @return {Vector3} The updated vertex position.
  18261. */
  18262. applyBoneTransform( index, target ) {
  18263. const skeleton = this.skeleton;
  18264. const geometry = this.geometry;
  18265. _skinIndex.fromBufferAttribute( geometry.attributes.skinIndex, index );
  18266. _skinWeight.fromBufferAttribute( geometry.attributes.skinWeight, index );
  18267. _basePosition.copy( target ).applyMatrix4( this.bindMatrix );
  18268. target.set( 0, 0, 0 );
  18269. for ( let i = 0; i < 4; i ++ ) {
  18270. const weight = _skinWeight.getComponent( i );
  18271. if ( weight !== 0 ) {
  18272. const boneIndex = _skinIndex.getComponent( i );
  18273. _matrix4.multiplyMatrices( skeleton.bones[ boneIndex ].matrixWorld, skeleton.boneInverses[ boneIndex ] );
  18274. target.addScaledVector( _vector3.copy( _basePosition ).applyMatrix4( _matrix4 ), weight );
  18275. }
  18276. }
  18277. return target.applyMatrix4( this.bindMatrixInverse );
  18278. }
  18279. }
  18280. /**
  18281. * A bone which is part of a {@link Skeleton}. The skeleton in turn is used by
  18282. * the {@link SkinnedMesh}.
  18283. *
  18284. * ```js
  18285. * const root = new THREE.Bone();
  18286. * const child = new THREE.Bone();
  18287. *
  18288. * root.add( child );
  18289. * child.position.y = 5;
  18290. * ```
  18291. *
  18292. * @augments Object3D
  18293. */
  18294. class Bone extends Object3D {
  18295. /**
  18296. * Constructs a new bone.
  18297. */
  18298. constructor() {
  18299. super();
  18300. /**
  18301. * This flag can be used for type testing.
  18302. *
  18303. * @type {boolean}
  18304. * @readonly
  18305. * @default true
  18306. */
  18307. this.isBone = true;
  18308. this.type = 'Bone';
  18309. }
  18310. }
  18311. /**
  18312. * Creates a texture directly from raw buffer data.
  18313. *
  18314. * The interpretation of the data depends on type and format: If the type is
  18315. * `UnsignedByteType`, a `Uint8Array` will be useful for addressing the
  18316. * texel data. If the format is `RGBAFormat`, data needs four values for
  18317. * one texel; Red, Green, Blue and Alpha (typically the opacity).
  18318. *
  18319. * @augments Texture
  18320. */
  18321. class DataTexture extends Texture {
  18322. /**
  18323. * Constructs a new data texture.
  18324. *
  18325. * @param {?TypedArray} [data=null] - The buffer data.
  18326. * @param {number} [width=1] - The width of the texture.
  18327. * @param {number} [height=1] - The height of the texture.
  18328. * @param {number} [format=RGBAFormat] - The texture format.
  18329. * @param {number} [type=UnsignedByteType] - The texture type.
  18330. * @param {number} [mapping=Texture.DEFAULT_MAPPING] - The texture mapping.
  18331. * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value.
  18332. * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value.
  18333. * @param {number} [magFilter=NearestFilter] - The mag filter value.
  18334. * @param {number} [minFilter=NearestFilter] - The min filter value.
  18335. * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value.
  18336. * @param {string} [colorSpace=NoColorSpace] - The color space.
  18337. */
  18338. constructor( data = null, width = 1, height = 1, format, type, mapping, wrapS, wrapT, magFilter = NearestFilter, minFilter = NearestFilter, anisotropy, colorSpace ) {
  18339. super( null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace );
  18340. /**
  18341. * This flag can be used for type testing.
  18342. *
  18343. * @type {boolean}
  18344. * @readonly
  18345. * @default true
  18346. */
  18347. this.isDataTexture = true;
  18348. /**
  18349. * The image definition of a data texture.
  18350. *
  18351. * @type {{data:TypedArray,width:number,height:number}}
  18352. */
  18353. this.image = { data: data, width: width, height: height };
  18354. /**
  18355. * Whether to generate mipmaps (if possible) for a texture.
  18356. *
  18357. * Overwritten and set to `false` by default.
  18358. *
  18359. * @type {boolean}
  18360. * @default false
  18361. */
  18362. this.generateMipmaps = false;
  18363. /**
  18364. * If set to `true`, the texture is flipped along the vertical axis when
  18365. * uploaded to the GPU.
  18366. *
  18367. * Overwritten and set to `false` by default.
  18368. *
  18369. * @type {boolean}
  18370. * @default false
  18371. */
  18372. this.flipY = false;
  18373. /**
  18374. * Specifies the alignment requirements for the start of each pixel row in memory.
  18375. *
  18376. * Overwritten and set to `1` by default.
  18377. *
  18378. * @type {boolean}
  18379. * @default 1
  18380. */
  18381. this.unpackAlignment = 1;
  18382. }
  18383. }
  18384. const _offsetMatrix = /*@__PURE__*/ new Matrix4();
  18385. const _identityMatrix = /*@__PURE__*/ new Matrix4();
  18386. /**
  18387. * Class for representing the armatures in `three.js`. The skeleton
  18388. * is defined by a hierarchy of bones.
  18389. *
  18390. * ```js
  18391. * const bones = [];
  18392. *
  18393. * const shoulder = new THREE.Bone();
  18394. * const elbow = new THREE.Bone();
  18395. * const hand = new THREE.Bone();
  18396. *
  18397. * shoulder.add( elbow );
  18398. * elbow.add( hand );
  18399. *
  18400. * bones.push( shoulder , elbow, hand);
  18401. *
  18402. * shoulder.position.y = -5;
  18403. * elbow.position.y = 0;
  18404. * hand.position.y = 5;
  18405. *
  18406. * const armSkeleton = new THREE.Skeleton( bones );
  18407. * ```
  18408. */
  18409. class Skeleton {
  18410. /**
  18411. * Constructs a new skeleton.
  18412. *
  18413. * @param {Array<Bone>} [bones] - An array of bones.
  18414. * @param {Array<Matrix4>} [boneInverses] - An array of bone inverse matrices.
  18415. * If not provided, these matrices will be computed automatically via {@link Skeleton#calculateInverses}.
  18416. */
  18417. constructor( bones = [], boneInverses = [] ) {
  18418. this.uuid = generateUUID();
  18419. /**
  18420. * An array of bones defining the skeleton.
  18421. *
  18422. * @type {Array<Bone>}
  18423. */
  18424. this.bones = bones.slice( 0 );
  18425. /**
  18426. * An array of bone inverse matrices.
  18427. *
  18428. * @type {Array<Matrix4>}
  18429. */
  18430. this.boneInverses = boneInverses;
  18431. /**
  18432. * An array buffer holding the bone data.
  18433. * Input data for {@link Skeleton#boneTexture}.
  18434. *
  18435. * @type {?Float32Array}
  18436. * @default null
  18437. */
  18438. this.boneMatrices = null;
  18439. /**
  18440. * A texture holding the bone data for use
  18441. * in the vertex shader.
  18442. *
  18443. * @type {?DataTexture}
  18444. * @default null
  18445. */
  18446. this.boneTexture = null;
  18447. this.init();
  18448. }
  18449. /**
  18450. * Initializes the skeleton. This method gets automatically called by the constructor
  18451. * but depending on how the skeleton is created it might be necessary to call this method
  18452. * manually.
  18453. */
  18454. init() {
  18455. const bones = this.bones;
  18456. const boneInverses = this.boneInverses;
  18457. this.boneMatrices = new Float32Array( bones.length * 16 );
  18458. // calculate inverse bone matrices if necessary
  18459. if ( boneInverses.length === 0 ) {
  18460. this.calculateInverses();
  18461. } else {
  18462. // handle special case
  18463. if ( bones.length !== boneInverses.length ) {
  18464. console.warn( 'THREE.Skeleton: Number of inverse bone matrices does not match amount of bones.' );
  18465. this.boneInverses = [];
  18466. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  18467. this.boneInverses.push( new Matrix4() );
  18468. }
  18469. }
  18470. }
  18471. }
  18472. /**
  18473. * Computes the bone inverse matrices. This method resets {@link Skeleton#boneInverses}
  18474. * and fills it with new matrices.
  18475. */
  18476. calculateInverses() {
  18477. this.boneInverses.length = 0;
  18478. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  18479. const inverse = new Matrix4();
  18480. if ( this.bones[ i ] ) {
  18481. inverse.copy( this.bones[ i ].matrixWorld ).invert();
  18482. }
  18483. this.boneInverses.push( inverse );
  18484. }
  18485. }
  18486. /**
  18487. * Resets the skeleton to the base pose.
  18488. */
  18489. pose() {
  18490. // recover the bind-time world matrices
  18491. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  18492. const bone = this.bones[ i ];
  18493. if ( bone ) {
  18494. bone.matrixWorld.copy( this.boneInverses[ i ] ).invert();
  18495. }
  18496. }
  18497. // compute the local matrices, positions, rotations and scales
  18498. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  18499. const bone = this.bones[ i ];
  18500. if ( bone ) {
  18501. if ( bone.parent && bone.parent.isBone ) {
  18502. bone.matrix.copy( bone.parent.matrixWorld ).invert();
  18503. bone.matrix.multiply( bone.matrixWorld );
  18504. } else {
  18505. bone.matrix.copy( bone.matrixWorld );
  18506. }
  18507. bone.matrix.decompose( bone.position, bone.quaternion, bone.scale );
  18508. }
  18509. }
  18510. }
  18511. /**
  18512. * Resets the skeleton to the base pose.
  18513. */
  18514. update() {
  18515. const bones = this.bones;
  18516. const boneInverses = this.boneInverses;
  18517. const boneMatrices = this.boneMatrices;
  18518. const boneTexture = this.boneTexture;
  18519. // flatten bone matrices to array
  18520. for ( let i = 0, il = bones.length; i < il; i ++ ) {
  18521. // compute the offset between the current and the original transform
  18522. const matrix = bones[ i ] ? bones[ i ].matrixWorld : _identityMatrix;
  18523. _offsetMatrix.multiplyMatrices( matrix, boneInverses[ i ] );
  18524. _offsetMatrix.toArray( boneMatrices, i * 16 );
  18525. }
  18526. if ( boneTexture !== null ) {
  18527. boneTexture.needsUpdate = true;
  18528. }
  18529. }
  18530. /**
  18531. * Returns a new skeleton with copied values from this instance.
  18532. *
  18533. * @return {Skeleton} A clone of this instance.
  18534. */
  18535. clone() {
  18536. return new Skeleton( this.bones, this.boneInverses );
  18537. }
  18538. /**
  18539. * Computes a data texture for passing bone data to the vertex shader.
  18540. *
  18541. * @return {Skeleton} A reference of this instance.
  18542. */
  18543. computeBoneTexture() {
  18544. // layout (1 matrix = 4 pixels)
  18545. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  18546. // with 8x8 pixel texture max 16 bones * 4 pixels = (8 * 8)
  18547. // 16x16 pixel texture max 64 bones * 4 pixels = (16 * 16)
  18548. // 32x32 pixel texture max 256 bones * 4 pixels = (32 * 32)
  18549. // 64x64 pixel texture max 1024 bones * 4 pixels = (64 * 64)
  18550. let size = Math.sqrt( this.bones.length * 4 ); // 4 pixels needed for 1 matrix
  18551. size = Math.ceil( size / 4 ) * 4;
  18552. size = Math.max( size, 4 );
  18553. const boneMatrices = new Float32Array( size * size * 4 ); // 4 floats per RGBA pixel
  18554. boneMatrices.set( this.boneMatrices ); // copy current values
  18555. const boneTexture = new DataTexture( boneMatrices, size, size, RGBAFormat, FloatType );
  18556. boneTexture.needsUpdate = true;
  18557. this.boneMatrices = boneMatrices;
  18558. this.boneTexture = boneTexture;
  18559. return this;
  18560. }
  18561. /**
  18562. * Searches through the skeleton's bone array and returns the first with a
  18563. * matching name.
  18564. *
  18565. * @param {string} name - The name of the bone.
  18566. * @return {Bone|undefined} The found bone. `undefined` if no bone has been found.
  18567. */
  18568. getBoneByName( name ) {
  18569. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  18570. const bone = this.bones[ i ];
  18571. if ( bone.name === name ) {
  18572. return bone;
  18573. }
  18574. }
  18575. return undefined;
  18576. }
  18577. /**
  18578. * Frees the GPU-related resources allocated by this instance. Call this
  18579. * method whenever this instance is no longer used in your app.
  18580. */
  18581. dispose( ) {
  18582. if ( this.boneTexture !== null ) {
  18583. this.boneTexture.dispose();
  18584. this.boneTexture = null;
  18585. }
  18586. }
  18587. /**
  18588. * Setups the skeleton by the given JSON and bones.
  18589. *
  18590. * @param {Object} json - The skeleton as serialized JSON.
  18591. * @param {Object<string, Bone>} bones - An array of bones.
  18592. * @return {Skeleton} A reference of this instance.
  18593. */
  18594. fromJSON( json, bones ) {
  18595. this.uuid = json.uuid;
  18596. for ( let i = 0, l = json.bones.length; i < l; i ++ ) {
  18597. const uuid = json.bones[ i ];
  18598. let bone = bones[ uuid ];
  18599. if ( bone === undefined ) {
  18600. console.warn( 'THREE.Skeleton: No bone found with UUID:', uuid );
  18601. bone = new Bone();
  18602. }
  18603. this.bones.push( bone );
  18604. this.boneInverses.push( new Matrix4().fromArray( json.boneInverses[ i ] ) );
  18605. }
  18606. this.init();
  18607. return this;
  18608. }
  18609. /**
  18610. * Serializes the skeleton into JSON.
  18611. *
  18612. * @return {Object} A JSON object representing the serialized skeleton.
  18613. * @see {@link ObjectLoader#parse}
  18614. */
  18615. toJSON() {
  18616. const data = {
  18617. metadata: {
  18618. version: 4.6,
  18619. type: 'Skeleton',
  18620. generator: 'Skeleton.toJSON'
  18621. },
  18622. bones: [],
  18623. boneInverses: []
  18624. };
  18625. data.uuid = this.uuid;
  18626. const bones = this.bones;
  18627. const boneInverses = this.boneInverses;
  18628. for ( let i = 0, l = bones.length; i < l; i ++ ) {
  18629. const bone = bones[ i ];
  18630. data.bones.push( bone.uuid );
  18631. const boneInverse = boneInverses[ i ];
  18632. data.boneInverses.push( boneInverse.toArray() );
  18633. }
  18634. return data;
  18635. }
  18636. }
  18637. /**
  18638. * An instanced version of a buffer attribute.
  18639. *
  18640. * @augments BufferAttribute
  18641. */
  18642. class InstancedBufferAttribute extends BufferAttribute {
  18643. /**
  18644. * Constructs a new instanced buffer attribute.
  18645. *
  18646. * @param {TypedArray} array - The array holding the attribute data.
  18647. * @param {number} itemSize - The item size.
  18648. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  18649. * @param {number} [meshPerAttribute=1] - How often a value of this buffer attribute should be repeated.
  18650. */
  18651. constructor( array, itemSize, normalized, meshPerAttribute = 1 ) {
  18652. super( array, itemSize, normalized );
  18653. /**
  18654. * This flag can be used for type testing.
  18655. *
  18656. * @type {boolean}
  18657. * @readonly
  18658. * @default true
  18659. */
  18660. this.isInstancedBufferAttribute = true;
  18661. /**
  18662. * Defines how often a value of this buffer attribute should be repeated. A
  18663. * value of one means that each value of the instanced attribute is used for
  18664. * a single instance. A value of two means that each value is used for two
  18665. * consecutive instances (and so on).
  18666. *
  18667. * @type {number}
  18668. * @default 1
  18669. */
  18670. this.meshPerAttribute = meshPerAttribute;
  18671. }
  18672. copy( source ) {
  18673. super.copy( source );
  18674. this.meshPerAttribute = source.meshPerAttribute;
  18675. return this;
  18676. }
  18677. toJSON() {
  18678. const data = super.toJSON();
  18679. data.meshPerAttribute = this.meshPerAttribute;
  18680. data.isInstancedBufferAttribute = true;
  18681. return data;
  18682. }
  18683. }
  18684. const _instanceLocalMatrix = /*@__PURE__*/ new Matrix4();
  18685. const _instanceWorldMatrix = /*@__PURE__*/ new Matrix4();
  18686. const _instanceIntersects = [];
  18687. const _box3 = /*@__PURE__*/ new Box3();
  18688. const _identity = /*@__PURE__*/ new Matrix4();
  18689. const _mesh$1 = /*@__PURE__*/ new Mesh();
  18690. const _sphere$4 = /*@__PURE__*/ new Sphere();
  18691. /**
  18692. * A special version of a mesh with instanced rendering support. Use
  18693. * this class if you have to render a large number of objects with the same
  18694. * geometry and material(s) but with different world transformations. The usage
  18695. * of 'InstancedMesh' will help you to reduce the number of draw calls and thus
  18696. * improve the overall rendering performance in your application.
  18697. *
  18698. * @augments Mesh
  18699. */
  18700. class InstancedMesh extends Mesh {
  18701. /**
  18702. * Constructs a new instanced mesh.
  18703. *
  18704. * @param {BufferGeometry} [geometry] - The mesh geometry.
  18705. * @param {Material|Array<Material>} [material] - The mesh material.
  18706. * @param {number} count - The number of instances.
  18707. */
  18708. constructor( geometry, material, count ) {
  18709. super( geometry, material );
  18710. /**
  18711. * This flag can be used for type testing.
  18712. *
  18713. * @type {boolean}
  18714. * @readonly
  18715. * @default true
  18716. */
  18717. this.isInstancedMesh = true;
  18718. /**
  18719. * Represents the local transformation of all instances. You have to set its
  18720. * {@link BufferAttribute#needsUpdate} flag to true if you modify instanced data
  18721. * via {@link InstancedMesh#setMatrixAt}.
  18722. *
  18723. * @type {InstancedBufferAttribute}
  18724. */
  18725. this.instanceMatrix = new InstancedBufferAttribute( new Float32Array( count * 16 ), 16 );
  18726. /**
  18727. * Represents the color of all instances. You have to set its
  18728. * {@link BufferAttribute#needsUpdate} flag to true if you modify instanced data
  18729. * via {@link InstancedMesh#setColorAt}.
  18730. *
  18731. * @type {?InstancedBufferAttribute}
  18732. * @default null
  18733. */
  18734. this.instanceColor = null;
  18735. /**
  18736. * Represents the morph target weights of all instances. You have to set its
  18737. * {@link Texture#needsUpdate} flag to true if you modify instanced data
  18738. * via {@link InstancedMesh#setMorphAt}.
  18739. *
  18740. * @type {?DataTexture}
  18741. * @default null
  18742. */
  18743. this.morphTexture = null;
  18744. /**
  18745. * The number of instances.
  18746. *
  18747. * @type {number}
  18748. */
  18749. this.count = count;
  18750. /**
  18751. * The bounding box of the instanced mesh. Can be computed via {@link InstancedMesh#computeBoundingBox}.
  18752. *
  18753. * @type {?Box3}
  18754. * @default null
  18755. */
  18756. this.boundingBox = null;
  18757. /**
  18758. * The bounding sphere of the instanced mesh. Can be computed via {@link InstancedMesh#computeBoundingSphere}.
  18759. *
  18760. * @type {?Sphere}
  18761. * @default null
  18762. */
  18763. this.boundingSphere = null;
  18764. for ( let i = 0; i < count; i ++ ) {
  18765. this.setMatrixAt( i, _identity );
  18766. }
  18767. }
  18768. /**
  18769. * Computes the bounding box of the instanced mesh, and updates {@link InstancedMesh#boundingBox}.
  18770. * The bounding box is not automatically computed by the engine; this method must be called by your app.
  18771. * You may need to recompute the bounding box if an instance is transformed via {@link InstancedMesh#setMatrixAt}.
  18772. */
  18773. computeBoundingBox() {
  18774. const geometry = this.geometry;
  18775. const count = this.count;
  18776. if ( this.boundingBox === null ) {
  18777. this.boundingBox = new Box3();
  18778. }
  18779. if ( geometry.boundingBox === null ) {
  18780. geometry.computeBoundingBox();
  18781. }
  18782. this.boundingBox.makeEmpty();
  18783. for ( let i = 0; i < count; i ++ ) {
  18784. this.getMatrixAt( i, _instanceLocalMatrix );
  18785. _box3.copy( geometry.boundingBox ).applyMatrix4( _instanceLocalMatrix );
  18786. this.boundingBox.union( _box3 );
  18787. }
  18788. }
  18789. /**
  18790. * Computes the bounding sphere of the instanced mesh, and updates {@link InstancedMesh#boundingSphere}
  18791. * The engine automatically computes the bounding sphere when it is needed, e.g., for ray casting or view frustum culling.
  18792. * You may need to recompute the bounding sphere if an instance is transformed via {@link InstancedMesh#setMatrixAt}.
  18793. */
  18794. computeBoundingSphere() {
  18795. const geometry = this.geometry;
  18796. const count = this.count;
  18797. if ( this.boundingSphere === null ) {
  18798. this.boundingSphere = new Sphere();
  18799. }
  18800. if ( geometry.boundingSphere === null ) {
  18801. geometry.computeBoundingSphere();
  18802. }
  18803. this.boundingSphere.makeEmpty();
  18804. for ( let i = 0; i < count; i ++ ) {
  18805. this.getMatrixAt( i, _instanceLocalMatrix );
  18806. _sphere$4.copy( geometry.boundingSphere ).applyMatrix4( _instanceLocalMatrix );
  18807. this.boundingSphere.union( _sphere$4 );
  18808. }
  18809. }
  18810. copy( source, recursive ) {
  18811. super.copy( source, recursive );
  18812. this.instanceMatrix.copy( source.instanceMatrix );
  18813. if ( source.morphTexture !== null ) this.morphTexture = source.morphTexture.clone();
  18814. if ( source.instanceColor !== null ) this.instanceColor = source.instanceColor.clone();
  18815. this.count = source.count;
  18816. if ( source.boundingBox !== null ) this.boundingBox = source.boundingBox.clone();
  18817. if ( source.boundingSphere !== null ) this.boundingSphere = source.boundingSphere.clone();
  18818. return this;
  18819. }
  18820. /**
  18821. * Gets the color of the defined instance.
  18822. *
  18823. * @param {number} index - The instance index.
  18824. * @param {Color} color - The target object that is used to store the method's result.
  18825. */
  18826. getColorAt( index, color ) {
  18827. color.fromArray( this.instanceColor.array, index * 3 );
  18828. }
  18829. /**
  18830. * Gets the local transformation matrix of the defined instance.
  18831. *
  18832. * @param {number} index - The instance index.
  18833. * @param {Matrix4} matrix - The target object that is used to store the method's result.
  18834. */
  18835. getMatrixAt( index, matrix ) {
  18836. matrix.fromArray( this.instanceMatrix.array, index * 16 );
  18837. }
  18838. /**
  18839. * Gets the morph target weights of the defined instance.
  18840. *
  18841. * @param {number} index - The instance index.
  18842. * @param {Mesh} object - The target object that is used to store the method's result.
  18843. */
  18844. getMorphAt( index, object ) {
  18845. const objectInfluences = object.morphTargetInfluences;
  18846. const array = this.morphTexture.source.data.data;
  18847. const len = objectInfluences.length + 1; // All influences + the baseInfluenceSum
  18848. const dataIndex = index * len + 1; // Skip the baseInfluenceSum at the beginning
  18849. for ( let i = 0; i < objectInfluences.length; i ++ ) {
  18850. objectInfluences[ i ] = array[ dataIndex + i ];
  18851. }
  18852. }
  18853. raycast( raycaster, intersects ) {
  18854. const matrixWorld = this.matrixWorld;
  18855. const raycastTimes = this.count;
  18856. _mesh$1.geometry = this.geometry;
  18857. _mesh$1.material = this.material;
  18858. if ( _mesh$1.material === undefined ) return;
  18859. // test with bounding sphere first
  18860. if ( this.boundingSphere === null ) this.computeBoundingSphere();
  18861. _sphere$4.copy( this.boundingSphere );
  18862. _sphere$4.applyMatrix4( matrixWorld );
  18863. if ( raycaster.ray.intersectsSphere( _sphere$4 ) === false ) return;
  18864. // now test each instance
  18865. for ( let instanceId = 0; instanceId < raycastTimes; instanceId ++ ) {
  18866. // calculate the world matrix for each instance
  18867. this.getMatrixAt( instanceId, _instanceLocalMatrix );
  18868. _instanceWorldMatrix.multiplyMatrices( matrixWorld, _instanceLocalMatrix );
  18869. // the mesh represents this single instance
  18870. _mesh$1.matrixWorld = _instanceWorldMatrix;
  18871. _mesh$1.raycast( raycaster, _instanceIntersects );
  18872. // process the result of raycast
  18873. for ( let i = 0, l = _instanceIntersects.length; i < l; i ++ ) {
  18874. const intersect = _instanceIntersects[ i ];
  18875. intersect.instanceId = instanceId;
  18876. intersect.object = this;
  18877. intersects.push( intersect );
  18878. }
  18879. _instanceIntersects.length = 0;
  18880. }
  18881. }
  18882. /**
  18883. * Sets the given color to the defined instance. Make sure you set the `needsUpdate` flag of
  18884. * {@link InstancedMesh#instanceColor} to `true` after updating all the colors.
  18885. *
  18886. * @param {number} index - The instance index.
  18887. * @param {Color} color - The instance color.
  18888. */
  18889. setColorAt( index, color ) {
  18890. if ( this.instanceColor === null ) {
  18891. this.instanceColor = new InstancedBufferAttribute( new Float32Array( this.instanceMatrix.count * 3 ).fill( 1 ), 3 );
  18892. }
  18893. color.toArray( this.instanceColor.array, index * 3 );
  18894. }
  18895. /**
  18896. * Sets the given local transformation matrix to the defined instance. Make sure you set the `needsUpdate` flag of
  18897. * {@link InstancedMesh#instanceMatrix} to `true` after updating all the colors.
  18898. *
  18899. * @param {number} index - The instance index.
  18900. * @param {Matrix4} matrix - The the local transformation.
  18901. */
  18902. setMatrixAt( index, matrix ) {
  18903. matrix.toArray( this.instanceMatrix.array, index * 16 );
  18904. }
  18905. /**
  18906. * Sets the morph target weights to the defined instance. Make sure you set the `needsUpdate` flag of
  18907. * {@link InstancedMesh#morphTexture} to `true` after updating all the influences.
  18908. *
  18909. * @param {number} index - The instance index.
  18910. * @param {Mesh} object - A mesh which `morphTargetInfluences` property containing the morph target weights
  18911. * of a single instance.
  18912. */
  18913. setMorphAt( index, object ) {
  18914. const objectInfluences = object.morphTargetInfluences;
  18915. const len = objectInfluences.length + 1; // morphBaseInfluence + all influences
  18916. if ( this.morphTexture === null ) {
  18917. this.morphTexture = new DataTexture( new Float32Array( len * this.count ), len, this.count, RedFormat, FloatType );
  18918. }
  18919. const array = this.morphTexture.source.data.data;
  18920. let morphInfluencesSum = 0;
  18921. for ( let i = 0; i < objectInfluences.length; i ++ ) {
  18922. morphInfluencesSum += objectInfluences[ i ];
  18923. }
  18924. const morphBaseInfluence = this.geometry.morphTargetsRelative ? 1 : 1 - morphInfluencesSum;
  18925. const dataIndex = len * index;
  18926. array[ dataIndex ] = morphBaseInfluence;
  18927. array.set( objectInfluences, dataIndex + 1 );
  18928. }
  18929. updateMorphTargets() {
  18930. }
  18931. /**
  18932. * Frees the GPU-related resources allocated by this instance. Call this
  18933. * method whenever this instance is no longer used in your app.
  18934. */
  18935. dispose() {
  18936. this.dispatchEvent( { type: 'dispose' } );
  18937. if ( this.morphTexture !== null ) {
  18938. this.morphTexture.dispose();
  18939. this.morphTexture = null;
  18940. }
  18941. }
  18942. }
  18943. const _vector1 = /*@__PURE__*/ new Vector3();
  18944. const _vector2 = /*@__PURE__*/ new Vector3();
  18945. const _normalMatrix = /*@__PURE__*/ new Matrix3();
  18946. /**
  18947. * A two dimensional surface that extends infinitely in 3D space, represented
  18948. * in [Hessian normal form]{@link http://mathworld.wolfram.com/HessianNormalForm.html}
  18949. * by a unit length normal vector and a constant.
  18950. */
  18951. class Plane {
  18952. /**
  18953. * Constructs a new plane.
  18954. *
  18955. * @param {Vector3} [normal=(1,0,0)] - A unit length vector defining the normal of the plane.
  18956. * @param {number} [constant=0] - The signed distance from the origin to the plane.
  18957. */
  18958. constructor( normal = new Vector3( 1, 0, 0 ), constant = 0 ) {
  18959. /**
  18960. * This flag can be used for type testing.
  18961. *
  18962. * @type {boolean}
  18963. * @readonly
  18964. * @default true
  18965. */
  18966. this.isPlane = true;
  18967. /**
  18968. * A unit length vector defining the normal of the plane.
  18969. *
  18970. * @type {Vector3}
  18971. */
  18972. this.normal = normal;
  18973. /**
  18974. * The signed distance from the origin to the plane.
  18975. *
  18976. * @type {number}
  18977. * @default 0
  18978. */
  18979. this.constant = constant;
  18980. }
  18981. /**
  18982. * Sets the plane components by copying the given values.
  18983. *
  18984. * @param {Vector3} normal - The normal.
  18985. * @param {number} constant - The constant.
  18986. * @return {Plane} A reference to this plane.
  18987. */
  18988. set( normal, constant ) {
  18989. this.normal.copy( normal );
  18990. this.constant = constant;
  18991. return this;
  18992. }
  18993. /**
  18994. * Sets the plane components by defining `x`, `y`, `z` as the
  18995. * plane normal and `w` as the constant.
  18996. *
  18997. * @param {number} x - The value for the normal's x component.
  18998. * @param {number} y - The value for the normal's y component.
  18999. * @param {number} z - The value for the normal's z component.
  19000. * @param {number} w - The constant value.
  19001. * @return {Plane} A reference to this plane.
  19002. */
  19003. setComponents( x, y, z, w ) {
  19004. this.normal.set( x, y, z );
  19005. this.constant = w;
  19006. return this;
  19007. }
  19008. /**
  19009. * Sets the plane from the given normal and coplanar point (that is a point
  19010. * that lies onto the plane).
  19011. *
  19012. * @param {Vector3} normal - The normal.
  19013. * @param {Vector3} point - A coplanar point.
  19014. * @return {Plane} A reference to this plane.
  19015. */
  19016. setFromNormalAndCoplanarPoint( normal, point ) {
  19017. this.normal.copy( normal );
  19018. this.constant = - point.dot( this.normal );
  19019. return this;
  19020. }
  19021. /**
  19022. * Sets the plane from three coplanar points. The winding order is
  19023. * assumed to be counter-clockwise, and determines the direction of
  19024. * the plane normal.
  19025. *
  19026. * @param {Vector3} a - The first coplanar point.
  19027. * @param {Vector3} b - The second coplanar point.
  19028. * @param {Vector3} c - The third coplanar point.
  19029. * @return {Plane} A reference to this plane.
  19030. */
  19031. setFromCoplanarPoints( a, b, c ) {
  19032. const normal = _vector1.subVectors( c, b ).cross( _vector2.subVectors( a, b ) ).normalize();
  19033. // Q: should an error be thrown if normal is zero (e.g. degenerate plane)?
  19034. this.setFromNormalAndCoplanarPoint( normal, a );
  19035. return this;
  19036. }
  19037. /**
  19038. * Copies the values of the given plane to this instance.
  19039. *
  19040. * @param {Plane} plane - The plane to copy.
  19041. * @return {Plane} A reference to this plane.
  19042. */
  19043. copy( plane ) {
  19044. this.normal.copy( plane.normal );
  19045. this.constant = plane.constant;
  19046. return this;
  19047. }
  19048. /**
  19049. * Normalizes the plane normal and adjusts the constant accordingly.
  19050. *
  19051. * @return {Plane} A reference to this plane.
  19052. */
  19053. normalize() {
  19054. // Note: will lead to a divide by zero if the plane is invalid.
  19055. const inverseNormalLength = 1.0 / this.normal.length();
  19056. this.normal.multiplyScalar( inverseNormalLength );
  19057. this.constant *= inverseNormalLength;
  19058. return this;
  19059. }
  19060. /**
  19061. * Negates both the plane normal and the constant.
  19062. *
  19063. * @return {Plane} A reference to this plane.
  19064. */
  19065. negate() {
  19066. this.constant *= -1;
  19067. this.normal.negate();
  19068. return this;
  19069. }
  19070. /**
  19071. * Returns the signed distance from the given point to this plane.
  19072. *
  19073. * @param {Vector3} point - The point to compute the distance for.
  19074. * @return {number} The signed distance.
  19075. */
  19076. distanceToPoint( point ) {
  19077. return this.normal.dot( point ) + this.constant;
  19078. }
  19079. /**
  19080. * Returns the signed distance from the given sphere to this plane.
  19081. *
  19082. * @param {Sphere} sphere - The sphere to compute the distance for.
  19083. * @return {number} The signed distance.
  19084. */
  19085. distanceToSphere( sphere ) {
  19086. return this.distanceToPoint( sphere.center ) - sphere.radius;
  19087. }
  19088. /**
  19089. * Projects a the given point onto the plane.
  19090. *
  19091. * @param {Vector3} point - The point to project.
  19092. * @param {Vector3} target - The target vector that is used to store the method's result.
  19093. * @return {Vector3} The projected point on the plane.
  19094. */
  19095. projectPoint( point, target ) {
  19096. return target.copy( point ).addScaledVector( this.normal, - this.distanceToPoint( point ) );
  19097. }
  19098. /**
  19099. * Returns the intersection point of the passed line and the plane. Returns
  19100. * `null` if the line does not intersect. Returns the line's starting point if
  19101. * the line is coplanar with the plane.
  19102. *
  19103. * @param {Line3} line - The line to compute the intersection for.
  19104. * @param {Vector3} target - The target vector that is used to store the method's result.
  19105. * @return {?Vector3} The intersection point.
  19106. */
  19107. intersectLine( line, target ) {
  19108. const direction = line.delta( _vector1 );
  19109. const denominator = this.normal.dot( direction );
  19110. if ( denominator === 0 ) {
  19111. // line is coplanar, return origin
  19112. if ( this.distanceToPoint( line.start ) === 0 ) {
  19113. return target.copy( line.start );
  19114. }
  19115. // Unsure if this is the correct method to handle this case.
  19116. return null;
  19117. }
  19118. const t = - ( line.start.dot( this.normal ) + this.constant ) / denominator;
  19119. if ( t < 0 || t > 1 ) {
  19120. return null;
  19121. }
  19122. return target.copy( line.start ).addScaledVector( direction, t );
  19123. }
  19124. /**
  19125. * Returns `true` if the given line segment intersects with (passes through) the plane.
  19126. *
  19127. * @param {Line3} line - The line to test.
  19128. * @return {boolean} Whether the given line segment intersects with the plane or not.
  19129. */
  19130. intersectsLine( line ) {
  19131. // Note: this tests if a line intersects the plane, not whether it (or its end-points) are coplanar with it.
  19132. const startSign = this.distanceToPoint( line.start );
  19133. const endSign = this.distanceToPoint( line.end );
  19134. return ( startSign < 0 && endSign > 0 ) || ( endSign < 0 && startSign > 0 );
  19135. }
  19136. /**
  19137. * Returns `true` if the given bounding box intersects with the plane.
  19138. *
  19139. * @param {Box3} box - The bounding box to test.
  19140. * @return {boolean} Whether the given bounding box intersects with the plane or not.
  19141. */
  19142. intersectsBox( box ) {
  19143. return box.intersectsPlane( this );
  19144. }
  19145. /**
  19146. * Returns `true` if the given bounding sphere intersects with the plane.
  19147. *
  19148. * @param {Sphere} sphere - The bounding sphere to test.
  19149. * @return {boolean} Whether the given bounding sphere intersects with the plane or not.
  19150. */
  19151. intersectsSphere( sphere ) {
  19152. return sphere.intersectsPlane( this );
  19153. }
  19154. /**
  19155. * Returns a coplanar vector to the plane, by calculating the
  19156. * projection of the normal at the origin onto the plane.
  19157. *
  19158. * @param {Vector3} target - The target vector that is used to store the method's result.
  19159. * @return {Vector3} The coplanar point.
  19160. */
  19161. coplanarPoint( target ) {
  19162. return target.copy( this.normal ).multiplyScalar( - this.constant );
  19163. }
  19164. /**
  19165. * Apply a 4x4 matrix to the plane. The matrix must be an affine, homogeneous transform.
  19166. *
  19167. * The optional normal matrix can be pre-computed like so:
  19168. * ```js
  19169. * const optionalNormalMatrix = new THREE.Matrix3().getNormalMatrix( matrix );
  19170. * ```
  19171. *
  19172. * @param {Matrix4} matrix - The transformation matrix.
  19173. * @param {Matrix4} [optionalNormalMatrix] - A pre-computed normal matrix.
  19174. * @return {Plane} A reference to this plane.
  19175. */
  19176. applyMatrix4( matrix, optionalNormalMatrix ) {
  19177. const normalMatrix = optionalNormalMatrix || _normalMatrix.getNormalMatrix( matrix );
  19178. const referencePoint = this.coplanarPoint( _vector1 ).applyMatrix4( matrix );
  19179. const normal = this.normal.applyMatrix3( normalMatrix ).normalize();
  19180. this.constant = - referencePoint.dot( normal );
  19181. return this;
  19182. }
  19183. /**
  19184. * Translates the plane by the distance defined by the given offset vector.
  19185. * Note that this only affects the plane constant and will not affect the normal vector.
  19186. *
  19187. * @param {Vector3} offset - The offset vector.
  19188. * @return {Plane} A reference to this plane.
  19189. */
  19190. translate( offset ) {
  19191. this.constant -= offset.dot( this.normal );
  19192. return this;
  19193. }
  19194. /**
  19195. * Returns `true` if this plane is equal with the given one.
  19196. *
  19197. * @param {Plane} plane - The plane to test for equality.
  19198. * @return {boolean} Whether this plane is equal with the given one.
  19199. */
  19200. equals( plane ) {
  19201. return plane.normal.equals( this.normal ) && ( plane.constant === this.constant );
  19202. }
  19203. /**
  19204. * Returns a new plane with copied values from this instance.
  19205. *
  19206. * @return {Plane} A clone of this instance.
  19207. */
  19208. clone() {
  19209. return new this.constructor().copy( this );
  19210. }
  19211. }
  19212. const _sphere$3 = /*@__PURE__*/ new Sphere();
  19213. const _vector$6 = /*@__PURE__*/ new Vector3();
  19214. /**
  19215. * Frustums are used to determine what is inside the camera's field of view.
  19216. * They help speed up the rendering process - objects which lie outside a camera's
  19217. * frustum can safely be excluded from rendering.
  19218. *
  19219. * This class is mainly intended for use internally by a renderer.
  19220. */
  19221. class Frustum {
  19222. /**
  19223. * Constructs a new frustum.
  19224. *
  19225. * @param {Plane} [p0] - The first plane that encloses the frustum.
  19226. * @param {Plane} [p1] - The second plane that encloses the frustum.
  19227. * @param {Plane} [p2] - The third plane that encloses the frustum.
  19228. * @param {Plane} [p3] - The fourth plane that encloses the frustum.
  19229. * @param {Plane} [p4] - The fifth plane that encloses the frustum.
  19230. * @param {Plane} [p5] - The sixth plane that encloses the frustum.
  19231. */
  19232. constructor( p0 = new Plane(), p1 = new Plane(), p2 = new Plane(), p3 = new Plane(), p4 = new Plane(), p5 = new Plane() ) {
  19233. /**
  19234. * This array holds the planes that enclose the frustum.
  19235. *
  19236. * @type {Array<Plane>}
  19237. */
  19238. this.planes = [ p0, p1, p2, p3, p4, p5 ];
  19239. }
  19240. /**
  19241. * Sets the frustum planes by copying the given planes.
  19242. *
  19243. * @param {Plane} [p0] - The first plane that encloses the frustum.
  19244. * @param {Plane} [p1] - The second plane that encloses the frustum.
  19245. * @param {Plane} [p2] - The third plane that encloses the frustum.
  19246. * @param {Plane} [p3] - The fourth plane that encloses the frustum.
  19247. * @param {Plane} [p4] - The fifth plane that encloses the frustum.
  19248. * @param {Plane} [p5] - The sixth plane that encloses the frustum.
  19249. * @return {Frustum} A reference to this frustum.
  19250. */
  19251. set( p0, p1, p2, p3, p4, p5 ) {
  19252. const planes = this.planes;
  19253. planes[ 0 ].copy( p0 );
  19254. planes[ 1 ].copy( p1 );
  19255. planes[ 2 ].copy( p2 );
  19256. planes[ 3 ].copy( p3 );
  19257. planes[ 4 ].copy( p4 );
  19258. planes[ 5 ].copy( p5 );
  19259. return this;
  19260. }
  19261. /**
  19262. * Copies the values of the given frustum to this instance.
  19263. *
  19264. * @param {Frustum} frustum - The frustum to copy.
  19265. * @return {Frustum} A reference to this frustum.
  19266. */
  19267. copy( frustum ) {
  19268. const planes = this.planes;
  19269. for ( let i = 0; i < 6; i ++ ) {
  19270. planes[ i ].copy( frustum.planes[ i ] );
  19271. }
  19272. return this;
  19273. }
  19274. /**
  19275. * Sets the frustum planes from the given projection matrix.
  19276. *
  19277. * @param {Matrix4} m - The projection matrix.
  19278. * @param {(WebGLCoordinateSystem|WebGPUCoordinateSystem)} coordinateSystem - The coordinate system.
  19279. * @return {Frustum} A reference to this frustum.
  19280. */
  19281. setFromProjectionMatrix( m, coordinateSystem = WebGLCoordinateSystem ) {
  19282. const planes = this.planes;
  19283. const me = m.elements;
  19284. const me0 = me[ 0 ], me1 = me[ 1 ], me2 = me[ 2 ], me3 = me[ 3 ];
  19285. const me4 = me[ 4 ], me5 = me[ 5 ], me6 = me[ 6 ], me7 = me[ 7 ];
  19286. const me8 = me[ 8 ], me9 = me[ 9 ], me10 = me[ 10 ], me11 = me[ 11 ];
  19287. const me12 = me[ 12 ], me13 = me[ 13 ], me14 = me[ 14 ], me15 = me[ 15 ];
  19288. planes[ 0 ].setComponents( me3 - me0, me7 - me4, me11 - me8, me15 - me12 ).normalize();
  19289. planes[ 1 ].setComponents( me3 + me0, me7 + me4, me11 + me8, me15 + me12 ).normalize();
  19290. planes[ 2 ].setComponents( me3 + me1, me7 + me5, me11 + me9, me15 + me13 ).normalize();
  19291. planes[ 3 ].setComponents( me3 - me1, me7 - me5, me11 - me9, me15 - me13 ).normalize();
  19292. planes[ 4 ].setComponents( me3 - me2, me7 - me6, me11 - me10, me15 - me14 ).normalize();
  19293. if ( coordinateSystem === WebGLCoordinateSystem ) {
  19294. planes[ 5 ].setComponents( me3 + me2, me7 + me6, me11 + me10, me15 + me14 ).normalize();
  19295. } else if ( coordinateSystem === WebGPUCoordinateSystem ) {
  19296. planes[ 5 ].setComponents( me2, me6, me10, me14 ).normalize();
  19297. } else {
  19298. throw new Error( 'THREE.Frustum.setFromProjectionMatrix(): Invalid coordinate system: ' + coordinateSystem );
  19299. }
  19300. return this;
  19301. }
  19302. /**
  19303. * Returns `true` if the 3D object's bounding sphere is intersecting this frustum.
  19304. *
  19305. * Note that the 3D object must have a geometry so that the bounding sphere can be calculated.
  19306. *
  19307. * @param {Object3D} object - The 3D object to test.
  19308. * @return {boolean} Whether the 3D object's bounding sphere is intersecting this frustum or not.
  19309. */
  19310. intersectsObject( object ) {
  19311. if ( object.boundingSphere !== undefined ) {
  19312. if ( object.boundingSphere === null ) object.computeBoundingSphere();
  19313. _sphere$3.copy( object.boundingSphere ).applyMatrix4( object.matrixWorld );
  19314. } else {
  19315. const geometry = object.geometry;
  19316. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  19317. _sphere$3.copy( geometry.boundingSphere ).applyMatrix4( object.matrixWorld );
  19318. }
  19319. return this.intersectsSphere( _sphere$3 );
  19320. }
  19321. /**
  19322. * Returns `true` if the given sprite is intersecting this frustum.
  19323. *
  19324. * @param {Sprite} sprite - The sprite to test.
  19325. * @return {boolean} Whether the sprite is intersecting this frustum or not.
  19326. */
  19327. intersectsSprite( sprite ) {
  19328. _sphere$3.center.set( 0, 0, 0 );
  19329. _sphere$3.radius = 0.7071067811865476;
  19330. _sphere$3.applyMatrix4( sprite.matrixWorld );
  19331. return this.intersectsSphere( _sphere$3 );
  19332. }
  19333. /**
  19334. * Returns `true` if the given bounding sphere is intersecting this frustum.
  19335. *
  19336. * @param {Sphere} sphere - The bounding sphere to test.
  19337. * @return {boolean} Whether the bounding sphere is intersecting this frustum or not.
  19338. */
  19339. intersectsSphere( sphere ) {
  19340. const planes = this.planes;
  19341. const center = sphere.center;
  19342. const negRadius = - sphere.radius;
  19343. for ( let i = 0; i < 6; i ++ ) {
  19344. const distance = planes[ i ].distanceToPoint( center );
  19345. if ( distance < negRadius ) {
  19346. return false;
  19347. }
  19348. }
  19349. return true;
  19350. }
  19351. /**
  19352. * Returns `true` if the given bounding box is intersecting this frustum.
  19353. *
  19354. * @param {Box3} box - The bounding box to test.
  19355. * @return {boolean} Whether the bounding box is intersecting this frustum or not.
  19356. */
  19357. intersectsBox( box ) {
  19358. const planes = this.planes;
  19359. for ( let i = 0; i < 6; i ++ ) {
  19360. const plane = planes[ i ];
  19361. // corner at max distance
  19362. _vector$6.x = plane.normal.x > 0 ? box.max.x : box.min.x;
  19363. _vector$6.y = plane.normal.y > 0 ? box.max.y : box.min.y;
  19364. _vector$6.z = plane.normal.z > 0 ? box.max.z : box.min.z;
  19365. if ( plane.distanceToPoint( _vector$6 ) < 0 ) {
  19366. return false;
  19367. }
  19368. }
  19369. return true;
  19370. }
  19371. /**
  19372. * Returns `true` if the given point lies within the frustum.
  19373. *
  19374. * @param {Vector3} point - The point to test.
  19375. * @return {boolean} Whether the point lies within this frustum or not.
  19376. */
  19377. containsPoint( point ) {
  19378. const planes = this.planes;
  19379. for ( let i = 0; i < 6; i ++ ) {
  19380. if ( planes[ i ].distanceToPoint( point ) < 0 ) {
  19381. return false;
  19382. }
  19383. }
  19384. return true;
  19385. }
  19386. /**
  19387. * Returns a new frustum with copied values from this instance.
  19388. *
  19389. * @return {Frustum} A clone of this instance.
  19390. */
  19391. clone() {
  19392. return new this.constructor().copy( this );
  19393. }
  19394. }
  19395. function ascIdSort( a, b ) {
  19396. return a - b;
  19397. }
  19398. function sortOpaque( a, b ) {
  19399. return a.z - b.z;
  19400. }
  19401. function sortTransparent( a, b ) {
  19402. return b.z - a.z;
  19403. }
  19404. class MultiDrawRenderList {
  19405. constructor() {
  19406. this.index = 0;
  19407. this.pool = [];
  19408. this.list = [];
  19409. }
  19410. push( start, count, z, index ) {
  19411. const pool = this.pool;
  19412. const list = this.list;
  19413. if ( this.index >= pool.length ) {
  19414. pool.push( {
  19415. start: -1,
  19416. count: -1,
  19417. z: -1,
  19418. index: -1,
  19419. } );
  19420. }
  19421. const item = pool[ this.index ];
  19422. list.push( item );
  19423. this.index ++;
  19424. item.start = start;
  19425. item.count = count;
  19426. item.z = z;
  19427. item.index = index;
  19428. }
  19429. reset() {
  19430. this.list.length = 0;
  19431. this.index = 0;
  19432. }
  19433. }
  19434. const _matrix$1 = /*@__PURE__*/ new Matrix4();
  19435. const _whiteColor = /*@__PURE__*/ new Color( 1, 1, 1 );
  19436. const _frustum = /*@__PURE__*/ new Frustum();
  19437. const _box$1 = /*@__PURE__*/ new Box3();
  19438. const _sphere$2 = /*@__PURE__*/ new Sphere();
  19439. const _vector$5 = /*@__PURE__*/ new Vector3();
  19440. const _forward = /*@__PURE__*/ new Vector3();
  19441. const _temp = /*@__PURE__*/ new Vector3();
  19442. const _renderList = /*@__PURE__*/ new MultiDrawRenderList();
  19443. const _mesh = /*@__PURE__*/ new Mesh();
  19444. const _batchIntersects = [];
  19445. // copies data from attribute "src" into "target" starting at "targetOffset"
  19446. function copyAttributeData( src, target, targetOffset = 0 ) {
  19447. const itemSize = target.itemSize;
  19448. if ( src.isInterleavedBufferAttribute || src.array.constructor !== target.array.constructor ) {
  19449. // use the component getters and setters if the array data cannot
  19450. // be copied directly
  19451. const vertexCount = src.count;
  19452. for ( let i = 0; i < vertexCount; i ++ ) {
  19453. for ( let c = 0; c < itemSize; c ++ ) {
  19454. target.setComponent( i + targetOffset, c, src.getComponent( i, c ) );
  19455. }
  19456. }
  19457. } else {
  19458. // faster copy approach using typed array set function
  19459. target.array.set( src.array, targetOffset * itemSize );
  19460. }
  19461. target.needsUpdate = true;
  19462. }
  19463. // safely copies array contents to a potentially smaller array
  19464. function copyArrayContents( src, target ) {
  19465. if ( src.constructor !== target.constructor ) {
  19466. // if arrays are of a different type (eg due to index size increasing) then data must be per-element copied
  19467. const len = Math.min( src.length, target.length );
  19468. for ( let i = 0; i < len; i ++ ) {
  19469. target[ i ] = src[ i ];
  19470. }
  19471. } else {
  19472. // if the arrays use the same data layout we can use a fast block copy
  19473. const len = Math.min( src.length, target.length );
  19474. target.set( new src.constructor( src.buffer, 0, len ) );
  19475. }
  19476. }
  19477. /**
  19478. * A special version of a mesh with multi draw batch rendering support. Use
  19479. * this class if you have to render a large number of objects with the same
  19480. * material but with different geometries or world transformations. The usage of
  19481. * `BatchedMesh` will help you to reduce the number of draw calls and thus improve the overall
  19482. * rendering performance in your application.
  19483. *
  19484. * ```js
  19485. * const box = new THREE.BoxGeometry( 1, 1, 1 );
  19486. * const sphere = new THREE.SphereGeometry( 1, 12, 12 );
  19487. * const material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } );
  19488. *
  19489. * // initialize and add geometries into the batched mesh
  19490. * const batchedMesh = new BatchedMesh( 10, 5000, 10000, material );
  19491. * const boxGeometryId = batchedMesh.addGeometry( box );
  19492. * const sphereGeometryId = batchedMesh.addGeometry( sphere );
  19493. *
  19494. * // create instances of those geometries
  19495. * const boxInstancedId1 = batchedMesh.addInstance( boxGeometryId );
  19496. * const boxInstancedId2 = batchedMesh.addInstance( boxGeometryId );
  19497. *
  19498. * const sphereInstancedId1 = batchedMesh.addInstance( sphereGeometryId );
  19499. * const sphereInstancedId2 = batchedMesh.addInstance( sphereGeometryId );
  19500. *
  19501. * // position the geometries
  19502. * batchedMesh.setMatrixAt( boxInstancedId1, boxMatrix1 );
  19503. * batchedMesh.setMatrixAt( boxInstancedId2, boxMatrix2 );
  19504. *
  19505. * batchedMesh.setMatrixAt( sphereInstancedId1, sphereMatrix1 );
  19506. * batchedMesh.setMatrixAt( sphereInstancedId2, sphereMatrix2 );
  19507. *
  19508. * scene.add( batchedMesh );
  19509. * ```
  19510. *
  19511. * @augments Mesh
  19512. */
  19513. class BatchedMesh extends Mesh {
  19514. /**
  19515. * Constructs a new batched mesh.
  19516. *
  19517. * @param {number} maxInstanceCount - The maximum number of individual instances planned to be added and rendered.
  19518. * @param {number} maxVertexCount - The maximum number of vertices to be used by all unique geometries.
  19519. * @param {number} [maxIndexCount=maxVertexCount*2] - The maximum number of indices to be used by all unique geometries
  19520. * @param {Material|Array<Material>} [material] - The mesh material.
  19521. */
  19522. constructor( maxInstanceCount, maxVertexCount, maxIndexCount = maxVertexCount * 2, material ) {
  19523. super( new BufferGeometry(), material );
  19524. /**
  19525. * This flag can be used for type testing.
  19526. *
  19527. * @type {boolean}
  19528. * @readonly
  19529. * @default true
  19530. */
  19531. this.isBatchedMesh = true;
  19532. /**
  19533. * When set ot `true`, the individual objects of a batch are frustum culled.
  19534. *
  19535. * @type {boolean}
  19536. * @default true
  19537. */
  19538. this.perObjectFrustumCulled = true;
  19539. /**
  19540. * When set to `true`, the individual objects of a batch are sorted to improve overdraw-related artifacts.
  19541. * If the material is marked as "transparent" objects are rendered back to front and if not then they are
  19542. * rendered front to back.
  19543. *
  19544. * @type {boolean}
  19545. * @default true
  19546. */
  19547. this.sortObjects = true;
  19548. /**
  19549. * The bounding box of the batched mesh. Can be computed via {@link BatchedMesh#computeBoundingBox}.
  19550. *
  19551. * @type {?Box3}
  19552. * @default null
  19553. */
  19554. this.boundingBox = null;
  19555. /**
  19556. * The bounding sphere of the batched mesh. Can be computed via {@link BatchedMesh#computeBoundingSphere}.
  19557. *
  19558. * @type {?Sphere}
  19559. * @default null
  19560. */
  19561. this.boundingSphere = null;
  19562. /**
  19563. * Takes a sort a function that is run before render. The function takes a list of instances to
  19564. * sort and a camera. The objects in the list include a "z" field to perform a depth-ordered
  19565. * sort with.
  19566. *
  19567. * @type {?Function}
  19568. * @default null
  19569. */
  19570. this.customSort = null;
  19571. // stores visible, active, and geometry id per instance and reserved buffer ranges for geometries
  19572. this._instanceInfo = [];
  19573. this._geometryInfo = [];
  19574. // instance, geometry ids that have been set as inactive, and are available to be overwritten
  19575. this._availableInstanceIds = [];
  19576. this._availableGeometryIds = [];
  19577. // used to track where the next point is that geometry should be inserted
  19578. this._nextIndexStart = 0;
  19579. this._nextVertexStart = 0;
  19580. this._geometryCount = 0;
  19581. // flags
  19582. this._visibilityChanged = true;
  19583. this._geometryInitialized = false;
  19584. // cached user options
  19585. this._maxInstanceCount = maxInstanceCount;
  19586. this._maxVertexCount = maxVertexCount;
  19587. this._maxIndexCount = maxIndexCount;
  19588. // buffers for multi draw
  19589. this._multiDrawCounts = new Int32Array( maxInstanceCount );
  19590. this._multiDrawStarts = new Int32Array( maxInstanceCount );
  19591. this._multiDrawCount = 0;
  19592. this._multiDrawInstances = null;
  19593. // Local matrix per geometry by using data texture
  19594. this._matricesTexture = null;
  19595. this._indirectTexture = null;
  19596. this._colorsTexture = null;
  19597. this._initMatricesTexture();
  19598. this._initIndirectTexture();
  19599. }
  19600. /**
  19601. * The maximum number of individual instances that can be stored in the batch.
  19602. *
  19603. * @type {number}
  19604. * @readonly
  19605. */
  19606. get maxInstanceCount() {
  19607. return this._maxInstanceCount;
  19608. }
  19609. /**
  19610. * The instance count.
  19611. *
  19612. * @type {number}
  19613. * @readonly
  19614. */
  19615. get instanceCount() {
  19616. return this._instanceInfo.length - this._availableInstanceIds.length;
  19617. }
  19618. /**
  19619. * The number of unused vertices.
  19620. *
  19621. * @type {number}
  19622. * @readonly
  19623. */
  19624. get unusedVertexCount() {
  19625. return this._maxVertexCount - this._nextVertexStart;
  19626. }
  19627. /**
  19628. * The number of unused indices.
  19629. *
  19630. * @type {number}
  19631. * @readonly
  19632. */
  19633. get unusedIndexCount() {
  19634. return this._maxIndexCount - this._nextIndexStart;
  19635. }
  19636. _initMatricesTexture() {
  19637. // layout (1 matrix = 4 pixels)
  19638. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  19639. // with 8x8 pixel texture max 16 matrices * 4 pixels = (8 * 8)
  19640. // 16x16 pixel texture max 64 matrices * 4 pixels = (16 * 16)
  19641. // 32x32 pixel texture max 256 matrices * 4 pixels = (32 * 32)
  19642. // 64x64 pixel texture max 1024 matrices * 4 pixels = (64 * 64)
  19643. let size = Math.sqrt( this._maxInstanceCount * 4 ); // 4 pixels needed for 1 matrix
  19644. size = Math.ceil( size / 4 ) * 4;
  19645. size = Math.max( size, 4 );
  19646. const matricesArray = new Float32Array( size * size * 4 ); // 4 floats per RGBA pixel
  19647. const matricesTexture = new DataTexture( matricesArray, size, size, RGBAFormat, FloatType );
  19648. this._matricesTexture = matricesTexture;
  19649. }
  19650. _initIndirectTexture() {
  19651. let size = Math.sqrt( this._maxInstanceCount );
  19652. size = Math.ceil( size );
  19653. const indirectArray = new Uint32Array( size * size );
  19654. const indirectTexture = new DataTexture( indirectArray, size, size, RedIntegerFormat, UnsignedIntType );
  19655. this._indirectTexture = indirectTexture;
  19656. }
  19657. _initColorsTexture() {
  19658. let size = Math.sqrt( this._maxInstanceCount );
  19659. size = Math.ceil( size );
  19660. // 4 floats per RGBA pixel initialized to white
  19661. const colorsArray = new Float32Array( size * size * 4 ).fill( 1 );
  19662. const colorsTexture = new DataTexture( colorsArray, size, size, RGBAFormat, FloatType );
  19663. colorsTexture.colorSpace = ColorManagement.workingColorSpace;
  19664. this._colorsTexture = colorsTexture;
  19665. }
  19666. _initializeGeometry( reference ) {
  19667. const geometry = this.geometry;
  19668. const maxVertexCount = this._maxVertexCount;
  19669. const maxIndexCount = this._maxIndexCount;
  19670. if ( this._geometryInitialized === false ) {
  19671. for ( const attributeName in reference.attributes ) {
  19672. const srcAttribute = reference.getAttribute( attributeName );
  19673. const { array, itemSize, normalized } = srcAttribute;
  19674. const dstArray = new array.constructor( maxVertexCount * itemSize );
  19675. const dstAttribute = new BufferAttribute( dstArray, itemSize, normalized );
  19676. geometry.setAttribute( attributeName, dstAttribute );
  19677. }
  19678. if ( reference.getIndex() !== null ) {
  19679. // Reserve last u16 index for primitive restart.
  19680. const indexArray = maxVertexCount > 65535
  19681. ? new Uint32Array( maxIndexCount )
  19682. : new Uint16Array( maxIndexCount );
  19683. geometry.setIndex( new BufferAttribute( indexArray, 1 ) );
  19684. }
  19685. this._geometryInitialized = true;
  19686. }
  19687. }
  19688. // Make sure the geometry is compatible with the existing combined geometry attributes
  19689. _validateGeometry( geometry ) {
  19690. // check to ensure the geometries are using consistent attributes and indices
  19691. const batchGeometry = this.geometry;
  19692. if ( Boolean( geometry.getIndex() ) !== Boolean( batchGeometry.getIndex() ) ) {
  19693. throw new Error( 'THREE.BatchedMesh: All geometries must consistently have "index".' );
  19694. }
  19695. for ( const attributeName in batchGeometry.attributes ) {
  19696. if ( ! geometry.hasAttribute( attributeName ) ) {
  19697. throw new Error( `THREE.BatchedMesh: Added geometry missing "${ attributeName }". All geometries must have consistent attributes.` );
  19698. }
  19699. const srcAttribute = geometry.getAttribute( attributeName );
  19700. const dstAttribute = batchGeometry.getAttribute( attributeName );
  19701. if ( srcAttribute.itemSize !== dstAttribute.itemSize || srcAttribute.normalized !== dstAttribute.normalized ) {
  19702. throw new Error( 'THREE.BatchedMesh: All attributes must have a consistent itemSize and normalized value.' );
  19703. }
  19704. }
  19705. }
  19706. /**
  19707. * Validates the instance defined by the given ID.
  19708. *
  19709. * @param {number} instanceId - The the instance to validate.
  19710. */
  19711. validateInstanceId( instanceId ) {
  19712. const instanceInfo = this._instanceInfo;
  19713. if ( instanceId < 0 || instanceId >= instanceInfo.length || instanceInfo[ instanceId ].active === false ) {
  19714. throw new Error( `THREE.BatchedMesh: Invalid instanceId ${instanceId}. Instance is either out of range or has been deleted.` );
  19715. }
  19716. }
  19717. /**
  19718. * Validates the geometry defined by the given ID.
  19719. *
  19720. * @param {number} geometryId - The the geometry to validate.
  19721. */
  19722. validateGeometryId( geometryId ) {
  19723. const geometryInfoList = this._geometryInfo;
  19724. if ( geometryId < 0 || geometryId >= geometryInfoList.length || geometryInfoList[ geometryId ].active === false ) {
  19725. throw new Error( `THREE.BatchedMesh: Invalid geometryId ${geometryId}. Geometry is either out of range or has been deleted.` );
  19726. }
  19727. }
  19728. /**
  19729. * Takes a sort a function that is run before render. The function takes a list of instances to
  19730. * sort and a camera. The objects in the list include a "z" field to perform a depth-ordered sort with.
  19731. *
  19732. * @param {Function} func - The custom sort function.
  19733. * @return {BatchedMesh} A reference to this batched mesh.
  19734. */
  19735. setCustomSort( func ) {
  19736. this.customSort = func;
  19737. return this;
  19738. }
  19739. /**
  19740. * Computes the bounding box, updating {@link BatchedMesh#boundingBox}.
  19741. * Bounding boxes aren't computed by default. They need to be explicitly computed,
  19742. * otherwise they are `null`.
  19743. */
  19744. computeBoundingBox() {
  19745. if ( this.boundingBox === null ) {
  19746. this.boundingBox = new Box3();
  19747. }
  19748. const boundingBox = this.boundingBox;
  19749. const instanceInfo = this._instanceInfo;
  19750. boundingBox.makeEmpty();
  19751. for ( let i = 0, l = instanceInfo.length; i < l; i ++ ) {
  19752. if ( instanceInfo[ i ].active === false ) continue;
  19753. const geometryId = instanceInfo[ i ].geometryIndex;
  19754. this.getMatrixAt( i, _matrix$1 );
  19755. this.getBoundingBoxAt( geometryId, _box$1 ).applyMatrix4( _matrix$1 );
  19756. boundingBox.union( _box$1 );
  19757. }
  19758. }
  19759. /**
  19760. * Computes the bounding sphere, updating {@link BatchedMesh#boundingSphere}.
  19761. * Bounding spheres aren't computed by default. They need to be explicitly computed,
  19762. * otherwise they are `null`.
  19763. */
  19764. computeBoundingSphere() {
  19765. if ( this.boundingSphere === null ) {
  19766. this.boundingSphere = new Sphere();
  19767. }
  19768. const boundingSphere = this.boundingSphere;
  19769. const instanceInfo = this._instanceInfo;
  19770. boundingSphere.makeEmpty();
  19771. for ( let i = 0, l = instanceInfo.length; i < l; i ++ ) {
  19772. if ( instanceInfo[ i ].active === false ) continue;
  19773. const geometryId = instanceInfo[ i ].geometryIndex;
  19774. this.getMatrixAt( i, _matrix$1 );
  19775. this.getBoundingSphereAt( geometryId, _sphere$2 ).applyMatrix4( _matrix$1 );
  19776. boundingSphere.union( _sphere$2 );
  19777. }
  19778. }
  19779. /**
  19780. * Adds a new instance to the batch using the geometry of the given ID and returns
  19781. * a new id referring to the new instance to be used by other functions.
  19782. *
  19783. * @param {number} geometryId - The ID of a previously added geometry via {@link BatchedMesh#addGeometry}.
  19784. * @return {number} The instance ID.
  19785. */
  19786. addInstance( geometryId ) {
  19787. const atCapacity = this._instanceInfo.length >= this.maxInstanceCount;
  19788. // ensure we're not over geometry
  19789. if ( atCapacity && this._availableInstanceIds.length === 0 ) {
  19790. throw new Error( 'THREE.BatchedMesh: Maximum item count reached.' );
  19791. }
  19792. const instanceInfo = {
  19793. visible: true,
  19794. active: true,
  19795. geometryIndex: geometryId,
  19796. };
  19797. let drawId = null;
  19798. // Prioritize using previously freed instance ids
  19799. if ( this._availableInstanceIds.length > 0 ) {
  19800. this._availableInstanceIds.sort( ascIdSort );
  19801. drawId = this._availableInstanceIds.shift();
  19802. this._instanceInfo[ drawId ] = instanceInfo;
  19803. } else {
  19804. drawId = this._instanceInfo.length;
  19805. this._instanceInfo.push( instanceInfo );
  19806. }
  19807. const matricesTexture = this._matricesTexture;
  19808. _matrix$1.identity().toArray( matricesTexture.image.data, drawId * 16 );
  19809. matricesTexture.needsUpdate = true;
  19810. const colorsTexture = this._colorsTexture;
  19811. if ( colorsTexture ) {
  19812. _whiteColor.toArray( colorsTexture.image.data, drawId * 4 );
  19813. colorsTexture.needsUpdate = true;
  19814. }
  19815. this._visibilityChanged = true;
  19816. return drawId;
  19817. }
  19818. /**
  19819. * Adds the given geometry to the batch and returns the associated
  19820. * geometry id referring to it to be used in other functions.
  19821. *
  19822. * @param {BufferGeometry} geometry - The geometry to add.
  19823. * @param {number} [reservedVertexCount=-1] - Optional parameter specifying the amount of
  19824. * vertex buffer space to reserve for the added geometry. This is necessary if it is planned
  19825. * to set a new geometry at this index at a later time that is larger than the original geometry.
  19826. * Defaults to the length of the given geometry vertex buffer.
  19827. * @param {number} [reservedIndexCount=-1] - Optional parameter specifying the amount of index
  19828. * buffer space to reserve for the added geometry. This is necessary if it is planned to set a
  19829. * new geometry at this index at a later time that is larger than the original geometry. Defaults to
  19830. * the length of the given geometry index buffer.
  19831. * @return {number} The geometry ID.
  19832. */
  19833. addGeometry( geometry, reservedVertexCount = -1, reservedIndexCount = -1 ) {
  19834. this._initializeGeometry( geometry );
  19835. this._validateGeometry( geometry );
  19836. const geometryInfo = {
  19837. // geometry information
  19838. vertexStart: -1,
  19839. vertexCount: -1,
  19840. reservedVertexCount: -1,
  19841. indexStart: -1,
  19842. indexCount: -1,
  19843. reservedIndexCount: -1,
  19844. // draw range information
  19845. start: -1,
  19846. count: -1,
  19847. // state
  19848. boundingBox: null,
  19849. boundingSphere: null,
  19850. active: true,
  19851. };
  19852. const geometryInfoList = this._geometryInfo;
  19853. geometryInfo.vertexStart = this._nextVertexStart;
  19854. geometryInfo.reservedVertexCount = reservedVertexCount === -1 ? geometry.getAttribute( 'position' ).count : reservedVertexCount;
  19855. const index = geometry.getIndex();
  19856. const hasIndex = index !== null;
  19857. if ( hasIndex ) {
  19858. geometryInfo.indexStart = this._nextIndexStart;
  19859. geometryInfo.reservedIndexCount = reservedIndexCount === -1 ? index.count : reservedIndexCount;
  19860. }
  19861. if (
  19862. geometryInfo.indexStart !== -1 &&
  19863. geometryInfo.indexStart + geometryInfo.reservedIndexCount > this._maxIndexCount ||
  19864. geometryInfo.vertexStart + geometryInfo.reservedVertexCount > this._maxVertexCount
  19865. ) {
  19866. throw new Error( 'THREE.BatchedMesh: Reserved space request exceeds the maximum buffer size.' );
  19867. }
  19868. // update id
  19869. let geometryId;
  19870. if ( this._availableGeometryIds.length > 0 ) {
  19871. this._availableGeometryIds.sort( ascIdSort );
  19872. geometryId = this._availableGeometryIds.shift();
  19873. geometryInfoList[ geometryId ] = geometryInfo;
  19874. } else {
  19875. geometryId = this._geometryCount;
  19876. this._geometryCount ++;
  19877. geometryInfoList.push( geometryInfo );
  19878. }
  19879. // update the geometry
  19880. this.setGeometryAt( geometryId, geometry );
  19881. // increment the next geometry position
  19882. this._nextIndexStart = geometryInfo.indexStart + geometryInfo.reservedIndexCount;
  19883. this._nextVertexStart = geometryInfo.vertexStart + geometryInfo.reservedVertexCount;
  19884. return geometryId;
  19885. }
  19886. /**
  19887. * Replaces the geometry at the given ID with the provided geometry. Throws an error if there
  19888. * is not enough space reserved for geometry. Calling this will change all instances that are
  19889. * rendering that geometry.
  19890. *
  19891. * @param {number} geometryId - The ID of the geometry that should be replaced with the given geometry.
  19892. * @param {BufferGeometry} geometry - The new geometry.
  19893. * @return {number} The geometry ID.
  19894. */
  19895. setGeometryAt( geometryId, geometry ) {
  19896. if ( geometryId >= this._geometryCount ) {
  19897. throw new Error( 'THREE.BatchedMesh: Maximum geometry count reached.' );
  19898. }
  19899. this._validateGeometry( geometry );
  19900. const batchGeometry = this.geometry;
  19901. const hasIndex = batchGeometry.getIndex() !== null;
  19902. const dstIndex = batchGeometry.getIndex();
  19903. const srcIndex = geometry.getIndex();
  19904. const geometryInfo = this._geometryInfo[ geometryId ];
  19905. if (
  19906. hasIndex &&
  19907. srcIndex.count > geometryInfo.reservedIndexCount ||
  19908. geometry.attributes.position.count > geometryInfo.reservedVertexCount
  19909. ) {
  19910. throw new Error( 'THREE.BatchedMesh: Reserved space not large enough for provided geometry.' );
  19911. }
  19912. // copy geometry buffer data over
  19913. const vertexStart = geometryInfo.vertexStart;
  19914. const reservedVertexCount = geometryInfo.reservedVertexCount;
  19915. geometryInfo.vertexCount = geometry.getAttribute( 'position' ).count;
  19916. for ( const attributeName in batchGeometry.attributes ) {
  19917. // copy attribute data
  19918. const srcAttribute = geometry.getAttribute( attributeName );
  19919. const dstAttribute = batchGeometry.getAttribute( attributeName );
  19920. copyAttributeData( srcAttribute, dstAttribute, vertexStart );
  19921. // fill the rest in with zeroes
  19922. const itemSize = srcAttribute.itemSize;
  19923. for ( let i = srcAttribute.count, l = reservedVertexCount; i < l; i ++ ) {
  19924. const index = vertexStart + i;
  19925. for ( let c = 0; c < itemSize; c ++ ) {
  19926. dstAttribute.setComponent( index, c, 0 );
  19927. }
  19928. }
  19929. dstAttribute.needsUpdate = true;
  19930. dstAttribute.addUpdateRange( vertexStart * itemSize, reservedVertexCount * itemSize );
  19931. }
  19932. // copy index
  19933. if ( hasIndex ) {
  19934. const indexStart = geometryInfo.indexStart;
  19935. const reservedIndexCount = geometryInfo.reservedIndexCount;
  19936. geometryInfo.indexCount = geometry.getIndex().count;
  19937. // copy index data over
  19938. for ( let i = 0; i < srcIndex.count; i ++ ) {
  19939. dstIndex.setX( indexStart + i, vertexStart + srcIndex.getX( i ) );
  19940. }
  19941. // fill the rest in with zeroes
  19942. for ( let i = srcIndex.count, l = reservedIndexCount; i < l; i ++ ) {
  19943. dstIndex.setX( indexStart + i, vertexStart );
  19944. }
  19945. dstIndex.needsUpdate = true;
  19946. dstIndex.addUpdateRange( indexStart, geometryInfo.reservedIndexCount );
  19947. }
  19948. // update the draw range
  19949. geometryInfo.start = hasIndex ? geometryInfo.indexStart : geometryInfo.vertexStart;
  19950. geometryInfo.count = hasIndex ? geometryInfo.indexCount : geometryInfo.vertexCount;
  19951. // store the bounding boxes
  19952. geometryInfo.boundingBox = null;
  19953. if ( geometry.boundingBox !== null ) {
  19954. geometryInfo.boundingBox = geometry.boundingBox.clone();
  19955. }
  19956. geometryInfo.boundingSphere = null;
  19957. if ( geometry.boundingSphere !== null ) {
  19958. geometryInfo.boundingSphere = geometry.boundingSphere.clone();
  19959. }
  19960. this._visibilityChanged = true;
  19961. return geometryId;
  19962. }
  19963. /**
  19964. * Deletes the geometry defined by the given ID from this batch. Any instances referencing
  19965. * this geometry will also be removed as a side effect.
  19966. *
  19967. * @param {number} geometryId - The ID of the geometry to remove from the batch.
  19968. * @return {BatchedMesh} A reference to this batched mesh.
  19969. */
  19970. deleteGeometry( geometryId ) {
  19971. const geometryInfoList = this._geometryInfo;
  19972. if ( geometryId >= geometryInfoList.length || geometryInfoList[ geometryId ].active === false ) {
  19973. return this;
  19974. }
  19975. // delete any instances associated with this geometry
  19976. const instanceInfo = this._instanceInfo;
  19977. for ( let i = 0, l = instanceInfo.length; i < l; i ++ ) {
  19978. if ( instanceInfo[ i ].active && instanceInfo[ i ].geometryIndex === geometryId ) {
  19979. this.deleteInstance( i );
  19980. }
  19981. }
  19982. geometryInfoList[ geometryId ].active = false;
  19983. this._availableGeometryIds.push( geometryId );
  19984. this._visibilityChanged = true;
  19985. return this;
  19986. }
  19987. /**
  19988. * Deletes an existing instance from the batch using the given ID.
  19989. *
  19990. * @param {number} instanceId - The ID of the instance to remove from the batch.
  19991. * @return {BatchedMesh} A reference to this batched mesh.
  19992. */
  19993. deleteInstance( instanceId ) {
  19994. this.validateInstanceId( instanceId );
  19995. this._instanceInfo[ instanceId ].active = false;
  19996. this._availableInstanceIds.push( instanceId );
  19997. this._visibilityChanged = true;
  19998. return this;
  19999. }
  20000. /**
  20001. * Repacks the sub geometries in [name] to remove any unused space remaining from
  20002. * previously deleted geometry, freeing up space to add new geometry.
  20003. *
  20004. * @param {number} instanceId - The ID of the instance to remove from the batch.
  20005. * @return {BatchedMesh} A reference to this batched mesh.
  20006. */
  20007. optimize() {
  20008. // track the next indices to copy data to
  20009. let nextVertexStart = 0;
  20010. let nextIndexStart = 0;
  20011. // Iterate over all geometry ranges in order sorted from earliest in the geometry buffer to latest
  20012. // in the geometry buffer. Because draw range objects can be reused there is no guarantee of their order.
  20013. const geometryInfoList = this._geometryInfo;
  20014. const indices = geometryInfoList
  20015. .map( ( e, i ) => i )
  20016. .sort( ( a, b ) => {
  20017. return geometryInfoList[ a ].vertexStart - geometryInfoList[ b ].vertexStart;
  20018. } );
  20019. const geometry = this.geometry;
  20020. for ( let i = 0, l = geometryInfoList.length; i < l; i ++ ) {
  20021. // if a geometry range is inactive then don't copy anything
  20022. const index = indices[ i ];
  20023. const geometryInfo = geometryInfoList[ index ];
  20024. if ( geometryInfo.active === false ) {
  20025. continue;
  20026. }
  20027. // if a geometry contains an index buffer then shift it, as well
  20028. if ( geometry.index !== null ) {
  20029. if ( geometryInfo.indexStart !== nextIndexStart ) {
  20030. const { indexStart, vertexStart, reservedIndexCount } = geometryInfo;
  20031. const index = geometry.index;
  20032. const array = index.array;
  20033. // shift the index pointers based on how the vertex data will shift
  20034. // adjusting the index must happen first so the original vertex start value is available
  20035. const elementDelta = nextVertexStart - vertexStart;
  20036. for ( let j = indexStart; j < indexStart + reservedIndexCount; j ++ ) {
  20037. array[ j ] = array[ j ] + elementDelta;
  20038. }
  20039. index.array.copyWithin( nextIndexStart, indexStart, indexStart + reservedIndexCount );
  20040. index.addUpdateRange( nextIndexStart, reservedIndexCount );
  20041. geometryInfo.indexStart = nextIndexStart;
  20042. }
  20043. nextIndexStart += geometryInfo.reservedIndexCount;
  20044. }
  20045. // if a geometry needs to be moved then copy attribute data to overwrite unused space
  20046. if ( geometryInfo.vertexStart !== nextVertexStart ) {
  20047. const { vertexStart, reservedVertexCount } = geometryInfo;
  20048. const attributes = geometry.attributes;
  20049. for ( const key in attributes ) {
  20050. const attribute = attributes[ key ];
  20051. const { array, itemSize } = attribute;
  20052. array.copyWithin( nextVertexStart * itemSize, vertexStart * itemSize, ( vertexStart + reservedVertexCount ) * itemSize );
  20053. attribute.addUpdateRange( nextVertexStart * itemSize, reservedVertexCount * itemSize );
  20054. }
  20055. geometryInfo.vertexStart = nextVertexStart;
  20056. }
  20057. nextVertexStart += geometryInfo.reservedVertexCount;
  20058. geometryInfo.start = geometry.index ? geometryInfo.indexStart : geometryInfo.vertexStart;
  20059. // step the next geometry points to the shifted position
  20060. this._nextIndexStart = geometry.index ? geometryInfo.indexStart + geometryInfo.reservedIndexCount : 0;
  20061. this._nextVertexStart = geometryInfo.vertexStart + geometryInfo.reservedVertexCount;
  20062. }
  20063. return this;
  20064. }
  20065. /**
  20066. * Returns the bounding box for the given geometry.
  20067. *
  20068. * @param {number} geometryId - The ID of the geometry to return the bounding box for.
  20069. * @param {Box3} target - The target object that is used to store the method's result.
  20070. * @return {Box3|null} The geometry's bounding box. Returns `null` if no geometry has been found for the given ID.
  20071. */
  20072. getBoundingBoxAt( geometryId, target ) {
  20073. if ( geometryId >= this._geometryCount ) {
  20074. return null;
  20075. }
  20076. // compute bounding box
  20077. const geometry = this.geometry;
  20078. const geometryInfo = this._geometryInfo[ geometryId ];
  20079. if ( geometryInfo.boundingBox === null ) {
  20080. const box = new Box3();
  20081. const index = geometry.index;
  20082. const position = geometry.attributes.position;
  20083. for ( let i = geometryInfo.start, l = geometryInfo.start + geometryInfo.count; i < l; i ++ ) {
  20084. let iv = i;
  20085. if ( index ) {
  20086. iv = index.getX( iv );
  20087. }
  20088. box.expandByPoint( _vector$5.fromBufferAttribute( position, iv ) );
  20089. }
  20090. geometryInfo.boundingBox = box;
  20091. }
  20092. target.copy( geometryInfo.boundingBox );
  20093. return target;
  20094. }
  20095. /**
  20096. * Returns the bounding sphere for the given geometry.
  20097. *
  20098. * @param {number} geometryId - The ID of the geometry to return the bounding sphere for.
  20099. * @param {Sphere} target - The target object that is used to store the method's result.
  20100. * @return {Sphere|null} The geometry's bounding sphere. Returns `null` if no geometry has been found for the given ID.
  20101. */
  20102. getBoundingSphereAt( geometryId, target ) {
  20103. if ( geometryId >= this._geometryCount ) {
  20104. return null;
  20105. }
  20106. // compute bounding sphere
  20107. const geometry = this.geometry;
  20108. const geometryInfo = this._geometryInfo[ geometryId ];
  20109. if ( geometryInfo.boundingSphere === null ) {
  20110. const sphere = new Sphere();
  20111. this.getBoundingBoxAt( geometryId, _box$1 );
  20112. _box$1.getCenter( sphere.center );
  20113. const index = geometry.index;
  20114. const position = geometry.attributes.position;
  20115. let maxRadiusSq = 0;
  20116. for ( let i = geometryInfo.start, l = geometryInfo.start + geometryInfo.count; i < l; i ++ ) {
  20117. let iv = i;
  20118. if ( index ) {
  20119. iv = index.getX( iv );
  20120. }
  20121. _vector$5.fromBufferAttribute( position, iv );
  20122. maxRadiusSq = Math.max( maxRadiusSq, sphere.center.distanceToSquared( _vector$5 ) );
  20123. }
  20124. sphere.radius = Math.sqrt( maxRadiusSq );
  20125. geometryInfo.boundingSphere = sphere;
  20126. }
  20127. target.copy( geometryInfo.boundingSphere );
  20128. return target;
  20129. }
  20130. /**
  20131. * Sets the given local transformation matrix to the defined instance.
  20132. * Negatively scaled matrices are not supported.
  20133. *
  20134. * @param {number} instanceId - The ID of an instance to set the matrix of.
  20135. * @param {Matrix4} matrix - A 4x4 matrix representing the local transformation of a single instance.
  20136. * @return {BatchedMesh} A reference to this batched mesh.
  20137. */
  20138. setMatrixAt( instanceId, matrix ) {
  20139. this.validateInstanceId( instanceId );
  20140. const matricesTexture = this._matricesTexture;
  20141. const matricesArray = this._matricesTexture.image.data;
  20142. matrix.toArray( matricesArray, instanceId * 16 );
  20143. matricesTexture.needsUpdate = true;
  20144. return this;
  20145. }
  20146. /**
  20147. * Returns the local transformation matrix of the defined instance.
  20148. *
  20149. * @param {number} instanceId - The ID of an instance to get the matrix of.
  20150. * @param {Matrix4} matrix - The target object that is used to store the method's result.
  20151. * @return {Matrix4} The instance's local transformation matrix.
  20152. */
  20153. getMatrixAt( instanceId, matrix ) {
  20154. this.validateInstanceId( instanceId );
  20155. return matrix.fromArray( this._matricesTexture.image.data, instanceId * 16 );
  20156. }
  20157. /**
  20158. * Sets the given color to the defined instance.
  20159. *
  20160. * @param {number} instanceId - The ID of an instance to set the color of.
  20161. * @param {Color} color - The color to set the instance to.
  20162. * @return {BatchedMesh} A reference to this batched mesh.
  20163. */
  20164. setColorAt( instanceId, color ) {
  20165. this.validateInstanceId( instanceId );
  20166. if ( this._colorsTexture === null ) {
  20167. this._initColorsTexture();
  20168. }
  20169. color.toArray( this._colorsTexture.image.data, instanceId * 4 );
  20170. this._colorsTexture.needsUpdate = true;
  20171. return this;
  20172. }
  20173. /**
  20174. * Returns the color of the defined instance.
  20175. *
  20176. * @param {number} instanceId - The ID of an instance to get the color of.
  20177. * @param {Color} color - The target object that is used to store the method's result.
  20178. * @return {Color} The instance's color.
  20179. */
  20180. getColorAt( instanceId, color ) {
  20181. this.validateInstanceId( instanceId );
  20182. return color.fromArray( this._colorsTexture.image.data, instanceId * 4 );
  20183. }
  20184. /**
  20185. * Sets the visibility of the instance.
  20186. *
  20187. * @param {number} instanceId - The id of the instance to set the visibility of.
  20188. * @param {boolean} visible - Whether the instance is visible or not.
  20189. * @return {BatchedMesh} A reference to this batched mesh.
  20190. */
  20191. setVisibleAt( instanceId, visible ) {
  20192. this.validateInstanceId( instanceId );
  20193. if ( this._instanceInfo[ instanceId ].visible === visible ) {
  20194. return this;
  20195. }
  20196. this._instanceInfo[ instanceId ].visible = visible;
  20197. this._visibilityChanged = true;
  20198. return this;
  20199. }
  20200. /**
  20201. * Returns the visibility state of the defined instance.
  20202. *
  20203. * @param {number} instanceId - The ID of an instance to get the visibility state of.
  20204. * @return {boolean} Whether the instance is visible or not.
  20205. */
  20206. getVisibleAt( instanceId ) {
  20207. this.validateInstanceId( instanceId );
  20208. return this._instanceInfo[ instanceId ].visible;
  20209. }
  20210. /**
  20211. * Sets the geometry ID of the instance at the given index.
  20212. *
  20213. * @param {number} instanceId - The ID of the instance to set the geometry ID of.
  20214. * @param {number} geometryId - The geometry ID to be use by the instance.
  20215. * @return {BatchedMesh} A reference to this batched mesh.
  20216. */
  20217. setGeometryIdAt( instanceId, geometryId ) {
  20218. this.validateInstanceId( instanceId );
  20219. this.validateGeometryId( geometryId );
  20220. this._instanceInfo[ instanceId ].geometryIndex = geometryId;
  20221. return this;
  20222. }
  20223. /**
  20224. * Returns the geometry ID of the defined instance.
  20225. *
  20226. * @param {number} instanceId - The ID of an instance to get the geometry ID of.
  20227. * @return {number} The instance's geometry ID.
  20228. */
  20229. getGeometryIdAt( instanceId ) {
  20230. this.validateInstanceId( instanceId );
  20231. return this._instanceInfo[ instanceId ].geometryIndex;
  20232. }
  20233. /**
  20234. * Get the range representing the subset of triangles related to the attached geometry,
  20235. * indicating the starting offset and count, or `null` if invalid.
  20236. *
  20237. * @param {number} geometryId - The id of the geometry to get the range of.
  20238. * @param {Object} [target] - The target object that is used to store the method's result.
  20239. * @return {{
  20240. * vertexStart:number,vertexCount:number,reservedVertexCount:number,
  20241. * indexStart:number,indexCount:number,reservedIndexCount:number,
  20242. * start:number,count:number
  20243. * }} The result object with range data.
  20244. */
  20245. getGeometryRangeAt( geometryId, target = {} ) {
  20246. this.validateGeometryId( geometryId );
  20247. const geometryInfo = this._geometryInfo[ geometryId ];
  20248. target.vertexStart = geometryInfo.vertexStart;
  20249. target.vertexCount = geometryInfo.vertexCount;
  20250. target.reservedVertexCount = geometryInfo.reservedVertexCount;
  20251. target.indexStart = geometryInfo.indexStart;
  20252. target.indexCount = geometryInfo.indexCount;
  20253. target.reservedIndexCount = geometryInfo.reservedIndexCount;
  20254. target.start = geometryInfo.start;
  20255. target.count = geometryInfo.count;
  20256. return target;
  20257. }
  20258. /**
  20259. * Resizes the necessary buffers to support the provided number of instances.
  20260. * If the provided arguments shrink the number of instances but there are not enough
  20261. * unused Ids at the end of the list then an error is thrown.
  20262. *
  20263. * @param {number} maxInstanceCount - The max number of individual instances that can be added and rendered by the batch.
  20264. */
  20265. setInstanceCount( maxInstanceCount ) {
  20266. // shrink the available instances as much as possible
  20267. const availableInstanceIds = this._availableInstanceIds;
  20268. const instanceInfo = this._instanceInfo;
  20269. availableInstanceIds.sort( ascIdSort );
  20270. while ( availableInstanceIds[ availableInstanceIds.length - 1 ] === instanceInfo.length ) {
  20271. instanceInfo.pop();
  20272. availableInstanceIds.pop();
  20273. }
  20274. // throw an error if it can't be shrunk to the desired size
  20275. if ( maxInstanceCount < instanceInfo.length ) {
  20276. throw new Error( `BatchedMesh: Instance ids outside the range ${ maxInstanceCount } are being used. Cannot shrink instance count.` );
  20277. }
  20278. // copy the multi draw counts
  20279. const multiDrawCounts = new Int32Array( maxInstanceCount );
  20280. const multiDrawStarts = new Int32Array( maxInstanceCount );
  20281. copyArrayContents( this._multiDrawCounts, multiDrawCounts );
  20282. copyArrayContents( this._multiDrawStarts, multiDrawStarts );
  20283. this._multiDrawCounts = multiDrawCounts;
  20284. this._multiDrawStarts = multiDrawStarts;
  20285. this._maxInstanceCount = maxInstanceCount;
  20286. // update texture data for instance sampling
  20287. const indirectTexture = this._indirectTexture;
  20288. const matricesTexture = this._matricesTexture;
  20289. const colorsTexture = this._colorsTexture;
  20290. indirectTexture.dispose();
  20291. this._initIndirectTexture();
  20292. copyArrayContents( indirectTexture.image.data, this._indirectTexture.image.data );
  20293. matricesTexture.dispose();
  20294. this._initMatricesTexture();
  20295. copyArrayContents( matricesTexture.image.data, this._matricesTexture.image.data );
  20296. if ( colorsTexture ) {
  20297. colorsTexture.dispose();
  20298. this._initColorsTexture();
  20299. copyArrayContents( colorsTexture.image.data, this._colorsTexture.image.data );
  20300. }
  20301. }
  20302. /**
  20303. * Resizes the available space in the batch's vertex and index buffer attributes to the provided sizes.
  20304. * If the provided arguments shrink the geometry buffers but there is not enough unused space at the
  20305. * end of the geometry attributes then an error is thrown.
  20306. *
  20307. * @param {number} maxVertexCount - The maximum number of vertices to be used by all unique geometries to resize to.
  20308. * @param {number} maxIndexCount - The maximum number of indices to be used by all unique geometries to resize to.
  20309. */
  20310. setGeometrySize( maxVertexCount, maxIndexCount ) {
  20311. // Check if we can shrink to the requested vertex attribute size
  20312. const validRanges = [ ...this._geometryInfo ].filter( info => info.active );
  20313. const requiredVertexLength = Math.max( ...validRanges.map( range => range.vertexStart + range.reservedVertexCount ) );
  20314. if ( requiredVertexLength > maxVertexCount ) {
  20315. throw new Error( `BatchedMesh: Geometry vertex values are being used outside the range ${ maxIndexCount }. Cannot shrink further.` );
  20316. }
  20317. // Check if we can shrink to the requested index attribute size
  20318. if ( this.geometry.index ) {
  20319. const requiredIndexLength = Math.max( ...validRanges.map( range => range.indexStart + range.reservedIndexCount ) );
  20320. if ( requiredIndexLength > maxIndexCount ) {
  20321. throw new Error( `BatchedMesh: Geometry index values are being used outside the range ${ maxIndexCount }. Cannot shrink further.` );
  20322. }
  20323. }
  20324. //
  20325. // dispose of the previous geometry
  20326. const oldGeometry = this.geometry;
  20327. oldGeometry.dispose();
  20328. // recreate the geometry needed based on the previous variant
  20329. this._maxVertexCount = maxVertexCount;
  20330. this._maxIndexCount = maxIndexCount;
  20331. if ( this._geometryInitialized ) {
  20332. this._geometryInitialized = false;
  20333. this.geometry = new BufferGeometry();
  20334. this._initializeGeometry( oldGeometry );
  20335. }
  20336. // copy data from the previous geometry
  20337. const geometry = this.geometry;
  20338. if ( oldGeometry.index ) {
  20339. copyArrayContents( oldGeometry.index.array, geometry.index.array );
  20340. }
  20341. for ( const key in oldGeometry.attributes ) {
  20342. copyArrayContents( oldGeometry.attributes[ key ].array, geometry.attributes[ key ].array );
  20343. }
  20344. }
  20345. raycast( raycaster, intersects ) {
  20346. const instanceInfo = this._instanceInfo;
  20347. const geometryInfoList = this._geometryInfo;
  20348. const matrixWorld = this.matrixWorld;
  20349. const batchGeometry = this.geometry;
  20350. // iterate over each geometry
  20351. _mesh.material = this.material;
  20352. _mesh.geometry.index = batchGeometry.index;
  20353. _mesh.geometry.attributes = batchGeometry.attributes;
  20354. if ( _mesh.geometry.boundingBox === null ) {
  20355. _mesh.geometry.boundingBox = new Box3();
  20356. }
  20357. if ( _mesh.geometry.boundingSphere === null ) {
  20358. _mesh.geometry.boundingSphere = new Sphere();
  20359. }
  20360. for ( let i = 0, l = instanceInfo.length; i < l; i ++ ) {
  20361. if ( ! instanceInfo[ i ].visible || ! instanceInfo[ i ].active ) {
  20362. continue;
  20363. }
  20364. const geometryId = instanceInfo[ i ].geometryIndex;
  20365. const geometryInfo = geometryInfoList[ geometryId ];
  20366. _mesh.geometry.setDrawRange( geometryInfo.start, geometryInfo.count );
  20367. // get the intersects
  20368. this.getMatrixAt( i, _mesh.matrixWorld ).premultiply( matrixWorld );
  20369. this.getBoundingBoxAt( geometryId, _mesh.geometry.boundingBox );
  20370. this.getBoundingSphereAt( geometryId, _mesh.geometry.boundingSphere );
  20371. _mesh.raycast( raycaster, _batchIntersects );
  20372. // add batch id to the intersects
  20373. for ( let j = 0, l = _batchIntersects.length; j < l; j ++ ) {
  20374. const intersect = _batchIntersects[ j ];
  20375. intersect.object = this;
  20376. intersect.batchId = i;
  20377. intersects.push( intersect );
  20378. }
  20379. _batchIntersects.length = 0;
  20380. }
  20381. _mesh.material = null;
  20382. _mesh.geometry.index = null;
  20383. _mesh.geometry.attributes = {};
  20384. _mesh.geometry.setDrawRange( 0, Infinity );
  20385. }
  20386. copy( source ) {
  20387. super.copy( source );
  20388. this.geometry = source.geometry.clone();
  20389. this.perObjectFrustumCulled = source.perObjectFrustumCulled;
  20390. this.sortObjects = source.sortObjects;
  20391. this.boundingBox = source.boundingBox !== null ? source.boundingBox.clone() : null;
  20392. this.boundingSphere = source.boundingSphere !== null ? source.boundingSphere.clone() : null;
  20393. this._geometryInfo = source._geometryInfo.map( info => ( {
  20394. ...info,
  20395. boundingBox: info.boundingBox !== null ? info.boundingBox.clone() : null,
  20396. boundingSphere: info.boundingSphere !== null ? info.boundingSphere.clone() : null,
  20397. } ) );
  20398. this._instanceInfo = source._instanceInfo.map( info => ( { ...info } ) );
  20399. this._maxInstanceCount = source._maxInstanceCount;
  20400. this._maxVertexCount = source._maxVertexCount;
  20401. this._maxIndexCount = source._maxIndexCount;
  20402. this._geometryInitialized = source._geometryInitialized;
  20403. this._geometryCount = source._geometryCount;
  20404. this._multiDrawCounts = source._multiDrawCounts.slice();
  20405. this._multiDrawStarts = source._multiDrawStarts.slice();
  20406. this._matricesTexture = source._matricesTexture.clone();
  20407. this._matricesTexture.image.data = this._matricesTexture.image.data.slice();
  20408. if ( this._colorsTexture !== null ) {
  20409. this._colorsTexture = source._colorsTexture.clone();
  20410. this._colorsTexture.image.data = this._colorsTexture.image.data.slice();
  20411. }
  20412. return this;
  20413. }
  20414. /**
  20415. * Frees the GPU-related resources allocated by this instance. Call this
  20416. * method whenever this instance is no longer used in your app.
  20417. */
  20418. dispose() {
  20419. // Assuming the geometry is not shared with other meshes
  20420. this.geometry.dispose();
  20421. this._matricesTexture.dispose();
  20422. this._matricesTexture = null;
  20423. this._indirectTexture.dispose();
  20424. this._indirectTexture = null;
  20425. if ( this._colorsTexture !== null ) {
  20426. this._colorsTexture.dispose();
  20427. this._colorsTexture = null;
  20428. }
  20429. }
  20430. onBeforeRender( renderer, scene, camera, geometry, material/*, _group*/ ) {
  20431. // if visibility has not changed and frustum culling and object sorting is not required
  20432. // then skip iterating over all items
  20433. if ( ! this._visibilityChanged && ! this.perObjectFrustumCulled && ! this.sortObjects ) {
  20434. return;
  20435. }
  20436. // the indexed version of the multi draw function requires specifying the start
  20437. // offset in bytes.
  20438. const index = geometry.getIndex();
  20439. const bytesPerElement = index === null ? 1 : index.array.BYTES_PER_ELEMENT;
  20440. const instanceInfo = this._instanceInfo;
  20441. const multiDrawStarts = this._multiDrawStarts;
  20442. const multiDrawCounts = this._multiDrawCounts;
  20443. const geometryInfoList = this._geometryInfo;
  20444. const perObjectFrustumCulled = this.perObjectFrustumCulled;
  20445. const indirectTexture = this._indirectTexture;
  20446. const indirectArray = indirectTexture.image.data;
  20447. // prepare the frustum in the local frame
  20448. if ( perObjectFrustumCulled ) {
  20449. _matrix$1
  20450. .multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse )
  20451. .multiply( this.matrixWorld );
  20452. _frustum.setFromProjectionMatrix(
  20453. _matrix$1,
  20454. renderer.coordinateSystem
  20455. );
  20456. }
  20457. let multiDrawCount = 0;
  20458. if ( this.sortObjects ) {
  20459. // get the camera position in the local frame
  20460. _matrix$1.copy( this.matrixWorld ).invert();
  20461. _vector$5.setFromMatrixPosition( camera.matrixWorld ).applyMatrix4( _matrix$1 );
  20462. _forward.set( 0, 0, -1 ).transformDirection( camera.matrixWorld ).transformDirection( _matrix$1 );
  20463. for ( let i = 0, l = instanceInfo.length; i < l; i ++ ) {
  20464. if ( instanceInfo[ i ].visible && instanceInfo[ i ].active ) {
  20465. const geometryId = instanceInfo[ i ].geometryIndex;
  20466. // get the bounds in world space
  20467. this.getMatrixAt( i, _matrix$1 );
  20468. this.getBoundingSphereAt( geometryId, _sphere$2 ).applyMatrix4( _matrix$1 );
  20469. // determine whether the batched geometry is within the frustum
  20470. let culled = false;
  20471. if ( perObjectFrustumCulled ) {
  20472. culled = ! _frustum.intersectsSphere( _sphere$2 );
  20473. }
  20474. if ( ! culled ) {
  20475. // get the distance from camera used for sorting
  20476. const geometryInfo = geometryInfoList[ geometryId ];
  20477. const z = _temp.subVectors( _sphere$2.center, _vector$5 ).dot( _forward );
  20478. _renderList.push( geometryInfo.start, geometryInfo.count, z, i );
  20479. }
  20480. }
  20481. }
  20482. // Sort the draw ranges and prep for rendering
  20483. const list = _renderList.list;
  20484. const customSort = this.customSort;
  20485. if ( customSort === null ) {
  20486. list.sort( material.transparent ? sortTransparent : sortOpaque );
  20487. } else {
  20488. customSort.call( this, list, camera );
  20489. }
  20490. for ( let i = 0, l = list.length; i < l; i ++ ) {
  20491. const item = list[ i ];
  20492. multiDrawStarts[ multiDrawCount ] = item.start * bytesPerElement;
  20493. multiDrawCounts[ multiDrawCount ] = item.count;
  20494. indirectArray[ multiDrawCount ] = item.index;
  20495. multiDrawCount ++;
  20496. }
  20497. _renderList.reset();
  20498. } else {
  20499. for ( let i = 0, l = instanceInfo.length; i < l; i ++ ) {
  20500. if ( instanceInfo[ i ].visible && instanceInfo[ i ].active ) {
  20501. const geometryId = instanceInfo[ i ].geometryIndex;
  20502. // determine whether the batched geometry is within the frustum
  20503. let culled = false;
  20504. if ( perObjectFrustumCulled ) {
  20505. // get the bounds in world space
  20506. this.getMatrixAt( i, _matrix$1 );
  20507. this.getBoundingSphereAt( geometryId, _sphere$2 ).applyMatrix4( _matrix$1 );
  20508. culled = ! _frustum.intersectsSphere( _sphere$2 );
  20509. }
  20510. if ( ! culled ) {
  20511. const geometryInfo = geometryInfoList[ geometryId ];
  20512. multiDrawStarts[ multiDrawCount ] = geometryInfo.start * bytesPerElement;
  20513. multiDrawCounts[ multiDrawCount ] = geometryInfo.count;
  20514. indirectArray[ multiDrawCount ] = i;
  20515. multiDrawCount ++;
  20516. }
  20517. }
  20518. }
  20519. }
  20520. indirectTexture.needsUpdate = true;
  20521. this._multiDrawCount = multiDrawCount;
  20522. this._visibilityChanged = false;
  20523. }
  20524. onBeforeShadow( renderer, object, camera, shadowCamera, geometry, depthMaterial/* , group */ ) {
  20525. this.onBeforeRender( renderer, null, shadowCamera, geometry, depthMaterial );
  20526. }
  20527. }
  20528. /**
  20529. * A material for rendering line primitives.
  20530. *
  20531. * Materials define the appearance of renderable 3D objects.
  20532. *
  20533. * ```js
  20534. * const material = new THREE.LineBasicMaterial( { color: 0xffffff } );
  20535. * ```
  20536. *
  20537. * @augments Material
  20538. */
  20539. class LineBasicMaterial extends Material {
  20540. /**
  20541. * Constructs a new line basic material.
  20542. *
  20543. * @param {Object} [parameters] - An object with one or more properties
  20544. * defining the material's appearance. Any property of the material
  20545. * (including any property from inherited materials) can be passed
  20546. * in here. Color values can be passed any type of value accepted
  20547. * by {@link Color#set}.
  20548. */
  20549. constructor( parameters ) {
  20550. super();
  20551. /**
  20552. * This flag can be used for type testing.
  20553. *
  20554. * @type {boolean}
  20555. * @readonly
  20556. * @default true
  20557. */
  20558. this.isLineBasicMaterial = true;
  20559. this.type = 'LineBasicMaterial';
  20560. /**
  20561. * Color of the material.
  20562. *
  20563. * @type {Color}
  20564. * @default (1,1,1)
  20565. */
  20566. this.color = new Color( 0xffffff );
  20567. /**
  20568. * Sets the color of the lines using data from a texture. The texture map
  20569. * color is modulated by the diffuse `color`.
  20570. *
  20571. * @type {?Texture}
  20572. * @default null
  20573. */
  20574. this.map = null;
  20575. /**
  20576. * Controls line thickness or lines.
  20577. *
  20578. * Can only be used with {@link SVGRenderer}. WebGL and WebGPU
  20579. * ignore this setting and always render line primitives with a
  20580. * width of one pixel.
  20581. *
  20582. * @type {number}
  20583. * @default 1
  20584. */
  20585. this.linewidth = 1;
  20586. /**
  20587. * Defines appearance of line ends.
  20588. *
  20589. * Can only be used with {@link SVGRenderer}.
  20590. *
  20591. * @type {('butt'|'round'|'square')}
  20592. * @default 'round'
  20593. */
  20594. this.linecap = 'round';
  20595. /**
  20596. * Defines appearance of line joints.
  20597. *
  20598. * Can only be used with {@link SVGRenderer}.
  20599. *
  20600. * @type {('round'|'bevel'|'miter')}
  20601. * @default 'round'
  20602. */
  20603. this.linejoin = 'round';
  20604. /**
  20605. * Whether the material is affected by fog or not.
  20606. *
  20607. * @type {boolean}
  20608. * @default true
  20609. */
  20610. this.fog = true;
  20611. this.setValues( parameters );
  20612. }
  20613. copy( source ) {
  20614. super.copy( source );
  20615. this.color.copy( source.color );
  20616. this.map = source.map;
  20617. this.linewidth = source.linewidth;
  20618. this.linecap = source.linecap;
  20619. this.linejoin = source.linejoin;
  20620. this.fog = source.fog;
  20621. return this;
  20622. }
  20623. }
  20624. const _vStart = /*@__PURE__*/ new Vector3();
  20625. const _vEnd = /*@__PURE__*/ new Vector3();
  20626. const _inverseMatrix$1 = /*@__PURE__*/ new Matrix4();
  20627. const _ray$1 = /*@__PURE__*/ new Ray();
  20628. const _sphere$1 = /*@__PURE__*/ new Sphere();
  20629. const _intersectPointOnRay = /*@__PURE__*/ new Vector3();
  20630. const _intersectPointOnSegment = /*@__PURE__*/ new Vector3();
  20631. /**
  20632. * A continuous line. The line are rendered by connecting consecutive
  20633. * vertices with straight lines.
  20634. *
  20635. * ```js
  20636. * const material = new THREE.LineBasicMaterial( { color: 0x0000ff } );
  20637. *
  20638. * const points = [];
  20639. * points.push( new THREE.Vector3( - 10, 0, 0 ) );
  20640. * points.push( new THREE.Vector3( 0, 10, 0 ) );
  20641. * points.push( new THREE.Vector3( 10, 0, 0 ) );
  20642. *
  20643. * const geometry = new THREE.BufferGeometry().setFromPoints( points );
  20644. *
  20645. * const line = new THREE.Line( geometry, material );
  20646. * scene.add( line );
  20647. * ```
  20648. *
  20649. * @augments Object3D
  20650. */
  20651. class Line extends Object3D {
  20652. /**
  20653. * Constructs a new line.
  20654. *
  20655. * @param {BufferGeometry} [geometry] - The line geometry.
  20656. * @param {Material|Array<Material>} [material] - The line material.
  20657. */
  20658. constructor( geometry = new BufferGeometry(), material = new LineBasicMaterial() ) {
  20659. super();
  20660. /**
  20661. * This flag can be used for type testing.
  20662. *
  20663. * @type {boolean}
  20664. * @readonly
  20665. * @default true
  20666. */
  20667. this.isLine = true;
  20668. this.type = 'Line';
  20669. /**
  20670. * The line geometry.
  20671. *
  20672. * @type {BufferGeometry}
  20673. */
  20674. this.geometry = geometry;
  20675. /**
  20676. * The line material.
  20677. *
  20678. * @type {Material|Array<Material>}
  20679. * @default LineBasicMaterial
  20680. */
  20681. this.material = material;
  20682. /**
  20683. * A dictionary representing the morph targets in the geometry. The key is the
  20684. * morph targets name, the value its attribute index. This member is `undefined`
  20685. * by default and only set when morph targets are detected in the geometry.
  20686. *
  20687. * @type {Object<String,number>|undefined}
  20688. * @default undefined
  20689. */
  20690. this.morphTargetDictionary = undefined;
  20691. /**
  20692. * An array of weights typically in the range `[0,1]` that specify how much of the morph
  20693. * is applied. This member is `undefined` by default and only set when morph targets are
  20694. * detected in the geometry.
  20695. *
  20696. * @type {Array<number>|undefined}
  20697. * @default undefined
  20698. */
  20699. this.morphTargetInfluences = undefined;
  20700. this.updateMorphTargets();
  20701. }
  20702. copy( source, recursive ) {
  20703. super.copy( source, recursive );
  20704. this.material = Array.isArray( source.material ) ? source.material.slice() : source.material;
  20705. this.geometry = source.geometry;
  20706. return this;
  20707. }
  20708. /**
  20709. * Computes an array of distance values which are necessary for rendering dashed lines.
  20710. * For each vertex in the geometry, the method calculates the cumulative length from the
  20711. * current point to the very beginning of the line.
  20712. *
  20713. * @return {Line} A reference to this line.
  20714. */
  20715. computeLineDistances() {
  20716. const geometry = this.geometry;
  20717. // we assume non-indexed geometry
  20718. if ( geometry.index === null ) {
  20719. const positionAttribute = geometry.attributes.position;
  20720. const lineDistances = [ 0 ];
  20721. for ( let i = 1, l = positionAttribute.count; i < l; i ++ ) {
  20722. _vStart.fromBufferAttribute( positionAttribute, i - 1 );
  20723. _vEnd.fromBufferAttribute( positionAttribute, i );
  20724. lineDistances[ i ] = lineDistances[ i - 1 ];
  20725. lineDistances[ i ] += _vStart.distanceTo( _vEnd );
  20726. }
  20727. geometry.setAttribute( 'lineDistance', new Float32BufferAttribute( lineDistances, 1 ) );
  20728. } else {
  20729. console.warn( 'THREE.Line.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.' );
  20730. }
  20731. return this;
  20732. }
  20733. /**
  20734. * Computes intersection points between a casted ray and this line.
  20735. *
  20736. * @param {Raycaster} raycaster - The raycaster.
  20737. * @param {Array<Object>} intersects - The target array that holds the intersection points.
  20738. */
  20739. raycast( raycaster, intersects ) {
  20740. const geometry = this.geometry;
  20741. const matrixWorld = this.matrixWorld;
  20742. const threshold = raycaster.params.Line.threshold;
  20743. const drawRange = geometry.drawRange;
  20744. // Checking boundingSphere distance to ray
  20745. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  20746. _sphere$1.copy( geometry.boundingSphere );
  20747. _sphere$1.applyMatrix4( matrixWorld );
  20748. _sphere$1.radius += threshold;
  20749. if ( raycaster.ray.intersectsSphere( _sphere$1 ) === false ) return;
  20750. //
  20751. _inverseMatrix$1.copy( matrixWorld ).invert();
  20752. _ray$1.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$1 );
  20753. const localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 );
  20754. const localThresholdSq = localThreshold * localThreshold;
  20755. const step = this.isLineSegments ? 2 : 1;
  20756. const index = geometry.index;
  20757. const attributes = geometry.attributes;
  20758. const positionAttribute = attributes.position;
  20759. if ( index !== null ) {
  20760. const start = Math.max( 0, drawRange.start );
  20761. const end = Math.min( index.count, ( drawRange.start + drawRange.count ) );
  20762. for ( let i = start, l = end - 1; i < l; i += step ) {
  20763. const a = index.getX( i );
  20764. const b = index.getX( i + 1 );
  20765. const intersect = checkIntersection( this, raycaster, _ray$1, localThresholdSq, a, b, i );
  20766. if ( intersect ) {
  20767. intersects.push( intersect );
  20768. }
  20769. }
  20770. if ( this.isLineLoop ) {
  20771. const a = index.getX( end - 1 );
  20772. const b = index.getX( start );
  20773. const intersect = checkIntersection( this, raycaster, _ray$1, localThresholdSq, a, b, end - 1 );
  20774. if ( intersect ) {
  20775. intersects.push( intersect );
  20776. }
  20777. }
  20778. } else {
  20779. const start = Math.max( 0, drawRange.start );
  20780. const end = Math.min( positionAttribute.count, ( drawRange.start + drawRange.count ) );
  20781. for ( let i = start, l = end - 1; i < l; i += step ) {
  20782. const intersect = checkIntersection( this, raycaster, _ray$1, localThresholdSq, i, i + 1, i );
  20783. if ( intersect ) {
  20784. intersects.push( intersect );
  20785. }
  20786. }
  20787. if ( this.isLineLoop ) {
  20788. const intersect = checkIntersection( this, raycaster, _ray$1, localThresholdSq, end - 1, start, end - 1 );
  20789. if ( intersect ) {
  20790. intersects.push( intersect );
  20791. }
  20792. }
  20793. }
  20794. }
  20795. /**
  20796. * Sets the values of {@link Line#morphTargetDictionary} and {@link Line#morphTargetInfluences}
  20797. * to make sure existing morph targets can influence this 3D object.
  20798. */
  20799. updateMorphTargets() {
  20800. const geometry = this.geometry;
  20801. const morphAttributes = geometry.morphAttributes;
  20802. const keys = Object.keys( morphAttributes );
  20803. if ( keys.length > 0 ) {
  20804. const morphAttribute = morphAttributes[ keys[ 0 ] ];
  20805. if ( morphAttribute !== undefined ) {
  20806. this.morphTargetInfluences = [];
  20807. this.morphTargetDictionary = {};
  20808. for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  20809. const name = morphAttribute[ m ].name || String( m );
  20810. this.morphTargetInfluences.push( 0 );
  20811. this.morphTargetDictionary[ name ] = m;
  20812. }
  20813. }
  20814. }
  20815. }
  20816. }
  20817. function checkIntersection( object, raycaster, ray, thresholdSq, a, b, i ) {
  20818. const positionAttribute = object.geometry.attributes.position;
  20819. _vStart.fromBufferAttribute( positionAttribute, a );
  20820. _vEnd.fromBufferAttribute( positionAttribute, b );
  20821. const distSq = ray.distanceSqToSegment( _vStart, _vEnd, _intersectPointOnRay, _intersectPointOnSegment );
  20822. if ( distSq > thresholdSq ) return;
  20823. _intersectPointOnRay.applyMatrix4( object.matrixWorld ); // Move back to world space for distance calculation
  20824. const distance = raycaster.ray.origin.distanceTo( _intersectPointOnRay );
  20825. if ( distance < raycaster.near || distance > raycaster.far ) return;
  20826. return {
  20827. distance: distance,
  20828. // What do we want? intersection point on the ray or on the segment??
  20829. // point: raycaster.ray.at( distance ),
  20830. point: _intersectPointOnSegment.clone().applyMatrix4( object.matrixWorld ),
  20831. index: i,
  20832. face: null,
  20833. faceIndex: null,
  20834. barycoord: null,
  20835. object: object
  20836. };
  20837. }
  20838. const _start = /*@__PURE__*/ new Vector3();
  20839. const _end = /*@__PURE__*/ new Vector3();
  20840. /**
  20841. * A series of lines drawn between pairs of vertices.
  20842. *
  20843. * @augments Line
  20844. */
  20845. class LineSegments extends Line {
  20846. /**
  20847. * Constructs a new line segments.
  20848. *
  20849. * @param {BufferGeometry} [geometry] - The line geometry.
  20850. * @param {Material|Array<Material>} [material] - The line material.
  20851. */
  20852. constructor( geometry, material ) {
  20853. super( geometry, material );
  20854. /**
  20855. * This flag can be used for type testing.
  20856. *
  20857. * @type {boolean}
  20858. * @readonly
  20859. * @default true
  20860. */
  20861. this.isLineSegments = true;
  20862. this.type = 'LineSegments';
  20863. }
  20864. computeLineDistances() {
  20865. const geometry = this.geometry;
  20866. // we assume non-indexed geometry
  20867. if ( geometry.index === null ) {
  20868. const positionAttribute = geometry.attributes.position;
  20869. const lineDistances = [];
  20870. for ( let i = 0, l = positionAttribute.count; i < l; i += 2 ) {
  20871. _start.fromBufferAttribute( positionAttribute, i );
  20872. _end.fromBufferAttribute( positionAttribute, i + 1 );
  20873. lineDistances[ i ] = ( i === 0 ) ? 0 : lineDistances[ i - 1 ];
  20874. lineDistances[ i + 1 ] = lineDistances[ i ] + _start.distanceTo( _end );
  20875. }
  20876. geometry.setAttribute( 'lineDistance', new Float32BufferAttribute( lineDistances, 1 ) );
  20877. } else {
  20878. console.warn( 'THREE.LineSegments.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.' );
  20879. }
  20880. return this;
  20881. }
  20882. }
  20883. /**
  20884. * A continuous line. This is nearly the same as {@link Line} the only difference
  20885. * is that the last vertex is connected with the first vertex in order to close
  20886. * the line to form a loop.
  20887. *
  20888. * @augments Line
  20889. */
  20890. class LineLoop extends Line {
  20891. /**
  20892. * Constructs a new line loop.
  20893. *
  20894. * @param {BufferGeometry} [geometry] - The line geometry.
  20895. * @param {Material|Array<Material>} [material] - The line material.
  20896. */
  20897. constructor( geometry, material ) {
  20898. super( geometry, material );
  20899. /**
  20900. * This flag can be used for type testing.
  20901. *
  20902. * @type {boolean}
  20903. * @readonly
  20904. * @default true
  20905. */
  20906. this.isLineLoop = true;
  20907. this.type = 'LineLoop';
  20908. }
  20909. }
  20910. /**
  20911. * A material for rendering point primitives.
  20912. *
  20913. * Materials define the appearance of renderable 3D objects.
  20914. *
  20915. * ```js
  20916. * const vertices = [];
  20917. *
  20918. * for ( let i = 0; i < 10000; i ++ ) {
  20919. * const x = THREE.MathUtils.randFloatSpread( 2000 );
  20920. * const y = THREE.MathUtils.randFloatSpread( 2000 );
  20921. * const z = THREE.MathUtils.randFloatSpread( 2000 );
  20922. *
  20923. * vertices.push( x, y, z );
  20924. * }
  20925. *
  20926. * const geometry = new THREE.BufferGeometry();
  20927. * geometry.setAttribute( 'position', new THREE.Float32BufferAttribute( vertices, 3 ) );
  20928. * const material = new THREE.PointsMaterial( { color: 0x888888 } );
  20929. * const points = new THREE.Points( geometry, material );
  20930. * scene.add( points );
  20931. * ```
  20932. *
  20933. * @augments Material
  20934. */
  20935. class PointsMaterial extends Material {
  20936. /**
  20937. * Constructs a new points material.
  20938. *
  20939. * @param {Object} [parameters] - An object with one or more properties
  20940. * defining the material's appearance. Any property of the material
  20941. * (including any property from inherited materials) can be passed
  20942. * in here. Color values can be passed any type of value accepted
  20943. * by {@link Color#set}.
  20944. */
  20945. constructor( parameters ) {
  20946. super();
  20947. /**
  20948. * This flag can be used for type testing.
  20949. *
  20950. * @type {boolean}
  20951. * @readonly
  20952. * @default true
  20953. */
  20954. this.isPointsMaterial = true;
  20955. this.type = 'PointsMaterial';
  20956. /**
  20957. * Color of the material.
  20958. *
  20959. * @type {Color}
  20960. * @default (1,1,1)
  20961. */
  20962. this.color = new Color( 0xffffff );
  20963. /**
  20964. * The color map. May optionally include an alpha channel, typically combined
  20965. * with {@link Material#transparent} or {@link Material#alphaTest}. The texture map
  20966. * color is modulated by the diffuse `color`.
  20967. *
  20968. * @type {?Texture}
  20969. * @default null
  20970. */
  20971. this.map = null;
  20972. /**
  20973. * The alpha map is a grayscale texture that controls the opacity across the
  20974. * surface (black: fully transparent; white: fully opaque).
  20975. *
  20976. * Only the color of the texture is used, ignoring the alpha channel if one
  20977. * exists. For RGB and RGBA textures, the renderer will use the green channel
  20978. * when sampling this texture due to the extra bit of precision provided for
  20979. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  20980. * luminance/alpha textures will also still work as expected.
  20981. *
  20982. * @type {?Texture}
  20983. * @default null
  20984. */
  20985. this.alphaMap = null;
  20986. /**
  20987. * Defines the size of the points in pixels.
  20988. *
  20989. * 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}.
  20990. *
  20991. * @type {number}
  20992. * @default 1
  20993. */
  20994. this.size = 1;
  20995. /**
  20996. * Specifies whether size of individual points is attenuated by the camera depth (perspective camera only).
  20997. *
  20998. * @type {boolean}
  20999. * @default true
  21000. */
  21001. this.sizeAttenuation = true;
  21002. /**
  21003. * Whether the material is affected by fog or not.
  21004. *
  21005. * @type {boolean}
  21006. * @default true
  21007. */
  21008. this.fog = true;
  21009. this.setValues( parameters );
  21010. }
  21011. copy( source ) {
  21012. super.copy( source );
  21013. this.color.copy( source.color );
  21014. this.map = source.map;
  21015. this.alphaMap = source.alphaMap;
  21016. this.size = source.size;
  21017. this.sizeAttenuation = source.sizeAttenuation;
  21018. this.fog = source.fog;
  21019. return this;
  21020. }
  21021. }
  21022. const _inverseMatrix = /*@__PURE__*/ new Matrix4();
  21023. const _ray = /*@__PURE__*/ new Ray();
  21024. const _sphere = /*@__PURE__*/ new Sphere();
  21025. const _position$2 = /*@__PURE__*/ new Vector3();
  21026. /**
  21027. * A class for displaying points or point clouds.
  21028. *
  21029. * @augments Object3D
  21030. */
  21031. class Points extends Object3D {
  21032. /**
  21033. * Constructs a new point cloud.
  21034. *
  21035. * @param {BufferGeometry} [geometry] - The points geometry.
  21036. * @param {Material|Array<Material>} [material] - The points material.
  21037. */
  21038. constructor( geometry = new BufferGeometry(), material = new PointsMaterial() ) {
  21039. super();
  21040. /**
  21041. * This flag can be used for type testing.
  21042. *
  21043. * @type {boolean}
  21044. * @readonly
  21045. * @default true
  21046. */
  21047. this.isPoints = true;
  21048. this.type = 'Points';
  21049. /**
  21050. * The points geometry.
  21051. *
  21052. * @type {BufferGeometry}
  21053. */
  21054. this.geometry = geometry;
  21055. /**
  21056. * The line material.
  21057. *
  21058. * @type {Material|Array<Material>}
  21059. * @default PointsMaterial
  21060. */
  21061. this.material = material;
  21062. /**
  21063. * A dictionary representing the morph targets in the geometry. The key is the
  21064. * morph targets name, the value its attribute index. This member is `undefined`
  21065. * by default and only set when morph targets are detected in the geometry.
  21066. *
  21067. * @type {Object<String,number>|undefined}
  21068. * @default undefined
  21069. */
  21070. this.morphTargetDictionary = undefined;
  21071. /**
  21072. * An array of weights typically in the range `[0,1]` that specify how much of the morph
  21073. * is applied. This member is `undefined` by default and only set when morph targets are
  21074. * detected in the geometry.
  21075. *
  21076. * @type {Array<number>|undefined}
  21077. * @default undefined
  21078. */
  21079. this.morphTargetInfluences = undefined;
  21080. this.updateMorphTargets();
  21081. }
  21082. copy( source, recursive ) {
  21083. super.copy( source, recursive );
  21084. this.material = Array.isArray( source.material ) ? source.material.slice() : source.material;
  21085. this.geometry = source.geometry;
  21086. return this;
  21087. }
  21088. /**
  21089. * Computes intersection points between a casted ray and this point cloud.
  21090. *
  21091. * @param {Raycaster} raycaster - The raycaster.
  21092. * @param {Array<Object>} intersects - The target array that holds the intersection points.
  21093. */
  21094. raycast( raycaster, intersects ) {
  21095. const geometry = this.geometry;
  21096. const matrixWorld = this.matrixWorld;
  21097. const threshold = raycaster.params.Points.threshold;
  21098. const drawRange = geometry.drawRange;
  21099. // Checking boundingSphere distance to ray
  21100. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  21101. _sphere.copy( geometry.boundingSphere );
  21102. _sphere.applyMatrix4( matrixWorld );
  21103. _sphere.radius += threshold;
  21104. if ( raycaster.ray.intersectsSphere( _sphere ) === false ) return;
  21105. //
  21106. _inverseMatrix.copy( matrixWorld ).invert();
  21107. _ray.copy( raycaster.ray ).applyMatrix4( _inverseMatrix );
  21108. const localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 );
  21109. const localThresholdSq = localThreshold * localThreshold;
  21110. const index = geometry.index;
  21111. const attributes = geometry.attributes;
  21112. const positionAttribute = attributes.position;
  21113. if ( index !== null ) {
  21114. const start = Math.max( 0, drawRange.start );
  21115. const end = Math.min( index.count, ( drawRange.start + drawRange.count ) );
  21116. for ( let i = start, il = end; i < il; i ++ ) {
  21117. const a = index.getX( i );
  21118. _position$2.fromBufferAttribute( positionAttribute, a );
  21119. testPoint( _position$2, a, localThresholdSq, matrixWorld, raycaster, intersects, this );
  21120. }
  21121. } else {
  21122. const start = Math.max( 0, drawRange.start );
  21123. const end = Math.min( positionAttribute.count, ( drawRange.start + drawRange.count ) );
  21124. for ( let i = start, l = end; i < l; i ++ ) {
  21125. _position$2.fromBufferAttribute( positionAttribute, i );
  21126. testPoint( _position$2, i, localThresholdSq, matrixWorld, raycaster, intersects, this );
  21127. }
  21128. }
  21129. }
  21130. /**
  21131. * Sets the values of {@link Points#morphTargetDictionary} and {@link Points#morphTargetInfluences}
  21132. * to make sure existing morph targets can influence this 3D object.
  21133. */
  21134. updateMorphTargets() {
  21135. const geometry = this.geometry;
  21136. const morphAttributes = geometry.morphAttributes;
  21137. const keys = Object.keys( morphAttributes );
  21138. if ( keys.length > 0 ) {
  21139. const morphAttribute = morphAttributes[ keys[ 0 ] ];
  21140. if ( morphAttribute !== undefined ) {
  21141. this.morphTargetInfluences = [];
  21142. this.morphTargetDictionary = {};
  21143. for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  21144. const name = morphAttribute[ m ].name || String( m );
  21145. this.morphTargetInfluences.push( 0 );
  21146. this.morphTargetDictionary[ name ] = m;
  21147. }
  21148. }
  21149. }
  21150. }
  21151. }
  21152. function testPoint( point, index, localThresholdSq, matrixWorld, raycaster, intersects, object ) {
  21153. const rayPointDistanceSq = _ray.distanceSqToPoint( point );
  21154. if ( rayPointDistanceSq < localThresholdSq ) {
  21155. const intersectPoint = new Vector3();
  21156. _ray.closestPointToPoint( point, intersectPoint );
  21157. intersectPoint.applyMatrix4( matrixWorld );
  21158. const distance = raycaster.ray.origin.distanceTo( intersectPoint );
  21159. if ( distance < raycaster.near || distance > raycaster.far ) return;
  21160. intersects.push( {
  21161. distance: distance,
  21162. distanceToRay: Math.sqrt( rayPointDistanceSq ),
  21163. point: intersectPoint,
  21164. index: index,
  21165. face: null,
  21166. faceIndex: null,
  21167. barycoord: null,
  21168. object: object
  21169. } );
  21170. }
  21171. }
  21172. /**
  21173. * A texture for use with a video.
  21174. *
  21175. * ```js
  21176. * // assuming you have created a HTML video element with id="video"
  21177. * const video = document.getElementById( 'video' );
  21178. * const texture = new THREE.VideoTexture( video );
  21179. * ```
  21180. *
  21181. * Note: After the initial use of a texture, its dimensions, format, and type
  21182. * cannot be changed. Instead, call {@link Texture#dispose} on the texture and instantiate a new one.
  21183. *
  21184. * @augments Texture
  21185. */
  21186. class VideoTexture extends Texture {
  21187. /**
  21188. * Constructs a new video texture.
  21189. *
  21190. * @param {Video} video - The video element to use as a data source for the texture.
  21191. * @param {number} [mapping=Texture.DEFAULT_MAPPING] - The texture mapping.
  21192. * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value.
  21193. * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value.
  21194. * @param {number} [magFilter=LinearFilter] - The mag filter value.
  21195. * @param {number} [minFilter=LinearFilter] - The min filter value.
  21196. * @param {number} [format=RGBAFormat] - The texture format.
  21197. * @param {number} [type=UnsignedByteType] - The texture type.
  21198. * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value.
  21199. */
  21200. constructor( video, mapping, wrapS, wrapT, magFilter = LinearFilter, minFilter = LinearFilter, format, type, anisotropy ) {
  21201. super( video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  21202. /**
  21203. * This flag can be used for type testing.
  21204. *
  21205. * @type {boolean}
  21206. * @readonly
  21207. * @default true
  21208. */
  21209. this.isVideoTexture = true;
  21210. /**
  21211. * Whether to generate mipmaps (if possible) for a texture.
  21212. *
  21213. * Overwritten and set to `false` by default.
  21214. *
  21215. * @type {boolean}
  21216. * @default false
  21217. */
  21218. this.generateMipmaps = false;
  21219. const scope = this;
  21220. function updateVideo() {
  21221. scope.needsUpdate = true;
  21222. video.requestVideoFrameCallback( updateVideo );
  21223. }
  21224. if ( 'requestVideoFrameCallback' in video ) {
  21225. video.requestVideoFrameCallback( updateVideo );
  21226. }
  21227. }
  21228. clone() {
  21229. return new this.constructor( this.image ).copy( this );
  21230. }
  21231. /**
  21232. * This method is called automatically by the renderer and sets {@link Texture#needsUpdate}
  21233. * to `true` every time a new frame is available.
  21234. *
  21235. * Only relevant if `requestVideoFrameCallback` is not supported in the browser.
  21236. */
  21237. update() {
  21238. const video = this.image;
  21239. const hasVideoFrameCallback = 'requestVideoFrameCallback' in video;
  21240. if ( hasVideoFrameCallback === false && video.readyState >= video.HAVE_CURRENT_DATA ) {
  21241. this.needsUpdate = true;
  21242. }
  21243. }
  21244. }
  21245. /**
  21246. * This class can be used as an alternative way to define video data. Instead of using
  21247. * an instance of `HTMLVideoElement` like with `VideoTexture`, `VideoFrameTexture` expects each frame is
  21248. * defined manually via {@link VideoFrameTexture#setFrame}. A typical use case for this module is when
  21249. * video frames are decoded with the WebCodecs API.
  21250. *
  21251. * ```js
  21252. * const texture = new THREE.VideoFrameTexture();
  21253. * texture.setFrame( frame );
  21254. * ```
  21255. *
  21256. * @augments VideoTexture
  21257. */
  21258. class VideoFrameTexture extends VideoTexture {
  21259. /**
  21260. * Constructs a new video frame texture.
  21261. *
  21262. * @param {number} [mapping=Texture.DEFAULT_MAPPING] - The texture mapping.
  21263. * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value.
  21264. * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value.
  21265. * @param {number} [magFilter=LinearFilter] - The mag filter value.
  21266. * @param {number} [minFilter=LinearFilter] - The min filter value.
  21267. * @param {number} [format=RGBAFormat] - The texture format.
  21268. * @param {number} [type=UnsignedByteType] - The texture type.
  21269. * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value.
  21270. */
  21271. constructor( mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  21272. super( {}, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  21273. /**
  21274. * This flag can be used for type testing.
  21275. *
  21276. * @type {boolean}
  21277. * @readonly
  21278. * @default true
  21279. */
  21280. this.isVideoFrameTexture = true;
  21281. }
  21282. /**
  21283. * This method overwritten with an empty implementation since
  21284. * this type of texture is updated via `setFrame()`.
  21285. */
  21286. update() {}
  21287. clone() {
  21288. return new this.constructor().copy( this ); // restoring Texture.clone()
  21289. }
  21290. /**
  21291. * Sets the current frame of the video. This will automatically update the texture
  21292. * so the data can be used for rendering.
  21293. *
  21294. * @param {VideoFrame} frame - The video frame.
  21295. */
  21296. setFrame( frame ) {
  21297. this.image = frame;
  21298. this.needsUpdate = true;
  21299. }
  21300. }
  21301. /**
  21302. * This class can only be used in combination with `copyFramebufferToTexture()` methods
  21303. * of renderers. It extracts the contents of the current bound framebuffer and provides it
  21304. * as a texture for further usage.
  21305. *
  21306. * ```js
  21307. * const pixelRatio = window.devicePixelRatio;
  21308. * const textureSize = 128 * pixelRatio;
  21309. *
  21310. * const frameTexture = new FramebufferTexture( textureSize, textureSize );
  21311. *
  21312. * // calculate start position for copying part of the frame data
  21313. * const vector = new Vector2();
  21314. * vector.x = ( window.innerWidth * pixelRatio / 2 ) - ( textureSize / 2 );
  21315. * vector.y = ( window.innerHeight * pixelRatio / 2 ) - ( textureSize / 2 );
  21316. *
  21317. * renderer.render( scene, camera );
  21318. *
  21319. * // copy part of the rendered frame into the framebuffer texture
  21320. * renderer.copyFramebufferToTexture( frameTexture, vector );
  21321. * ```
  21322. *
  21323. * @augments Texture
  21324. */
  21325. class FramebufferTexture extends Texture {
  21326. /**
  21327. * Constructs a new framebuffer texture.
  21328. *
  21329. * @param {number} width - The width of the texture.
  21330. * @param {number} height - The height of the texture.
  21331. */
  21332. constructor( width, height ) {
  21333. super( { width, height } );
  21334. /**
  21335. * This flag can be used for type testing.
  21336. *
  21337. * @type {boolean}
  21338. * @readonly
  21339. * @default true
  21340. */
  21341. this.isFramebufferTexture = true;
  21342. /**
  21343. * How the texture is sampled when a texel covers more than one pixel.
  21344. *
  21345. * Overwritten and set to `NearestFilter` by default to disable filtering.
  21346. *
  21347. * @type {(NearestFilter|NearestMipmapNearestFilter|NearestMipmapLinearFilter|LinearFilter|LinearMipmapNearestFilter|LinearMipmapLinearFilter)}
  21348. * @default NearestFilter
  21349. */
  21350. this.magFilter = NearestFilter;
  21351. /**
  21352. * How the texture is sampled when a texel covers less than one pixel.
  21353. *
  21354. * Overwritten and set to `NearestFilter` by default to disable filtering.
  21355. *
  21356. * @type {(NearestFilter|NearestMipmapNearestFilter|NearestMipmapLinearFilter|LinearFilter|LinearMipmapNearestFilter|LinearMipmapLinearFilter)}
  21357. * @default NearestFilter
  21358. */
  21359. this.minFilter = NearestFilter;
  21360. /**
  21361. * Whether to generate mipmaps (if possible) for a texture.
  21362. *
  21363. * Overwritten and set to `false` by default.
  21364. *
  21365. * @type {boolean}
  21366. * @default false
  21367. */
  21368. this.generateMipmaps = false;
  21369. this.needsUpdate = true;
  21370. }
  21371. }
  21372. /**
  21373. * Creates a texture based on data in compressed form.
  21374. *
  21375. * These texture are usually loaded with {@link CompressedTextureLoader}.
  21376. *
  21377. * @augments Texture
  21378. */
  21379. class CompressedTexture extends Texture {
  21380. /**
  21381. * Constructs a new compressed texture.
  21382. *
  21383. * @param {Array<Object>} mipmaps - This array holds for all mipmaps (including the bases mip)
  21384. * the data and dimensions.
  21385. * @param {number} width - The width of the texture.
  21386. * @param {number} height - The height of the texture.
  21387. * @param {number} [format=RGBAFormat] - The texture format.
  21388. * @param {number} [type=UnsignedByteType] - The texture type.
  21389. * @param {number} [mapping=Texture.DEFAULT_MAPPING] - The texture mapping.
  21390. * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value.
  21391. * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value.
  21392. * @param {number} [magFilter=LinearFilter] - The mag filter value.
  21393. * @param {number} [minFilter=LinearMipmapLinearFilter] - The min filter value.
  21394. * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value.
  21395. * @param {string} [colorSpace=NoColorSpace] - The color space.
  21396. */
  21397. constructor( mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, colorSpace ) {
  21398. super( null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace );
  21399. /**
  21400. * This flag can be used for type testing.
  21401. *
  21402. * @type {boolean}
  21403. * @readonly
  21404. * @default true
  21405. */
  21406. this.isCompressedTexture = true;
  21407. /**
  21408. * The image property of a compressed texture just defines its dimensions.
  21409. *
  21410. * @type {{width:number,height:number}}
  21411. */
  21412. this.image = { width: width, height: height };
  21413. /**
  21414. * This array holds for all mipmaps (including the bases mip) the data and dimensions.
  21415. *
  21416. * @type {Array<Object>}
  21417. */
  21418. this.mipmaps = mipmaps;
  21419. /**
  21420. * If set to `true`, the texture is flipped along the vertical axis when
  21421. * uploaded to the GPU.
  21422. *
  21423. * Overwritten and set to `false` by default since it is not possible to
  21424. * flip compressed textures.
  21425. *
  21426. * @type {boolean}
  21427. * @default false
  21428. * @readonly
  21429. */
  21430. this.flipY = false;
  21431. /**
  21432. * Whether to generate mipmaps (if possible) for a texture.
  21433. *
  21434. * Overwritten and set to `false` by default since it is not
  21435. * possible to generate mipmaps for compressed data. Mipmaps
  21436. * must be embedded in the compressed texture file.
  21437. *
  21438. * @type {boolean}
  21439. * @default false
  21440. * @readonly
  21441. */
  21442. this.generateMipmaps = false;
  21443. }
  21444. }
  21445. /**
  21446. * Creates a texture 2D array based on data in compressed form.
  21447. *
  21448. * These texture are usually loaded with {@link CompressedTextureLoader}.
  21449. *
  21450. * @augments CompressedTexture
  21451. */
  21452. class CompressedArrayTexture extends CompressedTexture {
  21453. /**
  21454. * Constructs a new compressed array texture.
  21455. *
  21456. * @param {Array<Object>} mipmaps - This array holds for all mipmaps (including the bases mip)
  21457. * the data and dimensions.
  21458. * @param {number} width - The width of the texture.
  21459. * @param {number} height - The height of the texture.
  21460. * @param {number} depth - The depth of the texture.
  21461. * @param {number} [format=RGBAFormat] - The min filter value.
  21462. * @param {number} [type=UnsignedByteType] - The min filter value.
  21463. */
  21464. constructor( mipmaps, width, height, depth, format, type ) {
  21465. super( mipmaps, width, height, format, type );
  21466. /**
  21467. * This flag can be used for type testing.
  21468. *
  21469. * @type {boolean}
  21470. * @readonly
  21471. * @default true
  21472. */
  21473. this.isCompressedArrayTexture = true;
  21474. /**
  21475. * The image property of a compressed texture just defines its dimensions.
  21476. *
  21477. * @name CompressedArrayTexture#image
  21478. * @type {{width:number,height:number,depth:number}}
  21479. */
  21480. this.image.depth = depth;
  21481. /**
  21482. * This defines how the texture is wrapped in the depth and corresponds to
  21483. * *W* in UVW mapping.
  21484. *
  21485. * @type {(RepeatWrapping|ClampToEdgeWrapping|MirroredRepeatWrapping)}
  21486. * @default ClampToEdgeWrapping
  21487. */
  21488. this.wrapR = ClampToEdgeWrapping;
  21489. /**
  21490. * A set of all layers which need to be updated in the texture.
  21491. *
  21492. * @type {Set<number>}
  21493. */
  21494. this.layerUpdates = new Set();
  21495. }
  21496. /**
  21497. * Describes that a specific layer of the texture needs to be updated.
  21498. * Normally when {@link Texture#needsUpdate} is set to `true`, the
  21499. * entire compressed texture array is sent to the GPU. Marking specific
  21500. * layers will only transmit subsets of all mipmaps associated with a
  21501. * specific depth in the array which is often much more performant.
  21502. *
  21503. * @param {number} layerIndex - The layer index that should be updated.
  21504. */
  21505. addLayerUpdate( layerIndex ) {
  21506. this.layerUpdates.add( layerIndex );
  21507. }
  21508. /**
  21509. * Resets the layer updates registry.
  21510. */
  21511. clearLayerUpdates() {
  21512. this.layerUpdates.clear();
  21513. }
  21514. }
  21515. /**
  21516. * Creates a cube texture based on data in compressed form.
  21517. *
  21518. * These texture are usually loaded with {@link CompressedTextureLoader}.
  21519. *
  21520. * @augments CompressedTexture
  21521. */
  21522. class CompressedCubeTexture extends CompressedTexture {
  21523. /**
  21524. * Constructs a new compressed texture.
  21525. *
  21526. * @param {Array<CompressedTexture>} images - An array of compressed textures.
  21527. * @param {number} [format=RGBAFormat] - The texture format.
  21528. * @param {number} [type=UnsignedByteType] - The texture type.
  21529. */
  21530. constructor( images, format, type ) {
  21531. super( undefined, images[ 0 ].width, images[ 0 ].height, format, type, CubeReflectionMapping );
  21532. /**
  21533. * This flag can be used for type testing.
  21534. *
  21535. * @type {boolean}
  21536. * @readonly
  21537. * @default true
  21538. */
  21539. this.isCompressedCubeTexture = true;
  21540. /**
  21541. * This flag can be used for type testing.
  21542. *
  21543. * @type {boolean}
  21544. * @readonly
  21545. * @default true
  21546. */
  21547. this.isCubeTexture = true;
  21548. this.image = images;
  21549. }
  21550. }
  21551. /**
  21552. * Creates a texture from a canvas element.
  21553. *
  21554. * This is almost the same as the base texture class, except that it sets {@link Texture#needsUpdate}
  21555. * to `true` immediately since a canvas can directly be used for rendering.
  21556. *
  21557. * @augments Texture
  21558. */
  21559. class CanvasTexture extends Texture {
  21560. /**
  21561. * Constructs a new texture.
  21562. *
  21563. * @param {HTMLCanvasElement} [canvas] - The HTML canvas element.
  21564. * @param {number} [mapping=Texture.DEFAULT_MAPPING] - The texture mapping.
  21565. * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value.
  21566. * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value.
  21567. * @param {number} [magFilter=LinearFilter] - The mag filter value.
  21568. * @param {number} [minFilter=LinearMipmapLinearFilter] - The min filter value.
  21569. * @param {number} [format=RGBAFormat] - The texture format.
  21570. * @param {number} [type=UnsignedByteType] - The texture type.
  21571. * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value.
  21572. */
  21573. constructor( canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  21574. super( canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  21575. /**
  21576. * This flag can be used for type testing.
  21577. *
  21578. * @type {boolean}
  21579. * @readonly
  21580. * @default true
  21581. */
  21582. this.isCanvasTexture = true;
  21583. this.needsUpdate = true;
  21584. }
  21585. }
  21586. /**
  21587. * This class can be used to automatically save the depth information of a
  21588. * rendering into a texture.
  21589. *
  21590. * @augments Texture
  21591. */
  21592. class DepthTexture extends Texture {
  21593. /**
  21594. * Constructs a new depth texture.
  21595. *
  21596. * @param {number} width - The width of the texture.
  21597. * @param {number} height - The height of the texture.
  21598. * @param {number} [type=UnsignedIntType] - The texture type.
  21599. * @param {number} [mapping=Texture.DEFAULT_MAPPING] - The texture mapping.
  21600. * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value.
  21601. * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value.
  21602. * @param {number} [magFilter=LinearFilter] - The mag filter value.
  21603. * @param {number} [minFilter=LinearFilter] - The min filter value.
  21604. * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value.
  21605. * @param {number} [format=DepthFormat] - The texture format.
  21606. */
  21607. constructor( width, height, type = UnsignedIntType, mapping, wrapS, wrapT, magFilter = NearestFilter, minFilter = NearestFilter, anisotropy, format = DepthFormat ) {
  21608. if ( format !== DepthFormat && format !== DepthStencilFormat ) {
  21609. throw new Error( 'DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat' );
  21610. }
  21611. super( null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  21612. /**
  21613. * This flag can be used for type testing.
  21614. *
  21615. * @type {boolean}
  21616. * @readonly
  21617. * @default true
  21618. */
  21619. this.isDepthTexture = true;
  21620. /**
  21621. * The image property of a depth texture just defines its dimensions.
  21622. *
  21623. * @type {{width:number,height:number}}
  21624. */
  21625. this.image = { width: width, height: height };
  21626. /**
  21627. * If set to `true`, the texture is flipped along the vertical axis when
  21628. * uploaded to the GPU.
  21629. *
  21630. * Overwritten and set to `false` by default.
  21631. *
  21632. * @type {boolean}
  21633. * @default false
  21634. */
  21635. this.flipY = false;
  21636. /**
  21637. * Whether to generate mipmaps (if possible) for a texture.
  21638. *
  21639. * Overwritten and set to `false` by default.
  21640. *
  21641. * @type {boolean}
  21642. * @default false
  21643. */
  21644. this.generateMipmaps = false;
  21645. /**
  21646. * The depth compare function.
  21647. *
  21648. * @type {?(NeverCompare|LessCompare|EqualCompare|LessEqualCompare|GreaterCompare|NotEqualCompare|GreaterEqualCompare|AlwaysCompare)}
  21649. * @default null
  21650. */
  21651. this.compareFunction = null;
  21652. }
  21653. copy( source ) {
  21654. super.copy( source );
  21655. this.source = new Source( Object.assign( {}, source.image ) ); // see #30540
  21656. this.compareFunction = source.compareFunction;
  21657. return this;
  21658. }
  21659. toJSON( meta ) {
  21660. const data = super.toJSON( meta );
  21661. if ( this.compareFunction !== null ) data.compareFunction = this.compareFunction;
  21662. return data;
  21663. }
  21664. }
  21665. /**
  21666. * An abstract base class for creating an analytic curve object that contains methods
  21667. * for interpolation.
  21668. *
  21669. * @abstract
  21670. */
  21671. class Curve {
  21672. /**
  21673. * Constructs a new curve.
  21674. */
  21675. constructor() {
  21676. /**
  21677. * The type property is used for detecting the object type
  21678. * in context of serialization/deserialization.
  21679. *
  21680. * @type {string}
  21681. * @readonly
  21682. */
  21683. this.type = 'Curve';
  21684. /**
  21685. * This value determines the amount of divisions when calculating the
  21686. * cumulative segment lengths of a curve via {@link Curve#getLengths}. To ensure
  21687. * precision when using methods like {@link Curve#getSpacedPoints}, it is
  21688. * recommended to increase the value of this property if the curve is very large.
  21689. *
  21690. * @type {number}
  21691. * @default 200
  21692. */
  21693. this.arcLengthDivisions = 200;
  21694. /**
  21695. * Must be set to `true` if the curve parameters have changed.
  21696. *
  21697. * @type {boolean}
  21698. * @default false
  21699. */
  21700. this.needsUpdate = false;
  21701. /**
  21702. * An internal cache that holds precomputed curve length values.
  21703. *
  21704. * @private
  21705. * @type {?Array<number>}
  21706. * @default null
  21707. */
  21708. this.cacheArcLengths = null;
  21709. }
  21710. /**
  21711. * This method returns a vector in 2D or 3D space (depending on the curve definition)
  21712. * for the given interpolation factor.
  21713. *
  21714. * @abstract
  21715. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  21716. * @param {(Vector2|Vector3)} [optionalTarget] - The optional target vector the result is written to.
  21717. * @return {(Vector2|Vector3)} The position on the curve. It can be a 2D or 3D vector depending on the curve definition.
  21718. */
  21719. getPoint( /* t, optionalTarget */ ) {
  21720. console.warn( 'THREE.Curve: .getPoint() not implemented.' );
  21721. }
  21722. /**
  21723. * This method returns a vector in 2D or 3D space (depending on the curve definition)
  21724. * for the given interpolation factor. Unlike {@link Curve#getPoint}, this method honors the length
  21725. * of the curve which equidistant samples.
  21726. *
  21727. * @param {number} u - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  21728. * @param {(Vector2|Vector3)} [optionalTarget] - The optional target vector the result is written to.
  21729. * @return {(Vector2|Vector3)} The position on the curve. It can be a 2D or 3D vector depending on the curve definition.
  21730. */
  21731. getPointAt( u, optionalTarget ) {
  21732. const t = this.getUtoTmapping( u );
  21733. return this.getPoint( t, optionalTarget );
  21734. }
  21735. /**
  21736. * This method samples the curve via {@link Curve#getPoint} and returns an array of points representing
  21737. * the curve shape.
  21738. *
  21739. * @param {number} [divisions=5] - The number of divisions.
  21740. * @return {Array<(Vector2|Vector3)>} An array holding the sampled curve values. The number of points is `divisions + 1`.
  21741. */
  21742. getPoints( divisions = 5 ) {
  21743. const points = [];
  21744. for ( let d = 0; d <= divisions; d ++ ) {
  21745. points.push( this.getPoint( d / divisions ) );
  21746. }
  21747. return points;
  21748. }
  21749. // Get sequence of points using getPointAt( u )
  21750. /**
  21751. * This method samples the curve via {@link Curve#getPointAt} and returns an array of points representing
  21752. * the curve shape. Unlike {@link Curve#getPoints}, this method returns equi-spaced points across the entire
  21753. * curve.
  21754. *
  21755. * @param {number} [divisions=5] - The number of divisions.
  21756. * @return {Array<(Vector2|Vector3)>} An array holding the sampled curve values. The number of points is `divisions + 1`.
  21757. */
  21758. getSpacedPoints( divisions = 5 ) {
  21759. const points = [];
  21760. for ( let d = 0; d <= divisions; d ++ ) {
  21761. points.push( this.getPointAt( d / divisions ) );
  21762. }
  21763. return points;
  21764. }
  21765. /**
  21766. * Returns the total arc length of the curve.
  21767. *
  21768. * @return {number} The length of the curve.
  21769. */
  21770. getLength() {
  21771. const lengths = this.getLengths();
  21772. return lengths[ lengths.length - 1 ];
  21773. }
  21774. /**
  21775. * Returns an array of cumulative segment lengths of the curve.
  21776. *
  21777. * @param {number} [divisions=this.arcLengthDivisions] - The number of divisions.
  21778. * @return {Array<number>} An array holding the cumulative segment lengths.
  21779. */
  21780. getLengths( divisions = this.arcLengthDivisions ) {
  21781. if ( this.cacheArcLengths &&
  21782. ( this.cacheArcLengths.length === divisions + 1 ) &&
  21783. ! this.needsUpdate ) {
  21784. return this.cacheArcLengths;
  21785. }
  21786. this.needsUpdate = false;
  21787. const cache = [];
  21788. let current, last = this.getPoint( 0 );
  21789. let sum = 0;
  21790. cache.push( 0 );
  21791. for ( let p = 1; p <= divisions; p ++ ) {
  21792. current = this.getPoint( p / divisions );
  21793. sum += current.distanceTo( last );
  21794. cache.push( sum );
  21795. last = current;
  21796. }
  21797. this.cacheArcLengths = cache;
  21798. return cache; // { sums: cache, sum: sum }; Sum is in the last element.
  21799. }
  21800. /**
  21801. * Update the cumulative segment distance cache. The method must be called
  21802. * every time curve parameters are changed. If an updated curve is part of a
  21803. * composed curve like {@link CurvePath}, this method must be called on the
  21804. * composed curve, too.
  21805. */
  21806. updateArcLengths() {
  21807. this.needsUpdate = true;
  21808. this.getLengths();
  21809. }
  21810. /**
  21811. * Given an interpolation factor in the range `[0,1]`, this method returns an updated
  21812. * interpolation factor in the same range that can be ued to sample equidistant points
  21813. * from a curve.
  21814. *
  21815. * @param {number} u - The interpolation factor.
  21816. * @param {?number} distance - An optional distance on the curve.
  21817. * @return {number} The updated interpolation factor.
  21818. */
  21819. getUtoTmapping( u, distance = null ) {
  21820. const arcLengths = this.getLengths();
  21821. let i = 0;
  21822. const il = arcLengths.length;
  21823. let targetArcLength; // The targeted u distance value to get
  21824. if ( distance ) {
  21825. targetArcLength = distance;
  21826. } else {
  21827. targetArcLength = u * arcLengths[ il - 1 ];
  21828. }
  21829. // binary search for the index with largest value smaller than target u distance
  21830. let low = 0, high = il - 1, comparison;
  21831. while ( low <= high ) {
  21832. 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
  21833. comparison = arcLengths[ i ] - targetArcLength;
  21834. if ( comparison < 0 ) {
  21835. low = i + 1;
  21836. } else if ( comparison > 0 ) {
  21837. high = i - 1;
  21838. } else {
  21839. high = i;
  21840. break;
  21841. // DONE
  21842. }
  21843. }
  21844. i = high;
  21845. if ( arcLengths[ i ] === targetArcLength ) {
  21846. return i / ( il - 1 );
  21847. }
  21848. // we could get finer grain at lengths, or use simple interpolation between two points
  21849. const lengthBefore = arcLengths[ i ];
  21850. const lengthAfter = arcLengths[ i + 1 ];
  21851. const segmentLength = lengthAfter - lengthBefore;
  21852. // determine where we are between the 'before' and 'after' points
  21853. const segmentFraction = ( targetArcLength - lengthBefore ) / segmentLength;
  21854. // add that fractional amount to t
  21855. const t = ( i + segmentFraction ) / ( il - 1 );
  21856. return t;
  21857. }
  21858. /**
  21859. * Returns a unit vector tangent for the given interpolation factor.
  21860. * If the derived curve does not implement its tangent derivation,
  21861. * two points a small delta apart will be used to find its gradient
  21862. * which seems to give a reasonable approximation.
  21863. *
  21864. * @param {number} t - The interpolation factor.
  21865. * @param {(Vector2|Vector3)} [optionalTarget] - The optional target vector the result is written to.
  21866. * @return {(Vector2|Vector3)} The tangent vector.
  21867. */
  21868. getTangent( t, optionalTarget ) {
  21869. const delta = 0.0001;
  21870. let t1 = t - delta;
  21871. let t2 = t + delta;
  21872. // Capping in case of danger
  21873. if ( t1 < 0 ) t1 = 0;
  21874. if ( t2 > 1 ) t2 = 1;
  21875. const pt1 = this.getPoint( t1 );
  21876. const pt2 = this.getPoint( t2 );
  21877. const tangent = optionalTarget || ( ( pt1.isVector2 ) ? new Vector2() : new Vector3() );
  21878. tangent.copy( pt2 ).sub( pt1 ).normalize();
  21879. return tangent;
  21880. }
  21881. /**
  21882. * Same as {@link Curve#getTangent} but with equidistant samples.
  21883. *
  21884. * @param {number} u - The interpolation factor.
  21885. * @param {(Vector2|Vector3)} [optionalTarget] - The optional target vector the result is written to.
  21886. * @return {(Vector2|Vector3)} The tangent vector.
  21887. * @see {@link Curve#getPointAt}
  21888. */
  21889. getTangentAt( u, optionalTarget ) {
  21890. const t = this.getUtoTmapping( u );
  21891. return this.getTangent( t, optionalTarget );
  21892. }
  21893. /**
  21894. * Generates the Frenet Frames. Requires a curve definition in 3D space. Used
  21895. * in geometries like {@link TubeGeometry} or {@link ExtrudeGeometry}.
  21896. *
  21897. * @param {number} segments - The number of segments.
  21898. * @param {boolean} [closed=false] - Whether the curve is closed or not.
  21899. * @return {{tangents: Array<Vector3>, normals: Array<Vector3>, binormals: Array<Vector3>}} The Frenet Frames.
  21900. */
  21901. computeFrenetFrames( segments, closed = false ) {
  21902. // see http://www.cs.indiana.edu/pub/techreports/TR425.pdf
  21903. const normal = new Vector3();
  21904. const tangents = [];
  21905. const normals = [];
  21906. const binormals = [];
  21907. const vec = new Vector3();
  21908. const mat = new Matrix4();
  21909. // compute the tangent vectors for each segment on the curve
  21910. for ( let i = 0; i <= segments; i ++ ) {
  21911. const u = i / segments;
  21912. tangents[ i ] = this.getTangentAt( u, new Vector3() );
  21913. }
  21914. // select an initial normal vector perpendicular to the first tangent vector,
  21915. // and in the direction of the minimum tangent xyz component
  21916. normals[ 0 ] = new Vector3();
  21917. binormals[ 0 ] = new Vector3();
  21918. let min = Number.MAX_VALUE;
  21919. const tx = Math.abs( tangents[ 0 ].x );
  21920. const ty = Math.abs( tangents[ 0 ].y );
  21921. const tz = Math.abs( tangents[ 0 ].z );
  21922. if ( tx <= min ) {
  21923. min = tx;
  21924. normal.set( 1, 0, 0 );
  21925. }
  21926. if ( ty <= min ) {
  21927. min = ty;
  21928. normal.set( 0, 1, 0 );
  21929. }
  21930. if ( tz <= min ) {
  21931. normal.set( 0, 0, 1 );
  21932. }
  21933. vec.crossVectors( tangents[ 0 ], normal ).normalize();
  21934. normals[ 0 ].crossVectors( tangents[ 0 ], vec );
  21935. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] );
  21936. // compute the slowly-varying normal and binormal vectors for each segment on the curve
  21937. for ( let i = 1; i <= segments; i ++ ) {
  21938. normals[ i ] = normals[ i - 1 ].clone();
  21939. binormals[ i ] = binormals[ i - 1 ].clone();
  21940. vec.crossVectors( tangents[ i - 1 ], tangents[ i ] );
  21941. if ( vec.length() > Number.EPSILON ) {
  21942. vec.normalize();
  21943. const theta = Math.acos( clamp( tangents[ i - 1 ].dot( tangents[ i ] ), -1, 1 ) ); // clamp for floating pt errors
  21944. normals[ i ].applyMatrix4( mat.makeRotationAxis( vec, theta ) );
  21945. }
  21946. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  21947. }
  21948. // if the curve is closed, postprocess the vectors so the first and last normal vectors are the same
  21949. if ( closed === true ) {
  21950. let theta = Math.acos( clamp( normals[ 0 ].dot( normals[ segments ] ), -1, 1 ) );
  21951. theta /= segments;
  21952. if ( tangents[ 0 ].dot( vec.crossVectors( normals[ 0 ], normals[ segments ] ) ) > 0 ) {
  21953. theta = - theta;
  21954. }
  21955. for ( let i = 1; i <= segments; i ++ ) {
  21956. // twist a little...
  21957. normals[ i ].applyMatrix4( mat.makeRotationAxis( tangents[ i ], theta * i ) );
  21958. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  21959. }
  21960. }
  21961. return {
  21962. tangents: tangents,
  21963. normals: normals,
  21964. binormals: binormals
  21965. };
  21966. }
  21967. /**
  21968. * Returns a new curve with copied values from this instance.
  21969. *
  21970. * @return {Curve} A clone of this instance.
  21971. */
  21972. clone() {
  21973. return new this.constructor().copy( this );
  21974. }
  21975. /**
  21976. * Copies the values of the given curve to this instance.
  21977. *
  21978. * @param {Curve} source - The curve to copy.
  21979. * @return {Curve} A reference to this curve.
  21980. */
  21981. copy( source ) {
  21982. this.arcLengthDivisions = source.arcLengthDivisions;
  21983. return this;
  21984. }
  21985. /**
  21986. * Serializes the curve into JSON.
  21987. *
  21988. * @return {Object} A JSON object representing the serialized curve.
  21989. * @see {@link ObjectLoader#parse}
  21990. */
  21991. toJSON() {
  21992. const data = {
  21993. metadata: {
  21994. version: 4.6,
  21995. type: 'Curve',
  21996. generator: 'Curve.toJSON'
  21997. }
  21998. };
  21999. data.arcLengthDivisions = this.arcLengthDivisions;
  22000. data.type = this.type;
  22001. return data;
  22002. }
  22003. /**
  22004. * Deserializes the curve from the given JSON.
  22005. *
  22006. * @param {Object} json - The JSON holding the serialized curve.
  22007. * @return {Curve} A reference to this curve.
  22008. */
  22009. fromJSON( json ) {
  22010. this.arcLengthDivisions = json.arcLengthDivisions;
  22011. return this;
  22012. }
  22013. }
  22014. /**
  22015. * A curve representing an ellipse.
  22016. *
  22017. * ```js
  22018. * const curve = new THREE.EllipseCurve(
  22019. * 0, 0,
  22020. * 10, 10,
  22021. * 0, 2 * Math.PI,
  22022. * false,
  22023. * 0
  22024. * );
  22025. *
  22026. * const points = curve.getPoints( 50 );
  22027. * const geometry = new THREE.BufferGeometry().setFromPoints( points );
  22028. *
  22029. * const material = new THREE.LineBasicMaterial( { color: 0xff0000 } );
  22030. *
  22031. * // Create the final object to add to the scene
  22032. * const ellipse = new THREE.Line( geometry, material );
  22033. * ```
  22034. *
  22035. * @augments Curve
  22036. */
  22037. class EllipseCurve extends Curve {
  22038. /**
  22039. * Constructs a new ellipse curve.
  22040. *
  22041. * @param {number} [aX=0] - The X center of the ellipse.
  22042. * @param {number} [aY=0] - The Y center of the ellipse.
  22043. * @param {number} [xRadius=1] - The radius of the ellipse in the x direction.
  22044. * @param {number} [yRadius=1] - The radius of the ellipse in the y direction.
  22045. * @param {number} [aStartAngle=0] - The start angle of the curve in radians starting from the positive X axis.
  22046. * @param {number} [aEndAngle=Math.PI*2] - The end angle of the curve in radians starting from the positive X axis.
  22047. * @param {boolean} [aClockwise=false] - Whether the ellipse is drawn clockwise or not.
  22048. * @param {number} [aRotation=0] - The rotation angle of the ellipse in radians, counterclockwise from the positive X axis.
  22049. */
  22050. constructor( aX = 0, aY = 0, xRadius = 1, yRadius = 1, aStartAngle = 0, aEndAngle = Math.PI * 2, aClockwise = false, aRotation = 0 ) {
  22051. super();
  22052. /**
  22053. * This flag can be used for type testing.
  22054. *
  22055. * @type {boolean}
  22056. * @readonly
  22057. * @default true
  22058. */
  22059. this.isEllipseCurve = true;
  22060. this.type = 'EllipseCurve';
  22061. /**
  22062. * The X center of the ellipse.
  22063. *
  22064. * @type {number}
  22065. * @default 0
  22066. */
  22067. this.aX = aX;
  22068. /**
  22069. * The Y center of the ellipse.
  22070. *
  22071. * @type {number}
  22072. * @default 0
  22073. */
  22074. this.aY = aY;
  22075. /**
  22076. * The radius of the ellipse in the x direction.
  22077. * Setting the this value equal to the {@link EllipseCurve#yRadius} will result in a circle.
  22078. *
  22079. * @type {number}
  22080. * @default 1
  22081. */
  22082. this.xRadius = xRadius;
  22083. /**
  22084. * The radius of the ellipse in the y direction.
  22085. * Setting the this value equal to the {@link EllipseCurve#xRadius} will result in a circle.
  22086. *
  22087. * @type {number}
  22088. * @default 1
  22089. */
  22090. this.yRadius = yRadius;
  22091. /**
  22092. * The start angle of the curve in radians starting from the positive X axis.
  22093. *
  22094. * @type {number}
  22095. * @default 0
  22096. */
  22097. this.aStartAngle = aStartAngle;
  22098. /**
  22099. * The end angle of the curve in radians starting from the positive X axis.
  22100. *
  22101. * @type {number}
  22102. * @default Math.PI*2
  22103. */
  22104. this.aEndAngle = aEndAngle;
  22105. /**
  22106. * Whether the ellipse is drawn clockwise or not.
  22107. *
  22108. * @type {boolean}
  22109. * @default false
  22110. */
  22111. this.aClockwise = aClockwise;
  22112. /**
  22113. * The rotation angle of the ellipse in radians, counterclockwise from the positive X axis.
  22114. *
  22115. * @type {number}
  22116. * @default 0
  22117. */
  22118. this.aRotation = aRotation;
  22119. }
  22120. /**
  22121. * Returns a point on the curve.
  22122. *
  22123. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  22124. * @param {Vector2} [optionalTarget] - The optional target vector the result is written to.
  22125. * @return {Vector2} The position on the curve.
  22126. */
  22127. getPoint( t, optionalTarget = new Vector2() ) {
  22128. const point = optionalTarget;
  22129. const twoPi = Math.PI * 2;
  22130. let deltaAngle = this.aEndAngle - this.aStartAngle;
  22131. const samePoints = Math.abs( deltaAngle ) < Number.EPSILON;
  22132. // ensures that deltaAngle is 0 .. 2 PI
  22133. while ( deltaAngle < 0 ) deltaAngle += twoPi;
  22134. while ( deltaAngle > twoPi ) deltaAngle -= twoPi;
  22135. if ( deltaAngle < Number.EPSILON ) {
  22136. if ( samePoints ) {
  22137. deltaAngle = 0;
  22138. } else {
  22139. deltaAngle = twoPi;
  22140. }
  22141. }
  22142. if ( this.aClockwise === true && ! samePoints ) {
  22143. if ( deltaAngle === twoPi ) {
  22144. deltaAngle = - twoPi;
  22145. } else {
  22146. deltaAngle = deltaAngle - twoPi;
  22147. }
  22148. }
  22149. const angle = this.aStartAngle + t * deltaAngle;
  22150. let x = this.aX + this.xRadius * Math.cos( angle );
  22151. let y = this.aY + this.yRadius * Math.sin( angle );
  22152. if ( this.aRotation !== 0 ) {
  22153. const cos = Math.cos( this.aRotation );
  22154. const sin = Math.sin( this.aRotation );
  22155. const tx = x - this.aX;
  22156. const ty = y - this.aY;
  22157. // Rotate the point about the center of the ellipse.
  22158. x = tx * cos - ty * sin + this.aX;
  22159. y = tx * sin + ty * cos + this.aY;
  22160. }
  22161. return point.set( x, y );
  22162. }
  22163. copy( source ) {
  22164. super.copy( source );
  22165. this.aX = source.aX;
  22166. this.aY = source.aY;
  22167. this.xRadius = source.xRadius;
  22168. this.yRadius = source.yRadius;
  22169. this.aStartAngle = source.aStartAngle;
  22170. this.aEndAngle = source.aEndAngle;
  22171. this.aClockwise = source.aClockwise;
  22172. this.aRotation = source.aRotation;
  22173. return this;
  22174. }
  22175. toJSON() {
  22176. const data = super.toJSON();
  22177. data.aX = this.aX;
  22178. data.aY = this.aY;
  22179. data.xRadius = this.xRadius;
  22180. data.yRadius = this.yRadius;
  22181. data.aStartAngle = this.aStartAngle;
  22182. data.aEndAngle = this.aEndAngle;
  22183. data.aClockwise = this.aClockwise;
  22184. data.aRotation = this.aRotation;
  22185. return data;
  22186. }
  22187. fromJSON( json ) {
  22188. super.fromJSON( json );
  22189. this.aX = json.aX;
  22190. this.aY = json.aY;
  22191. this.xRadius = json.xRadius;
  22192. this.yRadius = json.yRadius;
  22193. this.aStartAngle = json.aStartAngle;
  22194. this.aEndAngle = json.aEndAngle;
  22195. this.aClockwise = json.aClockwise;
  22196. this.aRotation = json.aRotation;
  22197. return this;
  22198. }
  22199. }
  22200. /**
  22201. * A curve representing an arc.
  22202. *
  22203. * @augments EllipseCurve
  22204. */
  22205. class ArcCurve extends EllipseCurve {
  22206. /**
  22207. * Constructs a new arc curve.
  22208. *
  22209. * @param {number} [aX=0] - The X center of the ellipse.
  22210. * @param {number} [aY=0] - The Y center of the ellipse.
  22211. * @param {number} [aRadius=1] - The radius of the ellipse in the x direction.
  22212. * @param {number} [aStartAngle=0] - The start angle of the curve in radians starting from the positive X axis.
  22213. * @param {number} [aEndAngle=Math.PI*2] - The end angle of the curve in radians starting from the positive X axis.
  22214. * @param {boolean} [aClockwise=false] - Whether the ellipse is drawn clockwise or not.
  22215. */
  22216. constructor( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  22217. super( aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  22218. /**
  22219. * This flag can be used for type testing.
  22220. *
  22221. * @type {boolean}
  22222. * @readonly
  22223. * @default true
  22224. */
  22225. this.isArcCurve = true;
  22226. this.type = 'ArcCurve';
  22227. }
  22228. }
  22229. function CubicPoly() {
  22230. /**
  22231. * Centripetal CatmullRom Curve - which is useful for avoiding
  22232. * cusps and self-intersections in non-uniform catmull rom curves.
  22233. * http://www.cemyuksel.com/research/catmullrom_param/catmullrom.pdf
  22234. *
  22235. * curve.type accepts centripetal(default), chordal and catmullrom
  22236. * curve.tension is used for catmullrom which defaults to 0.5
  22237. */
  22238. /*
  22239. Based on an optimized c++ solution in
  22240. - http://stackoverflow.com/questions/9489736/catmull-rom-curve-with-no-cusps-and-no-self-intersections/
  22241. - http://ideone.com/NoEbVM
  22242. This CubicPoly class could be used for reusing some variables and calculations,
  22243. but for three.js curve use, it could be possible inlined and flatten into a single function call
  22244. which can be placed in CurveUtils.
  22245. */
  22246. let c0 = 0, c1 = 0, c2 = 0, c3 = 0;
  22247. /*
  22248. * Compute coefficients for a cubic polynomial
  22249. * p(s) = c0 + c1*s + c2*s^2 + c3*s^3
  22250. * such that
  22251. * p(0) = x0, p(1) = x1
  22252. * and
  22253. * p'(0) = t0, p'(1) = t1.
  22254. */
  22255. function init( x0, x1, t0, t1 ) {
  22256. c0 = x0;
  22257. c1 = t0;
  22258. c2 = -3 * x0 + 3 * x1 - 2 * t0 - t1;
  22259. c3 = 2 * x0 - 2 * x1 + t0 + t1;
  22260. }
  22261. return {
  22262. initCatmullRom: function ( x0, x1, x2, x3, tension ) {
  22263. init( x1, x2, tension * ( x2 - x0 ), tension * ( x3 - x1 ) );
  22264. },
  22265. initNonuniformCatmullRom: function ( x0, x1, x2, x3, dt0, dt1, dt2 ) {
  22266. // compute tangents when parameterized in [t1,t2]
  22267. let t1 = ( x1 - x0 ) / dt0 - ( x2 - x0 ) / ( dt0 + dt1 ) + ( x2 - x1 ) / dt1;
  22268. let t2 = ( x2 - x1 ) / dt1 - ( x3 - x1 ) / ( dt1 + dt2 ) + ( x3 - x2 ) / dt2;
  22269. // rescale tangents for parametrization in [0,1]
  22270. t1 *= dt1;
  22271. t2 *= dt1;
  22272. init( x1, x2, t1, t2 );
  22273. },
  22274. calc: function ( t ) {
  22275. const t2 = t * t;
  22276. const t3 = t2 * t;
  22277. return c0 + c1 * t + c2 * t2 + c3 * t3;
  22278. }
  22279. };
  22280. }
  22281. //
  22282. const tmp = /*@__PURE__*/ new Vector3();
  22283. const px = /*@__PURE__*/ new CubicPoly();
  22284. const py = /*@__PURE__*/ new CubicPoly();
  22285. const pz = /*@__PURE__*/ new CubicPoly();
  22286. /**
  22287. * A curve representing a Catmull-Rom spline.
  22288. *
  22289. * ```js
  22290. * //Create a closed wavey loop
  22291. * const curve = new THREE.CatmullRomCurve3( [
  22292. * new THREE.Vector3( -10, 0, 10 ),
  22293. * new THREE.Vector3( -5, 5, 5 ),
  22294. * new THREE.Vector3( 0, 0, 0 ),
  22295. * new THREE.Vector3( 5, -5, 5 ),
  22296. * new THREE.Vector3( 10, 0, 10 )
  22297. * ] );
  22298. *
  22299. * const points = curve.getPoints( 50 );
  22300. * const geometry = new THREE.BufferGeometry().setFromPoints( points );
  22301. *
  22302. * const material = new THREE.LineBasicMaterial( { color: 0xff0000 } );
  22303. *
  22304. * // Create the final object to add to the scene
  22305. * const curveObject = new THREE.Line( geometry, material );
  22306. * ```
  22307. *
  22308. * @augments Curve
  22309. */
  22310. class CatmullRomCurve3 extends Curve {
  22311. /**
  22312. * Constructs a new Catmull-Rom curve.
  22313. *
  22314. * @param {Array<Vector3>} [points] - An array of 3D points defining the curve.
  22315. * @param {boolean} [closed=false] - Whether the curve is closed or not.
  22316. * @param {('centripetal'|'chordal'|'catmullrom')} [curveType='centripetal'] - The curve type.
  22317. * @param {number} [tension=0.5] - Tension of the curve.
  22318. */
  22319. constructor( points = [], closed = false, curveType = 'centripetal', tension = 0.5 ) {
  22320. super();
  22321. /**
  22322. * This flag can be used for type testing.
  22323. *
  22324. * @type {boolean}
  22325. * @readonly
  22326. * @default true
  22327. */
  22328. this.isCatmullRomCurve3 = true;
  22329. this.type = 'CatmullRomCurve3';
  22330. /**
  22331. * An array of 3D points defining the curve.
  22332. *
  22333. * @type {Array<Vector3>}
  22334. */
  22335. this.points = points;
  22336. /**
  22337. * Whether the curve is closed or not.
  22338. *
  22339. * @type {boolean}
  22340. * @default false
  22341. */
  22342. this.closed = closed;
  22343. /**
  22344. * The curve type.
  22345. *
  22346. * @type {('centripetal'|'chordal'|'catmullrom')}
  22347. * @default 'centripetal'
  22348. */
  22349. this.curveType = curveType;
  22350. /**
  22351. * Tension of the curve.
  22352. *
  22353. * @type {number}
  22354. * @default 0.5
  22355. */
  22356. this.tension = tension;
  22357. }
  22358. /**
  22359. * Returns a point on the curve.
  22360. *
  22361. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  22362. * @param {Vector3} [optionalTarget] - The optional target vector the result is written to.
  22363. * @return {Vector3} The position on the curve.
  22364. */
  22365. getPoint( t, optionalTarget = new Vector3() ) {
  22366. const point = optionalTarget;
  22367. const points = this.points;
  22368. const l = points.length;
  22369. const p = ( l - ( this.closed ? 0 : 1 ) ) * t;
  22370. let intPoint = Math.floor( p );
  22371. let weight = p - intPoint;
  22372. if ( this.closed ) {
  22373. intPoint += intPoint > 0 ? 0 : ( Math.floor( Math.abs( intPoint ) / l ) + 1 ) * l;
  22374. } else if ( weight === 0 && intPoint === l - 1 ) {
  22375. intPoint = l - 2;
  22376. weight = 1;
  22377. }
  22378. let p0, p3; // 4 points (p1 & p2 defined below)
  22379. if ( this.closed || intPoint > 0 ) {
  22380. p0 = points[ ( intPoint - 1 ) % l ];
  22381. } else {
  22382. // extrapolate first point
  22383. tmp.subVectors( points[ 0 ], points[ 1 ] ).add( points[ 0 ] );
  22384. p0 = tmp;
  22385. }
  22386. const p1 = points[ intPoint % l ];
  22387. const p2 = points[ ( intPoint + 1 ) % l ];
  22388. if ( this.closed || intPoint + 2 < l ) {
  22389. p3 = points[ ( intPoint + 2 ) % l ];
  22390. } else {
  22391. // extrapolate last point
  22392. tmp.subVectors( points[ l - 1 ], points[ l - 2 ] ).add( points[ l - 1 ] );
  22393. p3 = tmp;
  22394. }
  22395. if ( this.curveType === 'centripetal' || this.curveType === 'chordal' ) {
  22396. // init Centripetal / Chordal Catmull-Rom
  22397. const pow = this.curveType === 'chordal' ? 0.5 : 0.25;
  22398. let dt0 = Math.pow( p0.distanceToSquared( p1 ), pow );
  22399. let dt1 = Math.pow( p1.distanceToSquared( p2 ), pow );
  22400. let dt2 = Math.pow( p2.distanceToSquared( p3 ), pow );
  22401. // safety check for repeated points
  22402. if ( dt1 < 1e-4 ) dt1 = 1.0;
  22403. if ( dt0 < 1e-4 ) dt0 = dt1;
  22404. if ( dt2 < 1e-4 ) dt2 = dt1;
  22405. px.initNonuniformCatmullRom( p0.x, p1.x, p2.x, p3.x, dt0, dt1, dt2 );
  22406. py.initNonuniformCatmullRom( p0.y, p1.y, p2.y, p3.y, dt0, dt1, dt2 );
  22407. pz.initNonuniformCatmullRom( p0.z, p1.z, p2.z, p3.z, dt0, dt1, dt2 );
  22408. } else if ( this.curveType === 'catmullrom' ) {
  22409. px.initCatmullRom( p0.x, p1.x, p2.x, p3.x, this.tension );
  22410. py.initCatmullRom( p0.y, p1.y, p2.y, p3.y, this.tension );
  22411. pz.initCatmullRom( p0.z, p1.z, p2.z, p3.z, this.tension );
  22412. }
  22413. point.set(
  22414. px.calc( weight ),
  22415. py.calc( weight ),
  22416. pz.calc( weight )
  22417. );
  22418. return point;
  22419. }
  22420. copy( source ) {
  22421. super.copy( source );
  22422. this.points = [];
  22423. for ( let i = 0, l = source.points.length; i < l; i ++ ) {
  22424. const point = source.points[ i ];
  22425. this.points.push( point.clone() );
  22426. }
  22427. this.closed = source.closed;
  22428. this.curveType = source.curveType;
  22429. this.tension = source.tension;
  22430. return this;
  22431. }
  22432. toJSON() {
  22433. const data = super.toJSON();
  22434. data.points = [];
  22435. for ( let i = 0, l = this.points.length; i < l; i ++ ) {
  22436. const point = this.points[ i ];
  22437. data.points.push( point.toArray() );
  22438. }
  22439. data.closed = this.closed;
  22440. data.curveType = this.curveType;
  22441. data.tension = this.tension;
  22442. return data;
  22443. }
  22444. fromJSON( json ) {
  22445. super.fromJSON( json );
  22446. this.points = [];
  22447. for ( let i = 0, l = json.points.length; i < l; i ++ ) {
  22448. const point = json.points[ i ];
  22449. this.points.push( new Vector3().fromArray( point ) );
  22450. }
  22451. this.closed = json.closed;
  22452. this.curveType = json.curveType;
  22453. this.tension = json.tension;
  22454. return this;
  22455. }
  22456. }
  22457. // Bezier Curves formulas obtained from: https://en.wikipedia.org/wiki/B%C3%A9zier_curve
  22458. /**
  22459. * Computes a point on a Catmull-Rom spline.
  22460. *
  22461. * @param {number} t - The interpolation factor.
  22462. * @param {number} p0 - The first control point.
  22463. * @param {number} p1 - The second control point.
  22464. * @param {number} p2 - The third control point.
  22465. * @param {number} p3 - The fourth control point.
  22466. * @return {number} The calculated point on a Catmull-Rom spline.
  22467. */
  22468. function CatmullRom( t, p0, p1, p2, p3 ) {
  22469. const v0 = ( p2 - p0 ) * 0.5;
  22470. const v1 = ( p3 - p1 ) * 0.5;
  22471. const t2 = t * t;
  22472. const t3 = t * t2;
  22473. return ( 2 * p1 - 2 * p2 + v0 + v1 ) * t3 + ( -3 * p1 + 3 * p2 - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  22474. }
  22475. //
  22476. function QuadraticBezierP0( t, p ) {
  22477. const k = 1 - t;
  22478. return k * k * p;
  22479. }
  22480. function QuadraticBezierP1( t, p ) {
  22481. return 2 * ( 1 - t ) * t * p;
  22482. }
  22483. function QuadraticBezierP2( t, p ) {
  22484. return t * t * p;
  22485. }
  22486. /**
  22487. * Computes a point on a Quadratic Bezier curve.
  22488. *
  22489. * @param {number} t - The interpolation factor.
  22490. * @param {number} p0 - The first control point.
  22491. * @param {number} p1 - The second control point.
  22492. * @param {number} p2 - The third control point.
  22493. * @return {number} The calculated point on a Quadratic Bezier curve.
  22494. */
  22495. function QuadraticBezier( t, p0, p1, p2 ) {
  22496. return QuadraticBezierP0( t, p0 ) + QuadraticBezierP1( t, p1 ) +
  22497. QuadraticBezierP2( t, p2 );
  22498. }
  22499. //
  22500. function CubicBezierP0( t, p ) {
  22501. const k = 1 - t;
  22502. return k * k * k * p;
  22503. }
  22504. function CubicBezierP1( t, p ) {
  22505. const k = 1 - t;
  22506. return 3 * k * k * t * p;
  22507. }
  22508. function CubicBezierP2( t, p ) {
  22509. return 3 * ( 1 - t ) * t * t * p;
  22510. }
  22511. function CubicBezierP3( t, p ) {
  22512. return t * t * t * p;
  22513. }
  22514. /**
  22515. * Computes a point on a Cubic Bezier curve.
  22516. *
  22517. * @param {number} t - The interpolation factor.
  22518. * @param {number} p0 - The first control point.
  22519. * @param {number} p1 - The second control point.
  22520. * @param {number} p2 - The third control point.
  22521. * @param {number} p3 - The fourth control point.
  22522. * @return {number} The calculated point on a Cubic Bezier curve.
  22523. */
  22524. function CubicBezier( t, p0, p1, p2, p3 ) {
  22525. return CubicBezierP0( t, p0 ) + CubicBezierP1( t, p1 ) + CubicBezierP2( t, p2 ) +
  22526. CubicBezierP3( t, p3 );
  22527. }
  22528. /**
  22529. * A curve representing a 2D Cubic Bezier curve.
  22530. *
  22531. * ```js
  22532. * const curve = new THREE.CubicBezierCurve(
  22533. * new THREE.Vector2( - 0, 0 ),
  22534. * new THREE.Vector2( - 5, 15 ),
  22535. * new THREE.Vector2( 20, 15 ),
  22536. * new THREE.Vector2( 10, 0 )
  22537. * );
  22538. *
  22539. * const points = curve.getPoints( 50 );
  22540. * const geometry = new THREE.BufferGeometry().setFromPoints( points );
  22541. *
  22542. * const material = new THREE.LineBasicMaterial( { color: 0xff0000 } );
  22543. *
  22544. * // Create the final object to add to the scene
  22545. * const curveObject = new THREE.Line( geometry, material );
  22546. * ```
  22547. *
  22548. * @augments Curve
  22549. */
  22550. class CubicBezierCurve extends Curve {
  22551. /**
  22552. * Constructs a new Cubic Bezier curve.
  22553. *
  22554. * @param {Vector2} [v0] - The start point.
  22555. * @param {Vector2} [v1] - The first control point.
  22556. * @param {Vector2} [v2] - The second control point.
  22557. * @param {Vector2} [v3] - The end point.
  22558. */
  22559. constructor( v0 = new Vector2(), v1 = new Vector2(), v2 = new Vector2(), v3 = new Vector2() ) {
  22560. super();
  22561. /**
  22562. * This flag can be used for type testing.
  22563. *
  22564. * @type {boolean}
  22565. * @readonly
  22566. * @default true
  22567. */
  22568. this.isCubicBezierCurve = true;
  22569. this.type = 'CubicBezierCurve';
  22570. /**
  22571. * The start point.
  22572. *
  22573. * @type {Vector2}
  22574. */
  22575. this.v0 = v0;
  22576. /**
  22577. * The first control point.
  22578. *
  22579. * @type {Vector2}
  22580. */
  22581. this.v1 = v1;
  22582. /**
  22583. * The second control point.
  22584. *
  22585. * @type {Vector2}
  22586. */
  22587. this.v2 = v2;
  22588. /**
  22589. * The end point.
  22590. *
  22591. * @type {Vector2}
  22592. */
  22593. this.v3 = v3;
  22594. }
  22595. /**
  22596. * Returns a point on the curve.
  22597. *
  22598. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  22599. * @param {Vector2} [optionalTarget] - The optional target vector the result is written to.
  22600. * @return {Vector2} The position on the curve.
  22601. */
  22602. getPoint( t, optionalTarget = new Vector2() ) {
  22603. const point = optionalTarget;
  22604. const v0 = this.v0, v1 = this.v1, v2 = this.v2, v3 = this.v3;
  22605. point.set(
  22606. CubicBezier( t, v0.x, v1.x, v2.x, v3.x ),
  22607. CubicBezier( t, v0.y, v1.y, v2.y, v3.y )
  22608. );
  22609. return point;
  22610. }
  22611. copy( source ) {
  22612. super.copy( source );
  22613. this.v0.copy( source.v0 );
  22614. this.v1.copy( source.v1 );
  22615. this.v2.copy( source.v2 );
  22616. this.v3.copy( source.v3 );
  22617. return this;
  22618. }
  22619. toJSON() {
  22620. const data = super.toJSON();
  22621. data.v0 = this.v0.toArray();
  22622. data.v1 = this.v1.toArray();
  22623. data.v2 = this.v2.toArray();
  22624. data.v3 = this.v3.toArray();
  22625. return data;
  22626. }
  22627. fromJSON( json ) {
  22628. super.fromJSON( json );
  22629. this.v0.fromArray( json.v0 );
  22630. this.v1.fromArray( json.v1 );
  22631. this.v2.fromArray( json.v2 );
  22632. this.v3.fromArray( json.v3 );
  22633. return this;
  22634. }
  22635. }
  22636. /**
  22637. * A curve representing a 3D Cubic Bezier curve.
  22638. *
  22639. * @augments Curve
  22640. */
  22641. class CubicBezierCurve3 extends Curve {
  22642. /**
  22643. * Constructs a new Cubic Bezier curve.
  22644. *
  22645. * @param {Vector3} [v0] - The start point.
  22646. * @param {Vector3} [v1] - The first control point.
  22647. * @param {Vector3} [v2] - The second control point.
  22648. * @param {Vector3} [v3] - The end point.
  22649. */
  22650. constructor( v0 = new Vector3(), v1 = new Vector3(), v2 = new Vector3(), v3 = new Vector3() ) {
  22651. super();
  22652. /**
  22653. * This flag can be used for type testing.
  22654. *
  22655. * @type {boolean}
  22656. * @readonly
  22657. * @default true
  22658. */
  22659. this.isCubicBezierCurve3 = true;
  22660. this.type = 'CubicBezierCurve3';
  22661. /**
  22662. * The start point.
  22663. *
  22664. * @type {Vector3}
  22665. */
  22666. this.v0 = v0;
  22667. /**
  22668. * The first control point.
  22669. *
  22670. * @type {Vector3}
  22671. */
  22672. this.v1 = v1;
  22673. /**
  22674. * The second control point.
  22675. *
  22676. * @type {Vector3}
  22677. */
  22678. this.v2 = v2;
  22679. /**
  22680. * The end point.
  22681. *
  22682. * @type {Vector3}
  22683. */
  22684. this.v3 = v3;
  22685. }
  22686. /**
  22687. * Returns a point on the curve.
  22688. *
  22689. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  22690. * @param {Vector3} [optionalTarget] - The optional target vector the result is written to.
  22691. * @return {Vector3} The position on the curve.
  22692. */
  22693. getPoint( t, optionalTarget = new Vector3() ) {
  22694. const point = optionalTarget;
  22695. const v0 = this.v0, v1 = this.v1, v2 = this.v2, v3 = this.v3;
  22696. point.set(
  22697. CubicBezier( t, v0.x, v1.x, v2.x, v3.x ),
  22698. CubicBezier( t, v0.y, v1.y, v2.y, v3.y ),
  22699. CubicBezier( t, v0.z, v1.z, v2.z, v3.z )
  22700. );
  22701. return point;
  22702. }
  22703. copy( source ) {
  22704. super.copy( source );
  22705. this.v0.copy( source.v0 );
  22706. this.v1.copy( source.v1 );
  22707. this.v2.copy( source.v2 );
  22708. this.v3.copy( source.v3 );
  22709. return this;
  22710. }
  22711. toJSON() {
  22712. const data = super.toJSON();
  22713. data.v0 = this.v0.toArray();
  22714. data.v1 = this.v1.toArray();
  22715. data.v2 = this.v2.toArray();
  22716. data.v3 = this.v3.toArray();
  22717. return data;
  22718. }
  22719. fromJSON( json ) {
  22720. super.fromJSON( json );
  22721. this.v0.fromArray( json.v0 );
  22722. this.v1.fromArray( json.v1 );
  22723. this.v2.fromArray( json.v2 );
  22724. this.v3.fromArray( json.v3 );
  22725. return this;
  22726. }
  22727. }
  22728. /**
  22729. * A curve representing a 2D line segment.
  22730. *
  22731. * @augments Curve
  22732. */
  22733. class LineCurve extends Curve {
  22734. /**
  22735. * Constructs a new line curve.
  22736. *
  22737. * @param {Vector2} [v1] - The start point.
  22738. * @param {Vector2} [v2] - The end point.
  22739. */
  22740. constructor( v1 = new Vector2(), v2 = new Vector2() ) {
  22741. super();
  22742. /**
  22743. * This flag can be used for type testing.
  22744. *
  22745. * @type {boolean}
  22746. * @readonly
  22747. * @default true
  22748. */
  22749. this.isLineCurve = true;
  22750. this.type = 'LineCurve';
  22751. /**
  22752. * The start point.
  22753. *
  22754. * @type {Vector2}
  22755. */
  22756. this.v1 = v1;
  22757. /**
  22758. * The end point.
  22759. *
  22760. * @type {Vector2}
  22761. */
  22762. this.v2 = v2;
  22763. }
  22764. /**
  22765. * Returns a point on the line.
  22766. *
  22767. * @param {number} t - A interpolation factor representing a position on the line. Must be in the range `[0,1]`.
  22768. * @param {Vector2} [optionalTarget] - The optional target vector the result is written to.
  22769. * @return {Vector2} The position on the line.
  22770. */
  22771. getPoint( t, optionalTarget = new Vector2() ) {
  22772. const point = optionalTarget;
  22773. if ( t === 1 ) {
  22774. point.copy( this.v2 );
  22775. } else {
  22776. point.copy( this.v2 ).sub( this.v1 );
  22777. point.multiplyScalar( t ).add( this.v1 );
  22778. }
  22779. return point;
  22780. }
  22781. // Line curve is linear, so we can overwrite default getPointAt
  22782. getPointAt( u, optionalTarget ) {
  22783. return this.getPoint( u, optionalTarget );
  22784. }
  22785. getTangent( t, optionalTarget = new Vector2() ) {
  22786. return optionalTarget.subVectors( this.v2, this.v1 ).normalize();
  22787. }
  22788. getTangentAt( u, optionalTarget ) {
  22789. return this.getTangent( u, optionalTarget );
  22790. }
  22791. copy( source ) {
  22792. super.copy( source );
  22793. this.v1.copy( source.v1 );
  22794. this.v2.copy( source.v2 );
  22795. return this;
  22796. }
  22797. toJSON() {
  22798. const data = super.toJSON();
  22799. data.v1 = this.v1.toArray();
  22800. data.v2 = this.v2.toArray();
  22801. return data;
  22802. }
  22803. fromJSON( json ) {
  22804. super.fromJSON( json );
  22805. this.v1.fromArray( json.v1 );
  22806. this.v2.fromArray( json.v2 );
  22807. return this;
  22808. }
  22809. }
  22810. /**
  22811. * A curve representing a 3D line segment.
  22812. *
  22813. * @augments Curve
  22814. */
  22815. class LineCurve3 extends Curve {
  22816. /**
  22817. * Constructs a new line curve.
  22818. *
  22819. * @param {Vector3} [v1] - The start point.
  22820. * @param {Vector3} [v2] - The end point.
  22821. */
  22822. constructor( v1 = new Vector3(), v2 = new Vector3() ) {
  22823. super();
  22824. /**
  22825. * This flag can be used for type testing.
  22826. *
  22827. * @type {boolean}
  22828. * @readonly
  22829. * @default true
  22830. */
  22831. this.isLineCurve3 = true;
  22832. this.type = 'LineCurve3';
  22833. /**
  22834. * The start point.
  22835. *
  22836. * @type {Vector3}
  22837. */
  22838. this.v1 = v1;
  22839. /**
  22840. * The end point.
  22841. *
  22842. * @type {Vector2}
  22843. */
  22844. this.v2 = v2;
  22845. }
  22846. /**
  22847. * Returns a point on the line.
  22848. *
  22849. * @param {number} t - A interpolation factor representing a position on the line. Must be in the range `[0,1]`.
  22850. * @param {Vector3} [optionalTarget] - The optional target vector the result is written to.
  22851. * @return {Vector3} The position on the line.
  22852. */
  22853. getPoint( t, optionalTarget = new Vector3() ) {
  22854. const point = optionalTarget;
  22855. if ( t === 1 ) {
  22856. point.copy( this.v2 );
  22857. } else {
  22858. point.copy( this.v2 ).sub( this.v1 );
  22859. point.multiplyScalar( t ).add( this.v1 );
  22860. }
  22861. return point;
  22862. }
  22863. // Line curve is linear, so we can overwrite default getPointAt
  22864. getPointAt( u, optionalTarget ) {
  22865. return this.getPoint( u, optionalTarget );
  22866. }
  22867. getTangent( t, optionalTarget = new Vector3() ) {
  22868. return optionalTarget.subVectors( this.v2, this.v1 ).normalize();
  22869. }
  22870. getTangentAt( u, optionalTarget ) {
  22871. return this.getTangent( u, optionalTarget );
  22872. }
  22873. copy( source ) {
  22874. super.copy( source );
  22875. this.v1.copy( source.v1 );
  22876. this.v2.copy( source.v2 );
  22877. return this;
  22878. }
  22879. toJSON() {
  22880. const data = super.toJSON();
  22881. data.v1 = this.v1.toArray();
  22882. data.v2 = this.v2.toArray();
  22883. return data;
  22884. }
  22885. fromJSON( json ) {
  22886. super.fromJSON( json );
  22887. this.v1.fromArray( json.v1 );
  22888. this.v2.fromArray( json.v2 );
  22889. return this;
  22890. }
  22891. }
  22892. /**
  22893. * A curve representing a 2D Quadratic Bezier curve.
  22894. *
  22895. * ```js
  22896. * const curve = new THREE.QuadraticBezierCurve(
  22897. * new THREE.Vector2( - 10, 0 ),
  22898. * new THREE.Vector2( 20, 15 ),
  22899. * new THREE.Vector2( 10, 0 )
  22900. * )
  22901. *
  22902. * const points = curve.getPoints( 50 );
  22903. * const geometry = new THREE.BufferGeometry().setFromPoints( points );
  22904. *
  22905. * const material = new THREE.LineBasicMaterial( { color: 0xff0000 } );
  22906. *
  22907. * // Create the final object to add to the scene
  22908. * const curveObject = new THREE.Line( geometry, material );
  22909. * ```
  22910. *
  22911. * @augments Curve
  22912. */
  22913. class QuadraticBezierCurve extends Curve {
  22914. /**
  22915. * Constructs a new Quadratic Bezier curve.
  22916. *
  22917. * @param {Vector2} [v0] - The start point.
  22918. * @param {Vector2} [v1] - The control point.
  22919. * @param {Vector2} [v2] - The end point.
  22920. */
  22921. constructor( v0 = new Vector2(), v1 = new Vector2(), v2 = new Vector2() ) {
  22922. super();
  22923. /**
  22924. * This flag can be used for type testing.
  22925. *
  22926. * @type {boolean}
  22927. * @readonly
  22928. * @default true
  22929. */
  22930. this.isQuadraticBezierCurve = true;
  22931. this.type = 'QuadraticBezierCurve';
  22932. /**
  22933. * The start point.
  22934. *
  22935. * @type {Vector2}
  22936. */
  22937. this.v0 = v0;
  22938. /**
  22939. * The control point.
  22940. *
  22941. * @type {Vector2}
  22942. */
  22943. this.v1 = v1;
  22944. /**
  22945. * The end point.
  22946. *
  22947. * @type {Vector2}
  22948. */
  22949. this.v2 = v2;
  22950. }
  22951. /**
  22952. * Returns a point on the curve.
  22953. *
  22954. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  22955. * @param {Vector2} [optionalTarget] - The optional target vector the result is written to.
  22956. * @return {Vector2} The position on the curve.
  22957. */
  22958. getPoint( t, optionalTarget = new Vector2() ) {
  22959. const point = optionalTarget;
  22960. const v0 = this.v0, v1 = this.v1, v2 = this.v2;
  22961. point.set(
  22962. QuadraticBezier( t, v0.x, v1.x, v2.x ),
  22963. QuadraticBezier( t, v0.y, v1.y, v2.y )
  22964. );
  22965. return point;
  22966. }
  22967. copy( source ) {
  22968. super.copy( source );
  22969. this.v0.copy( source.v0 );
  22970. this.v1.copy( source.v1 );
  22971. this.v2.copy( source.v2 );
  22972. return this;
  22973. }
  22974. toJSON() {
  22975. const data = super.toJSON();
  22976. data.v0 = this.v0.toArray();
  22977. data.v1 = this.v1.toArray();
  22978. data.v2 = this.v2.toArray();
  22979. return data;
  22980. }
  22981. fromJSON( json ) {
  22982. super.fromJSON( json );
  22983. this.v0.fromArray( json.v0 );
  22984. this.v1.fromArray( json.v1 );
  22985. this.v2.fromArray( json.v2 );
  22986. return this;
  22987. }
  22988. }
  22989. /**
  22990. * A curve representing a 3D Quadratic Bezier curve.
  22991. *
  22992. * @augments Curve
  22993. */
  22994. class QuadraticBezierCurve3 extends Curve {
  22995. /**
  22996. * Constructs a new Quadratic Bezier curve.
  22997. *
  22998. * @param {Vector3} [v0] - The start point.
  22999. * @param {Vector3} [v1] - The control point.
  23000. * @param {Vector3} [v2] - The end point.
  23001. */
  23002. constructor( v0 = new Vector3(), v1 = new Vector3(), v2 = new Vector3() ) {
  23003. super();
  23004. /**
  23005. * This flag can be used for type testing.
  23006. *
  23007. * @type {boolean}
  23008. * @readonly
  23009. * @default true
  23010. */
  23011. this.isQuadraticBezierCurve3 = true;
  23012. this.type = 'QuadraticBezierCurve3';
  23013. /**
  23014. * The start point.
  23015. *
  23016. * @type {Vector3}
  23017. */
  23018. this.v0 = v0;
  23019. /**
  23020. * The control point.
  23021. *
  23022. * @type {Vector3}
  23023. */
  23024. this.v1 = v1;
  23025. /**
  23026. * The end point.
  23027. *
  23028. * @type {Vector3}
  23029. */
  23030. this.v2 = v2;
  23031. }
  23032. /**
  23033. * Returns a point on the curve.
  23034. *
  23035. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  23036. * @param {Vector3} [optionalTarget] - The optional target vector the result is written to.
  23037. * @return {Vector3} The position on the curve.
  23038. */
  23039. getPoint( t, optionalTarget = new Vector3() ) {
  23040. const point = optionalTarget;
  23041. const v0 = this.v0, v1 = this.v1, v2 = this.v2;
  23042. point.set(
  23043. QuadraticBezier( t, v0.x, v1.x, v2.x ),
  23044. QuadraticBezier( t, v0.y, v1.y, v2.y ),
  23045. QuadraticBezier( t, v0.z, v1.z, v2.z )
  23046. );
  23047. return point;
  23048. }
  23049. copy( source ) {
  23050. super.copy( source );
  23051. this.v0.copy( source.v0 );
  23052. this.v1.copy( source.v1 );
  23053. this.v2.copy( source.v2 );
  23054. return this;
  23055. }
  23056. toJSON() {
  23057. const data = super.toJSON();
  23058. data.v0 = this.v0.toArray();
  23059. data.v1 = this.v1.toArray();
  23060. data.v2 = this.v2.toArray();
  23061. return data;
  23062. }
  23063. fromJSON( json ) {
  23064. super.fromJSON( json );
  23065. this.v0.fromArray( json.v0 );
  23066. this.v1.fromArray( json.v1 );
  23067. this.v2.fromArray( json.v2 );
  23068. return this;
  23069. }
  23070. }
  23071. /**
  23072. * A curve representing a 2D spline curve.
  23073. *
  23074. * ```js
  23075. * // Create a sine-like wave
  23076. * const curve = new THREE.SplineCurve( [
  23077. * new THREE.Vector2( -10, 0 ),
  23078. * new THREE.Vector2( -5, 5 ),
  23079. * new THREE.Vector2( 0, 0 ),
  23080. * new THREE.Vector2( 5, -5 ),
  23081. * new THREE.Vector2( 10, 0 )
  23082. * ] );
  23083. *
  23084. * const points = curve.getPoints( 50 );
  23085. * const geometry = new THREE.BufferGeometry().setFromPoints( points );
  23086. *
  23087. * const material = new THREE.LineBasicMaterial( { color: 0xff0000 } );
  23088. *
  23089. * // Create the final object to add to the scene
  23090. * const splineObject = new THREE.Line( geometry, material );
  23091. * ```
  23092. *
  23093. * @augments Curve
  23094. */
  23095. class SplineCurve extends Curve {
  23096. /**
  23097. * Constructs a new 2D spline curve.
  23098. *
  23099. * @param {Array<Vector2>} [points] - An array of 2D points defining the curve.
  23100. */
  23101. constructor( points = [] ) {
  23102. super();
  23103. /**
  23104. * This flag can be used for type testing.
  23105. *
  23106. * @type {boolean}
  23107. * @readonly
  23108. * @default true
  23109. */
  23110. this.isSplineCurve = true;
  23111. this.type = 'SplineCurve';
  23112. /**
  23113. * An array of 2D points defining the curve.
  23114. *
  23115. * @type {Array<Vector2>}
  23116. */
  23117. this.points = points;
  23118. }
  23119. /**
  23120. * Returns a point on the curve.
  23121. *
  23122. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  23123. * @param {Vector2} [optionalTarget] - The optional target vector the result is written to.
  23124. * @return {Vector2} The position on the curve.
  23125. */
  23126. getPoint( t, optionalTarget = new Vector2() ) {
  23127. const point = optionalTarget;
  23128. const points = this.points;
  23129. const p = ( points.length - 1 ) * t;
  23130. const intPoint = Math.floor( p );
  23131. const weight = p - intPoint;
  23132. const p0 = points[ intPoint === 0 ? intPoint : intPoint - 1 ];
  23133. const p1 = points[ intPoint ];
  23134. const p2 = points[ intPoint > points.length - 2 ? points.length - 1 : intPoint + 1 ];
  23135. const p3 = points[ intPoint > points.length - 3 ? points.length - 1 : intPoint + 2 ];
  23136. point.set(
  23137. CatmullRom( weight, p0.x, p1.x, p2.x, p3.x ),
  23138. CatmullRom( weight, p0.y, p1.y, p2.y, p3.y )
  23139. );
  23140. return point;
  23141. }
  23142. copy( source ) {
  23143. super.copy( source );
  23144. this.points = [];
  23145. for ( let i = 0, l = source.points.length; i < l; i ++ ) {
  23146. const point = source.points[ i ];
  23147. this.points.push( point.clone() );
  23148. }
  23149. return this;
  23150. }
  23151. toJSON() {
  23152. const data = super.toJSON();
  23153. data.points = [];
  23154. for ( let i = 0, l = this.points.length; i < l; i ++ ) {
  23155. const point = this.points[ i ];
  23156. data.points.push( point.toArray() );
  23157. }
  23158. return data;
  23159. }
  23160. fromJSON( json ) {
  23161. super.fromJSON( json );
  23162. this.points = [];
  23163. for ( let i = 0, l = json.points.length; i < l; i ++ ) {
  23164. const point = json.points[ i ];
  23165. this.points.push( new Vector2().fromArray( point ) );
  23166. }
  23167. return this;
  23168. }
  23169. }
  23170. var Curves = /*#__PURE__*/Object.freeze({
  23171. __proto__: null,
  23172. ArcCurve: ArcCurve,
  23173. CatmullRomCurve3: CatmullRomCurve3,
  23174. CubicBezierCurve: CubicBezierCurve,
  23175. CubicBezierCurve3: CubicBezierCurve3,
  23176. EllipseCurve: EllipseCurve,
  23177. LineCurve: LineCurve,
  23178. LineCurve3: LineCurve3,
  23179. QuadraticBezierCurve: QuadraticBezierCurve,
  23180. QuadraticBezierCurve3: QuadraticBezierCurve3,
  23181. SplineCurve: SplineCurve
  23182. });
  23183. /**
  23184. * A base class extending {@link Curve}. `CurvePath` is simply an
  23185. * array of connected curves, but retains the API of a curve.
  23186. *
  23187. * @augments Curve
  23188. */
  23189. class CurvePath extends Curve {
  23190. /**
  23191. * Constructs a new curve path.
  23192. */
  23193. constructor() {
  23194. super();
  23195. this.type = 'CurvePath';
  23196. /**
  23197. * An array of curves defining the
  23198. * path.
  23199. *
  23200. * @type {Array<Curve>}
  23201. */
  23202. this.curves = [];
  23203. /**
  23204. * Whether the path should automatically be closed
  23205. * by a line curve.
  23206. *
  23207. * @type {boolean}
  23208. * @default false
  23209. */
  23210. this.autoClose = false;
  23211. }
  23212. /**
  23213. * Adds a curve to this curve path.
  23214. *
  23215. * @param {Curve} curve - The curve to add.
  23216. */
  23217. add( curve ) {
  23218. this.curves.push( curve );
  23219. }
  23220. /**
  23221. * Adds a line curve to close the path.
  23222. *
  23223. * @return {CurvePath} A reference to this curve path.
  23224. */
  23225. closePath() {
  23226. // Add a line curve if start and end of lines are not connected
  23227. const startPoint = this.curves[ 0 ].getPoint( 0 );
  23228. const endPoint = this.curves[ this.curves.length - 1 ].getPoint( 1 );
  23229. if ( ! startPoint.equals( endPoint ) ) {
  23230. const lineType = ( startPoint.isVector2 === true ) ? 'LineCurve' : 'LineCurve3';
  23231. this.curves.push( new Curves[ lineType ]( endPoint, startPoint ) );
  23232. }
  23233. return this;
  23234. }
  23235. /**
  23236. * This method returns a vector in 2D or 3D space (depending on the curve definitions)
  23237. * for the given interpolation factor.
  23238. *
  23239. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  23240. * @param {(Vector2|Vector3)} [optionalTarget] - The optional target vector the result is written to.
  23241. * @return {?(Vector2|Vector3)} The position on the curve. It can be a 2D or 3D vector depending on the curve definition.
  23242. */
  23243. getPoint( t, optionalTarget ) {
  23244. // To get accurate point with reference to
  23245. // entire path distance at time t,
  23246. // following has to be done:
  23247. // 1. Length of each sub path have to be known
  23248. // 2. Locate and identify type of curve
  23249. // 3. Get t for the curve
  23250. // 4. Return curve.getPointAt(t')
  23251. const d = t * this.getLength();
  23252. const curveLengths = this.getCurveLengths();
  23253. let i = 0;
  23254. // To think about boundaries points.
  23255. while ( i < curveLengths.length ) {
  23256. if ( curveLengths[ i ] >= d ) {
  23257. const diff = curveLengths[ i ] - d;
  23258. const curve = this.curves[ i ];
  23259. const segmentLength = curve.getLength();
  23260. const u = segmentLength === 0 ? 0 : 1 - diff / segmentLength;
  23261. return curve.getPointAt( u, optionalTarget );
  23262. }
  23263. i ++;
  23264. }
  23265. return null;
  23266. // loop where sum != 0, sum > d , sum+1 <d
  23267. }
  23268. getLength() {
  23269. // We cannot use the default THREE.Curve getPoint() with getLength() because in
  23270. // THREE.Curve, getLength() depends on getPoint() but in THREE.CurvePath
  23271. // getPoint() depends on getLength
  23272. const lens = this.getCurveLengths();
  23273. return lens[ lens.length - 1 ];
  23274. }
  23275. updateArcLengths() {
  23276. // cacheLengths must be recalculated.
  23277. this.needsUpdate = true;
  23278. this.cacheLengths = null;
  23279. this.getCurveLengths();
  23280. }
  23281. /**
  23282. * Returns list of cumulative curve lengths of the defined curves.
  23283. *
  23284. * @return {Array<number>} The curve lengths.
  23285. */
  23286. getCurveLengths() {
  23287. // Compute lengths and cache them
  23288. // We cannot overwrite getLengths() because UtoT mapping uses it.
  23289. // We use cache values if curves and cache array are same length
  23290. if ( this.cacheLengths && this.cacheLengths.length === this.curves.length ) {
  23291. return this.cacheLengths;
  23292. }
  23293. // Get length of sub-curve
  23294. // Push sums into cached array
  23295. const lengths = [];
  23296. let sums = 0;
  23297. for ( let i = 0, l = this.curves.length; i < l; i ++ ) {
  23298. sums += this.curves[ i ].getLength();
  23299. lengths.push( sums );
  23300. }
  23301. this.cacheLengths = lengths;
  23302. return lengths;
  23303. }
  23304. getSpacedPoints( divisions = 40 ) {
  23305. const points = [];
  23306. for ( let i = 0; i <= divisions; i ++ ) {
  23307. points.push( this.getPoint( i / divisions ) );
  23308. }
  23309. if ( this.autoClose ) {
  23310. points.push( points[ 0 ] );
  23311. }
  23312. return points;
  23313. }
  23314. getPoints( divisions = 12 ) {
  23315. const points = [];
  23316. let last;
  23317. for ( let i = 0, curves = this.curves; i < curves.length; i ++ ) {
  23318. const curve = curves[ i ];
  23319. const resolution = curve.isEllipseCurve ? divisions * 2
  23320. : ( curve.isLineCurve || curve.isLineCurve3 ) ? 1
  23321. : curve.isSplineCurve ? divisions * curve.points.length
  23322. : divisions;
  23323. const pts = curve.getPoints( resolution );
  23324. for ( let j = 0; j < pts.length; j ++ ) {
  23325. const point = pts[ j ];
  23326. if ( last && last.equals( point ) ) continue; // ensures no consecutive points are duplicates
  23327. points.push( point );
  23328. last = point;
  23329. }
  23330. }
  23331. if ( this.autoClose && points.length > 1 && ! points[ points.length - 1 ].equals( points[ 0 ] ) ) {
  23332. points.push( points[ 0 ] );
  23333. }
  23334. return points;
  23335. }
  23336. copy( source ) {
  23337. super.copy( source );
  23338. this.curves = [];
  23339. for ( let i = 0, l = source.curves.length; i < l; i ++ ) {
  23340. const curve = source.curves[ i ];
  23341. this.curves.push( curve.clone() );
  23342. }
  23343. this.autoClose = source.autoClose;
  23344. return this;
  23345. }
  23346. toJSON() {
  23347. const data = super.toJSON();
  23348. data.autoClose = this.autoClose;
  23349. data.curves = [];
  23350. for ( let i = 0, l = this.curves.length; i < l; i ++ ) {
  23351. const curve = this.curves[ i ];
  23352. data.curves.push( curve.toJSON() );
  23353. }
  23354. return data;
  23355. }
  23356. fromJSON( json ) {
  23357. super.fromJSON( json );
  23358. this.autoClose = json.autoClose;
  23359. this.curves = [];
  23360. for ( let i = 0, l = json.curves.length; i < l; i ++ ) {
  23361. const curve = json.curves[ i ];
  23362. this.curves.push( new Curves[ curve.type ]().fromJSON( curve ) );
  23363. }
  23364. return this;
  23365. }
  23366. }
  23367. /**
  23368. * A 2D path representation. The class provides methods for creating paths
  23369. * and contours of 2D shapes similar to the 2D Canvas API.
  23370. *
  23371. * ```js
  23372. * const path = new THREE.Path();
  23373. *
  23374. * path.lineTo( 0, 0.8 );
  23375. * path.quadraticCurveTo( 0, 1, 0.2, 1 );
  23376. * path.lineTo( 1, 1 );
  23377. *
  23378. * const points = path.getPoints();
  23379. *
  23380. * const geometry = new THREE.BufferGeometry().setFromPoints( points );
  23381. * const material = new THREE.LineBasicMaterial( { color: 0xffffff } );
  23382. *
  23383. * const line = new THREE.Line( geometry, material );
  23384. * scene.add( line );
  23385. * ```
  23386. *
  23387. * @augments CurvePath
  23388. */
  23389. class Path extends CurvePath {
  23390. /**
  23391. * Constructs a new path.
  23392. *
  23393. * @param {Array<Vector2>} [points] - An array of 2D points defining the path.
  23394. */
  23395. constructor( points ) {
  23396. super();
  23397. this.type = 'Path';
  23398. /**
  23399. * The current offset of the path. Any new curve added will start here.
  23400. *
  23401. * @type {Vector2}
  23402. */
  23403. this.currentPoint = new Vector2();
  23404. if ( points ) {
  23405. this.setFromPoints( points );
  23406. }
  23407. }
  23408. /**
  23409. * Creates a path from the given list of points. The points are added
  23410. * to the path as instances of {@link LineCurve}.
  23411. *
  23412. * @param {Array<Vector2>} points - An array of 2D points.
  23413. * @return {Path} A reference to this path.
  23414. */
  23415. setFromPoints( points ) {
  23416. this.moveTo( points[ 0 ].x, points[ 0 ].y );
  23417. for ( let i = 1, l = points.length; i < l; i ++ ) {
  23418. this.lineTo( points[ i ].x, points[ i ].y );
  23419. }
  23420. return this;
  23421. }
  23422. /**
  23423. * Moves {@link Path#currentPoint} to the given point.
  23424. *
  23425. * @param {number} x - The x coordinate.
  23426. * @param {number} y - The y coordinate.
  23427. * @return {Path} A reference to this path.
  23428. */
  23429. moveTo( x, y ) {
  23430. this.currentPoint.set( x, y ); // TODO consider referencing vectors instead of copying?
  23431. return this;
  23432. }
  23433. /**
  23434. * Adds an instance of {@link LineCurve} to the path by connecting
  23435. * the current point with the given one.
  23436. *
  23437. * @param {number} x - The x coordinate of the end point.
  23438. * @param {number} y - The y coordinate of the end point.
  23439. * @return {Path} A reference to this path.
  23440. */
  23441. lineTo( x, y ) {
  23442. const curve = new LineCurve( this.currentPoint.clone(), new Vector2( x, y ) );
  23443. this.curves.push( curve );
  23444. this.currentPoint.set( x, y );
  23445. return this;
  23446. }
  23447. /**
  23448. * Adds an instance of {@link QuadraticBezierCurve} to the path by connecting
  23449. * the current point with the given one.
  23450. *
  23451. * @param {number} aCPx - The x coordinate of the control point.
  23452. * @param {number} aCPy - The y coordinate of the control point.
  23453. * @param {number} aX - The x coordinate of the end point.
  23454. * @param {number} aY - The y coordinate of the end point.
  23455. * @return {Path} A reference to this path.
  23456. */
  23457. quadraticCurveTo( aCPx, aCPy, aX, aY ) {
  23458. const curve = new QuadraticBezierCurve(
  23459. this.currentPoint.clone(),
  23460. new Vector2( aCPx, aCPy ),
  23461. new Vector2( aX, aY )
  23462. );
  23463. this.curves.push( curve );
  23464. this.currentPoint.set( aX, aY );
  23465. return this;
  23466. }
  23467. /**
  23468. * Adds an instance of {@link CubicBezierCurve} to the path by connecting
  23469. * the current point with the given one.
  23470. *
  23471. * @param {number} aCP1x - The x coordinate of the first control point.
  23472. * @param {number} aCP1y - The y coordinate of the first control point.
  23473. * @param {number} aCP2x - The x coordinate of the second control point.
  23474. * @param {number} aCP2y - The y coordinate of the second control point.
  23475. * @param {number} aX - The x coordinate of the end point.
  23476. * @param {number} aY - The y coordinate of the end point.
  23477. * @return {Path} A reference to this path.
  23478. */
  23479. bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) {
  23480. const curve = new CubicBezierCurve(
  23481. this.currentPoint.clone(),
  23482. new Vector2( aCP1x, aCP1y ),
  23483. new Vector2( aCP2x, aCP2y ),
  23484. new Vector2( aX, aY )
  23485. );
  23486. this.curves.push( curve );
  23487. this.currentPoint.set( aX, aY );
  23488. return this;
  23489. }
  23490. /**
  23491. * Adds an instance of {@link SplineCurve} to the path by connecting
  23492. * the current point with the given list of points.
  23493. *
  23494. * @param {Array<Vector2>} pts - An array of points in 2D space.
  23495. * @return {Path} A reference to this path.
  23496. */
  23497. splineThru( pts ) {
  23498. const npts = [ this.currentPoint.clone() ].concat( pts );
  23499. const curve = new SplineCurve( npts );
  23500. this.curves.push( curve );
  23501. this.currentPoint.copy( pts[ pts.length - 1 ] );
  23502. return this;
  23503. }
  23504. /**
  23505. * Adds an arc as an instance of {@link EllipseCurve} to the path, positioned relative
  23506. * to the current point.
  23507. *
  23508. * @param {number} aX - The x coordinate of the center of the arc offsetted from the previous curve.
  23509. * @param {number} aY - The y coordinate of the center of the arc offsetted from the previous curve.
  23510. * @param {number} aRadius - The radius of the arc.
  23511. * @param {number} aStartAngle - The start angle in radians.
  23512. * @param {number} aEndAngle - The end angle in radians.
  23513. * @param {boolean} [aClockwise=false] - Whether to sweep the arc clockwise or not.
  23514. * @return {Path} A reference to this path.
  23515. */
  23516. arc( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  23517. const x0 = this.currentPoint.x;
  23518. const y0 = this.currentPoint.y;
  23519. this.absarc( aX + x0, aY + y0, aRadius,
  23520. aStartAngle, aEndAngle, aClockwise );
  23521. return this;
  23522. }
  23523. /**
  23524. * Adds an absolutely positioned arc as an instance of {@link EllipseCurve} to the path.
  23525. *
  23526. * @param {number} aX - The x coordinate of the center of the arc.
  23527. * @param {number} aY - The y coordinate of the center of the arc.
  23528. * @param {number} aRadius - The radius of the arc.
  23529. * @param {number} aStartAngle - The start angle in radians.
  23530. * @param {number} aEndAngle - The end angle in radians.
  23531. * @param {boolean} [aClockwise=false] - Whether to sweep the arc clockwise or not.
  23532. * @return {Path} A reference to this path.
  23533. */
  23534. absarc( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  23535. this.absellipse( aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  23536. return this;
  23537. }
  23538. /**
  23539. * Adds an ellipse as an instance of {@link EllipseCurve} to the path, positioned relative
  23540. * to the current point
  23541. *
  23542. * @param {number} aX - The x coordinate of the center of the ellipse offsetted from the previous curve.
  23543. * @param {number} aY - The y coordinate of the center of the ellipse offsetted from the previous curve.
  23544. * @param {number} xRadius - The radius of the ellipse in the x axis.
  23545. * @param {number} yRadius - The radius of the ellipse in the y axis.
  23546. * @param {number} aStartAngle - The start angle in radians.
  23547. * @param {number} aEndAngle - The end angle in radians.
  23548. * @param {boolean} [aClockwise=false] - Whether to sweep the ellipse clockwise or not.
  23549. * @param {number} [aRotation=0] - The rotation angle of the ellipse in radians, counterclockwise from the positive X axis.
  23550. * @return {Path} A reference to this path.
  23551. */
  23552. ellipse( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  23553. const x0 = this.currentPoint.x;
  23554. const y0 = this.currentPoint.y;
  23555. this.absellipse( aX + x0, aY + y0, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation );
  23556. return this;
  23557. }
  23558. /**
  23559. * Adds an absolutely positioned ellipse as an instance of {@link EllipseCurve} to the path.
  23560. *
  23561. * @param {number} aX - The x coordinate of the absolute center of the ellipse.
  23562. * @param {number} aY - The y coordinate of the absolute center of the ellipse.
  23563. * @param {number} xRadius - The radius of the ellipse in the x axis.
  23564. * @param {number} yRadius - The radius of the ellipse in the y axis.
  23565. * @param {number} aStartAngle - The start angle in radians.
  23566. * @param {number} aEndAngle - The end angle in radians.
  23567. * @param {boolean} [aClockwise=false] - Whether to sweep the ellipse clockwise or not.
  23568. * @param {number} [aRotation=0] - The rotation angle of the ellipse in radians, counterclockwise from the positive X axis.
  23569. * @return {Path} A reference to this path.
  23570. */
  23571. absellipse( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  23572. const curve = new EllipseCurve( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation );
  23573. if ( this.curves.length > 0 ) {
  23574. // if a previous curve is present, attempt to join
  23575. const firstPoint = curve.getPoint( 0 );
  23576. if ( ! firstPoint.equals( this.currentPoint ) ) {
  23577. this.lineTo( firstPoint.x, firstPoint.y );
  23578. }
  23579. }
  23580. this.curves.push( curve );
  23581. const lastPoint = curve.getPoint( 1 );
  23582. this.currentPoint.copy( lastPoint );
  23583. return this;
  23584. }
  23585. copy( source ) {
  23586. super.copy( source );
  23587. this.currentPoint.copy( source.currentPoint );
  23588. return this;
  23589. }
  23590. toJSON() {
  23591. const data = super.toJSON();
  23592. data.currentPoint = this.currentPoint.toArray();
  23593. return data;
  23594. }
  23595. fromJSON( json ) {
  23596. super.fromJSON( json );
  23597. this.currentPoint.fromArray( json.currentPoint );
  23598. return this;
  23599. }
  23600. }
  23601. /**
  23602. * Creates meshes with axial symmetry like vases. The lathe rotates around the Y axis.
  23603. *
  23604. * ```js
  23605. * const points = [];
  23606. * for ( let i = 0; i < 10; i ++ ) {
  23607. * points.push( new THREE.Vector2( Math.sin( i * 0.2 ) * 10 + 5, ( i - 5 ) * 2 ) );
  23608. * }
  23609. * const geometry = new THREE.LatheGeometry( points );
  23610. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  23611. * const lathe = new THREE.Mesh( geometry, material );
  23612. * scene.add( lathe );
  23613. * ```
  23614. *
  23615. * @augments BufferGeometry
  23616. */
  23617. class LatheGeometry extends BufferGeometry {
  23618. /**
  23619. * Constructs a new lathe geometry.
  23620. *
  23621. * @param {Array<Vector2|Vector3>} [points] - An array of points in 2D space. The x-coordinate of each point
  23622. * must be greater than zero.
  23623. * @param {number} [segments=12] - The number of circumference segments to generate.
  23624. * @param {number} [phiStart=0] - The starting angle in radians.
  23625. * @param {number} [phiLength=Math.PI*2] - The radian (0 to 2PI) range of the lathed section 2PI is a
  23626. * closed lathe, less than 2PI is a portion.
  23627. */
  23628. 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 ) {
  23629. super();
  23630. this.type = 'LatheGeometry';
  23631. /**
  23632. * Holds the constructor parameters that have been
  23633. * used to generate the geometry. Any modification
  23634. * after instantiation does not change the geometry.
  23635. *
  23636. * @type {Object}
  23637. */
  23638. this.parameters = {
  23639. points: points,
  23640. segments: segments,
  23641. phiStart: phiStart,
  23642. phiLength: phiLength
  23643. };
  23644. segments = Math.floor( segments );
  23645. // clamp phiLength so it's in range of [ 0, 2PI ]
  23646. phiLength = clamp( phiLength, 0, Math.PI * 2 );
  23647. // buffers
  23648. const indices = [];
  23649. const vertices = [];
  23650. const uvs = [];
  23651. const initNormals = [];
  23652. const normals = [];
  23653. // helper variables
  23654. const inverseSegments = 1.0 / segments;
  23655. const vertex = new Vector3();
  23656. const uv = new Vector2();
  23657. const normal = new Vector3();
  23658. const curNormal = new Vector3();
  23659. const prevNormal = new Vector3();
  23660. let dx = 0;
  23661. let dy = 0;
  23662. // pre-compute normals for initial "meridian"
  23663. for ( let j = 0; j <= ( points.length - 1 ); j ++ ) {
  23664. switch ( j ) {
  23665. case 0: // special handling for 1st vertex on path
  23666. dx = points[ j + 1 ].x - points[ j ].x;
  23667. dy = points[ j + 1 ].y - points[ j ].y;
  23668. normal.x = dy * 1.0;
  23669. normal.y = - dx;
  23670. normal.z = dy * 0.0;
  23671. prevNormal.copy( normal );
  23672. normal.normalize();
  23673. initNormals.push( normal.x, normal.y, normal.z );
  23674. break;
  23675. case ( points.length - 1 ): // special handling for last Vertex on path
  23676. initNormals.push( prevNormal.x, prevNormal.y, prevNormal.z );
  23677. break;
  23678. default: // default handling for all vertices in between
  23679. dx = points[ j + 1 ].x - points[ j ].x;
  23680. dy = points[ j + 1 ].y - points[ j ].y;
  23681. normal.x = dy * 1.0;
  23682. normal.y = - dx;
  23683. normal.z = dy * 0.0;
  23684. curNormal.copy( normal );
  23685. normal.x += prevNormal.x;
  23686. normal.y += prevNormal.y;
  23687. normal.z += prevNormal.z;
  23688. normal.normalize();
  23689. initNormals.push( normal.x, normal.y, normal.z );
  23690. prevNormal.copy( curNormal );
  23691. }
  23692. }
  23693. // generate vertices, uvs and normals
  23694. for ( let i = 0; i <= segments; i ++ ) {
  23695. const phi = phiStart + i * inverseSegments * phiLength;
  23696. const sin = Math.sin( phi );
  23697. const cos = Math.cos( phi );
  23698. for ( let j = 0; j <= ( points.length - 1 ); j ++ ) {
  23699. // vertex
  23700. vertex.x = points[ j ].x * sin;
  23701. vertex.y = points[ j ].y;
  23702. vertex.z = points[ j ].x * cos;
  23703. vertices.push( vertex.x, vertex.y, vertex.z );
  23704. // uv
  23705. uv.x = i / segments;
  23706. uv.y = j / ( points.length - 1 );
  23707. uvs.push( uv.x, uv.y );
  23708. // normal
  23709. const x = initNormals[ 3 * j + 0 ] * sin;
  23710. const y = initNormals[ 3 * j + 1 ];
  23711. const z = initNormals[ 3 * j + 0 ] * cos;
  23712. normals.push( x, y, z );
  23713. }
  23714. }
  23715. // indices
  23716. for ( let i = 0; i < segments; i ++ ) {
  23717. for ( let j = 0; j < ( points.length - 1 ); j ++ ) {
  23718. const base = j + i * points.length;
  23719. const a = base;
  23720. const b = base + points.length;
  23721. const c = base + points.length + 1;
  23722. const d = base + 1;
  23723. // faces
  23724. indices.push( a, b, d );
  23725. indices.push( c, d, b );
  23726. }
  23727. }
  23728. // build geometry
  23729. this.setIndex( indices );
  23730. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  23731. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  23732. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  23733. }
  23734. copy( source ) {
  23735. super.copy( source );
  23736. this.parameters = Object.assign( {}, source.parameters );
  23737. return this;
  23738. }
  23739. /**
  23740. * Factory method for creating an instance of this class from the given
  23741. * JSON object.
  23742. *
  23743. * @param {Object} data - A JSON object representing the serialized geometry.
  23744. * @return {LatheGeometry} A new instance.
  23745. */
  23746. static fromJSON( data ) {
  23747. return new LatheGeometry( data.points, data.segments, data.phiStart, data.phiLength );
  23748. }
  23749. }
  23750. /**
  23751. * A geometry class for a capsule with given radii and height. It is constructed using a lathe.
  23752. *
  23753. * ```js
  23754. * const geometry = new THREE.CapsuleGeometry( 1, 1, 4, 8 );
  23755. * const material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } );
  23756. * const capsule = new THREE.Mesh( geometry, material );
  23757. * scene.add( capsule );
  23758. * ```
  23759. *
  23760. * @augments LatheGeometry
  23761. */
  23762. class CapsuleGeometry extends LatheGeometry {
  23763. /**
  23764. * Constructs a new capsule geometry.
  23765. *
  23766. * @param {number} [radius=1] - Radius of the capsule.
  23767. * @param {number} [length=1] - Length of the middle section.
  23768. * @param {number} [capSegments=4] - Number of curve segments used to build the caps.
  23769. * @param {number} [radialSegments=8] - Number of segmented faces around the circumference of the capsule.
  23770. */
  23771. constructor( radius = 1, length = 1, capSegments = 4, radialSegments = 8 ) {
  23772. const path = new Path();
  23773. path.absarc( 0, - length / 2, radius, Math.PI * 1.5, 0 );
  23774. path.absarc( 0, length / 2, radius, 0, Math.PI * 0.5 );
  23775. super( path.getPoints( capSegments ), radialSegments );
  23776. this.type = 'CapsuleGeometry';
  23777. /**
  23778. * Holds the constructor parameters that have been
  23779. * used to generate the geometry. Any modification
  23780. * after instantiation does not change the geometry.
  23781. *
  23782. * @type {Object}
  23783. */
  23784. this.parameters = {
  23785. radius: radius,
  23786. length: length,
  23787. capSegments: capSegments,
  23788. radialSegments: radialSegments,
  23789. };
  23790. }
  23791. /**
  23792. * Factory method for creating an instance of this class from the given
  23793. * JSON object.
  23794. *
  23795. * @param {Object} data - A JSON object representing the serialized geometry.
  23796. * @return {CapsuleGeometry} A new instance.
  23797. */
  23798. static fromJSON( data ) {
  23799. return new CapsuleGeometry( data.radius, data.length, data.capSegments, data.radialSegments );
  23800. }
  23801. }
  23802. /**
  23803. * A simple shape of Euclidean geometry. It is constructed from a
  23804. * number of triangular segments that are oriented around a central point and
  23805. * extend as far out as a given radius. It is built counter-clockwise from a
  23806. * start angle and a given central angle. It can also be used to create
  23807. * regular polygons, where the number of segments determines the number of
  23808. * sides.
  23809. *
  23810. * ```js
  23811. * const geometry = new THREE.CircleGeometry( 5, 32 );
  23812. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  23813. * const circle = new THREE.Mesh( geometry, material );
  23814. * scene.add( circle )
  23815. * ```
  23816. *
  23817. * @augments BufferGeometry
  23818. */
  23819. class CircleGeometry extends BufferGeometry {
  23820. /**
  23821. * Constructs a new circle geometry.
  23822. *
  23823. * @param {number} [radius=1] - Radius of the circle.
  23824. * @param {number} [segments=32] - Number of segments (triangles), minimum = `3`.
  23825. * @param {number} [thetaStart=0] - Start angle for first segment in radians.
  23826. * @param {number} [thetaLength=Math.PI*2] - The central angle, often called theta,
  23827. * of the circular sector in radians. The default value results in a complete circle.
  23828. */
  23829. constructor( radius = 1, segments = 32, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  23830. super();
  23831. this.type = 'CircleGeometry';
  23832. /**
  23833. * Holds the constructor parameters that have been
  23834. * used to generate the geometry. Any modification
  23835. * after instantiation does not change the geometry.
  23836. *
  23837. * @type {Object}
  23838. */
  23839. this.parameters = {
  23840. radius: radius,
  23841. segments: segments,
  23842. thetaStart: thetaStart,
  23843. thetaLength: thetaLength
  23844. };
  23845. segments = Math.max( 3, segments );
  23846. // buffers
  23847. const indices = [];
  23848. const vertices = [];
  23849. const normals = [];
  23850. const uvs = [];
  23851. // helper variables
  23852. const vertex = new Vector3();
  23853. const uv = new Vector2();
  23854. // center point
  23855. vertices.push( 0, 0, 0 );
  23856. normals.push( 0, 0, 1 );
  23857. uvs.push( 0.5, 0.5 );
  23858. for ( let s = 0, i = 3; s <= segments; s ++, i += 3 ) {
  23859. const segment = thetaStart + s / segments * thetaLength;
  23860. // vertex
  23861. vertex.x = radius * Math.cos( segment );
  23862. vertex.y = radius * Math.sin( segment );
  23863. vertices.push( vertex.x, vertex.y, vertex.z );
  23864. // normal
  23865. normals.push( 0, 0, 1 );
  23866. // uvs
  23867. uv.x = ( vertices[ i ] / radius + 1 ) / 2;
  23868. uv.y = ( vertices[ i + 1 ] / radius + 1 ) / 2;
  23869. uvs.push( uv.x, uv.y );
  23870. }
  23871. // indices
  23872. for ( let i = 1; i <= segments; i ++ ) {
  23873. indices.push( i, i + 1, 0 );
  23874. }
  23875. // build geometry
  23876. this.setIndex( indices );
  23877. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  23878. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  23879. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  23880. }
  23881. copy( source ) {
  23882. super.copy( source );
  23883. this.parameters = Object.assign( {}, source.parameters );
  23884. return this;
  23885. }
  23886. /**
  23887. * Factory method for creating an instance of this class from the given
  23888. * JSON object.
  23889. *
  23890. * @param {Object} data - A JSON object representing the serialized geometry.
  23891. * @return {CircleGeometry} A new instance.
  23892. */
  23893. static fromJSON( data ) {
  23894. return new CircleGeometry( data.radius, data.segments, data.thetaStart, data.thetaLength );
  23895. }
  23896. }
  23897. /**
  23898. * A geometry class for representing a cylinder.
  23899. *
  23900. * ```js
  23901. * const geometry = new THREE.CylinderGeometry( 5, 5, 20, 32 );
  23902. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  23903. * const cylinder = new THREE.Mesh( geometry, material );
  23904. * scene.add( cylinder );
  23905. * ```
  23906. *
  23907. * @augments BufferGeometry
  23908. */
  23909. class CylinderGeometry extends BufferGeometry {
  23910. /**
  23911. * Constructs a new cylinder geometry.
  23912. *
  23913. * @param {number} [radiusTop=1] - Radius of the cylinder at the top.
  23914. * @param {number} [radiusBottom=1] - Radius of the cylinder at the bottom.
  23915. * @param {number} [height=1] - Height of the cylinder.
  23916. * @param {number} [radialSegments=32] - Number of segmented faces around the circumference of the cylinder.
  23917. * @param {number} [heightSegments=1] - Number of rows of faces along the height of the cylinder.
  23918. * @param {boolean} [openEnded=false] - Whether the base of the cylinder is open or capped.
  23919. * @param {number} [thetaStart=0] - Start angle for first segment, in radians.
  23920. * @param {number} [thetaLength=Math.PI*2] - The central angle, often called theta, of the circular sector, in radians.
  23921. * The default value results in a complete cylinder.
  23922. */
  23923. constructor( radiusTop = 1, radiusBottom = 1, height = 1, radialSegments = 32, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  23924. super();
  23925. this.type = 'CylinderGeometry';
  23926. /**
  23927. * Holds the constructor parameters that have been
  23928. * used to generate the geometry. Any modification
  23929. * after instantiation does not change the geometry.
  23930. *
  23931. * @type {Object}
  23932. */
  23933. this.parameters = {
  23934. radiusTop: radiusTop,
  23935. radiusBottom: radiusBottom,
  23936. height: height,
  23937. radialSegments: radialSegments,
  23938. heightSegments: heightSegments,
  23939. openEnded: openEnded,
  23940. thetaStart: thetaStart,
  23941. thetaLength: thetaLength
  23942. };
  23943. const scope = this;
  23944. radialSegments = Math.floor( radialSegments );
  23945. heightSegments = Math.floor( heightSegments );
  23946. // buffers
  23947. const indices = [];
  23948. const vertices = [];
  23949. const normals = [];
  23950. const uvs = [];
  23951. // helper variables
  23952. let index = 0;
  23953. const indexArray = [];
  23954. const halfHeight = height / 2;
  23955. let groupStart = 0;
  23956. // generate geometry
  23957. generateTorso();
  23958. if ( openEnded === false ) {
  23959. if ( radiusTop > 0 ) generateCap( true );
  23960. if ( radiusBottom > 0 ) generateCap( false );
  23961. }
  23962. // build geometry
  23963. this.setIndex( indices );
  23964. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  23965. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  23966. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  23967. function generateTorso() {
  23968. const normal = new Vector3();
  23969. const vertex = new Vector3();
  23970. let groupCount = 0;
  23971. // this will be used to calculate the normal
  23972. const slope = ( radiusBottom - radiusTop ) / height;
  23973. // generate vertices, normals and uvs
  23974. for ( let y = 0; y <= heightSegments; y ++ ) {
  23975. const indexRow = [];
  23976. const v = y / heightSegments;
  23977. // calculate the radius of the current row
  23978. const radius = v * ( radiusBottom - radiusTop ) + radiusTop;
  23979. for ( let x = 0; x <= radialSegments; x ++ ) {
  23980. const u = x / radialSegments;
  23981. const theta = u * thetaLength + thetaStart;
  23982. const sinTheta = Math.sin( theta );
  23983. const cosTheta = Math.cos( theta );
  23984. // vertex
  23985. vertex.x = radius * sinTheta;
  23986. vertex.y = - v * height + halfHeight;
  23987. vertex.z = radius * cosTheta;
  23988. vertices.push( vertex.x, vertex.y, vertex.z );
  23989. // normal
  23990. normal.set( sinTheta, slope, cosTheta ).normalize();
  23991. normals.push( normal.x, normal.y, normal.z );
  23992. // uv
  23993. uvs.push( u, 1 - v );
  23994. // save index of vertex in respective row
  23995. indexRow.push( index ++ );
  23996. }
  23997. // now save vertices of the row in our index array
  23998. indexArray.push( indexRow );
  23999. }
  24000. // generate indices
  24001. for ( let x = 0; x < radialSegments; x ++ ) {
  24002. for ( let y = 0; y < heightSegments; y ++ ) {
  24003. // we use the index array to access the correct indices
  24004. const a = indexArray[ y ][ x ];
  24005. const b = indexArray[ y + 1 ][ x ];
  24006. const c = indexArray[ y + 1 ][ x + 1 ];
  24007. const d = indexArray[ y ][ x + 1 ];
  24008. // faces
  24009. if ( radiusTop > 0 || y !== 0 ) {
  24010. indices.push( a, b, d );
  24011. groupCount += 3;
  24012. }
  24013. if ( radiusBottom > 0 || y !== heightSegments - 1 ) {
  24014. indices.push( b, c, d );
  24015. groupCount += 3;
  24016. }
  24017. }
  24018. }
  24019. // add a group to the geometry. this will ensure multi material support
  24020. scope.addGroup( groupStart, groupCount, 0 );
  24021. // calculate new start value for groups
  24022. groupStart += groupCount;
  24023. }
  24024. function generateCap( top ) {
  24025. // save the index of the first center vertex
  24026. const centerIndexStart = index;
  24027. const uv = new Vector2();
  24028. const vertex = new Vector3();
  24029. let groupCount = 0;
  24030. const radius = ( top === true ) ? radiusTop : radiusBottom;
  24031. const sign = ( top === true ) ? 1 : -1;
  24032. // first we generate the center vertex data of the cap.
  24033. // because the geometry needs one set of uvs per face,
  24034. // we must generate a center vertex per face/segment
  24035. for ( let x = 1; x <= radialSegments; x ++ ) {
  24036. // vertex
  24037. vertices.push( 0, halfHeight * sign, 0 );
  24038. // normal
  24039. normals.push( 0, sign, 0 );
  24040. // uv
  24041. uvs.push( 0.5, 0.5 );
  24042. // increase index
  24043. index ++;
  24044. }
  24045. // save the index of the last center vertex
  24046. const centerIndexEnd = index;
  24047. // now we generate the surrounding vertices, normals and uvs
  24048. for ( let x = 0; x <= radialSegments; x ++ ) {
  24049. const u = x / radialSegments;
  24050. const theta = u * thetaLength + thetaStart;
  24051. const cosTheta = Math.cos( theta );
  24052. const sinTheta = Math.sin( theta );
  24053. // vertex
  24054. vertex.x = radius * sinTheta;
  24055. vertex.y = halfHeight * sign;
  24056. vertex.z = radius * cosTheta;
  24057. vertices.push( vertex.x, vertex.y, vertex.z );
  24058. // normal
  24059. normals.push( 0, sign, 0 );
  24060. // uv
  24061. uv.x = ( cosTheta * 0.5 ) + 0.5;
  24062. uv.y = ( sinTheta * 0.5 * sign ) + 0.5;
  24063. uvs.push( uv.x, uv.y );
  24064. // increase index
  24065. index ++;
  24066. }
  24067. // generate indices
  24068. for ( let x = 0; x < radialSegments; x ++ ) {
  24069. const c = centerIndexStart + x;
  24070. const i = centerIndexEnd + x;
  24071. if ( top === true ) {
  24072. // face top
  24073. indices.push( i, i + 1, c );
  24074. } else {
  24075. // face bottom
  24076. indices.push( i + 1, i, c );
  24077. }
  24078. groupCount += 3;
  24079. }
  24080. // add a group to the geometry. this will ensure multi material support
  24081. scope.addGroup( groupStart, groupCount, top === true ? 1 : 2 );
  24082. // calculate new start value for groups
  24083. groupStart += groupCount;
  24084. }
  24085. }
  24086. copy( source ) {
  24087. super.copy( source );
  24088. this.parameters = Object.assign( {}, source.parameters );
  24089. return this;
  24090. }
  24091. /**
  24092. * Factory method for creating an instance of this class from the given
  24093. * JSON object.
  24094. *
  24095. * @param {Object} data - A JSON object representing the serialized geometry.
  24096. * @return {CylinderGeometry} A new instance.
  24097. */
  24098. static fromJSON( data ) {
  24099. return new CylinderGeometry( data.radiusTop, data.radiusBottom, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength );
  24100. }
  24101. }
  24102. /**
  24103. * A geometry class for representing a cone.
  24104. *
  24105. * ```js
  24106. * const geometry = new THREE.ConeGeometry( 5, 20, 32 );
  24107. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  24108. * const cone = new THREE.Mesh(geometry, material );
  24109. * scene.add( cone );
  24110. * ```
  24111. *
  24112. * @augments CylinderGeometry
  24113. */
  24114. class ConeGeometry extends CylinderGeometry {
  24115. /**
  24116. * Constructs a new cone geometry.
  24117. *
  24118. * @param {number} [radius=1] - Radius of the cone base.
  24119. * @param {number} [height=1] - Height of the cone.
  24120. * @param {number} [radialSegments=32] - Number of segmented faces around the circumference of the cone.
  24121. * @param {number} [heightSegments=1] - Number of rows of faces along the height of the cone.
  24122. * @param {boolean} [openEnded=false] - Whether the base of the cone is open or capped.
  24123. * @param {number} [thetaStart=0] - Start angle for first segment, in radians.
  24124. * @param {number} [thetaLength=Math.PI*2] - The central angle, often called theta, of the circular sector, in radians.
  24125. * The default value results in a complete cone.
  24126. */
  24127. constructor( radius = 1, height = 1, radialSegments = 32, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  24128. super( 0, radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength );
  24129. this.type = 'ConeGeometry';
  24130. /**
  24131. * Holds the constructor parameters that have been
  24132. * used to generate the geometry. Any modification
  24133. * after instantiation does not change the geometry.
  24134. *
  24135. * @type {Object}
  24136. */
  24137. this.parameters = {
  24138. radius: radius,
  24139. height: height,
  24140. radialSegments: radialSegments,
  24141. heightSegments: heightSegments,
  24142. openEnded: openEnded,
  24143. thetaStart: thetaStart,
  24144. thetaLength: thetaLength
  24145. };
  24146. }
  24147. /**
  24148. * Factory method for creating an instance of this class from the given
  24149. * JSON object.
  24150. *
  24151. * @param {Object} data - A JSON object representing the serialized geometry.
  24152. * @return {ConeGeometry} A new instance.
  24153. */
  24154. static fromJSON( data ) {
  24155. return new ConeGeometry( data.radius, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength );
  24156. }
  24157. }
  24158. /**
  24159. * A polyhedron is a solid in three dimensions with flat faces. This class
  24160. * will take an array of vertices, project them onto a sphere, and then
  24161. * divide them up to the desired level of detail.
  24162. *
  24163. * @augments BufferGeometry
  24164. */
  24165. class PolyhedronGeometry extends BufferGeometry {
  24166. /**
  24167. * Constructs a new polyhedron geometry.
  24168. *
  24169. * @param {Array<number>} [vertices] - A flat array of vertices describing the base shape.
  24170. * @param {Array<number>} [indices] - A flat array of indices describing the base shape.
  24171. * @param {number} [radius=1] - The radius of the shape.
  24172. * @param {number} [detail=0] - How many levels to subdivide the geometry. The more detail, the smoother the shape.
  24173. */
  24174. constructor( vertices = [], indices = [], radius = 1, detail = 0 ) {
  24175. super();
  24176. this.type = 'PolyhedronGeometry';
  24177. /**
  24178. * Holds the constructor parameters that have been
  24179. * used to generate the geometry. Any modification
  24180. * after instantiation does not change the geometry.
  24181. *
  24182. * @type {Object}
  24183. */
  24184. this.parameters = {
  24185. vertices: vertices,
  24186. indices: indices,
  24187. radius: radius,
  24188. detail: detail
  24189. };
  24190. // default buffer data
  24191. const vertexBuffer = [];
  24192. const uvBuffer = [];
  24193. // the subdivision creates the vertex buffer data
  24194. subdivide( detail );
  24195. // all vertices should lie on a conceptual sphere with a given radius
  24196. applyRadius( radius );
  24197. // finally, create the uv data
  24198. generateUVs();
  24199. // build non-indexed geometry
  24200. this.setAttribute( 'position', new Float32BufferAttribute( vertexBuffer, 3 ) );
  24201. this.setAttribute( 'normal', new Float32BufferAttribute( vertexBuffer.slice(), 3 ) );
  24202. this.setAttribute( 'uv', new Float32BufferAttribute( uvBuffer, 2 ) );
  24203. if ( detail === 0 ) {
  24204. this.computeVertexNormals(); // flat normals
  24205. } else {
  24206. this.normalizeNormals(); // smooth normals
  24207. }
  24208. // helper functions
  24209. function subdivide( detail ) {
  24210. const a = new Vector3();
  24211. const b = new Vector3();
  24212. const c = new Vector3();
  24213. // iterate over all faces and apply a subdivision with the given detail value
  24214. for ( let i = 0; i < indices.length; i += 3 ) {
  24215. // get the vertices of the face
  24216. getVertexByIndex( indices[ i + 0 ], a );
  24217. getVertexByIndex( indices[ i + 1 ], b );
  24218. getVertexByIndex( indices[ i + 2 ], c );
  24219. // perform subdivision
  24220. subdivideFace( a, b, c, detail );
  24221. }
  24222. }
  24223. function subdivideFace( a, b, c, detail ) {
  24224. const cols = detail + 1;
  24225. // we use this multidimensional array as a data structure for creating the subdivision
  24226. const v = [];
  24227. // construct all of the vertices for this subdivision
  24228. for ( let i = 0; i <= cols; i ++ ) {
  24229. v[ i ] = [];
  24230. const aj = a.clone().lerp( c, i / cols );
  24231. const bj = b.clone().lerp( c, i / cols );
  24232. const rows = cols - i;
  24233. for ( let j = 0; j <= rows; j ++ ) {
  24234. if ( j === 0 && i === cols ) {
  24235. v[ i ][ j ] = aj;
  24236. } else {
  24237. v[ i ][ j ] = aj.clone().lerp( bj, j / rows );
  24238. }
  24239. }
  24240. }
  24241. // construct all of the faces
  24242. for ( let i = 0; i < cols; i ++ ) {
  24243. for ( let j = 0; j < 2 * ( cols - i ) - 1; j ++ ) {
  24244. const k = Math.floor( j / 2 );
  24245. if ( j % 2 === 0 ) {
  24246. pushVertex( v[ i ][ k + 1 ] );
  24247. pushVertex( v[ i + 1 ][ k ] );
  24248. pushVertex( v[ i ][ k ] );
  24249. } else {
  24250. pushVertex( v[ i ][ k + 1 ] );
  24251. pushVertex( v[ i + 1 ][ k + 1 ] );
  24252. pushVertex( v[ i + 1 ][ k ] );
  24253. }
  24254. }
  24255. }
  24256. }
  24257. function applyRadius( radius ) {
  24258. const vertex = new Vector3();
  24259. // iterate over the entire buffer and apply the radius to each vertex
  24260. for ( let i = 0; i < vertexBuffer.length; i += 3 ) {
  24261. vertex.x = vertexBuffer[ i + 0 ];
  24262. vertex.y = vertexBuffer[ i + 1 ];
  24263. vertex.z = vertexBuffer[ i + 2 ];
  24264. vertex.normalize().multiplyScalar( radius );
  24265. vertexBuffer[ i + 0 ] = vertex.x;
  24266. vertexBuffer[ i + 1 ] = vertex.y;
  24267. vertexBuffer[ i + 2 ] = vertex.z;
  24268. }
  24269. }
  24270. function generateUVs() {
  24271. const vertex = new Vector3();
  24272. for ( let i = 0; i < vertexBuffer.length; i += 3 ) {
  24273. vertex.x = vertexBuffer[ i + 0 ];
  24274. vertex.y = vertexBuffer[ i + 1 ];
  24275. vertex.z = vertexBuffer[ i + 2 ];
  24276. const u = azimuth( vertex ) / 2 / Math.PI + 0.5;
  24277. const v = inclination( vertex ) / Math.PI + 0.5;
  24278. uvBuffer.push( u, 1 - v );
  24279. }
  24280. correctUVs();
  24281. correctSeam();
  24282. }
  24283. function correctSeam() {
  24284. // handle case when face straddles the seam, see #3269
  24285. for ( let i = 0; i < uvBuffer.length; i += 6 ) {
  24286. // uv data of a single face
  24287. const x0 = uvBuffer[ i + 0 ];
  24288. const x1 = uvBuffer[ i + 2 ];
  24289. const x2 = uvBuffer[ i + 4 ];
  24290. const max = Math.max( x0, x1, x2 );
  24291. const min = Math.min( x0, x1, x2 );
  24292. // 0.9 is somewhat arbitrary
  24293. if ( max > 0.9 && min < 0.1 ) {
  24294. if ( x0 < 0.2 ) uvBuffer[ i + 0 ] += 1;
  24295. if ( x1 < 0.2 ) uvBuffer[ i + 2 ] += 1;
  24296. if ( x2 < 0.2 ) uvBuffer[ i + 4 ] += 1;
  24297. }
  24298. }
  24299. }
  24300. function pushVertex( vertex ) {
  24301. vertexBuffer.push( vertex.x, vertex.y, vertex.z );
  24302. }
  24303. function getVertexByIndex( index, vertex ) {
  24304. const stride = index * 3;
  24305. vertex.x = vertices[ stride + 0 ];
  24306. vertex.y = vertices[ stride + 1 ];
  24307. vertex.z = vertices[ stride + 2 ];
  24308. }
  24309. function correctUVs() {
  24310. const a = new Vector3();
  24311. const b = new Vector3();
  24312. const c = new Vector3();
  24313. const centroid = new Vector3();
  24314. const uvA = new Vector2();
  24315. const uvB = new Vector2();
  24316. const uvC = new Vector2();
  24317. for ( let i = 0, j = 0; i < vertexBuffer.length; i += 9, j += 6 ) {
  24318. a.set( vertexBuffer[ i + 0 ], vertexBuffer[ i + 1 ], vertexBuffer[ i + 2 ] );
  24319. b.set( vertexBuffer[ i + 3 ], vertexBuffer[ i + 4 ], vertexBuffer[ i + 5 ] );
  24320. c.set( vertexBuffer[ i + 6 ], vertexBuffer[ i + 7 ], vertexBuffer[ i + 8 ] );
  24321. uvA.set( uvBuffer[ j + 0 ], uvBuffer[ j + 1 ] );
  24322. uvB.set( uvBuffer[ j + 2 ], uvBuffer[ j + 3 ] );
  24323. uvC.set( uvBuffer[ j + 4 ], uvBuffer[ j + 5 ] );
  24324. centroid.copy( a ).add( b ).add( c ).divideScalar( 3 );
  24325. const azi = azimuth( centroid );
  24326. correctUV( uvA, j + 0, a, azi );
  24327. correctUV( uvB, j + 2, b, azi );
  24328. correctUV( uvC, j + 4, c, azi );
  24329. }
  24330. }
  24331. function correctUV( uv, stride, vector, azimuth ) {
  24332. if ( ( azimuth < 0 ) && ( uv.x === 1 ) ) {
  24333. uvBuffer[ stride ] = uv.x - 1;
  24334. }
  24335. if ( ( vector.x === 0 ) && ( vector.z === 0 ) ) {
  24336. uvBuffer[ stride ] = azimuth / 2 / Math.PI + 0.5;
  24337. }
  24338. }
  24339. // Angle around the Y axis, counter-clockwise when looking from above.
  24340. function azimuth( vector ) {
  24341. return Math.atan2( vector.z, - vector.x );
  24342. }
  24343. // Angle above the XZ plane.
  24344. function inclination( vector ) {
  24345. return Math.atan2( - vector.y, Math.sqrt( ( vector.x * vector.x ) + ( vector.z * vector.z ) ) );
  24346. }
  24347. }
  24348. copy( source ) {
  24349. super.copy( source );
  24350. this.parameters = Object.assign( {}, source.parameters );
  24351. return this;
  24352. }
  24353. /**
  24354. * Factory method for creating an instance of this class from the given
  24355. * JSON object.
  24356. *
  24357. * @param {Object} data - A JSON object representing the serialized geometry.
  24358. * @return {PolyhedronGeometry} A new instance.
  24359. */
  24360. static fromJSON( data ) {
  24361. return new PolyhedronGeometry( data.vertices, data.indices, data.radius, data.details );
  24362. }
  24363. }
  24364. /**
  24365. * A geometry class for representing a dodecahedron.
  24366. *
  24367. * ```js
  24368. * const geometry = new THREE.DodecahedronGeometry();
  24369. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  24370. * const dodecahedron = new THREE.Mesh( geometry, material );
  24371. * scene.add( dodecahedron );
  24372. * ```
  24373. *
  24374. * @augments PolyhedronGeometry
  24375. */
  24376. class DodecahedronGeometry extends PolyhedronGeometry {
  24377. /**
  24378. * Constructs a new dodecahedron geometry.
  24379. *
  24380. * @param {number} [radius=1] - Radius of the dodecahedron.
  24381. * @param {number} [detail=0] - Setting this to a value greater than `0` adds vertices making it no longer a dodecahedron.
  24382. */
  24383. constructor( radius = 1, detail = 0 ) {
  24384. const t = ( 1 + Math.sqrt( 5 ) ) / 2;
  24385. const r = 1 / t;
  24386. const vertices = [
  24387. // (±1, ±1, ±1)
  24388. -1, -1, -1, -1, -1, 1,
  24389. -1, 1, -1, -1, 1, 1,
  24390. 1, -1, -1, 1, -1, 1,
  24391. 1, 1, -1, 1, 1, 1,
  24392. // (0, ±1/φ, ±φ)
  24393. 0, - r, - t, 0, - r, t,
  24394. 0, r, - t, 0, r, t,
  24395. // (±1/φ, ±φ, 0)
  24396. - r, - t, 0, - r, t, 0,
  24397. r, - t, 0, r, t, 0,
  24398. // (±φ, 0, ±1/φ)
  24399. - t, 0, - r, t, 0, - r,
  24400. - t, 0, r, t, 0, r
  24401. ];
  24402. const indices = [
  24403. 3, 11, 7, 3, 7, 15, 3, 15, 13,
  24404. 7, 19, 17, 7, 17, 6, 7, 6, 15,
  24405. 17, 4, 8, 17, 8, 10, 17, 10, 6,
  24406. 8, 0, 16, 8, 16, 2, 8, 2, 10,
  24407. 0, 12, 1, 0, 1, 18, 0, 18, 16,
  24408. 6, 10, 2, 6, 2, 13, 6, 13, 15,
  24409. 2, 16, 18, 2, 18, 3, 2, 3, 13,
  24410. 18, 1, 9, 18, 9, 11, 18, 11, 3,
  24411. 4, 14, 12, 4, 12, 0, 4, 0, 8,
  24412. 11, 9, 5, 11, 5, 19, 11, 19, 7,
  24413. 19, 5, 14, 19, 14, 4, 19, 4, 17,
  24414. 1, 12, 14, 1, 14, 5, 1, 5, 9
  24415. ];
  24416. super( vertices, indices, radius, detail );
  24417. this.type = 'DodecahedronGeometry';
  24418. /**
  24419. * Holds the constructor parameters that have been
  24420. * used to generate the geometry. Any modification
  24421. * after instantiation does not change the geometry.
  24422. *
  24423. * @type {Object}
  24424. */
  24425. this.parameters = {
  24426. radius: radius,
  24427. detail: detail
  24428. };
  24429. }
  24430. /**
  24431. * Factory method for creating an instance of this class from the given
  24432. * JSON object.
  24433. *
  24434. * @param {Object} data - A JSON object representing the serialized geometry.
  24435. * @return {DodecahedronGeometry} A new instance.
  24436. */
  24437. static fromJSON( data ) {
  24438. return new DodecahedronGeometry( data.radius, data.detail );
  24439. }
  24440. }
  24441. const _v0 = /*@__PURE__*/ new Vector3();
  24442. const _v1$1 = /*@__PURE__*/ new Vector3();
  24443. const _normal = /*@__PURE__*/ new Vector3();
  24444. const _triangle = /*@__PURE__*/ new Triangle();
  24445. /**
  24446. * Can be used as a helper object to view the edges of a geometry.
  24447. *
  24448. * ```js
  24449. * const geometry = new THREE.BoxGeometry();
  24450. * const edges = new THREE.EdgesGeometry( geometry );
  24451. * const line = new THREE.LineSegments( edges );
  24452. * scene.add( line );
  24453. * ```
  24454. *
  24455. * Note: It is not yet possible to serialize/deserialize instances of this class.
  24456. *
  24457. * @augments BufferGeometry
  24458. */
  24459. class EdgesGeometry extends BufferGeometry {
  24460. /**
  24461. * Constructs a new edges geometry.
  24462. *
  24463. * @param {?BufferGeometry} [geometry=null] - The geometry.
  24464. * @param {number} [thresholdAngle=1] - An edge is only rendered if the angle (in degrees)
  24465. * between the face normals of the adjoining faces exceeds this value.
  24466. */
  24467. constructor( geometry = null, thresholdAngle = 1 ) {
  24468. super();
  24469. this.type = 'EdgesGeometry';
  24470. /**
  24471. * Holds the constructor parameters that have been
  24472. * used to generate the geometry. Any modification
  24473. * after instantiation does not change the geometry.
  24474. *
  24475. * @type {Object}
  24476. */
  24477. this.parameters = {
  24478. geometry: geometry,
  24479. thresholdAngle: thresholdAngle
  24480. };
  24481. if ( geometry !== null ) {
  24482. const precisionPoints = 4;
  24483. const precision = Math.pow( 10, precisionPoints );
  24484. const thresholdDot = Math.cos( DEG2RAD * thresholdAngle );
  24485. const indexAttr = geometry.getIndex();
  24486. const positionAttr = geometry.getAttribute( 'position' );
  24487. const indexCount = indexAttr ? indexAttr.count : positionAttr.count;
  24488. const indexArr = [ 0, 0, 0 ];
  24489. const vertKeys = [ 'a', 'b', 'c' ];
  24490. const hashes = new Array( 3 );
  24491. const edgeData = {};
  24492. const vertices = [];
  24493. for ( let i = 0; i < indexCount; i += 3 ) {
  24494. if ( indexAttr ) {
  24495. indexArr[ 0 ] = indexAttr.getX( i );
  24496. indexArr[ 1 ] = indexAttr.getX( i + 1 );
  24497. indexArr[ 2 ] = indexAttr.getX( i + 2 );
  24498. } else {
  24499. indexArr[ 0 ] = i;
  24500. indexArr[ 1 ] = i + 1;
  24501. indexArr[ 2 ] = i + 2;
  24502. }
  24503. const { a, b, c } = _triangle;
  24504. a.fromBufferAttribute( positionAttr, indexArr[ 0 ] );
  24505. b.fromBufferAttribute( positionAttr, indexArr[ 1 ] );
  24506. c.fromBufferAttribute( positionAttr, indexArr[ 2 ] );
  24507. _triangle.getNormal( _normal );
  24508. // create hashes for the edge from the vertices
  24509. hashes[ 0 ] = `${ Math.round( a.x * precision ) },${ Math.round( a.y * precision ) },${ Math.round( a.z * precision ) }`;
  24510. hashes[ 1 ] = `${ Math.round( b.x * precision ) },${ Math.round( b.y * precision ) },${ Math.round( b.z * precision ) }`;
  24511. hashes[ 2 ] = `${ Math.round( c.x * precision ) },${ Math.round( c.y * precision ) },${ Math.round( c.z * precision ) }`;
  24512. // skip degenerate triangles
  24513. if ( hashes[ 0 ] === hashes[ 1 ] || hashes[ 1 ] === hashes[ 2 ] || hashes[ 2 ] === hashes[ 0 ] ) {
  24514. continue;
  24515. }
  24516. // iterate over every edge
  24517. for ( let j = 0; j < 3; j ++ ) {
  24518. // get the first and next vertex making up the edge
  24519. const jNext = ( j + 1 ) % 3;
  24520. const vecHash0 = hashes[ j ];
  24521. const vecHash1 = hashes[ jNext ];
  24522. const v0 = _triangle[ vertKeys[ j ] ];
  24523. const v1 = _triangle[ vertKeys[ jNext ] ];
  24524. const hash = `${ vecHash0 }_${ vecHash1 }`;
  24525. const reverseHash = `${ vecHash1 }_${ vecHash0 }`;
  24526. if ( reverseHash in edgeData && edgeData[ reverseHash ] ) {
  24527. // if we found a sibling edge add it into the vertex array if
  24528. // it meets the angle threshold and delete the edge from the map.
  24529. if ( _normal.dot( edgeData[ reverseHash ].normal ) <= thresholdDot ) {
  24530. vertices.push( v0.x, v0.y, v0.z );
  24531. vertices.push( v1.x, v1.y, v1.z );
  24532. }
  24533. edgeData[ reverseHash ] = null;
  24534. } else if ( ! ( hash in edgeData ) ) {
  24535. // if we've already got an edge here then skip adding a new one
  24536. edgeData[ hash ] = {
  24537. index0: indexArr[ j ],
  24538. index1: indexArr[ jNext ],
  24539. normal: _normal.clone(),
  24540. };
  24541. }
  24542. }
  24543. }
  24544. // iterate over all remaining, unmatched edges and add them to the vertex array
  24545. for ( const key in edgeData ) {
  24546. if ( edgeData[ key ] ) {
  24547. const { index0, index1 } = edgeData[ key ];
  24548. _v0.fromBufferAttribute( positionAttr, index0 );
  24549. _v1$1.fromBufferAttribute( positionAttr, index1 );
  24550. vertices.push( _v0.x, _v0.y, _v0.z );
  24551. vertices.push( _v1$1.x, _v1$1.y, _v1$1.z );
  24552. }
  24553. }
  24554. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  24555. }
  24556. }
  24557. copy( source ) {
  24558. super.copy( source );
  24559. this.parameters = Object.assign( {}, source.parameters );
  24560. return this;
  24561. }
  24562. }
  24563. /**
  24564. * Defines an arbitrary 2d shape plane using paths with optional holes. It
  24565. * can be used with {@link ExtrudeGeometry}, {@link ShapeGeometry}, to get
  24566. * points, or to get triangulated faces.
  24567. *
  24568. * ```js
  24569. * const heartShape = new THREE.Shape();
  24570. *
  24571. * heartShape.moveTo( 25, 25 );
  24572. * heartShape.bezierCurveTo( 25, 25, 20, 0, 0, 0 );
  24573. * heartShape.bezierCurveTo( - 30, 0, - 30, 35, - 30, 35 );
  24574. * heartShape.bezierCurveTo( - 30, 55, - 10, 77, 25, 95 );
  24575. * heartShape.bezierCurveTo( 60, 77, 80, 55, 80, 35 );
  24576. * heartShape.bezierCurveTo( 80, 35, 80, 0, 50, 0 );
  24577. * heartShape.bezierCurveTo( 35, 0, 25, 25, 25, 25 );
  24578. *
  24579. * const extrudeSettings = {
  24580. * depth: 8,
  24581. * bevelEnabled: true,
  24582. * bevelSegments: 2,
  24583. * steps: 2,
  24584. * bevelSize: 1,
  24585. * bevelThickness: 1
  24586. * };
  24587. *
  24588. * const geometry = new THREE.ExtrudeGeometry( heartShape, extrudeSettings );
  24589. * const mesh = new THREE.Mesh( geometry, new THREE.MeshBasicMaterial() );
  24590. * ```
  24591. *
  24592. * @augments Path
  24593. */
  24594. class Shape extends Path {
  24595. /**
  24596. * Constructs a new shape.
  24597. *
  24598. * @param {Array<Vector2>} [points] - An array of 2D points defining the shape.
  24599. */
  24600. constructor( points ) {
  24601. super( points );
  24602. /**
  24603. * The UUID of the shape.
  24604. *
  24605. * @type {string}
  24606. * @readonly
  24607. */
  24608. this.uuid = generateUUID();
  24609. this.type = 'Shape';
  24610. /**
  24611. * Defines the holes in the shape. Hole definitions must use the
  24612. * opposite winding order (CW/CCW) than the outer shape.
  24613. *
  24614. * @type {Array<Path>}
  24615. * @readonly
  24616. */
  24617. this.holes = [];
  24618. }
  24619. /**
  24620. * Returns an array representing each contour of the holes
  24621. * as a list of 2D points.
  24622. *
  24623. * @param {number} divisions - The fineness of the result.
  24624. * @return {Array<Array<Vector2>>} The holes as a series of 2D points.
  24625. */
  24626. getPointsHoles( divisions ) {
  24627. const holesPts = [];
  24628. for ( let i = 0, l = this.holes.length; i < l; i ++ ) {
  24629. holesPts[ i ] = this.holes[ i ].getPoints( divisions );
  24630. }
  24631. return holesPts;
  24632. }
  24633. // get points of shape and holes (keypoints based on segments parameter)
  24634. /**
  24635. * Returns an object that holds contour data for the shape and its holes as
  24636. * arrays of 2D points.
  24637. *
  24638. * @param {number} divisions - The fineness of the result.
  24639. * @return {{shape:Array<Vector2>,holes:Array<Array<Vector2>>}} An object with contour data.
  24640. */
  24641. extractPoints( divisions ) {
  24642. return {
  24643. shape: this.getPoints( divisions ),
  24644. holes: this.getPointsHoles( divisions )
  24645. };
  24646. }
  24647. copy( source ) {
  24648. super.copy( source );
  24649. this.holes = [];
  24650. for ( let i = 0, l = source.holes.length; i < l; i ++ ) {
  24651. const hole = source.holes[ i ];
  24652. this.holes.push( hole.clone() );
  24653. }
  24654. return this;
  24655. }
  24656. toJSON() {
  24657. const data = super.toJSON();
  24658. data.uuid = this.uuid;
  24659. data.holes = [];
  24660. for ( let i = 0, l = this.holes.length; i < l; i ++ ) {
  24661. const hole = this.holes[ i ];
  24662. data.holes.push( hole.toJSON() );
  24663. }
  24664. return data;
  24665. }
  24666. fromJSON( json ) {
  24667. super.fromJSON( json );
  24668. this.uuid = json.uuid;
  24669. this.holes = [];
  24670. for ( let i = 0, l = json.holes.length; i < l; i ++ ) {
  24671. const hole = json.holes[ i ];
  24672. this.holes.push( new Path().fromJSON( hole ) );
  24673. }
  24674. return this;
  24675. }
  24676. }
  24677. /**
  24678. * An implementation of the earcut polygon triangulation algorithm. The code
  24679. * is a port of [mapbox/earcut]{@link https://github.com/mapbox/earcut mapbox/earcut} (v2.2.4).
  24680. *
  24681. * @hideconstructor
  24682. */
  24683. class Earcut {
  24684. /**
  24685. * Triangulates the given shape definition by returning an array of triangles.
  24686. *
  24687. * @param {Array<number>} data - An array with 2D points.
  24688. * @param {Array<number>} holeIndices - An array with indices defining holes.
  24689. * @param {number} [dim=2] - The number of coordinates per vertex in the input array.
  24690. * @return {Array<number>} An array representing the triangulated faces. Each face is defined by three consecutive numbers
  24691. * representing vertex indices.
  24692. */
  24693. static triangulate( data, holeIndices, dim = 2 ) {
  24694. const hasHoles = holeIndices && holeIndices.length;
  24695. const outerLen = hasHoles ? holeIndices[ 0 ] * dim : data.length;
  24696. let outerNode = linkedList( data, 0, outerLen, dim, true );
  24697. const triangles = [];
  24698. if ( ! outerNode || outerNode.next === outerNode.prev ) return triangles;
  24699. let minX, minY, maxX, maxY, x, y, invSize;
  24700. if ( hasHoles ) outerNode = eliminateHoles( data, holeIndices, outerNode, dim );
  24701. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  24702. if ( data.length > 80 * dim ) {
  24703. minX = maxX = data[ 0 ];
  24704. minY = maxY = data[ 1 ];
  24705. for ( let i = dim; i < outerLen; i += dim ) {
  24706. x = data[ i ];
  24707. y = data[ i + 1 ];
  24708. if ( x < minX ) minX = x;
  24709. if ( y < minY ) minY = y;
  24710. if ( x > maxX ) maxX = x;
  24711. if ( y > maxY ) maxY = y;
  24712. }
  24713. // minX, minY and invSize are later used to transform coords into integers for z-order calculation
  24714. invSize = Math.max( maxX - minX, maxY - minY );
  24715. invSize = invSize !== 0 ? 32767 / invSize : 0;
  24716. }
  24717. earcutLinked( outerNode, triangles, dim, minX, minY, invSize, 0 );
  24718. return triangles;
  24719. }
  24720. }
  24721. // create a circular doubly linked list from polygon points in the specified winding order
  24722. function linkedList( data, start, end, dim, clockwise ) {
  24723. let i, last;
  24724. if ( clockwise === ( signedArea( data, start, end, dim ) > 0 ) ) {
  24725. for ( i = start; i < end; i += dim ) last = insertNode( i, data[ i ], data[ i + 1 ], last );
  24726. } else {
  24727. for ( i = end - dim; i >= start; i -= dim ) last = insertNode( i, data[ i ], data[ i + 1 ], last );
  24728. }
  24729. if ( last && equals( last, last.next ) ) {
  24730. removeNode( last );
  24731. last = last.next;
  24732. }
  24733. return last;
  24734. }
  24735. // eliminate colinear or duplicate points
  24736. function filterPoints( start, end ) {
  24737. if ( ! start ) return start;
  24738. if ( ! end ) end = start;
  24739. let p = start,
  24740. again;
  24741. do {
  24742. again = false;
  24743. if ( ! p.steiner && ( equals( p, p.next ) || area( p.prev, p, p.next ) === 0 ) ) {
  24744. removeNode( p );
  24745. p = end = p.prev;
  24746. if ( p === p.next ) break;
  24747. again = true;
  24748. } else {
  24749. p = p.next;
  24750. }
  24751. } while ( again || p !== end );
  24752. return end;
  24753. }
  24754. // main ear slicing loop which triangulates a polygon (given as a linked list)
  24755. function earcutLinked( ear, triangles, dim, minX, minY, invSize, pass ) {
  24756. if ( ! ear ) return;
  24757. // interlink polygon nodes in z-order
  24758. if ( ! pass && invSize ) indexCurve( ear, minX, minY, invSize );
  24759. let stop = ear,
  24760. prev, next;
  24761. // iterate through ears, slicing them one by one
  24762. while ( ear.prev !== ear.next ) {
  24763. prev = ear.prev;
  24764. next = ear.next;
  24765. if ( invSize ? isEarHashed( ear, minX, minY, invSize ) : isEar( ear ) ) {
  24766. // cut off the triangle
  24767. triangles.push( prev.i / dim | 0 );
  24768. triangles.push( ear.i / dim | 0 );
  24769. triangles.push( next.i / dim | 0 );
  24770. removeNode( ear );
  24771. // skipping the next vertex leads to less sliver triangles
  24772. ear = next.next;
  24773. stop = next.next;
  24774. continue;
  24775. }
  24776. ear = next;
  24777. // if we looped through the whole remaining polygon and can't find any more ears
  24778. if ( ear === stop ) {
  24779. // try filtering points and slicing again
  24780. if ( ! pass ) {
  24781. earcutLinked( filterPoints( ear ), triangles, dim, minX, minY, invSize, 1 );
  24782. // if this didn't work, try curing all small self-intersections locally
  24783. } else if ( pass === 1 ) {
  24784. ear = cureLocalIntersections( filterPoints( ear ), triangles, dim );
  24785. earcutLinked( ear, triangles, dim, minX, minY, invSize, 2 );
  24786. // as a last resort, try splitting the remaining polygon into two
  24787. } else if ( pass === 2 ) {
  24788. splitEarcut( ear, triangles, dim, minX, minY, invSize );
  24789. }
  24790. break;
  24791. }
  24792. }
  24793. }
  24794. // check whether a polygon node forms a valid ear with adjacent nodes
  24795. function isEar( ear ) {
  24796. const a = ear.prev,
  24797. b = ear,
  24798. c = ear.next;
  24799. if ( area( a, b, c ) >= 0 ) return false; // reflex, can't be an ear
  24800. // now make sure we don't have other points inside the potential ear
  24801. const ax = a.x, bx = b.x, cx = c.x, ay = a.y, by = b.y, cy = c.y;
  24802. // triangle bbox; min & max are calculated like this for speed
  24803. const x0 = ax < bx ? ( ax < cx ? ax : cx ) : ( bx < cx ? bx : cx ),
  24804. y0 = ay < by ? ( ay < cy ? ay : cy ) : ( by < cy ? by : cy ),
  24805. x1 = ax > bx ? ( ax > cx ? ax : cx ) : ( bx > cx ? bx : cx ),
  24806. y1 = ay > by ? ( ay > cy ? ay : cy ) : ( by > cy ? by : cy );
  24807. let p = c.next;
  24808. while ( p !== a ) {
  24809. if ( p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 &&
  24810. pointInTriangle( ax, ay, bx, by, cx, cy, p.x, p.y ) &&
  24811. area( p.prev, p, p.next ) >= 0 ) return false;
  24812. p = p.next;
  24813. }
  24814. return true;
  24815. }
  24816. function isEarHashed( ear, minX, minY, invSize ) {
  24817. const a = ear.prev,
  24818. b = ear,
  24819. c = ear.next;
  24820. if ( area( a, b, c ) >= 0 ) return false; // reflex, can't be an ear
  24821. const ax = a.x, bx = b.x, cx = c.x, ay = a.y, by = b.y, cy = c.y;
  24822. // triangle bbox; min & max are calculated like this for speed
  24823. const x0 = ax < bx ? ( ax < cx ? ax : cx ) : ( bx < cx ? bx : cx ),
  24824. y0 = ay < by ? ( ay < cy ? ay : cy ) : ( by < cy ? by : cy ),
  24825. x1 = ax > bx ? ( ax > cx ? ax : cx ) : ( bx > cx ? bx : cx ),
  24826. y1 = ay > by ? ( ay > cy ? ay : cy ) : ( by > cy ? by : cy );
  24827. // z-order range for the current triangle bbox;
  24828. const minZ = zOrder( x0, y0, minX, minY, invSize ),
  24829. maxZ = zOrder( x1, y1, minX, minY, invSize );
  24830. let p = ear.prevZ,
  24831. n = ear.nextZ;
  24832. // look for points inside the triangle in both directions
  24833. while ( p && p.z >= minZ && n && n.z <= maxZ ) {
  24834. if ( p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 && p !== a && p !== c &&
  24835. pointInTriangle( ax, ay, bx, by, cx, cy, p.x, p.y ) && area( p.prev, p, p.next ) >= 0 ) return false;
  24836. p = p.prevZ;
  24837. if ( n.x >= x0 && n.x <= x1 && n.y >= y0 && n.y <= y1 && n !== a && n !== c &&
  24838. pointInTriangle( ax, ay, bx, by, cx, cy, n.x, n.y ) && area( n.prev, n, n.next ) >= 0 ) return false;
  24839. n = n.nextZ;
  24840. }
  24841. // look for remaining points in decreasing z-order
  24842. while ( p && p.z >= minZ ) {
  24843. if ( p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 && p !== a && p !== c &&
  24844. pointInTriangle( ax, ay, bx, by, cx, cy, p.x, p.y ) && area( p.prev, p, p.next ) >= 0 ) return false;
  24845. p = p.prevZ;
  24846. }
  24847. // look for remaining points in increasing z-order
  24848. while ( n && n.z <= maxZ ) {
  24849. if ( n.x >= x0 && n.x <= x1 && n.y >= y0 && n.y <= y1 && n !== a && n !== c &&
  24850. pointInTriangle( ax, ay, bx, by, cx, cy, n.x, n.y ) && area( n.prev, n, n.next ) >= 0 ) return false;
  24851. n = n.nextZ;
  24852. }
  24853. return true;
  24854. }
  24855. // go through all polygon nodes and cure small local self-intersections
  24856. function cureLocalIntersections( start, triangles, dim ) {
  24857. let p = start;
  24858. do {
  24859. const a = p.prev,
  24860. b = p.next.next;
  24861. if ( ! equals( a, b ) && intersects( a, p, p.next, b ) && locallyInside( a, b ) && locallyInside( b, a ) ) {
  24862. triangles.push( a.i / dim | 0 );
  24863. triangles.push( p.i / dim | 0 );
  24864. triangles.push( b.i / dim | 0 );
  24865. // remove two nodes involved
  24866. removeNode( p );
  24867. removeNode( p.next );
  24868. p = start = b;
  24869. }
  24870. p = p.next;
  24871. } while ( p !== start );
  24872. return filterPoints( p );
  24873. }
  24874. // try splitting polygon into two and triangulate them independently
  24875. function splitEarcut( start, triangles, dim, minX, minY, invSize ) {
  24876. // look for a valid diagonal that divides the polygon into two
  24877. let a = start;
  24878. do {
  24879. let b = a.next.next;
  24880. while ( b !== a.prev ) {
  24881. if ( a.i !== b.i && isValidDiagonal( a, b ) ) {
  24882. // split the polygon in two by the diagonal
  24883. let c = splitPolygon( a, b );
  24884. // filter colinear points around the cuts
  24885. a = filterPoints( a, a.next );
  24886. c = filterPoints( c, c.next );
  24887. // run earcut on each half
  24888. earcutLinked( a, triangles, dim, minX, minY, invSize, 0 );
  24889. earcutLinked( c, triangles, dim, minX, minY, invSize, 0 );
  24890. return;
  24891. }
  24892. b = b.next;
  24893. }
  24894. a = a.next;
  24895. } while ( a !== start );
  24896. }
  24897. // link every hole into the outer loop, producing a single-ring polygon without holes
  24898. function eliminateHoles( data, holeIndices, outerNode, dim ) {
  24899. const queue = [];
  24900. let i, len, start, end, list;
  24901. for ( i = 0, len = holeIndices.length; i < len; i ++ ) {
  24902. start = holeIndices[ i ] * dim;
  24903. end = i < len - 1 ? holeIndices[ i + 1 ] * dim : data.length;
  24904. list = linkedList( data, start, end, dim, false );
  24905. if ( list === list.next ) list.steiner = true;
  24906. queue.push( getLeftmost( list ) );
  24907. }
  24908. queue.sort( compareX );
  24909. // process holes from left to right
  24910. for ( i = 0; i < queue.length; i ++ ) {
  24911. outerNode = eliminateHole( queue[ i ], outerNode );
  24912. }
  24913. return outerNode;
  24914. }
  24915. function compareX( a, b ) {
  24916. return a.x - b.x;
  24917. }
  24918. // find a bridge between vertices that connects hole with an outer ring and link it
  24919. function eliminateHole( hole, outerNode ) {
  24920. const bridge = findHoleBridge( hole, outerNode );
  24921. if ( ! bridge ) {
  24922. return outerNode;
  24923. }
  24924. const bridgeReverse = splitPolygon( bridge, hole );
  24925. // filter collinear points around the cuts
  24926. filterPoints( bridgeReverse, bridgeReverse.next );
  24927. return filterPoints( bridge, bridge.next );
  24928. }
  24929. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  24930. function findHoleBridge( hole, outerNode ) {
  24931. let p = outerNode,
  24932. qx = - Infinity,
  24933. m;
  24934. const hx = hole.x, hy = hole.y;
  24935. // find a segment intersected by a ray from the hole's leftmost point to the left;
  24936. // segment's endpoint with lesser x will be potential connection point
  24937. do {
  24938. if ( hy <= p.y && hy >= p.next.y && p.next.y !== p.y ) {
  24939. const x = p.x + ( hy - p.y ) * ( p.next.x - p.x ) / ( p.next.y - p.y );
  24940. if ( x <= hx && x > qx ) {
  24941. qx = x;
  24942. m = p.x < p.next.x ? p : p.next;
  24943. if ( x === hx ) return m; // hole touches outer segment; pick leftmost endpoint
  24944. }
  24945. }
  24946. p = p.next;
  24947. } while ( p !== outerNode );
  24948. if ( ! m ) return null;
  24949. // look for points inside the triangle of hole point, segment intersection and endpoint;
  24950. // if there are no points found, we have a valid connection;
  24951. // otherwise choose the point of the minimum angle with the ray as connection point
  24952. const stop = m,
  24953. mx = m.x,
  24954. my = m.y;
  24955. let tanMin = Infinity, tan;
  24956. p = m;
  24957. do {
  24958. if ( hx >= p.x && p.x >= mx && hx !== p.x &&
  24959. pointInTriangle( hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y ) ) {
  24960. tan = Math.abs( hy - p.y ) / ( hx - p.x ); // tangential
  24961. if ( locallyInside( p, hole ) && ( tan < tanMin || ( tan === tanMin && ( p.x > m.x || ( p.x === m.x && sectorContainsSector( m, p ) ) ) ) ) ) {
  24962. m = p;
  24963. tanMin = tan;
  24964. }
  24965. }
  24966. p = p.next;
  24967. } while ( p !== stop );
  24968. return m;
  24969. }
  24970. // whether sector in vertex m contains sector in vertex p in the same coordinates
  24971. function sectorContainsSector( m, p ) {
  24972. return area( m.prev, m, p.prev ) < 0 && area( p.next, m, m.next ) < 0;
  24973. }
  24974. // interlink polygon nodes in z-order
  24975. function indexCurve( start, minX, minY, invSize ) {
  24976. let p = start;
  24977. do {
  24978. if ( p.z === 0 ) p.z = zOrder( p.x, p.y, minX, minY, invSize );
  24979. p.prevZ = p.prev;
  24980. p.nextZ = p.next;
  24981. p = p.next;
  24982. } while ( p !== start );
  24983. p.prevZ.nextZ = null;
  24984. p.prevZ = null;
  24985. sortLinked( p );
  24986. }
  24987. // Simon Tatham's linked list merge sort algorithm
  24988. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  24989. function sortLinked( list ) {
  24990. let i, p, q, e, tail, numMerges, pSize, qSize,
  24991. inSize = 1;
  24992. do {
  24993. p = list;
  24994. list = null;
  24995. tail = null;
  24996. numMerges = 0;
  24997. while ( p ) {
  24998. numMerges ++;
  24999. q = p;
  25000. pSize = 0;
  25001. for ( i = 0; i < inSize; i ++ ) {
  25002. pSize ++;
  25003. q = q.nextZ;
  25004. if ( ! q ) break;
  25005. }
  25006. qSize = inSize;
  25007. while ( pSize > 0 || ( qSize > 0 && q ) ) {
  25008. if ( pSize !== 0 && ( qSize === 0 || ! q || p.z <= q.z ) ) {
  25009. e = p;
  25010. p = p.nextZ;
  25011. pSize --;
  25012. } else {
  25013. e = q;
  25014. q = q.nextZ;
  25015. qSize --;
  25016. }
  25017. if ( tail ) tail.nextZ = e;
  25018. else list = e;
  25019. e.prevZ = tail;
  25020. tail = e;
  25021. }
  25022. p = q;
  25023. }
  25024. tail.nextZ = null;
  25025. inSize *= 2;
  25026. } while ( numMerges > 1 );
  25027. return list;
  25028. }
  25029. // z-order of a point given coords and inverse of the longer side of data bbox
  25030. function zOrder( x, y, minX, minY, invSize ) {
  25031. // coords are transformed into non-negative 15-bit integer range
  25032. x = ( x - minX ) * invSize | 0;
  25033. y = ( y - minY ) * invSize | 0;
  25034. x = ( x | ( x << 8 ) ) & 0x00FF00FF;
  25035. x = ( x | ( x << 4 ) ) & 0x0F0F0F0F;
  25036. x = ( x | ( x << 2 ) ) & 0x33333333;
  25037. x = ( x | ( x << 1 ) ) & 0x55555555;
  25038. y = ( y | ( y << 8 ) ) & 0x00FF00FF;
  25039. y = ( y | ( y << 4 ) ) & 0x0F0F0F0F;
  25040. y = ( y | ( y << 2 ) ) & 0x33333333;
  25041. y = ( y | ( y << 1 ) ) & 0x55555555;
  25042. return x | ( y << 1 );
  25043. }
  25044. // find the leftmost node of a polygon ring
  25045. function getLeftmost( start ) {
  25046. let p = start,
  25047. leftmost = start;
  25048. do {
  25049. if ( p.x < leftmost.x || ( p.x === leftmost.x && p.y < leftmost.y ) ) leftmost = p;
  25050. p = p.next;
  25051. } while ( p !== start );
  25052. return leftmost;
  25053. }
  25054. // check if a point lies within a convex triangle
  25055. function pointInTriangle( ax, ay, bx, by, cx, cy, px, py ) {
  25056. return ( cx - px ) * ( ay - py ) >= ( ax - px ) * ( cy - py ) &&
  25057. ( ax - px ) * ( by - py ) >= ( bx - px ) * ( ay - py ) &&
  25058. ( bx - px ) * ( cy - py ) >= ( cx - px ) * ( by - py );
  25059. }
  25060. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  25061. function isValidDiagonal( a, b ) {
  25062. return a.next.i !== b.i && a.prev.i !== b.i && ! intersectsPolygon( a, b ) && // doesn't intersect other edges
  25063. ( locallyInside( a, b ) && locallyInside( b, a ) && middleInside( a, b ) && // locally visible
  25064. ( area( a.prev, a, b.prev ) || area( a, b.prev, b ) ) || // does not create opposite-facing sectors
  25065. equals( a, b ) && area( a.prev, a, a.next ) > 0 && area( b.prev, b, b.next ) > 0 ); // special zero-length case
  25066. }
  25067. // signed area of a triangle
  25068. function area( p, q, r ) {
  25069. return ( q.y - p.y ) * ( r.x - q.x ) - ( q.x - p.x ) * ( r.y - q.y );
  25070. }
  25071. // check if two points are equal
  25072. function equals( p1, p2 ) {
  25073. return p1.x === p2.x && p1.y === p2.y;
  25074. }
  25075. // check if two segments intersect
  25076. function intersects( p1, q1, p2, q2 ) {
  25077. const o1 = sign( area( p1, q1, p2 ) );
  25078. const o2 = sign( area( p1, q1, q2 ) );
  25079. const o3 = sign( area( p2, q2, p1 ) );
  25080. const o4 = sign( area( p2, q2, q1 ) );
  25081. if ( o1 !== o2 && o3 !== o4 ) return true; // general case
  25082. if ( o1 === 0 && onSegment( p1, p2, q1 ) ) return true; // p1, q1 and p2 are collinear and p2 lies on p1q1
  25083. if ( o2 === 0 && onSegment( p1, q2, q1 ) ) return true; // p1, q1 and q2 are collinear and q2 lies on p1q1
  25084. if ( o3 === 0 && onSegment( p2, p1, q2 ) ) return true; // p2, q2 and p1 are collinear and p1 lies on p2q2
  25085. if ( o4 === 0 && onSegment( p2, q1, q2 ) ) return true; // p2, q2 and q1 are collinear and q1 lies on p2q2
  25086. return false;
  25087. }
  25088. // for collinear points p, q, r, check if point q lies on segment pr
  25089. function onSegment( p, q, r ) {
  25090. 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 );
  25091. }
  25092. function sign( num ) {
  25093. return num > 0 ? 1 : num < 0 ? -1 : 0;
  25094. }
  25095. // check if a polygon diagonal intersects any polygon segments
  25096. function intersectsPolygon( a, b ) {
  25097. let p = a;
  25098. do {
  25099. if ( p.i !== a.i && p.next.i !== a.i && p.i !== b.i && p.next.i !== b.i &&
  25100. intersects( p, p.next, a, b ) ) return true;
  25101. p = p.next;
  25102. } while ( p !== a );
  25103. return false;
  25104. }
  25105. // check if a polygon diagonal is locally inside the polygon
  25106. function locallyInside( a, b ) {
  25107. return area( a.prev, a, a.next ) < 0 ?
  25108. area( a, b, a.next ) >= 0 && area( a, a.prev, b ) >= 0 :
  25109. area( a, b, a.prev ) < 0 || area( a, a.next, b ) < 0;
  25110. }
  25111. // check if the middle point of a polygon diagonal is inside the polygon
  25112. function middleInside( a, b ) {
  25113. let p = a,
  25114. inside = false;
  25115. const px = ( a.x + b.x ) / 2,
  25116. py = ( a.y + b.y ) / 2;
  25117. do {
  25118. if ( ( ( p.y > py ) !== ( p.next.y > py ) ) && p.next.y !== p.y &&
  25119. ( px < ( p.next.x - p.x ) * ( py - p.y ) / ( p.next.y - p.y ) + p.x ) )
  25120. inside = ! inside;
  25121. p = p.next;
  25122. } while ( p !== a );
  25123. return inside;
  25124. }
  25125. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  25126. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  25127. function splitPolygon( a, b ) {
  25128. const a2 = new Node( a.i, a.x, a.y ),
  25129. b2 = new Node( b.i, b.x, b.y ),
  25130. an = a.next,
  25131. bp = b.prev;
  25132. a.next = b;
  25133. b.prev = a;
  25134. a2.next = an;
  25135. an.prev = a2;
  25136. b2.next = a2;
  25137. a2.prev = b2;
  25138. bp.next = b2;
  25139. b2.prev = bp;
  25140. return b2;
  25141. }
  25142. // create a node and optionally link it with previous one (in a circular doubly linked list)
  25143. function insertNode( i, x, y, last ) {
  25144. const p = new Node( i, x, y );
  25145. if ( ! last ) {
  25146. p.prev = p;
  25147. p.next = p;
  25148. } else {
  25149. p.next = last.next;
  25150. p.prev = last;
  25151. last.next.prev = p;
  25152. last.next = p;
  25153. }
  25154. return p;
  25155. }
  25156. function removeNode( p ) {
  25157. p.next.prev = p.prev;
  25158. p.prev.next = p.next;
  25159. if ( p.prevZ ) p.prevZ.nextZ = p.nextZ;
  25160. if ( p.nextZ ) p.nextZ.prevZ = p.prevZ;
  25161. }
  25162. function Node( i, x, y ) {
  25163. // vertex index in coordinates array
  25164. this.i = i;
  25165. // vertex coordinates
  25166. this.x = x;
  25167. this.y = y;
  25168. // previous and next vertex nodes in a polygon ring
  25169. this.prev = null;
  25170. this.next = null;
  25171. // z-order curve value
  25172. this.z = 0;
  25173. // previous and next nodes in z-order
  25174. this.prevZ = null;
  25175. this.nextZ = null;
  25176. // indicates whether this is a steiner point
  25177. this.steiner = false;
  25178. }
  25179. function signedArea( data, start, end, dim ) {
  25180. let sum = 0;
  25181. for ( let i = start, j = end - dim; i < end; i += dim ) {
  25182. sum += ( data[ j ] - data[ i ] ) * ( data[ i + 1 ] + data[ j + 1 ] );
  25183. j = i;
  25184. }
  25185. return sum;
  25186. }
  25187. /**
  25188. * A class containing utility functions for shapes.
  25189. *
  25190. * @hideconstructor
  25191. */
  25192. class ShapeUtils {
  25193. /**
  25194. * Calculate area of a ( 2D ) contour polygon.
  25195. *
  25196. * @param {Array<Vector2>} contour - An array of 2D points.
  25197. * @return {number} The area.
  25198. */
  25199. static area( contour ) {
  25200. const n = contour.length;
  25201. let a = 0.0;
  25202. for ( let p = n - 1, q = 0; q < n; p = q ++ ) {
  25203. a += contour[ p ].x * contour[ q ].y - contour[ q ].x * contour[ p ].y;
  25204. }
  25205. return a * 0.5;
  25206. }
  25207. /**
  25208. * Returns `true` if the given contour uses a clockwise winding order.
  25209. *
  25210. * @param {Array<Vector2>} pts - An array of 2D points defining a polygon.
  25211. * @return {boolean} Whether the given contour uses a clockwise winding order or not.
  25212. */
  25213. static isClockWise( pts ) {
  25214. return ShapeUtils.area( pts ) < 0;
  25215. }
  25216. /**
  25217. * Triangulates the given shape definition.
  25218. *
  25219. * @param {Array<Vector2>} contour - An array of 2D points defining the contour.
  25220. * @param {Array<Array<Vector2>>} holes - An array that holds arrays of 2D points defining the holes.
  25221. * @return {Array<Array<number>>} An array that holds for each face definition an array with three indices.
  25222. */
  25223. static triangulateShape( contour, holes ) {
  25224. const vertices = []; // flat array of vertices like [ x0,y0, x1,y1, x2,y2, ... ]
  25225. const holeIndices = []; // array of hole indices
  25226. const faces = []; // final array of vertex indices like [ [ a,b,d ], [ b,c,d ] ]
  25227. removeDupEndPts( contour );
  25228. addContour( vertices, contour );
  25229. //
  25230. let holeIndex = contour.length;
  25231. holes.forEach( removeDupEndPts );
  25232. for ( let i = 0; i < holes.length; i ++ ) {
  25233. holeIndices.push( holeIndex );
  25234. holeIndex += holes[ i ].length;
  25235. addContour( vertices, holes[ i ] );
  25236. }
  25237. //
  25238. const triangles = Earcut.triangulate( vertices, holeIndices );
  25239. //
  25240. for ( let i = 0; i < triangles.length; i += 3 ) {
  25241. faces.push( triangles.slice( i, i + 3 ) );
  25242. }
  25243. return faces;
  25244. }
  25245. }
  25246. function removeDupEndPts( points ) {
  25247. const l = points.length;
  25248. if ( l > 2 && points[ l - 1 ].equals( points[ 0 ] ) ) {
  25249. points.pop();
  25250. }
  25251. }
  25252. function addContour( vertices, contour ) {
  25253. for ( let i = 0; i < contour.length; i ++ ) {
  25254. vertices.push( contour[ i ].x );
  25255. vertices.push( contour[ i ].y );
  25256. }
  25257. }
  25258. /**
  25259. * Creates extruded geometry from a path shape.
  25260. *
  25261. * ```js
  25262. * const length = 12, width = 8;
  25263. *
  25264. * const shape = new THREE.Shape();
  25265. * shape.moveTo( 0,0 );
  25266. * shape.lineTo( 0, width );
  25267. * shape.lineTo( length, width );
  25268. * shape.lineTo( length, 0 );
  25269. * shape.lineTo( 0, 0 );
  25270. *
  25271. * const geometry = new THREE.ExtrudeGeometry( shape );
  25272. * const material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } );
  25273. * const mesh = new THREE.Mesh( geometry, material ) ;
  25274. * scene.add( mesh );
  25275. * ```
  25276. *
  25277. * @augments BufferGeometry
  25278. */
  25279. class ExtrudeGeometry extends BufferGeometry {
  25280. /**
  25281. * Constructs a new extrude geometry.
  25282. *
  25283. * @param {Shape|Array<Shape>} [shapes] - A shape or an array of shapes.
  25284. * @param {ExtrudeGeometry~Options} [options] - The extrude settings.
  25285. */
  25286. 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 = {} ) {
  25287. super();
  25288. this.type = 'ExtrudeGeometry';
  25289. /**
  25290. * Holds the constructor parameters that have been
  25291. * used to generate the geometry. Any modification
  25292. * after instantiation does not change the geometry.
  25293. *
  25294. * @type {Object}
  25295. */
  25296. this.parameters = {
  25297. shapes: shapes,
  25298. options: options
  25299. };
  25300. shapes = Array.isArray( shapes ) ? shapes : [ shapes ];
  25301. const scope = this;
  25302. const verticesArray = [];
  25303. const uvArray = [];
  25304. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  25305. const shape = shapes[ i ];
  25306. addShape( shape );
  25307. }
  25308. // build geometry
  25309. this.setAttribute( 'position', new Float32BufferAttribute( verticesArray, 3 ) );
  25310. this.setAttribute( 'uv', new Float32BufferAttribute( uvArray, 2 ) );
  25311. this.computeVertexNormals();
  25312. // functions
  25313. function addShape( shape ) {
  25314. const placeholder = [];
  25315. // options
  25316. const curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  25317. const steps = options.steps !== undefined ? options.steps : 1;
  25318. const depth = options.depth !== undefined ? options.depth : 1;
  25319. let bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true;
  25320. let bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 0.2;
  25321. let bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 0.1;
  25322. let bevelOffset = options.bevelOffset !== undefined ? options.bevelOffset : 0;
  25323. let bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3;
  25324. const extrudePath = options.extrudePath;
  25325. const uvgen = options.UVGenerator !== undefined ? options.UVGenerator : WorldUVGenerator;
  25326. //
  25327. let extrudePts, extrudeByPath = false;
  25328. let splineTube, binormal, normal, position2;
  25329. if ( extrudePath ) {
  25330. extrudePts = extrudePath.getSpacedPoints( steps );
  25331. extrudeByPath = true;
  25332. bevelEnabled = false; // bevels not supported for path extrusion
  25333. // SETUP TNB variables
  25334. // TODO1 - have a .isClosed in spline?
  25335. splineTube = extrudePath.computeFrenetFrames( steps, false );
  25336. // console.log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length);
  25337. binormal = new Vector3();
  25338. normal = new Vector3();
  25339. position2 = new Vector3();
  25340. }
  25341. // Safeguards if bevels are not enabled
  25342. if ( ! bevelEnabled ) {
  25343. bevelSegments = 0;
  25344. bevelThickness = 0;
  25345. bevelSize = 0;
  25346. bevelOffset = 0;
  25347. }
  25348. // Variables initialization
  25349. const shapePoints = shape.extractPoints( curveSegments );
  25350. let vertices = shapePoints.shape;
  25351. const holes = shapePoints.holes;
  25352. const reverse = ! ShapeUtils.isClockWise( vertices );
  25353. if ( reverse ) {
  25354. vertices = vertices.reverse();
  25355. // Maybe we should also check if holes are in the opposite direction, just to be safe ...
  25356. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  25357. const ahole = holes[ h ];
  25358. if ( ShapeUtils.isClockWise( ahole ) ) {
  25359. holes[ h ] = ahole.reverse();
  25360. }
  25361. }
  25362. }
  25363. const faces = ShapeUtils.triangulateShape( vertices, holes );
  25364. /* Vertices */
  25365. const contour = vertices; // vertices has all points but contour has only points of circumference
  25366. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  25367. const ahole = holes[ h ];
  25368. vertices = vertices.concat( ahole );
  25369. }
  25370. function scalePt2( pt, vec, size ) {
  25371. if ( ! vec ) console.error( 'THREE.ExtrudeGeometry: vec does not exist' );
  25372. return pt.clone().addScaledVector( vec, size );
  25373. }
  25374. const vlen = vertices.length, flen = faces.length;
  25375. // Find directions for point movement
  25376. function getBevelVec( inPt, inPrev, inNext ) {
  25377. // computes for inPt the corresponding point inPt' on a new contour
  25378. // shifted by 1 unit (length of normalized vector) to the left
  25379. // if we walk along contour clockwise, this new contour is outside the old one
  25380. //
  25381. // inPt' is the intersection of the two lines parallel to the two
  25382. // adjacent edges of inPt at a distance of 1 unit on the left side.
  25383. let v_trans_x, v_trans_y, shrink_by; // resulting translation vector for inPt
  25384. // good reading for geometry algorithms (here: line-line intersection)
  25385. // http://geomalgorithms.com/a05-_intersect-1.html
  25386. const v_prev_x = inPt.x - inPrev.x,
  25387. v_prev_y = inPt.y - inPrev.y;
  25388. const v_next_x = inNext.x - inPt.x,
  25389. v_next_y = inNext.y - inPt.y;
  25390. const v_prev_lensq = ( v_prev_x * v_prev_x + v_prev_y * v_prev_y );
  25391. // check for collinear edges
  25392. const collinear0 = ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  25393. if ( Math.abs( collinear0 ) > Number.EPSILON ) {
  25394. // not collinear
  25395. // length of vectors for normalizing
  25396. const v_prev_len = Math.sqrt( v_prev_lensq );
  25397. const v_next_len = Math.sqrt( v_next_x * v_next_x + v_next_y * v_next_y );
  25398. // shift adjacent points by unit vectors to the left
  25399. const ptPrevShift_x = ( inPrev.x - v_prev_y / v_prev_len );
  25400. const ptPrevShift_y = ( inPrev.y + v_prev_x / v_prev_len );
  25401. const ptNextShift_x = ( inNext.x - v_next_y / v_next_len );
  25402. const ptNextShift_y = ( inNext.y + v_next_x / v_next_len );
  25403. // scaling factor for v_prev to intersection point
  25404. const sf = ( ( ptNextShift_x - ptPrevShift_x ) * v_next_y -
  25405. ( ptNextShift_y - ptPrevShift_y ) * v_next_x ) /
  25406. ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  25407. // vector from inPt to intersection point
  25408. v_trans_x = ( ptPrevShift_x + v_prev_x * sf - inPt.x );
  25409. v_trans_y = ( ptPrevShift_y + v_prev_y * sf - inPt.y );
  25410. // Don't normalize!, otherwise sharp corners become ugly
  25411. // but prevent crazy spikes
  25412. const v_trans_lensq = ( v_trans_x * v_trans_x + v_trans_y * v_trans_y );
  25413. if ( v_trans_lensq <= 2 ) {
  25414. return new Vector2( v_trans_x, v_trans_y );
  25415. } else {
  25416. shrink_by = Math.sqrt( v_trans_lensq / 2 );
  25417. }
  25418. } else {
  25419. // handle special case of collinear edges
  25420. let direction_eq = false; // assumes: opposite
  25421. if ( v_prev_x > Number.EPSILON ) {
  25422. if ( v_next_x > Number.EPSILON ) {
  25423. direction_eq = true;
  25424. }
  25425. } else {
  25426. if ( v_prev_x < - Number.EPSILON ) {
  25427. if ( v_next_x < - Number.EPSILON ) {
  25428. direction_eq = true;
  25429. }
  25430. } else {
  25431. if ( Math.sign( v_prev_y ) === Math.sign( v_next_y ) ) {
  25432. direction_eq = true;
  25433. }
  25434. }
  25435. }
  25436. if ( direction_eq ) {
  25437. // console.log("Warning: lines are a straight sequence");
  25438. v_trans_x = - v_prev_y;
  25439. v_trans_y = v_prev_x;
  25440. shrink_by = Math.sqrt( v_prev_lensq );
  25441. } else {
  25442. // console.log("Warning: lines are a straight spike");
  25443. v_trans_x = v_prev_x;
  25444. v_trans_y = v_prev_y;
  25445. shrink_by = Math.sqrt( v_prev_lensq / 2 );
  25446. }
  25447. }
  25448. return new Vector2( v_trans_x / shrink_by, v_trans_y / shrink_by );
  25449. }
  25450. const contourMovements = [];
  25451. for ( let i = 0, il = contour.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  25452. if ( j === il ) j = 0;
  25453. if ( k === il ) k = 0;
  25454. // (j)---(i)---(k)
  25455. // console.log('i,j,k', i, j , k)
  25456. contourMovements[ i ] = getBevelVec( contour[ i ], contour[ j ], contour[ k ] );
  25457. }
  25458. const holesMovements = [];
  25459. let oneHoleMovements, verticesMovements = contourMovements.concat();
  25460. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  25461. const ahole = holes[ h ];
  25462. oneHoleMovements = [];
  25463. for ( let i = 0, il = ahole.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  25464. if ( j === il ) j = 0;
  25465. if ( k === il ) k = 0;
  25466. // (j)---(i)---(k)
  25467. oneHoleMovements[ i ] = getBevelVec( ahole[ i ], ahole[ j ], ahole[ k ] );
  25468. }
  25469. holesMovements.push( oneHoleMovements );
  25470. verticesMovements = verticesMovements.concat( oneHoleMovements );
  25471. }
  25472. // Loop bevelSegments, 1 for the front, 1 for the back
  25473. for ( let b = 0; b < bevelSegments; b ++ ) {
  25474. //for ( b = bevelSegments; b > 0; b -- ) {
  25475. const t = b / bevelSegments;
  25476. const z = bevelThickness * Math.cos( t * Math.PI / 2 );
  25477. const bs = bevelSize * Math.sin( t * Math.PI / 2 ) + bevelOffset;
  25478. // contract shape
  25479. for ( let i = 0, il = contour.length; i < il; i ++ ) {
  25480. const vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  25481. v( vert.x, vert.y, - z );
  25482. }
  25483. // expand holes
  25484. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  25485. const ahole = holes[ h ];
  25486. oneHoleMovements = holesMovements[ h ];
  25487. for ( let i = 0, il = ahole.length; i < il; i ++ ) {
  25488. const vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  25489. v( vert.x, vert.y, - z );
  25490. }
  25491. }
  25492. }
  25493. const bs = bevelSize + bevelOffset;
  25494. // Back facing vertices
  25495. for ( let i = 0; i < vlen; i ++ ) {
  25496. const vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  25497. if ( ! extrudeByPath ) {
  25498. v( vert.x, vert.y, 0 );
  25499. } else {
  25500. // v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x );
  25501. normal.copy( splineTube.normals[ 0 ] ).multiplyScalar( vert.x );
  25502. binormal.copy( splineTube.binormals[ 0 ] ).multiplyScalar( vert.y );
  25503. position2.copy( extrudePts[ 0 ] ).add( normal ).add( binormal );
  25504. v( position2.x, position2.y, position2.z );
  25505. }
  25506. }
  25507. // Add stepped vertices...
  25508. // Including front facing vertices
  25509. for ( let s = 1; s <= steps; s ++ ) {
  25510. for ( let i = 0; i < vlen; i ++ ) {
  25511. const vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  25512. if ( ! extrudeByPath ) {
  25513. v( vert.x, vert.y, depth / steps * s );
  25514. } else {
  25515. // v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x );
  25516. normal.copy( splineTube.normals[ s ] ).multiplyScalar( vert.x );
  25517. binormal.copy( splineTube.binormals[ s ] ).multiplyScalar( vert.y );
  25518. position2.copy( extrudePts[ s ] ).add( normal ).add( binormal );
  25519. v( position2.x, position2.y, position2.z );
  25520. }
  25521. }
  25522. }
  25523. // Add bevel segments planes
  25524. //for ( b = 1; b <= bevelSegments; b ++ ) {
  25525. for ( let b = bevelSegments - 1; b >= 0; b -- ) {
  25526. const t = b / bevelSegments;
  25527. const z = bevelThickness * Math.cos( t * Math.PI / 2 );
  25528. const bs = bevelSize * Math.sin( t * Math.PI / 2 ) + bevelOffset;
  25529. // contract shape
  25530. for ( let i = 0, il = contour.length; i < il; i ++ ) {
  25531. const vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  25532. v( vert.x, vert.y, depth + z );
  25533. }
  25534. // expand holes
  25535. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  25536. const ahole = holes[ h ];
  25537. oneHoleMovements = holesMovements[ h ];
  25538. for ( let i = 0, il = ahole.length; i < il; i ++ ) {
  25539. const vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  25540. if ( ! extrudeByPath ) {
  25541. v( vert.x, vert.y, depth + z );
  25542. } else {
  25543. v( vert.x, vert.y + extrudePts[ steps - 1 ].y, extrudePts[ steps - 1 ].x + z );
  25544. }
  25545. }
  25546. }
  25547. }
  25548. /* Faces */
  25549. // Top and bottom faces
  25550. buildLidFaces();
  25551. // Sides faces
  25552. buildSideFaces();
  25553. ///// Internal functions
  25554. function buildLidFaces() {
  25555. const start = verticesArray.length / 3;
  25556. if ( bevelEnabled ) {
  25557. let layer = 0; // steps + 1
  25558. let offset = vlen * layer;
  25559. // Bottom faces
  25560. for ( let i = 0; i < flen; i ++ ) {
  25561. const face = faces[ i ];
  25562. f3( face[ 2 ] + offset, face[ 1 ] + offset, face[ 0 ] + offset );
  25563. }
  25564. layer = steps + bevelSegments * 2;
  25565. offset = vlen * layer;
  25566. // Top faces
  25567. for ( let i = 0; i < flen; i ++ ) {
  25568. const face = faces[ i ];
  25569. f3( face[ 0 ] + offset, face[ 1 ] + offset, face[ 2 ] + offset );
  25570. }
  25571. } else {
  25572. // Bottom faces
  25573. for ( let i = 0; i < flen; i ++ ) {
  25574. const face = faces[ i ];
  25575. f3( face[ 2 ], face[ 1 ], face[ 0 ] );
  25576. }
  25577. // Top faces
  25578. for ( let i = 0; i < flen; i ++ ) {
  25579. const face = faces[ i ];
  25580. f3( face[ 0 ] + vlen * steps, face[ 1 ] + vlen * steps, face[ 2 ] + vlen * steps );
  25581. }
  25582. }
  25583. scope.addGroup( start, verticesArray.length / 3 - start, 0 );
  25584. }
  25585. // Create faces for the z-sides of the shape
  25586. function buildSideFaces() {
  25587. const start = verticesArray.length / 3;
  25588. let layeroffset = 0;
  25589. sidewalls( contour, layeroffset );
  25590. layeroffset += contour.length;
  25591. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  25592. const ahole = holes[ h ];
  25593. sidewalls( ahole, layeroffset );
  25594. //, true
  25595. layeroffset += ahole.length;
  25596. }
  25597. scope.addGroup( start, verticesArray.length / 3 - start, 1 );
  25598. }
  25599. function sidewalls( contour, layeroffset ) {
  25600. let i = contour.length;
  25601. while ( -- i >= 0 ) {
  25602. const j = i;
  25603. let k = i - 1;
  25604. if ( k < 0 ) k = contour.length - 1;
  25605. //console.log('b', i,j, i-1, k,vertices.length);
  25606. for ( let s = 0, sl = ( steps + bevelSegments * 2 ); s < sl; s ++ ) {
  25607. const slen1 = vlen * s;
  25608. const slen2 = vlen * ( s + 1 );
  25609. const a = layeroffset + j + slen1,
  25610. b = layeroffset + k + slen1,
  25611. c = layeroffset + k + slen2,
  25612. d = layeroffset + j + slen2;
  25613. f4( a, b, c, d );
  25614. }
  25615. }
  25616. }
  25617. function v( x, y, z ) {
  25618. placeholder.push( x );
  25619. placeholder.push( y );
  25620. placeholder.push( z );
  25621. }
  25622. function f3( a, b, c ) {
  25623. addVertex( a );
  25624. addVertex( b );
  25625. addVertex( c );
  25626. const nextIndex = verticesArray.length / 3;
  25627. const uvs = uvgen.generateTopUV( scope, verticesArray, nextIndex - 3, nextIndex - 2, nextIndex - 1 );
  25628. addUV( uvs[ 0 ] );
  25629. addUV( uvs[ 1 ] );
  25630. addUV( uvs[ 2 ] );
  25631. }
  25632. function f4( a, b, c, d ) {
  25633. addVertex( a );
  25634. addVertex( b );
  25635. addVertex( d );
  25636. addVertex( b );
  25637. addVertex( c );
  25638. addVertex( d );
  25639. const nextIndex = verticesArray.length / 3;
  25640. const uvs = uvgen.generateSideWallUV( scope, verticesArray, nextIndex - 6, nextIndex - 3, nextIndex - 2, nextIndex - 1 );
  25641. addUV( uvs[ 0 ] );
  25642. addUV( uvs[ 1 ] );
  25643. addUV( uvs[ 3 ] );
  25644. addUV( uvs[ 1 ] );
  25645. addUV( uvs[ 2 ] );
  25646. addUV( uvs[ 3 ] );
  25647. }
  25648. function addVertex( index ) {
  25649. verticesArray.push( placeholder[ index * 3 + 0 ] );
  25650. verticesArray.push( placeholder[ index * 3 + 1 ] );
  25651. verticesArray.push( placeholder[ index * 3 + 2 ] );
  25652. }
  25653. function addUV( vector2 ) {
  25654. uvArray.push( vector2.x );
  25655. uvArray.push( vector2.y );
  25656. }
  25657. }
  25658. }
  25659. copy( source ) {
  25660. super.copy( source );
  25661. this.parameters = Object.assign( {}, source.parameters );
  25662. return this;
  25663. }
  25664. toJSON() {
  25665. const data = super.toJSON();
  25666. const shapes = this.parameters.shapes;
  25667. const options = this.parameters.options;
  25668. return toJSON$1( shapes, options, data );
  25669. }
  25670. /**
  25671. * Factory method for creating an instance of this class from the given
  25672. * JSON object.
  25673. *
  25674. * @param {Object} data - A JSON object representing the serialized geometry.
  25675. * @param {Array<Shape>} shapes - An array of shapes.
  25676. * @return {ExtrudeGeometry} A new instance.
  25677. */
  25678. static fromJSON( data, shapes ) {
  25679. const geometryShapes = [];
  25680. for ( let j = 0, jl = data.shapes.length; j < jl; j ++ ) {
  25681. const shape = shapes[ data.shapes[ j ] ];
  25682. geometryShapes.push( shape );
  25683. }
  25684. const extrudePath = data.options.extrudePath;
  25685. if ( extrudePath !== undefined ) {
  25686. data.options.extrudePath = new Curves[ extrudePath.type ]().fromJSON( extrudePath );
  25687. }
  25688. return new ExtrudeGeometry( geometryShapes, data.options );
  25689. }
  25690. }
  25691. const WorldUVGenerator = {
  25692. generateTopUV: function ( geometry, vertices, indexA, indexB, indexC ) {
  25693. const a_x = vertices[ indexA * 3 ];
  25694. const a_y = vertices[ indexA * 3 + 1 ];
  25695. const b_x = vertices[ indexB * 3 ];
  25696. const b_y = vertices[ indexB * 3 + 1 ];
  25697. const c_x = vertices[ indexC * 3 ];
  25698. const c_y = vertices[ indexC * 3 + 1 ];
  25699. return [
  25700. new Vector2( a_x, a_y ),
  25701. new Vector2( b_x, b_y ),
  25702. new Vector2( c_x, c_y )
  25703. ];
  25704. },
  25705. generateSideWallUV: function ( geometry, vertices, indexA, indexB, indexC, indexD ) {
  25706. const a_x = vertices[ indexA * 3 ];
  25707. const a_y = vertices[ indexA * 3 + 1 ];
  25708. const a_z = vertices[ indexA * 3 + 2 ];
  25709. const b_x = vertices[ indexB * 3 ];
  25710. const b_y = vertices[ indexB * 3 + 1 ];
  25711. const b_z = vertices[ indexB * 3 + 2 ];
  25712. const c_x = vertices[ indexC * 3 ];
  25713. const c_y = vertices[ indexC * 3 + 1 ];
  25714. const c_z = vertices[ indexC * 3 + 2 ];
  25715. const d_x = vertices[ indexD * 3 ];
  25716. const d_y = vertices[ indexD * 3 + 1 ];
  25717. const d_z = vertices[ indexD * 3 + 2 ];
  25718. if ( Math.abs( a_y - b_y ) < Math.abs( a_x - b_x ) ) {
  25719. return [
  25720. new Vector2( a_x, 1 - a_z ),
  25721. new Vector2( b_x, 1 - b_z ),
  25722. new Vector2( c_x, 1 - c_z ),
  25723. new Vector2( d_x, 1 - d_z )
  25724. ];
  25725. } else {
  25726. return [
  25727. new Vector2( a_y, 1 - a_z ),
  25728. new Vector2( b_y, 1 - b_z ),
  25729. new Vector2( c_y, 1 - c_z ),
  25730. new Vector2( d_y, 1 - d_z )
  25731. ];
  25732. }
  25733. }
  25734. };
  25735. function toJSON$1( shapes, options, data ) {
  25736. data.shapes = [];
  25737. if ( Array.isArray( shapes ) ) {
  25738. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  25739. const shape = shapes[ i ];
  25740. data.shapes.push( shape.uuid );
  25741. }
  25742. } else {
  25743. data.shapes.push( shapes.uuid );
  25744. }
  25745. data.options = Object.assign( {}, options );
  25746. if ( options.extrudePath !== undefined ) data.options.extrudePath = options.extrudePath.toJSON();
  25747. return data;
  25748. }
  25749. /**
  25750. * A geometry class for representing an icosahedron.
  25751. *
  25752. * ```js
  25753. * const geometry = new THREE.IcosahedronGeometry();
  25754. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  25755. * const icosahedron = new THREE.Mesh( geometry, material );
  25756. * scene.add( icosahedron );
  25757. * ```
  25758. *
  25759. * @augments PolyhedronGeometry
  25760. */
  25761. class IcosahedronGeometry extends PolyhedronGeometry {
  25762. /**
  25763. * Constructs a new icosahedron geometry.
  25764. *
  25765. * @param {number} [radius=1] - Radius of the icosahedron.
  25766. * @param {number} [detail=0] - Setting this to a value greater than `0` adds vertices making it no longer a icosahedron.
  25767. */
  25768. constructor( radius = 1, detail = 0 ) {
  25769. const t = ( 1 + Math.sqrt( 5 ) ) / 2;
  25770. const vertices = [
  25771. -1, t, 0, 1, t, 0, -1, - t, 0, 1, - t, 0,
  25772. 0, -1, t, 0, 1, t, 0, -1, - t, 0, 1, - t,
  25773. t, 0, -1, t, 0, 1, - t, 0, -1, - t, 0, 1
  25774. ];
  25775. const indices = [
  25776. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 0, 10, 11,
  25777. 1, 5, 9, 5, 11, 4, 11, 10, 2, 10, 7, 6, 7, 1, 8,
  25778. 3, 9, 4, 3, 4, 2, 3, 2, 6, 3, 6, 8, 3, 8, 9,
  25779. 4, 9, 5, 2, 4, 11, 6, 2, 10, 8, 6, 7, 9, 8, 1
  25780. ];
  25781. super( vertices, indices, radius, detail );
  25782. this.type = 'IcosahedronGeometry';
  25783. /**
  25784. * Holds the constructor parameters that have been
  25785. * used to generate the geometry. Any modification
  25786. * after instantiation does not change the geometry.
  25787. *
  25788. * @type {Object}
  25789. */
  25790. this.parameters = {
  25791. radius: radius,
  25792. detail: detail
  25793. };
  25794. }
  25795. /**
  25796. * Factory method for creating an instance of this class from the given
  25797. * JSON object.
  25798. *
  25799. * @param {Object} data - A JSON object representing the serialized geometry.
  25800. * @return {IcosahedronGeometry} A new instance.
  25801. */
  25802. static fromJSON( data ) {
  25803. return new IcosahedronGeometry( data.radius, data.detail );
  25804. }
  25805. }
  25806. /**
  25807. * A geometry class for representing an octahedron.
  25808. *
  25809. * ```js
  25810. * const geometry = new THREE.OctahedronGeometry();
  25811. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  25812. * const octahedron = new THREE.Mesh( geometry, material );
  25813. * scene.add( octahedron );
  25814. * ```
  25815. *
  25816. * @augments PolyhedronGeometry
  25817. */
  25818. class OctahedronGeometry extends PolyhedronGeometry {
  25819. /**
  25820. * Constructs a new octahedron geometry.
  25821. *
  25822. * @param {number} [radius=1] - Radius of the octahedron.
  25823. * @param {number} [detail=0] - Setting this to a value greater than `0` adds vertices making it no longer a octahedron.
  25824. */
  25825. constructor( radius = 1, detail = 0 ) {
  25826. const vertices = [
  25827. 1, 0, 0, -1, 0, 0, 0, 1, 0,
  25828. 0, -1, 0, 0, 0, 1, 0, 0, -1
  25829. ];
  25830. const indices = [
  25831. 0, 2, 4, 0, 4, 3, 0, 3, 5,
  25832. 0, 5, 2, 1, 2, 5, 1, 5, 3,
  25833. 1, 3, 4, 1, 4, 2
  25834. ];
  25835. super( vertices, indices, radius, detail );
  25836. this.type = 'OctahedronGeometry';
  25837. /**
  25838. * Holds the constructor parameters that have been
  25839. * used to generate the geometry. Any modification
  25840. * after instantiation does not change the geometry.
  25841. *
  25842. * @type {Object}
  25843. */
  25844. this.parameters = {
  25845. radius: radius,
  25846. detail: detail
  25847. };
  25848. }
  25849. /**
  25850. * Factory method for creating an instance of this class from the given
  25851. * JSON object.
  25852. *
  25853. * @param {Object} data - A JSON object representing the serialized geometry.
  25854. * @return {OctahedronGeometry} A new instance.
  25855. */
  25856. static fromJSON( data ) {
  25857. return new OctahedronGeometry( data.radius, data.detail );
  25858. }
  25859. }
  25860. /**
  25861. * A geometry class for representing a plane.
  25862. *
  25863. * ```js
  25864. * const geometry = new THREE.PlaneGeometry( 1, 1 );
  25865. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00, side: THREE.DoubleSide } );
  25866. * const plane = new THREE.Mesh( geometry, material );
  25867. * scene.add( plane );
  25868. * ```
  25869. *
  25870. * @augments BufferGeometry
  25871. */
  25872. class PlaneGeometry extends BufferGeometry {
  25873. /**
  25874. * Constructs a new plane geometry.
  25875. *
  25876. * @param {number} [width=1] - The width along the X axis.
  25877. * @param {number} [height=1] - The height along the Y axis
  25878. * @param {number} [widthSegments=1] - The number of segments along the X axis.
  25879. * @param {number} [heightSegments=1] - The number of segments along the Y axis.
  25880. */
  25881. constructor( width = 1, height = 1, widthSegments = 1, heightSegments = 1 ) {
  25882. super();
  25883. this.type = 'PlaneGeometry';
  25884. /**
  25885. * Holds the constructor parameters that have been
  25886. * used to generate the geometry. Any modification
  25887. * after instantiation does not change the geometry.
  25888. *
  25889. * @type {Object}
  25890. */
  25891. this.parameters = {
  25892. width: width,
  25893. height: height,
  25894. widthSegments: widthSegments,
  25895. heightSegments: heightSegments
  25896. };
  25897. const width_half = width / 2;
  25898. const height_half = height / 2;
  25899. const gridX = Math.floor( widthSegments );
  25900. const gridY = Math.floor( heightSegments );
  25901. const gridX1 = gridX + 1;
  25902. const gridY1 = gridY + 1;
  25903. const segment_width = width / gridX;
  25904. const segment_height = height / gridY;
  25905. //
  25906. const indices = [];
  25907. const vertices = [];
  25908. const normals = [];
  25909. const uvs = [];
  25910. for ( let iy = 0; iy < gridY1; iy ++ ) {
  25911. const y = iy * segment_height - height_half;
  25912. for ( let ix = 0; ix < gridX1; ix ++ ) {
  25913. const x = ix * segment_width - width_half;
  25914. vertices.push( x, - y, 0 );
  25915. normals.push( 0, 0, 1 );
  25916. uvs.push( ix / gridX );
  25917. uvs.push( 1 - ( iy / gridY ) );
  25918. }
  25919. }
  25920. for ( let iy = 0; iy < gridY; iy ++ ) {
  25921. for ( let ix = 0; ix < gridX; ix ++ ) {
  25922. const a = ix + gridX1 * iy;
  25923. const b = ix + gridX1 * ( iy + 1 );
  25924. const c = ( ix + 1 ) + gridX1 * ( iy + 1 );
  25925. const d = ( ix + 1 ) + gridX1 * iy;
  25926. indices.push( a, b, d );
  25927. indices.push( b, c, d );
  25928. }
  25929. }
  25930. this.setIndex( indices );
  25931. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  25932. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  25933. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  25934. }
  25935. copy( source ) {
  25936. super.copy( source );
  25937. this.parameters = Object.assign( {}, source.parameters );
  25938. return this;
  25939. }
  25940. /**
  25941. * Factory method for creating an instance of this class from the given
  25942. * JSON object.
  25943. *
  25944. * @param {Object} data - A JSON object representing the serialized geometry.
  25945. * @return {PlaneGeometry} A new instance.
  25946. */
  25947. static fromJSON( data ) {
  25948. return new PlaneGeometry( data.width, data.height, data.widthSegments, data.heightSegments );
  25949. }
  25950. }
  25951. /**
  25952. * A class for generating a two-dimensional ring geometry.
  25953. *
  25954. * ```js
  25955. * const geometry = new THREE.RingGeometry( 1, 5, 32 );
  25956. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00, side: THREE.DoubleSide } );
  25957. * const mesh = new THREE.Mesh( geometry, material );
  25958. * scene.add( mesh );
  25959. * ```
  25960. *
  25961. * @augments BufferGeometry
  25962. */
  25963. class RingGeometry extends BufferGeometry {
  25964. /**
  25965. * Constructs a new ring geometry.
  25966. *
  25967. * @param {number} [innerRadius=0.5] - The inner radius of the ring.
  25968. * @param {number} [outerRadius=1] - The outer radius of the ring.
  25969. * @param {number} [thetaSegments=32] - Number of segments. A higher number means the ring will be more round. Minimum is `3`.
  25970. * @param {number} [phiSegments=1] - Number of segments per ring segment. Minimum is `1`.
  25971. * @param {number} [thetaStart=0] - Starting angle in radians.
  25972. * @param {number} [thetaLength=Math.PI*2] - Central angle in radians.
  25973. */
  25974. constructor( innerRadius = 0.5, outerRadius = 1, thetaSegments = 32, phiSegments = 1, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  25975. super();
  25976. this.type = 'RingGeometry';
  25977. /**
  25978. * Holds the constructor parameters that have been
  25979. * used to generate the geometry. Any modification
  25980. * after instantiation does not change the geometry.
  25981. *
  25982. * @type {Object}
  25983. */
  25984. this.parameters = {
  25985. innerRadius: innerRadius,
  25986. outerRadius: outerRadius,
  25987. thetaSegments: thetaSegments,
  25988. phiSegments: phiSegments,
  25989. thetaStart: thetaStart,
  25990. thetaLength: thetaLength
  25991. };
  25992. thetaSegments = Math.max( 3, thetaSegments );
  25993. phiSegments = Math.max( 1, phiSegments );
  25994. // buffers
  25995. const indices = [];
  25996. const vertices = [];
  25997. const normals = [];
  25998. const uvs = [];
  25999. // some helper variables
  26000. let radius = innerRadius;
  26001. const radiusStep = ( ( outerRadius - innerRadius ) / phiSegments );
  26002. const vertex = new Vector3();
  26003. const uv = new Vector2();
  26004. // generate vertices, normals and uvs
  26005. for ( let j = 0; j <= phiSegments; j ++ ) {
  26006. for ( let i = 0; i <= thetaSegments; i ++ ) {
  26007. // values are generate from the inside of the ring to the outside
  26008. const segment = thetaStart + i / thetaSegments * thetaLength;
  26009. // vertex
  26010. vertex.x = radius * Math.cos( segment );
  26011. vertex.y = radius * Math.sin( segment );
  26012. vertices.push( vertex.x, vertex.y, vertex.z );
  26013. // normal
  26014. normals.push( 0, 0, 1 );
  26015. // uv
  26016. uv.x = ( vertex.x / outerRadius + 1 ) / 2;
  26017. uv.y = ( vertex.y / outerRadius + 1 ) / 2;
  26018. uvs.push( uv.x, uv.y );
  26019. }
  26020. // increase the radius for next row of vertices
  26021. radius += radiusStep;
  26022. }
  26023. // indices
  26024. for ( let j = 0; j < phiSegments; j ++ ) {
  26025. const thetaSegmentLevel = j * ( thetaSegments + 1 );
  26026. for ( let i = 0; i < thetaSegments; i ++ ) {
  26027. const segment = i + thetaSegmentLevel;
  26028. const a = segment;
  26029. const b = segment + thetaSegments + 1;
  26030. const c = segment + thetaSegments + 2;
  26031. const d = segment + 1;
  26032. // faces
  26033. indices.push( a, b, d );
  26034. indices.push( b, c, d );
  26035. }
  26036. }
  26037. // build geometry
  26038. this.setIndex( indices );
  26039. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  26040. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  26041. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  26042. }
  26043. copy( source ) {
  26044. super.copy( source );
  26045. this.parameters = Object.assign( {}, source.parameters );
  26046. return this;
  26047. }
  26048. /**
  26049. * Factory method for creating an instance of this class from the given
  26050. * JSON object.
  26051. *
  26052. * @param {Object} data - A JSON object representing the serialized geometry.
  26053. * @return {RingGeometry} A new instance.
  26054. */
  26055. static fromJSON( data ) {
  26056. return new RingGeometry( data.innerRadius, data.outerRadius, data.thetaSegments, data.phiSegments, data.thetaStart, data.thetaLength );
  26057. }
  26058. }
  26059. /**
  26060. * Creates an one-sided polygonal geometry from one or more path shapes.
  26061. *
  26062. * ```js
  26063. * const arcShape = new THREE.Shape()
  26064. * .moveTo( 5, 1 )
  26065. * .absarc( 1, 1, 4, 0, Math.PI * 2, false );
  26066. *
  26067. * const geometry = new THREE.ShapeGeometry( arcShape );
  26068. * const material = new THREE.MeshBasicMaterial( { color: 0x00ff00, side: THREE.DoubleSide } );
  26069. * const mesh = new THREE.Mesh( geometry, material ) ;
  26070. * scene.add( mesh );
  26071. * ```
  26072. *
  26073. * @augments BufferGeometry
  26074. */
  26075. class ShapeGeometry extends BufferGeometry {
  26076. /**
  26077. * Constructs a new shape geometry.
  26078. *
  26079. * @param {Shape|Array<Shape>} [shapes] - A shape or an array of shapes.
  26080. * @param {number} [curveSegments=12] - Number of segments per shape.
  26081. */
  26082. constructor( shapes = new Shape( [ new Vector2( 0, 0.5 ), new Vector2( -0.5, -0.5 ), new Vector2( 0.5, -0.5 ) ] ), curveSegments = 12 ) {
  26083. super();
  26084. this.type = 'ShapeGeometry';
  26085. /**
  26086. * Holds the constructor parameters that have been
  26087. * used to generate the geometry. Any modification
  26088. * after instantiation does not change the geometry.
  26089. *
  26090. * @type {Object}
  26091. */
  26092. this.parameters = {
  26093. shapes: shapes,
  26094. curveSegments: curveSegments
  26095. };
  26096. // buffers
  26097. const indices = [];
  26098. const vertices = [];
  26099. const normals = [];
  26100. const uvs = [];
  26101. // helper variables
  26102. let groupStart = 0;
  26103. let groupCount = 0;
  26104. // allow single and array values for "shapes" parameter
  26105. if ( Array.isArray( shapes ) === false ) {
  26106. addShape( shapes );
  26107. } else {
  26108. for ( let i = 0; i < shapes.length; i ++ ) {
  26109. addShape( shapes[ i ] );
  26110. this.addGroup( groupStart, groupCount, i ); // enables MultiMaterial support
  26111. groupStart += groupCount;
  26112. groupCount = 0;
  26113. }
  26114. }
  26115. // build geometry
  26116. this.setIndex( indices );
  26117. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  26118. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  26119. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  26120. // helper functions
  26121. function addShape( shape ) {
  26122. const indexOffset = vertices.length / 3;
  26123. const points = shape.extractPoints( curveSegments );
  26124. let shapeVertices = points.shape;
  26125. const shapeHoles = points.holes;
  26126. // check direction of vertices
  26127. if ( ShapeUtils.isClockWise( shapeVertices ) === false ) {
  26128. shapeVertices = shapeVertices.reverse();
  26129. }
  26130. for ( let i = 0, l = shapeHoles.length; i < l; i ++ ) {
  26131. const shapeHole = shapeHoles[ i ];
  26132. if ( ShapeUtils.isClockWise( shapeHole ) === true ) {
  26133. shapeHoles[ i ] = shapeHole.reverse();
  26134. }
  26135. }
  26136. const faces = ShapeUtils.triangulateShape( shapeVertices, shapeHoles );
  26137. // join vertices of inner and outer paths to a single array
  26138. for ( let i = 0, l = shapeHoles.length; i < l; i ++ ) {
  26139. const shapeHole = shapeHoles[ i ];
  26140. shapeVertices = shapeVertices.concat( shapeHole );
  26141. }
  26142. // vertices, normals, uvs
  26143. for ( let i = 0, l = shapeVertices.length; i < l; i ++ ) {
  26144. const vertex = shapeVertices[ i ];
  26145. vertices.push( vertex.x, vertex.y, 0 );
  26146. normals.push( 0, 0, 1 );
  26147. uvs.push( vertex.x, vertex.y ); // world uvs
  26148. }
  26149. // indices
  26150. for ( let i = 0, l = faces.length; i < l; i ++ ) {
  26151. const face = faces[ i ];
  26152. const a = face[ 0 ] + indexOffset;
  26153. const b = face[ 1 ] + indexOffset;
  26154. const c = face[ 2 ] + indexOffset;
  26155. indices.push( a, b, c );
  26156. groupCount += 3;
  26157. }
  26158. }
  26159. }
  26160. copy( source ) {
  26161. super.copy( source );
  26162. this.parameters = Object.assign( {}, source.parameters );
  26163. return this;
  26164. }
  26165. toJSON() {
  26166. const data = super.toJSON();
  26167. const shapes = this.parameters.shapes;
  26168. return toJSON( shapes, data );
  26169. }
  26170. /**
  26171. * Factory method for creating an instance of this class from the given
  26172. * JSON object.
  26173. *
  26174. * @param {Object} data - A JSON object representing the serialized geometry.
  26175. * @param {Array<Shape>} shapes - An array of shapes.
  26176. * @return {ShapeGeometry} A new instance.
  26177. */
  26178. static fromJSON( data, shapes ) {
  26179. const geometryShapes = [];
  26180. for ( let j = 0, jl = data.shapes.length; j < jl; j ++ ) {
  26181. const shape = shapes[ data.shapes[ j ] ];
  26182. geometryShapes.push( shape );
  26183. }
  26184. return new ShapeGeometry( geometryShapes, data.curveSegments );
  26185. }
  26186. }
  26187. function toJSON( shapes, data ) {
  26188. data.shapes = [];
  26189. if ( Array.isArray( shapes ) ) {
  26190. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  26191. const shape = shapes[ i ];
  26192. data.shapes.push( shape.uuid );
  26193. }
  26194. } else {
  26195. data.shapes.push( shapes.uuid );
  26196. }
  26197. return data;
  26198. }
  26199. /**
  26200. * A class for generating a sphere geometry.
  26201. *
  26202. * ```js
  26203. * const geometry = new THREE.SphereGeometry( 15, 32, 16 );
  26204. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  26205. * const sphere = new THREE.Mesh( geometry, material );
  26206. * scene.add( sphere );
  26207. * ```
  26208. *
  26209. * @augments BufferGeometry
  26210. */
  26211. class SphereGeometry extends BufferGeometry {
  26212. /**
  26213. * Constructs a new sphere geometry.
  26214. *
  26215. * @param {number} [radius=1] - The sphere radius.
  26216. * @param {number} [widthSegments=32] - The number of horizontal segments. Minimum value is `3`.
  26217. * @param {number} [heightSegments=16] - The number of vertical segments. Minimum value is `2`.
  26218. * @param {number} [phiStart=0] - The horizontal starting angle in radians.
  26219. * @param {number} [phiLength=Math.PI*2] - The horizontal sweep angle size.
  26220. * @param {number} [thetaStart=0] - The vertical starting angle in radians.
  26221. * @param {number} [thetaLength=Math.PI] - The vertical sweep angle size.
  26222. */
  26223. constructor( radius = 1, widthSegments = 32, heightSegments = 16, phiStart = 0, phiLength = Math.PI * 2, thetaStart = 0, thetaLength = Math.PI ) {
  26224. super();
  26225. this.type = 'SphereGeometry';
  26226. /**
  26227. * Holds the constructor parameters that have been
  26228. * used to generate the geometry. Any modification
  26229. * after instantiation does not change the geometry.
  26230. *
  26231. * @type {Object}
  26232. */
  26233. this.parameters = {
  26234. radius: radius,
  26235. widthSegments: widthSegments,
  26236. heightSegments: heightSegments,
  26237. phiStart: phiStart,
  26238. phiLength: phiLength,
  26239. thetaStart: thetaStart,
  26240. thetaLength: thetaLength
  26241. };
  26242. widthSegments = Math.max( 3, Math.floor( widthSegments ) );
  26243. heightSegments = Math.max( 2, Math.floor( heightSegments ) );
  26244. const thetaEnd = Math.min( thetaStart + thetaLength, Math.PI );
  26245. let index = 0;
  26246. const grid = [];
  26247. const vertex = new Vector3();
  26248. const normal = new Vector3();
  26249. // buffers
  26250. const indices = [];
  26251. const vertices = [];
  26252. const normals = [];
  26253. const uvs = [];
  26254. // generate vertices, normals and uvs
  26255. for ( let iy = 0; iy <= heightSegments; iy ++ ) {
  26256. const verticesRow = [];
  26257. const v = iy / heightSegments;
  26258. // special case for the poles
  26259. let uOffset = 0;
  26260. if ( iy === 0 && thetaStart === 0 ) {
  26261. uOffset = 0.5 / widthSegments;
  26262. } else if ( iy === heightSegments && thetaEnd === Math.PI ) {
  26263. uOffset = -0.5 / widthSegments;
  26264. }
  26265. for ( let ix = 0; ix <= widthSegments; ix ++ ) {
  26266. const u = ix / widthSegments;
  26267. // vertex
  26268. vertex.x = - radius * Math.cos( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  26269. vertex.y = radius * Math.cos( thetaStart + v * thetaLength );
  26270. vertex.z = radius * Math.sin( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  26271. vertices.push( vertex.x, vertex.y, vertex.z );
  26272. // normal
  26273. normal.copy( vertex ).normalize();
  26274. normals.push( normal.x, normal.y, normal.z );
  26275. // uv
  26276. uvs.push( u + uOffset, 1 - v );
  26277. verticesRow.push( index ++ );
  26278. }
  26279. grid.push( verticesRow );
  26280. }
  26281. // indices
  26282. for ( let iy = 0; iy < heightSegments; iy ++ ) {
  26283. for ( let ix = 0; ix < widthSegments; ix ++ ) {
  26284. const a = grid[ iy ][ ix + 1 ];
  26285. const b = grid[ iy ][ ix ];
  26286. const c = grid[ iy + 1 ][ ix ];
  26287. const d = grid[ iy + 1 ][ ix + 1 ];
  26288. if ( iy !== 0 || thetaStart > 0 ) indices.push( a, b, d );
  26289. if ( iy !== heightSegments - 1 || thetaEnd < Math.PI ) indices.push( b, c, d );
  26290. }
  26291. }
  26292. // build geometry
  26293. this.setIndex( indices );
  26294. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  26295. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  26296. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  26297. }
  26298. copy( source ) {
  26299. super.copy( source );
  26300. this.parameters = Object.assign( {}, source.parameters );
  26301. return this;
  26302. }
  26303. /**
  26304. * Factory method for creating an instance of this class from the given
  26305. * JSON object.
  26306. *
  26307. * @param {Object} data - A JSON object representing the serialized geometry.
  26308. * @return {SphereGeometry} A new instance.
  26309. */
  26310. static fromJSON( data ) {
  26311. return new SphereGeometry( data.radius, data.widthSegments, data.heightSegments, data.phiStart, data.phiLength, data.thetaStart, data.thetaLength );
  26312. }
  26313. }
  26314. /**
  26315. * A geometry class for representing an tetrahedron.
  26316. *
  26317. * ```js
  26318. * const geometry = new THREE.TetrahedronGeometry();
  26319. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  26320. * const tetrahedron = new THREE.Mesh( geometry, material );
  26321. * scene.add( tetrahedron );
  26322. * ```
  26323. *
  26324. * @augments PolyhedronGeometry
  26325. */
  26326. class TetrahedronGeometry extends PolyhedronGeometry {
  26327. /**
  26328. * Constructs a new tetrahedron geometry.
  26329. *
  26330. * @param {number} [radius=1] - Radius of the tetrahedron.
  26331. * @param {number} [detail=0] - Setting this to a value greater than `0` adds vertices making it no longer a tetrahedron.
  26332. */
  26333. constructor( radius = 1, detail = 0 ) {
  26334. const vertices = [
  26335. 1, 1, 1, -1, -1, 1, -1, 1, -1, 1, -1, -1
  26336. ];
  26337. const indices = [
  26338. 2, 1, 0, 0, 3, 2, 1, 3, 0, 2, 3, 1
  26339. ];
  26340. super( vertices, indices, radius, detail );
  26341. this.type = 'TetrahedronGeometry';
  26342. /**
  26343. * Holds the constructor parameters that have been
  26344. * used to generate the geometry. Any modification
  26345. * after instantiation does not change the geometry.
  26346. *
  26347. * @type {Object}
  26348. */
  26349. this.parameters = {
  26350. radius: radius,
  26351. detail: detail
  26352. };
  26353. }
  26354. /**
  26355. * Factory method for creating an instance of this class from the given
  26356. * JSON object.
  26357. *
  26358. * @param {Object} data - A JSON object representing the serialized geometry.
  26359. * @return {TetrahedronGeometry} A new instance.
  26360. */
  26361. static fromJSON( data ) {
  26362. return new TetrahedronGeometry( data.radius, data.detail );
  26363. }
  26364. }
  26365. /**
  26366. * A geometry class for representing an torus.
  26367. *
  26368. * ```js
  26369. * const geometry = new THREE.TorusGeometry( 10, 3, 16, 100 );
  26370. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  26371. * const torus = new THREE.Mesh( geometry, material );
  26372. * scene.add( torus );
  26373. * ```
  26374. *
  26375. * @augments BufferGeometry
  26376. */
  26377. class TorusGeometry extends BufferGeometry {
  26378. /**
  26379. * Constructs a new torus geometry.
  26380. *
  26381. * @param {number} [radius=1] - Radius of the torus, from the center of the torus to the center of the tube.
  26382. * @param {number} [tube=0.4] - Radius of the tube. Must be smaller than `radius`.
  26383. * @param {number} [radialSegments=12] - The number of radial segments.
  26384. * @param {number} [tubularSegments=48] - The number of tubular segments.
  26385. * @param {number} [arc=Math.PI*2] - Central angle in radians.
  26386. */
  26387. constructor( radius = 1, tube = 0.4, radialSegments = 12, tubularSegments = 48, arc = Math.PI * 2 ) {
  26388. super();
  26389. this.type = 'TorusGeometry';
  26390. /**
  26391. * Holds the constructor parameters that have been
  26392. * used to generate the geometry. Any modification
  26393. * after instantiation does not change the geometry.
  26394. *
  26395. * @type {Object}
  26396. */
  26397. this.parameters = {
  26398. radius: radius,
  26399. tube: tube,
  26400. radialSegments: radialSegments,
  26401. tubularSegments: tubularSegments,
  26402. arc: arc
  26403. };
  26404. radialSegments = Math.floor( radialSegments );
  26405. tubularSegments = Math.floor( tubularSegments );
  26406. // buffers
  26407. const indices = [];
  26408. const vertices = [];
  26409. const normals = [];
  26410. const uvs = [];
  26411. // helper variables
  26412. const center = new Vector3();
  26413. const vertex = new Vector3();
  26414. const normal = new Vector3();
  26415. // generate vertices, normals and uvs
  26416. for ( let j = 0; j <= radialSegments; j ++ ) {
  26417. for ( let i = 0; i <= tubularSegments; i ++ ) {
  26418. const u = i / tubularSegments * arc;
  26419. const v = j / radialSegments * Math.PI * 2;
  26420. // vertex
  26421. vertex.x = ( radius + tube * Math.cos( v ) ) * Math.cos( u );
  26422. vertex.y = ( radius + tube * Math.cos( v ) ) * Math.sin( u );
  26423. vertex.z = tube * Math.sin( v );
  26424. vertices.push( vertex.x, vertex.y, vertex.z );
  26425. // normal
  26426. center.x = radius * Math.cos( u );
  26427. center.y = radius * Math.sin( u );
  26428. normal.subVectors( vertex, center ).normalize();
  26429. normals.push( normal.x, normal.y, normal.z );
  26430. // uv
  26431. uvs.push( i / tubularSegments );
  26432. uvs.push( j / radialSegments );
  26433. }
  26434. }
  26435. // generate indices
  26436. for ( let j = 1; j <= radialSegments; j ++ ) {
  26437. for ( let i = 1; i <= tubularSegments; i ++ ) {
  26438. // indices
  26439. const a = ( tubularSegments + 1 ) * j + i - 1;
  26440. const b = ( tubularSegments + 1 ) * ( j - 1 ) + i - 1;
  26441. const c = ( tubularSegments + 1 ) * ( j - 1 ) + i;
  26442. const d = ( tubularSegments + 1 ) * j + i;
  26443. // faces
  26444. indices.push( a, b, d );
  26445. indices.push( b, c, d );
  26446. }
  26447. }
  26448. // build geometry
  26449. this.setIndex( indices );
  26450. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  26451. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  26452. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  26453. }
  26454. copy( source ) {
  26455. super.copy( source );
  26456. this.parameters = Object.assign( {}, source.parameters );
  26457. return this;
  26458. }
  26459. /**
  26460. * Factory method for creating an instance of this class from the given
  26461. * JSON object.
  26462. *
  26463. * @param {Object} data - A JSON object representing the serialized geometry.
  26464. * @return {TorusGeometry} A new instance.
  26465. */
  26466. static fromJSON( data ) {
  26467. return new TorusGeometry( data.radius, data.tube, data.radialSegments, data.tubularSegments, data.arc );
  26468. }
  26469. }
  26470. /**
  26471. * Creates a torus knot, the particular shape of which is defined by a pair
  26472. * of coprime integers, p and q. If p and q are not coprime, the result will
  26473. * be a torus link.
  26474. *
  26475. * ```js
  26476. * const geometry = new THREE.TorusKnotGeometry( 10, 3, 100, 16 );
  26477. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  26478. * const torusKnot = new THREE.Mesh( geometry, material );
  26479. * scene.add( torusKnot );
  26480. * ```
  26481. *
  26482. * @augments BufferGeometry
  26483. */
  26484. class TorusKnotGeometry extends BufferGeometry {
  26485. /**
  26486. * Constructs a new torus knot geometry.
  26487. *
  26488. * @param {number} [radius=1] - Radius of the torus knot.
  26489. * @param {number} [tube=0.4] - Radius of the tube.
  26490. * @param {number} [tubularSegments=64] - The number of tubular segments.
  26491. * @param {number} [radialSegments=8] - The number of radial segments.
  26492. * @param {number} [p=2] - This value determines, how many times the geometry winds around its axis of rotational symmetry.
  26493. * @param {number} [q=3] - This value determines, how many times the geometry winds around a circle in the interior of the torus.
  26494. */
  26495. constructor( radius = 1, tube = 0.4, tubularSegments = 64, radialSegments = 8, p = 2, q = 3 ) {
  26496. super();
  26497. this.type = 'TorusKnotGeometry';
  26498. /**
  26499. * Holds the constructor parameters that have been
  26500. * used to generate the geometry. Any modification
  26501. * after instantiation does not change the geometry.
  26502. *
  26503. * @type {Object}
  26504. */
  26505. this.parameters = {
  26506. radius: radius,
  26507. tube: tube,
  26508. tubularSegments: tubularSegments,
  26509. radialSegments: radialSegments,
  26510. p: p,
  26511. q: q
  26512. };
  26513. tubularSegments = Math.floor( tubularSegments );
  26514. radialSegments = Math.floor( radialSegments );
  26515. // buffers
  26516. const indices = [];
  26517. const vertices = [];
  26518. const normals = [];
  26519. const uvs = [];
  26520. // helper variables
  26521. const vertex = new Vector3();
  26522. const normal = new Vector3();
  26523. const P1 = new Vector3();
  26524. const P2 = new Vector3();
  26525. const B = new Vector3();
  26526. const T = new Vector3();
  26527. const N = new Vector3();
  26528. // generate vertices, normals and uvs
  26529. for ( let i = 0; i <= tubularSegments; ++ i ) {
  26530. // the radian "u" is used to calculate the position on the torus curve of the current tubular segment
  26531. const u = i / tubularSegments * p * Math.PI * 2;
  26532. // now we calculate two points. P1 is our current position on the curve, P2 is a little farther ahead.
  26533. // these points are used to create a special "coordinate space", which is necessary to calculate the correct vertex positions
  26534. calculatePositionOnCurve( u, p, q, radius, P1 );
  26535. calculatePositionOnCurve( u + 0.01, p, q, radius, P2 );
  26536. // calculate orthonormal basis
  26537. T.subVectors( P2, P1 );
  26538. N.addVectors( P2, P1 );
  26539. B.crossVectors( T, N );
  26540. N.crossVectors( B, T );
  26541. // normalize B, N. T can be ignored, we don't use it
  26542. B.normalize();
  26543. N.normalize();
  26544. for ( let j = 0; j <= radialSegments; ++ j ) {
  26545. // now calculate the vertices. they are nothing more than an extrusion of the torus curve.
  26546. // because we extrude a shape in the xy-plane, there is no need to calculate a z-value.
  26547. const v = j / radialSegments * Math.PI * 2;
  26548. const cx = - tube * Math.cos( v );
  26549. const cy = tube * Math.sin( v );
  26550. // now calculate the final vertex position.
  26551. // first we orient the extrusion with our basis vectors, then we add it to the current position on the curve
  26552. vertex.x = P1.x + ( cx * N.x + cy * B.x );
  26553. vertex.y = P1.y + ( cx * N.y + cy * B.y );
  26554. vertex.z = P1.z + ( cx * N.z + cy * B.z );
  26555. vertices.push( vertex.x, vertex.y, vertex.z );
  26556. // normal (P1 is always the center/origin of the extrusion, thus we can use it to calculate the normal)
  26557. normal.subVectors( vertex, P1 ).normalize();
  26558. normals.push( normal.x, normal.y, normal.z );
  26559. // uv
  26560. uvs.push( i / tubularSegments );
  26561. uvs.push( j / radialSegments );
  26562. }
  26563. }
  26564. // generate indices
  26565. for ( let j = 1; j <= tubularSegments; j ++ ) {
  26566. for ( let i = 1; i <= radialSegments; i ++ ) {
  26567. // indices
  26568. const a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 );
  26569. const b = ( radialSegments + 1 ) * j + ( i - 1 );
  26570. const c = ( radialSegments + 1 ) * j + i;
  26571. const d = ( radialSegments + 1 ) * ( j - 1 ) + i;
  26572. // faces
  26573. indices.push( a, b, d );
  26574. indices.push( b, c, d );
  26575. }
  26576. }
  26577. // build geometry
  26578. this.setIndex( indices );
  26579. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  26580. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  26581. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  26582. // this function calculates the current position on the torus curve
  26583. function calculatePositionOnCurve( u, p, q, radius, position ) {
  26584. const cu = Math.cos( u );
  26585. const su = Math.sin( u );
  26586. const quOverP = q / p * u;
  26587. const cs = Math.cos( quOverP );
  26588. position.x = radius * ( 2 + cs ) * 0.5 * cu;
  26589. position.y = radius * ( 2 + cs ) * su * 0.5;
  26590. position.z = radius * Math.sin( quOverP ) * 0.5;
  26591. }
  26592. }
  26593. copy( source ) {
  26594. super.copy( source );
  26595. this.parameters = Object.assign( {}, source.parameters );
  26596. return this;
  26597. }
  26598. /**
  26599. * Factory method for creating an instance of this class from the given
  26600. * JSON object.
  26601. *
  26602. * @param {Object} data - A JSON object representing the serialized geometry.
  26603. * @return {TorusKnotGeometry} A new instance.
  26604. */
  26605. static fromJSON( data ) {
  26606. return new TorusKnotGeometry( data.radius, data.tube, data.tubularSegments, data.radialSegments, data.p, data.q );
  26607. }
  26608. }
  26609. /**
  26610. * Creates a tube that extrudes along a 3D curve.
  26611. *
  26612. * ```js
  26613. * class CustomSinCurve extends THREE.Curve {
  26614. *
  26615. * getPoint( t, optionalTarget = new THREE.Vector3() ) {
  26616. *
  26617. * const tx = t * 3 - 1.5;
  26618. * const ty = Math.sin( 2 * Math.PI * t );
  26619. * const tz = 0;
  26620. *
  26621. * return optionalTarget.set( tx, ty, tz );
  26622. * }
  26623. *
  26624. * }
  26625. *
  26626. * const path = new CustomSinCurve( 10 );
  26627. * const geometry = new THREE.TubeGeometry( path, 20, 2, 8, false );
  26628. * const material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } );
  26629. * const mesh = new THREE.Mesh( geometry, material );
  26630. * scene.add( mesh );
  26631. * ```
  26632. *
  26633. * @augments BufferGeometry
  26634. */
  26635. class TubeGeometry extends BufferGeometry {
  26636. /**
  26637. * Constructs a new tube geometry.
  26638. *
  26639. * @param {Curve} [path=QuadraticBezierCurve3] - A 3D curve defining the path of the tube.
  26640. * @param {number} [tubularSegments=64] - The number of segments that make up the tube.
  26641. * @param {number} [radius=1] -The radius of the tube.
  26642. * @param {number} [radialSegments=8] - The number of segments that make up the cross-section.
  26643. * @param {boolean} [closed=false] - Whether the tube is closed or not.
  26644. */
  26645. 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 ) {
  26646. super();
  26647. this.type = 'TubeGeometry';
  26648. /**
  26649. * Holds the constructor parameters that have been
  26650. * used to generate the geometry. Any modification
  26651. * after instantiation does not change the geometry.
  26652. *
  26653. * @type {Object}
  26654. */
  26655. this.parameters = {
  26656. path: path,
  26657. tubularSegments: tubularSegments,
  26658. radius: radius,
  26659. radialSegments: radialSegments,
  26660. closed: closed
  26661. };
  26662. const frames = path.computeFrenetFrames( tubularSegments, closed );
  26663. // expose internals
  26664. this.tangents = frames.tangents;
  26665. this.normals = frames.normals;
  26666. this.binormals = frames.binormals;
  26667. // helper variables
  26668. const vertex = new Vector3();
  26669. const normal = new Vector3();
  26670. const uv = new Vector2();
  26671. let P = new Vector3();
  26672. // buffer
  26673. const vertices = [];
  26674. const normals = [];
  26675. const uvs = [];
  26676. const indices = [];
  26677. // create buffer data
  26678. generateBufferData();
  26679. // build geometry
  26680. this.setIndex( indices );
  26681. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  26682. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  26683. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  26684. // functions
  26685. function generateBufferData() {
  26686. for ( let i = 0; i < tubularSegments; i ++ ) {
  26687. generateSegment( i );
  26688. }
  26689. // if the geometry is not closed, generate the last row of vertices and normals
  26690. // at the regular position on the given path
  26691. //
  26692. // if the geometry is closed, duplicate the first row of vertices and normals (uvs will differ)
  26693. generateSegment( ( closed === false ) ? tubularSegments : 0 );
  26694. // uvs are generated in a separate function.
  26695. // this makes it easy compute correct values for closed geometries
  26696. generateUVs();
  26697. // finally create faces
  26698. generateIndices();
  26699. }
  26700. function generateSegment( i ) {
  26701. // we use getPointAt to sample evenly distributed points from the given path
  26702. P = path.getPointAt( i / tubularSegments, P );
  26703. // retrieve corresponding normal and binormal
  26704. const N = frames.normals[ i ];
  26705. const B = frames.binormals[ i ];
  26706. // generate normals and vertices for the current segment
  26707. for ( let j = 0; j <= radialSegments; j ++ ) {
  26708. const v = j / radialSegments * Math.PI * 2;
  26709. const sin = Math.sin( v );
  26710. const cos = - Math.cos( v );
  26711. // normal
  26712. normal.x = ( cos * N.x + sin * B.x );
  26713. normal.y = ( cos * N.y + sin * B.y );
  26714. normal.z = ( cos * N.z + sin * B.z );
  26715. normal.normalize();
  26716. normals.push( normal.x, normal.y, normal.z );
  26717. // vertex
  26718. vertex.x = P.x + radius * normal.x;
  26719. vertex.y = P.y + radius * normal.y;
  26720. vertex.z = P.z + radius * normal.z;
  26721. vertices.push( vertex.x, vertex.y, vertex.z );
  26722. }
  26723. }
  26724. function generateIndices() {
  26725. for ( let j = 1; j <= tubularSegments; j ++ ) {
  26726. for ( let i = 1; i <= radialSegments; i ++ ) {
  26727. const a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 );
  26728. const b = ( radialSegments + 1 ) * j + ( i - 1 );
  26729. const c = ( radialSegments + 1 ) * j + i;
  26730. const d = ( radialSegments + 1 ) * ( j - 1 ) + i;
  26731. // faces
  26732. indices.push( a, b, d );
  26733. indices.push( b, c, d );
  26734. }
  26735. }
  26736. }
  26737. function generateUVs() {
  26738. for ( let i = 0; i <= tubularSegments; i ++ ) {
  26739. for ( let j = 0; j <= radialSegments; j ++ ) {
  26740. uv.x = i / tubularSegments;
  26741. uv.y = j / radialSegments;
  26742. uvs.push( uv.x, uv.y );
  26743. }
  26744. }
  26745. }
  26746. }
  26747. copy( source ) {
  26748. super.copy( source );
  26749. this.parameters = Object.assign( {}, source.parameters );
  26750. return this;
  26751. }
  26752. toJSON() {
  26753. const data = super.toJSON();
  26754. data.path = this.parameters.path.toJSON();
  26755. return data;
  26756. }
  26757. /**
  26758. * Factory method for creating an instance of this class from the given
  26759. * JSON object.
  26760. *
  26761. * @param {Object} data - A JSON object representing the serialized geometry.
  26762. * @return {TubeGeometry} A new instance.
  26763. */
  26764. static fromJSON( data ) {
  26765. // This only works for built-in curves (e.g. CatmullRomCurve3).
  26766. // User defined curves or instances of CurvePath will not be deserialized.
  26767. return new TubeGeometry(
  26768. new Curves[ data.path.type ]().fromJSON( data.path ),
  26769. data.tubularSegments,
  26770. data.radius,
  26771. data.radialSegments,
  26772. data.closed
  26773. );
  26774. }
  26775. }
  26776. /**
  26777. * Can be used as a helper object to visualize a geometry as a wireframe.
  26778. *
  26779. * ```js
  26780. * const geometry = new THREE.SphereGeometry();
  26781. *
  26782. * const wireframe = new THREE.WireframeGeometry( geometry );
  26783. *
  26784. * const line = new THREE.LineSegments( wireframe );
  26785. * line.material.depthWrite = false;
  26786. * line.material.opacity = 0.25;
  26787. * line.material.transparent = true;
  26788. *
  26789. * scene.add( line );
  26790. * ```
  26791. *
  26792. * Note: It is not yet possible to serialize/deserialize instances of this class.
  26793. *
  26794. * @augments BufferGeometry
  26795. */
  26796. class WireframeGeometry extends BufferGeometry {
  26797. /**
  26798. * Constructs a new wireframe geometry.
  26799. *
  26800. * @param {?BufferGeometry} [geometry=null] - The geometry.
  26801. */
  26802. constructor( geometry = null ) {
  26803. super();
  26804. this.type = 'WireframeGeometry';
  26805. /**
  26806. * Holds the constructor parameters that have been
  26807. * used to generate the geometry. Any modification
  26808. * after instantiation does not change the geometry.
  26809. *
  26810. * @type {Object}
  26811. */
  26812. this.parameters = {
  26813. geometry: geometry
  26814. };
  26815. if ( geometry !== null ) {
  26816. // buffer
  26817. const vertices = [];
  26818. const edges = new Set();
  26819. // helper variables
  26820. const start = new Vector3();
  26821. const end = new Vector3();
  26822. if ( geometry.index !== null ) {
  26823. // indexed BufferGeometry
  26824. const position = geometry.attributes.position;
  26825. const indices = geometry.index;
  26826. let groups = geometry.groups;
  26827. if ( groups.length === 0 ) {
  26828. groups = [ { start: 0, count: indices.count, materialIndex: 0 } ];
  26829. }
  26830. // create a data structure that contains all edges without duplicates
  26831. for ( let o = 0, ol = groups.length; o < ol; ++ o ) {
  26832. const group = groups[ o ];
  26833. const groupStart = group.start;
  26834. const groupCount = group.count;
  26835. for ( let i = groupStart, l = ( groupStart + groupCount ); i < l; i += 3 ) {
  26836. for ( let j = 0; j < 3; j ++ ) {
  26837. const index1 = indices.getX( i + j );
  26838. const index2 = indices.getX( i + ( j + 1 ) % 3 );
  26839. start.fromBufferAttribute( position, index1 );
  26840. end.fromBufferAttribute( position, index2 );
  26841. if ( isUniqueEdge( start, end, edges ) === true ) {
  26842. vertices.push( start.x, start.y, start.z );
  26843. vertices.push( end.x, end.y, end.z );
  26844. }
  26845. }
  26846. }
  26847. }
  26848. } else {
  26849. // non-indexed BufferGeometry
  26850. const position = geometry.attributes.position;
  26851. for ( let i = 0, l = ( position.count / 3 ); i < l; i ++ ) {
  26852. for ( let j = 0; j < 3; j ++ ) {
  26853. // three edges per triangle, an edge is represented as (index1, index2)
  26854. // e.g. the first triangle has the following edges: (0,1),(1,2),(2,0)
  26855. const index1 = 3 * i + j;
  26856. const index2 = 3 * i + ( ( j + 1 ) % 3 );
  26857. start.fromBufferAttribute( position, index1 );
  26858. end.fromBufferAttribute( position, index2 );
  26859. if ( isUniqueEdge( start, end, edges ) === true ) {
  26860. vertices.push( start.x, start.y, start.z );
  26861. vertices.push( end.x, end.y, end.z );
  26862. }
  26863. }
  26864. }
  26865. }
  26866. // build geometry
  26867. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  26868. }
  26869. }
  26870. copy( source ) {
  26871. super.copy( source );
  26872. this.parameters = Object.assign( {}, source.parameters );
  26873. return this;
  26874. }
  26875. }
  26876. function isUniqueEdge( start, end, edges ) {
  26877. const hash1 = `${start.x},${start.y},${start.z}-${end.x},${end.y},${end.z}`;
  26878. const hash2 = `${end.x},${end.y},${end.z}-${start.x},${start.y},${start.z}`; // coincident edge
  26879. if ( edges.has( hash1 ) === true || edges.has( hash2 ) === true ) {
  26880. return false;
  26881. } else {
  26882. edges.add( hash1 );
  26883. edges.add( hash2 );
  26884. return true;
  26885. }
  26886. }
  26887. var Geometries = /*#__PURE__*/Object.freeze({
  26888. __proto__: null,
  26889. BoxGeometry: BoxGeometry,
  26890. CapsuleGeometry: CapsuleGeometry,
  26891. CircleGeometry: CircleGeometry,
  26892. ConeGeometry: ConeGeometry,
  26893. CylinderGeometry: CylinderGeometry,
  26894. DodecahedronGeometry: DodecahedronGeometry,
  26895. EdgesGeometry: EdgesGeometry,
  26896. ExtrudeGeometry: ExtrudeGeometry,
  26897. IcosahedronGeometry: IcosahedronGeometry,
  26898. LatheGeometry: LatheGeometry,
  26899. OctahedronGeometry: OctahedronGeometry,
  26900. PlaneGeometry: PlaneGeometry,
  26901. PolyhedronGeometry: PolyhedronGeometry,
  26902. RingGeometry: RingGeometry,
  26903. ShapeGeometry: ShapeGeometry,
  26904. SphereGeometry: SphereGeometry,
  26905. TetrahedronGeometry: TetrahedronGeometry,
  26906. TorusGeometry: TorusGeometry,
  26907. TorusKnotGeometry: TorusKnotGeometry,
  26908. TubeGeometry: TubeGeometry,
  26909. WireframeGeometry: WireframeGeometry
  26910. });
  26911. /**
  26912. * This material can receive shadows, but otherwise is completely transparent.
  26913. *
  26914. * ```js
  26915. * const geometry = new THREE.PlaneGeometry( 2000, 2000 );
  26916. * geometry.rotateX( - Math.PI / 2 );
  26917. *
  26918. * const material = new THREE.ShadowMaterial();
  26919. * material.opacity = 0.2;
  26920. *
  26921. * const plane = new THREE.Mesh( geometry, material );
  26922. * plane.position.y = -200;
  26923. * plane.receiveShadow = true;
  26924. * scene.add( plane );
  26925. * ```
  26926. *
  26927. * @augments Material
  26928. */
  26929. class ShadowMaterial extends Material {
  26930. /**
  26931. * Constructs a new shadow material.
  26932. *
  26933. * @param {Object} [parameters] - An object with one or more properties
  26934. * defining the material's appearance. Any property of the material
  26935. * (including any property from inherited materials) can be passed
  26936. * in here. Color values can be passed any type of value accepted
  26937. * by {@link Color#set}.
  26938. */
  26939. constructor( parameters ) {
  26940. super();
  26941. /**
  26942. * This flag can be used for type testing.
  26943. *
  26944. * @type {boolean}
  26945. * @readonly
  26946. * @default true
  26947. */
  26948. this.isShadowMaterial = true;
  26949. this.type = 'ShadowMaterial';
  26950. /**
  26951. * Color of the material.
  26952. *
  26953. * @type {Color}
  26954. * @default (0,0,0)
  26955. */
  26956. this.color = new Color( 0x000000 );
  26957. /**
  26958. * Overwritten since shadow materials are transparent
  26959. * by default.
  26960. *
  26961. * @type {boolean}
  26962. * @default true
  26963. */
  26964. this.transparent = true;
  26965. /**
  26966. * Whether the material is affected by fog or not.
  26967. *
  26968. * @type {boolean}
  26969. * @default true
  26970. */
  26971. this.fog = true;
  26972. this.setValues( parameters );
  26973. }
  26974. copy( source ) {
  26975. super.copy( source );
  26976. this.color.copy( source.color );
  26977. this.fog = source.fog;
  26978. return this;
  26979. }
  26980. }
  26981. /**
  26982. * This class works just like {@link ShaderMaterial}, except that definitions
  26983. * of built-in uniforms and attributes are not automatically prepended to the
  26984. * GLSL shader code.
  26985. *
  26986. * `RawShaderMaterial` can only be used with {@link WebGLRenderer}.
  26987. *
  26988. * @augments ShaderMaterial
  26989. */
  26990. class RawShaderMaterial extends ShaderMaterial {
  26991. /**
  26992. * Constructs a new raw shader material.
  26993. *
  26994. * @param {Object} [parameters] - An object with one or more properties
  26995. * defining the material's appearance. Any property of the material
  26996. * (including any property from inherited materials) can be passed
  26997. * in here. Color values can be passed any type of value accepted
  26998. * by {@link Color#set}.
  26999. */
  27000. constructor( parameters ) {
  27001. super( parameters );
  27002. /**
  27003. * This flag can be used for type testing.
  27004. *
  27005. * @type {boolean}
  27006. * @readonly
  27007. * @default true
  27008. */
  27009. this.isRawShaderMaterial = true;
  27010. this.type = 'RawShaderMaterial';
  27011. }
  27012. }
  27013. /**
  27014. * A standard physically based material, using Metallic-Roughness workflow.
  27015. *
  27016. * Physically based rendering (PBR) has recently become the standard in many
  27017. * 3D applications, such as [Unity]{@link https://blogs.unity3d.com/2014/10/29/physically-based-shading-in-unity-5-a-primer/},
  27018. * [Unreal]{@link https://docs.unrealengine.com/latest/INT/Engine/Rendering/Materials/PhysicallyBased/} and
  27019. * [3D Studio Max]{@link http://area.autodesk.com/blogs/the-3ds-max-blog/what039s-new-for-rendering-in-3ds-max-2017}.
  27020. *
  27021. * This approach differs from older approaches in that instead of using
  27022. * approximations for the way in which light interacts with a surface, a
  27023. * physically correct model is used. The idea is that, instead of tweaking
  27024. * materials to look good under specific lighting, a material can be created
  27025. * that will react 'correctly' under all lighting scenarios.
  27026. *
  27027. * In practice this gives a more accurate and realistic looking result than
  27028. * the {@link MeshLambertMaterial} or {@link MeshPhongMaterial}, at the cost of
  27029. * being somewhat more computationally expensive. `MeshStandardMaterial` uses per-fragment
  27030. * shading.
  27031. *
  27032. * Note that for best results you should always specify an environment map when using this material.
  27033. *
  27034. * For a non-technical introduction to the concept of PBR and how to set up a
  27035. * PBR material, check out these articles by the people at [marmoset]{@link https://www.marmoset.co}:
  27036. *
  27037. * - [Basic Theory of Physically Based Rendering]{@link https://www.marmoset.co/posts/basic-theory-of-physically-based-rendering/}
  27038. * - [Physically Based Rendering and You Can Too]{@link https://www.marmoset.co/posts/physically-based-rendering-and-you-can-too/}
  27039. *
  27040. * Technical details of the approach used in three.js (and most other PBR systems) can be found is this
  27041. * [paper from Disney]{@link https://media.disneyanimation.com/uploads/production/publication_asset/48/asset/s2012_pbs_disney_brdf_notes_v3.pdf}
  27042. * (pdf), by Brent Burley.
  27043. *
  27044. * @augments Material
  27045. */
  27046. class MeshStandardMaterial extends Material {
  27047. /**
  27048. * Constructs a new mesh standard material.
  27049. *
  27050. * @param {Object} [parameters] - An object with one or more properties
  27051. * defining the material's appearance. Any property of the material
  27052. * (including any property from inherited materials) can be passed
  27053. * in here. Color values can be passed any type of value accepted
  27054. * by {@link Color#set}.
  27055. */
  27056. constructor( parameters ) {
  27057. super();
  27058. /**
  27059. * This flag can be used for type testing.
  27060. *
  27061. * @type {boolean}
  27062. * @readonly
  27063. * @default true
  27064. */
  27065. this.isMeshStandardMaterial = true;
  27066. this.type = 'MeshStandardMaterial';
  27067. this.defines = { 'STANDARD': '' };
  27068. /**
  27069. * Color of the material.
  27070. *
  27071. * @type {Color}
  27072. * @default (1,1,1)
  27073. */
  27074. this.color = new Color( 0xffffff ); // diffuse
  27075. /**
  27076. * How rough the material appears. `0.0` means a smooth mirror reflection, `1.0`
  27077. * means fully diffuse. If `roughnessMap` is also provided,
  27078. * both values are multiplied.
  27079. *
  27080. * @type {number}
  27081. * @default 1
  27082. */
  27083. this.roughness = 1.0;
  27084. /**
  27085. * How much the material is like a metal. Non-metallic materials such as wood
  27086. * or stone use `0.0`, metallic use `1.0`, with nothing (usually) in between.
  27087. * A value between `0.0` and `1.0` could be used for a rusty metal look.
  27088. * If `metalnessMap` is also provided, both values are multiplied.
  27089. *
  27090. * @type {number}
  27091. * @default 0
  27092. */
  27093. this.metalness = 0.0;
  27094. /**
  27095. * The color map. May optionally include an alpha channel, typically combined
  27096. * with {@link Material#transparent} or {@link Material#alphaTest}. The texture map
  27097. * color is modulated by the diffuse `color`.
  27098. *
  27099. * @type {?Texture}
  27100. * @default null
  27101. */
  27102. this.map = null;
  27103. /**
  27104. * The light map. Requires a second set of UVs.
  27105. *
  27106. * @type {?Texture}
  27107. * @default null
  27108. */
  27109. this.lightMap = null;
  27110. /**
  27111. * Intensity of the baked light.
  27112. *
  27113. * @type {number}
  27114. * @default 1
  27115. */
  27116. this.lightMapIntensity = 1.0;
  27117. /**
  27118. * The red channel of this texture is used as the ambient occlusion map.
  27119. * Requires a second set of UVs.
  27120. *
  27121. * @type {?Texture}
  27122. * @default null
  27123. */
  27124. this.aoMap = null;
  27125. /**
  27126. * Intensity of the ambient occlusion effect. Range is `[0,1]`, where `0`
  27127. * disables ambient occlusion. Where intensity is `1` and the AO map's
  27128. * red channel is also `1`, ambient light is fully occluded on a surface.
  27129. *
  27130. * @type {number}
  27131. * @default 1
  27132. */
  27133. this.aoMapIntensity = 1.0;
  27134. /**
  27135. * Emissive (light) color of the material, essentially a solid color
  27136. * unaffected by other lighting.
  27137. *
  27138. * @type {Color}
  27139. * @default (0,0,0)
  27140. */
  27141. this.emissive = new Color( 0x000000 );
  27142. /**
  27143. * Intensity of the emissive light. Modulates the emissive color.
  27144. *
  27145. * @type {number}
  27146. * @default 1
  27147. */
  27148. this.emissiveIntensity = 1.0;
  27149. /**
  27150. * Set emissive (glow) map. The emissive map color is modulated by the
  27151. * emissive color and the emissive intensity. If you have an emissive map,
  27152. * be sure to set the emissive color to something other than black.
  27153. *
  27154. * @type {?Texture}
  27155. * @default null
  27156. */
  27157. this.emissiveMap = null;
  27158. /**
  27159. * The texture to create a bump map. The black and white values map to the
  27160. * perceived depth in relation to the lights. Bump doesn't actually affect
  27161. * the geometry of the object, only the lighting. If a normal map is defined
  27162. * this will be ignored.
  27163. *
  27164. * @type {?Texture}
  27165. * @default null
  27166. */
  27167. this.bumpMap = null;
  27168. /**
  27169. * How much the bump map affects the material. Typical range is `[0,1]`.
  27170. *
  27171. * @type {number}
  27172. * @default 1
  27173. */
  27174. this.bumpScale = 1;
  27175. /**
  27176. * The texture to create a normal map. The RGB values affect the surface
  27177. * normal for each pixel fragment and change the way the color is lit. Normal
  27178. * maps do not change the actual shape of the surface, only the lighting. In
  27179. * case the material has a normal map authored using the left handed
  27180. * convention, the `y` component of `normalScale` should be negated to compensate
  27181. * for the different handedness.
  27182. *
  27183. * @type {?Texture}
  27184. * @default null
  27185. */
  27186. this.normalMap = null;
  27187. /**
  27188. * The type of normal map.
  27189. *
  27190. * @type {(TangentSpaceNormalMap|ObjectSpaceNormalMap)}
  27191. * @default TangentSpaceNormalMap
  27192. */
  27193. this.normalMapType = TangentSpaceNormalMap;
  27194. /**
  27195. * How much the normal map affects the material. Typical value range is `[0,1]`.
  27196. *
  27197. * @type {Vector2}
  27198. * @default (1,1)
  27199. */
  27200. this.normalScale = new Vector2( 1, 1 );
  27201. /**
  27202. * The displacement map affects the position of the mesh's vertices. Unlike
  27203. * other maps which only affect the light and shade of the material the
  27204. * displaced vertices can cast shadows, block other objects, and otherwise
  27205. * act as real geometry. The displacement texture is an image where the value
  27206. * of each pixel (white being the highest) is mapped against, and
  27207. * repositions, the vertices of the mesh.
  27208. *
  27209. * @type {?Texture}
  27210. * @default null
  27211. */
  27212. this.displacementMap = null;
  27213. /**
  27214. * How much the displacement map affects the mesh (where black is no
  27215. * displacement, and white is maximum displacement). Without a displacement
  27216. * map set, this value is not applied.
  27217. *
  27218. * @type {number}
  27219. * @default 0
  27220. */
  27221. this.displacementScale = 1;
  27222. /**
  27223. * The offset of the displacement map's values on the mesh's vertices.
  27224. * The bias is added to the scaled sample of the displacement map.
  27225. * Without a displacement map set, this value is not applied.
  27226. *
  27227. * @type {number}
  27228. * @default 0
  27229. */
  27230. this.displacementBias = 0;
  27231. /**
  27232. * The green channel of this texture is used to alter the roughness of the
  27233. * material.
  27234. *
  27235. * @type {?Texture}
  27236. * @default null
  27237. */
  27238. this.roughnessMap = null;
  27239. /**
  27240. * The blue channel of this texture is used to alter the metalness of the
  27241. * material.
  27242. *
  27243. * @type {?Texture}
  27244. * @default null
  27245. */
  27246. this.metalnessMap = null;
  27247. /**
  27248. * The alpha map is a grayscale texture that controls the opacity across the
  27249. * surface (black: fully transparent; white: fully opaque).
  27250. *
  27251. * Only the color of the texture is used, ignoring the alpha channel if one
  27252. * exists. For RGB and RGBA textures, the renderer will use the green channel
  27253. * when sampling this texture due to the extra bit of precision provided for
  27254. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  27255. * luminance/alpha textures will also still work as expected.
  27256. *
  27257. * @type {?Texture}
  27258. * @default null
  27259. */
  27260. this.alphaMap = null;
  27261. /**
  27262. * The environment map. To ensure a physically correct rendering, environment maps
  27263. * are internally pre-processed with {@link PMREMGenerator}.
  27264. *
  27265. * @type {?Texture}
  27266. * @default null
  27267. */
  27268. this.envMap = null;
  27269. /**
  27270. * The rotation of the environment map in radians.
  27271. *
  27272. * @type {Euler}
  27273. * @default (0,0,0)
  27274. */
  27275. this.envMapRotation = new Euler();
  27276. /**
  27277. * Scales the effect of the environment map by multiplying its color.
  27278. *
  27279. * @type {number}
  27280. * @default 1
  27281. */
  27282. this.envMapIntensity = 1.0;
  27283. /**
  27284. * Renders the geometry as a wireframe.
  27285. *
  27286. * @type {boolean}
  27287. * @default false
  27288. */
  27289. this.wireframe = false;
  27290. /**
  27291. * Controls the thickness of the wireframe.
  27292. *
  27293. * Can only be used with {@link SVGRenderer}.
  27294. *
  27295. * @type {number}
  27296. * @default 1
  27297. */
  27298. this.wireframeLinewidth = 1;
  27299. /**
  27300. * Defines appearance of wireframe ends.
  27301. *
  27302. * Can only be used with {@link SVGRenderer}.
  27303. *
  27304. * @type {('round'|'bevel'|'miter')}
  27305. * @default 'round'
  27306. */
  27307. this.wireframeLinecap = 'round';
  27308. /**
  27309. * Defines appearance of wireframe joints.
  27310. *
  27311. * Can only be used with {@link SVGRenderer}.
  27312. *
  27313. * @type {('round'|'bevel'|'miter')}
  27314. * @default 'round'
  27315. */
  27316. this.wireframeLinejoin = 'round';
  27317. /**
  27318. * Whether the material is rendered with flat shading or not.
  27319. *
  27320. * @type {boolean}
  27321. * @default false
  27322. */
  27323. this.flatShading = false;
  27324. /**
  27325. * Whether the material is affected by fog or not.
  27326. *
  27327. * @type {boolean}
  27328. * @default true
  27329. */
  27330. this.fog = true;
  27331. this.setValues( parameters );
  27332. }
  27333. copy( source ) {
  27334. super.copy( source );
  27335. this.defines = { 'STANDARD': '' };
  27336. this.color.copy( source.color );
  27337. this.roughness = source.roughness;
  27338. this.metalness = source.metalness;
  27339. this.map = source.map;
  27340. this.lightMap = source.lightMap;
  27341. this.lightMapIntensity = source.lightMapIntensity;
  27342. this.aoMap = source.aoMap;
  27343. this.aoMapIntensity = source.aoMapIntensity;
  27344. this.emissive.copy( source.emissive );
  27345. this.emissiveMap = source.emissiveMap;
  27346. this.emissiveIntensity = source.emissiveIntensity;
  27347. this.bumpMap = source.bumpMap;
  27348. this.bumpScale = source.bumpScale;
  27349. this.normalMap = source.normalMap;
  27350. this.normalMapType = source.normalMapType;
  27351. this.normalScale.copy( source.normalScale );
  27352. this.displacementMap = source.displacementMap;
  27353. this.displacementScale = source.displacementScale;
  27354. this.displacementBias = source.displacementBias;
  27355. this.roughnessMap = source.roughnessMap;
  27356. this.metalnessMap = source.metalnessMap;
  27357. this.alphaMap = source.alphaMap;
  27358. this.envMap = source.envMap;
  27359. this.envMapRotation.copy( source.envMapRotation );
  27360. this.envMapIntensity = source.envMapIntensity;
  27361. this.wireframe = source.wireframe;
  27362. this.wireframeLinewidth = source.wireframeLinewidth;
  27363. this.wireframeLinecap = source.wireframeLinecap;
  27364. this.wireframeLinejoin = source.wireframeLinejoin;
  27365. this.flatShading = source.flatShading;
  27366. this.fog = source.fog;
  27367. return this;
  27368. }
  27369. }
  27370. /**
  27371. * An extension of the {@link MeshStandardMaterial}, providing more advanced
  27372. * physically-based rendering properties:
  27373. *
  27374. * - Anisotropy: Ability to represent the anisotropic property of materials
  27375. * as observable with brushed metals.
  27376. * - Clearcoat: Some materials — like car paints, carbon fiber, and wet surfaces — require
  27377. * a clear, reflective layer on top of another layer that may be irregular or rough.
  27378. * Clearcoat approximates this effect, without the need for a separate transparent surface.
  27379. * - Iridescence: Allows to render the effect where hue varies depending on the viewing
  27380. * angle and illumination angle. This can be seen on soap bubbles, oil films, or on the
  27381. * wings of many insects.
  27382. * - Physically-based transparency: One limitation of {@link Material#opacity} is that highly
  27383. * transparent materials are less reflective. Physically-based transmission provides a more
  27384. * realistic option for thin, transparent surfaces like glass.
  27385. * - Advanced reflectivity: More flexible reflectivity for non-metallic materials.
  27386. * - Sheen: Can be used for representing cloth and fabric materials.
  27387. *
  27388. * As a result of these complex shading features, `MeshPhysicalMaterial` has a
  27389. * higher performance cost, per pixel, than other three.js materials. Most
  27390. * effects are disabled by default, and add cost as they are enabled. For
  27391. * best results, always specify an environment map when using this material.
  27392. *
  27393. * @augments MeshStandardMaterial
  27394. */
  27395. class MeshPhysicalMaterial extends MeshStandardMaterial {
  27396. /**
  27397. * Constructs a new mesh physical material.
  27398. *
  27399. * @param {Object} [parameters] - An object with one or more properties
  27400. * defining the material's appearance. Any property of the material
  27401. * (including any property from inherited materials) can be passed
  27402. * in here. Color values can be passed any type of value accepted
  27403. * by {@link Color#set}.
  27404. */
  27405. constructor( parameters ) {
  27406. super();
  27407. /**
  27408. * This flag can be used for type testing.
  27409. *
  27410. * @type {boolean}
  27411. * @readonly
  27412. * @default true
  27413. */
  27414. this.isMeshPhysicalMaterial = true;
  27415. this.defines = {
  27416. 'STANDARD': '',
  27417. 'PHYSICAL': ''
  27418. };
  27419. this.type = 'MeshPhysicalMaterial';
  27420. /**
  27421. * The rotation of the anisotropy in tangent, bitangent space, measured in radians
  27422. * counter-clockwise from the tangent. When `anisotropyMap` is present, this
  27423. * property provides additional rotation to the vectors in the texture.
  27424. *
  27425. * @type {number}
  27426. * @default 1
  27427. */
  27428. this.anisotropyRotation = 0;
  27429. /**
  27430. * Red and green channels represent the anisotropy direction in `[-1, 1]` tangent,
  27431. * bitangent space, to be rotated by `anisotropyRotation`. The blue channel
  27432. * contains strength as `[0, 1]` to be multiplied by `anisotropy`.
  27433. *
  27434. * @type {?Texture}
  27435. * @default null
  27436. */
  27437. this.anisotropyMap = null;
  27438. /**
  27439. * The red channel of this texture is multiplied against `clearcoat`,
  27440. * for per-pixel control over a coating's intensity.
  27441. *
  27442. * @type {?Texture}
  27443. * @default null
  27444. */
  27445. this.clearcoatMap = null;
  27446. /**
  27447. * Roughness of the clear coat layer, from `0.0` to `1.0`.
  27448. *
  27449. * @type {number}
  27450. * @default 0
  27451. */
  27452. this.clearcoatRoughness = 0.0;
  27453. /**
  27454. * The green channel of this texture is multiplied against
  27455. * `clearcoatRoughness`, for per-pixel control over a coating's roughness.
  27456. *
  27457. * @type {?Texture}
  27458. * @default null
  27459. */
  27460. this.clearcoatRoughnessMap = null;
  27461. /**
  27462. * How much `clearcoatNormalMap` affects the clear coat layer, from
  27463. * `(0,0)` to `(1,1)`.
  27464. *
  27465. * @type {Vector2}
  27466. * @default (1,1)
  27467. */
  27468. this.clearcoatNormalScale = new Vector2( 1, 1 );
  27469. /**
  27470. * Can be used to enable independent normals for the clear coat layer.
  27471. *
  27472. * @type {?Texture}
  27473. * @default null
  27474. */
  27475. this.clearcoatNormalMap = null;
  27476. /**
  27477. * Index-of-refraction for non-metallic materials, from `1.0` to `2.333`.
  27478. *
  27479. * @type {number}
  27480. * @default 1.5
  27481. */
  27482. this.ior = 1.5;
  27483. /**
  27484. * Degree of reflectivity, from `0.0` to `1.0`. Default is `0.5`, which
  27485. * corresponds to an index-of-refraction of `1.5`.
  27486. *
  27487. * This models the reflectivity of non-metallic materials. It has no effect
  27488. * when `metalness` is `1.0`
  27489. *
  27490. * @name MeshPhysicalMaterial#reflectivity
  27491. * @type {number}
  27492. * @default 0.5
  27493. */
  27494. Object.defineProperty( this, 'reflectivity', {
  27495. get: function () {
  27496. return ( clamp( 2.5 * ( this.ior - 1 ) / ( this.ior + 1 ), 0, 1 ) );
  27497. },
  27498. set: function ( reflectivity ) {
  27499. this.ior = ( 1 + 0.4 * reflectivity ) / ( 1 - 0.4 * reflectivity );
  27500. }
  27501. } );
  27502. /**
  27503. * The red channel of this texture is multiplied against `iridescence`, for per-pixel
  27504. * control over iridescence.
  27505. *
  27506. * @type {?Texture}
  27507. * @default null
  27508. */
  27509. this.iridescenceMap = null;
  27510. /**
  27511. * Strength of the iridescence RGB color shift effect, represented by an index-of-refraction.
  27512. * Between `1.0` to `2.333`.
  27513. *
  27514. * @type {number}
  27515. * @default 1.3
  27516. */
  27517. this.iridescenceIOR = 1.3;
  27518. /**
  27519. *Array of exactly 2 elements, specifying minimum and maximum thickness of the iridescence layer.
  27520. Thickness of iridescence layer has an equivalent effect of the one `thickness` has on `ior`.
  27521. *
  27522. * @type {Array<number,number>}
  27523. * @default [100,400]
  27524. */
  27525. this.iridescenceThicknessRange = [ 100, 400 ];
  27526. /**
  27527. * A texture that defines the thickness of the iridescence layer, stored in the green channel.
  27528. * Minimum and maximum values of thickness are defined by `iridescenceThicknessRange` array:
  27529. * - `0.0` in the green channel will result in thickness equal to first element of the array.
  27530. * - `1.0` in the green channel will result in thickness equal to second element of the array.
  27531. * - Values in-between will linearly interpolate between the elements of the array.
  27532. *
  27533. * @type {?Texture}
  27534. * @default null
  27535. */
  27536. this.iridescenceThicknessMap = null;
  27537. /**
  27538. * The sheen tint.
  27539. *
  27540. * @type {Color}
  27541. * @default (0,0,0)
  27542. */
  27543. this.sheenColor = new Color( 0x000000 );
  27544. /**
  27545. * The RGB channels of this texture are multiplied against `sheenColor`, for per-pixel control
  27546. * over sheen tint.
  27547. *
  27548. * @type {?Texture}
  27549. * @default null
  27550. */
  27551. this.sheenColorMap = null;
  27552. /**
  27553. * Roughness of the sheen layer, from `0.0` to `1.0`.
  27554. *
  27555. * @type {number}
  27556. * @default 1
  27557. */
  27558. this.sheenRoughness = 1.0;
  27559. /**
  27560. * The alpha channel of this texture is multiplied against `sheenRoughness`, for per-pixel control
  27561. * over sheen roughness.
  27562. *
  27563. * @type {?Texture}
  27564. * @default null
  27565. */
  27566. this.sheenRoughnessMap = null;
  27567. /**
  27568. * The red channel of this texture is multiplied against `transmission`, for per-pixel control over
  27569. * optical transparency.
  27570. *
  27571. * @type {?Texture}
  27572. * @default null
  27573. */
  27574. this.transmissionMap = null;
  27575. /**
  27576. * The thickness of the volume beneath the surface. The value is given in the
  27577. * coordinate space of the mesh. If the value is `0` the material is
  27578. * thin-walled. Otherwise the material is a volume boundary.
  27579. *
  27580. * @type {number}
  27581. * @default 0
  27582. */
  27583. this.thickness = 0;
  27584. /**
  27585. * A texture that defines the thickness, stored in the green channel. This will
  27586. * be multiplied by `thickness`.
  27587. *
  27588. * @type {?Texture}
  27589. * @default null
  27590. */
  27591. this.thicknessMap = null;
  27592. /**
  27593. * Density of the medium given as the average distance that light travels in
  27594. * the medium before interacting with a particle. The value is given in world
  27595. * space units, and must be greater than zero.
  27596. *
  27597. * @type {number}
  27598. * @default Infinity
  27599. */
  27600. this.attenuationDistance = Infinity;
  27601. /**
  27602. * The color that white light turns into due to absorption when reaching the
  27603. * attenuation distance.
  27604. *
  27605. * @type {Color}
  27606. * @default (1,1,1)
  27607. */
  27608. this.attenuationColor = new Color( 1, 1, 1 );
  27609. /**
  27610. * A float that scales the amount of specular reflection for non-metals only.
  27611. * When set to zero, the model is effectively Lambertian. From `0.0` to `1.0`.
  27612. *
  27613. * @type {number}
  27614. * @default 1
  27615. */
  27616. this.specularIntensity = 1.0;
  27617. /**
  27618. * The alpha channel of this texture is multiplied against `specularIntensity`,
  27619. * for per-pixel control over specular intensity.
  27620. *
  27621. * @type {?Texture}
  27622. * @default null
  27623. */
  27624. this.specularIntensityMap = null;
  27625. /**
  27626. * Tints the specular reflection at normal incidence for non-metals only.
  27627. *
  27628. * @type {Color}
  27629. * @default (1,1,1)
  27630. */
  27631. this.specularColor = new Color( 1, 1, 1 );
  27632. /**
  27633. * The RGB channels of this texture are multiplied against `specularColor`,
  27634. * for per-pixel control over specular color.
  27635. *
  27636. * @type {?Texture}
  27637. * @default null
  27638. */
  27639. this.specularColorMap = null;
  27640. this._anisotropy = 0;
  27641. this._clearcoat = 0;
  27642. this._dispersion = 0;
  27643. this._iridescence = 0;
  27644. this._sheen = 0.0;
  27645. this._transmission = 0;
  27646. this.setValues( parameters );
  27647. }
  27648. /**
  27649. * The anisotropy strength.
  27650. *
  27651. * @type {number}
  27652. * @default 0
  27653. */
  27654. get anisotropy() {
  27655. return this._anisotropy;
  27656. }
  27657. set anisotropy( value ) {
  27658. if ( this._anisotropy > 0 !== value > 0 ) {
  27659. this.version ++;
  27660. }
  27661. this._anisotropy = value;
  27662. }
  27663. /**
  27664. * Represents the intensity of the clear coat layer, from `0.0` to `1.0`. Use
  27665. * clear coat related properties to enable multilayer materials that have a
  27666. * thin translucent layer over the base layer.
  27667. *
  27668. * @type {number}
  27669. * @default 0
  27670. */
  27671. get clearcoat() {
  27672. return this._clearcoat;
  27673. }
  27674. set clearcoat( value ) {
  27675. if ( this._clearcoat > 0 !== value > 0 ) {
  27676. this.version ++;
  27677. }
  27678. this._clearcoat = value;
  27679. }
  27680. /**
  27681. * The intensity of the iridescence layer, simulating RGB color shift based on the angle between
  27682. * the surface and the viewer, from `0.0` to `1.0`.
  27683. *
  27684. * @type {number}
  27685. * @default 0
  27686. */
  27687. get iridescence() {
  27688. return this._iridescence;
  27689. }
  27690. set iridescence( value ) {
  27691. if ( this._iridescence > 0 !== value > 0 ) {
  27692. this.version ++;
  27693. }
  27694. this._iridescence = value;
  27695. }
  27696. /**
  27697. * Defines the strength of the angular separation of colors (chromatic aberration) transmitting
  27698. * through a relatively clear volume. Any value zero or larger is valid, the typical range of
  27699. * realistic values is `[0, 1]`. This property can be only be used with transmissive objects.
  27700. *
  27701. * @type {number}
  27702. * @default 0
  27703. */
  27704. get dispersion() {
  27705. return this._dispersion;
  27706. }
  27707. set dispersion( value ) {
  27708. if ( this._dispersion > 0 !== value > 0 ) {
  27709. this.version ++;
  27710. }
  27711. this._dispersion = value;
  27712. }
  27713. /**
  27714. * The intensity of the sheen layer, from `0.0` to `1.0`.
  27715. *
  27716. * @type {number}
  27717. * @default 0
  27718. */
  27719. get sheen() {
  27720. return this._sheen;
  27721. }
  27722. set sheen( value ) {
  27723. if ( this._sheen > 0 !== value > 0 ) {
  27724. this.version ++;
  27725. }
  27726. this._sheen = value;
  27727. }
  27728. /**
  27729. * Degree of transmission (or optical transparency), from `0.0` to `1.0`.
  27730. *
  27731. * Thin, transparent or semitransparent, plastic or glass materials remain
  27732. * largely reflective even if they are fully transmissive. The transmission
  27733. * property can be used to model these materials.
  27734. *
  27735. * When transmission is non-zero, `opacity` should be set to `1`.
  27736. *
  27737. * @type {number}
  27738. * @default 0
  27739. */
  27740. get transmission() {
  27741. return this._transmission;
  27742. }
  27743. set transmission( value ) {
  27744. if ( this._transmission > 0 !== value > 0 ) {
  27745. this.version ++;
  27746. }
  27747. this._transmission = value;
  27748. }
  27749. copy( source ) {
  27750. super.copy( source );
  27751. this.defines = {
  27752. 'STANDARD': '',
  27753. 'PHYSICAL': ''
  27754. };
  27755. this.anisotropy = source.anisotropy;
  27756. this.anisotropyRotation = source.anisotropyRotation;
  27757. this.anisotropyMap = source.anisotropyMap;
  27758. this.clearcoat = source.clearcoat;
  27759. this.clearcoatMap = source.clearcoatMap;
  27760. this.clearcoatRoughness = source.clearcoatRoughness;
  27761. this.clearcoatRoughnessMap = source.clearcoatRoughnessMap;
  27762. this.clearcoatNormalMap = source.clearcoatNormalMap;
  27763. this.clearcoatNormalScale.copy( source.clearcoatNormalScale );
  27764. this.dispersion = source.dispersion;
  27765. this.ior = source.ior;
  27766. this.iridescence = source.iridescence;
  27767. this.iridescenceMap = source.iridescenceMap;
  27768. this.iridescenceIOR = source.iridescenceIOR;
  27769. this.iridescenceThicknessRange = [ ...source.iridescenceThicknessRange ];
  27770. this.iridescenceThicknessMap = source.iridescenceThicknessMap;
  27771. this.sheen = source.sheen;
  27772. this.sheenColor.copy( source.sheenColor );
  27773. this.sheenColorMap = source.sheenColorMap;
  27774. this.sheenRoughness = source.sheenRoughness;
  27775. this.sheenRoughnessMap = source.sheenRoughnessMap;
  27776. this.transmission = source.transmission;
  27777. this.transmissionMap = source.transmissionMap;
  27778. this.thickness = source.thickness;
  27779. this.thicknessMap = source.thicknessMap;
  27780. this.attenuationDistance = source.attenuationDistance;
  27781. this.attenuationColor.copy( source.attenuationColor );
  27782. this.specularIntensity = source.specularIntensity;
  27783. this.specularIntensityMap = source.specularIntensityMap;
  27784. this.specularColor.copy( source.specularColor );
  27785. this.specularColorMap = source.specularColorMap;
  27786. return this;
  27787. }
  27788. }
  27789. /**
  27790. * A material for shiny surfaces with specular highlights.
  27791. *
  27792. * The material uses a non-physically based [Blinn-Phong]{@link https://en.wikipedia.org/wiki/Blinn-Phong_shading_model}
  27793. * model for calculating reflectance. Unlike the Lambertian model used in the
  27794. * {@link MeshLambertMaterial} this can simulate shiny surfaces with specular
  27795. * highlights (such as varnished wood). `MeshPhongMaterial` uses per-fragment shading.
  27796. *
  27797. * Performance will generally be greater when using this material over the
  27798. * {@link MeshStandardMaterial} or {@link MeshPhysicalMaterial}, at the cost of
  27799. * some graphical accuracy.
  27800. *
  27801. * @augments Material
  27802. */
  27803. class MeshPhongMaterial extends Material {
  27804. /**
  27805. * Constructs a new mesh phong material.
  27806. *
  27807. * @param {Object} [parameters] - An object with one or more properties
  27808. * defining the material's appearance. Any property of the material
  27809. * (including any property from inherited materials) can be passed
  27810. * in here. Color values can be passed any type of value accepted
  27811. * by {@link Color#set}.
  27812. */
  27813. constructor( parameters ) {
  27814. super();
  27815. /**
  27816. * This flag can be used for type testing.
  27817. *
  27818. * @type {boolean}
  27819. * @readonly
  27820. * @default true
  27821. */
  27822. this.isMeshPhongMaterial = true;
  27823. this.type = 'MeshPhongMaterial';
  27824. /**
  27825. * Color of the material.
  27826. *
  27827. * @type {Color}
  27828. * @default (1,1,1)
  27829. */
  27830. this.color = new Color( 0xffffff ); // diffuse
  27831. /**
  27832. * Specular color of the material. The default color is set to `0x111111` (very dark grey)
  27833. *
  27834. * This defines how shiny the material is and the color of its shine.
  27835. *
  27836. * @type {Color}
  27837. */
  27838. this.specular = new Color( 0x111111 );
  27839. /**
  27840. * How shiny the specular highlight is; a higher value gives a sharper highlight.
  27841. *
  27842. * @type {number}
  27843. * @default 30
  27844. */
  27845. this.shininess = 30;
  27846. /**
  27847. * The color map. May optionally include an alpha channel, typically combined
  27848. * with {@link Material#transparent} or {@link Material#alphaTest}. The texture map
  27849. * color is modulated by the diffuse `color`.
  27850. *
  27851. * @type {?Texture}
  27852. * @default null
  27853. */
  27854. this.map = null;
  27855. /**
  27856. * The light map. Requires a second set of UVs.
  27857. *
  27858. * @type {?Texture}
  27859. * @default null
  27860. */
  27861. this.lightMap = null;
  27862. /**
  27863. * Intensity of the baked light.
  27864. *
  27865. * @type {number}
  27866. * @default 1
  27867. */
  27868. this.lightMapIntensity = 1.0;
  27869. /**
  27870. * The red channel of this texture is used as the ambient occlusion map.
  27871. * Requires a second set of UVs.
  27872. *
  27873. * @type {?Texture}
  27874. * @default null
  27875. */
  27876. this.aoMap = null;
  27877. /**
  27878. * Intensity of the ambient occlusion effect. Range is `[0,1]`, where `0`
  27879. * disables ambient occlusion. Where intensity is `1` and the AO map's
  27880. * red channel is also `1`, ambient light is fully occluded on a surface.
  27881. *
  27882. * @type {number}
  27883. * @default 1
  27884. */
  27885. this.aoMapIntensity = 1.0;
  27886. /**
  27887. * Emissive (light) color of the material, essentially a solid color
  27888. * unaffected by other lighting.
  27889. *
  27890. * @type {Color}
  27891. * @default (0,0,0)
  27892. */
  27893. this.emissive = new Color( 0x000000 );
  27894. /**
  27895. * Intensity of the emissive light. Modulates the emissive color.
  27896. *
  27897. * @type {number}
  27898. * @default 1
  27899. */
  27900. this.emissiveIntensity = 1.0;
  27901. /**
  27902. * Set emissive (glow) map. The emissive map color is modulated by the
  27903. * emissive color and the emissive intensity. If you have an emissive map,
  27904. * be sure to set the emissive color to something other than black.
  27905. *
  27906. * @type {?Texture}
  27907. * @default null
  27908. */
  27909. this.emissiveMap = null;
  27910. /**
  27911. * The texture to create a bump map. The black and white values map to the
  27912. * perceived depth in relation to the lights. Bump doesn't actually affect
  27913. * the geometry of the object, only the lighting. If a normal map is defined
  27914. * this will be ignored.
  27915. *
  27916. * @type {?Texture}
  27917. * @default null
  27918. */
  27919. this.bumpMap = null;
  27920. /**
  27921. * How much the bump map affects the material. Typical range is `[0,1]`.
  27922. *
  27923. * @type {number}
  27924. * @default 1
  27925. */
  27926. this.bumpScale = 1;
  27927. /**
  27928. * The texture to create a normal map. The RGB values affect the surface
  27929. * normal for each pixel fragment and change the way the color is lit. Normal
  27930. * maps do not change the actual shape of the surface, only the lighting. In
  27931. * case the material has a normal map authored using the left handed
  27932. * convention, the `y` component of `normalScale` should be negated to compensate
  27933. * for the different handedness.
  27934. *
  27935. * @type {?Texture}
  27936. * @default null
  27937. */
  27938. this.normalMap = null;
  27939. /**
  27940. * The type of normal map.
  27941. *
  27942. * @type {(TangentSpaceNormalMap|ObjectSpaceNormalMap)}
  27943. * @default TangentSpaceNormalMap
  27944. */
  27945. this.normalMapType = TangentSpaceNormalMap;
  27946. /**
  27947. * How much the normal map affects the material. Typical value range is `[0,1]`.
  27948. *
  27949. * @type {Vector2}
  27950. * @default (1,1)
  27951. */
  27952. this.normalScale = new Vector2( 1, 1 );
  27953. /**
  27954. * The displacement map affects the position of the mesh's vertices. Unlike
  27955. * other maps which only affect the light and shade of the material the
  27956. * displaced vertices can cast shadows, block other objects, and otherwise
  27957. * act as real geometry. The displacement texture is an image where the value
  27958. * of each pixel (white being the highest) is mapped against, and
  27959. * repositions, the vertices of the mesh.
  27960. *
  27961. * @type {?Texture}
  27962. * @default null
  27963. */
  27964. this.displacementMap = null;
  27965. /**
  27966. * How much the displacement map affects the mesh (where black is no
  27967. * displacement, and white is maximum displacement). Without a displacement
  27968. * map set, this value is not applied.
  27969. *
  27970. * @type {number}
  27971. * @default 0
  27972. */
  27973. this.displacementScale = 1;
  27974. /**
  27975. * The offset of the displacement map's values on the mesh's vertices.
  27976. * The bias is added to the scaled sample of the displacement map.
  27977. * Without a displacement map set, this value is not applied.
  27978. *
  27979. * @type {number}
  27980. * @default 0
  27981. */
  27982. this.displacementBias = 0;
  27983. /**
  27984. * The specular map value affects both how much the specular surface
  27985. * highlight contributes and how much of the environment map affects the
  27986. * surface.
  27987. *
  27988. * @type {?Texture}
  27989. * @default null
  27990. */
  27991. this.specularMap = null;
  27992. /**
  27993. * The alpha map is a grayscale texture that controls the opacity across the
  27994. * surface (black: fully transparent; white: fully opaque).
  27995. *
  27996. * Only the color of the texture is used, ignoring the alpha channel if one
  27997. * exists. For RGB and RGBA textures, the renderer will use the green channel
  27998. * when sampling this texture due to the extra bit of precision provided for
  27999. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  28000. * luminance/alpha textures will also still work as expected.
  28001. *
  28002. * @type {?Texture}
  28003. * @default null
  28004. */
  28005. this.alphaMap = null;
  28006. /**
  28007. * The environment map.
  28008. *
  28009. * @type {?Texture}
  28010. * @default null
  28011. */
  28012. this.envMap = null;
  28013. /**
  28014. * The rotation of the environment map in radians.
  28015. *
  28016. * @type {Euler}
  28017. * @default (0,0,0)
  28018. */
  28019. this.envMapRotation = new Euler();
  28020. /**
  28021. * How to combine the result of the surface's color with the environment map, if any.
  28022. *
  28023. * When set to `MixOperation`, the {@link MeshBasicMaterial#reflectivity} is used to
  28024. * blend between the two colors.
  28025. *
  28026. * @type {(MultiplyOperation|MixOperation|AddOperation)}
  28027. * @default MultiplyOperation
  28028. */
  28029. this.combine = MultiplyOperation;
  28030. /**
  28031. * How much the environment map affects the surface.
  28032. * The valid range is between `0` (no reflections) and `1` (full reflections).
  28033. *
  28034. * @type {number}
  28035. * @default 1
  28036. */
  28037. this.reflectivity = 1;
  28038. /**
  28039. * The index of refraction (IOR) of air (approximately 1) divided by the
  28040. * index of refraction of the material. It is used with environment mapping
  28041. * modes {@link CubeRefractionMapping} and {@link EquirectangularRefractionMapping}.
  28042. * The refraction ratio should not exceed `1`.
  28043. *
  28044. * @type {number}
  28045. * @default 0.98
  28046. */
  28047. this.refractionRatio = 0.98;
  28048. /**
  28049. * Renders the geometry as a wireframe.
  28050. *
  28051. * @type {boolean}
  28052. * @default false
  28053. */
  28054. this.wireframe = false;
  28055. /**
  28056. * Controls the thickness of the wireframe.
  28057. *
  28058. * Can only be used with {@link SVGRenderer}.
  28059. *
  28060. * @type {number}
  28061. * @default 1
  28062. */
  28063. this.wireframeLinewidth = 1;
  28064. /**
  28065. * Defines appearance of wireframe ends.
  28066. *
  28067. * Can only be used with {@link SVGRenderer}.
  28068. *
  28069. * @type {('round'|'bevel'|'miter')}
  28070. * @default 'round'
  28071. */
  28072. this.wireframeLinecap = 'round';
  28073. /**
  28074. * Defines appearance of wireframe joints.
  28075. *
  28076. * Can only be used with {@link SVGRenderer}.
  28077. *
  28078. * @type {('round'|'bevel'|'miter')}
  28079. * @default 'round'
  28080. */
  28081. this.wireframeLinejoin = 'round';
  28082. /**
  28083. * Whether the material is rendered with flat shading or not.
  28084. *
  28085. * @type {boolean}
  28086. * @default false
  28087. */
  28088. this.flatShading = false;
  28089. /**
  28090. * Whether the material is affected by fog or not.
  28091. *
  28092. * @type {boolean}
  28093. * @default true
  28094. */
  28095. this.fog = true;
  28096. this.setValues( parameters );
  28097. }
  28098. copy( source ) {
  28099. super.copy( source );
  28100. this.color.copy( source.color );
  28101. this.specular.copy( source.specular );
  28102. this.shininess = source.shininess;
  28103. this.map = source.map;
  28104. this.lightMap = source.lightMap;
  28105. this.lightMapIntensity = source.lightMapIntensity;
  28106. this.aoMap = source.aoMap;
  28107. this.aoMapIntensity = source.aoMapIntensity;
  28108. this.emissive.copy( source.emissive );
  28109. this.emissiveMap = source.emissiveMap;
  28110. this.emissiveIntensity = source.emissiveIntensity;
  28111. this.bumpMap = source.bumpMap;
  28112. this.bumpScale = source.bumpScale;
  28113. this.normalMap = source.normalMap;
  28114. this.normalMapType = source.normalMapType;
  28115. this.normalScale.copy( source.normalScale );
  28116. this.displacementMap = source.displacementMap;
  28117. this.displacementScale = source.displacementScale;
  28118. this.displacementBias = source.displacementBias;
  28119. this.specularMap = source.specularMap;
  28120. this.alphaMap = source.alphaMap;
  28121. this.envMap = source.envMap;
  28122. this.envMapRotation.copy( source.envMapRotation );
  28123. this.combine = source.combine;
  28124. this.reflectivity = source.reflectivity;
  28125. this.refractionRatio = source.refractionRatio;
  28126. this.wireframe = source.wireframe;
  28127. this.wireframeLinewidth = source.wireframeLinewidth;
  28128. this.wireframeLinecap = source.wireframeLinecap;
  28129. this.wireframeLinejoin = source.wireframeLinejoin;
  28130. this.flatShading = source.flatShading;
  28131. this.fog = source.fog;
  28132. return this;
  28133. }
  28134. }
  28135. /**
  28136. * A material implementing toon shading.
  28137. *
  28138. * @augments Material
  28139. */
  28140. class MeshToonMaterial extends Material {
  28141. /**
  28142. * Constructs a new mesh toon material.
  28143. *
  28144. * @param {Object} [parameters] - An object with one or more properties
  28145. * defining the material's appearance. Any property of the material
  28146. * (including any property from inherited materials) can be passed
  28147. * in here. Color values can be passed any type of value accepted
  28148. * by {@link Color#set}.
  28149. */
  28150. constructor( parameters ) {
  28151. super();
  28152. /**
  28153. * This flag can be used for type testing.
  28154. *
  28155. * @type {boolean}
  28156. * @readonly
  28157. * @default true
  28158. */
  28159. this.isMeshToonMaterial = true;
  28160. this.defines = { 'TOON': '' };
  28161. this.type = 'MeshToonMaterial';
  28162. /**
  28163. * Color of the material.
  28164. *
  28165. * @type {Color}
  28166. * @default (1,1,1)
  28167. */
  28168. this.color = new Color( 0xffffff );
  28169. /**
  28170. * The color map. May optionally include an alpha channel, typically combined
  28171. * with {@link Material#transparent} or {@link Material#alphaTest}. The texture map
  28172. * color is modulated by the diffuse `color`.
  28173. *
  28174. * @type {?Texture}
  28175. * @default null
  28176. */
  28177. this.map = null;
  28178. /**
  28179. * Gradient map for toon shading. It's required to set
  28180. * {@link Texture#minFilter} and {@link Texture#magFilter} to {@linkNearestFilter}
  28181. * when using this type of texture.
  28182. *
  28183. * @type {?Texture}
  28184. * @default null
  28185. */
  28186. this.gradientMap = null;
  28187. /**
  28188. * The light map. Requires a second set of UVs.
  28189. *
  28190. * @type {?Texture}
  28191. * @default null
  28192. */
  28193. this.lightMap = null;
  28194. /**
  28195. * Intensity of the baked light.
  28196. *
  28197. * @type {number}
  28198. * @default 1
  28199. */
  28200. this.lightMapIntensity = 1.0;
  28201. /**
  28202. * The red channel of this texture is used as the ambient occlusion map.
  28203. * Requires a second set of UVs.
  28204. *
  28205. * @type {?Texture}
  28206. * @default null
  28207. */
  28208. this.aoMap = null;
  28209. /**
  28210. * Intensity of the ambient occlusion effect. Range is `[0,1]`, where `0`
  28211. * disables ambient occlusion. Where intensity is `1` and the AO map's
  28212. * red channel is also `1`, ambient light is fully occluded on a surface.
  28213. *
  28214. * @type {number}
  28215. * @default 1
  28216. */
  28217. this.aoMapIntensity = 1.0;
  28218. /**
  28219. * Emissive (light) color of the material, essentially a solid color
  28220. * unaffected by other lighting.
  28221. *
  28222. * @type {Color}
  28223. * @default (0,0,0)
  28224. */
  28225. this.emissive = new Color( 0x000000 );
  28226. /**
  28227. * Intensity of the emissive light. Modulates the emissive color.
  28228. *
  28229. * @type {number}
  28230. * @default 1
  28231. */
  28232. this.emissiveIntensity = 1.0;
  28233. /**
  28234. * Set emissive (glow) map. The emissive map color is modulated by the
  28235. * emissive color and the emissive intensity. If you have an emissive map,
  28236. * be sure to set the emissive color to something other than black.
  28237. *
  28238. * @type {?Texture}
  28239. * @default null
  28240. */
  28241. this.emissiveMap = null;
  28242. /**
  28243. * The texture to create a bump map. The black and white values map to the
  28244. * perceived depth in relation to the lights. Bump doesn't actually affect
  28245. * the geometry of the object, only the lighting. If a normal map is defined
  28246. * this will be ignored.
  28247. *
  28248. * @type {?Texture}
  28249. * @default null
  28250. */
  28251. this.bumpMap = null;
  28252. /**
  28253. * How much the bump map affects the material. Typical range is `[0,1]`.
  28254. *
  28255. * @type {number}
  28256. * @default 1
  28257. */
  28258. this.bumpScale = 1;
  28259. /**
  28260. * The texture to create a normal map. The RGB values affect the surface
  28261. * normal for each pixel fragment and change the way the color is lit. Normal
  28262. * maps do not change the actual shape of the surface, only the lighting. In
  28263. * case the material has a normal map authored using the left handed
  28264. * convention, the `y` component of `normalScale` should be negated to compensate
  28265. * for the different handedness.
  28266. *
  28267. * @type {?Texture}
  28268. * @default null
  28269. */
  28270. this.normalMap = null;
  28271. /**
  28272. * The type of normal map.
  28273. *
  28274. * @type {(TangentSpaceNormalMap|ObjectSpaceNormalMap)}
  28275. * @default TangentSpaceNormalMap
  28276. */
  28277. this.normalMapType = TangentSpaceNormalMap;
  28278. /**
  28279. * How much the normal map affects the material. Typical value range is `[0,1]`.
  28280. *
  28281. * @type {Vector2}
  28282. * @default (1,1)
  28283. */
  28284. this.normalScale = new Vector2( 1, 1 );
  28285. /**
  28286. * The displacement map affects the position of the mesh's vertices. Unlike
  28287. * other maps which only affect the light and shade of the material the
  28288. * displaced vertices can cast shadows, block other objects, and otherwise
  28289. * act as real geometry. The displacement texture is an image where the value
  28290. * of each pixel (white being the highest) is mapped against, and
  28291. * repositions, the vertices of the mesh.
  28292. *
  28293. * @type {?Texture}
  28294. * @default null
  28295. */
  28296. this.displacementMap = null;
  28297. /**
  28298. * How much the displacement map affects the mesh (where black is no
  28299. * displacement, and white is maximum displacement). Without a displacement
  28300. * map set, this value is not applied.
  28301. *
  28302. * @type {number}
  28303. * @default 0
  28304. */
  28305. this.displacementScale = 1;
  28306. /**
  28307. * The offset of the displacement map's values on the mesh's vertices.
  28308. * The bias is added to the scaled sample of the displacement map.
  28309. * Without a displacement map set, this value is not applied.
  28310. *
  28311. * @type {number}
  28312. * @default 0
  28313. */
  28314. this.displacementBias = 0;
  28315. /**
  28316. * The alpha map is a grayscale texture that controls the opacity across the
  28317. * surface (black: fully transparent; white: fully opaque).
  28318. *
  28319. * Only the color of the texture is used, ignoring the alpha channel if one
  28320. * exists. For RGB and RGBA textures, the renderer will use the green channel
  28321. * when sampling this texture due to the extra bit of precision provided for
  28322. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  28323. * luminance/alpha textures will also still work as expected.
  28324. *
  28325. * @type {?Texture}
  28326. * @default null
  28327. */
  28328. this.alphaMap = null;
  28329. /**
  28330. * Renders the geometry as a wireframe.
  28331. *
  28332. * @type {boolean}
  28333. * @default false
  28334. */
  28335. this.wireframe = false;
  28336. /**
  28337. * Controls the thickness of the wireframe.
  28338. *
  28339. * Can only be used with {@link SVGRenderer}.
  28340. *
  28341. * @type {number}
  28342. * @default 1
  28343. */
  28344. this.wireframeLinewidth = 1;
  28345. /**
  28346. * Defines appearance of wireframe ends.
  28347. *
  28348. * Can only be used with {@link SVGRenderer}.
  28349. *
  28350. * @type {('round'|'bevel'|'miter')}
  28351. * @default 'round'
  28352. */
  28353. this.wireframeLinecap = 'round';
  28354. /**
  28355. * Defines appearance of wireframe joints.
  28356. *
  28357. * Can only be used with {@link SVGRenderer}.
  28358. *
  28359. * @type {('round'|'bevel'|'miter')}
  28360. * @default 'round'
  28361. */
  28362. this.wireframeLinejoin = 'round';
  28363. /**
  28364. * Whether the material is affected by fog or not.
  28365. *
  28366. * @type {boolean}
  28367. * @default true
  28368. */
  28369. this.fog = true;
  28370. this.setValues( parameters );
  28371. }
  28372. copy( source ) {
  28373. super.copy( source );
  28374. this.color.copy( source.color );
  28375. this.map = source.map;
  28376. this.gradientMap = source.gradientMap;
  28377. this.lightMap = source.lightMap;
  28378. this.lightMapIntensity = source.lightMapIntensity;
  28379. this.aoMap = source.aoMap;
  28380. this.aoMapIntensity = source.aoMapIntensity;
  28381. this.emissive.copy( source.emissive );
  28382. this.emissiveMap = source.emissiveMap;
  28383. this.emissiveIntensity = source.emissiveIntensity;
  28384. this.bumpMap = source.bumpMap;
  28385. this.bumpScale = source.bumpScale;
  28386. this.normalMap = source.normalMap;
  28387. this.normalMapType = source.normalMapType;
  28388. this.normalScale.copy( source.normalScale );
  28389. this.displacementMap = source.displacementMap;
  28390. this.displacementScale = source.displacementScale;
  28391. this.displacementBias = source.displacementBias;
  28392. this.alphaMap = source.alphaMap;
  28393. this.wireframe = source.wireframe;
  28394. this.wireframeLinewidth = source.wireframeLinewidth;
  28395. this.wireframeLinecap = source.wireframeLinecap;
  28396. this.wireframeLinejoin = source.wireframeLinejoin;
  28397. this.fog = source.fog;
  28398. return this;
  28399. }
  28400. }
  28401. /**
  28402. * A material that maps the normal vectors to RGB colors.
  28403. *
  28404. * @augments Material
  28405. */
  28406. class MeshNormalMaterial extends Material {
  28407. /**
  28408. * Constructs a new mesh normal material.
  28409. *
  28410. * @param {Object} [parameters] - An object with one or more properties
  28411. * defining the material's appearance. Any property of the material
  28412. * (including any property from inherited materials) can be passed
  28413. * in here. Color values can be passed any type of value accepted
  28414. * by {@link Color#set}.
  28415. */
  28416. constructor( parameters ) {
  28417. super();
  28418. /**
  28419. * This flag can be used for type testing.
  28420. *
  28421. * @type {boolean}
  28422. * @readonly
  28423. * @default true
  28424. */
  28425. this.isMeshNormalMaterial = true;
  28426. this.type = 'MeshNormalMaterial';
  28427. /**
  28428. * The texture to create a bump map. The black and white values map to the
  28429. * perceived depth in relation to the lights. Bump doesn't actually affect
  28430. * the geometry of the object, only the lighting. If a normal map is defined
  28431. * this will be ignored.
  28432. *
  28433. * @type {?Texture}
  28434. * @default null
  28435. */
  28436. this.bumpMap = null;
  28437. /**
  28438. * How much the bump map affects the material. Typical range is `[0,1]`.
  28439. *
  28440. * @type {number}
  28441. * @default 1
  28442. */
  28443. this.bumpScale = 1;
  28444. /**
  28445. * The texture to create a normal map. The RGB values affect the surface
  28446. * normal for each pixel fragment and change the way the color is lit. Normal
  28447. * maps do not change the actual shape of the surface, only the lighting. In
  28448. * case the material has a normal map authored using the left handed
  28449. * convention, the `y` component of `normalScale` should be negated to compensate
  28450. * for the different handedness.
  28451. *
  28452. * @type {?Texture}
  28453. * @default null
  28454. */
  28455. this.normalMap = null;
  28456. /**
  28457. * The type of normal map.
  28458. *
  28459. * @type {(TangentSpaceNormalMap|ObjectSpaceNormalMap)}
  28460. * @default TangentSpaceNormalMap
  28461. */
  28462. this.normalMapType = TangentSpaceNormalMap;
  28463. /**
  28464. * How much the normal map affects the material. Typical value range is `[0,1]`.
  28465. *
  28466. * @type {Vector2}
  28467. * @default (1,1)
  28468. */
  28469. this.normalScale = new Vector2( 1, 1 );
  28470. /**
  28471. * The displacement map affects the position of the mesh's vertices. Unlike
  28472. * other maps which only affect the light and shade of the material the
  28473. * displaced vertices can cast shadows, block other objects, and otherwise
  28474. * act as real geometry. The displacement texture is an image where the value
  28475. * of each pixel (white being the highest) is mapped against, and
  28476. * repositions, the vertices of the mesh.
  28477. *
  28478. * @type {?Texture}
  28479. * @default null
  28480. */
  28481. this.displacementMap = null;
  28482. /**
  28483. * How much the displacement map affects the mesh (where black is no
  28484. * displacement, and white is maximum displacement). Without a displacement
  28485. * map set, this value is not applied.
  28486. *
  28487. * @type {number}
  28488. * @default 0
  28489. */
  28490. this.displacementScale = 1;
  28491. /**
  28492. * The offset of the displacement map's values on the mesh's vertices.
  28493. * The bias is added to the scaled sample of the displacement map.
  28494. * Without a displacement map set, this value is not applied.
  28495. *
  28496. * @type {number}
  28497. * @default 0
  28498. */
  28499. this.displacementBias = 0;
  28500. /**
  28501. * Renders the geometry as a wireframe.
  28502. *
  28503. * @type {boolean}
  28504. * @default false
  28505. */
  28506. this.wireframe = false;
  28507. /**
  28508. * Controls the thickness of the wireframe.
  28509. *
  28510. * WebGL and WebGPU ignore this property and always render
  28511. * 1 pixel wide lines.
  28512. *
  28513. * @type {number}
  28514. * @default 1
  28515. */
  28516. this.wireframeLinewidth = 1;
  28517. /**
  28518. * Whether the material is rendered with flat shading or not.
  28519. *
  28520. * @type {boolean}
  28521. * @default false
  28522. */
  28523. this.flatShading = false;
  28524. this.setValues( parameters );
  28525. }
  28526. copy( source ) {
  28527. super.copy( source );
  28528. this.bumpMap = source.bumpMap;
  28529. this.bumpScale = source.bumpScale;
  28530. this.normalMap = source.normalMap;
  28531. this.normalMapType = source.normalMapType;
  28532. this.normalScale.copy( source.normalScale );
  28533. this.displacementMap = source.displacementMap;
  28534. this.displacementScale = source.displacementScale;
  28535. this.displacementBias = source.displacementBias;
  28536. this.wireframe = source.wireframe;
  28537. this.wireframeLinewidth = source.wireframeLinewidth;
  28538. this.flatShading = source.flatShading;
  28539. return this;
  28540. }
  28541. }
  28542. /**
  28543. * A material for non-shiny surfaces, without specular highlights.
  28544. *
  28545. * The material uses a non-physically based [Lambertian]{@link https://en.wikipedia.org/wiki/Lambertian_reflectance}
  28546. * model for calculating reflectance. This can simulate some surfaces (such
  28547. * as untreated wood or stone) well, but cannot simulate shiny surfaces with
  28548. * specular highlights (such as varnished wood). `MeshLambertMaterial` uses per-fragment
  28549. * shading.
  28550. *
  28551. * Due to the simplicity of the reflectance and illumination models,
  28552. * performance will be greater when using this material over the
  28553. * {@link MeshPhongMaterial}, {@link MeshStandardMaterial} or
  28554. * {@link MeshPhysicalMaterial}, at the cost of some graphical accuracy.
  28555. *
  28556. * @augments Material
  28557. */
  28558. class MeshLambertMaterial extends Material {
  28559. /**
  28560. * Constructs a new mesh lambert material.
  28561. *
  28562. * @param {Object} [parameters] - An object with one or more properties
  28563. * defining the material's appearance. Any property of the material
  28564. * (including any property from inherited materials) can be passed
  28565. * in here. Color values can be passed any type of value accepted
  28566. * by {@link Color#set}.
  28567. */
  28568. constructor( parameters ) {
  28569. super();
  28570. /**
  28571. * This flag can be used for type testing.
  28572. *
  28573. * @type {boolean}
  28574. * @readonly
  28575. * @default true
  28576. */
  28577. this.isMeshLambertMaterial = true;
  28578. this.type = 'MeshLambertMaterial';
  28579. /**
  28580. * Color of the material.
  28581. *
  28582. * @type {Color}
  28583. * @default (1,1,1)
  28584. */
  28585. this.color = new Color( 0xffffff ); // diffuse
  28586. /**
  28587. * The color map. May optionally include an alpha channel, typically combined
  28588. * with {@link Material#transparent} or {@link Material#alphaTest}. The texture map
  28589. * color is modulated by the diffuse `color`.
  28590. *
  28591. * @type {?Texture}
  28592. * @default null
  28593. */
  28594. this.map = null;
  28595. /**
  28596. * The light map. Requires a second set of UVs.
  28597. *
  28598. * @type {?Texture}
  28599. * @default null
  28600. */
  28601. this.lightMap = null;
  28602. /**
  28603. * Intensity of the baked light.
  28604. *
  28605. * @type {number}
  28606. * @default 1
  28607. */
  28608. this.lightMapIntensity = 1.0;
  28609. /**
  28610. * The red channel of this texture is used as the ambient occlusion map.
  28611. * Requires a second set of UVs.
  28612. *
  28613. * @type {?Texture}
  28614. * @default null
  28615. */
  28616. this.aoMap = null;
  28617. /**
  28618. * Intensity of the ambient occlusion effect. Range is `[0,1]`, where `0`
  28619. * disables ambient occlusion. Where intensity is `1` and the AO map's
  28620. * red channel is also `1`, ambient light is fully occluded on a surface.
  28621. *
  28622. * @type {number}
  28623. * @default 1
  28624. */
  28625. this.aoMapIntensity = 1.0;
  28626. /**
  28627. * Emissive (light) color of the material, essentially a solid color
  28628. * unaffected by other lighting.
  28629. *
  28630. * @type {Color}
  28631. * @default (0,0,0)
  28632. */
  28633. this.emissive = new Color( 0x000000 );
  28634. /**
  28635. * Intensity of the emissive light. Modulates the emissive color.
  28636. *
  28637. * @type {number}
  28638. * @default 1
  28639. */
  28640. this.emissiveIntensity = 1.0;
  28641. /**
  28642. * Set emissive (glow) map. The emissive map color is modulated by the
  28643. * emissive color and the emissive intensity. If you have an emissive map,
  28644. * be sure to set the emissive color to something other than black.
  28645. *
  28646. * @type {?Texture}
  28647. * @default null
  28648. */
  28649. this.emissiveMap = null;
  28650. /**
  28651. * The texture to create a bump map. The black and white values map to the
  28652. * perceived depth in relation to the lights. Bump doesn't actually affect
  28653. * the geometry of the object, only the lighting. If a normal map is defined
  28654. * this will be ignored.
  28655. *
  28656. * @type {?Texture}
  28657. * @default null
  28658. */
  28659. this.bumpMap = null;
  28660. /**
  28661. * How much the bump map affects the material. Typical range is `[0,1]`.
  28662. *
  28663. * @type {number}
  28664. * @default 1
  28665. */
  28666. this.bumpScale = 1;
  28667. /**
  28668. * The texture to create a normal map. The RGB values affect the surface
  28669. * normal for each pixel fragment and change the way the color is lit. Normal
  28670. * maps do not change the actual shape of the surface, only the lighting. In
  28671. * case the material has a normal map authored using the left handed
  28672. * convention, the `y` component of `normalScale` should be negated to compensate
  28673. * for the different handedness.
  28674. *
  28675. * @type {?Texture}
  28676. * @default null
  28677. */
  28678. this.normalMap = null;
  28679. /**
  28680. * The type of normal map.
  28681. *
  28682. * @type {(TangentSpaceNormalMap|ObjectSpaceNormalMap)}
  28683. * @default TangentSpaceNormalMap
  28684. */
  28685. this.normalMapType = TangentSpaceNormalMap;
  28686. /**
  28687. * How much the normal map affects the material. Typical value range is `[0,1]`.
  28688. *
  28689. * @type {Vector2}
  28690. * @default (1,1)
  28691. */
  28692. this.normalScale = new Vector2( 1, 1 );
  28693. /**
  28694. * The displacement map affects the position of the mesh's vertices. Unlike
  28695. * other maps which only affect the light and shade of the material the
  28696. * displaced vertices can cast shadows, block other objects, and otherwise
  28697. * act as real geometry. The displacement texture is an image where the value
  28698. * of each pixel (white being the highest) is mapped against, and
  28699. * repositions, the vertices of the mesh.
  28700. *
  28701. * @type {?Texture}
  28702. * @default null
  28703. */
  28704. this.displacementMap = null;
  28705. /**
  28706. * How much the displacement map affects the mesh (where black is no
  28707. * displacement, and white is maximum displacement). Without a displacement
  28708. * map set, this value is not applied.
  28709. *
  28710. * @type {number}
  28711. * @default 0
  28712. */
  28713. this.displacementScale = 1;
  28714. /**
  28715. * The offset of the displacement map's values on the mesh's vertices.
  28716. * The bias is added to the scaled sample of the displacement map.
  28717. * Without a displacement map set, this value is not applied.
  28718. *
  28719. * @type {number}
  28720. * @default 0
  28721. */
  28722. this.displacementBias = 0;
  28723. /**
  28724. * Specular map used by the material.
  28725. *
  28726. * @type {?Texture}
  28727. * @default null
  28728. */
  28729. this.specularMap = null;
  28730. /**
  28731. * The alpha map is a grayscale texture that controls the opacity across the
  28732. * surface (black: fully transparent; white: fully opaque).
  28733. *
  28734. * Only the color of the texture is used, ignoring the alpha channel if one
  28735. * exists. For RGB and RGBA textures, the renderer will use the green channel
  28736. * when sampling this texture due to the extra bit of precision provided for
  28737. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  28738. * luminance/alpha textures will also still work as expected.
  28739. *
  28740. * @type {?Texture}
  28741. * @default null
  28742. */
  28743. this.alphaMap = null;
  28744. /**
  28745. * The environment map.
  28746. *
  28747. * @type {?Texture}
  28748. * @default null
  28749. */
  28750. this.envMap = null;
  28751. /**
  28752. * The rotation of the environment map in radians.
  28753. *
  28754. * @type {Euler}
  28755. * @default (0,0,0)
  28756. */
  28757. this.envMapRotation = new Euler();
  28758. /**
  28759. * How to combine the result of the surface's color with the environment map, if any.
  28760. *
  28761. * When set to `MixOperation`, the {@link MeshBasicMaterial#reflectivity} is used to
  28762. * blend between the two colors.
  28763. *
  28764. * @type {(MultiplyOperation|MixOperation|AddOperation)}
  28765. * @default MultiplyOperation
  28766. */
  28767. this.combine = MultiplyOperation;
  28768. /**
  28769. * How much the environment map affects the surface.
  28770. * The valid range is between `0` (no reflections) and `1` (full reflections).
  28771. *
  28772. * @type {number}
  28773. * @default 1
  28774. */
  28775. this.reflectivity = 1;
  28776. /**
  28777. * The index of refraction (IOR) of air (approximately 1) divided by the
  28778. * index of refraction of the material. It is used with environment mapping
  28779. * modes {@link CubeRefractionMapping} and {@link EquirectangularRefractionMapping}.
  28780. * The refraction ratio should not exceed `1`.
  28781. *
  28782. * @type {number}
  28783. * @default 0.98
  28784. */
  28785. this.refractionRatio = 0.98;
  28786. /**
  28787. * Renders the geometry as a wireframe.
  28788. *
  28789. * @type {boolean}
  28790. * @default false
  28791. */
  28792. this.wireframe = false;
  28793. /**
  28794. * Controls the thickness of the wireframe.
  28795. *
  28796. * Can only be used with {@link SVGRenderer}.
  28797. *
  28798. * @type {number}
  28799. * @default 1
  28800. */
  28801. this.wireframeLinewidth = 1;
  28802. /**
  28803. * Defines appearance of wireframe ends.
  28804. *
  28805. * Can only be used with {@link SVGRenderer}.
  28806. *
  28807. * @type {('round'|'bevel'|'miter')}
  28808. * @default 'round'
  28809. */
  28810. this.wireframeLinecap = 'round';
  28811. /**
  28812. * Defines appearance of wireframe joints.
  28813. *
  28814. * Can only be used with {@link SVGRenderer}.
  28815. *
  28816. * @type {('round'|'bevel'|'miter')}
  28817. * @default 'round'
  28818. */
  28819. this.wireframeLinejoin = 'round';
  28820. /**
  28821. * Whether the material is rendered with flat shading or not.
  28822. *
  28823. * @type {boolean}
  28824. * @default false
  28825. */
  28826. this.flatShading = false;
  28827. /**
  28828. * Whether the material is affected by fog or not.
  28829. *
  28830. * @type {boolean}
  28831. * @default true
  28832. */
  28833. this.fog = true;
  28834. this.setValues( parameters );
  28835. }
  28836. copy( source ) {
  28837. super.copy( source );
  28838. this.color.copy( source.color );
  28839. this.map = source.map;
  28840. this.lightMap = source.lightMap;
  28841. this.lightMapIntensity = source.lightMapIntensity;
  28842. this.aoMap = source.aoMap;
  28843. this.aoMapIntensity = source.aoMapIntensity;
  28844. this.emissive.copy( source.emissive );
  28845. this.emissiveMap = source.emissiveMap;
  28846. this.emissiveIntensity = source.emissiveIntensity;
  28847. this.bumpMap = source.bumpMap;
  28848. this.bumpScale = source.bumpScale;
  28849. this.normalMap = source.normalMap;
  28850. this.normalMapType = source.normalMapType;
  28851. this.normalScale.copy( source.normalScale );
  28852. this.displacementMap = source.displacementMap;
  28853. this.displacementScale = source.displacementScale;
  28854. this.displacementBias = source.displacementBias;
  28855. this.specularMap = source.specularMap;
  28856. this.alphaMap = source.alphaMap;
  28857. this.envMap = source.envMap;
  28858. this.envMapRotation.copy( source.envMapRotation );
  28859. this.combine = source.combine;
  28860. this.reflectivity = source.reflectivity;
  28861. this.refractionRatio = source.refractionRatio;
  28862. this.wireframe = source.wireframe;
  28863. this.wireframeLinewidth = source.wireframeLinewidth;
  28864. this.wireframeLinecap = source.wireframeLinecap;
  28865. this.wireframeLinejoin = source.wireframeLinejoin;
  28866. this.flatShading = source.flatShading;
  28867. this.fog = source.fog;
  28868. return this;
  28869. }
  28870. }
  28871. /**
  28872. * A material for drawing geometry by depth. Depth is based off of the camera
  28873. * near and far plane. White is nearest, black is farthest.
  28874. *
  28875. * @augments Material
  28876. */
  28877. class MeshDepthMaterial extends Material {
  28878. /**
  28879. * Constructs a new mesh depth material.
  28880. *
  28881. * @param {Object} [parameters] - An object with one or more properties
  28882. * defining the material's appearance. Any property of the material
  28883. * (including any property from inherited materials) can be passed
  28884. * in here. Color values can be passed any type of value accepted
  28885. * by {@link Color#set}.
  28886. */
  28887. constructor( parameters ) {
  28888. super();
  28889. /**
  28890. * This flag can be used for type testing.
  28891. *
  28892. * @type {boolean}
  28893. * @readonly
  28894. * @default true
  28895. */
  28896. this.isMeshDepthMaterial = true;
  28897. this.type = 'MeshDepthMaterial';
  28898. /**
  28899. * Type for depth packing.
  28900. *
  28901. * @type {(BasicDepthPacking|RGBADepthPacking|RGBDepthPacking|RGDepthPacking)}
  28902. * @default BasicDepthPacking
  28903. */
  28904. this.depthPacking = BasicDepthPacking;
  28905. /**
  28906. * The color map. May optionally include an alpha channel, typically combined
  28907. * with {@link Material#transparent} or {@link Material#alphaTest}.
  28908. *
  28909. * @type {?Texture}
  28910. * @default null
  28911. */
  28912. this.map = null;
  28913. /**
  28914. * The alpha map is a grayscale texture that controls the opacity across the
  28915. * surface (black: fully transparent; white: fully opaque).
  28916. *
  28917. * Only the color of the texture is used, ignoring the alpha channel if one
  28918. * exists. For RGB and RGBA textures, the renderer will use the green channel
  28919. * when sampling this texture due to the extra bit of precision provided for
  28920. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  28921. * luminance/alpha textures will also still work as expected.
  28922. *
  28923. * @type {?Texture}
  28924. * @default null
  28925. */
  28926. this.alphaMap = null;
  28927. /**
  28928. * The displacement map affects the position of the mesh's vertices. Unlike
  28929. * other maps which only affect the light and shade of the material the
  28930. * displaced vertices can cast shadows, block other objects, and otherwise
  28931. * act as real geometry. The displacement texture is an image where the value
  28932. * of each pixel (white being the highest) is mapped against, and
  28933. * repositions, the vertices of the mesh.
  28934. *
  28935. * @type {?Texture}
  28936. * @default null
  28937. */
  28938. this.displacementMap = null;
  28939. /**
  28940. * How much the displacement map affects the mesh (where black is no
  28941. * displacement, and white is maximum displacement). Without a displacement
  28942. * map set, this value is not applied.
  28943. *
  28944. * @type {number}
  28945. * @default 0
  28946. */
  28947. this.displacementScale = 1;
  28948. /**
  28949. * The offset of the displacement map's values on the mesh's vertices.
  28950. * The bias is added to the scaled sample of the displacement map.
  28951. * Without a displacement map set, this value is not applied.
  28952. *
  28953. * @type {number}
  28954. * @default 0
  28955. */
  28956. this.displacementBias = 0;
  28957. /**
  28958. * Renders the geometry as a wireframe.
  28959. *
  28960. * @type {boolean}
  28961. * @default false
  28962. */
  28963. this.wireframe = false;
  28964. /**
  28965. * Controls the thickness of the wireframe.
  28966. *
  28967. * WebGL and WebGPU ignore this property and always render
  28968. * 1 pixel wide lines.
  28969. *
  28970. * @type {number}
  28971. * @default 1
  28972. */
  28973. this.wireframeLinewidth = 1;
  28974. this.setValues( parameters );
  28975. }
  28976. copy( source ) {
  28977. super.copy( source );
  28978. this.depthPacking = source.depthPacking;
  28979. this.map = source.map;
  28980. this.alphaMap = source.alphaMap;
  28981. this.displacementMap = source.displacementMap;
  28982. this.displacementScale = source.displacementScale;
  28983. this.displacementBias = source.displacementBias;
  28984. this.wireframe = source.wireframe;
  28985. this.wireframeLinewidth = source.wireframeLinewidth;
  28986. return this;
  28987. }
  28988. }
  28989. /**
  28990. * A material used internally for implementing shadow mapping with
  28991. * point lights.
  28992. *
  28993. * Can also be used to customize the shadow casting of an object by assigning
  28994. * an instance of `MeshDistanceMaterial` to {@link Object3D#customDistanceMaterial}.
  28995. * The following examples demonstrates this approach in order to ensure
  28996. * transparent parts of objects do no cast shadows.
  28997. *
  28998. * @augments Material
  28999. */
  29000. class MeshDistanceMaterial extends Material {
  29001. /**
  29002. * Constructs a new mesh distance material.
  29003. *
  29004. * @param {Object} [parameters] - An object with one or more properties
  29005. * defining the material's appearance. Any property of the material
  29006. * (including any property from inherited materials) can be passed
  29007. * in here. Color values can be passed any type of value accepted
  29008. * by {@link Color#set}.
  29009. */
  29010. constructor( parameters ) {
  29011. super();
  29012. /**
  29013. * This flag can be used for type testing.
  29014. *
  29015. * @type {boolean}
  29016. * @readonly
  29017. * @default true
  29018. */
  29019. this.isMeshDistanceMaterial = true;
  29020. this.type = 'MeshDistanceMaterial';
  29021. /**
  29022. * The color map. May optionally include an alpha channel, typically combined
  29023. * with {@link Material#transparent} or {@link Material#alphaTest}.
  29024. *
  29025. * @type {?Texture}
  29026. * @default null
  29027. */
  29028. this.map = null;
  29029. /**
  29030. * The alpha map is a grayscale texture that controls the opacity across the
  29031. * surface (black: fully transparent; white: fully opaque).
  29032. *
  29033. * Only the color of the texture is used, ignoring the alpha channel if one
  29034. * exists. For RGB and RGBA textures, the renderer will use the green channel
  29035. * when sampling this texture due to the extra bit of precision provided for
  29036. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  29037. * luminance/alpha textures will also still work as expected.
  29038. *
  29039. * @type {?Texture}
  29040. * @default null
  29041. */
  29042. this.alphaMap = null;
  29043. /**
  29044. * The displacement map affects the position of the mesh's vertices. Unlike
  29045. * other maps which only affect the light and shade of the material the
  29046. * displaced vertices can cast shadows, block other objects, and otherwise
  29047. * act as real geometry. The displacement texture is an image where the value
  29048. * of each pixel (white being the highest) is mapped against, and
  29049. * repositions, the vertices of the mesh.
  29050. *
  29051. * @type {?Texture}
  29052. * @default null
  29053. */
  29054. this.displacementMap = null;
  29055. /**
  29056. * How much the displacement map affects the mesh (where black is no
  29057. * displacement, and white is maximum displacement). Without a displacement
  29058. * map set, this value is not applied.
  29059. *
  29060. * @type {number}
  29061. * @default 0
  29062. */
  29063. this.displacementScale = 1;
  29064. /**
  29065. * The offset of the displacement map's values on the mesh's vertices.
  29066. * The bias is added to the scaled sample of the displacement map.
  29067. * Without a displacement map set, this value is not applied.
  29068. *
  29069. * @type {number}
  29070. * @default 0
  29071. */
  29072. this.displacementBias = 0;
  29073. this.setValues( parameters );
  29074. }
  29075. copy( source ) {
  29076. super.copy( source );
  29077. this.map = source.map;
  29078. this.alphaMap = source.alphaMap;
  29079. this.displacementMap = source.displacementMap;
  29080. this.displacementScale = source.displacementScale;
  29081. this.displacementBias = source.displacementBias;
  29082. return this;
  29083. }
  29084. }
  29085. /**
  29086. * This material is defined by a MatCap (or Lit Sphere) texture, which encodes the
  29087. * material color and shading.
  29088. *
  29089. * `MeshMatcapMaterial` does not respond to lights since the matcap image file encodes
  29090. * baked lighting. It will cast a shadow onto an object that receives shadows
  29091. * (and shadow clipping works), but it will not self-shadow or receive
  29092. * shadows.
  29093. *
  29094. * @augments Material
  29095. */
  29096. class MeshMatcapMaterial extends Material {
  29097. /**
  29098. * Constructs a new mesh matcap material.
  29099. *
  29100. * @param {Object} [parameters] - An object with one or more properties
  29101. * defining the material's appearance. Any property of the material
  29102. * (including any property from inherited materials) can be passed
  29103. * in here. Color values can be passed any type of value accepted
  29104. * by {@link Color#set}.
  29105. */
  29106. constructor( parameters ) {
  29107. super();
  29108. /**
  29109. * This flag can be used for type testing.
  29110. *
  29111. * @type {boolean}
  29112. * @readonly
  29113. * @default true
  29114. */
  29115. this.isMeshMatcapMaterial = true;
  29116. this.defines = { 'MATCAP': '' };
  29117. this.type = 'MeshMatcapMaterial';
  29118. /**
  29119. * Color of the material.
  29120. *
  29121. * @type {Color}
  29122. * @default (1,1,1)
  29123. */
  29124. this.color = new Color( 0xffffff ); // diffuse
  29125. /**
  29126. * The matcap map.
  29127. *
  29128. * @type {?Texture}
  29129. * @default null
  29130. */
  29131. this.matcap = null;
  29132. /**
  29133. * The color map. May optionally include an alpha channel, typically combined
  29134. * with {@link Material#transparent} or {@link Material#alphaTest}. The texture map
  29135. * color is modulated by the diffuse `color`.
  29136. *
  29137. * @type {?Texture}
  29138. * @default null
  29139. */
  29140. this.map = null;
  29141. /**
  29142. * The texture to create a bump map. The black and white values map to the
  29143. * perceived depth in relation to the lights. Bump doesn't actually affect
  29144. * the geometry of the object, only the lighting. If a normal map is defined
  29145. * this will be ignored.
  29146. *
  29147. * @type {?Texture}
  29148. * @default null
  29149. */
  29150. this.bumpMap = null;
  29151. /**
  29152. * How much the bump map affects the material. Typical range is `[0,1]`.
  29153. *
  29154. * @type {number}
  29155. * @default 1
  29156. */
  29157. this.bumpScale = 1;
  29158. /**
  29159. * The texture to create a normal map. The RGB values affect the surface
  29160. * normal for each pixel fragment and change the way the color is lit. Normal
  29161. * maps do not change the actual shape of the surface, only the lighting. In
  29162. * case the material has a normal map authored using the left handed
  29163. * convention, the `y` component of `normalScale` should be negated to compensate
  29164. * for the different handedness.
  29165. *
  29166. * @type {?Texture}
  29167. * @default null
  29168. */
  29169. this.normalMap = null;
  29170. /**
  29171. * The type of normal map.
  29172. *
  29173. * @type {(TangentSpaceNormalMap|ObjectSpaceNormalMap)}
  29174. * @default TangentSpaceNormalMap
  29175. */
  29176. this.normalMapType = TangentSpaceNormalMap;
  29177. /**
  29178. * How much the normal map affects the material. Typical value range is `[0,1]`.
  29179. *
  29180. * @type {Vector2}
  29181. * @default (1,1)
  29182. */
  29183. this.normalScale = new Vector2( 1, 1 );
  29184. /**
  29185. * The displacement map affects the position of the mesh's vertices. Unlike
  29186. * other maps which only affect the light and shade of the material the
  29187. * displaced vertices can cast shadows, block other objects, and otherwise
  29188. * act as real geometry. The displacement texture is an image where the value
  29189. * of each pixel (white being the highest) is mapped against, and
  29190. * repositions, the vertices of the mesh.
  29191. *
  29192. * @type {?Texture}
  29193. * @default null
  29194. */
  29195. this.displacementMap = null;
  29196. /**
  29197. * How much the displacement map affects the mesh (where black is no
  29198. * displacement, and white is maximum displacement). Without a displacement
  29199. * map set, this value is not applied.
  29200. *
  29201. * @type {number}
  29202. * @default 0
  29203. */
  29204. this.displacementScale = 1;
  29205. /**
  29206. * The offset of the displacement map's values on the mesh's vertices.
  29207. * The bias is added to the scaled sample of the displacement map.
  29208. * Without a displacement map set, this value is not applied.
  29209. *
  29210. * @type {number}
  29211. * @default 0
  29212. */
  29213. this.displacementBias = 0;
  29214. /**
  29215. * The alpha map is a grayscale texture that controls the opacity across the
  29216. * surface (black: fully transparent; white: fully opaque).
  29217. *
  29218. * Only the color of the texture is used, ignoring the alpha channel if one
  29219. * exists. For RGB and RGBA textures, the renderer will use the green channel
  29220. * when sampling this texture due to the extra bit of precision provided for
  29221. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  29222. * luminance/alpha textures will also still work as expected.
  29223. *
  29224. * @type {?Texture}
  29225. * @default null
  29226. */
  29227. this.alphaMap = null;
  29228. /**
  29229. * Whether the material is rendered with flat shading or not.
  29230. *
  29231. * @type {boolean}
  29232. * @default false
  29233. */
  29234. this.flatShading = false;
  29235. /**
  29236. * Whether the material is affected by fog or not.
  29237. *
  29238. * @type {boolean}
  29239. * @default true
  29240. */
  29241. this.fog = true;
  29242. this.setValues( parameters );
  29243. }
  29244. copy( source ) {
  29245. super.copy( source );
  29246. this.defines = { 'MATCAP': '' };
  29247. this.color.copy( source.color );
  29248. this.matcap = source.matcap;
  29249. this.map = source.map;
  29250. this.bumpMap = source.bumpMap;
  29251. this.bumpScale = source.bumpScale;
  29252. this.normalMap = source.normalMap;
  29253. this.normalMapType = source.normalMapType;
  29254. this.normalScale.copy( source.normalScale );
  29255. this.displacementMap = source.displacementMap;
  29256. this.displacementScale = source.displacementScale;
  29257. this.displacementBias = source.displacementBias;
  29258. this.alphaMap = source.alphaMap;
  29259. this.flatShading = source.flatShading;
  29260. this.fog = source.fog;
  29261. return this;
  29262. }
  29263. }
  29264. /**
  29265. * A material for rendering line primitives.
  29266. *
  29267. * Materials define the appearance of renderable 3D objects.
  29268. *
  29269. * ```js
  29270. * const material = new THREE.LineDashedMaterial( {
  29271. * color: 0xffffff,
  29272. * scale: 1,
  29273. * dashSize: 3,
  29274. * gapSize: 1,
  29275. * } );
  29276. * ```
  29277. *
  29278. * @augments LineBasicMaterial
  29279. */
  29280. class LineDashedMaterial extends LineBasicMaterial {
  29281. /**
  29282. * Constructs a new line dashed material.
  29283. *
  29284. * @param {Object} [parameters] - An object with one or more properties
  29285. * defining the material's appearance. Any property of the material
  29286. * (including any property from inherited materials) can be passed
  29287. * in here. Color values can be passed any type of value accepted
  29288. * by {@link Color#set}.
  29289. */
  29290. constructor( parameters ) {
  29291. super();
  29292. /**
  29293. * This flag can be used for type testing.
  29294. *
  29295. * @type {boolean}
  29296. * @readonly
  29297. * @default true
  29298. */
  29299. this.isLineDashedMaterial = true;
  29300. this.type = 'LineDashedMaterial';
  29301. /**
  29302. * The scale of the dashed part of a line.
  29303. *
  29304. * @type {number}
  29305. * @default 1
  29306. */
  29307. this.scale = 1;
  29308. /**
  29309. * The size of the dash. This is both the gap with the stroke.
  29310. *
  29311. * @type {number}
  29312. * @default 3
  29313. */
  29314. this.dashSize = 3;
  29315. /**
  29316. * The size of the gap.
  29317. *
  29318. * @type {number}
  29319. * @default 1
  29320. */
  29321. this.gapSize = 1;
  29322. this.setValues( parameters );
  29323. }
  29324. copy( source ) {
  29325. super.copy( source );
  29326. this.scale = source.scale;
  29327. this.dashSize = source.dashSize;
  29328. this.gapSize = source.gapSize;
  29329. return this;
  29330. }
  29331. }
  29332. /**
  29333. * Converts an array to a specific type.
  29334. *
  29335. * @param {TypedArray|Array} array - The array to convert.
  29336. * @param {TypedArray.constructor} type - The constructor of a typed array that defines the new type.
  29337. * @return {TypedArray} The converted array.
  29338. */
  29339. function convertArray( array, type ) {
  29340. if ( ! array || array.constructor === type ) return array;
  29341. if ( typeof type.BYTES_PER_ELEMENT === 'number' ) {
  29342. return new type( array ); // create typed array
  29343. }
  29344. return Array.prototype.slice.call( array ); // create Array
  29345. }
  29346. /**
  29347. * Returns `true` if the given object is a typed array.
  29348. *
  29349. * @param {any} object - The object to check.
  29350. * @return {boolean} Whether the given object is a typed array.
  29351. */
  29352. function isTypedArray( object ) {
  29353. return ArrayBuffer.isView( object ) && ! ( object instanceof DataView );
  29354. }
  29355. /**
  29356. * Returns an array by which times and values can be sorted.
  29357. *
  29358. * @param {Array<number>} times - The keyframe time values.
  29359. * @return {Array<number>} The array.
  29360. */
  29361. function getKeyframeOrder( times ) {
  29362. function compareTime( i, j ) {
  29363. return times[ i ] - times[ j ];
  29364. }
  29365. const n = times.length;
  29366. const result = new Array( n );
  29367. for ( let i = 0; i !== n; ++ i ) result[ i ] = i;
  29368. result.sort( compareTime );
  29369. return result;
  29370. }
  29371. /**
  29372. * Sorts the given array by the previously computed order via `getKeyframeOrder()`.
  29373. *
  29374. * @param {Array<number>} values - The values to sort.
  29375. * @param {number} stride - The stride.
  29376. * @param {Array<number>} order - The sort order.
  29377. * @return {Array<number>} The sorted values.
  29378. */
  29379. function sortedArray( values, stride, order ) {
  29380. const nValues = values.length;
  29381. const result = new values.constructor( nValues );
  29382. for ( let i = 0, dstOffset = 0; dstOffset !== nValues; ++ i ) {
  29383. const srcOffset = order[ i ] * stride;
  29384. for ( let j = 0; j !== stride; ++ j ) {
  29385. result[ dstOffset ++ ] = values[ srcOffset + j ];
  29386. }
  29387. }
  29388. return result;
  29389. }
  29390. /**
  29391. * Used for parsing AOS keyframe formats.
  29392. *
  29393. * @param {Array<number>} jsonKeys - A list of JSON keyframes.
  29394. * @param {Array<number>} times - This array will be filled with keyframe times by this function.
  29395. * @param {Array<number>} values - This array will be filled with keyframe values by this function.
  29396. * @param {string} valuePropertyName - The name of the property to use.
  29397. */
  29398. function flattenJSON( jsonKeys, times, values, valuePropertyName ) {
  29399. let i = 1, key = jsonKeys[ 0 ];
  29400. while ( key !== undefined && key[ valuePropertyName ] === undefined ) {
  29401. key = jsonKeys[ i ++ ];
  29402. }
  29403. if ( key === undefined ) return; // no data
  29404. let value = key[ valuePropertyName ];
  29405. if ( value === undefined ) return; // no data
  29406. if ( Array.isArray( value ) ) {
  29407. do {
  29408. value = key[ valuePropertyName ];
  29409. if ( value !== undefined ) {
  29410. times.push( key.time );
  29411. values.push( ...value ); // push all elements
  29412. }
  29413. key = jsonKeys[ i ++ ];
  29414. } while ( key !== undefined );
  29415. } else if ( value.toArray !== undefined ) {
  29416. // ...assume THREE.Math-ish
  29417. do {
  29418. value = key[ valuePropertyName ];
  29419. if ( value !== undefined ) {
  29420. times.push( key.time );
  29421. value.toArray( values, values.length );
  29422. }
  29423. key = jsonKeys[ i ++ ];
  29424. } while ( key !== undefined );
  29425. } else {
  29426. // otherwise push as-is
  29427. do {
  29428. value = key[ valuePropertyName ];
  29429. if ( value !== undefined ) {
  29430. times.push( key.time );
  29431. values.push( value );
  29432. }
  29433. key = jsonKeys[ i ++ ];
  29434. } while ( key !== undefined );
  29435. }
  29436. }
  29437. /**
  29438. * Creates a new clip, containing only the segment of the original clip between the given frames.
  29439. *
  29440. * @param {AnimationClip} sourceClip - The values to sort.
  29441. * @param {string} name - The name of the clip.
  29442. * @param {number} startFrame - The start frame.
  29443. * @param {number} endFrame - The end frame.
  29444. * @param {number} [fps=30] - The FPS.
  29445. * @return {AnimationClip} The new sub clip.
  29446. */
  29447. function subclip( sourceClip, name, startFrame, endFrame, fps = 30 ) {
  29448. const clip = sourceClip.clone();
  29449. clip.name = name;
  29450. const tracks = [];
  29451. for ( let i = 0; i < clip.tracks.length; ++ i ) {
  29452. const track = clip.tracks[ i ];
  29453. const valueSize = track.getValueSize();
  29454. const times = [];
  29455. const values = [];
  29456. for ( let j = 0; j < track.times.length; ++ j ) {
  29457. const frame = track.times[ j ] * fps;
  29458. if ( frame < startFrame || frame >= endFrame ) continue;
  29459. times.push( track.times[ j ] );
  29460. for ( let k = 0; k < valueSize; ++ k ) {
  29461. values.push( track.values[ j * valueSize + k ] );
  29462. }
  29463. }
  29464. if ( times.length === 0 ) continue;
  29465. track.times = convertArray( times, track.times.constructor );
  29466. track.values = convertArray( values, track.values.constructor );
  29467. tracks.push( track );
  29468. }
  29469. clip.tracks = tracks;
  29470. // find minimum .times value across all tracks in the trimmed clip
  29471. let minStartTime = Infinity;
  29472. for ( let i = 0; i < clip.tracks.length; ++ i ) {
  29473. if ( minStartTime > clip.tracks[ i ].times[ 0 ] ) {
  29474. minStartTime = clip.tracks[ i ].times[ 0 ];
  29475. }
  29476. }
  29477. // shift all tracks such that clip begins at t=0
  29478. for ( let i = 0; i < clip.tracks.length; ++ i ) {
  29479. clip.tracks[ i ].shift( -1 * minStartTime );
  29480. }
  29481. clip.resetDuration();
  29482. return clip;
  29483. }
  29484. /**
  29485. * Converts the keyframes of the given animation clip to an additive format.
  29486. *
  29487. * @param {AnimationClip} targetClip - The clip to make additive.
  29488. * @param {number} [referenceFrame=0] - The reference frame.
  29489. * @param {AnimationClip} [referenceClip=targetClip] - The reference clip.
  29490. * @param {number} [fps=30] - The FPS.
  29491. * @return {AnimationClip} The updated clip which is now additive.
  29492. */
  29493. function makeClipAdditive( targetClip, referenceFrame = 0, referenceClip = targetClip, fps = 30 ) {
  29494. if ( fps <= 0 ) fps = 30;
  29495. const numTracks = referenceClip.tracks.length;
  29496. const referenceTime = referenceFrame / fps;
  29497. // Make each track's values relative to the values at the reference frame
  29498. for ( let i = 0; i < numTracks; ++ i ) {
  29499. const referenceTrack = referenceClip.tracks[ i ];
  29500. const referenceTrackType = referenceTrack.ValueTypeName;
  29501. // Skip this track if it's non-numeric
  29502. if ( referenceTrackType === 'bool' || referenceTrackType === 'string' ) continue;
  29503. // Find the track in the target clip whose name and type matches the reference track
  29504. const targetTrack = targetClip.tracks.find( function ( track ) {
  29505. return track.name === referenceTrack.name
  29506. && track.ValueTypeName === referenceTrackType;
  29507. } );
  29508. if ( targetTrack === undefined ) continue;
  29509. let referenceOffset = 0;
  29510. const referenceValueSize = referenceTrack.getValueSize();
  29511. if ( referenceTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline ) {
  29512. referenceOffset = referenceValueSize / 3;
  29513. }
  29514. let targetOffset = 0;
  29515. const targetValueSize = targetTrack.getValueSize();
  29516. if ( targetTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline ) {
  29517. targetOffset = targetValueSize / 3;
  29518. }
  29519. const lastIndex = referenceTrack.times.length - 1;
  29520. let referenceValue;
  29521. // Find the value to subtract out of the track
  29522. if ( referenceTime <= referenceTrack.times[ 0 ] ) {
  29523. // Reference frame is earlier than the first keyframe, so just use the first keyframe
  29524. const startIndex = referenceOffset;
  29525. const endIndex = referenceValueSize - referenceOffset;
  29526. referenceValue = referenceTrack.values.slice( startIndex, endIndex );
  29527. } else if ( referenceTime >= referenceTrack.times[ lastIndex ] ) {
  29528. // Reference frame is after the last keyframe, so just use the last keyframe
  29529. const startIndex = lastIndex * referenceValueSize + referenceOffset;
  29530. const endIndex = startIndex + referenceValueSize - referenceOffset;
  29531. referenceValue = referenceTrack.values.slice( startIndex, endIndex );
  29532. } else {
  29533. // Interpolate to the reference value
  29534. const interpolant = referenceTrack.createInterpolant();
  29535. const startIndex = referenceOffset;
  29536. const endIndex = referenceValueSize - referenceOffset;
  29537. interpolant.evaluate( referenceTime );
  29538. referenceValue = interpolant.resultBuffer.slice( startIndex, endIndex );
  29539. }
  29540. // Conjugate the quaternion
  29541. if ( referenceTrackType === 'quaternion' ) {
  29542. const referenceQuat = new Quaternion().fromArray( referenceValue ).normalize().conjugate();
  29543. referenceQuat.toArray( referenceValue );
  29544. }
  29545. // Subtract the reference value from all of the track values
  29546. const numTimes = targetTrack.times.length;
  29547. for ( let j = 0; j < numTimes; ++ j ) {
  29548. const valueStart = j * targetValueSize + targetOffset;
  29549. if ( referenceTrackType === 'quaternion' ) {
  29550. // Multiply the conjugate for quaternion track types
  29551. Quaternion.multiplyQuaternionsFlat(
  29552. targetTrack.values,
  29553. valueStart,
  29554. referenceValue,
  29555. 0,
  29556. targetTrack.values,
  29557. valueStart
  29558. );
  29559. } else {
  29560. const valueEnd = targetValueSize - targetOffset * 2;
  29561. // Subtract each value for all other numeric track types
  29562. for ( let k = 0; k < valueEnd; ++ k ) {
  29563. targetTrack.values[ valueStart + k ] -= referenceValue[ k ];
  29564. }
  29565. }
  29566. }
  29567. }
  29568. targetClip.blendMode = AdditiveAnimationBlendMode;
  29569. return targetClip;
  29570. }
  29571. /**
  29572. * A class with various methods to assist with animations.
  29573. *
  29574. * @hideconstructor
  29575. */
  29576. class AnimationUtils {
  29577. /**
  29578. * Converts an array to a specific type
  29579. *
  29580. * @static
  29581. * @param {TypedArray|Array} array - The array to convert.
  29582. * @param {TypedArray.constructor} type - The constructor of a type array.
  29583. * @return {TypedArray} The converted array
  29584. */
  29585. static convertArray( array, type ) {
  29586. return convertArray( array, type );
  29587. }
  29588. /**
  29589. * Returns `true` if the given object is a typed array.
  29590. *
  29591. * @static
  29592. * @param {any} object - The object to check.
  29593. * @return {boolean} Whether the given object is a typed array.
  29594. */
  29595. static isTypedArray( object ) {
  29596. return isTypedArray( object );
  29597. }
  29598. /**
  29599. * Returns an array by which times and values can be sorted.
  29600. *
  29601. * @static
  29602. * @param {Array<number>} times - The keyframe time values.
  29603. * @return {Array<number>} The array.
  29604. */
  29605. static getKeyframeOrder( times ) {
  29606. return getKeyframeOrder( times );
  29607. }
  29608. /**
  29609. * Sorts the given array by the previously computed order via `getKeyframeOrder()`.
  29610. *
  29611. * @static
  29612. * @param {Array<number>} values - The values to sort.
  29613. * @param {number} stride - The stride.
  29614. * @param {Array<number>} order - The sort order.
  29615. * @return {Array<number>} The sorted values.
  29616. */
  29617. static sortedArray( values, stride, order ) {
  29618. return sortedArray( values, stride, order );
  29619. }
  29620. /**
  29621. * Used for parsing AOS keyframe formats.
  29622. *
  29623. * @static
  29624. * @param {Array<number>} jsonKeys - A list of JSON keyframes.
  29625. * @param {Array<number>} times - This array will be filled with keyframe times by this method.
  29626. * @param {Array<number>} values - This array will be filled with keyframe values by this method.
  29627. * @param {string} valuePropertyName - The name of the property to use.
  29628. */
  29629. static flattenJSON( jsonKeys, times, values, valuePropertyName ) {
  29630. flattenJSON( jsonKeys, times, values, valuePropertyName );
  29631. }
  29632. /**
  29633. * Creates a new clip, containing only the segment of the original clip between the given frames.
  29634. *
  29635. * @static
  29636. * @param {AnimationClip} sourceClip - The values to sort.
  29637. * @param {string} name - The name of the clip.
  29638. * @param {number} startFrame - The start frame.
  29639. * @param {number} endFrame - The end frame.
  29640. * @param {number} [fps=30] - The FPS.
  29641. * @return {AnimationClip} The new sub clip.
  29642. */
  29643. static subclip( sourceClip, name, startFrame, endFrame, fps = 30 ) {
  29644. return subclip( sourceClip, name, startFrame, endFrame, fps );
  29645. }
  29646. /**
  29647. * Converts the keyframes of the given animation clip to an additive format.
  29648. *
  29649. * @static
  29650. * @param {AnimationClip} targetClip - The clip to make additive.
  29651. * @param {number} [referenceFrame=0] - The reference frame.
  29652. * @param {AnimationClip} [referenceClip=targetClip] - The reference clip.
  29653. * @param {number} [fps=30] - The FPS.
  29654. * @return {AnimationClip} The updated clip which is now additive.
  29655. */
  29656. static makeClipAdditive( targetClip, referenceFrame = 0, referenceClip = targetClip, fps = 30 ) {
  29657. return makeClipAdditive( targetClip, referenceFrame, referenceClip, fps );
  29658. }
  29659. }
  29660. /**
  29661. * Abstract base class of interpolants over parametric samples.
  29662. *
  29663. * The parameter domain is one dimensional, typically the time or a path
  29664. * along a curve defined by the data.
  29665. *
  29666. * The sample values can have any dimensionality and derived classes may
  29667. * apply special interpretations to the data.
  29668. *
  29669. * This class provides the interval seek in a Template Method, deferring
  29670. * the actual interpolation to derived classes.
  29671. *
  29672. * Time complexity is O(1) for linear access crossing at most two points
  29673. * and O(log N) for random access, where N is the number of positions.
  29674. *
  29675. * References: {@link http://www.oodesign.com/template-method-pattern.html}
  29676. *
  29677. * @abstract
  29678. */
  29679. class Interpolant {
  29680. /**
  29681. * Constructs a new interpolant.
  29682. *
  29683. * @param {TypedArray} parameterPositions - The parameter positions hold the interpolation factors.
  29684. * @param {TypedArray} sampleValues - The sample values.
  29685. * @param {number} sampleSize - The sample size
  29686. * @param {TypedArray} [resultBuffer] - The result buffer.
  29687. */
  29688. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  29689. /**
  29690. * The parameter positions.
  29691. *
  29692. * @type {TypedArray}
  29693. */
  29694. this.parameterPositions = parameterPositions;
  29695. /**
  29696. * A cache index.
  29697. *
  29698. * @private
  29699. * @type {number}
  29700. * @default 0
  29701. */
  29702. this._cachedIndex = 0;
  29703. /**
  29704. * The result buffer.
  29705. *
  29706. * @type {TypedArray}
  29707. */
  29708. this.resultBuffer = resultBuffer !== undefined ? resultBuffer : new sampleValues.constructor( sampleSize );
  29709. /**
  29710. * The sample values.
  29711. *
  29712. * @type {TypedArray}
  29713. */
  29714. this.sampleValues = sampleValues;
  29715. /**
  29716. * The value size.
  29717. *
  29718. * @type {TypedArray}
  29719. */
  29720. this.valueSize = sampleSize;
  29721. /**
  29722. * The interpolation settings.
  29723. *
  29724. * @type {?Object}
  29725. * @default null
  29726. */
  29727. this.settings = null;
  29728. /**
  29729. * The default settings object.
  29730. *
  29731. * @type {Object}
  29732. */
  29733. this.DefaultSettings_ = {};
  29734. }
  29735. /**
  29736. * Evaluate the interpolant at position `t`.
  29737. *
  29738. * @param {number} t - The interpolation factor.
  29739. * @return {TypedArray} The result buffer.
  29740. */
  29741. evaluate( t ) {
  29742. const pp = this.parameterPositions;
  29743. let i1 = this._cachedIndex,
  29744. t1 = pp[ i1 ],
  29745. t0 = pp[ i1 - 1 ];
  29746. validate_interval: {
  29747. seek: {
  29748. let right;
  29749. linear_scan: {
  29750. //- See http://jsperf.com/comparison-to-undefined/3
  29751. //- slower code:
  29752. //-
  29753. //- if ( t >= t1 || t1 === undefined ) {
  29754. forward_scan: if ( ! ( t < t1 ) ) {
  29755. for ( let giveUpAt = i1 + 2; ; ) {
  29756. if ( t1 === undefined ) {
  29757. if ( t < t0 ) break forward_scan;
  29758. // after end
  29759. i1 = pp.length;
  29760. this._cachedIndex = i1;
  29761. return this.copySampleValue_( i1 - 1 );
  29762. }
  29763. if ( i1 === giveUpAt ) break; // this loop
  29764. t0 = t1;
  29765. t1 = pp[ ++ i1 ];
  29766. if ( t < t1 ) {
  29767. // we have arrived at the sought interval
  29768. break seek;
  29769. }
  29770. }
  29771. // prepare binary search on the right side of the index
  29772. right = pp.length;
  29773. break linear_scan;
  29774. }
  29775. //- slower code:
  29776. //- if ( t < t0 || t0 === undefined ) {
  29777. if ( ! ( t >= t0 ) ) {
  29778. // looping?
  29779. const t1global = pp[ 1 ];
  29780. if ( t < t1global ) {
  29781. i1 = 2; // + 1, using the scan for the details
  29782. t0 = t1global;
  29783. }
  29784. // linear reverse scan
  29785. for ( let giveUpAt = i1 - 2; ; ) {
  29786. if ( t0 === undefined ) {
  29787. // before start
  29788. this._cachedIndex = 0;
  29789. return this.copySampleValue_( 0 );
  29790. }
  29791. if ( i1 === giveUpAt ) break; // this loop
  29792. t1 = t0;
  29793. t0 = pp[ -- i1 - 1 ];
  29794. if ( t >= t0 ) {
  29795. // we have arrived at the sought interval
  29796. break seek;
  29797. }
  29798. }
  29799. // prepare binary search on the left side of the index
  29800. right = i1;
  29801. i1 = 0;
  29802. break linear_scan;
  29803. }
  29804. // the interval is valid
  29805. break validate_interval;
  29806. } // linear scan
  29807. // binary search
  29808. while ( i1 < right ) {
  29809. const mid = ( i1 + right ) >>> 1;
  29810. if ( t < pp[ mid ] ) {
  29811. right = mid;
  29812. } else {
  29813. i1 = mid + 1;
  29814. }
  29815. }
  29816. t1 = pp[ i1 ];
  29817. t0 = pp[ i1 - 1 ];
  29818. // check boundary cases, again
  29819. if ( t0 === undefined ) {
  29820. this._cachedIndex = 0;
  29821. return this.copySampleValue_( 0 );
  29822. }
  29823. if ( t1 === undefined ) {
  29824. i1 = pp.length;
  29825. this._cachedIndex = i1;
  29826. return this.copySampleValue_( i1 - 1 );
  29827. }
  29828. } // seek
  29829. this._cachedIndex = i1;
  29830. this.intervalChanged_( i1, t0, t1 );
  29831. } // validate_interval
  29832. return this.interpolate_( i1, t0, t, t1 );
  29833. }
  29834. /**
  29835. * Returns the interpolation settings.
  29836. *
  29837. * @return {Object} The interpolation settings.
  29838. */
  29839. getSettings_() {
  29840. return this.settings || this.DefaultSettings_;
  29841. }
  29842. /**
  29843. * Copies a sample value to the result buffer.
  29844. *
  29845. * @param {number} index - An index into the sample value buffer.
  29846. * @return {TypedArray} The result buffer.
  29847. */
  29848. copySampleValue_( index ) {
  29849. // copies a sample value to the result buffer
  29850. const result = this.resultBuffer,
  29851. values = this.sampleValues,
  29852. stride = this.valueSize,
  29853. offset = index * stride;
  29854. for ( let i = 0; i !== stride; ++ i ) {
  29855. result[ i ] = values[ offset + i ];
  29856. }
  29857. return result;
  29858. }
  29859. /**
  29860. * Copies a sample value to the result buffer.
  29861. *
  29862. * @abstract
  29863. * @param {number} i1 - An index into the sample value buffer.
  29864. * @param {number} t0 - The previous interpolation factor.
  29865. * @param {number} t - The current interpolation factor.
  29866. * @param {number} t1 - The next interpolation factor.
  29867. * @return {TypedArray} The result buffer.
  29868. */
  29869. interpolate_( /* i1, t0, t, t1 */ ) {
  29870. throw new Error( 'call to abstract method' );
  29871. // implementations shall return this.resultBuffer
  29872. }
  29873. /**
  29874. * Optional method that is executed when the interval has changed.
  29875. *
  29876. * @param {number} i1 - An index into the sample value buffer.
  29877. * @param {number} t0 - The previous interpolation factor.
  29878. * @param {number} t - The current interpolation factor.
  29879. */
  29880. intervalChanged_( /* i1, t0, t1 */ ) {
  29881. // empty
  29882. }
  29883. }
  29884. /**
  29885. * Fast and simple cubic spline interpolant.
  29886. *
  29887. * It was derived from a Hermitian construction setting the first derivative
  29888. * at each sample position to the linear slope between neighboring positions
  29889. * over their parameter interval.
  29890. *
  29891. * @augments Interpolant
  29892. */
  29893. class CubicInterpolant extends Interpolant {
  29894. /**
  29895. * Constructs a new cubic interpolant.
  29896. *
  29897. * @param {TypedArray} parameterPositions - The parameter positions hold the interpolation factors.
  29898. * @param {TypedArray} sampleValues - The sample values.
  29899. * @param {number} sampleSize - The sample size
  29900. * @param {TypedArray} [resultBuffer] - The result buffer.
  29901. */
  29902. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  29903. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  29904. this._weightPrev = -0;
  29905. this._offsetPrev = -0;
  29906. this._weightNext = -0;
  29907. this._offsetNext = -0;
  29908. this.DefaultSettings_ = {
  29909. endingStart: ZeroCurvatureEnding,
  29910. endingEnd: ZeroCurvatureEnding
  29911. };
  29912. }
  29913. intervalChanged_( i1, t0, t1 ) {
  29914. const pp = this.parameterPositions;
  29915. let iPrev = i1 - 2,
  29916. iNext = i1 + 1,
  29917. tPrev = pp[ iPrev ],
  29918. tNext = pp[ iNext ];
  29919. if ( tPrev === undefined ) {
  29920. switch ( this.getSettings_().endingStart ) {
  29921. case ZeroSlopeEnding:
  29922. // f'(t0) = 0
  29923. iPrev = i1;
  29924. tPrev = 2 * t0 - t1;
  29925. break;
  29926. case WrapAroundEnding:
  29927. // use the other end of the curve
  29928. iPrev = pp.length - 2;
  29929. tPrev = t0 + pp[ iPrev ] - pp[ iPrev + 1 ];
  29930. break;
  29931. default: // ZeroCurvatureEnding
  29932. // f''(t0) = 0 a.k.a. Natural Spline
  29933. iPrev = i1;
  29934. tPrev = t1;
  29935. }
  29936. }
  29937. if ( tNext === undefined ) {
  29938. switch ( this.getSettings_().endingEnd ) {
  29939. case ZeroSlopeEnding:
  29940. // f'(tN) = 0
  29941. iNext = i1;
  29942. tNext = 2 * t1 - t0;
  29943. break;
  29944. case WrapAroundEnding:
  29945. // use the other end of the curve
  29946. iNext = 1;
  29947. tNext = t1 + pp[ 1 ] - pp[ 0 ];
  29948. break;
  29949. default: // ZeroCurvatureEnding
  29950. // f''(tN) = 0, a.k.a. Natural Spline
  29951. iNext = i1 - 1;
  29952. tNext = t0;
  29953. }
  29954. }
  29955. const halfDt = ( t1 - t0 ) * 0.5,
  29956. stride = this.valueSize;
  29957. this._weightPrev = halfDt / ( t0 - tPrev );
  29958. this._weightNext = halfDt / ( tNext - t1 );
  29959. this._offsetPrev = iPrev * stride;
  29960. this._offsetNext = iNext * stride;
  29961. }
  29962. interpolate_( i1, t0, t, t1 ) {
  29963. const result = this.resultBuffer,
  29964. values = this.sampleValues,
  29965. stride = this.valueSize,
  29966. o1 = i1 * stride, o0 = o1 - stride,
  29967. oP = this._offsetPrev, oN = this._offsetNext,
  29968. wP = this._weightPrev, wN = this._weightNext,
  29969. p = ( t - t0 ) / ( t1 - t0 ),
  29970. pp = p * p,
  29971. ppp = pp * p;
  29972. // evaluate polynomials
  29973. const sP = - wP * ppp + 2 * wP * pp - wP * p;
  29974. const s0 = ( 1 + wP ) * ppp + ( -1.5 - 2 * wP ) * pp + ( -0.5 + wP ) * p + 1;
  29975. const s1 = ( -1 - wN ) * ppp + ( 1.5 + wN ) * pp + 0.5 * p;
  29976. const sN = wN * ppp - wN * pp;
  29977. // combine data linearly
  29978. for ( let i = 0; i !== stride; ++ i ) {
  29979. result[ i ] =
  29980. sP * values[ oP + i ] +
  29981. s0 * values[ o0 + i ] +
  29982. s1 * values[ o1 + i ] +
  29983. sN * values[ oN + i ];
  29984. }
  29985. return result;
  29986. }
  29987. }
  29988. /**
  29989. * A basic linear interpolant.
  29990. *
  29991. * @augments Interpolant
  29992. */
  29993. class LinearInterpolant extends Interpolant {
  29994. /**
  29995. * Constructs a new linear interpolant.
  29996. *
  29997. * @param {TypedArray} parameterPositions - The parameter positions hold the interpolation factors.
  29998. * @param {TypedArray} sampleValues - The sample values.
  29999. * @param {number} sampleSize - The sample size
  30000. * @param {TypedArray} [resultBuffer] - The result buffer.
  30001. */
  30002. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  30003. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  30004. }
  30005. interpolate_( i1, t0, t, t1 ) {
  30006. const result = this.resultBuffer,
  30007. values = this.sampleValues,
  30008. stride = this.valueSize,
  30009. offset1 = i1 * stride,
  30010. offset0 = offset1 - stride,
  30011. weight1 = ( t - t0 ) / ( t1 - t0 ),
  30012. weight0 = 1 - weight1;
  30013. for ( let i = 0; i !== stride; ++ i ) {
  30014. result[ i ] =
  30015. values[ offset0 + i ] * weight0 +
  30016. values[ offset1 + i ] * weight1;
  30017. }
  30018. return result;
  30019. }
  30020. }
  30021. /**
  30022. * Interpolant that evaluates to the sample value at the position preceding
  30023. * the parameter.
  30024. *
  30025. * @augments Interpolant
  30026. */
  30027. class DiscreteInterpolant extends Interpolant {
  30028. /**
  30029. * Constructs a new discrete interpolant.
  30030. *
  30031. * @param {TypedArray} parameterPositions - The parameter positions hold the interpolation factors.
  30032. * @param {TypedArray} sampleValues - The sample values.
  30033. * @param {number} sampleSize - The sample size
  30034. * @param {TypedArray} [resultBuffer] - The result buffer.
  30035. */
  30036. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  30037. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  30038. }
  30039. interpolate_( i1 /*, t0, t, t1 */ ) {
  30040. return this.copySampleValue_( i1 - 1 );
  30041. }
  30042. }
  30043. /**
  30044. * Represents s a timed sequence of keyframes, which are composed of lists of
  30045. * times and related values, and which are used to animate a specific property
  30046. * of an object.
  30047. */
  30048. class KeyframeTrack {
  30049. /**
  30050. * Constructs a new keyframe track.
  30051. *
  30052. * @param {string} name - The keyframe track's name.
  30053. * @param {Array<number>} times - A list of keyframe times.
  30054. * @param {Array<number>} values - A list of keyframe values.
  30055. * @param {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)} [interpolation] - The interpolation type.
  30056. */
  30057. constructor( name, times, values, interpolation ) {
  30058. if ( name === undefined ) throw new Error( 'THREE.KeyframeTrack: track name is undefined' );
  30059. if ( times === undefined || times.length === 0 ) throw new Error( 'THREE.KeyframeTrack: no keyframes in track named ' + name );
  30060. /**
  30061. * The track's name can refer to morph targets or bones or
  30062. * possibly other values within an animated object. See {@link PropertyBinding#parseTrackName}
  30063. * for the forms of strings that can be parsed for property binding.
  30064. *
  30065. * @type {string}
  30066. */
  30067. this.name = name;
  30068. /**
  30069. * The keyframe times.
  30070. *
  30071. * @type {Float32Array}
  30072. */
  30073. this.times = convertArray( times, this.TimeBufferType );
  30074. /**
  30075. * The keyframe values.
  30076. *
  30077. * @type {Float32Array}
  30078. */
  30079. this.values = convertArray( values, this.ValueBufferType );
  30080. this.setInterpolation( interpolation || this.DefaultInterpolation );
  30081. }
  30082. /**
  30083. * Converts the keyframe track to JSON.
  30084. *
  30085. * @static
  30086. * @param {KeyframeTrack} track - The keyframe track to serialize.
  30087. * @return {Object} The serialized keyframe track as JSON.
  30088. */
  30089. static toJSON( track ) {
  30090. const trackType = track.constructor;
  30091. let json;
  30092. // derived classes can define a static toJSON method
  30093. if ( trackType.toJSON !== this.toJSON ) {
  30094. json = trackType.toJSON( track );
  30095. } else {
  30096. // by default, we assume the data can be serialized as-is
  30097. json = {
  30098. 'name': track.name,
  30099. 'times': convertArray( track.times, Array ),
  30100. 'values': convertArray( track.values, Array )
  30101. };
  30102. const interpolation = track.getInterpolation();
  30103. if ( interpolation !== track.DefaultInterpolation ) {
  30104. json.interpolation = interpolation;
  30105. }
  30106. }
  30107. json.type = track.ValueTypeName; // mandatory
  30108. return json;
  30109. }
  30110. /**
  30111. * Factory method for creating a new discrete interpolant.
  30112. *
  30113. * @static
  30114. * @param {TypedArray} [result] - The result buffer.
  30115. * @return {DiscreteInterpolant} The new interpolant.
  30116. */
  30117. InterpolantFactoryMethodDiscrete( result ) {
  30118. return new DiscreteInterpolant( this.times, this.values, this.getValueSize(), result );
  30119. }
  30120. /**
  30121. * Factory method for creating a new linear interpolant.
  30122. *
  30123. * @static
  30124. * @param {TypedArray} [result] - The result buffer.
  30125. * @return {LinearInterpolant} The new interpolant.
  30126. */
  30127. InterpolantFactoryMethodLinear( result ) {
  30128. return new LinearInterpolant( this.times, this.values, this.getValueSize(), result );
  30129. }
  30130. /**
  30131. * Factory method for creating a new smooth interpolant.
  30132. *
  30133. * @static
  30134. * @param {TypedArray} [result] - The result buffer.
  30135. * @return {CubicInterpolant} The new interpolant.
  30136. */
  30137. InterpolantFactoryMethodSmooth( result ) {
  30138. return new CubicInterpolant( this.times, this.values, this.getValueSize(), result );
  30139. }
  30140. /**
  30141. * Defines the interpolation factor method for this keyframe track.
  30142. *
  30143. * @param {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)} interpolation - The interpolation type.
  30144. * @return {KeyframeTrack} A reference to this keyframe track.
  30145. */
  30146. setInterpolation( interpolation ) {
  30147. let factoryMethod;
  30148. switch ( interpolation ) {
  30149. case InterpolateDiscrete:
  30150. factoryMethod = this.InterpolantFactoryMethodDiscrete;
  30151. break;
  30152. case InterpolateLinear:
  30153. factoryMethod = this.InterpolantFactoryMethodLinear;
  30154. break;
  30155. case InterpolateSmooth:
  30156. factoryMethod = this.InterpolantFactoryMethodSmooth;
  30157. break;
  30158. }
  30159. if ( factoryMethod === undefined ) {
  30160. const message = 'unsupported interpolation for ' +
  30161. this.ValueTypeName + ' keyframe track named ' + this.name;
  30162. if ( this.createInterpolant === undefined ) {
  30163. // fall back to default, unless the default itself is messed up
  30164. if ( interpolation !== this.DefaultInterpolation ) {
  30165. this.setInterpolation( this.DefaultInterpolation );
  30166. } else {
  30167. throw new Error( message ); // fatal, in this case
  30168. }
  30169. }
  30170. console.warn( 'THREE.KeyframeTrack:', message );
  30171. return this;
  30172. }
  30173. this.createInterpolant = factoryMethod;
  30174. return this;
  30175. }
  30176. /**
  30177. * Returns the current interpolation type.
  30178. *
  30179. * @return {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)} The interpolation type.
  30180. */
  30181. getInterpolation() {
  30182. switch ( this.createInterpolant ) {
  30183. case this.InterpolantFactoryMethodDiscrete:
  30184. return InterpolateDiscrete;
  30185. case this.InterpolantFactoryMethodLinear:
  30186. return InterpolateLinear;
  30187. case this.InterpolantFactoryMethodSmooth:
  30188. return InterpolateSmooth;
  30189. }
  30190. }
  30191. /**
  30192. * Returns the value size.
  30193. *
  30194. * @return {number} The value size.
  30195. */
  30196. getValueSize() {
  30197. return this.values.length / this.times.length;
  30198. }
  30199. /**
  30200. * Moves all keyframes either forward or backward in time.
  30201. *
  30202. * @param {number} timeOffset - The offset to move the time values.
  30203. * @return {KeyframeTrack} A reference to this keyframe track.
  30204. */
  30205. shift( timeOffset ) {
  30206. if ( timeOffset !== 0.0 ) {
  30207. const times = this.times;
  30208. for ( let i = 0, n = times.length; i !== n; ++ i ) {
  30209. times[ i ] += timeOffset;
  30210. }
  30211. }
  30212. return this;
  30213. }
  30214. /**
  30215. * Scale all keyframe times by a factor (useful for frame - seconds conversions).
  30216. *
  30217. * @param {number} timeScale - The time scale.
  30218. * @return {KeyframeTrack} A reference to this keyframe track.
  30219. */
  30220. scale( timeScale ) {
  30221. if ( timeScale !== 1.0 ) {
  30222. const times = this.times;
  30223. for ( let i = 0, n = times.length; i !== n; ++ i ) {
  30224. times[ i ] *= timeScale;
  30225. }
  30226. }
  30227. return this;
  30228. }
  30229. /**
  30230. * Removes keyframes before and after animation without changing any values within the defined time range.
  30231. *
  30232. * Note: The method does not shift around keys to the start of the track time, because for interpolated
  30233. * keys this will change their values
  30234. *
  30235. * @param {number} startTime - The start time.
  30236. * @param {number} endTime - The end time.
  30237. * @return {KeyframeTrack} A reference to this keyframe track.
  30238. */
  30239. trim( startTime, endTime ) {
  30240. const times = this.times,
  30241. nKeys = times.length;
  30242. let from = 0,
  30243. to = nKeys - 1;
  30244. while ( from !== nKeys && times[ from ] < startTime ) {
  30245. ++ from;
  30246. }
  30247. while ( to !== -1 && times[ to ] > endTime ) {
  30248. -- to;
  30249. }
  30250. ++ to; // inclusive -> exclusive bound
  30251. if ( from !== 0 || to !== nKeys ) {
  30252. // empty tracks are forbidden, so keep at least one keyframe
  30253. if ( from >= to ) {
  30254. to = Math.max( to, 1 );
  30255. from = to - 1;
  30256. }
  30257. const stride = this.getValueSize();
  30258. this.times = times.slice( from, to );
  30259. this.values = this.values.slice( from * stride, to * stride );
  30260. }
  30261. return this;
  30262. }
  30263. /**
  30264. * Performs minimal validation on the keyframe track. Returns `true` if the values
  30265. * are valid.
  30266. *
  30267. * @return {boolean} Whether the keyframes are valid or not.
  30268. */
  30269. validate() {
  30270. let valid = true;
  30271. const valueSize = this.getValueSize();
  30272. if ( valueSize - Math.floor( valueSize ) !== 0 ) {
  30273. console.error( 'THREE.KeyframeTrack: Invalid value size in track.', this );
  30274. valid = false;
  30275. }
  30276. const times = this.times,
  30277. values = this.values,
  30278. nKeys = times.length;
  30279. if ( nKeys === 0 ) {
  30280. console.error( 'THREE.KeyframeTrack: Track is empty.', this );
  30281. valid = false;
  30282. }
  30283. let prevTime = null;
  30284. for ( let i = 0; i !== nKeys; i ++ ) {
  30285. const currTime = times[ i ];
  30286. if ( typeof currTime === 'number' && isNaN( currTime ) ) {
  30287. console.error( 'THREE.KeyframeTrack: Time is not a valid number.', this, i, currTime );
  30288. valid = false;
  30289. break;
  30290. }
  30291. if ( prevTime !== null && prevTime > currTime ) {
  30292. console.error( 'THREE.KeyframeTrack: Out of order keys.', this, i, currTime, prevTime );
  30293. valid = false;
  30294. break;
  30295. }
  30296. prevTime = currTime;
  30297. }
  30298. if ( values !== undefined ) {
  30299. if ( isTypedArray( values ) ) {
  30300. for ( let i = 0, n = values.length; i !== n; ++ i ) {
  30301. const value = values[ i ];
  30302. if ( isNaN( value ) ) {
  30303. console.error( 'THREE.KeyframeTrack: Value is not a valid number.', this, i, value );
  30304. valid = false;
  30305. break;
  30306. }
  30307. }
  30308. }
  30309. }
  30310. return valid;
  30311. }
  30312. /**
  30313. * Optimizes this keyframe track by removing equivalent sequential keys (which are
  30314. * common in morph target sequences).
  30315. *
  30316. * @return {AnimationClip} A reference to this animation clip.
  30317. */
  30318. optimize() {
  30319. // (0,0,0,0,1,1,1,0,0,0,0,0,0,0) --> (0,0,1,1,0,0)
  30320. // times or values may be shared with other tracks, so overwriting is unsafe
  30321. const times = this.times.slice(),
  30322. values = this.values.slice(),
  30323. stride = this.getValueSize(),
  30324. smoothInterpolation = this.getInterpolation() === InterpolateSmooth,
  30325. lastIndex = times.length - 1;
  30326. let writeIndex = 1;
  30327. for ( let i = 1; i < lastIndex; ++ i ) {
  30328. let keep = false;
  30329. const time = times[ i ];
  30330. const timeNext = times[ i + 1 ];
  30331. // remove adjacent keyframes scheduled at the same time
  30332. if ( time !== timeNext && ( i !== 1 || time !== times[ 0 ] ) ) {
  30333. if ( ! smoothInterpolation ) {
  30334. // remove unnecessary keyframes same as their neighbors
  30335. const offset = i * stride,
  30336. offsetP = offset - stride,
  30337. offsetN = offset + stride;
  30338. for ( let j = 0; j !== stride; ++ j ) {
  30339. const value = values[ offset + j ];
  30340. if ( value !== values[ offsetP + j ] ||
  30341. value !== values[ offsetN + j ] ) {
  30342. keep = true;
  30343. break;
  30344. }
  30345. }
  30346. } else {
  30347. keep = true;
  30348. }
  30349. }
  30350. // in-place compaction
  30351. if ( keep ) {
  30352. if ( i !== writeIndex ) {
  30353. times[ writeIndex ] = times[ i ];
  30354. const readOffset = i * stride,
  30355. writeOffset = writeIndex * stride;
  30356. for ( let j = 0; j !== stride; ++ j ) {
  30357. values[ writeOffset + j ] = values[ readOffset + j ];
  30358. }
  30359. }
  30360. ++ writeIndex;
  30361. }
  30362. }
  30363. // flush last keyframe (compaction looks ahead)
  30364. if ( lastIndex > 0 ) {
  30365. times[ writeIndex ] = times[ lastIndex ];
  30366. for ( let readOffset = lastIndex * stride, writeOffset = writeIndex * stride, j = 0; j !== stride; ++ j ) {
  30367. values[ writeOffset + j ] = values[ readOffset + j ];
  30368. }
  30369. ++ writeIndex;
  30370. }
  30371. if ( writeIndex !== times.length ) {
  30372. this.times = times.slice( 0, writeIndex );
  30373. this.values = values.slice( 0, writeIndex * stride );
  30374. } else {
  30375. this.times = times;
  30376. this.values = values;
  30377. }
  30378. return this;
  30379. }
  30380. /**
  30381. * Returns a new keyframe track with copied values from this instance.
  30382. *
  30383. * @return {KeyframeTrack} A clone of this instance.
  30384. */
  30385. clone() {
  30386. const times = this.times.slice();
  30387. const values = this.values.slice();
  30388. const TypedKeyframeTrack = this.constructor;
  30389. const track = new TypedKeyframeTrack( this.name, times, values );
  30390. // Interpolant argument to constructor is not saved, so copy the factory method directly.
  30391. track.createInterpolant = this.createInterpolant;
  30392. return track;
  30393. }
  30394. }
  30395. /**
  30396. * The value type name.
  30397. *
  30398. * @type {String}
  30399. * @default ''
  30400. */
  30401. KeyframeTrack.prototype.ValueTypeName = '';
  30402. /**
  30403. * The time buffer type of this keyframe track.
  30404. *
  30405. * @type {TypedArray|Array}
  30406. * @default Float32Array.constructor
  30407. */
  30408. KeyframeTrack.prototype.TimeBufferType = Float32Array;
  30409. /**
  30410. * The value buffer type of this keyframe track.
  30411. *
  30412. * @type {TypedArray|Array}
  30413. * @default Float32Array.constructor
  30414. */
  30415. KeyframeTrack.prototype.ValueBufferType = Float32Array;
  30416. /**
  30417. * The default interpolation type of this keyframe track.
  30418. *
  30419. * @type {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)}
  30420. * @default InterpolateLinear
  30421. */
  30422. KeyframeTrack.prototype.DefaultInterpolation = InterpolateLinear;
  30423. /**
  30424. * A track for boolean keyframe values.
  30425. *
  30426. * @augments KeyframeTrack
  30427. */
  30428. class BooleanKeyframeTrack extends KeyframeTrack {
  30429. /**
  30430. * Constructs a new boolean keyframe track.
  30431. *
  30432. * This keyframe track type has no `interpolation` parameter because the
  30433. * interpolation is always discrete.
  30434. *
  30435. * @param {string} name - The keyframe track's name.
  30436. * @param {Array<number>} times - A list of keyframe times.
  30437. * @param {Array<number>} values - A list of keyframe values.
  30438. */
  30439. constructor( name, times, values ) {
  30440. super( name, times, values );
  30441. }
  30442. }
  30443. /**
  30444. * The value type name.
  30445. *
  30446. * @type {String}
  30447. * @default 'bool'
  30448. */
  30449. BooleanKeyframeTrack.prototype.ValueTypeName = 'bool';
  30450. /**
  30451. * The value buffer type of this keyframe track.
  30452. *
  30453. * @type {TypedArray|Array}
  30454. * @default Array.constructor
  30455. */
  30456. BooleanKeyframeTrack.prototype.ValueBufferType = Array;
  30457. /**
  30458. * The default interpolation type of this keyframe track.
  30459. *
  30460. * @type {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)}
  30461. * @default InterpolateDiscrete
  30462. */
  30463. BooleanKeyframeTrack.prototype.DefaultInterpolation = InterpolateDiscrete;
  30464. BooleanKeyframeTrack.prototype.InterpolantFactoryMethodLinear = undefined;
  30465. BooleanKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  30466. /**
  30467. * A track for color keyframe values.
  30468. *
  30469. * @augments KeyframeTrack
  30470. */
  30471. class ColorKeyframeTrack extends KeyframeTrack {
  30472. /**
  30473. * Constructs a new color keyframe track.
  30474. *
  30475. * @param {string} name - The keyframe track's name.
  30476. * @param {Array<number>} times - A list of keyframe times.
  30477. * @param {Array<number>} values - A list of keyframe values.
  30478. * @param {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)} [interpolation] - The interpolation type.
  30479. */
  30480. constructor( name, times, values, interpolation ) {
  30481. super( name, times, values, interpolation );
  30482. }
  30483. }
  30484. /**
  30485. * The value type name.
  30486. *
  30487. * @type {String}
  30488. * @default 'color'
  30489. */
  30490. ColorKeyframeTrack.prototype.ValueTypeName = 'color';
  30491. /**
  30492. * A track for numeric keyframe values.
  30493. *
  30494. * @augments KeyframeTrack
  30495. */
  30496. class NumberKeyframeTrack extends KeyframeTrack {
  30497. /**
  30498. * Constructs a new number keyframe track.
  30499. *
  30500. * @param {string} name - The keyframe track's name.
  30501. * @param {Array<number>} times - A list of keyframe times.
  30502. * @param {Array<number>} values - A list of keyframe values.
  30503. * @param {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)} [interpolation] - The interpolation type.
  30504. */
  30505. constructor( name, times, values, interpolation ) {
  30506. super( name, times, values, interpolation );
  30507. }
  30508. }
  30509. /**
  30510. * The value type name.
  30511. *
  30512. * @type {String}
  30513. * @default 'number'
  30514. */
  30515. NumberKeyframeTrack.prototype.ValueTypeName = 'number';
  30516. /**
  30517. * Spherical linear unit quaternion interpolant.
  30518. *
  30519. * @augments Interpolant
  30520. */
  30521. class QuaternionLinearInterpolant extends Interpolant {
  30522. /**
  30523. * Constructs a new SLERP interpolant.
  30524. *
  30525. * @param {TypedArray} parameterPositions - The parameter positions hold the interpolation factors.
  30526. * @param {TypedArray} sampleValues - The sample values.
  30527. * @param {number} sampleSize - The sample size
  30528. * @param {TypedArray} [resultBuffer] - The result buffer.
  30529. */
  30530. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  30531. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  30532. }
  30533. interpolate_( i1, t0, t, t1 ) {
  30534. const result = this.resultBuffer,
  30535. values = this.sampleValues,
  30536. stride = this.valueSize,
  30537. alpha = ( t - t0 ) / ( t1 - t0 );
  30538. let offset = i1 * stride;
  30539. for ( let end = offset + stride; offset !== end; offset += 4 ) {
  30540. Quaternion.slerpFlat( result, 0, values, offset - stride, values, offset, alpha );
  30541. }
  30542. return result;
  30543. }
  30544. }
  30545. /**
  30546. * A track for Quaternion keyframe values.
  30547. *
  30548. * @augments KeyframeTrack
  30549. */
  30550. class QuaternionKeyframeTrack extends KeyframeTrack {
  30551. /**
  30552. * Constructs a new Quaternion keyframe track.
  30553. *
  30554. * @param {string} name - The keyframe track's name.
  30555. * @param {Array<number>} times - A list of keyframe times.
  30556. * @param {Array<number>} values - A list of keyframe values.
  30557. * @param {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)} [interpolation] - The interpolation type.
  30558. */
  30559. constructor( name, times, values, interpolation ) {
  30560. super( name, times, values, interpolation );
  30561. }
  30562. /**
  30563. * Overwritten so the method returns Quaternion based interpolant.
  30564. *
  30565. * @static
  30566. * @param {TypedArray} [result] - The result buffer.
  30567. * @return {QuaternionLinearInterpolant} The new interpolant.
  30568. */
  30569. InterpolantFactoryMethodLinear( result ) {
  30570. return new QuaternionLinearInterpolant( this.times, this.values, this.getValueSize(), result );
  30571. }
  30572. }
  30573. /**
  30574. * The value type name.
  30575. *
  30576. * @type {String}
  30577. * @default 'quaternion'
  30578. */
  30579. QuaternionKeyframeTrack.prototype.ValueTypeName = 'quaternion';
  30580. // ValueBufferType is inherited
  30581. // DefaultInterpolation is inherited;
  30582. QuaternionKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  30583. /**
  30584. * A track for string keyframe values.
  30585. *
  30586. * @augments KeyframeTrack
  30587. */
  30588. class StringKeyframeTrack extends KeyframeTrack {
  30589. /**
  30590. * Constructs a new string keyframe track.
  30591. *
  30592. * This keyframe track type has no `interpolation` parameter because the
  30593. * interpolation is always discrete.
  30594. *
  30595. * @param {string} name - The keyframe track's name.
  30596. * @param {Array<number>} times - A list of keyframe times.
  30597. * @param {Array<number>} values - A list of keyframe values.
  30598. */
  30599. constructor( name, times, values ) {
  30600. super( name, times, values );
  30601. }
  30602. }
  30603. /**
  30604. * The value type name.
  30605. *
  30606. * @type {String}
  30607. * @default 'string'
  30608. */
  30609. StringKeyframeTrack.prototype.ValueTypeName = 'string';
  30610. /**
  30611. * The value buffer type of this keyframe track.
  30612. *
  30613. * @type {TypedArray|Array}
  30614. * @default Array.constructor
  30615. */
  30616. StringKeyframeTrack.prototype.ValueBufferType = Array;
  30617. /**
  30618. * The default interpolation type of this keyframe track.
  30619. *
  30620. * @type {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)}
  30621. * @default InterpolateDiscrete
  30622. */
  30623. StringKeyframeTrack.prototype.DefaultInterpolation = InterpolateDiscrete;
  30624. StringKeyframeTrack.prototype.InterpolantFactoryMethodLinear = undefined;
  30625. StringKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  30626. /**
  30627. * A track for vector keyframe values.
  30628. *
  30629. * @augments KeyframeTrack
  30630. */
  30631. class VectorKeyframeTrack extends KeyframeTrack {
  30632. /**
  30633. * Constructs a new vector keyframe track.
  30634. *
  30635. * @param {string} name - The keyframe track's name.
  30636. * @param {Array<number>} times - A list of keyframe times.
  30637. * @param {Array<number>} values - A list of keyframe values.
  30638. * @param {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)} [interpolation] - The interpolation type.
  30639. */
  30640. constructor( name, times, values, interpolation ) {
  30641. super( name, times, values, interpolation );
  30642. }
  30643. }
  30644. /**
  30645. * The value type name.
  30646. *
  30647. * @type {String}
  30648. * @default 'vector'
  30649. */
  30650. VectorKeyframeTrack.prototype.ValueTypeName = 'vector';
  30651. /**
  30652. * A reusable set of keyframe tracks which represent an animation.
  30653. */
  30654. class AnimationClip {
  30655. /**
  30656. * Constructs a new animation clip.
  30657. *
  30658. * Note: Instead of instantiating an AnimationClip directly with the constructor, you can
  30659. * use the static interface of this class for creating clips. In most cases though, animation clips
  30660. * will automatically be created by loaders when importing animated 3D assets.
  30661. *
  30662. * @param {string} [name=''] - The clip's name.
  30663. * @param {number} [duration=-1] - The clip's duration in seconds. If a negative value is passed,
  30664. * the duration will be calculated from the passed keyframes.
  30665. * @param {Array<KeyframeTrack>} tracks - An array of keyframe tracks.
  30666. * @param {(NormalAnimationBlendMode|AdditiveAnimationBlendMode)} [blendMode=NormalAnimationBlendMode] - Defines how the animation
  30667. * is blended/combined when two or more animations are simultaneously played.
  30668. */
  30669. constructor( name = '', duration = -1, tracks = [], blendMode = NormalAnimationBlendMode ) {
  30670. /**
  30671. * The clip's name.
  30672. *
  30673. * @type {string}
  30674. */
  30675. this.name = name;
  30676. /**
  30677. * An array of keyframe tracks.
  30678. *
  30679. * @type {Array<KeyframeTrack>}
  30680. */
  30681. this.tracks = tracks;
  30682. /**
  30683. * The clip's duration in seconds.
  30684. *
  30685. * @type {number}
  30686. */
  30687. this.duration = duration;
  30688. /**
  30689. * Defines how the animation is blended/combined when two or more animations
  30690. * are simultaneously played.
  30691. *
  30692. * @type {(NormalAnimationBlendMode|AdditiveAnimationBlendMode)}
  30693. */
  30694. this.blendMode = blendMode;
  30695. /**
  30696. * The UUID of the animation clip.
  30697. *
  30698. * @type {string}
  30699. * @readonly
  30700. */
  30701. this.uuid = generateUUID();
  30702. // this means it should figure out its duration by scanning the tracks
  30703. if ( this.duration < 0 ) {
  30704. this.resetDuration();
  30705. }
  30706. }
  30707. /**
  30708. * Factory method for creating an animation clip from the given JSON.
  30709. *
  30710. * @static
  30711. * @param {Object} json - The serialized animation clip.
  30712. * @return {AnimationClip} The new animation clip.
  30713. */
  30714. static parse( json ) {
  30715. const tracks = [],
  30716. jsonTracks = json.tracks,
  30717. frameTime = 1.0 / ( json.fps || 1.0 );
  30718. for ( let i = 0, n = jsonTracks.length; i !== n; ++ i ) {
  30719. tracks.push( parseKeyframeTrack( jsonTracks[ i ] ).scale( frameTime ) );
  30720. }
  30721. const clip = new this( json.name, json.duration, tracks, json.blendMode );
  30722. clip.uuid = json.uuid;
  30723. return clip;
  30724. }
  30725. /**
  30726. * Serializes the given animation clip into JSON.
  30727. *
  30728. * @static
  30729. * @param {AnimationClip} clip - The animation clip to serialize.
  30730. * @return {Object} The JSON object.
  30731. */
  30732. static toJSON( clip ) {
  30733. const tracks = [],
  30734. clipTracks = clip.tracks;
  30735. const json = {
  30736. 'name': clip.name,
  30737. 'duration': clip.duration,
  30738. 'tracks': tracks,
  30739. 'uuid': clip.uuid,
  30740. 'blendMode': clip.blendMode
  30741. };
  30742. for ( let i = 0, n = clipTracks.length; i !== n; ++ i ) {
  30743. tracks.push( KeyframeTrack.toJSON( clipTracks[ i ] ) );
  30744. }
  30745. return json;
  30746. }
  30747. /**
  30748. * Returns a new animation clip from the passed morph targets array of a
  30749. * geometry, taking a name and the number of frames per second.
  30750. *
  30751. * Note: The fps parameter is required, but the animation speed can be
  30752. * overridden via {@link AnimationAction#setDuration}.
  30753. *
  30754. * @static
  30755. * @param {string} name - The name of the animation clip.
  30756. * @param {Array<Object>} morphTargetSequence - A sequence of morph targets.
  30757. * @param {number} fps - The Frames-Per-Second value.
  30758. * @param {boolean} noLoop - Whether the clip should be no loop or not.
  30759. * @return {AnimationClip} The new animation clip.
  30760. */
  30761. static CreateFromMorphTargetSequence( name, morphTargetSequence, fps, noLoop ) {
  30762. const numMorphTargets = morphTargetSequence.length;
  30763. const tracks = [];
  30764. for ( let i = 0; i < numMorphTargets; i ++ ) {
  30765. let times = [];
  30766. let values = [];
  30767. times.push(
  30768. ( i + numMorphTargets - 1 ) % numMorphTargets,
  30769. i,
  30770. ( i + 1 ) % numMorphTargets );
  30771. values.push( 0, 1, 0 );
  30772. const order = getKeyframeOrder( times );
  30773. times = sortedArray( times, 1, order );
  30774. values = sortedArray( values, 1, order );
  30775. // if there is a key at the first frame, duplicate it as the
  30776. // last frame as well for perfect loop.
  30777. if ( ! noLoop && times[ 0 ] === 0 ) {
  30778. times.push( numMorphTargets );
  30779. values.push( values[ 0 ] );
  30780. }
  30781. tracks.push(
  30782. new NumberKeyframeTrack(
  30783. '.morphTargetInfluences[' + morphTargetSequence[ i ].name + ']',
  30784. times, values
  30785. ).scale( 1.0 / fps ) );
  30786. }
  30787. return new this( name, -1, tracks );
  30788. }
  30789. /**
  30790. * Searches for an animation clip by name, taking as its first parameter
  30791. * either an array of clips, or a mesh or geometry that contains an
  30792. * array named "animations" property.
  30793. *
  30794. * @static
  30795. * @param {(Array<AnimationClip>|Object3D)} objectOrClipArray - The array or object to search through.
  30796. * @param {string} name - The name to search for.
  30797. * @return {?AnimationClip} The found animation clip. Returns `null` if no clip has been found.
  30798. */
  30799. static findByName( objectOrClipArray, name ) {
  30800. let clipArray = objectOrClipArray;
  30801. if ( ! Array.isArray( objectOrClipArray ) ) {
  30802. const o = objectOrClipArray;
  30803. clipArray = o.geometry && o.geometry.animations || o.animations;
  30804. }
  30805. for ( let i = 0; i < clipArray.length; i ++ ) {
  30806. if ( clipArray[ i ].name === name ) {
  30807. return clipArray[ i ];
  30808. }
  30809. }
  30810. return null;
  30811. }
  30812. /**
  30813. * Returns an array of new AnimationClips created from the morph target
  30814. * sequences of a geometry, trying to sort morph target names into
  30815. * animation-group-based patterns like "Walk_001, Walk_002, Run_001, Run_002...".
  30816. *
  30817. * See {@link MD2Loader#parse} as an example for how the method should be used.
  30818. *
  30819. * @static
  30820. * @param {Array<Object>} morphTargets - A sequence of morph targets.
  30821. * @param {number} fps - The Frames-Per-Second value.
  30822. * @param {boolean} noLoop - Whether the clip should be no loop or not.
  30823. * @return {Array<AnimationClip>} An array of new animation clips.
  30824. */
  30825. static CreateClipsFromMorphTargetSequences( morphTargets, fps, noLoop ) {
  30826. const animationToMorphTargets = {};
  30827. // tested with https://regex101.com/ on trick sequences
  30828. // such flamingo_flyA_003, flamingo_run1_003, crdeath0059
  30829. const pattern = /^([\w-]*?)([\d]+)$/;
  30830. // sort morph target names into animation groups based
  30831. // patterns like Walk_001, Walk_002, Run_001, Run_002
  30832. for ( let i = 0, il = morphTargets.length; i < il; i ++ ) {
  30833. const morphTarget = morphTargets[ i ];
  30834. const parts = morphTarget.name.match( pattern );
  30835. if ( parts && parts.length > 1 ) {
  30836. const name = parts[ 1 ];
  30837. let animationMorphTargets = animationToMorphTargets[ name ];
  30838. if ( ! animationMorphTargets ) {
  30839. animationToMorphTargets[ name ] = animationMorphTargets = [];
  30840. }
  30841. animationMorphTargets.push( morphTarget );
  30842. }
  30843. }
  30844. const clips = [];
  30845. for ( const name in animationToMorphTargets ) {
  30846. clips.push( this.CreateFromMorphTargetSequence( name, animationToMorphTargets[ name ], fps, noLoop ) );
  30847. }
  30848. return clips;
  30849. }
  30850. /**
  30851. * Parses the `animation.hierarchy` format and returns a new animation clip.
  30852. *
  30853. * @static
  30854. * @deprecated since r175.
  30855. * @param {Object} animation - A serialized animation clip as JSON.
  30856. * @param {Array<Bones>} bones - An array of bones.
  30857. * @return {?AnimationClip} The new animation clip.
  30858. */
  30859. static parseAnimation( animation, bones ) {
  30860. console.warn( 'THREE.AnimationClip: parseAnimation() is deprecated and will be removed with r185' );
  30861. if ( ! animation ) {
  30862. console.error( 'THREE.AnimationClip: No animation in JSONLoader data.' );
  30863. return null;
  30864. }
  30865. const addNonemptyTrack = function ( trackType, trackName, animationKeys, propertyName, destTracks ) {
  30866. // only return track if there are actually keys.
  30867. if ( animationKeys.length !== 0 ) {
  30868. const times = [];
  30869. const values = [];
  30870. flattenJSON( animationKeys, times, values, propertyName );
  30871. // empty keys are filtered out, so check again
  30872. if ( times.length !== 0 ) {
  30873. destTracks.push( new trackType( trackName, times, values ) );
  30874. }
  30875. }
  30876. };
  30877. const tracks = [];
  30878. const clipName = animation.name || 'default';
  30879. const fps = animation.fps || 30;
  30880. const blendMode = animation.blendMode;
  30881. // automatic length determination in AnimationClip.
  30882. let duration = animation.length || -1;
  30883. const hierarchyTracks = animation.hierarchy || [];
  30884. for ( let h = 0; h < hierarchyTracks.length; h ++ ) {
  30885. const animationKeys = hierarchyTracks[ h ].keys;
  30886. // skip empty tracks
  30887. if ( ! animationKeys || animationKeys.length === 0 ) continue;
  30888. // process morph targets
  30889. if ( animationKeys[ 0 ].morphTargets ) {
  30890. // figure out all morph targets used in this track
  30891. const morphTargetNames = {};
  30892. let k;
  30893. for ( k = 0; k < animationKeys.length; k ++ ) {
  30894. if ( animationKeys[ k ].morphTargets ) {
  30895. for ( let m = 0; m < animationKeys[ k ].morphTargets.length; m ++ ) {
  30896. morphTargetNames[ animationKeys[ k ].morphTargets[ m ] ] = -1;
  30897. }
  30898. }
  30899. }
  30900. // create a track for each morph target with all zero
  30901. // morphTargetInfluences except for the keys in which
  30902. // the morphTarget is named.
  30903. for ( const morphTargetName in morphTargetNames ) {
  30904. const times = [];
  30905. const values = [];
  30906. for ( let m = 0; m !== animationKeys[ k ].morphTargets.length; ++ m ) {
  30907. const animationKey = animationKeys[ k ];
  30908. times.push( animationKey.time );
  30909. values.push( ( animationKey.morphTarget === morphTargetName ) ? 1 : 0 );
  30910. }
  30911. tracks.push( new NumberKeyframeTrack( '.morphTargetInfluence[' + morphTargetName + ']', times, values ) );
  30912. }
  30913. duration = morphTargetNames.length * fps;
  30914. } else {
  30915. // ...assume skeletal animation
  30916. const boneName = '.bones[' + bones[ h ].name + ']';
  30917. addNonemptyTrack(
  30918. VectorKeyframeTrack, boneName + '.position',
  30919. animationKeys, 'pos', tracks );
  30920. addNonemptyTrack(
  30921. QuaternionKeyframeTrack, boneName + '.quaternion',
  30922. animationKeys, 'rot', tracks );
  30923. addNonemptyTrack(
  30924. VectorKeyframeTrack, boneName + '.scale',
  30925. animationKeys, 'scl', tracks );
  30926. }
  30927. }
  30928. if ( tracks.length === 0 ) {
  30929. return null;
  30930. }
  30931. const clip = new this( clipName, duration, tracks, blendMode );
  30932. return clip;
  30933. }
  30934. /**
  30935. * Sets the duration of this clip to the duration of its longest keyframe track.
  30936. *
  30937. * @return {AnimationClip} A reference to this animation clip.
  30938. */
  30939. resetDuration() {
  30940. const tracks = this.tracks;
  30941. let duration = 0;
  30942. for ( let i = 0, n = tracks.length; i !== n; ++ i ) {
  30943. const track = this.tracks[ i ];
  30944. duration = Math.max( duration, track.times[ track.times.length - 1 ] );
  30945. }
  30946. this.duration = duration;
  30947. return this;
  30948. }
  30949. /**
  30950. * Trims all tracks to the clip's duration.
  30951. *
  30952. * @return {AnimationClip} A reference to this animation clip.
  30953. */
  30954. trim() {
  30955. for ( let i = 0; i < this.tracks.length; i ++ ) {
  30956. this.tracks[ i ].trim( 0, this.duration );
  30957. }
  30958. return this;
  30959. }
  30960. /**
  30961. * Performs minimal validation on each track in the clip. Returns `true` if all
  30962. * tracks are valid.
  30963. *
  30964. * @return {boolean} Whether the clip's keyframes are valid or not.
  30965. */
  30966. validate() {
  30967. let valid = true;
  30968. for ( let i = 0; i < this.tracks.length; i ++ ) {
  30969. valid = valid && this.tracks[ i ].validate();
  30970. }
  30971. return valid;
  30972. }
  30973. /**
  30974. * Optimizes each track by removing equivalent sequential keys (which are
  30975. * common in morph target sequences).
  30976. *
  30977. * @return {AnimationClip} A reference to this animation clip.
  30978. */
  30979. optimize() {
  30980. for ( let i = 0; i < this.tracks.length; i ++ ) {
  30981. this.tracks[ i ].optimize();
  30982. }
  30983. return this;
  30984. }
  30985. /**
  30986. * Returns a new animation clip with copied values from this instance.
  30987. *
  30988. * @return {AnimationClip} A clone of this instance.
  30989. */
  30990. clone() {
  30991. const tracks = [];
  30992. for ( let i = 0; i < this.tracks.length; i ++ ) {
  30993. tracks.push( this.tracks[ i ].clone() );
  30994. }
  30995. return new this.constructor( this.name, this.duration, tracks, this.blendMode );
  30996. }
  30997. /**
  30998. * Serializes this animation clip into JSON.
  30999. *
  31000. * @return {Object} The JSON object.
  31001. */
  31002. toJSON() {
  31003. return this.constructor.toJSON( this );
  31004. }
  31005. }
  31006. function getTrackTypeForValueTypeName( typeName ) {
  31007. switch ( typeName.toLowerCase() ) {
  31008. case 'scalar':
  31009. case 'double':
  31010. case 'float':
  31011. case 'number':
  31012. case 'integer':
  31013. return NumberKeyframeTrack;
  31014. case 'vector':
  31015. case 'vector2':
  31016. case 'vector3':
  31017. case 'vector4':
  31018. return VectorKeyframeTrack;
  31019. case 'color':
  31020. return ColorKeyframeTrack;
  31021. case 'quaternion':
  31022. return QuaternionKeyframeTrack;
  31023. case 'bool':
  31024. case 'boolean':
  31025. return BooleanKeyframeTrack;
  31026. case 'string':
  31027. return StringKeyframeTrack;
  31028. }
  31029. throw new Error( 'THREE.KeyframeTrack: Unsupported typeName: ' + typeName );
  31030. }
  31031. function parseKeyframeTrack( json ) {
  31032. if ( json.type === undefined ) {
  31033. throw new Error( 'THREE.KeyframeTrack: track type undefined, can not parse' );
  31034. }
  31035. const trackType = getTrackTypeForValueTypeName( json.type );
  31036. if ( json.times === undefined ) {
  31037. const times = [], values = [];
  31038. flattenJSON( json.keys, times, values, 'value' );
  31039. json.times = times;
  31040. json.values = values;
  31041. }
  31042. // derived classes can define a static parse method
  31043. if ( trackType.parse !== undefined ) {
  31044. return trackType.parse( json );
  31045. } else {
  31046. // by default, we assume a constructor compatible with the base
  31047. return new trackType( json.name, json.times, json.values, json.interpolation );
  31048. }
  31049. }
  31050. /**
  31051. * @class
  31052. * @classdesc A simple caching system, used internally by {@link FileLoader}.
  31053. * To enable caching across all loaders that use {@link FileLoader}, add `THREE.Cache.enabled = true.` once in your app.
  31054. * @hideconstructor
  31055. */
  31056. const Cache = {
  31057. /**
  31058. * Whether caching is enabled or not.
  31059. *
  31060. * @static
  31061. * @type {boolean}
  31062. * @default false
  31063. */
  31064. enabled: false,
  31065. /**
  31066. * A dictionary that holds cached files.
  31067. *
  31068. * @static
  31069. * @type {Object<string,Object>}
  31070. */
  31071. files: {},
  31072. /**
  31073. * Adds a cache entry with a key to reference the file. If this key already
  31074. * holds a file, it is overwritten.
  31075. *
  31076. * @static
  31077. * @param {string} key - The key to reference the cached file.
  31078. * @param {Object} file - The file to be cached.
  31079. */
  31080. add: function ( key, file ) {
  31081. if ( this.enabled === false ) return;
  31082. // console.log( 'THREE.Cache', 'Adding key:', key );
  31083. this.files[ key ] = file;
  31084. },
  31085. /**
  31086. * Gets the cached value for the given key.
  31087. *
  31088. * @static
  31089. * @param {string} key - The key to reference the cached file.
  31090. * @return {Object|undefined} The cached file. If the key does not exist `undefined` is returned.
  31091. */
  31092. get: function ( key ) {
  31093. if ( this.enabled === false ) return;
  31094. // console.log( 'THREE.Cache', 'Checking key:', key );
  31095. return this.files[ key ];
  31096. },
  31097. /**
  31098. * Removes the cached file associated with the given key.
  31099. *
  31100. * @static
  31101. * @param {string} key - The key to reference the cached file.
  31102. */
  31103. remove: function ( key ) {
  31104. delete this.files[ key ];
  31105. },
  31106. /**
  31107. * Remove all values from the cache.
  31108. *
  31109. * @static
  31110. */
  31111. clear: function () {
  31112. this.files = {};
  31113. }
  31114. };
  31115. /**
  31116. * Handles and keeps track of loaded and pending data. A default global
  31117. * instance of this class is created and used by loaders if not supplied
  31118. * manually.
  31119. *
  31120. * In general that should be sufficient, however there are times when it can
  31121. * be useful to have separate loaders - for example if you want to show
  31122. * separate loading bars for objects and textures.
  31123. *
  31124. * ```js
  31125. * const manager = new THREE.LoadingManager();
  31126. * manager.onLoad = () => console.log( 'Loading complete!' );
  31127. *
  31128. * const loader1 = new OBJLoader( manager );
  31129. * const loader2 = new ColladaLoader( manager );
  31130. * ```
  31131. */
  31132. class LoadingManager {
  31133. /**
  31134. * Constructs a new loading manager.
  31135. *
  31136. * @param {Function} [onLoad] - Executes when all items have been loaded.
  31137. * @param {Function} [onProgress] - Executes when single items have been loaded.
  31138. * @param {Function} [onError] - Executes when an error occurs.
  31139. */
  31140. constructor( onLoad, onProgress, onError ) {
  31141. const scope = this;
  31142. let isLoading = false;
  31143. let itemsLoaded = 0;
  31144. let itemsTotal = 0;
  31145. let urlModifier = undefined;
  31146. const handlers = [];
  31147. // Refer to #5689 for the reason why we don't set .onStart
  31148. // in the constructor
  31149. /**
  31150. * Executes when an item starts loading.
  31151. *
  31152. * @type {Function|undefined}
  31153. * @default undefined
  31154. */
  31155. this.onStart = undefined;
  31156. /**
  31157. * Executes when all items have been loaded.
  31158. *
  31159. * @type {Function|undefined}
  31160. * @default undefined
  31161. */
  31162. this.onLoad = onLoad;
  31163. /**
  31164. * Executes when single items have been loaded.
  31165. *
  31166. * @type {Function|undefined}
  31167. * @default undefined
  31168. */
  31169. this.onProgress = onProgress;
  31170. /**
  31171. * Executes when an error occurs.
  31172. *
  31173. * @type {Function|undefined}
  31174. * @default undefined
  31175. */
  31176. this.onError = onError;
  31177. /**
  31178. * This should be called by any loader using the manager when the loader
  31179. * starts loading an item.
  31180. *
  31181. * @param {string} url - The URL to load.
  31182. */
  31183. this.itemStart = function ( url ) {
  31184. itemsTotal ++;
  31185. if ( isLoading === false ) {
  31186. if ( scope.onStart !== undefined ) {
  31187. scope.onStart( url, itemsLoaded, itemsTotal );
  31188. }
  31189. }
  31190. isLoading = true;
  31191. };
  31192. /**
  31193. * This should be called by any loader using the manager when the loader
  31194. * ended loading an item.
  31195. *
  31196. * @param {string} url - The URL of the loaded item.
  31197. */
  31198. this.itemEnd = function ( url ) {
  31199. itemsLoaded ++;
  31200. if ( scope.onProgress !== undefined ) {
  31201. scope.onProgress( url, itemsLoaded, itemsTotal );
  31202. }
  31203. if ( itemsLoaded === itemsTotal ) {
  31204. isLoading = false;
  31205. if ( scope.onLoad !== undefined ) {
  31206. scope.onLoad();
  31207. }
  31208. }
  31209. };
  31210. /**
  31211. * This should be called by any loader using the manager when the loader
  31212. * encounters an error when loading an item.
  31213. *
  31214. * @param {string} url - The URL of the item that produces an error.
  31215. */
  31216. this.itemError = function ( url ) {
  31217. if ( scope.onError !== undefined ) {
  31218. scope.onError( url );
  31219. }
  31220. };
  31221. /**
  31222. * Given a URL, uses the URL modifier callback (if any) and returns a
  31223. * resolved URL. If no URL modifier is set, returns the original URL.
  31224. *
  31225. * @param {string} url - The URL to load.
  31226. * @return {string} The resolved URL.
  31227. */
  31228. this.resolveURL = function ( url ) {
  31229. if ( urlModifier ) {
  31230. return urlModifier( url );
  31231. }
  31232. return url;
  31233. };
  31234. /**
  31235. * If provided, the callback will be passed each resource URL before a
  31236. * request is sent. The callback may return the original URL, or a new URL to
  31237. * override loading behavior. This behavior can be used to load assets from
  31238. * .ZIP files, drag-and-drop APIs, and Data URIs.
  31239. *
  31240. * ```js
  31241. * const blobs = {'fish.gltf': blob1, 'diffuse.png': blob2, 'normal.png': blob3};
  31242. *
  31243. * const manager = new THREE.LoadingManager();
  31244. *
  31245. * // Initialize loading manager with URL callback.
  31246. * const objectURLs = [];
  31247. * manager.setURLModifier( ( url ) => {
  31248. *
  31249. * url = URL.createObjectURL( blobs[ url ] );
  31250. * objectURLs.push( url );
  31251. * return url;
  31252. *
  31253. * } );
  31254. *
  31255. * // Load as usual, then revoke the blob URLs.
  31256. * const loader = new GLTFLoader( manager );
  31257. * loader.load( 'fish.gltf', (gltf) => {
  31258. *
  31259. * scene.add( gltf.scene );
  31260. * objectURLs.forEach( ( url ) => URL.revokeObjectURL( url ) );
  31261. *
  31262. * } );
  31263. * ```
  31264. *
  31265. * @param {function(string):string} transform - URL modifier callback. Called with an URL and must return a resolved URL.
  31266. * @return {LoadingManager} A reference to this loading manager.
  31267. */
  31268. this.setURLModifier = function ( transform ) {
  31269. urlModifier = transform;
  31270. return this;
  31271. };
  31272. /**
  31273. * Registers a loader with the given regular expression. Can be used to
  31274. * define what loader should be used in order to load specific files. A
  31275. * typical use case is to overwrite the default loader for textures.
  31276. *
  31277. * ```js
  31278. * // add handler for TGA textures
  31279. * manager.addHandler( /\.tga$/i, new TGALoader() );
  31280. * ```
  31281. *
  31282. * @param {string} regex - A regular expression.
  31283. * @param {Loader} loader - A loader that should handle matched cases.
  31284. * @return {LoadingManager} A reference to this loading manager.
  31285. */
  31286. this.addHandler = function ( regex, loader ) {
  31287. handlers.push( regex, loader );
  31288. return this;
  31289. };
  31290. /**
  31291. * Removes the loader for the given regular expression.
  31292. *
  31293. * @param {string} regex - A regular expression.
  31294. * @return {LoadingManager} A reference to this loading manager.
  31295. */
  31296. this.removeHandler = function ( regex ) {
  31297. const index = handlers.indexOf( regex );
  31298. if ( index !== -1 ) {
  31299. handlers.splice( index, 2 );
  31300. }
  31301. return this;
  31302. };
  31303. /**
  31304. * Can be used to retrieve the registered loader for the given file path.
  31305. *
  31306. * @param {string} file - The file path.
  31307. * @return {?Loader} The registered loader. Returns `null` if no loader was found.
  31308. */
  31309. this.getHandler = function ( file ) {
  31310. for ( let i = 0, l = handlers.length; i < l; i += 2 ) {
  31311. const regex = handlers[ i ];
  31312. const loader = handlers[ i + 1 ];
  31313. if ( regex.global ) regex.lastIndex = 0; // see #17920
  31314. if ( regex.test( file ) ) {
  31315. return loader;
  31316. }
  31317. }
  31318. return null;
  31319. };
  31320. }
  31321. }
  31322. /**
  31323. * The global default loading manager.
  31324. *
  31325. * @constant
  31326. * @type {LoadingManager}
  31327. */
  31328. const DefaultLoadingManager = /*@__PURE__*/ new LoadingManager();
  31329. /**
  31330. * Abstract base class for loaders.
  31331. *
  31332. * @abstract
  31333. */
  31334. class Loader {
  31335. /**
  31336. * Constructs a new loader.
  31337. *
  31338. * @param {LoadingManager} [manager] - The loading manager.
  31339. */
  31340. constructor( manager ) {
  31341. /**
  31342. * The loading manager.
  31343. *
  31344. * @type {LoadingManager}
  31345. * @default DefaultLoadingManager
  31346. */
  31347. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  31348. /**
  31349. * The crossOrigin string to implement CORS for loading the url from a
  31350. * different domain that allows CORS.
  31351. *
  31352. * @type {string}
  31353. * @default 'anonymous'
  31354. */
  31355. this.crossOrigin = 'anonymous';
  31356. /**
  31357. * Whether the XMLHttpRequest uses credentials.
  31358. *
  31359. * @type {boolean}
  31360. * @default false
  31361. */
  31362. this.withCredentials = false;
  31363. /**
  31364. * The base path from which the asset will be loaded.
  31365. *
  31366. * @type {string}
  31367. */
  31368. this.path = '';
  31369. /**
  31370. * The base path from which additional resources like textures will be loaded.
  31371. *
  31372. * @type {string}
  31373. */
  31374. this.resourcePath = '';
  31375. /**
  31376. * The [request header]{@link https://developer.mozilla.org/en-US/docs/Glossary/Request_header}
  31377. * used in HTTP request.
  31378. *
  31379. * @type {Object}
  31380. */
  31381. this.requestHeader = {};
  31382. }
  31383. /**
  31384. * This method needs to be implemented by all concrete loaders. It holds the
  31385. * logic for loading assets from the backend.
  31386. *
  31387. * @param {string} url - The path/URL of the file to be loaded.
  31388. * @param {Function} onLoad - Executed when the loading process has been finished.
  31389. * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
  31390. * @param {onErrorCallback} onError - Executed when errors occur.
  31391. */
  31392. load( /* url, onLoad, onProgress, onError */ ) {}
  31393. /**
  31394. * A async version of {@link Loader#load}.
  31395. *
  31396. * @param {string} url - The path/URL of the file to be loaded.
  31397. * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
  31398. * @return {Promise} A Promise that resolves when the asset has been loaded.
  31399. */
  31400. loadAsync( url, onProgress ) {
  31401. const scope = this;
  31402. return new Promise( function ( resolve, reject ) {
  31403. scope.load( url, resolve, onProgress, reject );
  31404. } );
  31405. }
  31406. /**
  31407. * This method needs to be implemented by all concrete loaders. It holds the
  31408. * logic for parsing the asset into three.js entities.
  31409. *
  31410. * @param {any} data - The data to parse.
  31411. */
  31412. parse( /* data */ ) {}
  31413. /**
  31414. * Sets the `crossOrigin` String to implement CORS for loading the URL
  31415. * from a different domain that allows CORS.
  31416. *
  31417. * @param {string} crossOrigin - The `crossOrigin` value.
  31418. * @return {Loader} A reference to this instance.
  31419. */
  31420. setCrossOrigin( crossOrigin ) {
  31421. this.crossOrigin = crossOrigin;
  31422. return this;
  31423. }
  31424. /**
  31425. * Whether the XMLHttpRequest uses credentials such as cookies, authorization
  31426. * headers or TLS client certificates, see [XMLHttpRequest.withCredentials]{@link https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/withCredentials}.
  31427. *
  31428. * Note: This setting has no effect if you are loading files locally or from the same domain.
  31429. *
  31430. * @param {boolean} value - The `withCredentials` value.
  31431. * @return {Loader} A reference to this instance.
  31432. */
  31433. setWithCredentials( value ) {
  31434. this.withCredentials = value;
  31435. return this;
  31436. }
  31437. /**
  31438. * Sets the base path for the asset.
  31439. *
  31440. * @param {string} path - The base path.
  31441. * @return {Loader} A reference to this instance.
  31442. */
  31443. setPath( path ) {
  31444. this.path = path;
  31445. return this;
  31446. }
  31447. /**
  31448. * Sets the base path for dependent resources like textures.
  31449. *
  31450. * @param {string} resourcePath - The resource path.
  31451. * @return {Loader} A reference to this instance.
  31452. */
  31453. setResourcePath( resourcePath ) {
  31454. this.resourcePath = resourcePath;
  31455. return this;
  31456. }
  31457. /**
  31458. * Sets the given request header.
  31459. *
  31460. * @param {Object} requestHeader - A [request header]{@link https://developer.mozilla.org/en-US/docs/Glossary/Request_header}
  31461. * for configuring the HTTP request.
  31462. * @return {Loader} A reference to this instance.
  31463. */
  31464. setRequestHeader( requestHeader ) {
  31465. this.requestHeader = requestHeader;
  31466. return this;
  31467. }
  31468. }
  31469. /**
  31470. * Callback for onProgress in loaders.
  31471. *
  31472. * @callback onProgressCallback
  31473. * @param {ProgressEvent} event - An instance of `ProgressEvent` that represents the current loading status.
  31474. */
  31475. /**
  31476. * Callback for onError in loaders.
  31477. *
  31478. * @callback onErrorCallback
  31479. * @param {Error} error - The error which occurred during the loading process.
  31480. */
  31481. /**
  31482. * The default material name that is used by loaders
  31483. * when creating materials for loaded 3D objects.
  31484. *
  31485. * Note: Not all loaders might honor this setting.
  31486. *
  31487. * @static
  31488. * @type {string}
  31489. * @default '__DEFAULT'
  31490. */
  31491. Loader.DEFAULT_MATERIAL_NAME = '__DEFAULT';
  31492. const loading = {};
  31493. class HttpError extends Error {
  31494. constructor( message, response ) {
  31495. super( message );
  31496. this.response = response;
  31497. }
  31498. }
  31499. /**
  31500. * A low level class for loading resources with the Fetch API, used internally by
  31501. * most loaders. It can also be used directly to load any file type that does
  31502. * not have a loader.
  31503. *
  31504. * This loader supports caching. If you want to use it, add `THREE.Cache.enabled = true;`
  31505. * once to your application.
  31506. *
  31507. * ```js
  31508. * const loader = new THREE.FileLoader();
  31509. * const data = await loader.loadAsync( 'example.txt' );
  31510. * ```
  31511. *
  31512. * @augments Loader
  31513. */
  31514. class FileLoader extends Loader {
  31515. /**
  31516. * Constructs a new file loader.
  31517. *
  31518. * @param {LoadingManager} [manager] - The loading manager.
  31519. */
  31520. constructor( manager ) {
  31521. super( manager );
  31522. /**
  31523. * The expected mime type.
  31524. *
  31525. * @type {string}
  31526. */
  31527. this.mimeType = '';
  31528. /**
  31529. * The expected response type.
  31530. *
  31531. * @type {('arraybuffer'|'blob'|'document'|'json'|'')}
  31532. * @default ''
  31533. */
  31534. this.responseType = '';
  31535. }
  31536. /**
  31537. * Starts loading from the given URL and pass the loaded response to the `onLoad()` callback.
  31538. *
  31539. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  31540. * @param {function(any)} onLoad - Executed when the loading process has been finished.
  31541. * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
  31542. * @param {onErrorCallback} onError - Executed when errors occur.
  31543. * @return {any|undefined} The cached resource if available.
  31544. */
  31545. load( url, onLoad, onProgress, onError ) {
  31546. if ( url === undefined ) url = '';
  31547. if ( this.path !== undefined ) url = this.path + url;
  31548. url = this.manager.resolveURL( url );
  31549. const cached = Cache.get( url );
  31550. if ( cached !== undefined ) {
  31551. this.manager.itemStart( url );
  31552. setTimeout( () => {
  31553. if ( onLoad ) onLoad( cached );
  31554. this.manager.itemEnd( url );
  31555. }, 0 );
  31556. return cached;
  31557. }
  31558. // Check if request is duplicate
  31559. if ( loading[ url ] !== undefined ) {
  31560. loading[ url ].push( {
  31561. onLoad: onLoad,
  31562. onProgress: onProgress,
  31563. onError: onError
  31564. } );
  31565. return;
  31566. }
  31567. // Initialise array for duplicate requests
  31568. loading[ url ] = [];
  31569. loading[ url ].push( {
  31570. onLoad: onLoad,
  31571. onProgress: onProgress,
  31572. onError: onError,
  31573. } );
  31574. // create request
  31575. const req = new Request( url, {
  31576. headers: new Headers( this.requestHeader ),
  31577. credentials: this.withCredentials ? 'include' : 'same-origin',
  31578. // An abort controller could be added within a future PR
  31579. } );
  31580. // record states ( avoid data race )
  31581. const mimeType = this.mimeType;
  31582. const responseType = this.responseType;
  31583. // start the fetch
  31584. fetch( req )
  31585. .then( response => {
  31586. if ( response.status === 200 || response.status === 0 ) {
  31587. // Some browsers return HTTP Status 0 when using non-http protocol
  31588. // e.g. 'file://' or 'data://'. Handle as success.
  31589. if ( response.status === 0 ) {
  31590. console.warn( 'THREE.FileLoader: HTTP Status 0 received.' );
  31591. }
  31592. // Workaround: Checking if response.body === undefined for Alipay browser #23548
  31593. if ( typeof ReadableStream === 'undefined' || response.body === undefined || response.body.getReader === undefined ) {
  31594. return response;
  31595. }
  31596. const callbacks = loading[ url ];
  31597. const reader = response.body.getReader();
  31598. // Nginx needs X-File-Size check
  31599. // https://serverfault.com/questions/482875/why-does-nginx-remove-content-length-header-for-chunked-content
  31600. const contentLength = response.headers.get( 'X-File-Size' ) || response.headers.get( 'Content-Length' );
  31601. const total = contentLength ? parseInt( contentLength ) : 0;
  31602. const lengthComputable = total !== 0;
  31603. let loaded = 0;
  31604. // periodically read data into the new stream tracking while download progress
  31605. const stream = new ReadableStream( {
  31606. start( controller ) {
  31607. readData();
  31608. function readData() {
  31609. reader.read().then( ( { done, value } ) => {
  31610. if ( done ) {
  31611. controller.close();
  31612. } else {
  31613. loaded += value.byteLength;
  31614. const event = new ProgressEvent( 'progress', { lengthComputable, loaded, total } );
  31615. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  31616. const callback = callbacks[ i ];
  31617. if ( callback.onProgress ) callback.onProgress( event );
  31618. }
  31619. controller.enqueue( value );
  31620. readData();
  31621. }
  31622. }, ( e ) => {
  31623. controller.error( e );
  31624. } );
  31625. }
  31626. }
  31627. } );
  31628. return new Response( stream );
  31629. } else {
  31630. throw new HttpError( `fetch for "${response.url}" responded with ${response.status}: ${response.statusText}`, response );
  31631. }
  31632. } )
  31633. .then( response => {
  31634. switch ( responseType ) {
  31635. case 'arraybuffer':
  31636. return response.arrayBuffer();
  31637. case 'blob':
  31638. return response.blob();
  31639. case 'document':
  31640. return response.text()
  31641. .then( text => {
  31642. const parser = new DOMParser();
  31643. return parser.parseFromString( text, mimeType );
  31644. } );
  31645. case 'json':
  31646. return response.json();
  31647. default:
  31648. if ( mimeType === '' ) {
  31649. return response.text();
  31650. } else {
  31651. // sniff encoding
  31652. const re = /charset="?([^;"\s]*)"?/i;
  31653. const exec = re.exec( mimeType );
  31654. const label = exec && exec[ 1 ] ? exec[ 1 ].toLowerCase() : undefined;
  31655. const decoder = new TextDecoder( label );
  31656. return response.arrayBuffer().then( ab => decoder.decode( ab ) );
  31657. }
  31658. }
  31659. } )
  31660. .then( data => {
  31661. // Add to cache only on HTTP success, so that we do not cache
  31662. // error response bodies as proper responses to requests.
  31663. Cache.add( url, data );
  31664. const callbacks = loading[ url ];
  31665. delete loading[ url ];
  31666. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  31667. const callback = callbacks[ i ];
  31668. if ( callback.onLoad ) callback.onLoad( data );
  31669. }
  31670. } )
  31671. .catch( err => {
  31672. // Abort errors and other errors are handled the same
  31673. const callbacks = loading[ url ];
  31674. if ( callbacks === undefined ) {
  31675. // When onLoad was called and url was deleted in `loading`
  31676. this.manager.itemError( url );
  31677. throw err;
  31678. }
  31679. delete loading[ url ];
  31680. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  31681. const callback = callbacks[ i ];
  31682. if ( callback.onError ) callback.onError( err );
  31683. }
  31684. this.manager.itemError( url );
  31685. } )
  31686. .finally( () => {
  31687. this.manager.itemEnd( url );
  31688. } );
  31689. this.manager.itemStart( url );
  31690. }
  31691. /**
  31692. * Sets the expected response type.
  31693. *
  31694. * @param {('arraybuffer'|'blob'|'document'|'json'|'')} value - The response type.
  31695. * @return {FileLoader} A reference to this file loader.
  31696. */
  31697. setResponseType( value ) {
  31698. this.responseType = value;
  31699. return this;
  31700. }
  31701. /**
  31702. * Sets the expected mime type of the loaded file.
  31703. *
  31704. * @param {string} value - The mime type.
  31705. * @return {FileLoader} A reference to this file loader.
  31706. */
  31707. setMimeType( value ) {
  31708. this.mimeType = value;
  31709. return this;
  31710. }
  31711. }
  31712. /**
  31713. * Class for loading animation clips in the JSON format. The files are internally
  31714. * loaded via {@link FileLoader}.
  31715. *
  31716. * ```js
  31717. * const loader = new THREE.AnimationLoader();
  31718. * const animations = await loader.loadAsync( 'animations/animation.js' );
  31719. * ```
  31720. *
  31721. * @augments Loader
  31722. */
  31723. class AnimationLoader extends Loader {
  31724. /**
  31725. * Constructs a new animation loader.
  31726. *
  31727. * @param {LoadingManager} [manager] - The loading manager.
  31728. */
  31729. constructor( manager ) {
  31730. super( manager );
  31731. }
  31732. /**
  31733. * Starts loading from the given URL and pass the loaded animations as an array
  31734. * holding instances of {@link AnimationClip} to the `onLoad()` callback.
  31735. *
  31736. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  31737. * @param {function(Array<AnimationClip>)} onLoad - Executed when the loading process has been finished.
  31738. * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
  31739. * @param {onErrorCallback} onError - Executed when errors occur.
  31740. */
  31741. load( url, onLoad, onProgress, onError ) {
  31742. const scope = this;
  31743. const loader = new FileLoader( this.manager );
  31744. loader.setPath( this.path );
  31745. loader.setRequestHeader( this.requestHeader );
  31746. loader.setWithCredentials( this.withCredentials );
  31747. loader.load( url, function ( text ) {
  31748. try {
  31749. onLoad( scope.parse( JSON.parse( text ) ) );
  31750. } catch ( e ) {
  31751. if ( onError ) {
  31752. onError( e );
  31753. } else {
  31754. console.error( e );
  31755. }
  31756. scope.manager.itemError( url );
  31757. }
  31758. }, onProgress, onError );
  31759. }
  31760. /**
  31761. * Parses the given JSON object and returns an array of animation clips.
  31762. *
  31763. * @param {Object} json - The serialized animation clips.
  31764. * @return {Array<AnimationClip>} The parsed animation clips.
  31765. */
  31766. parse( json ) {
  31767. const animations = [];
  31768. for ( let i = 0; i < json.length; i ++ ) {
  31769. const clip = AnimationClip.parse( json[ i ] );
  31770. animations.push( clip );
  31771. }
  31772. return animations;
  31773. }
  31774. }
  31775. /**
  31776. * Abstract base class for loading compressed texture formats S3TC, ASTC or ETC.
  31777. * Textures are internally loaded via {@link FileLoader}.
  31778. *
  31779. * Derived classes have to implement the `parse()` method which holds the parsing
  31780. * for the respective format.
  31781. *
  31782. * @abstract
  31783. * @augments Loader
  31784. */
  31785. class CompressedTextureLoader extends Loader {
  31786. /**
  31787. * Constructs a new compressed texture loader.
  31788. *
  31789. * @param {LoadingManager} [manager] - The loading manager.
  31790. */
  31791. constructor( manager ) {
  31792. super( manager );
  31793. }
  31794. /**
  31795. * Starts loading from the given URL and passes the loaded compressed texture
  31796. * to the `onLoad()` callback. The method also returns a new texture object which can
  31797. * directly be used for material creation. If you do it this way, the texture
  31798. * may pop up in your scene once the respective loading process is finished.
  31799. *
  31800. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  31801. * @param {function(CompressedTexture)} onLoad - Executed when the loading process has been finished.
  31802. * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
  31803. * @param {onErrorCallback} onError - Executed when errors occur.
  31804. * @return {CompressedTexture} The compressed texture.
  31805. */
  31806. load( url, onLoad, onProgress, onError ) {
  31807. const scope = this;
  31808. const images = [];
  31809. const texture = new CompressedTexture();
  31810. const loader = new FileLoader( this.manager );
  31811. loader.setPath( this.path );
  31812. loader.setResponseType( 'arraybuffer' );
  31813. loader.setRequestHeader( this.requestHeader );
  31814. loader.setWithCredentials( scope.withCredentials );
  31815. let loaded = 0;
  31816. function loadTexture( i ) {
  31817. loader.load( url[ i ], function ( buffer ) {
  31818. const texDatas = scope.parse( buffer, true );
  31819. images[ i ] = {
  31820. width: texDatas.width,
  31821. height: texDatas.height,
  31822. format: texDatas.format,
  31823. mipmaps: texDatas.mipmaps
  31824. };
  31825. loaded += 1;
  31826. if ( loaded === 6 ) {
  31827. if ( texDatas.mipmapCount === 1 ) texture.minFilter = LinearFilter;
  31828. texture.image = images;
  31829. texture.format = texDatas.format;
  31830. texture.needsUpdate = true;
  31831. if ( onLoad ) onLoad( texture );
  31832. }
  31833. }, onProgress, onError );
  31834. }
  31835. if ( Array.isArray( url ) ) {
  31836. for ( let i = 0, il = url.length; i < il; ++ i ) {
  31837. loadTexture( i );
  31838. }
  31839. } else {
  31840. // compressed cubemap texture stored in a single DDS file
  31841. loader.load( url, function ( buffer ) {
  31842. const texDatas = scope.parse( buffer, true );
  31843. if ( texDatas.isCubemap ) {
  31844. const faces = texDatas.mipmaps.length / texDatas.mipmapCount;
  31845. for ( let f = 0; f < faces; f ++ ) {
  31846. images[ f ] = { mipmaps: [] };
  31847. for ( let i = 0; i < texDatas.mipmapCount; i ++ ) {
  31848. images[ f ].mipmaps.push( texDatas.mipmaps[ f * texDatas.mipmapCount + i ] );
  31849. images[ f ].format = texDatas.format;
  31850. images[ f ].width = texDatas.width;
  31851. images[ f ].height = texDatas.height;
  31852. }
  31853. }
  31854. texture.image = images;
  31855. } else {
  31856. texture.image.width = texDatas.width;
  31857. texture.image.height = texDatas.height;
  31858. texture.mipmaps = texDatas.mipmaps;
  31859. }
  31860. if ( texDatas.mipmapCount === 1 ) {
  31861. texture.minFilter = LinearFilter;
  31862. }
  31863. texture.format = texDatas.format;
  31864. texture.needsUpdate = true;
  31865. if ( onLoad ) onLoad( texture );
  31866. }, onProgress, onError );
  31867. }
  31868. return texture;
  31869. }
  31870. }
  31871. /**
  31872. * A loader for loading images. The class loads images with the HTML `Image` API.
  31873. *
  31874. * ```js
  31875. * const loader = new THREE.ImageLoader();
  31876. * const image = await loader.loadAsync( 'image.png' );
  31877. * ```
  31878. * Please note that `ImageLoader` has dropped support for progress
  31879. * events in `r84`. For an `ImageLoader` that supports progress events, see
  31880. * [this thread]{@link https://github.com/mrdoob/three.js/issues/10439#issuecomment-275785639}.
  31881. *
  31882. * @augments Loader
  31883. */
  31884. class ImageLoader extends Loader {
  31885. /**
  31886. * Constructs a new image loader.
  31887. *
  31888. * @param {LoadingManager} [manager] - The loading manager.
  31889. */
  31890. constructor( manager ) {
  31891. super( manager );
  31892. }
  31893. /**
  31894. * Starts loading from the given URL and passes the loaded image
  31895. * to the `onLoad()` callback. The method also returns a new `Image` object which can
  31896. * directly be used for texture creation. If you do it this way, the texture
  31897. * may pop up in your scene once the respective loading process is finished.
  31898. *
  31899. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  31900. * @param {function(Image)} onLoad - Executed when the loading process has been finished.
  31901. * @param {onProgressCallback} onProgress - Unsupported in this loader.
  31902. * @param {onErrorCallback} onError - Executed when errors occur.
  31903. * @return {Image} The image.
  31904. */
  31905. load( url, onLoad, onProgress, onError ) {
  31906. if ( this.path !== undefined ) url = this.path + url;
  31907. url = this.manager.resolveURL( url );
  31908. const scope = this;
  31909. const cached = Cache.get( url );
  31910. if ( cached !== undefined ) {
  31911. scope.manager.itemStart( url );
  31912. setTimeout( function () {
  31913. if ( onLoad ) onLoad( cached );
  31914. scope.manager.itemEnd( url );
  31915. }, 0 );
  31916. return cached;
  31917. }
  31918. const image = createElementNS( 'img' );
  31919. function onImageLoad() {
  31920. removeEventListeners();
  31921. Cache.add( url, this );
  31922. if ( onLoad ) onLoad( this );
  31923. scope.manager.itemEnd( url );
  31924. }
  31925. function onImageError( event ) {
  31926. removeEventListeners();
  31927. if ( onError ) onError( event );
  31928. scope.manager.itemError( url );
  31929. scope.manager.itemEnd( url );
  31930. }
  31931. function removeEventListeners() {
  31932. image.removeEventListener( 'load', onImageLoad, false );
  31933. image.removeEventListener( 'error', onImageError, false );
  31934. }
  31935. image.addEventListener( 'load', onImageLoad, false );
  31936. image.addEventListener( 'error', onImageError, false );
  31937. if ( url.slice( 0, 5 ) !== 'data:' ) {
  31938. if ( this.crossOrigin !== undefined ) image.crossOrigin = this.crossOrigin;
  31939. }
  31940. scope.manager.itemStart( url );
  31941. image.src = url;
  31942. return image;
  31943. }
  31944. }
  31945. /**
  31946. * Class for loading cube textures. Images are internally loaded via {@link ImageLoader}.
  31947. *
  31948. * The loader returns an instance of {@link CubeTexture} and expects the cube map to
  31949. * be defined as six separate images representing the sides of a cube. Other cube map definitions
  31950. * like vertical and horizontal cross, column and row layouts are not supported.
  31951. *
  31952. * Note that, by convention, cube maps are specified in a coordinate system
  31953. * in which positive-x is to the right when looking up the positive-z axis --
  31954. * in other words, using a left-handed coordinate system. Since three.js uses
  31955. * a right-handed coordinate system, environment maps used in three.js will
  31956. * have pos-x and neg-x swapped.
  31957. *
  31958. * The loaded cube texture is in sRGB color space. Meaning {@link Texture#colorSpace}
  31959. * is set to `SRGBColorSpace` by default.
  31960. *
  31961. * ```js
  31962. * const loader = new THREE.CubeTextureLoader().setPath( 'textures/cubeMaps/' );
  31963. * const cubeTexture = await loader.loadAsync( [
  31964. * 'px.png', 'nx.png', 'py.png', 'ny.png', 'pz.png', 'nz.png'
  31965. * ] );
  31966. * scene.background = cubeTexture;
  31967. * ```
  31968. *
  31969. * @augments Loader
  31970. */
  31971. class CubeTextureLoader extends Loader {
  31972. /**
  31973. * Constructs a new cube texture loader.
  31974. *
  31975. * @param {LoadingManager} [manager] - The loading manager.
  31976. */
  31977. constructor( manager ) {
  31978. super( manager );
  31979. }
  31980. /**
  31981. * Starts loading from the given URL and pass the fully loaded cube texture
  31982. * to the `onLoad()` callback. The method also returns a new cube texture object which can
  31983. * directly be used for material creation. If you do it this way, the cube texture
  31984. * may pop up in your scene once the respective loading process is finished.
  31985. *
  31986. * @param {Array<string>} urls - Array of 6 URLs to images, one for each side of the
  31987. * cube texture. The urls should be specified in the following order: pos-x,
  31988. * neg-x, pos-y, neg-y, pos-z, neg-z. An array of data URIs are allowed as well.
  31989. * @param {function(CubeTexture)} onLoad - Executed when the loading process has been finished.
  31990. * @param {onProgressCallback} onProgress - Unsupported in this loader.
  31991. * @param {onErrorCallback} onError - Executed when errors occur.
  31992. * @return {CubeTexture} The cube texture.
  31993. */
  31994. load( urls, onLoad, onProgress, onError ) {
  31995. const texture = new CubeTexture();
  31996. texture.colorSpace = SRGBColorSpace;
  31997. const loader = new ImageLoader( this.manager );
  31998. loader.setCrossOrigin( this.crossOrigin );
  31999. loader.setPath( this.path );
  32000. let loaded = 0;
  32001. function loadTexture( i ) {
  32002. loader.load( urls[ i ], function ( image ) {
  32003. texture.images[ i ] = image;
  32004. loaded ++;
  32005. if ( loaded === 6 ) {
  32006. texture.needsUpdate = true;
  32007. if ( onLoad ) onLoad( texture );
  32008. }
  32009. }, undefined, onError );
  32010. }
  32011. for ( let i = 0; i < urls.length; ++ i ) {
  32012. loadTexture( i );
  32013. }
  32014. return texture;
  32015. }
  32016. }
  32017. /**
  32018. * Abstract base class for loading binary texture formats RGBE, EXR or TGA.
  32019. * Textures are internally loaded via {@link FileLoader}.
  32020. *
  32021. * Derived classes have to implement the `parse()` method which holds the parsing
  32022. * for the respective format.
  32023. *
  32024. * @abstract
  32025. * @augments Loader
  32026. */
  32027. class DataTextureLoader extends Loader {
  32028. /**
  32029. * Constructs a new data texture loader.
  32030. *
  32031. * @param {LoadingManager} [manager] - The loading manager.
  32032. */
  32033. constructor( manager ) {
  32034. super( manager );
  32035. }
  32036. /**
  32037. * Starts loading from the given URL and passes the loaded data texture
  32038. * to the `onLoad()` callback. The method also returns a new texture object which can
  32039. * directly be used for material creation. If you do it this way, the texture
  32040. * may pop up in your scene once the respective loading process is finished.
  32041. *
  32042. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  32043. * @param {function(DataTexture)} onLoad - Executed when the loading process has been finished.
  32044. * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
  32045. * @param {onErrorCallback} onError - Executed when errors occur.
  32046. * @return {DataTexture} The data texture.
  32047. */
  32048. load( url, onLoad, onProgress, onError ) {
  32049. const scope = this;
  32050. const texture = new DataTexture();
  32051. const loader = new FileLoader( this.manager );
  32052. loader.setResponseType( 'arraybuffer' );
  32053. loader.setRequestHeader( this.requestHeader );
  32054. loader.setPath( this.path );
  32055. loader.setWithCredentials( scope.withCredentials );
  32056. loader.load( url, function ( buffer ) {
  32057. let texData;
  32058. try {
  32059. texData = scope.parse( buffer );
  32060. } catch ( error ) {
  32061. if ( onError !== undefined ) {
  32062. onError( error );
  32063. } else {
  32064. console.error( error );
  32065. return;
  32066. }
  32067. }
  32068. if ( texData.image !== undefined ) {
  32069. texture.image = texData.image;
  32070. } else if ( texData.data !== undefined ) {
  32071. texture.image.width = texData.width;
  32072. texture.image.height = texData.height;
  32073. texture.image.data = texData.data;
  32074. }
  32075. texture.wrapS = texData.wrapS !== undefined ? texData.wrapS : ClampToEdgeWrapping;
  32076. texture.wrapT = texData.wrapT !== undefined ? texData.wrapT : ClampToEdgeWrapping;
  32077. texture.magFilter = texData.magFilter !== undefined ? texData.magFilter : LinearFilter;
  32078. texture.minFilter = texData.minFilter !== undefined ? texData.minFilter : LinearFilter;
  32079. texture.anisotropy = texData.anisotropy !== undefined ? texData.anisotropy : 1;
  32080. if ( texData.colorSpace !== undefined ) {
  32081. texture.colorSpace = texData.colorSpace;
  32082. }
  32083. if ( texData.flipY !== undefined ) {
  32084. texture.flipY = texData.flipY;
  32085. }
  32086. if ( texData.format !== undefined ) {
  32087. texture.format = texData.format;
  32088. }
  32089. if ( texData.type !== undefined ) {
  32090. texture.type = texData.type;
  32091. }
  32092. if ( texData.mipmaps !== undefined ) {
  32093. texture.mipmaps = texData.mipmaps;
  32094. texture.minFilter = LinearMipmapLinearFilter; // presumably...
  32095. }
  32096. if ( texData.mipmapCount === 1 ) {
  32097. texture.minFilter = LinearFilter;
  32098. }
  32099. if ( texData.generateMipmaps !== undefined ) {
  32100. texture.generateMipmaps = texData.generateMipmaps;
  32101. }
  32102. texture.needsUpdate = true;
  32103. if ( onLoad ) onLoad( texture, texData );
  32104. }, onProgress, onError );
  32105. return texture;
  32106. }
  32107. }
  32108. /**
  32109. * Class for loading textures. Images are internally
  32110. * loaded via {@link ImageLoader}.
  32111. *
  32112. * ```js
  32113. * const loader = new THREE.TextureLoader();
  32114. * const texture = await loader.loadAsync( 'textures/land_ocean_ice_cloud_2048.jpg' );
  32115. *
  32116. * const material = new THREE.MeshBasicMaterial( { map:texture } );
  32117. * ```
  32118. * Please note that `TextureLoader` has dropped support for progress
  32119. * events in `r84`. For a `TextureLoader` that supports progress events, see
  32120. * [this thread]{@link https://github.com/mrdoob/three.js/issues/10439#issuecomment-293260145}.
  32121. *
  32122. * @augments Loader
  32123. */
  32124. class TextureLoader extends Loader {
  32125. /**
  32126. * Constructs a new texture loader.
  32127. *
  32128. * @param {LoadingManager} [manager] - The loading manager.
  32129. */
  32130. constructor( manager ) {
  32131. super( manager );
  32132. }
  32133. /**
  32134. * Starts loading from the given URL and pass the fully loaded texture
  32135. * to the `onLoad()` callback. The method also returns a new texture object which can
  32136. * directly be used for material creation. If you do it this way, the texture
  32137. * may pop up in your scene once the respective loading process is finished.
  32138. *
  32139. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  32140. * @param {function(Texture)} onLoad - Executed when the loading process has been finished.
  32141. * @param {onProgressCallback} onProgress - Unsupported in this loader.
  32142. * @param {onErrorCallback} onError - Executed when errors occur.
  32143. * @return {Texture} The texture.
  32144. */
  32145. load( url, onLoad, onProgress, onError ) {
  32146. const texture = new Texture();
  32147. const loader = new ImageLoader( this.manager );
  32148. loader.setCrossOrigin( this.crossOrigin );
  32149. loader.setPath( this.path );
  32150. loader.load( url, function ( image ) {
  32151. texture.image = image;
  32152. texture.needsUpdate = true;
  32153. if ( onLoad !== undefined ) {
  32154. onLoad( texture );
  32155. }
  32156. }, onProgress, onError );
  32157. return texture;
  32158. }
  32159. }
  32160. /**
  32161. * Abstract base class for lights - all other light types inherit the
  32162. * properties and methods described here.
  32163. *
  32164. * @abstract
  32165. * @augments Object3D
  32166. */
  32167. class Light extends Object3D {
  32168. /**
  32169. * Constructs a new light.
  32170. *
  32171. * @param {(number|Color|string)} [color=0xffffff] - The light's color.
  32172. * @param {number} [intensity=1] - The light's strength/intensity.
  32173. */
  32174. constructor( color, intensity = 1 ) {
  32175. super();
  32176. /**
  32177. * This flag can be used for type testing.
  32178. *
  32179. * @type {boolean}
  32180. * @readonly
  32181. * @default true
  32182. */
  32183. this.isLight = true;
  32184. this.type = 'Light';
  32185. /**
  32186. * The light's color.
  32187. *
  32188. * @type {Color}
  32189. */
  32190. this.color = new Color( color );
  32191. /**
  32192. * The light's intensity.
  32193. *
  32194. * @type {number}
  32195. * @default 1
  32196. */
  32197. this.intensity = intensity;
  32198. }
  32199. /**
  32200. * Frees the GPU-related resources allocated by this instance. Call this
  32201. * method whenever this instance is no longer used in your app.
  32202. */
  32203. dispose() {
  32204. // Empty here in base class; some subclasses override.
  32205. }
  32206. copy( source, recursive ) {
  32207. super.copy( source, recursive );
  32208. this.color.copy( source.color );
  32209. this.intensity = source.intensity;
  32210. return this;
  32211. }
  32212. toJSON( meta ) {
  32213. const data = super.toJSON( meta );
  32214. data.object.color = this.color.getHex();
  32215. data.object.intensity = this.intensity;
  32216. if ( this.groundColor !== undefined ) data.object.groundColor = this.groundColor.getHex();
  32217. if ( this.distance !== undefined ) data.object.distance = this.distance;
  32218. if ( this.angle !== undefined ) data.object.angle = this.angle;
  32219. if ( this.decay !== undefined ) data.object.decay = this.decay;
  32220. if ( this.penumbra !== undefined ) data.object.penumbra = this.penumbra;
  32221. if ( this.shadow !== undefined ) data.object.shadow = this.shadow.toJSON();
  32222. if ( this.target !== undefined ) data.object.target = this.target.uuid;
  32223. return data;
  32224. }
  32225. }
  32226. /**
  32227. * A light source positioned directly above the scene, with color fading from
  32228. * the sky color to the ground color.
  32229. *
  32230. * This light cannot be used to cast shadows.
  32231. *
  32232. * ```js
  32233. * const light = new THREE.HemisphereLight( 0xffffbb, 0x080820, 1 );
  32234. * scene.add( light );
  32235. * ```
  32236. *
  32237. * @augments Light
  32238. */
  32239. class HemisphereLight extends Light {
  32240. /**
  32241. * Constructs a new hemisphere light.
  32242. *
  32243. * @param {(number|Color|string)} [skyColor=0xffffff] - The light's sky color.
  32244. * @param {(number|Color|string)} [groundColor=0xffffff] - The light's ground color.
  32245. * @param {number} [intensity=1] - The light's strength/intensity.
  32246. */
  32247. constructor( skyColor, groundColor, intensity ) {
  32248. super( skyColor, intensity );
  32249. /**
  32250. * This flag can be used for type testing.
  32251. *
  32252. * @type {boolean}
  32253. * @readonly
  32254. * @default true
  32255. */
  32256. this.isHemisphereLight = true;
  32257. this.type = 'HemisphereLight';
  32258. this.position.copy( Object3D.DEFAULT_UP );
  32259. this.updateMatrix();
  32260. /**
  32261. * The light's ground color.
  32262. *
  32263. * @type {Color}
  32264. */
  32265. this.groundColor = new Color( groundColor );
  32266. }
  32267. copy( source, recursive ) {
  32268. super.copy( source, recursive );
  32269. this.groundColor.copy( source.groundColor );
  32270. return this;
  32271. }
  32272. }
  32273. const _projScreenMatrix$1 = /*@__PURE__*/ new Matrix4();
  32274. const _lightPositionWorld$1 = /*@__PURE__*/ new Vector3();
  32275. const _lookTarget$1 = /*@__PURE__*/ new Vector3();
  32276. /**
  32277. * Abstract base class for light shadow classes. These classes
  32278. * represent the shadow configuration for different light types.
  32279. *
  32280. * @abstract
  32281. */
  32282. class LightShadow {
  32283. /**
  32284. * Constructs a new light shadow.
  32285. *
  32286. * @param {Camera} camera - The light's view of the world.
  32287. */
  32288. constructor( camera ) {
  32289. /**
  32290. * The light's view of the world.
  32291. *
  32292. * @type {Camera}
  32293. */
  32294. this.camera = camera;
  32295. /**
  32296. * The intensity of the shadow. The default is `1`.
  32297. * Valid values are in the range `[0, 1]`.
  32298. *
  32299. * @type {number}
  32300. * @default 1
  32301. */
  32302. this.intensity = 1;
  32303. /**
  32304. * Shadow map bias, how much to add or subtract from the normalized depth
  32305. * when deciding whether a surface is in shadow.
  32306. *
  32307. * The default is `0`. Very tiny adjustments here (in the order of `0.0001`)
  32308. * may help reduce artifacts in shadows.
  32309. *
  32310. * @type {number}
  32311. * @default 0
  32312. */
  32313. this.bias = 0;
  32314. /**
  32315. * Defines how much the position used to query the shadow map is offset along
  32316. * the object normal. The default is `0`. Increasing this value can be used to
  32317. * reduce shadow acne especially in large scenes where light shines onto
  32318. * geometry at a shallow angle. The cost is that shadows may appear distorted.
  32319. *
  32320. * @type {number}
  32321. * @default 0
  32322. */
  32323. this.normalBias = 0;
  32324. /**
  32325. * Setting this to values greater than 1 will blur the edges of the shadow.
  32326. * High values will cause unwanted banding effects in the shadows - a greater
  32327. * map size will allow for a higher value to be used here before these effects
  32328. * become visible.
  32329. *
  32330. * The property has no effect when the shadow map type is `PCFSoftShadowMap` and
  32331. * and it is recommended to increase softness by decreasing the shadow map size instead.
  32332. *
  32333. * The property has no effect when the shadow map type is `BasicShadowMap`.
  32334. *
  32335. * @type {number}
  32336. * @default 1
  32337. */
  32338. this.radius = 1;
  32339. /**
  32340. * The amount of samples to use when blurring a VSM shadow map.
  32341. *
  32342. * @type {number}
  32343. * @default 8
  32344. */
  32345. this.blurSamples = 8;
  32346. /**
  32347. * Defines the width and height of the shadow map. Higher values give better quality
  32348. * shadows at the cost of computation time. Values must be powers of two.
  32349. *
  32350. * @type {Vector2}
  32351. * @default (512,512)
  32352. */
  32353. this.mapSize = new Vector2( 512, 512 );
  32354. /**
  32355. * The depth map generated using the internal camera; a location beyond a
  32356. * pixel's depth is in shadow. Computed internally during rendering.
  32357. *
  32358. * @type {?RenderTarget}
  32359. * @default null
  32360. */
  32361. this.map = null;
  32362. /**
  32363. * The distribution map generated using the internal camera; an occlusion is
  32364. * calculated based on the distribution of depths. Computed internally during
  32365. * rendering.
  32366. *
  32367. * @type {?RenderTarget}
  32368. * @default null
  32369. */
  32370. this.mapPass = null;
  32371. /**
  32372. * Model to shadow camera space, to compute location and depth in shadow map.
  32373. * This is computed internally during rendering.
  32374. *
  32375. * @type {Matrix4}
  32376. */
  32377. this.matrix = new Matrix4();
  32378. /**
  32379. * Enables automatic updates of the light's shadow. If you do not require dynamic
  32380. * lighting / shadows, you may set this to `false`.
  32381. *
  32382. * @type {boolean}
  32383. * @default true
  32384. */
  32385. this.autoUpdate = true;
  32386. /**
  32387. * When set to `true`, shadow maps will be updated in the next `render` call.
  32388. * If you have set {@link LightShadow#autoUpdate} to `false`, you will need to
  32389. * set this property to `true` and then make a render call to update the light's shadow.
  32390. *
  32391. * @type {boolean}
  32392. * @default false
  32393. */
  32394. this.needsUpdate = false;
  32395. this._frustum = new Frustum();
  32396. this._frameExtents = new Vector2( 1, 1 );
  32397. this._viewportCount = 1;
  32398. this._viewports = [
  32399. new Vector4( 0, 0, 1, 1 )
  32400. ];
  32401. }
  32402. /**
  32403. * Used internally by the renderer to get the number of viewports that need
  32404. * to be rendered for this shadow.
  32405. *
  32406. * @return {number} The viewport count.
  32407. */
  32408. getViewportCount() {
  32409. return this._viewportCount;
  32410. }
  32411. /**
  32412. * Gets the shadow cameras frustum. Used internally by the renderer to cull objects.
  32413. *
  32414. * @return {Frustum} The shadow camera frustum.
  32415. */
  32416. getFrustum() {
  32417. return this._frustum;
  32418. }
  32419. /**
  32420. * Update the matrices for the camera and shadow, used internally by the renderer.
  32421. *
  32422. * @param {Light} light - The light for which the shadow is being rendered.
  32423. */
  32424. updateMatrices( light ) {
  32425. const shadowCamera = this.camera;
  32426. const shadowMatrix = this.matrix;
  32427. _lightPositionWorld$1.setFromMatrixPosition( light.matrixWorld );
  32428. shadowCamera.position.copy( _lightPositionWorld$1 );
  32429. _lookTarget$1.setFromMatrixPosition( light.target.matrixWorld );
  32430. shadowCamera.lookAt( _lookTarget$1 );
  32431. shadowCamera.updateMatrixWorld();
  32432. _projScreenMatrix$1.multiplyMatrices( shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse );
  32433. this._frustum.setFromProjectionMatrix( _projScreenMatrix$1 );
  32434. shadowMatrix.set(
  32435. 0.5, 0.0, 0.0, 0.5,
  32436. 0.0, 0.5, 0.0, 0.5,
  32437. 0.0, 0.0, 0.5, 0.5,
  32438. 0.0, 0.0, 0.0, 1.0
  32439. );
  32440. shadowMatrix.multiply( _projScreenMatrix$1 );
  32441. }
  32442. /**
  32443. * Returns a viewport definition for the given viewport index.
  32444. *
  32445. * @param {number} viewportIndex - The viewport index.
  32446. * @return {Vector4} The viewport.
  32447. */
  32448. getViewport( viewportIndex ) {
  32449. return this._viewports[ viewportIndex ];
  32450. }
  32451. /**
  32452. * Returns the frame extends.
  32453. *
  32454. * @return {Vector2} The frame extends.
  32455. */
  32456. getFrameExtents() {
  32457. return this._frameExtents;
  32458. }
  32459. /**
  32460. * Frees the GPU-related resources allocated by this instance. Call this
  32461. * method whenever this instance is no longer used in your app.
  32462. */
  32463. dispose() {
  32464. if ( this.map ) {
  32465. this.map.dispose();
  32466. }
  32467. if ( this.mapPass ) {
  32468. this.mapPass.dispose();
  32469. }
  32470. }
  32471. /**
  32472. * Copies the values of the given light shadow instance to this instance.
  32473. *
  32474. * @param {LightShadow} source - The light shadow to copy.
  32475. * @return {LightShadow} A reference to this light shadow instance.
  32476. */
  32477. copy( source ) {
  32478. this.camera = source.camera.clone();
  32479. this.intensity = source.intensity;
  32480. this.bias = source.bias;
  32481. this.radius = source.radius;
  32482. this.mapSize.copy( source.mapSize );
  32483. return this;
  32484. }
  32485. /**
  32486. * Returns a new light shadow instance with copied values from this instance.
  32487. *
  32488. * @return {LightShadow} A clone of this instance.
  32489. */
  32490. clone() {
  32491. return new this.constructor().copy( this );
  32492. }
  32493. /**
  32494. * Serializes the light shadow into JSON.
  32495. *
  32496. * @return {Object} A JSON object representing the serialized light shadow.
  32497. * @see {@link ObjectLoader#parse}
  32498. */
  32499. toJSON() {
  32500. const object = {};
  32501. if ( this.intensity !== 1 ) object.intensity = this.intensity;
  32502. if ( this.bias !== 0 ) object.bias = this.bias;
  32503. if ( this.normalBias !== 0 ) object.normalBias = this.normalBias;
  32504. if ( this.radius !== 1 ) object.radius = this.radius;
  32505. if ( this.mapSize.x !== 512 || this.mapSize.y !== 512 ) object.mapSize = this.mapSize.toArray();
  32506. object.camera = this.camera.toJSON( false ).object;
  32507. delete object.camera.matrix;
  32508. return object;
  32509. }
  32510. }
  32511. /**
  32512. * Represents the shadow configuration of directional lights.
  32513. *
  32514. * @augments LightShadow
  32515. */
  32516. class SpotLightShadow extends LightShadow {
  32517. /**
  32518. * Constructs a new spot light shadow.
  32519. */
  32520. constructor() {
  32521. super( new PerspectiveCamera( 50, 1, 0.5, 500 ) );
  32522. /**
  32523. * This flag can be used for type testing.
  32524. *
  32525. * @type {boolean}
  32526. * @readonly
  32527. * @default true
  32528. */
  32529. this.isSpotLightShadow = true;
  32530. /**
  32531. * Used to focus the shadow camera. The camera's field of view is set as a
  32532. * percentage of the spotlight's field-of-view. Range is `[0, 1]`.
  32533. *
  32534. * @type {number}
  32535. * @default 1
  32536. */
  32537. this.focus = 1;
  32538. }
  32539. updateMatrices( light ) {
  32540. const camera = this.camera;
  32541. const fov = RAD2DEG * 2 * light.angle * this.focus;
  32542. const aspect = this.mapSize.width / this.mapSize.height;
  32543. const far = light.distance || camera.far;
  32544. if ( fov !== camera.fov || aspect !== camera.aspect || far !== camera.far ) {
  32545. camera.fov = fov;
  32546. camera.aspect = aspect;
  32547. camera.far = far;
  32548. camera.updateProjectionMatrix();
  32549. }
  32550. super.updateMatrices( light );
  32551. }
  32552. copy( source ) {
  32553. super.copy( source );
  32554. this.focus = source.focus;
  32555. return this;
  32556. }
  32557. }
  32558. /**
  32559. * This light gets emitted from a single point in one direction, along a cone
  32560. * that increases in size the further from the light it gets.
  32561. *
  32562. * This light can cast shadows - see the {@link SpotLightShadow} for details.
  32563. *
  32564. * ```js
  32565. * // white spotlight shining from the side, modulated by a texture
  32566. * const spotLight = new THREE.SpotLight( 0xffffff );
  32567. * spotLight.position.set( 100, 1000, 100 );
  32568. * spotLight.map = new THREE.TextureLoader().load( url );
  32569. *
  32570. * spotLight.castShadow = true;
  32571. * spotLight.shadow.mapSize.width = 1024;
  32572. * spotLight.shadow.mapSize.height = 1024;
  32573. * spotLight.shadow.camera.near = 500;
  32574. * spotLight.shadow.camera.far = 4000;
  32575. * spotLight.shadow.camera.fov = 30;s
  32576. * ```
  32577. *
  32578. * @augments Light
  32579. */
  32580. class SpotLight extends Light {
  32581. /**
  32582. * Constructs a new spot light.
  32583. *
  32584. * @param {(number|Color|string)} [color=0xffffff] - The light's color.
  32585. * @param {number} [intensity=1] - The light's strength/intensity measured in candela (cd).
  32586. * @param {number} [distance=0] - Maximum range of the light. `0` means no limit.
  32587. * @param {number} [angle=Math.PI/3] - Maximum angle of light dispersion from its direction whose upper bound is `Math.PI/2`.
  32588. * @param {number} [penumbra=0] - Percent of the spotlight cone that is attenuated due to penumbra. Value range is `[0,1]`.
  32589. * @param {number} [decay=2] - The amount the light dims along the distance of the light.
  32590. */
  32591. constructor( color, intensity, distance = 0, angle = Math.PI / 3, penumbra = 0, decay = 2 ) {
  32592. super( color, intensity );
  32593. /**
  32594. * This flag can be used for type testing.
  32595. *
  32596. * @type {boolean}
  32597. * @readonly
  32598. * @default true
  32599. */
  32600. this.isSpotLight = true;
  32601. this.type = 'SpotLight';
  32602. this.position.copy( Object3D.DEFAULT_UP );
  32603. this.updateMatrix();
  32604. /**
  32605. * The spot light points from its position to the
  32606. * target's position.
  32607. *
  32608. * For the target's position to be changed to anything other
  32609. * than the default, it must be added to the scene.
  32610. *
  32611. * It is also possible to set the target to be another 3D object
  32612. * in the scene. The light will now track the target object.
  32613. *
  32614. * @type {Object3D}
  32615. */
  32616. this.target = new Object3D();
  32617. /**
  32618. * Maximum range of the light. `0` means no limit.
  32619. *
  32620. * @type {number}
  32621. * @default 0
  32622. */
  32623. this.distance = distance;
  32624. /**
  32625. * Maximum angle of light dispersion from its direction whose upper bound is `Math.PI/2`.
  32626. *
  32627. * @type {number}
  32628. * @default Math.PI/3
  32629. */
  32630. this.angle = angle;
  32631. /**
  32632. * Percent of the spotlight cone that is attenuated due to penumbra.
  32633. * Value range is `[0,1]`.
  32634. *
  32635. * @type {number}
  32636. * @default 0
  32637. */
  32638. this.penumbra = penumbra;
  32639. /**
  32640. * The amount the light dims along the distance of the light. In context of
  32641. * physically-correct rendering the default value should not be changed.
  32642. *
  32643. * @type {number}
  32644. * @default 2
  32645. */
  32646. this.decay = decay;
  32647. /**
  32648. * A texture used to modulate the color of the light. The spot light
  32649. * color is mixed with the RGB value of this texture, with a ratio
  32650. * corresponding to its alpha value. The cookie-like masking effect is
  32651. * reproduced using pixel values (0, 0, 0, 1-cookie_value).
  32652. *
  32653. * *Warning*: This property is disabled if {@link Object3D#castShadow} is set to `false`.
  32654. *
  32655. * @type {?Texture}
  32656. * @default null
  32657. */
  32658. this.map = null;
  32659. /**
  32660. * This property holds the light's shadow configuration.
  32661. *
  32662. * @type {SpotLightShadow}
  32663. */
  32664. this.shadow = new SpotLightShadow();
  32665. }
  32666. /**
  32667. * The light's power. Power is the luminous power of the light measured in lumens (lm).
  32668. * Changing the power will also change the light's intensity.
  32669. *
  32670. * @type {number}
  32671. */
  32672. get power() {
  32673. // compute the light's luminous power (in lumens) from its intensity (in candela)
  32674. // by convention for a spotlight, luminous power (lm) = π * luminous intensity (cd)
  32675. return this.intensity * Math.PI;
  32676. }
  32677. set power( power ) {
  32678. // set the light's intensity (in candela) from the desired luminous power (in lumens)
  32679. this.intensity = power / Math.PI;
  32680. }
  32681. dispose() {
  32682. this.shadow.dispose();
  32683. }
  32684. copy( source, recursive ) {
  32685. super.copy( source, recursive );
  32686. this.distance = source.distance;
  32687. this.angle = source.angle;
  32688. this.penumbra = source.penumbra;
  32689. this.decay = source.decay;
  32690. this.target = source.target.clone();
  32691. this.shadow = source.shadow.clone();
  32692. return this;
  32693. }
  32694. }
  32695. const _projScreenMatrix = /*@__PURE__*/ new Matrix4();
  32696. const _lightPositionWorld = /*@__PURE__*/ new Vector3();
  32697. const _lookTarget = /*@__PURE__*/ new Vector3();
  32698. /**
  32699. * Represents the shadow configuration of point lights.
  32700. *
  32701. * @augments LightShadow
  32702. */
  32703. class PointLightShadow extends LightShadow {
  32704. /**
  32705. * Constructs a new point light shadow.
  32706. */
  32707. constructor() {
  32708. super( new PerspectiveCamera( 90, 1, 0.5, 500 ) );
  32709. /**
  32710. * This flag can be used for type testing.
  32711. *
  32712. * @type {boolean}
  32713. * @readonly
  32714. * @default true
  32715. */
  32716. this.isPointLightShadow = true;
  32717. this._frameExtents = new Vector2( 4, 2 );
  32718. this._viewportCount = 6;
  32719. this._viewports = [
  32720. // These viewports map a cube-map onto a 2D texture with the
  32721. // following orientation:
  32722. //
  32723. // xzXZ
  32724. // y Y
  32725. //
  32726. // X - Positive x direction
  32727. // x - Negative x direction
  32728. // Y - Positive y direction
  32729. // y - Negative y direction
  32730. // Z - Positive z direction
  32731. // z - Negative z direction
  32732. // positive X
  32733. new Vector4( 2, 1, 1, 1 ),
  32734. // negative X
  32735. new Vector4( 0, 1, 1, 1 ),
  32736. // positive Z
  32737. new Vector4( 3, 1, 1, 1 ),
  32738. // negative Z
  32739. new Vector4( 1, 1, 1, 1 ),
  32740. // positive Y
  32741. new Vector4( 3, 0, 1, 1 ),
  32742. // negative Y
  32743. new Vector4( 1, 0, 1, 1 )
  32744. ];
  32745. this._cubeDirections = [
  32746. new Vector3( 1, 0, 0 ), new Vector3( -1, 0, 0 ), new Vector3( 0, 0, 1 ),
  32747. new Vector3( 0, 0, -1 ), new Vector3( 0, 1, 0 ), new Vector3( 0, -1, 0 )
  32748. ];
  32749. this._cubeUps = [
  32750. new Vector3( 0, 1, 0 ), new Vector3( 0, 1, 0 ), new Vector3( 0, 1, 0 ),
  32751. new Vector3( 0, 1, 0 ), new Vector3( 0, 0, 1 ), new Vector3( 0, 0, -1 )
  32752. ];
  32753. }
  32754. /**
  32755. * Update the matrices for the camera and shadow, used internally by the renderer.
  32756. *
  32757. * @param {Light} light - The light for which the shadow is being rendered.
  32758. * @param {number} [viewportIndex=0] - The viewport index.
  32759. */
  32760. updateMatrices( light, viewportIndex = 0 ) {
  32761. const camera = this.camera;
  32762. const shadowMatrix = this.matrix;
  32763. const far = light.distance || camera.far;
  32764. if ( far !== camera.far ) {
  32765. camera.far = far;
  32766. camera.updateProjectionMatrix();
  32767. }
  32768. _lightPositionWorld.setFromMatrixPosition( light.matrixWorld );
  32769. camera.position.copy( _lightPositionWorld );
  32770. _lookTarget.copy( camera.position );
  32771. _lookTarget.add( this._cubeDirections[ viewportIndex ] );
  32772. camera.up.copy( this._cubeUps[ viewportIndex ] );
  32773. camera.lookAt( _lookTarget );
  32774. camera.updateMatrixWorld();
  32775. shadowMatrix.makeTranslation( - _lightPositionWorld.x, - _lightPositionWorld.y, - _lightPositionWorld.z );
  32776. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  32777. this._frustum.setFromProjectionMatrix( _projScreenMatrix );
  32778. }
  32779. }
  32780. /**
  32781. * A light that gets emitted from a single point in all directions. A common
  32782. * use case for this is to replicate the light emitted from a bare
  32783. * lightbulb.
  32784. *
  32785. * This light can cast shadows - see the {@link PointLightShadow} for details.
  32786. *
  32787. * ```js
  32788. * const light = new THREE.PointLight( 0xff0000, 1, 100 );
  32789. * light.position.set( 50, 50, 50 );
  32790. * scene.add( light );
  32791. * ```
  32792. *
  32793. * @augments Light
  32794. */
  32795. class PointLight extends Light {
  32796. /**
  32797. * Constructs a new point light.
  32798. *
  32799. * @param {(number|Color|string)} [color=0xffffff] - The light's color.
  32800. * @param {number} [intensity=1] - The light's strength/intensity measured in candela (cd).
  32801. * @param {number} [distance=0] - Maximum range of the light. `0` means no limit.
  32802. * @param {number} [decay=2] - The amount the light dims along the distance of the light.
  32803. */
  32804. constructor( color, intensity, distance = 0, decay = 2 ) {
  32805. super( color, intensity );
  32806. /**
  32807. * This flag can be used for type testing.
  32808. *
  32809. * @type {boolean}
  32810. * @readonly
  32811. * @default true
  32812. */
  32813. this.isPointLight = true;
  32814. this.type = 'PointLight';
  32815. /**
  32816. * When distance is zero, light will attenuate according to inverse-square
  32817. * law to infinite distance. When distance is non-zero, light will attenuate
  32818. * according to inverse-square law until near the distance cutoff, where it
  32819. * will then attenuate quickly and smoothly to 0. Inherently, cutoffs are not
  32820. * physically correct.
  32821. *
  32822. * @type {number}
  32823. * @default 0
  32824. */
  32825. this.distance = distance;
  32826. /**
  32827. * The amount the light dims along the distance of the light. In context of
  32828. * physically-correct rendering the default value should not be changed.
  32829. *
  32830. * @type {number}
  32831. * @default 2
  32832. */
  32833. this.decay = decay;
  32834. /**
  32835. * This property holds the light's shadow configuration.
  32836. *
  32837. * @type {PointLightShadow}
  32838. */
  32839. this.shadow = new PointLightShadow();
  32840. }
  32841. /**
  32842. * The light's power. Power is the luminous power of the light measured in lumens (lm).
  32843. * Changing the power will also change the light's intensity.
  32844. *
  32845. * @type {number}
  32846. */
  32847. get power() {
  32848. // compute the light's luminous power (in lumens) from its intensity (in candela)
  32849. // for an isotropic light source, luminous power (lm) = 4 π luminous intensity (cd)
  32850. return this.intensity * 4 * Math.PI;
  32851. }
  32852. set power( power ) {
  32853. // set the light's intensity (in candela) from the desired luminous power (in lumens)
  32854. this.intensity = power / ( 4 * Math.PI );
  32855. }
  32856. dispose() {
  32857. this.shadow.dispose();
  32858. }
  32859. copy( source, recursive ) {
  32860. super.copy( source, recursive );
  32861. this.distance = source.distance;
  32862. this.decay = source.decay;
  32863. this.shadow = source.shadow.clone();
  32864. return this;
  32865. }
  32866. }
  32867. /**
  32868. * Camera that uses [orthographic projection]{@link https://en.wikipedia.org/wiki/Orthographic_projection}.
  32869. *
  32870. * In this projection mode, an object's size in the rendered image stays
  32871. * constant regardless of its distance from the camera. This can be useful
  32872. * for rendering 2D scenes and UI elements, amongst other things.
  32873. *
  32874. * ```js
  32875. * const camera = new THREE.OrthographicCamera( width / - 2, width / 2, height / 2, height / - 2, 1, 1000 );
  32876. * scene.add( camera );
  32877. * ```
  32878. *
  32879. * @augments Camera
  32880. */
  32881. class OrthographicCamera extends Camera {
  32882. /**
  32883. * Constructs a new orthographic camera.
  32884. *
  32885. * @param {number} [left=-1] - The left plane of the camera's frustum.
  32886. * @param {number} [right=1] - The right plane of the camera's frustum.
  32887. * @param {number} [top=1] - The top plane of the camera's frustum.
  32888. * @param {number} [bottom=-1] - The bottom plane of the camera's frustum.
  32889. * @param {number} [near=0.1] - The camera's near plane.
  32890. * @param {number} [far=2000] - The camera's far plane.
  32891. */
  32892. constructor( left = -1, right = 1, top = 1, bottom = -1, near = 0.1, far = 2000 ) {
  32893. super();
  32894. /**
  32895. * This flag can be used for type testing.
  32896. *
  32897. * @type {boolean}
  32898. * @readonly
  32899. * @default true
  32900. */
  32901. this.isOrthographicCamera = true;
  32902. this.type = 'OrthographicCamera';
  32903. /**
  32904. * The zoom factor of the camera.
  32905. *
  32906. * @type {number}
  32907. * @default 1
  32908. */
  32909. this.zoom = 1;
  32910. /**
  32911. * Represents the frustum window specification. This property should not be edited
  32912. * directly but via {@link PerspectiveCamera#setViewOffset} and {@link PerspectiveCamera#clearViewOffset}.
  32913. *
  32914. * @type {?Object}
  32915. * @default null
  32916. */
  32917. this.view = null;
  32918. /**
  32919. * The left plane of the camera's frustum.
  32920. *
  32921. * @type {number}
  32922. * @default -1
  32923. */
  32924. this.left = left;
  32925. /**
  32926. * The right plane of the camera's frustum.
  32927. *
  32928. * @type {number}
  32929. * @default 1
  32930. */
  32931. this.right = right;
  32932. /**
  32933. * The top plane of the camera's frustum.
  32934. *
  32935. * @type {number}
  32936. * @default 1
  32937. */
  32938. this.top = top;
  32939. /**
  32940. * The bottom plane of the camera's frustum.
  32941. *
  32942. * @type {number}
  32943. * @default -1
  32944. */
  32945. this.bottom = bottom;
  32946. /**
  32947. * The camera's near plane. The valid range is greater than `0`
  32948. * and less than the current value of {@link OrthographicCamera#far}.
  32949. *
  32950. * Note that, unlike for the {@link PerspectiveCamera}, `0` is a
  32951. * valid value for an orthographic camera's near plane.
  32952. *
  32953. * @type {number}
  32954. * @default 0.1
  32955. */
  32956. this.near = near;
  32957. /**
  32958. * The camera's far plane. Must be greater than the
  32959. * current value of {@link OrthographicCamera#near}.
  32960. *
  32961. * @type {number}
  32962. * @default 2000
  32963. */
  32964. this.far = far;
  32965. this.updateProjectionMatrix();
  32966. }
  32967. copy( source, recursive ) {
  32968. super.copy( source, recursive );
  32969. this.left = source.left;
  32970. this.right = source.right;
  32971. this.top = source.top;
  32972. this.bottom = source.bottom;
  32973. this.near = source.near;
  32974. this.far = source.far;
  32975. this.zoom = source.zoom;
  32976. this.view = source.view === null ? null : Object.assign( {}, source.view );
  32977. return this;
  32978. }
  32979. /**
  32980. * Sets an offset in a larger frustum. This is useful for multi-window or
  32981. * multi-monitor/multi-machine setups.
  32982. *
  32983. * @param {number} fullWidth - The full width of multiview setup.
  32984. * @param {number} fullHeight - The full height of multiview setup.
  32985. * @param {number} x - The horizontal offset of the subcamera.
  32986. * @param {number} y - The vertical offset of the subcamera.
  32987. * @param {number} width - The width of subcamera.
  32988. * @param {number} height - The height of subcamera.
  32989. * @see {@link PerspectiveCamera#setViewOffset}
  32990. */
  32991. setViewOffset( fullWidth, fullHeight, x, y, width, height ) {
  32992. if ( this.view === null ) {
  32993. this.view = {
  32994. enabled: true,
  32995. fullWidth: 1,
  32996. fullHeight: 1,
  32997. offsetX: 0,
  32998. offsetY: 0,
  32999. width: 1,
  33000. height: 1
  33001. };
  33002. }
  33003. this.view.enabled = true;
  33004. this.view.fullWidth = fullWidth;
  33005. this.view.fullHeight = fullHeight;
  33006. this.view.offsetX = x;
  33007. this.view.offsetY = y;
  33008. this.view.width = width;
  33009. this.view.height = height;
  33010. this.updateProjectionMatrix();
  33011. }
  33012. /**
  33013. * Removes the view offset from the projection matrix.
  33014. */
  33015. clearViewOffset() {
  33016. if ( this.view !== null ) {
  33017. this.view.enabled = false;
  33018. }
  33019. this.updateProjectionMatrix();
  33020. }
  33021. /**
  33022. * Updates the camera's projection matrix. Must be called after any change of
  33023. * camera properties.
  33024. */
  33025. updateProjectionMatrix() {
  33026. const dx = ( this.right - this.left ) / ( 2 * this.zoom );
  33027. const dy = ( this.top - this.bottom ) / ( 2 * this.zoom );
  33028. const cx = ( this.right + this.left ) / 2;
  33029. const cy = ( this.top + this.bottom ) / 2;
  33030. let left = cx - dx;
  33031. let right = cx + dx;
  33032. let top = cy + dy;
  33033. let bottom = cy - dy;
  33034. if ( this.view !== null && this.view.enabled ) {
  33035. const scaleW = ( this.right - this.left ) / this.view.fullWidth / this.zoom;
  33036. const scaleH = ( this.top - this.bottom ) / this.view.fullHeight / this.zoom;
  33037. left += scaleW * this.view.offsetX;
  33038. right = left + scaleW * this.view.width;
  33039. top -= scaleH * this.view.offsetY;
  33040. bottom = top - scaleH * this.view.height;
  33041. }
  33042. this.projectionMatrix.makeOrthographic( left, right, top, bottom, this.near, this.far, this.coordinateSystem );
  33043. this.projectionMatrixInverse.copy( this.projectionMatrix ).invert();
  33044. }
  33045. toJSON( meta ) {
  33046. const data = super.toJSON( meta );
  33047. data.object.zoom = this.zoom;
  33048. data.object.left = this.left;
  33049. data.object.right = this.right;
  33050. data.object.top = this.top;
  33051. data.object.bottom = this.bottom;
  33052. data.object.near = this.near;
  33053. data.object.far = this.far;
  33054. if ( this.view !== null ) data.object.view = Object.assign( {}, this.view );
  33055. return data;
  33056. }
  33057. }
  33058. /**
  33059. * Represents the shadow configuration of directional lights.
  33060. *
  33061. * @augments LightShadow
  33062. */
  33063. class DirectionalLightShadow extends LightShadow {
  33064. /**
  33065. * Constructs a new directional light shadow.
  33066. */
  33067. constructor() {
  33068. super( new OrthographicCamera( -5, 5, 5, -5, 0.5, 500 ) );
  33069. /**
  33070. * This flag can be used for type testing.
  33071. *
  33072. * @type {boolean}
  33073. * @readonly
  33074. * @default true
  33075. */
  33076. this.isDirectionalLightShadow = true;
  33077. }
  33078. }
  33079. /**
  33080. * A light that gets emitted in a specific direction. This light will behave
  33081. * as though it is infinitely far away and the rays produced from it are all
  33082. * parallel. The common use case for this is to simulate daylight; the sun is
  33083. * far enough away that its position can be considered to be infinite, and
  33084. * all light rays coming from it are parallel.
  33085. *
  33086. * A common point of confusion for directional lights is that setting the
  33087. * rotation has no effect. This is because three.js's DirectionalLight is the
  33088. * equivalent to what is often called a 'Target Direct Light' in other
  33089. * applications.
  33090. *
  33091. * This means that its direction is calculated as pointing from the light's
  33092. * {@link Object3D#position} to the {@link DirectionalLight#target} position
  33093. * (as opposed to a 'Free Direct Light' that just has a rotation
  33094. * component).
  33095. *
  33096. * This light can cast shadows - see the {@link DirectionalLightShadow} for details.
  33097. *
  33098. * ```js
  33099. * // White directional light at half intensity shining from the top.
  33100. * const directionalLight = new THREE.DirectionalLight( 0xffffff, 0.5 );
  33101. * scene.add( directionalLight );
  33102. * ```
  33103. *
  33104. * @augments Light
  33105. */
  33106. class DirectionalLight extends Light {
  33107. /**
  33108. * Constructs a new directional light.
  33109. *
  33110. * @param {(number|Color|string)} [color=0xffffff] - The light's color.
  33111. * @param {number} [intensity=1] - The light's strength/intensity.
  33112. */
  33113. constructor( color, intensity ) {
  33114. super( color, intensity );
  33115. /**
  33116. * This flag can be used for type testing.
  33117. *
  33118. * @type {boolean}
  33119. * @readonly
  33120. * @default true
  33121. */
  33122. this.isDirectionalLight = true;
  33123. this.type = 'DirectionalLight';
  33124. this.position.copy( Object3D.DEFAULT_UP );
  33125. this.updateMatrix();
  33126. /**
  33127. * The directional light points from its position to the
  33128. * target's position.
  33129. *
  33130. * For the target's position to be changed to anything other
  33131. * than the default, it must be added to the scene.
  33132. *
  33133. * It is also possible to set the target to be another 3D object
  33134. * in the scene. The light will now track the target object.
  33135. *
  33136. * @type {Object3D}
  33137. */
  33138. this.target = new Object3D();
  33139. /**
  33140. * This property holds the light's shadow configuration.
  33141. *
  33142. * @type {DirectionalLightShadow}
  33143. */
  33144. this.shadow = new DirectionalLightShadow();
  33145. }
  33146. dispose() {
  33147. this.shadow.dispose();
  33148. }
  33149. copy( source ) {
  33150. super.copy( source );
  33151. this.target = source.target.clone();
  33152. this.shadow = source.shadow.clone();
  33153. return this;
  33154. }
  33155. }
  33156. /**
  33157. * This light globally illuminates all objects in the scene equally.
  33158. *
  33159. * It cannot be used to cast shadows as it does not have a direction.
  33160. *
  33161. * ```js
  33162. * const light = new THREE.AmbientLight( 0x404040 ); // soft white light
  33163. * scene.add( light );
  33164. * ```
  33165. *
  33166. * @augments Light
  33167. */
  33168. class AmbientLight extends Light {
  33169. /**
  33170. * Constructs a new ambient light.
  33171. *
  33172. * @param {(number|Color|string)} [color=0xffffff] - The light's color.
  33173. * @param {number} [intensity=1] - The light's strength/intensity.
  33174. */
  33175. constructor( color, intensity ) {
  33176. super( color, intensity );
  33177. /**
  33178. * This flag can be used for type testing.
  33179. *
  33180. * @type {boolean}
  33181. * @readonly
  33182. * @default true
  33183. */
  33184. this.isAmbientLight = true;
  33185. this.type = 'AmbientLight';
  33186. }
  33187. }
  33188. /**
  33189. * This class emits light uniformly across the face a rectangular plane.
  33190. * This light type can be used to simulate light sources such as bright
  33191. * windows or strip lighting.
  33192. *
  33193. * Important Notes:
  33194. *
  33195. * - There is no shadow support.
  33196. * - Only PBR materials are supported.
  33197. * - You have to include `RectAreaLightUniformsLib` (`WebGLRenderer`) or `RectAreaLightTexturesLib` (`WebGPURenderer`)
  33198. * into your app and init the uniforms/textures.
  33199. *
  33200. * ```js
  33201. * RectAreaLightUniformsLib.init(); // only relevant for WebGLRenderer
  33202. * THREE.RectAreaLightNode.setLTC( RectAreaLightTexturesLib.init() ); // only relevant for WebGPURenderer
  33203. *
  33204. * const intensity = 1; const width = 10; const height = 10;
  33205. * const rectLight = new THREE.RectAreaLight( 0xffffff, intensity, width, height );
  33206. * rectLight.position.set( 5, 5, 0 );
  33207. * rectLight.lookAt( 0, 0, 0 );
  33208. * scene.add( rectLight )
  33209. * ```
  33210. *
  33211. * @augments Light
  33212. */
  33213. class RectAreaLight extends Light {
  33214. /**
  33215. * Constructs a new area light.
  33216. *
  33217. * @param {(number|Color|string)} [color=0xffffff] - The light's color.
  33218. * @param {number} [intensity=1] - The light's strength/intensity.
  33219. * @param {number} [width=10] - The width of the light.
  33220. * @param {number} [height=10] - The height of the light.
  33221. */
  33222. constructor( color, intensity, width = 10, height = 10 ) {
  33223. super( color, intensity );
  33224. /**
  33225. * This flag can be used for type testing.
  33226. *
  33227. * @type {boolean}
  33228. * @readonly
  33229. * @default true
  33230. */
  33231. this.isRectAreaLight = true;
  33232. this.type = 'RectAreaLight';
  33233. /**
  33234. * The width of the light.
  33235. *
  33236. * @type {number}
  33237. * @default 10
  33238. */
  33239. this.width = width;
  33240. /**
  33241. * The height of the light.
  33242. *
  33243. * @type {number}
  33244. * @default 10
  33245. */
  33246. this.height = height;
  33247. }
  33248. /**
  33249. * The light's power. Power is the luminous power of the light measured in lumens (lm).
  33250. * Changing the power will also change the light's intensity.
  33251. *
  33252. * @type {number}
  33253. */
  33254. get power() {
  33255. // compute the light's luminous power (in lumens) from its intensity (in nits)
  33256. return this.intensity * this.width * this.height * Math.PI;
  33257. }
  33258. set power( power ) {
  33259. // set the light's intensity (in nits) from the desired luminous power (in lumens)
  33260. this.intensity = power / ( this.width * this.height * Math.PI );
  33261. }
  33262. copy( source ) {
  33263. super.copy( source );
  33264. this.width = source.width;
  33265. this.height = source.height;
  33266. return this;
  33267. }
  33268. toJSON( meta ) {
  33269. const data = super.toJSON( meta );
  33270. data.object.width = this.width;
  33271. data.object.height = this.height;
  33272. return data;
  33273. }
  33274. }
  33275. /**
  33276. * Represents a third-order spherical harmonics (SH). Light probes use this class
  33277. * to encode lighting information.
  33278. *
  33279. * - Primary reference: {@link https://graphics.stanford.edu/papers/envmap/envmap.pdf}
  33280. * - Secondary reference: {@link https://www.ppsloan.org/publications/StupidSH36.pdf}
  33281. */
  33282. class SphericalHarmonics3 {
  33283. /**
  33284. * Constructs a new spherical harmonics.
  33285. */
  33286. constructor() {
  33287. /**
  33288. * This flag can be used for type testing.
  33289. *
  33290. * @type {boolean}
  33291. * @readonly
  33292. * @default true
  33293. */
  33294. this.isSphericalHarmonics3 = true;
  33295. /**
  33296. * An array holding the (9) SH coefficients.
  33297. *
  33298. * @type {Array<Vector3>}
  33299. */
  33300. this.coefficients = [];
  33301. for ( let i = 0; i < 9; i ++ ) {
  33302. this.coefficients.push( new Vector3() );
  33303. }
  33304. }
  33305. /**
  33306. * Sets the given SH coefficients to this instance by copying
  33307. * the values.
  33308. *
  33309. * @param {Array<Vector3>} coefficients - The SH coefficients.
  33310. * @return {SphericalHarmonics3} A reference to this spherical harmonics.
  33311. */
  33312. set( coefficients ) {
  33313. for ( let i = 0; i < 9; i ++ ) {
  33314. this.coefficients[ i ].copy( coefficients[ i ] );
  33315. }
  33316. return this;
  33317. }
  33318. /**
  33319. * Sets all SH coefficients to `0`.
  33320. *
  33321. * @return {SphericalHarmonics3} A reference to this spherical harmonics.
  33322. */
  33323. zero() {
  33324. for ( let i = 0; i < 9; i ++ ) {
  33325. this.coefficients[ i ].set( 0, 0, 0 );
  33326. }
  33327. return this;
  33328. }
  33329. /**
  33330. * Returns the radiance in the direction of the given normal.
  33331. *
  33332. * @param {Vector3} normal - The normal vector (assumed to be unit length)
  33333. * @param {Vector3} target - The target vector that is used to store the method's result.
  33334. * @return {Vector3} The radiance.
  33335. */
  33336. getAt( normal, target ) {
  33337. // normal is assumed to be unit length
  33338. const x = normal.x, y = normal.y, z = normal.z;
  33339. const coeff = this.coefficients;
  33340. // band 0
  33341. target.copy( coeff[ 0 ] ).multiplyScalar( 0.282095 );
  33342. // band 1
  33343. target.addScaledVector( coeff[ 1 ], 0.488603 * y );
  33344. target.addScaledVector( coeff[ 2 ], 0.488603 * z );
  33345. target.addScaledVector( coeff[ 3 ], 0.488603 * x );
  33346. // band 2
  33347. target.addScaledVector( coeff[ 4 ], 1.092548 * ( x * y ) );
  33348. target.addScaledVector( coeff[ 5 ], 1.092548 * ( y * z ) );
  33349. target.addScaledVector( coeff[ 6 ], 0.315392 * ( 3.0 * z * z - 1.0 ) );
  33350. target.addScaledVector( coeff[ 7 ], 1.092548 * ( x * z ) );
  33351. target.addScaledVector( coeff[ 8 ], 0.546274 * ( x * x - y * y ) );
  33352. return target;
  33353. }
  33354. /**
  33355. * Returns the irradiance (radiance convolved with cosine lobe) in the
  33356. * direction of the given normal.
  33357. *
  33358. * @param {Vector3} normal - The normal vector (assumed to be unit length)
  33359. * @param {Vector3} target - The target vector that is used to store the method's result.
  33360. * @return {Vector3} The irradiance.
  33361. */
  33362. getIrradianceAt( normal, target ) {
  33363. // normal is assumed to be unit length
  33364. const x = normal.x, y = normal.y, z = normal.z;
  33365. const coeff = this.coefficients;
  33366. // band 0
  33367. target.copy( coeff[ 0 ] ).multiplyScalar( 0.886227 ); // π * 0.282095
  33368. // band 1
  33369. target.addScaledVector( coeff[ 1 ], 2.0 * 0.511664 * y ); // ( 2 * π / 3 ) * 0.488603
  33370. target.addScaledVector( coeff[ 2 ], 2.0 * 0.511664 * z );
  33371. target.addScaledVector( coeff[ 3 ], 2.0 * 0.511664 * x );
  33372. // band 2
  33373. target.addScaledVector( coeff[ 4 ], 2.0 * 0.429043 * x * y ); // ( π / 4 ) * 1.092548
  33374. target.addScaledVector( coeff[ 5 ], 2.0 * 0.429043 * y * z );
  33375. target.addScaledVector( coeff[ 6 ], 0.743125 * z * z - 0.247708 ); // ( π / 4 ) * 0.315392 * 3
  33376. target.addScaledVector( coeff[ 7 ], 2.0 * 0.429043 * x * z );
  33377. target.addScaledVector( coeff[ 8 ], 0.429043 * ( x * x - y * y ) ); // ( π / 4 ) * 0.546274
  33378. return target;
  33379. }
  33380. /**
  33381. * Adds the given SH to this instance.
  33382. *
  33383. * @param {SphericalHarmonics3} sh - The SH to add.
  33384. * @return {SphericalHarmonics3} A reference to this spherical harmonics.
  33385. */
  33386. add( sh ) {
  33387. for ( let i = 0; i < 9; i ++ ) {
  33388. this.coefficients[ i ].add( sh.coefficients[ i ] );
  33389. }
  33390. return this;
  33391. }
  33392. /**
  33393. * A convenience method for performing {@link SphericalHarmonics3#add} and
  33394. * {@link SphericalHarmonics3#scale} at once.
  33395. *
  33396. * @param {SphericalHarmonics3} sh - The SH to add.
  33397. * @param {number} s - The scale factor.
  33398. * @return {SphericalHarmonics3} A reference to this spherical harmonics.
  33399. */
  33400. addScaledSH( sh, s ) {
  33401. for ( let i = 0; i < 9; i ++ ) {
  33402. this.coefficients[ i ].addScaledVector( sh.coefficients[ i ], s );
  33403. }
  33404. return this;
  33405. }
  33406. /**
  33407. * Scales this SH by the given scale factor.
  33408. *
  33409. * @param {number} s - The scale factor.
  33410. * @return {SphericalHarmonics3} A reference to this spherical harmonics.
  33411. */
  33412. scale( s ) {
  33413. for ( let i = 0; i < 9; i ++ ) {
  33414. this.coefficients[ i ].multiplyScalar( s );
  33415. }
  33416. return this;
  33417. }
  33418. /**
  33419. * Linear interpolates between the given SH and this instance by the given
  33420. * alpha factor.
  33421. *
  33422. * @param {SphericalHarmonics3} sh - The SH to interpolate with.
  33423. * @param {number} alpha - The alpha factor.
  33424. * @return {SphericalHarmonics3} A reference to this spherical harmonics.
  33425. */
  33426. lerp( sh, alpha ) {
  33427. for ( let i = 0; i < 9; i ++ ) {
  33428. this.coefficients[ i ].lerp( sh.coefficients[ i ], alpha );
  33429. }
  33430. return this;
  33431. }
  33432. /**
  33433. * Returns `true` if this spherical harmonics is equal with the given one.
  33434. *
  33435. * @param {SphericalHarmonics3} sh - The spherical harmonics to test for equality.
  33436. * @return {boolean} Whether this spherical harmonics is equal with the given one.
  33437. */
  33438. equals( sh ) {
  33439. for ( let i = 0; i < 9; i ++ ) {
  33440. if ( ! this.coefficients[ i ].equals( sh.coefficients[ i ] ) ) {
  33441. return false;
  33442. }
  33443. }
  33444. return true;
  33445. }
  33446. /**
  33447. * Copies the values of the given spherical harmonics to this instance.
  33448. *
  33449. * @param {SphericalHarmonics3} sh - The spherical harmonics to copy.
  33450. * @return {SphericalHarmonics3} A reference to this spherical harmonics.
  33451. */
  33452. copy( sh ) {
  33453. return this.set( sh.coefficients );
  33454. }
  33455. /**
  33456. * Returns a new spherical harmonics with copied values from this instance.
  33457. *
  33458. * @return {SphericalHarmonics3} A clone of this instance.
  33459. */
  33460. clone() {
  33461. return new this.constructor().copy( this );
  33462. }
  33463. /**
  33464. * Sets the SH coefficients of this instance from the given array.
  33465. *
  33466. * @param {Array<number>} array - An array holding the SH coefficients.
  33467. * @param {number} [offset=0] - The array offset where to start copying.
  33468. * @return {SphericalHarmonics3} A clone of this instance.
  33469. */
  33470. fromArray( array, offset = 0 ) {
  33471. const coefficients = this.coefficients;
  33472. for ( let i = 0; i < 9; i ++ ) {
  33473. coefficients[ i ].fromArray( array, offset + ( i * 3 ) );
  33474. }
  33475. return this;
  33476. }
  33477. /**
  33478. * Returns an array with the SH coefficients, or copies them into the provided
  33479. * array. The coefficients are represented as numbers.
  33480. *
  33481. * @param {Array<number>} [array=[]] - The target array.
  33482. * @param {number} [offset=0] - The array offset where to start copying.
  33483. * @return {Array<number>} An array with flat SH coefficients.
  33484. */
  33485. toArray( array = [], offset = 0 ) {
  33486. const coefficients = this.coefficients;
  33487. for ( let i = 0; i < 9; i ++ ) {
  33488. coefficients[ i ].toArray( array, offset + ( i * 3 ) );
  33489. }
  33490. return array;
  33491. }
  33492. /**
  33493. * Computes the SH basis for the given normal vector.
  33494. *
  33495. * @param {Vector3} normal - The normal.
  33496. * @param {Array<number>} shBasis - The target array holding the SH basis.
  33497. */
  33498. static getBasisAt( normal, shBasis ) {
  33499. // normal is assumed to be unit length
  33500. const x = normal.x, y = normal.y, z = normal.z;
  33501. // band 0
  33502. shBasis[ 0 ] = 0.282095;
  33503. // band 1
  33504. shBasis[ 1 ] = 0.488603 * y;
  33505. shBasis[ 2 ] = 0.488603 * z;
  33506. shBasis[ 3 ] = 0.488603 * x;
  33507. // band 2
  33508. shBasis[ 4 ] = 1.092548 * x * y;
  33509. shBasis[ 5 ] = 1.092548 * y * z;
  33510. shBasis[ 6 ] = 0.315392 * ( 3 * z * z - 1 );
  33511. shBasis[ 7 ] = 1.092548 * x * z;
  33512. shBasis[ 8 ] = 0.546274 * ( x * x - y * y );
  33513. }
  33514. }
  33515. /**
  33516. * Light probes are an alternative way of adding light to a 3D scene. Unlike
  33517. * classical light sources (e.g. directional, point or spot lights), light
  33518. * probes do not emit light. Instead they store information about light
  33519. * passing through 3D space. During rendering, the light that hits a 3D
  33520. * object is approximated by using the data from the light probe.
  33521. *
  33522. * Light probes are usually created from (radiance) environment maps. The
  33523. * class {@link LightProbeGenerator} can be used to create light probes from
  33524. * cube textures or render targets. However, light estimation data could also
  33525. * be provided in other forms e.g. by WebXR. This enables the rendering of
  33526. * augmented reality content that reacts to real world lighting.
  33527. *
  33528. * The current probe implementation in three.js supports so-called diffuse
  33529. * light probes. This type of light probe is functionally equivalent to an
  33530. * irradiance environment map.
  33531. *
  33532. * @augments Light
  33533. */
  33534. class LightProbe extends Light {
  33535. /**
  33536. * Constructs a new light probe.
  33537. *
  33538. * @param {SphericalHarmonics3} sh - The spherical harmonics which represents encoded lighting information.
  33539. * @param {number} [intensity=1] - The light's strength/intensity.
  33540. */
  33541. constructor( sh = new SphericalHarmonics3(), intensity = 1 ) {
  33542. super( undefined, intensity );
  33543. /**
  33544. * This flag can be used for type testing.
  33545. *
  33546. * @type {boolean}
  33547. * @readonly
  33548. * @default true
  33549. */
  33550. this.isLightProbe = true;
  33551. /**
  33552. * A light probe uses spherical harmonics to encode lighting information.
  33553. *
  33554. * @type {SphericalHarmonics3}
  33555. */
  33556. this.sh = sh;
  33557. }
  33558. copy( source ) {
  33559. super.copy( source );
  33560. this.sh.copy( source.sh );
  33561. return this;
  33562. }
  33563. /**
  33564. * Deserializes the light prove from the given JSON.
  33565. *
  33566. * @param {Object} json - The JSON holding the serialized light probe.
  33567. * @return {LightProbe} A reference to this light probe.
  33568. */
  33569. fromJSON( json ) {
  33570. this.intensity = json.intensity; // TODO: Move this bit to Light.fromJSON();
  33571. this.sh.fromArray( json.sh );
  33572. return this;
  33573. }
  33574. toJSON( meta ) {
  33575. const data = super.toJSON( meta );
  33576. data.object.sh = this.sh.toArray();
  33577. return data;
  33578. }
  33579. }
  33580. /**
  33581. * Class for loading geometries. The files are internally
  33582. * loaded via {@link FileLoader}.
  33583. *
  33584. * ```js
  33585. * const loader = new THREE.MaterialLoader();
  33586. * const material = await loader.loadAsync( 'material.json' );
  33587. * ```
  33588. * This loader does not support node materials. Use {@link NodeMaterialLoader} instead.
  33589. *
  33590. * @augments Loader
  33591. */
  33592. class MaterialLoader extends Loader {
  33593. /**
  33594. * Constructs a new material loader.
  33595. *
  33596. * @param {LoadingManager} [manager] - The loading manager.
  33597. */
  33598. constructor( manager ) {
  33599. super( manager );
  33600. /**
  33601. * A dictionary holding textures used by the material.
  33602. *
  33603. * @type {Object<string,Texture>}
  33604. */
  33605. this.textures = {};
  33606. }
  33607. /**
  33608. * Starts loading from the given URL and pass the loaded material to the `onLoad()` callback.
  33609. *
  33610. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  33611. * @param {function(Material)} onLoad - Executed when the loading process has been finished.
  33612. * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
  33613. * @param {onErrorCallback} onError - Executed when errors occur.
  33614. */
  33615. load( url, onLoad, onProgress, onError ) {
  33616. const scope = this;
  33617. const loader = new FileLoader( scope.manager );
  33618. loader.setPath( scope.path );
  33619. loader.setRequestHeader( scope.requestHeader );
  33620. loader.setWithCredentials( scope.withCredentials );
  33621. loader.load( url, function ( text ) {
  33622. try {
  33623. onLoad( scope.parse( JSON.parse( text ) ) );
  33624. } catch ( e ) {
  33625. if ( onError ) {
  33626. onError( e );
  33627. } else {
  33628. console.error( e );
  33629. }
  33630. scope.manager.itemError( url );
  33631. }
  33632. }, onProgress, onError );
  33633. }
  33634. /**
  33635. * Parses the given JSON object and returns a material.
  33636. *
  33637. * @param {Object} json - The serialized material.
  33638. * @return {Material} The parsed material.
  33639. */
  33640. parse( json ) {
  33641. const textures = this.textures;
  33642. function getTexture( name ) {
  33643. if ( textures[ name ] === undefined ) {
  33644. console.warn( 'THREE.MaterialLoader: Undefined texture', name );
  33645. }
  33646. return textures[ name ];
  33647. }
  33648. const material = this.createMaterialFromType( json.type );
  33649. if ( json.uuid !== undefined ) material.uuid = json.uuid;
  33650. if ( json.name !== undefined ) material.name = json.name;
  33651. if ( json.color !== undefined && material.color !== undefined ) material.color.setHex( json.color );
  33652. if ( json.roughness !== undefined ) material.roughness = json.roughness;
  33653. if ( json.metalness !== undefined ) material.metalness = json.metalness;
  33654. if ( json.sheen !== undefined ) material.sheen = json.sheen;
  33655. if ( json.sheenColor !== undefined ) material.sheenColor = new Color().setHex( json.sheenColor );
  33656. if ( json.sheenRoughness !== undefined ) material.sheenRoughness = json.sheenRoughness;
  33657. if ( json.emissive !== undefined && material.emissive !== undefined ) material.emissive.setHex( json.emissive );
  33658. if ( json.specular !== undefined && material.specular !== undefined ) material.specular.setHex( json.specular );
  33659. if ( json.specularIntensity !== undefined ) material.specularIntensity = json.specularIntensity;
  33660. if ( json.specularColor !== undefined && material.specularColor !== undefined ) material.specularColor.setHex( json.specularColor );
  33661. if ( json.shininess !== undefined ) material.shininess = json.shininess;
  33662. if ( json.clearcoat !== undefined ) material.clearcoat = json.clearcoat;
  33663. if ( json.clearcoatRoughness !== undefined ) material.clearcoatRoughness = json.clearcoatRoughness;
  33664. if ( json.dispersion !== undefined ) material.dispersion = json.dispersion;
  33665. if ( json.iridescence !== undefined ) material.iridescence = json.iridescence;
  33666. if ( json.iridescenceIOR !== undefined ) material.iridescenceIOR = json.iridescenceIOR;
  33667. if ( json.iridescenceThicknessRange !== undefined ) material.iridescenceThicknessRange = json.iridescenceThicknessRange;
  33668. if ( json.transmission !== undefined ) material.transmission = json.transmission;
  33669. if ( json.thickness !== undefined ) material.thickness = json.thickness;
  33670. if ( json.attenuationDistance !== undefined ) material.attenuationDistance = json.attenuationDistance;
  33671. if ( json.attenuationColor !== undefined && material.attenuationColor !== undefined ) material.attenuationColor.setHex( json.attenuationColor );
  33672. if ( json.anisotropy !== undefined ) material.anisotropy = json.anisotropy;
  33673. if ( json.anisotropyRotation !== undefined ) material.anisotropyRotation = json.anisotropyRotation;
  33674. if ( json.fog !== undefined ) material.fog = json.fog;
  33675. if ( json.flatShading !== undefined ) material.flatShading = json.flatShading;
  33676. if ( json.blending !== undefined ) material.blending = json.blending;
  33677. if ( json.combine !== undefined ) material.combine = json.combine;
  33678. if ( json.side !== undefined ) material.side = json.side;
  33679. if ( json.shadowSide !== undefined ) material.shadowSide = json.shadowSide;
  33680. if ( json.opacity !== undefined ) material.opacity = json.opacity;
  33681. if ( json.transparent !== undefined ) material.transparent = json.transparent;
  33682. if ( json.alphaTest !== undefined ) material.alphaTest = json.alphaTest;
  33683. if ( json.alphaHash !== undefined ) material.alphaHash = json.alphaHash;
  33684. if ( json.depthFunc !== undefined ) material.depthFunc = json.depthFunc;
  33685. if ( json.depthTest !== undefined ) material.depthTest = json.depthTest;
  33686. if ( json.depthWrite !== undefined ) material.depthWrite = json.depthWrite;
  33687. if ( json.colorWrite !== undefined ) material.colorWrite = json.colorWrite;
  33688. if ( json.blendSrc !== undefined ) material.blendSrc = json.blendSrc;
  33689. if ( json.blendDst !== undefined ) material.blendDst = json.blendDst;
  33690. if ( json.blendEquation !== undefined ) material.blendEquation = json.blendEquation;
  33691. if ( json.blendSrcAlpha !== undefined ) material.blendSrcAlpha = json.blendSrcAlpha;
  33692. if ( json.blendDstAlpha !== undefined ) material.blendDstAlpha = json.blendDstAlpha;
  33693. if ( json.blendEquationAlpha !== undefined ) material.blendEquationAlpha = json.blendEquationAlpha;
  33694. if ( json.blendColor !== undefined && material.blendColor !== undefined ) material.blendColor.setHex( json.blendColor );
  33695. if ( json.blendAlpha !== undefined ) material.blendAlpha = json.blendAlpha;
  33696. if ( json.stencilWriteMask !== undefined ) material.stencilWriteMask = json.stencilWriteMask;
  33697. if ( json.stencilFunc !== undefined ) material.stencilFunc = json.stencilFunc;
  33698. if ( json.stencilRef !== undefined ) material.stencilRef = json.stencilRef;
  33699. if ( json.stencilFuncMask !== undefined ) material.stencilFuncMask = json.stencilFuncMask;
  33700. if ( json.stencilFail !== undefined ) material.stencilFail = json.stencilFail;
  33701. if ( json.stencilZFail !== undefined ) material.stencilZFail = json.stencilZFail;
  33702. if ( json.stencilZPass !== undefined ) material.stencilZPass = json.stencilZPass;
  33703. if ( json.stencilWrite !== undefined ) material.stencilWrite = json.stencilWrite;
  33704. if ( json.wireframe !== undefined ) material.wireframe = json.wireframe;
  33705. if ( json.wireframeLinewidth !== undefined ) material.wireframeLinewidth = json.wireframeLinewidth;
  33706. if ( json.wireframeLinecap !== undefined ) material.wireframeLinecap = json.wireframeLinecap;
  33707. if ( json.wireframeLinejoin !== undefined ) material.wireframeLinejoin = json.wireframeLinejoin;
  33708. if ( json.rotation !== undefined ) material.rotation = json.rotation;
  33709. if ( json.linewidth !== undefined ) material.linewidth = json.linewidth;
  33710. if ( json.dashSize !== undefined ) material.dashSize = json.dashSize;
  33711. if ( json.gapSize !== undefined ) material.gapSize = json.gapSize;
  33712. if ( json.scale !== undefined ) material.scale = json.scale;
  33713. if ( json.polygonOffset !== undefined ) material.polygonOffset = json.polygonOffset;
  33714. if ( json.polygonOffsetFactor !== undefined ) material.polygonOffsetFactor = json.polygonOffsetFactor;
  33715. if ( json.polygonOffsetUnits !== undefined ) material.polygonOffsetUnits = json.polygonOffsetUnits;
  33716. if ( json.dithering !== undefined ) material.dithering = json.dithering;
  33717. if ( json.alphaToCoverage !== undefined ) material.alphaToCoverage = json.alphaToCoverage;
  33718. if ( json.premultipliedAlpha !== undefined ) material.premultipliedAlpha = json.premultipliedAlpha;
  33719. if ( json.forceSinglePass !== undefined ) material.forceSinglePass = json.forceSinglePass;
  33720. if ( json.visible !== undefined ) material.visible = json.visible;
  33721. if ( json.toneMapped !== undefined ) material.toneMapped = json.toneMapped;
  33722. if ( json.userData !== undefined ) material.userData = json.userData;
  33723. if ( json.vertexColors !== undefined ) {
  33724. if ( typeof json.vertexColors === 'number' ) {
  33725. material.vertexColors = ( json.vertexColors > 0 ) ? true : false;
  33726. } else {
  33727. material.vertexColors = json.vertexColors;
  33728. }
  33729. }
  33730. // Shader Material
  33731. if ( json.uniforms !== undefined ) {
  33732. for ( const name in json.uniforms ) {
  33733. const uniform = json.uniforms[ name ];
  33734. material.uniforms[ name ] = {};
  33735. switch ( uniform.type ) {
  33736. case 't':
  33737. material.uniforms[ name ].value = getTexture( uniform.value );
  33738. break;
  33739. case 'c':
  33740. material.uniforms[ name ].value = new Color().setHex( uniform.value );
  33741. break;
  33742. case 'v2':
  33743. material.uniforms[ name ].value = new Vector2().fromArray( uniform.value );
  33744. break;
  33745. case 'v3':
  33746. material.uniforms[ name ].value = new Vector3().fromArray( uniform.value );
  33747. break;
  33748. case 'v4':
  33749. material.uniforms[ name ].value = new Vector4().fromArray( uniform.value );
  33750. break;
  33751. case 'm3':
  33752. material.uniforms[ name ].value = new Matrix3().fromArray( uniform.value );
  33753. break;
  33754. case 'm4':
  33755. material.uniforms[ name ].value = new Matrix4().fromArray( uniform.value );
  33756. break;
  33757. default:
  33758. material.uniforms[ name ].value = uniform.value;
  33759. }
  33760. }
  33761. }
  33762. if ( json.defines !== undefined ) material.defines = json.defines;
  33763. if ( json.vertexShader !== undefined ) material.vertexShader = json.vertexShader;
  33764. if ( json.fragmentShader !== undefined ) material.fragmentShader = json.fragmentShader;
  33765. if ( json.glslVersion !== undefined ) material.glslVersion = json.glslVersion;
  33766. if ( json.extensions !== undefined ) {
  33767. for ( const key in json.extensions ) {
  33768. material.extensions[ key ] = json.extensions[ key ];
  33769. }
  33770. }
  33771. if ( json.lights !== undefined ) material.lights = json.lights;
  33772. if ( json.clipping !== undefined ) material.clipping = json.clipping;
  33773. // for PointsMaterial
  33774. if ( json.size !== undefined ) material.size = json.size;
  33775. if ( json.sizeAttenuation !== undefined ) material.sizeAttenuation = json.sizeAttenuation;
  33776. // maps
  33777. if ( json.map !== undefined ) material.map = getTexture( json.map );
  33778. if ( json.matcap !== undefined ) material.matcap = getTexture( json.matcap );
  33779. if ( json.alphaMap !== undefined ) material.alphaMap = getTexture( json.alphaMap );
  33780. if ( json.bumpMap !== undefined ) material.bumpMap = getTexture( json.bumpMap );
  33781. if ( json.bumpScale !== undefined ) material.bumpScale = json.bumpScale;
  33782. if ( json.normalMap !== undefined ) material.normalMap = getTexture( json.normalMap );
  33783. if ( json.normalMapType !== undefined ) material.normalMapType = json.normalMapType;
  33784. if ( json.normalScale !== undefined ) {
  33785. let normalScale = json.normalScale;
  33786. if ( Array.isArray( normalScale ) === false ) {
  33787. // Blender exporter used to export a scalar. See #7459
  33788. normalScale = [ normalScale, normalScale ];
  33789. }
  33790. material.normalScale = new Vector2().fromArray( normalScale );
  33791. }
  33792. if ( json.displacementMap !== undefined ) material.displacementMap = getTexture( json.displacementMap );
  33793. if ( json.displacementScale !== undefined ) material.displacementScale = json.displacementScale;
  33794. if ( json.displacementBias !== undefined ) material.displacementBias = json.displacementBias;
  33795. if ( json.roughnessMap !== undefined ) material.roughnessMap = getTexture( json.roughnessMap );
  33796. if ( json.metalnessMap !== undefined ) material.metalnessMap = getTexture( json.metalnessMap );
  33797. if ( json.emissiveMap !== undefined ) material.emissiveMap = getTexture( json.emissiveMap );
  33798. if ( json.emissiveIntensity !== undefined ) material.emissiveIntensity = json.emissiveIntensity;
  33799. if ( json.specularMap !== undefined ) material.specularMap = getTexture( json.specularMap );
  33800. if ( json.specularIntensityMap !== undefined ) material.specularIntensityMap = getTexture( json.specularIntensityMap );
  33801. if ( json.specularColorMap !== undefined ) material.specularColorMap = getTexture( json.specularColorMap );
  33802. if ( json.envMap !== undefined ) material.envMap = getTexture( json.envMap );
  33803. if ( json.envMapRotation !== undefined ) material.envMapRotation.fromArray( json.envMapRotation );
  33804. if ( json.envMapIntensity !== undefined ) material.envMapIntensity = json.envMapIntensity;
  33805. if ( json.reflectivity !== undefined ) material.reflectivity = json.reflectivity;
  33806. if ( json.refractionRatio !== undefined ) material.refractionRatio = json.refractionRatio;
  33807. if ( json.lightMap !== undefined ) material.lightMap = getTexture( json.lightMap );
  33808. if ( json.lightMapIntensity !== undefined ) material.lightMapIntensity = json.lightMapIntensity;
  33809. if ( json.aoMap !== undefined ) material.aoMap = getTexture( json.aoMap );
  33810. if ( json.aoMapIntensity !== undefined ) material.aoMapIntensity = json.aoMapIntensity;
  33811. if ( json.gradientMap !== undefined ) material.gradientMap = getTexture( json.gradientMap );
  33812. if ( json.clearcoatMap !== undefined ) material.clearcoatMap = getTexture( json.clearcoatMap );
  33813. if ( json.clearcoatRoughnessMap !== undefined ) material.clearcoatRoughnessMap = getTexture( json.clearcoatRoughnessMap );
  33814. if ( json.clearcoatNormalMap !== undefined ) material.clearcoatNormalMap = getTexture( json.clearcoatNormalMap );
  33815. if ( json.clearcoatNormalScale !== undefined ) material.clearcoatNormalScale = new Vector2().fromArray( json.clearcoatNormalScale );
  33816. if ( json.iridescenceMap !== undefined ) material.iridescenceMap = getTexture( json.iridescenceMap );
  33817. if ( json.iridescenceThicknessMap !== undefined ) material.iridescenceThicknessMap = getTexture( json.iridescenceThicknessMap );
  33818. if ( json.transmissionMap !== undefined ) material.transmissionMap = getTexture( json.transmissionMap );
  33819. if ( json.thicknessMap !== undefined ) material.thicknessMap = getTexture( json.thicknessMap );
  33820. if ( json.anisotropyMap !== undefined ) material.anisotropyMap = getTexture( json.anisotropyMap );
  33821. if ( json.sheenColorMap !== undefined ) material.sheenColorMap = getTexture( json.sheenColorMap );
  33822. if ( json.sheenRoughnessMap !== undefined ) material.sheenRoughnessMap = getTexture( json.sheenRoughnessMap );
  33823. return material;
  33824. }
  33825. /**
  33826. * Textures are not embedded in the material JSON so they have
  33827. * to be injected before the loading process starts.
  33828. *
  33829. * @param {Object} value - A dictionary holding textures for material properties.
  33830. * @return {MaterialLoader} A reference to this material loader.
  33831. */
  33832. setTextures( value ) {
  33833. this.textures = value;
  33834. return this;
  33835. }
  33836. /**
  33837. * Creates a material for the given type.
  33838. *
  33839. * @param {string} type - The material type.
  33840. * @return {Material} The new material.
  33841. */
  33842. createMaterialFromType( type ) {
  33843. return MaterialLoader.createMaterialFromType( type );
  33844. }
  33845. /**
  33846. * Creates a material for the given type.
  33847. *
  33848. * @static
  33849. * @param {string} type - The material type.
  33850. * @return {Material} The new material.
  33851. */
  33852. static createMaterialFromType( type ) {
  33853. const materialLib = {
  33854. ShadowMaterial,
  33855. SpriteMaterial,
  33856. RawShaderMaterial,
  33857. ShaderMaterial,
  33858. PointsMaterial,
  33859. MeshPhysicalMaterial,
  33860. MeshStandardMaterial,
  33861. MeshPhongMaterial,
  33862. MeshToonMaterial,
  33863. MeshNormalMaterial,
  33864. MeshLambertMaterial,
  33865. MeshDepthMaterial,
  33866. MeshDistanceMaterial,
  33867. MeshBasicMaterial,
  33868. MeshMatcapMaterial,
  33869. LineDashedMaterial,
  33870. LineBasicMaterial,
  33871. Material
  33872. };
  33873. return new materialLib[ type ]();
  33874. }
  33875. }
  33876. /**
  33877. * A class with loader utility functions.
  33878. */
  33879. class LoaderUtils {
  33880. /**
  33881. * Extracts the base URL from the given URL.
  33882. *
  33883. * @param {string} url -The URL to extract the base URL from.
  33884. * @return {string} The extracted base URL.
  33885. */
  33886. static extractUrlBase( url ) {
  33887. const index = url.lastIndexOf( '/' );
  33888. if ( index === -1 ) return './';
  33889. return url.slice( 0, index + 1 );
  33890. }
  33891. /**
  33892. * Resolves relative URLs against the given path. Absolute paths, data urls,
  33893. * and blob URLs will be returned as is. Invalid URLs will return an empty
  33894. * string.
  33895. *
  33896. * @param {string} url -The URL to resolve.
  33897. * @param {string} path - The base path for relative URLs to be resolved against.
  33898. * @return {string} The resolved URL.
  33899. */
  33900. static resolveURL( url, path ) {
  33901. // Invalid URL
  33902. if ( typeof url !== 'string' || url === '' ) return '';
  33903. // Host Relative URL
  33904. if ( /^https?:\/\//i.test( path ) && /^\//.test( url ) ) {
  33905. path = path.replace( /(^https?:\/\/[^\/]+).*/i, '$1' );
  33906. }
  33907. // Absolute URL http://,https://,//
  33908. if ( /^(https?:)?\/\//i.test( url ) ) return url;
  33909. // Data URI
  33910. if ( /^data:.*,.*$/i.test( url ) ) return url;
  33911. // Blob URL
  33912. if ( /^blob:.*$/i.test( url ) ) return url;
  33913. // Relative URL
  33914. return path + url;
  33915. }
  33916. }
  33917. /**
  33918. * An instanced version of a geometry.
  33919. */
  33920. class InstancedBufferGeometry extends BufferGeometry {
  33921. /**
  33922. * Constructs a new instanced buffer geometry.
  33923. */
  33924. constructor() {
  33925. super();
  33926. /**
  33927. * This flag can be used for type testing.
  33928. *
  33929. * @type {boolean}
  33930. * @readonly
  33931. * @default true
  33932. */
  33933. this.isInstancedBufferGeometry = true;
  33934. this.type = 'InstancedBufferGeometry';
  33935. /**
  33936. * The instance count.
  33937. *
  33938. * @type {number}
  33939. * @default Infinity
  33940. */
  33941. this.instanceCount = Infinity;
  33942. }
  33943. copy( source ) {
  33944. super.copy( source );
  33945. this.instanceCount = source.instanceCount;
  33946. return this;
  33947. }
  33948. toJSON() {
  33949. const data = super.toJSON();
  33950. data.instanceCount = this.instanceCount;
  33951. data.isInstancedBufferGeometry = true;
  33952. return data;
  33953. }
  33954. }
  33955. /**
  33956. * Class for loading geometries. The files are internally
  33957. * loaded via {@link FileLoader}.
  33958. *
  33959. * ```js
  33960. * const loader = new THREE.BufferGeometryLoader();
  33961. * const geometry = await loader.loadAsync( 'models/json/pressure.json' );
  33962. *
  33963. * const material = new THREE.MeshBasicMaterial( { color: 0xF5F5F5 } );
  33964. * const object = new THREE.Mesh( geometry, material );
  33965. * scene.add( object );
  33966. * ```
  33967. *
  33968. * @augments Loader
  33969. */
  33970. class BufferGeometryLoader extends Loader {
  33971. /**
  33972. * Constructs a new geometry loader.
  33973. *
  33974. * @param {LoadingManager} [manager] - The loading manager.
  33975. */
  33976. constructor( manager ) {
  33977. super( manager );
  33978. }
  33979. /**
  33980. * Starts loading from the given URL and pass the loaded geometry to the `onLoad()` callback.
  33981. *
  33982. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  33983. * @param {function(BufferGeometry)} onLoad - Executed when the loading process has been finished.
  33984. * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
  33985. * @param {onErrorCallback} onError - Executed when errors occur.
  33986. */
  33987. load( url, onLoad, onProgress, onError ) {
  33988. const scope = this;
  33989. const loader = new FileLoader( scope.manager );
  33990. loader.setPath( scope.path );
  33991. loader.setRequestHeader( scope.requestHeader );
  33992. loader.setWithCredentials( scope.withCredentials );
  33993. loader.load( url, function ( text ) {
  33994. try {
  33995. onLoad( scope.parse( JSON.parse( text ) ) );
  33996. } catch ( e ) {
  33997. if ( onError ) {
  33998. onError( e );
  33999. } else {
  34000. console.error( e );
  34001. }
  34002. scope.manager.itemError( url );
  34003. }
  34004. }, onProgress, onError );
  34005. }
  34006. /**
  34007. * Parses the given JSON object and returns a geometry.
  34008. *
  34009. * @param {Object} json - The serialized geometry.
  34010. * @return {BufferGeometry} The parsed geometry.
  34011. */
  34012. parse( json ) {
  34013. const interleavedBufferMap = {};
  34014. const arrayBufferMap = {};
  34015. function getInterleavedBuffer( json, uuid ) {
  34016. if ( interleavedBufferMap[ uuid ] !== undefined ) return interleavedBufferMap[ uuid ];
  34017. const interleavedBuffers = json.interleavedBuffers;
  34018. const interleavedBuffer = interleavedBuffers[ uuid ];
  34019. const buffer = getArrayBuffer( json, interleavedBuffer.buffer );
  34020. const array = getTypedArray( interleavedBuffer.type, buffer );
  34021. const ib = new InterleavedBuffer( array, interleavedBuffer.stride );
  34022. ib.uuid = interleavedBuffer.uuid;
  34023. interleavedBufferMap[ uuid ] = ib;
  34024. return ib;
  34025. }
  34026. function getArrayBuffer( json, uuid ) {
  34027. if ( arrayBufferMap[ uuid ] !== undefined ) return arrayBufferMap[ uuid ];
  34028. const arrayBuffers = json.arrayBuffers;
  34029. const arrayBuffer = arrayBuffers[ uuid ];
  34030. const ab = new Uint32Array( arrayBuffer ).buffer;
  34031. arrayBufferMap[ uuid ] = ab;
  34032. return ab;
  34033. }
  34034. const geometry = json.isInstancedBufferGeometry ? new InstancedBufferGeometry() : new BufferGeometry();
  34035. const index = json.data.index;
  34036. if ( index !== undefined ) {
  34037. const typedArray = getTypedArray( index.type, index.array );
  34038. geometry.setIndex( new BufferAttribute( typedArray, 1 ) );
  34039. }
  34040. const attributes = json.data.attributes;
  34041. for ( const key in attributes ) {
  34042. const attribute = attributes[ key ];
  34043. let bufferAttribute;
  34044. if ( attribute.isInterleavedBufferAttribute ) {
  34045. const interleavedBuffer = getInterleavedBuffer( json.data, attribute.data );
  34046. bufferAttribute = new InterleavedBufferAttribute( interleavedBuffer, attribute.itemSize, attribute.offset, attribute.normalized );
  34047. } else {
  34048. const typedArray = getTypedArray( attribute.type, attribute.array );
  34049. const bufferAttributeConstr = attribute.isInstancedBufferAttribute ? InstancedBufferAttribute : BufferAttribute;
  34050. bufferAttribute = new bufferAttributeConstr( typedArray, attribute.itemSize, attribute.normalized );
  34051. }
  34052. if ( attribute.name !== undefined ) bufferAttribute.name = attribute.name;
  34053. if ( attribute.usage !== undefined ) bufferAttribute.setUsage( attribute.usage );
  34054. geometry.setAttribute( key, bufferAttribute );
  34055. }
  34056. const morphAttributes = json.data.morphAttributes;
  34057. if ( morphAttributes ) {
  34058. for ( const key in morphAttributes ) {
  34059. const attributeArray = morphAttributes[ key ];
  34060. const array = [];
  34061. for ( let i = 0, il = attributeArray.length; i < il; i ++ ) {
  34062. const attribute = attributeArray[ i ];
  34063. let bufferAttribute;
  34064. if ( attribute.isInterleavedBufferAttribute ) {
  34065. const interleavedBuffer = getInterleavedBuffer( json.data, attribute.data );
  34066. bufferAttribute = new InterleavedBufferAttribute( interleavedBuffer, attribute.itemSize, attribute.offset, attribute.normalized );
  34067. } else {
  34068. const typedArray = getTypedArray( attribute.type, attribute.array );
  34069. bufferAttribute = new BufferAttribute( typedArray, attribute.itemSize, attribute.normalized );
  34070. }
  34071. if ( attribute.name !== undefined ) bufferAttribute.name = attribute.name;
  34072. array.push( bufferAttribute );
  34073. }
  34074. geometry.morphAttributes[ key ] = array;
  34075. }
  34076. }
  34077. const morphTargetsRelative = json.data.morphTargetsRelative;
  34078. if ( morphTargetsRelative ) {
  34079. geometry.morphTargetsRelative = true;
  34080. }
  34081. const groups = json.data.groups || json.data.drawcalls || json.data.offsets;
  34082. if ( groups !== undefined ) {
  34083. for ( let i = 0, n = groups.length; i !== n; ++ i ) {
  34084. const group = groups[ i ];
  34085. geometry.addGroup( group.start, group.count, group.materialIndex );
  34086. }
  34087. }
  34088. const boundingSphere = json.data.boundingSphere;
  34089. if ( boundingSphere !== undefined ) {
  34090. const center = new Vector3();
  34091. if ( boundingSphere.center !== undefined ) {
  34092. center.fromArray( boundingSphere.center );
  34093. }
  34094. geometry.boundingSphere = new Sphere( center, boundingSphere.radius );
  34095. }
  34096. if ( json.name ) geometry.name = json.name;
  34097. if ( json.userData ) geometry.userData = json.userData;
  34098. return geometry;
  34099. }
  34100. }
  34101. /**
  34102. * 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}.
  34103. * The files are internally loaded via {@link FileLoader}.
  34104. *
  34105. * ```js
  34106. * const loader = new THREE.ObjectLoader();
  34107. * const obj = await loader.loadAsync( 'models/json/example.json' );
  34108. * scene.add( obj );
  34109. *
  34110. * // Alternatively, to parse a previously loaded JSON structure
  34111. * const object = await loader.parseAsync( a_json_object );
  34112. * scene.add( object );
  34113. * ```
  34114. *
  34115. * @augments Loader
  34116. */
  34117. class ObjectLoader extends Loader {
  34118. /**
  34119. * Constructs a new object loader.
  34120. *
  34121. * @param {LoadingManager} [manager] - The loading manager.
  34122. */
  34123. constructor( manager ) {
  34124. super( manager );
  34125. }
  34126. /**
  34127. * Starts loading from the given URL and pass the loaded 3D object to the `onLoad()` callback.
  34128. *
  34129. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  34130. * @param {function(Object3D)} onLoad - Executed when the loading process has been finished.
  34131. * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
  34132. * @param {onErrorCallback} onError - Executed when errors occur.
  34133. */
  34134. load( url, onLoad, onProgress, onError ) {
  34135. const scope = this;
  34136. const path = ( this.path === '' ) ? LoaderUtils.extractUrlBase( url ) : this.path;
  34137. this.resourcePath = this.resourcePath || path;
  34138. const loader = new FileLoader( this.manager );
  34139. loader.setPath( this.path );
  34140. loader.setRequestHeader( this.requestHeader );
  34141. loader.setWithCredentials( this.withCredentials );
  34142. loader.load( url, function ( text ) {
  34143. let json = null;
  34144. try {
  34145. json = JSON.parse( text );
  34146. } catch ( error ) {
  34147. if ( onError !== undefined ) onError( error );
  34148. console.error( 'THREE:ObjectLoader: Can\'t parse ' + url + '.', error.message );
  34149. return;
  34150. }
  34151. const metadata = json.metadata;
  34152. if ( metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry' ) {
  34153. if ( onError !== undefined ) onError( new Error( 'THREE.ObjectLoader: Can\'t load ' + url ) );
  34154. console.error( 'THREE.ObjectLoader: Can\'t load ' + url );
  34155. return;
  34156. }
  34157. scope.parse( json, onLoad );
  34158. }, onProgress, onError );
  34159. }
  34160. /**
  34161. * Async version of {@link ObjectLoader#load}.
  34162. *
  34163. * @async
  34164. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  34165. * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
  34166. * @return {Promise<Object3D>} A Promise that resolves with the loaded 3D object.
  34167. */
  34168. async loadAsync( url, onProgress ) {
  34169. const scope = this;
  34170. const path = ( this.path === '' ) ? LoaderUtils.extractUrlBase( url ) : this.path;
  34171. this.resourcePath = this.resourcePath || path;
  34172. const loader = new FileLoader( this.manager );
  34173. loader.setPath( this.path );
  34174. loader.setRequestHeader( this.requestHeader );
  34175. loader.setWithCredentials( this.withCredentials );
  34176. const text = await loader.loadAsync( url, onProgress );
  34177. const json = JSON.parse( text );
  34178. const metadata = json.metadata;
  34179. if ( metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry' ) {
  34180. throw new Error( 'THREE.ObjectLoader: Can\'t load ' + url );
  34181. }
  34182. return await scope.parseAsync( json );
  34183. }
  34184. /**
  34185. * Parses the given JSON. This is used internally by {@link ObjectLoader#load}
  34186. * but can also be used directly to parse a previously loaded JSON structure.
  34187. *
  34188. * @param {Object} json - The serialized 3D object.
  34189. * @param {onLoad} onLoad - Executed when all resources (e.g. textures) have been fully loaded.
  34190. * @return {Object3D} The parsed 3D object.
  34191. */
  34192. parse( json, onLoad ) {
  34193. const animations = this.parseAnimations( json.animations );
  34194. const shapes = this.parseShapes( json.shapes );
  34195. const geometries = this.parseGeometries( json.geometries, shapes );
  34196. const images = this.parseImages( json.images, function () {
  34197. if ( onLoad !== undefined ) onLoad( object );
  34198. } );
  34199. const textures = this.parseTextures( json.textures, images );
  34200. const materials = this.parseMaterials( json.materials, textures );
  34201. const object = this.parseObject( json.object, geometries, materials, textures, animations );
  34202. const skeletons = this.parseSkeletons( json.skeletons, object );
  34203. this.bindSkeletons( object, skeletons );
  34204. this.bindLightTargets( object );
  34205. //
  34206. if ( onLoad !== undefined ) {
  34207. let hasImages = false;
  34208. for ( const uuid in images ) {
  34209. if ( images[ uuid ].data instanceof HTMLImageElement ) {
  34210. hasImages = true;
  34211. break;
  34212. }
  34213. }
  34214. if ( hasImages === false ) onLoad( object );
  34215. }
  34216. return object;
  34217. }
  34218. /**
  34219. * Async version of {@link ObjectLoader#parse}.
  34220. *
  34221. * @param {Object} json - The serialized 3D object.
  34222. * @return {Promise<Object3D>} A Promise that resolves with the parsed 3D object.
  34223. */
  34224. async parseAsync( json ) {
  34225. const animations = this.parseAnimations( json.animations );
  34226. const shapes = this.parseShapes( json.shapes );
  34227. const geometries = this.parseGeometries( json.geometries, shapes );
  34228. const images = await this.parseImagesAsync( json.images );
  34229. const textures = this.parseTextures( json.textures, images );
  34230. const materials = this.parseMaterials( json.materials, textures );
  34231. const object = this.parseObject( json.object, geometries, materials, textures, animations );
  34232. const skeletons = this.parseSkeletons( json.skeletons, object );
  34233. this.bindSkeletons( object, skeletons );
  34234. this.bindLightTargets( object );
  34235. return object;
  34236. }
  34237. // internals
  34238. parseShapes( json ) {
  34239. const shapes = {};
  34240. if ( json !== undefined ) {
  34241. for ( let i = 0, l = json.length; i < l; i ++ ) {
  34242. const shape = new Shape().fromJSON( json[ i ] );
  34243. shapes[ shape.uuid ] = shape;
  34244. }
  34245. }
  34246. return shapes;
  34247. }
  34248. parseSkeletons( json, object ) {
  34249. const skeletons = {};
  34250. const bones = {};
  34251. // generate bone lookup table
  34252. object.traverse( function ( child ) {
  34253. if ( child.isBone ) bones[ child.uuid ] = child;
  34254. } );
  34255. // create skeletons
  34256. if ( json !== undefined ) {
  34257. for ( let i = 0, l = json.length; i < l; i ++ ) {
  34258. const skeleton = new Skeleton().fromJSON( json[ i ], bones );
  34259. skeletons[ skeleton.uuid ] = skeleton;
  34260. }
  34261. }
  34262. return skeletons;
  34263. }
  34264. parseGeometries( json, shapes ) {
  34265. const geometries = {};
  34266. if ( json !== undefined ) {
  34267. const bufferGeometryLoader = new BufferGeometryLoader();
  34268. for ( let i = 0, l = json.length; i < l; i ++ ) {
  34269. let geometry;
  34270. const data = json[ i ];
  34271. switch ( data.type ) {
  34272. case 'BufferGeometry':
  34273. case 'InstancedBufferGeometry':
  34274. geometry = bufferGeometryLoader.parse( data );
  34275. break;
  34276. default:
  34277. if ( data.type in Geometries ) {
  34278. geometry = Geometries[ data.type ].fromJSON( data, shapes );
  34279. } else {
  34280. console.warn( `THREE.ObjectLoader: Unsupported geometry type "${ data.type }"` );
  34281. }
  34282. }
  34283. geometry.uuid = data.uuid;
  34284. if ( data.name !== undefined ) geometry.name = data.name;
  34285. if ( data.userData !== undefined ) geometry.userData = data.userData;
  34286. geometries[ data.uuid ] = geometry;
  34287. }
  34288. }
  34289. return geometries;
  34290. }
  34291. parseMaterials( json, textures ) {
  34292. const cache = {}; // MultiMaterial
  34293. const materials = {};
  34294. if ( json !== undefined ) {
  34295. const loader = new MaterialLoader();
  34296. loader.setTextures( textures );
  34297. for ( let i = 0, l = json.length; i < l; i ++ ) {
  34298. const data = json[ i ];
  34299. if ( cache[ data.uuid ] === undefined ) {
  34300. cache[ data.uuid ] = loader.parse( data );
  34301. }
  34302. materials[ data.uuid ] = cache[ data.uuid ];
  34303. }
  34304. }
  34305. return materials;
  34306. }
  34307. parseAnimations( json ) {
  34308. const animations = {};
  34309. if ( json !== undefined ) {
  34310. for ( let i = 0; i < json.length; i ++ ) {
  34311. const data = json[ i ];
  34312. const clip = AnimationClip.parse( data );
  34313. animations[ clip.uuid ] = clip;
  34314. }
  34315. }
  34316. return animations;
  34317. }
  34318. parseImages( json, onLoad ) {
  34319. const scope = this;
  34320. const images = {};
  34321. let loader;
  34322. function loadImage( url ) {
  34323. scope.manager.itemStart( url );
  34324. return loader.load( url, function () {
  34325. scope.manager.itemEnd( url );
  34326. }, undefined, function () {
  34327. scope.manager.itemError( url );
  34328. scope.manager.itemEnd( url );
  34329. } );
  34330. }
  34331. function deserializeImage( image ) {
  34332. if ( typeof image === 'string' ) {
  34333. const url = image;
  34334. const path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test( url ) ? url : scope.resourcePath + url;
  34335. return loadImage( path );
  34336. } else {
  34337. if ( image.data ) {
  34338. return {
  34339. data: getTypedArray( image.type, image.data ),
  34340. width: image.width,
  34341. height: image.height
  34342. };
  34343. } else {
  34344. return null;
  34345. }
  34346. }
  34347. }
  34348. if ( json !== undefined && json.length > 0 ) {
  34349. const manager = new LoadingManager( onLoad );
  34350. loader = new ImageLoader( manager );
  34351. loader.setCrossOrigin( this.crossOrigin );
  34352. for ( let i = 0, il = json.length; i < il; i ++ ) {
  34353. const image = json[ i ];
  34354. const url = image.url;
  34355. if ( Array.isArray( url ) ) {
  34356. // load array of images e.g CubeTexture
  34357. const imageArray = [];
  34358. for ( let j = 0, jl = url.length; j < jl; j ++ ) {
  34359. const currentUrl = url[ j ];
  34360. const deserializedImage = deserializeImage( currentUrl );
  34361. if ( deserializedImage !== null ) {
  34362. if ( deserializedImage instanceof HTMLImageElement ) {
  34363. imageArray.push( deserializedImage );
  34364. } else {
  34365. // special case: handle array of data textures for cube textures
  34366. imageArray.push( new DataTexture( deserializedImage.data, deserializedImage.width, deserializedImage.height ) );
  34367. }
  34368. }
  34369. }
  34370. images[ image.uuid ] = new Source( imageArray );
  34371. } else {
  34372. // load single image
  34373. const deserializedImage = deserializeImage( image.url );
  34374. images[ image.uuid ] = new Source( deserializedImage );
  34375. }
  34376. }
  34377. }
  34378. return images;
  34379. }
  34380. async parseImagesAsync( json ) {
  34381. const scope = this;
  34382. const images = {};
  34383. let loader;
  34384. async function deserializeImage( image ) {
  34385. if ( typeof image === 'string' ) {
  34386. const url = image;
  34387. const path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test( url ) ? url : scope.resourcePath + url;
  34388. return await loader.loadAsync( path );
  34389. } else {
  34390. if ( image.data ) {
  34391. return {
  34392. data: getTypedArray( image.type, image.data ),
  34393. width: image.width,
  34394. height: image.height
  34395. };
  34396. } else {
  34397. return null;
  34398. }
  34399. }
  34400. }
  34401. if ( json !== undefined && json.length > 0 ) {
  34402. loader = new ImageLoader( this.manager );
  34403. loader.setCrossOrigin( this.crossOrigin );
  34404. for ( let i = 0, il = json.length; i < il; i ++ ) {
  34405. const image = json[ i ];
  34406. const url = image.url;
  34407. if ( Array.isArray( url ) ) {
  34408. // load array of images e.g CubeTexture
  34409. const imageArray = [];
  34410. for ( let j = 0, jl = url.length; j < jl; j ++ ) {
  34411. const currentUrl = url[ j ];
  34412. const deserializedImage = await deserializeImage( currentUrl );
  34413. if ( deserializedImage !== null ) {
  34414. if ( deserializedImage instanceof HTMLImageElement ) {
  34415. imageArray.push( deserializedImage );
  34416. } else {
  34417. // special case: handle array of data textures for cube textures
  34418. imageArray.push( new DataTexture( deserializedImage.data, deserializedImage.width, deserializedImage.height ) );
  34419. }
  34420. }
  34421. }
  34422. images[ image.uuid ] = new Source( imageArray );
  34423. } else {
  34424. // load single image
  34425. const deserializedImage = await deserializeImage( image.url );
  34426. images[ image.uuid ] = new Source( deserializedImage );
  34427. }
  34428. }
  34429. }
  34430. return images;
  34431. }
  34432. parseTextures( json, images ) {
  34433. function parseConstant( value, type ) {
  34434. if ( typeof value === 'number' ) return value;
  34435. console.warn( 'THREE.ObjectLoader.parseTexture: Constant should be in numeric form.', value );
  34436. return type[ value ];
  34437. }
  34438. const textures = {};
  34439. if ( json !== undefined ) {
  34440. for ( let i = 0, l = json.length; i < l; i ++ ) {
  34441. const data = json[ i ];
  34442. if ( data.image === undefined ) {
  34443. console.warn( 'THREE.ObjectLoader: No "image" specified for', data.uuid );
  34444. }
  34445. if ( images[ data.image ] === undefined ) {
  34446. console.warn( 'THREE.ObjectLoader: Undefined image', data.image );
  34447. }
  34448. const source = images[ data.image ];
  34449. const image = source.data;
  34450. let texture;
  34451. if ( Array.isArray( image ) ) {
  34452. texture = new CubeTexture();
  34453. if ( image.length === 6 ) texture.needsUpdate = true;
  34454. } else {
  34455. if ( image && image.data ) {
  34456. texture = new DataTexture();
  34457. } else {
  34458. texture = new Texture();
  34459. }
  34460. if ( image ) texture.needsUpdate = true; // textures can have undefined image data
  34461. }
  34462. texture.source = source;
  34463. texture.uuid = data.uuid;
  34464. if ( data.name !== undefined ) texture.name = data.name;
  34465. if ( data.mapping !== undefined ) texture.mapping = parseConstant( data.mapping, TEXTURE_MAPPING );
  34466. if ( data.channel !== undefined ) texture.channel = data.channel;
  34467. if ( data.offset !== undefined ) texture.offset.fromArray( data.offset );
  34468. if ( data.repeat !== undefined ) texture.repeat.fromArray( data.repeat );
  34469. if ( data.center !== undefined ) texture.center.fromArray( data.center );
  34470. if ( data.rotation !== undefined ) texture.rotation = data.rotation;
  34471. if ( data.wrap !== undefined ) {
  34472. texture.wrapS = parseConstant( data.wrap[ 0 ], TEXTURE_WRAPPING );
  34473. texture.wrapT = parseConstant( data.wrap[ 1 ], TEXTURE_WRAPPING );
  34474. }
  34475. if ( data.format !== undefined ) texture.format = data.format;
  34476. if ( data.internalFormat !== undefined ) texture.internalFormat = data.internalFormat;
  34477. if ( data.type !== undefined ) texture.type = data.type;
  34478. if ( data.colorSpace !== undefined ) texture.colorSpace = data.colorSpace;
  34479. if ( data.minFilter !== undefined ) texture.minFilter = parseConstant( data.minFilter, TEXTURE_FILTER );
  34480. if ( data.magFilter !== undefined ) texture.magFilter = parseConstant( data.magFilter, TEXTURE_FILTER );
  34481. if ( data.anisotropy !== undefined ) texture.anisotropy = data.anisotropy;
  34482. if ( data.flipY !== undefined ) texture.flipY = data.flipY;
  34483. if ( data.generateMipmaps !== undefined ) texture.generateMipmaps = data.generateMipmaps;
  34484. if ( data.premultiplyAlpha !== undefined ) texture.premultiplyAlpha = data.premultiplyAlpha;
  34485. if ( data.unpackAlignment !== undefined ) texture.unpackAlignment = data.unpackAlignment;
  34486. if ( data.compareFunction !== undefined ) texture.compareFunction = data.compareFunction;
  34487. if ( data.userData !== undefined ) texture.userData = data.userData;
  34488. textures[ data.uuid ] = texture;
  34489. }
  34490. }
  34491. return textures;
  34492. }
  34493. parseObject( data, geometries, materials, textures, animations ) {
  34494. let object;
  34495. function getGeometry( name ) {
  34496. if ( geometries[ name ] === undefined ) {
  34497. console.warn( 'THREE.ObjectLoader: Undefined geometry', name );
  34498. }
  34499. return geometries[ name ];
  34500. }
  34501. function getMaterial( name ) {
  34502. if ( name === undefined ) return undefined;
  34503. if ( Array.isArray( name ) ) {
  34504. const array = [];
  34505. for ( let i = 0, l = name.length; i < l; i ++ ) {
  34506. const uuid = name[ i ];
  34507. if ( materials[ uuid ] === undefined ) {
  34508. console.warn( 'THREE.ObjectLoader: Undefined material', uuid );
  34509. }
  34510. array.push( materials[ uuid ] );
  34511. }
  34512. return array;
  34513. }
  34514. if ( materials[ name ] === undefined ) {
  34515. console.warn( 'THREE.ObjectLoader: Undefined material', name );
  34516. }
  34517. return materials[ name ];
  34518. }
  34519. function getTexture( uuid ) {
  34520. if ( textures[ uuid ] === undefined ) {
  34521. console.warn( 'THREE.ObjectLoader: Undefined texture', uuid );
  34522. }
  34523. return textures[ uuid ];
  34524. }
  34525. let geometry, material;
  34526. switch ( data.type ) {
  34527. case 'Scene':
  34528. object = new Scene();
  34529. if ( data.background !== undefined ) {
  34530. if ( Number.isInteger( data.background ) ) {
  34531. object.background = new Color( data.background );
  34532. } else {
  34533. object.background = getTexture( data.background );
  34534. }
  34535. }
  34536. if ( data.environment !== undefined ) {
  34537. object.environment = getTexture( data.environment );
  34538. }
  34539. if ( data.fog !== undefined ) {
  34540. if ( data.fog.type === 'Fog' ) {
  34541. object.fog = new Fog( data.fog.color, data.fog.near, data.fog.far );
  34542. } else if ( data.fog.type === 'FogExp2' ) {
  34543. object.fog = new FogExp2( data.fog.color, data.fog.density );
  34544. }
  34545. if ( data.fog.name !== '' ) {
  34546. object.fog.name = data.fog.name;
  34547. }
  34548. }
  34549. if ( data.backgroundBlurriness !== undefined ) object.backgroundBlurriness = data.backgroundBlurriness;
  34550. if ( data.backgroundIntensity !== undefined ) object.backgroundIntensity = data.backgroundIntensity;
  34551. if ( data.backgroundRotation !== undefined ) object.backgroundRotation.fromArray( data.backgroundRotation );
  34552. if ( data.environmentIntensity !== undefined ) object.environmentIntensity = data.environmentIntensity;
  34553. if ( data.environmentRotation !== undefined ) object.environmentRotation.fromArray( data.environmentRotation );
  34554. break;
  34555. case 'PerspectiveCamera':
  34556. object = new PerspectiveCamera( data.fov, data.aspect, data.near, data.far );
  34557. if ( data.focus !== undefined ) object.focus = data.focus;
  34558. if ( data.zoom !== undefined ) object.zoom = data.zoom;
  34559. if ( data.filmGauge !== undefined ) object.filmGauge = data.filmGauge;
  34560. if ( data.filmOffset !== undefined ) object.filmOffset = data.filmOffset;
  34561. if ( data.view !== undefined ) object.view = Object.assign( {}, data.view );
  34562. break;
  34563. case 'OrthographicCamera':
  34564. object = new OrthographicCamera( data.left, data.right, data.top, data.bottom, data.near, data.far );
  34565. if ( data.zoom !== undefined ) object.zoom = data.zoom;
  34566. if ( data.view !== undefined ) object.view = Object.assign( {}, data.view );
  34567. break;
  34568. case 'AmbientLight':
  34569. object = new AmbientLight( data.color, data.intensity );
  34570. break;
  34571. case 'DirectionalLight':
  34572. object = new DirectionalLight( data.color, data.intensity );
  34573. object.target = data.target || '';
  34574. break;
  34575. case 'PointLight':
  34576. object = new PointLight( data.color, data.intensity, data.distance, data.decay );
  34577. break;
  34578. case 'RectAreaLight':
  34579. object = new RectAreaLight( data.color, data.intensity, data.width, data.height );
  34580. break;
  34581. case 'SpotLight':
  34582. object = new SpotLight( data.color, data.intensity, data.distance, data.angle, data.penumbra, data.decay );
  34583. object.target = data.target || '';
  34584. break;
  34585. case 'HemisphereLight':
  34586. object = new HemisphereLight( data.color, data.groundColor, data.intensity );
  34587. break;
  34588. case 'LightProbe':
  34589. object = new LightProbe().fromJSON( data );
  34590. break;
  34591. case 'SkinnedMesh':
  34592. geometry = getGeometry( data.geometry );
  34593. material = getMaterial( data.material );
  34594. object = new SkinnedMesh( geometry, material );
  34595. if ( data.bindMode !== undefined ) object.bindMode = data.bindMode;
  34596. if ( data.bindMatrix !== undefined ) object.bindMatrix.fromArray( data.bindMatrix );
  34597. if ( data.skeleton !== undefined ) object.skeleton = data.skeleton;
  34598. break;
  34599. case 'Mesh':
  34600. geometry = getGeometry( data.geometry );
  34601. material = getMaterial( data.material );
  34602. object = new Mesh( geometry, material );
  34603. break;
  34604. case 'InstancedMesh':
  34605. geometry = getGeometry( data.geometry );
  34606. material = getMaterial( data.material );
  34607. const count = data.count;
  34608. const instanceMatrix = data.instanceMatrix;
  34609. const instanceColor = data.instanceColor;
  34610. object = new InstancedMesh( geometry, material, count );
  34611. object.instanceMatrix = new InstancedBufferAttribute( new Float32Array( instanceMatrix.array ), 16 );
  34612. if ( instanceColor !== undefined ) object.instanceColor = new InstancedBufferAttribute( new Float32Array( instanceColor.array ), instanceColor.itemSize );
  34613. break;
  34614. case 'BatchedMesh':
  34615. geometry = getGeometry( data.geometry );
  34616. material = getMaterial( data.material );
  34617. object = new BatchedMesh( data.maxInstanceCount, data.maxVertexCount, data.maxIndexCount, material );
  34618. object.geometry = geometry;
  34619. object.perObjectFrustumCulled = data.perObjectFrustumCulled;
  34620. object.sortObjects = data.sortObjects;
  34621. object._drawRanges = data.drawRanges;
  34622. object._reservedRanges = data.reservedRanges;
  34623. object._visibility = data.visibility;
  34624. object._active = data.active;
  34625. object._bounds = data.bounds.map( bound => {
  34626. const box = new Box3();
  34627. box.min.fromArray( bound.boxMin );
  34628. box.max.fromArray( bound.boxMax );
  34629. const sphere = new Sphere();
  34630. sphere.radius = bound.sphereRadius;
  34631. sphere.center.fromArray( bound.sphereCenter );
  34632. return {
  34633. boxInitialized: bound.boxInitialized,
  34634. box: box,
  34635. sphereInitialized: bound.sphereInitialized,
  34636. sphere: sphere
  34637. };
  34638. } );
  34639. object._maxInstanceCount = data.maxInstanceCount;
  34640. object._maxVertexCount = data.maxVertexCount;
  34641. object._maxIndexCount = data.maxIndexCount;
  34642. object._geometryInitialized = data.geometryInitialized;
  34643. object._geometryCount = data.geometryCount;
  34644. object._matricesTexture = getTexture( data.matricesTexture.uuid );
  34645. if ( data.colorsTexture !== undefined ) object._colorsTexture = getTexture( data.colorsTexture.uuid );
  34646. break;
  34647. case 'LOD':
  34648. object = new LOD();
  34649. break;
  34650. case 'Line':
  34651. object = new Line( getGeometry( data.geometry ), getMaterial( data.material ) );
  34652. break;
  34653. case 'LineLoop':
  34654. object = new LineLoop( getGeometry( data.geometry ), getMaterial( data.material ) );
  34655. break;
  34656. case 'LineSegments':
  34657. object = new LineSegments( getGeometry( data.geometry ), getMaterial( data.material ) );
  34658. break;
  34659. case 'PointCloud':
  34660. case 'Points':
  34661. object = new Points( getGeometry( data.geometry ), getMaterial( data.material ) );
  34662. break;
  34663. case 'Sprite':
  34664. object = new Sprite( getMaterial( data.material ) );
  34665. break;
  34666. case 'Group':
  34667. object = new Group();
  34668. break;
  34669. case 'Bone':
  34670. object = new Bone();
  34671. break;
  34672. default:
  34673. object = new Object3D();
  34674. }
  34675. object.uuid = data.uuid;
  34676. if ( data.name !== undefined ) object.name = data.name;
  34677. if ( data.matrix !== undefined ) {
  34678. object.matrix.fromArray( data.matrix );
  34679. if ( data.matrixAutoUpdate !== undefined ) object.matrixAutoUpdate = data.matrixAutoUpdate;
  34680. if ( object.matrixAutoUpdate ) object.matrix.decompose( object.position, object.quaternion, object.scale );
  34681. } else {
  34682. if ( data.position !== undefined ) object.position.fromArray( data.position );
  34683. if ( data.rotation !== undefined ) object.rotation.fromArray( data.rotation );
  34684. if ( data.quaternion !== undefined ) object.quaternion.fromArray( data.quaternion );
  34685. if ( data.scale !== undefined ) object.scale.fromArray( data.scale );
  34686. }
  34687. if ( data.up !== undefined ) object.up.fromArray( data.up );
  34688. if ( data.castShadow !== undefined ) object.castShadow = data.castShadow;
  34689. if ( data.receiveShadow !== undefined ) object.receiveShadow = data.receiveShadow;
  34690. if ( data.shadow ) {
  34691. if ( data.shadow.intensity !== undefined ) object.shadow.intensity = data.shadow.intensity;
  34692. if ( data.shadow.bias !== undefined ) object.shadow.bias = data.shadow.bias;
  34693. if ( data.shadow.normalBias !== undefined ) object.shadow.normalBias = data.shadow.normalBias;
  34694. if ( data.shadow.radius !== undefined ) object.shadow.radius = data.shadow.radius;
  34695. if ( data.shadow.mapSize !== undefined ) object.shadow.mapSize.fromArray( data.shadow.mapSize );
  34696. if ( data.shadow.camera !== undefined ) object.shadow.camera = this.parseObject( data.shadow.camera );
  34697. }
  34698. if ( data.visible !== undefined ) object.visible = data.visible;
  34699. if ( data.frustumCulled !== undefined ) object.frustumCulled = data.frustumCulled;
  34700. if ( data.renderOrder !== undefined ) object.renderOrder = data.renderOrder;
  34701. if ( data.userData !== undefined ) object.userData = data.userData;
  34702. if ( data.layers !== undefined ) object.layers.mask = data.layers;
  34703. if ( data.children !== undefined ) {
  34704. const children = data.children;
  34705. for ( let i = 0; i < children.length; i ++ ) {
  34706. object.add( this.parseObject( children[ i ], geometries, materials, textures, animations ) );
  34707. }
  34708. }
  34709. if ( data.animations !== undefined ) {
  34710. const objectAnimations = data.animations;
  34711. for ( let i = 0; i < objectAnimations.length; i ++ ) {
  34712. const uuid = objectAnimations[ i ];
  34713. object.animations.push( animations[ uuid ] );
  34714. }
  34715. }
  34716. if ( data.type === 'LOD' ) {
  34717. if ( data.autoUpdate !== undefined ) object.autoUpdate = data.autoUpdate;
  34718. const levels = data.levels;
  34719. for ( let l = 0; l < levels.length; l ++ ) {
  34720. const level = levels[ l ];
  34721. const child = object.getObjectByProperty( 'uuid', level.object );
  34722. if ( child !== undefined ) {
  34723. object.addLevel( child, level.distance, level.hysteresis );
  34724. }
  34725. }
  34726. }
  34727. return object;
  34728. }
  34729. bindSkeletons( object, skeletons ) {
  34730. if ( Object.keys( skeletons ).length === 0 ) return;
  34731. object.traverse( function ( child ) {
  34732. if ( child.isSkinnedMesh === true && child.skeleton !== undefined ) {
  34733. const skeleton = skeletons[ child.skeleton ];
  34734. if ( skeleton === undefined ) {
  34735. console.warn( 'THREE.ObjectLoader: No skeleton found with UUID:', child.skeleton );
  34736. } else {
  34737. child.bind( skeleton, child.bindMatrix );
  34738. }
  34739. }
  34740. } );
  34741. }
  34742. bindLightTargets( object ) {
  34743. object.traverse( function ( child ) {
  34744. if ( child.isDirectionalLight || child.isSpotLight ) {
  34745. const uuid = child.target;
  34746. const target = object.getObjectByProperty( 'uuid', uuid );
  34747. if ( target !== undefined ) {
  34748. child.target = target;
  34749. } else {
  34750. child.target = new Object3D();
  34751. }
  34752. }
  34753. } );
  34754. }
  34755. }
  34756. const TEXTURE_MAPPING = {
  34757. UVMapping: UVMapping,
  34758. CubeReflectionMapping: CubeReflectionMapping,
  34759. CubeRefractionMapping: CubeRefractionMapping,
  34760. EquirectangularReflectionMapping: EquirectangularReflectionMapping,
  34761. EquirectangularRefractionMapping: EquirectangularRefractionMapping,
  34762. CubeUVReflectionMapping: CubeUVReflectionMapping
  34763. };
  34764. const TEXTURE_WRAPPING = {
  34765. RepeatWrapping: RepeatWrapping,
  34766. ClampToEdgeWrapping: ClampToEdgeWrapping,
  34767. MirroredRepeatWrapping: MirroredRepeatWrapping
  34768. };
  34769. const TEXTURE_FILTER = {
  34770. NearestFilter: NearestFilter,
  34771. NearestMipmapNearestFilter: NearestMipmapNearestFilter,
  34772. NearestMipmapLinearFilter: NearestMipmapLinearFilter,
  34773. LinearFilter: LinearFilter,
  34774. LinearMipmapNearestFilter: LinearMipmapNearestFilter,
  34775. LinearMipmapLinearFilter: LinearMipmapLinearFilter
  34776. };
  34777. /**
  34778. * A loader for loading images as an [ImageBitmap]{@link https://developer.mozilla.org/en-US/docs/Web/API/ImageBitmap}.
  34779. * An `ImageBitmap` provides an asynchronous and resource efficient pathway to prepare
  34780. * textures for rendering.
  34781. *
  34782. * Note that {@link Texture#flipY} and {@link Texture#premultiplyAlpha} are ignored with image bitmaps.
  34783. * They needs these configuration on bitmap creation unlike regular images need them on uploading to GPU.
  34784. *
  34785. * You need to set the equivalent options via {@link ImageBitmapLoader#setOptions} instead.
  34786. *
  34787. * Also note that unlike {@link FileLoader}, this loader does not avoid multiple concurrent requests to the same URL.
  34788. *
  34789. * ```js
  34790. * const loader = new THREE.ImageBitmapLoader();
  34791. * loader.setOptions( { imageOrientation: 'flipY' } ); // set options if needed
  34792. * const imageBitmap = await loader.loadAsync( 'image.png' );
  34793. *
  34794. * const texture = new THREE.Texture( imageBitmap );
  34795. * texture.needsUpdate = true;
  34796. * ```
  34797. *
  34798. * @augments Loader
  34799. */
  34800. class ImageBitmapLoader extends Loader {
  34801. /**
  34802. * Constructs a new image bitmap loader.
  34803. *
  34804. * @param {LoadingManager} [manager] - The loading manager.
  34805. */
  34806. constructor( manager ) {
  34807. super( manager );
  34808. /**
  34809. * This flag can be used for type testing.
  34810. *
  34811. * @type {boolean}
  34812. * @readonly
  34813. * @default true
  34814. */
  34815. this.isImageBitmapLoader = true;
  34816. if ( typeof createImageBitmap === 'undefined' ) {
  34817. console.warn( 'THREE.ImageBitmapLoader: createImageBitmap() not supported.' );
  34818. }
  34819. if ( typeof fetch === 'undefined' ) {
  34820. console.warn( 'THREE.ImageBitmapLoader: fetch() not supported.' );
  34821. }
  34822. /**
  34823. * Represents the loader options.
  34824. *
  34825. * @type {Object}
  34826. * @default {premultiplyAlpha:'none'}
  34827. */
  34828. this.options = { premultiplyAlpha: 'none' };
  34829. }
  34830. /**
  34831. * Sets the given loader options. The structure of the object must match the `options` parameter of
  34832. * [createImageBitmap]{@link https://developer.mozilla.org/en-US/docs/Web/API/Window/createImageBitmap}.
  34833. *
  34834. * @param {Object} options - The loader options to set.
  34835. * @return {ImageBitmapLoader} A reference to this image bitmap loader.
  34836. */
  34837. setOptions( options ) {
  34838. this.options = options;
  34839. return this;
  34840. }
  34841. /**
  34842. * Starts loading from the given URL and pass the loaded image bitmap to the `onLoad()` callback.
  34843. *
  34844. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  34845. * @param {function(ImageBitmap)} onLoad - Executed when the loading process has been finished.
  34846. * @param {onProgressCallback} onProgress - Unsupported in this loader.
  34847. * @param {onErrorCallback} onError - Executed when errors occur.
  34848. * @return {ImageBitmap|undefined} The image bitmap.
  34849. */
  34850. load( url, onLoad, onProgress, onError ) {
  34851. if ( url === undefined ) url = '';
  34852. if ( this.path !== undefined ) url = this.path + url;
  34853. url = this.manager.resolveURL( url );
  34854. const scope = this;
  34855. const cached = Cache.get( url );
  34856. if ( cached !== undefined ) {
  34857. scope.manager.itemStart( url );
  34858. // If cached is a promise, wait for it to resolve
  34859. if ( cached.then ) {
  34860. cached.then( imageBitmap => {
  34861. if ( onLoad ) onLoad( imageBitmap );
  34862. scope.manager.itemEnd( url );
  34863. } ).catch( e => {
  34864. if ( onError ) onError( e );
  34865. } );
  34866. return;
  34867. }
  34868. // If cached is not a promise (i.e., it's already an imageBitmap)
  34869. setTimeout( function () {
  34870. if ( onLoad ) onLoad( cached );
  34871. scope.manager.itemEnd( url );
  34872. }, 0 );
  34873. return cached;
  34874. }
  34875. const fetchOptions = {};
  34876. fetchOptions.credentials = ( this.crossOrigin === 'anonymous' ) ? 'same-origin' : 'include';
  34877. fetchOptions.headers = this.requestHeader;
  34878. const promise = fetch( url, fetchOptions ).then( function ( res ) {
  34879. return res.blob();
  34880. } ).then( function ( blob ) {
  34881. return createImageBitmap( blob, Object.assign( scope.options, { colorSpaceConversion: 'none' } ) );
  34882. } ).then( function ( imageBitmap ) {
  34883. Cache.add( url, imageBitmap );
  34884. if ( onLoad ) onLoad( imageBitmap );
  34885. scope.manager.itemEnd( url );
  34886. return imageBitmap;
  34887. } ).catch( function ( e ) {
  34888. if ( onError ) onError( e );
  34889. Cache.remove( url );
  34890. scope.manager.itemError( url );
  34891. scope.manager.itemEnd( url );
  34892. } );
  34893. Cache.add( url, promise );
  34894. scope.manager.itemStart( url );
  34895. }
  34896. }
  34897. let _context;
  34898. /**
  34899. * Manages the global audio context in the engine.
  34900. *
  34901. * @hideconstructor
  34902. */
  34903. class AudioContext {
  34904. /**
  34905. * Returns the global native audio context.
  34906. *
  34907. * @return {AudioContext} The native audio context.
  34908. */
  34909. static getContext() {
  34910. if ( _context === undefined ) {
  34911. _context = new ( window.AudioContext || window.webkitAudioContext )();
  34912. }
  34913. return _context;
  34914. }
  34915. /**
  34916. * Allows to set the global native audio context from outside.
  34917. *
  34918. * @param {AudioContext} value - The native context to set.
  34919. */
  34920. static setContext( value ) {
  34921. _context = value;
  34922. }
  34923. }
  34924. /**
  34925. * Class for loading audio buffers. Audios are internally
  34926. * loaded via {@link FileLoader}.
  34927. *
  34928. * ```js
  34929. * const audioListener = new THREE.AudioListener();
  34930. * const ambientSound = new THREE.Audio( audioListener );
  34931. *
  34932. * const loader = new THREE.AudioLoader();
  34933. * const audioBuffer = await loader.loadAsync( 'audio/ambient_ocean.ogg' );
  34934. *
  34935. * ambientSound.setBuffer( audioBuffer );
  34936. * ambientSound.play();
  34937. * ```
  34938. *
  34939. * @augments Loader
  34940. */
  34941. class AudioLoader extends Loader {
  34942. /**
  34943. * Constructs a new audio loader.
  34944. *
  34945. * @param {LoadingManager} [manager] - The loading manager.
  34946. */
  34947. constructor( manager ) {
  34948. super( manager );
  34949. }
  34950. /**
  34951. * Starts loading from the given URL and passes the loaded audio buffer
  34952. * to the `onLoad()` callback.
  34953. *
  34954. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  34955. * @param {function(AudioBuffer)} onLoad - Executed when the loading process has been finished.
  34956. * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
  34957. * @param {onErrorCallback} onError - Executed when errors occur.
  34958. */
  34959. load( url, onLoad, onProgress, onError ) {
  34960. const scope = this;
  34961. const loader = new FileLoader( this.manager );
  34962. loader.setResponseType( 'arraybuffer' );
  34963. loader.setPath( this.path );
  34964. loader.setRequestHeader( this.requestHeader );
  34965. loader.setWithCredentials( this.withCredentials );
  34966. loader.load( url, function ( buffer ) {
  34967. try {
  34968. // Create a copy of the buffer. The `decodeAudioData` method
  34969. // detaches the buffer when complete, preventing reuse.
  34970. const bufferCopy = buffer.slice( 0 );
  34971. const context = AudioContext.getContext();
  34972. context.decodeAudioData( bufferCopy, function ( audioBuffer ) {
  34973. onLoad( audioBuffer );
  34974. } ).catch( handleError );
  34975. } catch ( e ) {
  34976. handleError( e );
  34977. }
  34978. }, onProgress, onError );
  34979. function handleError( e ) {
  34980. if ( onError ) {
  34981. onError( e );
  34982. } else {
  34983. console.error( e );
  34984. }
  34985. scope.manager.itemError( url );
  34986. }
  34987. }
  34988. }
  34989. const _eyeRight = /*@__PURE__*/ new Matrix4();
  34990. const _eyeLeft = /*@__PURE__*/ new Matrix4();
  34991. const _projectionMatrix = /*@__PURE__*/ new Matrix4();
  34992. /**
  34993. * A special type of camera that uses two perspective cameras with
  34994. * stereoscopic projection. Can be used for rendering stereo effects
  34995. * like [3D Anaglyph]{@link https://en.wikipedia.org/wiki/Anaglyph_3D} or
  34996. * [Parallax Barrier]{@link https://en.wikipedia.org/wiki/parallax_barrier}.
  34997. */
  34998. class StereoCamera {
  34999. /**
  35000. * Constructs a new stereo camera.
  35001. */
  35002. constructor() {
  35003. /**
  35004. * The type property is used for detecting the object type
  35005. * in context of serialization/deserialization.
  35006. *
  35007. * @type {string}
  35008. * @readonly
  35009. */
  35010. this.type = 'StereoCamera';
  35011. /**
  35012. * The aspect.
  35013. *
  35014. * @type {number}
  35015. * @default 1
  35016. */
  35017. this.aspect = 1;
  35018. /**
  35019. * The eye separation which represents the distance
  35020. * between the left and right camera.
  35021. *
  35022. * @type {number}
  35023. * @default 0.064
  35024. */
  35025. this.eyeSep = 0.064;
  35026. /**
  35027. * The camera representing the left eye. This is added to layer `1` so objects to be
  35028. * rendered by the left camera must also be added to this layer.
  35029. *
  35030. * @type {PerspectiveCamera}
  35031. */
  35032. this.cameraL = new PerspectiveCamera();
  35033. this.cameraL.layers.enable( 1 );
  35034. this.cameraL.matrixAutoUpdate = false;
  35035. /**
  35036. * The camera representing the right eye. This is added to layer `2` so objects to be
  35037. * rendered by the right camera must also be added to this layer.
  35038. *
  35039. * @type {PerspectiveCamera}
  35040. */
  35041. this.cameraR = new PerspectiveCamera();
  35042. this.cameraR.layers.enable( 2 );
  35043. this.cameraR.matrixAutoUpdate = false;
  35044. this._cache = {
  35045. focus: null,
  35046. fov: null,
  35047. aspect: null,
  35048. near: null,
  35049. far: null,
  35050. zoom: null,
  35051. eyeSep: null
  35052. };
  35053. }
  35054. /**
  35055. * Updates the stereo camera based on the given perspective camera.
  35056. *
  35057. * @param {PerspectiveCamera} camera - The perspective camera.
  35058. */
  35059. update( camera ) {
  35060. const cache = this._cache;
  35061. const needsUpdate = cache.focus !== camera.focus || cache.fov !== camera.fov ||
  35062. cache.aspect !== camera.aspect * this.aspect || cache.near !== camera.near ||
  35063. cache.far !== camera.far || cache.zoom !== camera.zoom || cache.eyeSep !== this.eyeSep;
  35064. if ( needsUpdate ) {
  35065. cache.focus = camera.focus;
  35066. cache.fov = camera.fov;
  35067. cache.aspect = camera.aspect * this.aspect;
  35068. cache.near = camera.near;
  35069. cache.far = camera.far;
  35070. cache.zoom = camera.zoom;
  35071. cache.eyeSep = this.eyeSep;
  35072. // Off-axis stereoscopic effect based on
  35073. // http://paulbourke.net/stereographics/stereorender/
  35074. _projectionMatrix.copy( camera.projectionMatrix );
  35075. const eyeSepHalf = cache.eyeSep / 2;
  35076. const eyeSepOnProjection = eyeSepHalf * cache.near / cache.focus;
  35077. const ymax = ( cache.near * Math.tan( DEG2RAD * cache.fov * 0.5 ) ) / cache.zoom;
  35078. let xmin, xmax;
  35079. // translate xOffset
  35080. _eyeLeft.elements[ 12 ] = - eyeSepHalf;
  35081. _eyeRight.elements[ 12 ] = eyeSepHalf;
  35082. // for left eye
  35083. xmin = - ymax * cache.aspect + eyeSepOnProjection;
  35084. xmax = ymax * cache.aspect + eyeSepOnProjection;
  35085. _projectionMatrix.elements[ 0 ] = 2 * cache.near / ( xmax - xmin );
  35086. _projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin );
  35087. this.cameraL.projectionMatrix.copy( _projectionMatrix );
  35088. // for right eye
  35089. xmin = - ymax * cache.aspect - eyeSepOnProjection;
  35090. xmax = ymax * cache.aspect - eyeSepOnProjection;
  35091. _projectionMatrix.elements[ 0 ] = 2 * cache.near / ( xmax - xmin );
  35092. _projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin );
  35093. this.cameraR.projectionMatrix.copy( _projectionMatrix );
  35094. }
  35095. this.cameraL.matrixWorld.copy( camera.matrixWorld ).multiply( _eyeLeft );
  35096. this.cameraR.matrixWorld.copy( camera.matrixWorld ).multiply( _eyeRight );
  35097. }
  35098. }
  35099. /**
  35100. * This type of camera can be used in order to efficiently render a scene with a
  35101. * predefined set of cameras. This is an important performance aspect for
  35102. * rendering VR scenes.
  35103. *
  35104. * An instance of `ArrayCamera` always has an array of sub cameras. It's mandatory
  35105. * to define for each sub camera the `viewport` property which determines the
  35106. * part of the viewport that is rendered with this camera.
  35107. *
  35108. * @augments PerspectiveCamera
  35109. */
  35110. class ArrayCamera extends PerspectiveCamera {
  35111. /**
  35112. * Constructs a new array camera.
  35113. *
  35114. * @param {Array<PerspectiveCamera>} [array=[]] - An array of perspective sub cameras.
  35115. */
  35116. constructor( array = [] ) {
  35117. super();
  35118. /**
  35119. * This flag can be used for type testing.
  35120. *
  35121. * @type {boolean}
  35122. * @readonly
  35123. * @default true
  35124. */
  35125. this.isArrayCamera = true;
  35126. /**
  35127. * An array of perspective sub cameras.
  35128. *
  35129. * @type {Array<PerspectiveCamera>}
  35130. */
  35131. this.cameras = array;
  35132. this.index = 0;
  35133. }
  35134. }
  35135. /**
  35136. * Class for keeping track of time.
  35137. */
  35138. class Clock {
  35139. /**
  35140. * Constructs a new clock.
  35141. *
  35142. * @param {boolean} [autoStart=true] - Whether to automatically start the clock when
  35143. * `getDelta()` is called for the first time.
  35144. */
  35145. constructor( autoStart = true ) {
  35146. /**
  35147. * If set to `true`, the clock starts automatically when `getDelta()` is called
  35148. * for the first time.
  35149. *
  35150. * @type {boolean}
  35151. * @default true
  35152. */
  35153. this.autoStart = autoStart;
  35154. /**
  35155. * Holds the time at which the clock's `start()` method was last called.
  35156. *
  35157. * @type {number}
  35158. * @default 0
  35159. */
  35160. this.startTime = 0;
  35161. /**
  35162. * Holds the time at which the clock's `start()`, `getElapsedTime()` or
  35163. * `getDelta()` methods were last called.
  35164. *
  35165. * @type {number}
  35166. * @default 0
  35167. */
  35168. this.oldTime = 0;
  35169. /**
  35170. * Keeps track of the total time that the clock has been running.
  35171. *
  35172. * @type {number}
  35173. * @default 0
  35174. */
  35175. this.elapsedTime = 0;
  35176. /**
  35177. * Whether the clock is running or not.
  35178. *
  35179. * @type {boolean}
  35180. * @default true
  35181. */
  35182. this.running = false;
  35183. }
  35184. /**
  35185. * Starts the clock. When `autoStart` is set to `true`, the method is automatically
  35186. * called by the class.
  35187. */
  35188. start() {
  35189. this.startTime = now();
  35190. this.oldTime = this.startTime;
  35191. this.elapsedTime = 0;
  35192. this.running = true;
  35193. }
  35194. /**
  35195. * Stops the clock.
  35196. */
  35197. stop() {
  35198. this.getElapsedTime();
  35199. this.running = false;
  35200. this.autoStart = false;
  35201. }
  35202. /**
  35203. * Returns the elapsed time in seconds.
  35204. *
  35205. * @return {number} The elapsed time.
  35206. */
  35207. getElapsedTime() {
  35208. this.getDelta();
  35209. return this.elapsedTime;
  35210. }
  35211. /**
  35212. * Returns the delta time in seconds.
  35213. *
  35214. * @return {number} The delta time.
  35215. */
  35216. getDelta() {
  35217. let diff = 0;
  35218. if ( this.autoStart && ! this.running ) {
  35219. this.start();
  35220. return 0;
  35221. }
  35222. if ( this.running ) {
  35223. const newTime = now();
  35224. diff = ( newTime - this.oldTime ) / 1000;
  35225. this.oldTime = newTime;
  35226. this.elapsedTime += diff;
  35227. }
  35228. return diff;
  35229. }
  35230. }
  35231. function now() {
  35232. return performance.now();
  35233. }
  35234. const _position$1 = /*@__PURE__*/ new Vector3();
  35235. const _quaternion$1 = /*@__PURE__*/ new Quaternion();
  35236. const _scale$1 = /*@__PURE__*/ new Vector3();
  35237. const _orientation$1 = /*@__PURE__*/ new Vector3();
  35238. /**
  35239. * The class represents a virtual listener of the all positional and non-positional audio effects
  35240. * in the scene. A three.js application usually creates a single listener. It is a mandatory
  35241. * constructor parameter for audios entities like {@link Audio} and {@link PositionalAudio}.
  35242. *
  35243. * In most cases, the listener object is a child of the camera. So the 3D transformation of the
  35244. * camera represents the 3D transformation of the listener.
  35245. *
  35246. * @augments Object3D
  35247. */
  35248. class AudioListener extends Object3D {
  35249. /**
  35250. * Constructs a new audio listener.
  35251. */
  35252. constructor() {
  35253. super();
  35254. this.type = 'AudioListener';
  35255. /**
  35256. * The native audio context.
  35257. *
  35258. * @type {AudioContext}
  35259. * @readonly
  35260. */
  35261. this.context = AudioContext.getContext();
  35262. /**
  35263. * The gain node used for volume control.
  35264. *
  35265. * @type {GainNode}
  35266. * @readonly
  35267. */
  35268. this.gain = this.context.createGain();
  35269. this.gain.connect( this.context.destination );
  35270. /**
  35271. * An optional filter.
  35272. *
  35273. * Defined via {@link AudioListener#setFilter}.
  35274. *
  35275. * @type {?AudioNode}
  35276. * @default null
  35277. * @readonly
  35278. */
  35279. this.filter = null;
  35280. /**
  35281. * Time delta values required for `linearRampToValueAtTime()` usage.
  35282. *
  35283. * @type {number}
  35284. * @default 0
  35285. * @readonly
  35286. */
  35287. this.timeDelta = 0;
  35288. // private
  35289. this._clock = new Clock();
  35290. }
  35291. /**
  35292. * Returns the listener's input node.
  35293. *
  35294. * This method is used by other audio nodes to connect to this listener.
  35295. *
  35296. * @return {GainNode} The input node.
  35297. */
  35298. getInput() {
  35299. return this.gain;
  35300. }
  35301. /**
  35302. * Removes the current filter from this listener.
  35303. *
  35304. * @return {AudioListener} A reference to this listener.
  35305. */
  35306. removeFilter() {
  35307. if ( this.filter !== null ) {
  35308. this.gain.disconnect( this.filter );
  35309. this.filter.disconnect( this.context.destination );
  35310. this.gain.connect( this.context.destination );
  35311. this.filter = null;
  35312. }
  35313. return this;
  35314. }
  35315. /**
  35316. * Returns the current set filter.
  35317. *
  35318. * @return {?AudioNode} The filter.
  35319. */
  35320. getFilter() {
  35321. return this.filter;
  35322. }
  35323. /**
  35324. * Sets the given filter to this listener.
  35325. *
  35326. * @param {AudioNode} value - The filter to set.
  35327. * @return {AudioListener} A reference to this listener.
  35328. */
  35329. setFilter( value ) {
  35330. if ( this.filter !== null ) {
  35331. this.gain.disconnect( this.filter );
  35332. this.filter.disconnect( this.context.destination );
  35333. } else {
  35334. this.gain.disconnect( this.context.destination );
  35335. }
  35336. this.filter = value;
  35337. this.gain.connect( this.filter );
  35338. this.filter.connect( this.context.destination );
  35339. return this;
  35340. }
  35341. /**
  35342. * Returns the applications master volume.
  35343. *
  35344. * @return {number} The master volume.
  35345. */
  35346. getMasterVolume() {
  35347. return this.gain.gain.value;
  35348. }
  35349. /**
  35350. * Sets the applications master volume. This volume setting affects
  35351. * all audio nodes in the scene.
  35352. *
  35353. * @param {number} value - The master volume to set.
  35354. * @return {AudioListener} A reference to this listener.
  35355. */
  35356. setMasterVolume( value ) {
  35357. this.gain.gain.setTargetAtTime( value, this.context.currentTime, 0.01 );
  35358. return this;
  35359. }
  35360. updateMatrixWorld( force ) {
  35361. super.updateMatrixWorld( force );
  35362. const listener = this.context.listener;
  35363. const up = this.up;
  35364. this.timeDelta = this._clock.getDelta();
  35365. this.matrixWorld.decompose( _position$1, _quaternion$1, _scale$1 );
  35366. _orientation$1.set( 0, 0, -1 ).applyQuaternion( _quaternion$1 );
  35367. if ( listener.positionX ) {
  35368. // code path for Chrome (see #14393)
  35369. const endTime = this.context.currentTime + this.timeDelta;
  35370. listener.positionX.linearRampToValueAtTime( _position$1.x, endTime );
  35371. listener.positionY.linearRampToValueAtTime( _position$1.y, endTime );
  35372. listener.positionZ.linearRampToValueAtTime( _position$1.z, endTime );
  35373. listener.forwardX.linearRampToValueAtTime( _orientation$1.x, endTime );
  35374. listener.forwardY.linearRampToValueAtTime( _orientation$1.y, endTime );
  35375. listener.forwardZ.linearRampToValueAtTime( _orientation$1.z, endTime );
  35376. listener.upX.linearRampToValueAtTime( up.x, endTime );
  35377. listener.upY.linearRampToValueAtTime( up.y, endTime );
  35378. listener.upZ.linearRampToValueAtTime( up.z, endTime );
  35379. } else {
  35380. listener.setPosition( _position$1.x, _position$1.y, _position$1.z );
  35381. listener.setOrientation( _orientation$1.x, _orientation$1.y, _orientation$1.z, up.x, up.y, up.z );
  35382. }
  35383. }
  35384. }
  35385. /**
  35386. * Represents a non-positional ( global ) audio object.
  35387. *
  35388. * This and related audio modules make use of the [Web Audio API]{@link https://www.w3.org/TR/webaudio-1.1/}.
  35389. *
  35390. * ```js
  35391. * // create an AudioListener and add it to the camera
  35392. * const listener = new THREE.AudioListener();
  35393. * camera.add( listener );
  35394. *
  35395. * // create a global audio source
  35396. * const sound = new THREE.Audio( listener );
  35397. *
  35398. * // load a sound and set it as the Audio object's buffer
  35399. * const audioLoader = new THREE.AudioLoader();
  35400. * audioLoader.load( 'sounds/ambient.ogg', function( buffer ) {
  35401. * sound.setBuffer( buffer );
  35402. * sound.setLoop( true );
  35403. * sound.setVolume( 0.5 );
  35404. * sound.play();
  35405. * });
  35406. * ```
  35407. *
  35408. * @augments Object3D
  35409. */
  35410. class Audio extends Object3D {
  35411. /**
  35412. * Constructs a new audio.
  35413. *
  35414. * @param {AudioListener} listener - The global audio listener.
  35415. */
  35416. constructor( listener ) {
  35417. super();
  35418. this.type = 'Audio';
  35419. /**
  35420. * The global audio listener.
  35421. *
  35422. * @type {AudioListener}
  35423. * @readonly
  35424. */
  35425. this.listener = listener;
  35426. /**
  35427. * The audio context.
  35428. *
  35429. * @type {AudioContext}
  35430. * @readonly
  35431. */
  35432. this.context = listener.context;
  35433. /**
  35434. * The gain node used for volume control.
  35435. *
  35436. * @type {GainNode}
  35437. * @readonly
  35438. */
  35439. this.gain = this.context.createGain();
  35440. this.gain.connect( listener.getInput() );
  35441. /**
  35442. * Whether to start playback automatically or not.
  35443. *
  35444. * @type {boolean}
  35445. * @default false
  35446. */
  35447. this.autoplay = false;
  35448. /**
  35449. * A reference to an audio buffer.
  35450. *
  35451. * Defined via {@link Audio#setBuffer}.
  35452. *
  35453. * @type {?AudioBuffer}
  35454. * @default null
  35455. * @readonly
  35456. */
  35457. this.buffer = null;
  35458. /**
  35459. * Modify pitch, measured in cents. +/- 100 is a semitone.
  35460. * +/- 1200 is an octave.
  35461. *
  35462. * Defined via {@link Audio#setDetune}.
  35463. *
  35464. * @type {number}
  35465. * @default 0
  35466. * @readonly
  35467. */
  35468. this.detune = 0;
  35469. /**
  35470. * Whether the audio should loop or not.
  35471. *
  35472. * Defined via {@link Audio#setLoop}.
  35473. *
  35474. * @type {boolean}
  35475. * @default false
  35476. * @readonly
  35477. */
  35478. this.loop = false;
  35479. /**
  35480. * Defines where in the audio buffer the replay should
  35481. * start, in seconds.
  35482. *
  35483. * @type {number}
  35484. * @default 0
  35485. */
  35486. this.loopStart = 0;
  35487. /**
  35488. * Defines where in the audio buffer the replay should
  35489. * stop, in seconds.
  35490. *
  35491. * @type {number}
  35492. * @default 0
  35493. */
  35494. this.loopEnd = 0;
  35495. /**
  35496. * An offset to the time within the audio buffer the playback
  35497. * should begin, in seconds.
  35498. *
  35499. * @type {number}
  35500. * @default 0
  35501. */
  35502. this.offset = 0;
  35503. /**
  35504. * Overrides the default duration of the audio.
  35505. *
  35506. * @type {undefined|number}
  35507. * @default undefined
  35508. */
  35509. this.duration = undefined;
  35510. /**
  35511. * The playback speed.
  35512. *
  35513. * Defined via {@link Audio#setPlaybackRate}.
  35514. *
  35515. * @type {number}
  35516. * @readonly
  35517. * @default 1
  35518. */
  35519. this.playbackRate = 1;
  35520. /**
  35521. * Indicates whether the audio is playing or not.
  35522. *
  35523. * This flag will be automatically set when using {@link Audio#play},
  35524. * {@link Audio#pause}, {@link Audio#stop}.
  35525. *
  35526. * @type {boolean}
  35527. * @readonly
  35528. * @default false
  35529. */
  35530. this.isPlaying = false;
  35531. /**
  35532. * Indicates whether the audio playback can be controlled
  35533. * with method like {@link Audio#play} or {@link Audio#pause}.
  35534. *
  35535. * This flag will be automatically set when audio sources are
  35536. * defined.
  35537. *
  35538. * @type {boolean}
  35539. * @readonly
  35540. * @default true
  35541. */
  35542. this.hasPlaybackControl = true;
  35543. /**
  35544. * Holds a reference to the current audio source.
  35545. *
  35546. * The property is automatically by one of the `set*()` methods.
  35547. *
  35548. * @type {?AudioNode}
  35549. * @readonly
  35550. * @default null
  35551. */
  35552. this.source = null;
  35553. /**
  35554. * Defines the source type.
  35555. *
  35556. * The property is automatically by one of the `set*()` methods.
  35557. *
  35558. * @type {('empty'|'audioNode'|'mediaNode'|'mediaStreamNode'|'buffer')}
  35559. * @readonly
  35560. * @default 'empty'
  35561. */
  35562. this.sourceType = 'empty';
  35563. this._startedAt = 0;
  35564. this._progress = 0;
  35565. this._connected = false;
  35566. /**
  35567. * Can be used to apply a variety of low-order filters to create
  35568. * more complex sound effects e.g. via `BiquadFilterNode`.
  35569. *
  35570. * The property is automatically set by {@link Audio#setFilters}.
  35571. *
  35572. * @type {Array<AudioNode>}
  35573. * @readonly
  35574. */
  35575. this.filters = [];
  35576. }
  35577. /**
  35578. * Returns the output audio node.
  35579. *
  35580. * @return {GainNode} The output node.
  35581. */
  35582. getOutput() {
  35583. return this.gain;
  35584. }
  35585. /**
  35586. * Sets the given audio node as the source of this instance.
  35587. *
  35588. * {@link Audio#sourceType} is set to `audioNode` and {@link Audio#hasPlaybackControl} to `false`.
  35589. *
  35590. * @param {AudioNode} audioNode - The audio node like an instance of `OscillatorNode`.
  35591. * @return {Audio} A reference to this instance.
  35592. */
  35593. setNodeSource( audioNode ) {
  35594. this.hasPlaybackControl = false;
  35595. this.sourceType = 'audioNode';
  35596. this.source = audioNode;
  35597. this.connect();
  35598. return this;
  35599. }
  35600. /**
  35601. * Sets the given media element as the source of this instance.
  35602. *
  35603. * {@link Audio#sourceType} is set to `mediaNode` and {@link Audio#hasPlaybackControl} to `false`.
  35604. *
  35605. * @param {HTMLMediaElement} mediaElement - The media element.
  35606. * @return {Audio} A reference to this instance.
  35607. */
  35608. setMediaElementSource( mediaElement ) {
  35609. this.hasPlaybackControl = false;
  35610. this.sourceType = 'mediaNode';
  35611. this.source = this.context.createMediaElementSource( mediaElement );
  35612. this.connect();
  35613. return this;
  35614. }
  35615. /**
  35616. * Sets the given media stream as the source of this instance.
  35617. *
  35618. * {@link Audio#sourceType} is set to `mediaStreamNode` and {@link Audio#hasPlaybackControl} to `false`.
  35619. *
  35620. * @param {MediaStream} mediaStream - The media stream.
  35621. * @return {Audio} A reference to this instance.
  35622. */
  35623. setMediaStreamSource( mediaStream ) {
  35624. this.hasPlaybackControl = false;
  35625. this.sourceType = 'mediaStreamNode';
  35626. this.source = this.context.createMediaStreamSource( mediaStream );
  35627. this.connect();
  35628. return this;
  35629. }
  35630. /**
  35631. * Sets the given audio buffer as the source of this instance.
  35632. *
  35633. * {@link Audio#sourceType} is set to `buffer` and {@link Audio#hasPlaybackControl} to `true`.
  35634. *
  35635. * @param {AudioBuffer} audioBuffer - The audio buffer.
  35636. * @return {Audio} A reference to this instance.
  35637. */
  35638. setBuffer( audioBuffer ) {
  35639. this.buffer = audioBuffer;
  35640. this.sourceType = 'buffer';
  35641. if ( this.autoplay ) this.play();
  35642. return this;
  35643. }
  35644. /**
  35645. * Starts the playback of the audio.
  35646. *
  35647. * Can only be used with compatible audio sources that allow playback control.
  35648. *
  35649. * @param {number} [delay=0] - The delay, in seconds, at which the audio should start playing.
  35650. * @return {Audio|undefined} A reference to this instance.
  35651. */
  35652. play( delay = 0 ) {
  35653. if ( this.isPlaying === true ) {
  35654. console.warn( 'THREE.Audio: Audio is already playing.' );
  35655. return;
  35656. }
  35657. if ( this.hasPlaybackControl === false ) {
  35658. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  35659. return;
  35660. }
  35661. this._startedAt = this.context.currentTime + delay;
  35662. const source = this.context.createBufferSource();
  35663. source.buffer = this.buffer;
  35664. source.loop = this.loop;
  35665. source.loopStart = this.loopStart;
  35666. source.loopEnd = this.loopEnd;
  35667. source.onended = this.onEnded.bind( this );
  35668. source.start( this._startedAt, this._progress + this.offset, this.duration );
  35669. this.isPlaying = true;
  35670. this.source = source;
  35671. this.setDetune( this.detune );
  35672. this.setPlaybackRate( this.playbackRate );
  35673. return this.connect();
  35674. }
  35675. /**
  35676. * Pauses the playback of the audio.
  35677. *
  35678. * Can only be used with compatible audio sources that allow playback control.
  35679. *
  35680. * @return {Audio|undefined} A reference to this instance.
  35681. */
  35682. pause() {
  35683. if ( this.hasPlaybackControl === false ) {
  35684. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  35685. return;
  35686. }
  35687. if ( this.isPlaying === true ) {
  35688. // update current progress
  35689. this._progress += Math.max( this.context.currentTime - this._startedAt, 0 ) * this.playbackRate;
  35690. if ( this.loop === true ) {
  35691. // ensure _progress does not exceed duration with looped audios
  35692. this._progress = this._progress % ( this.duration || this.buffer.duration );
  35693. }
  35694. this.source.stop();
  35695. this.source.onended = null;
  35696. this.isPlaying = false;
  35697. }
  35698. return this;
  35699. }
  35700. /**
  35701. * Stops the playback of the audio.
  35702. *
  35703. * Can only be used with compatible audio sources that allow playback control.
  35704. *
  35705. * @param {number} [delay=0] - The delay, in seconds, at which the audio should stop playing.
  35706. * @return {Audio|undefined} A reference to this instance.
  35707. */
  35708. stop( delay = 0 ) {
  35709. if ( this.hasPlaybackControl === false ) {
  35710. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  35711. return;
  35712. }
  35713. this._progress = 0;
  35714. if ( this.source !== null ) {
  35715. this.source.stop( this.context.currentTime + delay );
  35716. this.source.onended = null;
  35717. }
  35718. this.isPlaying = false;
  35719. return this;
  35720. }
  35721. /**
  35722. * Connects to the audio source. This is used internally on
  35723. * initialisation and when setting / removing filters.
  35724. *
  35725. * @return {Audio} A reference to this instance.
  35726. */
  35727. connect() {
  35728. if ( this.filters.length > 0 ) {
  35729. this.source.connect( this.filters[ 0 ] );
  35730. for ( let i = 1, l = this.filters.length; i < l; i ++ ) {
  35731. this.filters[ i - 1 ].connect( this.filters[ i ] );
  35732. }
  35733. this.filters[ this.filters.length - 1 ].connect( this.getOutput() );
  35734. } else {
  35735. this.source.connect( this.getOutput() );
  35736. }
  35737. this._connected = true;
  35738. return this;
  35739. }
  35740. /**
  35741. * Disconnects to the audio source. This is used internally on
  35742. * initialisation and when setting / removing filters.
  35743. *
  35744. * @return {Audio|undefined} A reference to this instance.
  35745. */
  35746. disconnect() {
  35747. if ( this._connected === false ) {
  35748. return;
  35749. }
  35750. if ( this.filters.length > 0 ) {
  35751. this.source.disconnect( this.filters[ 0 ] );
  35752. for ( let i = 1, l = this.filters.length; i < l; i ++ ) {
  35753. this.filters[ i - 1 ].disconnect( this.filters[ i ] );
  35754. }
  35755. this.filters[ this.filters.length - 1 ].disconnect( this.getOutput() );
  35756. } else {
  35757. this.source.disconnect( this.getOutput() );
  35758. }
  35759. this._connected = false;
  35760. return this;
  35761. }
  35762. /**
  35763. * Returns the current set filters.
  35764. *
  35765. * @return {Array<AudioNode>} The list of filters.
  35766. */
  35767. getFilters() {
  35768. return this.filters;
  35769. }
  35770. /**
  35771. * Sets an array of filters and connects them with the audio source.
  35772. *
  35773. * @param {Array<AudioNode>} [value] - A list of filters.
  35774. * @return {Audio} A reference to this instance.
  35775. */
  35776. setFilters( value ) {
  35777. if ( ! value ) value = [];
  35778. if ( this._connected === true ) {
  35779. this.disconnect();
  35780. this.filters = value.slice();
  35781. this.connect();
  35782. } else {
  35783. this.filters = value.slice();
  35784. }
  35785. return this;
  35786. }
  35787. /**
  35788. * Defines the detuning of oscillation in cents.
  35789. *
  35790. * @param {number} value - The detuning of oscillation in cents.
  35791. * @return {Audio} A reference to this instance.
  35792. */
  35793. setDetune( value ) {
  35794. this.detune = value;
  35795. if ( this.isPlaying === true && this.source.detune !== undefined ) {
  35796. this.source.detune.setTargetAtTime( this.detune, this.context.currentTime, 0.01 );
  35797. }
  35798. return this;
  35799. }
  35800. /**
  35801. * Returns the detuning of oscillation in cents.
  35802. *
  35803. * @return {number} The detuning of oscillation in cents.
  35804. */
  35805. getDetune() {
  35806. return this.detune;
  35807. }
  35808. /**
  35809. * Returns the first filter in the list of filters.
  35810. *
  35811. * @return {AudioNode|undefined} The first filter in the list of filters.
  35812. */
  35813. getFilter() {
  35814. return this.getFilters()[ 0 ];
  35815. }
  35816. /**
  35817. * Applies a single filter node to the audio.
  35818. *
  35819. * @param {AudioNode} [filter] - The filter to set.
  35820. * @return {Audio} A reference to this instance.
  35821. */
  35822. setFilter( filter ) {
  35823. return this.setFilters( filter ? [ filter ] : [] );
  35824. }
  35825. /**
  35826. * Sets the playback rate.
  35827. *
  35828. * Can only be used with compatible audio sources that allow playback control.
  35829. *
  35830. * @param {number} [value] - The playback rate to set.
  35831. * @return {Audio|undefined} A reference to this instance.
  35832. */
  35833. setPlaybackRate( value ) {
  35834. if ( this.hasPlaybackControl === false ) {
  35835. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  35836. return;
  35837. }
  35838. this.playbackRate = value;
  35839. if ( this.isPlaying === true ) {
  35840. this.source.playbackRate.setTargetAtTime( this.playbackRate, this.context.currentTime, 0.01 );
  35841. }
  35842. return this;
  35843. }
  35844. /**
  35845. * Returns the current playback rate.
  35846. * @return {number} The playback rate.
  35847. */
  35848. getPlaybackRate() {
  35849. return this.playbackRate;
  35850. }
  35851. /**
  35852. * Automatically called when playback finished.
  35853. */
  35854. onEnded() {
  35855. this.isPlaying = false;
  35856. this._progress = 0;
  35857. }
  35858. /**
  35859. * Returns the loop flag.
  35860. *
  35861. * Can only be used with compatible audio sources that allow playback control.
  35862. *
  35863. * @return {boolean} Whether the audio should loop or not.
  35864. */
  35865. getLoop() {
  35866. if ( this.hasPlaybackControl === false ) {
  35867. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  35868. return false;
  35869. }
  35870. return this.loop;
  35871. }
  35872. /**
  35873. * Sets the loop flag.
  35874. *
  35875. * Can only be used with compatible audio sources that allow playback control.
  35876. *
  35877. * @param {boolean} value - Whether the audio should loop or not.
  35878. * @return {Audio|undefined} A reference to this instance.
  35879. */
  35880. setLoop( value ) {
  35881. if ( this.hasPlaybackControl === false ) {
  35882. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  35883. return;
  35884. }
  35885. this.loop = value;
  35886. if ( this.isPlaying === true ) {
  35887. this.source.loop = this.loop;
  35888. }
  35889. return this;
  35890. }
  35891. /**
  35892. * Sets the loop start value which defines where in the audio buffer the replay should
  35893. * start, in seconds.
  35894. *
  35895. * @param {number} value - The loop start value.
  35896. * @return {Audio} A reference to this instance.
  35897. */
  35898. setLoopStart( value ) {
  35899. this.loopStart = value;
  35900. return this;
  35901. }
  35902. /**
  35903. * Sets the loop end value which defines where in the audio buffer the replay should
  35904. * stop, in seconds.
  35905. *
  35906. * @param {number} value - The loop end value.
  35907. * @return {Audio} A reference to this instance.
  35908. */
  35909. setLoopEnd( value ) {
  35910. this.loopEnd = value;
  35911. return this;
  35912. }
  35913. /**
  35914. * Returns the volume.
  35915. *
  35916. * @return {number} The volume.
  35917. */
  35918. getVolume() {
  35919. return this.gain.gain.value;
  35920. }
  35921. /**
  35922. * Sets the volume.
  35923. *
  35924. * @param {number} value - The volume to set.
  35925. * @return {Audio} A reference to this instance.
  35926. */
  35927. setVolume( value ) {
  35928. this.gain.gain.setTargetAtTime( value, this.context.currentTime, 0.01 );
  35929. return this;
  35930. }
  35931. copy( source, recursive ) {
  35932. super.copy( source, recursive );
  35933. if ( source.sourceType !== 'buffer' ) {
  35934. console.warn( 'THREE.Audio: Audio source type cannot be copied.' );
  35935. return this;
  35936. }
  35937. this.autoplay = source.autoplay;
  35938. this.buffer = source.buffer;
  35939. this.detune = source.detune;
  35940. this.loop = source.loop;
  35941. this.loopStart = source.loopStart;
  35942. this.loopEnd = source.loopEnd;
  35943. this.offset = source.offset;
  35944. this.duration = source.duration;
  35945. this.playbackRate = source.playbackRate;
  35946. this.hasPlaybackControl = source.hasPlaybackControl;
  35947. this.sourceType = source.sourceType;
  35948. this.filters = source.filters.slice();
  35949. return this;
  35950. }
  35951. clone( recursive ) {
  35952. return new this.constructor( this.listener ).copy( this, recursive );
  35953. }
  35954. }
  35955. const _position = /*@__PURE__*/ new Vector3();
  35956. const _quaternion = /*@__PURE__*/ new Quaternion();
  35957. const _scale = /*@__PURE__*/ new Vector3();
  35958. const _orientation = /*@__PURE__*/ new Vector3();
  35959. /**
  35960. * Represents a positional audio object.
  35961. *
  35962. * ```js
  35963. * // create an AudioListener and add it to the camera
  35964. * const listener = new THREE.AudioListener();
  35965. * camera.add( listener );
  35966. *
  35967. * // create the PositionalAudio object (passing in the listener)
  35968. * const sound = new THREE.PositionalAudio( listener );
  35969. *
  35970. * // load a sound and set it as the PositionalAudio object's buffer
  35971. * const audioLoader = new THREE.AudioLoader();
  35972. * audioLoader.load( 'sounds/song.ogg', function( buffer ) {
  35973. * sound.setBuffer( buffer );
  35974. * sound.setRefDistance( 20 );
  35975. * sound.play();
  35976. * });
  35977. *
  35978. * // create an object for the sound to play from
  35979. * const sphere = new THREE.SphereGeometry( 20, 32, 16 );
  35980. * const material = new THREE.MeshPhongMaterial( { color: 0xff2200 } );
  35981. * const mesh = new THREE.Mesh( sphere, material );
  35982. * scene.add( mesh );
  35983. *
  35984. * // finally add the sound to the mesh
  35985. * mesh.add( sound );
  35986. *
  35987. * @augments Audio
  35988. */
  35989. class PositionalAudio extends Audio {
  35990. /**
  35991. * Constructs a positional audio.
  35992. *
  35993. * @param {AudioListener} listener - The global audio listener.
  35994. */
  35995. constructor( listener ) {
  35996. super( listener );
  35997. /**
  35998. * The panner node represents the location, direction, and behavior of an audio
  35999. * source in 3D space.
  36000. *
  36001. * @type {PannerNode}
  36002. * @readonly
  36003. */
  36004. this.panner = this.context.createPanner();
  36005. this.panner.panningModel = 'HRTF';
  36006. this.panner.connect( this.gain );
  36007. }
  36008. connect() {
  36009. super.connect();
  36010. this.panner.connect( this.gain );
  36011. return this;
  36012. }
  36013. disconnect() {
  36014. super.disconnect();
  36015. this.panner.disconnect( this.gain );
  36016. return this;
  36017. }
  36018. getOutput() {
  36019. return this.panner;
  36020. }
  36021. /**
  36022. * Returns the current reference distance.
  36023. *
  36024. * @return {number} The reference distance.
  36025. */
  36026. getRefDistance() {
  36027. return this.panner.refDistance;
  36028. }
  36029. /**
  36030. * Defines the reference distance for reducing volume as the audio source moves
  36031. * further from the listener – i.e. the distance at which the volume reduction
  36032. * starts taking effect.
  36033. *
  36034. * @param {number} value - The reference distance to set.
  36035. * @return {PositionalAudio} A reference to this instance.
  36036. */
  36037. setRefDistance( value ) {
  36038. this.panner.refDistance = value;
  36039. return this;
  36040. }
  36041. /**
  36042. * Returns the current rolloff factor.
  36043. *
  36044. * @return {number} The rolloff factor.
  36045. */
  36046. getRolloffFactor() {
  36047. return this.panner.rolloffFactor;
  36048. }
  36049. /**
  36050. * Defines how quickly the volume is reduced as the source moves away from the listener.
  36051. *
  36052. * @param {number} value - The rolloff factor.
  36053. * @return {PositionalAudio} A reference to this instance.
  36054. */
  36055. setRolloffFactor( value ) {
  36056. this.panner.rolloffFactor = value;
  36057. return this;
  36058. }
  36059. /**
  36060. * Returns the current distance model.
  36061. *
  36062. * @return {('linear'|'inverse'|'exponential')} The distance model.
  36063. */
  36064. getDistanceModel() {
  36065. return this.panner.distanceModel;
  36066. }
  36067. /**
  36068. * Defines which algorithm to use to reduce the volume of the audio source
  36069. * as it moves away from the listener.
  36070. *
  36071. * Read [the spec]{@link https://www.w3.org/TR/webaudio-1.1/#enumdef-distancemodeltype}
  36072. * for more details.
  36073. *
  36074. * @param {('linear'|'inverse'|'exponential')} value - The distance model to set.
  36075. * @return {PositionalAudio} A reference to this instance.
  36076. */
  36077. setDistanceModel( value ) {
  36078. this.panner.distanceModel = value;
  36079. return this;
  36080. }
  36081. /**
  36082. * Returns the current max distance.
  36083. *
  36084. * @return {number} The max distance.
  36085. */
  36086. getMaxDistance() {
  36087. return this.panner.maxDistance;
  36088. }
  36089. /**
  36090. * Defines the maximum distance between the audio source and the listener,
  36091. * after which the volume is not reduced any further.
  36092. *
  36093. * This value is used only by the `linear` distance model.
  36094. *
  36095. * @param {number} value - The max distance.
  36096. * @return {PositionalAudio} A reference to this instance.
  36097. */
  36098. setMaxDistance( value ) {
  36099. this.panner.maxDistance = value;
  36100. return this;
  36101. }
  36102. /**
  36103. * Sets the directional cone in which the audio can be listened.
  36104. *
  36105. * @param {number} coneInnerAngle - An angle, in degrees, of a cone inside of which there will be no volume reduction.
  36106. * @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.
  36107. * @param {number} coneOuterGain - The amount of volume reduction outside the cone defined by the `coneOuterAngle`. When set to `0`, no sound can be heard.
  36108. * @return {PositionalAudio} A reference to this instance.
  36109. */
  36110. setDirectionalCone( coneInnerAngle, coneOuterAngle, coneOuterGain ) {
  36111. this.panner.coneInnerAngle = coneInnerAngle;
  36112. this.panner.coneOuterAngle = coneOuterAngle;
  36113. this.panner.coneOuterGain = coneOuterGain;
  36114. return this;
  36115. }
  36116. updateMatrixWorld( force ) {
  36117. super.updateMatrixWorld( force );
  36118. if ( this.hasPlaybackControl === true && this.isPlaying === false ) return;
  36119. this.matrixWorld.decompose( _position, _quaternion, _scale );
  36120. _orientation.set( 0, 0, 1 ).applyQuaternion( _quaternion );
  36121. const panner = this.panner;
  36122. if ( panner.positionX ) {
  36123. // code path for Chrome and Firefox (see #14393)
  36124. const endTime = this.context.currentTime + this.listener.timeDelta;
  36125. panner.positionX.linearRampToValueAtTime( _position.x, endTime );
  36126. panner.positionY.linearRampToValueAtTime( _position.y, endTime );
  36127. panner.positionZ.linearRampToValueAtTime( _position.z, endTime );
  36128. panner.orientationX.linearRampToValueAtTime( _orientation.x, endTime );
  36129. panner.orientationY.linearRampToValueAtTime( _orientation.y, endTime );
  36130. panner.orientationZ.linearRampToValueAtTime( _orientation.z, endTime );
  36131. } else {
  36132. panner.setPosition( _position.x, _position.y, _position.z );
  36133. panner.setOrientation( _orientation.x, _orientation.y, _orientation.z );
  36134. }
  36135. }
  36136. }
  36137. /**
  36138. * This class can be used to analyse audio data.
  36139. *
  36140. * ```js
  36141. * // create an AudioListener and add it to the camera
  36142. * const listener = new THREE.AudioListener();
  36143. * camera.add( listener );
  36144. *
  36145. * // create an Audio source
  36146. * const sound = new THREE.Audio( listener );
  36147. *
  36148. * // load a sound and set it as the Audio object's buffer
  36149. * const audioLoader = new THREE.AudioLoader();
  36150. * audioLoader.load( 'sounds/ambient.ogg', function( buffer ) {
  36151. * sound.setBuffer( buffer );
  36152. * sound.setLoop(true);
  36153. * sound.setVolume(0.5);
  36154. * sound.play();
  36155. * });
  36156. *
  36157. * // create an AudioAnalyser, passing in the sound and desired fftSize
  36158. * const analyser = new THREE.AudioAnalyser( sound, 32 );
  36159. *
  36160. * // get the average frequency of the sound
  36161. * const data = analyser.getAverageFrequency();
  36162. * ```
  36163. */
  36164. class AudioAnalyser {
  36165. /**
  36166. * Constructs a new audio analyzer.
  36167. *
  36168. * @param {Audio} audio - The audio to analyze.
  36169. * @param {number} [fftSize=2048] - The window size in samples that is used when performing a Fast Fourier Transform (FFT) to get frequency domain data.
  36170. */
  36171. constructor( audio, fftSize = 2048 ) {
  36172. /**
  36173. * The global audio listener.
  36174. *
  36175. * @type {AnalyserNode}
  36176. */
  36177. this.analyser = audio.context.createAnalyser();
  36178. this.analyser.fftSize = fftSize;
  36179. /**
  36180. * Holds the analyzed data.
  36181. *
  36182. * @type {Uint8Array}
  36183. */
  36184. this.data = new Uint8Array( this.analyser.frequencyBinCount );
  36185. audio.getOutput().connect( this.analyser );
  36186. }
  36187. /**
  36188. * Returns an array with frequency data of the audio.
  36189. *
  36190. * Each item in the array represents the decibel value for a specific frequency.
  36191. * The frequencies are spread linearly from 0 to 1/2 of the sample rate.
  36192. * For example, for 48000 sample rate, the last item of the array will represent
  36193. * the decibel value for 24000 Hz.
  36194. *
  36195. * @return {Uint8Array} The frequency data.
  36196. */
  36197. getFrequencyData() {
  36198. this.analyser.getByteFrequencyData( this.data );
  36199. return this.data;
  36200. }
  36201. /**
  36202. * Returns the average of the frequencies returned by {@link AudioAnalyser#getFrequencyData}.
  36203. *
  36204. * @return {number} The average frequency.
  36205. */
  36206. getAverageFrequency() {
  36207. let value = 0;
  36208. const data = this.getFrequencyData();
  36209. for ( let i = 0; i < data.length; i ++ ) {
  36210. value += data[ i ];
  36211. }
  36212. return value / data.length;
  36213. }
  36214. }
  36215. /**
  36216. * Buffered scene graph property that allows weighted accumulation; used internally.
  36217. */
  36218. class PropertyMixer {
  36219. /**
  36220. * Constructs a new property mixer.
  36221. *
  36222. * @param {PropertyBinding} binding - The property binding.
  36223. * @param {string} typeName - The keyframe track type name.
  36224. * @param {number} valueSize - The keyframe track value size.
  36225. */
  36226. constructor( binding, typeName, valueSize ) {
  36227. /**
  36228. * The property binding.
  36229. *
  36230. * @type {PropertyBinding}
  36231. */
  36232. this.binding = binding;
  36233. /**
  36234. * The keyframe track value size.
  36235. *
  36236. * @type {number}
  36237. */
  36238. this.valueSize = valueSize;
  36239. let mixFunction,
  36240. mixFunctionAdditive,
  36241. setIdentity;
  36242. // buffer layout: [ incoming | accu0 | accu1 | orig | addAccu | (optional work) ]
  36243. //
  36244. // interpolators can use .buffer as their .result
  36245. // the data then goes to 'incoming'
  36246. //
  36247. // 'accu0' and 'accu1' are used frame-interleaved for
  36248. // the cumulative result and are compared to detect
  36249. // changes
  36250. //
  36251. // 'orig' stores the original state of the property
  36252. //
  36253. // 'add' is used for additive cumulative results
  36254. //
  36255. // 'work' is optional and is only present for quaternion types. It is used
  36256. // to store intermediate quaternion multiplication results
  36257. switch ( typeName ) {
  36258. case 'quaternion':
  36259. mixFunction = this._slerp;
  36260. mixFunctionAdditive = this._slerpAdditive;
  36261. setIdentity = this._setAdditiveIdentityQuaternion;
  36262. this.buffer = new Float64Array( valueSize * 6 );
  36263. this._workIndex = 5;
  36264. break;
  36265. case 'string':
  36266. case 'bool':
  36267. mixFunction = this._select;
  36268. // Use the regular mix function and for additive on these types,
  36269. // additive is not relevant for non-numeric types
  36270. mixFunctionAdditive = this._select;
  36271. setIdentity = this._setAdditiveIdentityOther;
  36272. this.buffer = new Array( valueSize * 5 );
  36273. break;
  36274. default:
  36275. mixFunction = this._lerp;
  36276. mixFunctionAdditive = this._lerpAdditive;
  36277. setIdentity = this._setAdditiveIdentityNumeric;
  36278. this.buffer = new Float64Array( valueSize * 5 );
  36279. }
  36280. this._mixBufferRegion = mixFunction;
  36281. this._mixBufferRegionAdditive = mixFunctionAdditive;
  36282. this._setIdentity = setIdentity;
  36283. this._origIndex = 3;
  36284. this._addIndex = 4;
  36285. /**
  36286. * TODO
  36287. *
  36288. * @type {number}
  36289. * @default 0
  36290. */
  36291. this.cumulativeWeight = 0;
  36292. /**
  36293. * TODO
  36294. *
  36295. * @type {number}
  36296. * @default 0
  36297. */
  36298. this.cumulativeWeightAdditive = 0;
  36299. /**
  36300. * TODO
  36301. *
  36302. * @type {number}
  36303. * @default 0
  36304. */
  36305. this.useCount = 0;
  36306. /**
  36307. * TODO
  36308. *
  36309. * @type {number}
  36310. * @default 0
  36311. */
  36312. this.referenceCount = 0;
  36313. }
  36314. /**
  36315. * Accumulates data in the `incoming` region into `accu<i>`.
  36316. *
  36317. * @param {number} accuIndex - The accumulation index.
  36318. * @param {number} weight - The weight.
  36319. */
  36320. accumulate( accuIndex, weight ) {
  36321. // note: happily accumulating nothing when weight = 0, the caller knows
  36322. // the weight and shouldn't have made the call in the first place
  36323. const buffer = this.buffer,
  36324. stride = this.valueSize,
  36325. offset = accuIndex * stride + stride;
  36326. let currentWeight = this.cumulativeWeight;
  36327. if ( currentWeight === 0 ) {
  36328. // accuN := incoming * weight
  36329. for ( let i = 0; i !== stride; ++ i ) {
  36330. buffer[ offset + i ] = buffer[ i ];
  36331. }
  36332. currentWeight = weight;
  36333. } else {
  36334. // accuN := accuN + incoming * weight
  36335. currentWeight += weight;
  36336. const mix = weight / currentWeight;
  36337. this._mixBufferRegion( buffer, offset, 0, mix, stride );
  36338. }
  36339. this.cumulativeWeight = currentWeight;
  36340. }
  36341. /**
  36342. * Accumulates data in the `incoming` region into `add`.
  36343. *
  36344. * @param {number} weight - The weight.
  36345. */
  36346. accumulateAdditive( weight ) {
  36347. const buffer = this.buffer,
  36348. stride = this.valueSize,
  36349. offset = stride * this._addIndex;
  36350. if ( this.cumulativeWeightAdditive === 0 ) {
  36351. // add = identity
  36352. this._setIdentity();
  36353. }
  36354. // add := add + incoming * weight
  36355. this._mixBufferRegionAdditive( buffer, offset, 0, weight, stride );
  36356. this.cumulativeWeightAdditive += weight;
  36357. }
  36358. /**
  36359. * Applies the state of `accu<i>` to the binding when accus differ.
  36360. *
  36361. * @param {number} accuIndex - The accumulation index.
  36362. */
  36363. apply( accuIndex ) {
  36364. const stride = this.valueSize,
  36365. buffer = this.buffer,
  36366. offset = accuIndex * stride + stride,
  36367. weight = this.cumulativeWeight,
  36368. weightAdditive = this.cumulativeWeightAdditive,
  36369. binding = this.binding;
  36370. this.cumulativeWeight = 0;
  36371. this.cumulativeWeightAdditive = 0;
  36372. if ( weight < 1 ) {
  36373. // accuN := accuN + original * ( 1 - cumulativeWeight )
  36374. const originalValueOffset = stride * this._origIndex;
  36375. this._mixBufferRegion(
  36376. buffer, offset, originalValueOffset, 1 - weight, stride );
  36377. }
  36378. if ( weightAdditive > 0 ) {
  36379. // accuN := accuN + additive accuN
  36380. this._mixBufferRegionAdditive( buffer, offset, this._addIndex * stride, 1, stride );
  36381. }
  36382. for ( let i = stride, e = stride + stride; i !== e; ++ i ) {
  36383. if ( buffer[ i ] !== buffer[ i + stride ] ) {
  36384. // value has changed -> update scene graph
  36385. binding.setValue( buffer, offset );
  36386. break;
  36387. }
  36388. }
  36389. }
  36390. /**
  36391. * Remembers the state of the bound property and copy it to both accus.
  36392. */
  36393. saveOriginalState() {
  36394. const binding = this.binding;
  36395. const buffer = this.buffer,
  36396. stride = this.valueSize,
  36397. originalValueOffset = stride * this._origIndex;
  36398. binding.getValue( buffer, originalValueOffset );
  36399. // accu[0..1] := orig -- initially detect changes against the original
  36400. for ( let i = stride, e = originalValueOffset; i !== e; ++ i ) {
  36401. buffer[ i ] = buffer[ originalValueOffset + ( i % stride ) ];
  36402. }
  36403. // Add to identity for additive
  36404. this._setIdentity();
  36405. this.cumulativeWeight = 0;
  36406. this.cumulativeWeightAdditive = 0;
  36407. }
  36408. /**
  36409. * Applies the state previously taken via {@link PropertyMixer#saveOriginalState} to the binding.
  36410. */
  36411. restoreOriginalState() {
  36412. const originalValueOffset = this.valueSize * 3;
  36413. this.binding.setValue( this.buffer, originalValueOffset );
  36414. }
  36415. // internals
  36416. _setAdditiveIdentityNumeric() {
  36417. const startIndex = this._addIndex * this.valueSize;
  36418. const endIndex = startIndex + this.valueSize;
  36419. for ( let i = startIndex; i < endIndex; i ++ ) {
  36420. this.buffer[ i ] = 0;
  36421. }
  36422. }
  36423. _setAdditiveIdentityQuaternion() {
  36424. this._setAdditiveIdentityNumeric();
  36425. this.buffer[ this._addIndex * this.valueSize + 3 ] = 1;
  36426. }
  36427. _setAdditiveIdentityOther() {
  36428. const startIndex = this._origIndex * this.valueSize;
  36429. const targetIndex = this._addIndex * this.valueSize;
  36430. for ( let i = 0; i < this.valueSize; i ++ ) {
  36431. this.buffer[ targetIndex + i ] = this.buffer[ startIndex + i ];
  36432. }
  36433. }
  36434. // mix functions
  36435. _select( buffer, dstOffset, srcOffset, t, stride ) {
  36436. if ( t >= 0.5 ) {
  36437. for ( let i = 0; i !== stride; ++ i ) {
  36438. buffer[ dstOffset + i ] = buffer[ srcOffset + i ];
  36439. }
  36440. }
  36441. }
  36442. _slerp( buffer, dstOffset, srcOffset, t ) {
  36443. Quaternion.slerpFlat( buffer, dstOffset, buffer, dstOffset, buffer, srcOffset, t );
  36444. }
  36445. _slerpAdditive( buffer, dstOffset, srcOffset, t, stride ) {
  36446. const workOffset = this._workIndex * stride;
  36447. // Store result in intermediate buffer offset
  36448. Quaternion.multiplyQuaternionsFlat( buffer, workOffset, buffer, dstOffset, buffer, srcOffset );
  36449. // Slerp to the intermediate result
  36450. Quaternion.slerpFlat( buffer, dstOffset, buffer, dstOffset, buffer, workOffset, t );
  36451. }
  36452. _lerp( buffer, dstOffset, srcOffset, t, stride ) {
  36453. const s = 1 - t;
  36454. for ( let i = 0; i !== stride; ++ i ) {
  36455. const j = dstOffset + i;
  36456. buffer[ j ] = buffer[ j ] * s + buffer[ srcOffset + i ] * t;
  36457. }
  36458. }
  36459. _lerpAdditive( buffer, dstOffset, srcOffset, t, stride ) {
  36460. for ( let i = 0; i !== stride; ++ i ) {
  36461. const j = dstOffset + i;
  36462. buffer[ j ] = buffer[ j ] + buffer[ srcOffset + i ] * t;
  36463. }
  36464. }
  36465. }
  36466. // Characters [].:/ are reserved for track binding syntax.
  36467. const _RESERVED_CHARS_RE = '\\[\\]\\.:\\/';
  36468. const _reservedRe = new RegExp( '[' + _RESERVED_CHARS_RE + ']', 'g' );
  36469. // Attempts to allow node names from any language. ES5's `\w` regexp matches
  36470. // only latin characters, and the unicode \p{L} is not yet supported. So
  36471. // instead, we exclude reserved characters and match everything else.
  36472. const _wordChar = '[^' + _RESERVED_CHARS_RE + ']';
  36473. const _wordCharOrDot = '[^' + _RESERVED_CHARS_RE.replace( '\\.', '' ) + ']';
  36474. // Parent directories, delimited by '/' or ':'. Currently unused, but must
  36475. // be matched to parse the rest of the track name.
  36476. const _directoryRe = /*@__PURE__*/ /((?:WC+[\/:])*)/.source.replace( 'WC', _wordChar );
  36477. // Target node. May contain word characters (a-zA-Z0-9_) and '.' or '-'.
  36478. const _nodeRe = /*@__PURE__*/ /(WCOD+)?/.source.replace( 'WCOD', _wordCharOrDot );
  36479. // Object on target node, and accessor. May not contain reserved
  36480. // characters. Accessor may contain any character except closing bracket.
  36481. const _objectRe = /*@__PURE__*/ /(?:\.(WC+)(?:\[(.+)\])?)?/.source.replace( 'WC', _wordChar );
  36482. // Property and accessor. May not contain reserved characters. Accessor may
  36483. // contain any non-bracket characters.
  36484. const _propertyRe = /*@__PURE__*/ /\.(WC+)(?:\[(.+)\])?/.source.replace( 'WC', _wordChar );
  36485. const _trackRe = new RegExp( ''
  36486. + '^'
  36487. + _directoryRe
  36488. + _nodeRe
  36489. + _objectRe
  36490. + _propertyRe
  36491. + '$'
  36492. );
  36493. const _supportedObjectNames = [ 'material', 'materials', 'bones', 'map' ];
  36494. class Composite {
  36495. constructor( targetGroup, path, optionalParsedPath ) {
  36496. const parsedPath = optionalParsedPath || PropertyBinding.parseTrackName( path );
  36497. this._targetGroup = targetGroup;
  36498. this._bindings = targetGroup.subscribe_( path, parsedPath );
  36499. }
  36500. getValue( array, offset ) {
  36501. this.bind(); // bind all binding
  36502. const firstValidIndex = this._targetGroup.nCachedObjects_,
  36503. binding = this._bindings[ firstValidIndex ];
  36504. // and only call .getValue on the first
  36505. if ( binding !== undefined ) binding.getValue( array, offset );
  36506. }
  36507. setValue( array, offset ) {
  36508. const bindings = this._bindings;
  36509. for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  36510. bindings[ i ].setValue( array, offset );
  36511. }
  36512. }
  36513. bind() {
  36514. const bindings = this._bindings;
  36515. for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  36516. bindings[ i ].bind();
  36517. }
  36518. }
  36519. unbind() {
  36520. const bindings = this._bindings;
  36521. for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  36522. bindings[ i ].unbind();
  36523. }
  36524. }
  36525. }
  36526. // Note: This class uses a State pattern on a per-method basis:
  36527. // 'bind' sets 'this.getValue' / 'setValue' and shadows the
  36528. // prototype version of these methods with one that represents
  36529. // the bound state. When the property is not found, the methods
  36530. // become no-ops.
  36531. /**
  36532. * This holds a reference to a real property in the scene graph; used internally.
  36533. */
  36534. class PropertyBinding {
  36535. /**
  36536. * Constructs a new property binding.
  36537. *
  36538. * @param {Object} rootNode - The root node.
  36539. * @param {string} path - The path.
  36540. * @param {?Object} [parsedPath] - The parsed path.
  36541. */
  36542. constructor( rootNode, path, parsedPath ) {
  36543. /**
  36544. * The object path to the animated property.
  36545. *
  36546. * @type {string}
  36547. */
  36548. this.path = path;
  36549. /**
  36550. * An object holding information about the path.
  36551. *
  36552. * @type {Object}
  36553. */
  36554. this.parsedPath = parsedPath || PropertyBinding.parseTrackName( path );
  36555. /**
  36556. * The object owns the animated property.
  36557. *
  36558. * @type {?Object}
  36559. */
  36560. this.node = PropertyBinding.findNode( rootNode, this.parsedPath.nodeName );
  36561. /**
  36562. * The root node.
  36563. *
  36564. * @type {Object3D|Skeleton}
  36565. */
  36566. this.rootNode = rootNode;
  36567. // initial state of these methods that calls 'bind'
  36568. this.getValue = this._getValue_unbound;
  36569. this.setValue = this._setValue_unbound;
  36570. }
  36571. /**
  36572. * Factory method for creating a property binding from the given parameters.
  36573. *
  36574. * @static
  36575. * @param {Object} root - The root node.
  36576. * @param {string} path - The path.
  36577. * @param {?Object} [parsedPath] - The parsed path.
  36578. * @return {PropertyBinding|Composite} The created property binding or composite.
  36579. */
  36580. static create( root, path, parsedPath ) {
  36581. if ( ! ( root && root.isAnimationObjectGroup ) ) {
  36582. return new PropertyBinding( root, path, parsedPath );
  36583. } else {
  36584. return new PropertyBinding.Composite( root, path, parsedPath );
  36585. }
  36586. }
  36587. /**
  36588. * Replaces spaces with underscores and removes unsupported characters from
  36589. * node names, to ensure compatibility with parseTrackName().
  36590. *
  36591. * @param {string} name - Node name to be sanitized.
  36592. * @return {string} The sanitized node name.
  36593. */
  36594. static sanitizeNodeName( name ) {
  36595. return name.replace( /\s/g, '_' ).replace( _reservedRe, '' );
  36596. }
  36597. /**
  36598. * Parses the given track name (an object path to an animated property) and
  36599. * returns an object with information about the path. Matches strings in the following forms:
  36600. *
  36601. * - nodeName.property
  36602. * - nodeName.property[accessor]
  36603. * - nodeName.material.property[accessor]
  36604. * - uuid.property[accessor]
  36605. * - uuid.objectName[objectIndex].propertyName[propertyIndex]
  36606. * - parentName/nodeName.property
  36607. * - parentName/parentName/nodeName.property[index]
  36608. * - .bone[Armature.DEF_cog].position
  36609. * - scene:helium_balloon_model:helium_balloon_model.position
  36610. *
  36611. * @static
  36612. * @param {string} trackName - The track name to parse.
  36613. * @return {Object} The parsed track name as an object.
  36614. */
  36615. static parseTrackName( trackName ) {
  36616. const matches = _trackRe.exec( trackName );
  36617. if ( matches === null ) {
  36618. throw new Error( 'PropertyBinding: Cannot parse trackName: ' + trackName );
  36619. }
  36620. const results = {
  36621. // directoryName: matches[ 1 ], // (tschw) currently unused
  36622. nodeName: matches[ 2 ],
  36623. objectName: matches[ 3 ],
  36624. objectIndex: matches[ 4 ],
  36625. propertyName: matches[ 5 ], // required
  36626. propertyIndex: matches[ 6 ]
  36627. };
  36628. const lastDot = results.nodeName && results.nodeName.lastIndexOf( '.' );
  36629. if ( lastDot !== undefined && lastDot !== -1 ) {
  36630. const objectName = results.nodeName.substring( lastDot + 1 );
  36631. // Object names must be checked against an allowlist. Otherwise, there
  36632. // is no way to parse 'foo.bar.baz': 'baz' must be a property, but
  36633. // 'bar' could be the objectName, or part of a nodeName (which can
  36634. // include '.' characters).
  36635. if ( _supportedObjectNames.indexOf( objectName ) !== -1 ) {
  36636. results.nodeName = results.nodeName.substring( 0, lastDot );
  36637. results.objectName = objectName;
  36638. }
  36639. }
  36640. if ( results.propertyName === null || results.propertyName.length === 0 ) {
  36641. throw new Error( 'PropertyBinding: can not parse propertyName from trackName: ' + trackName );
  36642. }
  36643. return results;
  36644. }
  36645. /**
  36646. * Searches for a node in the hierarchy of the given root object by the given
  36647. * node name.
  36648. *
  36649. * @static
  36650. * @param {Object} root - The root object.
  36651. * @param {string|number} nodeName - The name of the node.
  36652. * @return {?Object} The found node. Returns `null` if no object was found.
  36653. */
  36654. static findNode( root, nodeName ) {
  36655. if ( nodeName === undefined || nodeName === '' || nodeName === '.' || nodeName === -1 || nodeName === root.name || nodeName === root.uuid ) {
  36656. return root;
  36657. }
  36658. // search into skeleton bones.
  36659. if ( root.skeleton ) {
  36660. const bone = root.skeleton.getBoneByName( nodeName );
  36661. if ( bone !== undefined ) {
  36662. return bone;
  36663. }
  36664. }
  36665. // search into node subtree.
  36666. if ( root.children ) {
  36667. const searchNodeSubtree = function ( children ) {
  36668. for ( let i = 0; i < children.length; i ++ ) {
  36669. const childNode = children[ i ];
  36670. if ( childNode.name === nodeName || childNode.uuid === nodeName ) {
  36671. return childNode;
  36672. }
  36673. const result = searchNodeSubtree( childNode.children );
  36674. if ( result ) return result;
  36675. }
  36676. return null;
  36677. };
  36678. const subTreeNode = searchNodeSubtree( root.children );
  36679. if ( subTreeNode ) {
  36680. return subTreeNode;
  36681. }
  36682. }
  36683. return null;
  36684. }
  36685. // these are used to "bind" a nonexistent property
  36686. _getValue_unavailable() {}
  36687. _setValue_unavailable() {}
  36688. // Getters
  36689. _getValue_direct( buffer, offset ) {
  36690. buffer[ offset ] = this.targetObject[ this.propertyName ];
  36691. }
  36692. _getValue_array( buffer, offset ) {
  36693. const source = this.resolvedProperty;
  36694. for ( let i = 0, n = source.length; i !== n; ++ i ) {
  36695. buffer[ offset ++ ] = source[ i ];
  36696. }
  36697. }
  36698. _getValue_arrayElement( buffer, offset ) {
  36699. buffer[ offset ] = this.resolvedProperty[ this.propertyIndex ];
  36700. }
  36701. _getValue_toArray( buffer, offset ) {
  36702. this.resolvedProperty.toArray( buffer, offset );
  36703. }
  36704. // Direct
  36705. _setValue_direct( buffer, offset ) {
  36706. this.targetObject[ this.propertyName ] = buffer[ offset ];
  36707. }
  36708. _setValue_direct_setNeedsUpdate( buffer, offset ) {
  36709. this.targetObject[ this.propertyName ] = buffer[ offset ];
  36710. this.targetObject.needsUpdate = true;
  36711. }
  36712. _setValue_direct_setMatrixWorldNeedsUpdate( buffer, offset ) {
  36713. this.targetObject[ this.propertyName ] = buffer[ offset ];
  36714. this.targetObject.matrixWorldNeedsUpdate = true;
  36715. }
  36716. // EntireArray
  36717. _setValue_array( buffer, offset ) {
  36718. const dest = this.resolvedProperty;
  36719. for ( let i = 0, n = dest.length; i !== n; ++ i ) {
  36720. dest[ i ] = buffer[ offset ++ ];
  36721. }
  36722. }
  36723. _setValue_array_setNeedsUpdate( buffer, offset ) {
  36724. const dest = this.resolvedProperty;
  36725. for ( let i = 0, n = dest.length; i !== n; ++ i ) {
  36726. dest[ i ] = buffer[ offset ++ ];
  36727. }
  36728. this.targetObject.needsUpdate = true;
  36729. }
  36730. _setValue_array_setMatrixWorldNeedsUpdate( buffer, offset ) {
  36731. const dest = this.resolvedProperty;
  36732. for ( let i = 0, n = dest.length; i !== n; ++ i ) {
  36733. dest[ i ] = buffer[ offset ++ ];
  36734. }
  36735. this.targetObject.matrixWorldNeedsUpdate = true;
  36736. }
  36737. // ArrayElement
  36738. _setValue_arrayElement( buffer, offset ) {
  36739. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  36740. }
  36741. _setValue_arrayElement_setNeedsUpdate( buffer, offset ) {
  36742. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  36743. this.targetObject.needsUpdate = true;
  36744. }
  36745. _setValue_arrayElement_setMatrixWorldNeedsUpdate( buffer, offset ) {
  36746. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  36747. this.targetObject.matrixWorldNeedsUpdate = true;
  36748. }
  36749. // HasToFromArray
  36750. _setValue_fromArray( buffer, offset ) {
  36751. this.resolvedProperty.fromArray( buffer, offset );
  36752. }
  36753. _setValue_fromArray_setNeedsUpdate( buffer, offset ) {
  36754. this.resolvedProperty.fromArray( buffer, offset );
  36755. this.targetObject.needsUpdate = true;
  36756. }
  36757. _setValue_fromArray_setMatrixWorldNeedsUpdate( buffer, offset ) {
  36758. this.resolvedProperty.fromArray( buffer, offset );
  36759. this.targetObject.matrixWorldNeedsUpdate = true;
  36760. }
  36761. _getValue_unbound( targetArray, offset ) {
  36762. this.bind();
  36763. this.getValue( targetArray, offset );
  36764. }
  36765. _setValue_unbound( sourceArray, offset ) {
  36766. this.bind();
  36767. this.setValue( sourceArray, offset );
  36768. }
  36769. /**
  36770. * Creates a getter / setter pair for the property tracked by this binding.
  36771. */
  36772. bind() {
  36773. let targetObject = this.node;
  36774. const parsedPath = this.parsedPath;
  36775. const objectName = parsedPath.objectName;
  36776. const propertyName = parsedPath.propertyName;
  36777. let propertyIndex = parsedPath.propertyIndex;
  36778. if ( ! targetObject ) {
  36779. targetObject = PropertyBinding.findNode( this.rootNode, parsedPath.nodeName );
  36780. this.node = targetObject;
  36781. }
  36782. // set fail state so we can just 'return' on error
  36783. this.getValue = this._getValue_unavailable;
  36784. this.setValue = this._setValue_unavailable;
  36785. // ensure there is a value node
  36786. if ( ! targetObject ) {
  36787. console.warn( 'THREE.PropertyBinding: No target node found for track: ' + this.path + '.' );
  36788. return;
  36789. }
  36790. if ( objectName ) {
  36791. let objectIndex = parsedPath.objectIndex;
  36792. // special cases were we need to reach deeper into the hierarchy to get the face materials....
  36793. switch ( objectName ) {
  36794. case 'materials':
  36795. if ( ! targetObject.material ) {
  36796. console.error( 'THREE.PropertyBinding: Can not bind to material as node does not have a material.', this );
  36797. return;
  36798. }
  36799. if ( ! targetObject.material.materials ) {
  36800. console.error( 'THREE.PropertyBinding: Can not bind to material.materials as node.material does not have a materials array.', this );
  36801. return;
  36802. }
  36803. targetObject = targetObject.material.materials;
  36804. break;
  36805. case 'bones':
  36806. if ( ! targetObject.skeleton ) {
  36807. console.error( 'THREE.PropertyBinding: Can not bind to bones as node does not have a skeleton.', this );
  36808. return;
  36809. }
  36810. // potential future optimization: skip this if propertyIndex is already an integer
  36811. // and convert the integer string to a true integer.
  36812. targetObject = targetObject.skeleton.bones;
  36813. // support resolving morphTarget names into indices.
  36814. for ( let i = 0; i < targetObject.length; i ++ ) {
  36815. if ( targetObject[ i ].name === objectIndex ) {
  36816. objectIndex = i;
  36817. break;
  36818. }
  36819. }
  36820. break;
  36821. case 'map':
  36822. if ( 'map' in targetObject ) {
  36823. targetObject = targetObject.map;
  36824. break;
  36825. }
  36826. if ( ! targetObject.material ) {
  36827. console.error( 'THREE.PropertyBinding: Can not bind to material as node does not have a material.', this );
  36828. return;
  36829. }
  36830. if ( ! targetObject.material.map ) {
  36831. console.error( 'THREE.PropertyBinding: Can not bind to material.map as node.material does not have a map.', this );
  36832. return;
  36833. }
  36834. targetObject = targetObject.material.map;
  36835. break;
  36836. default:
  36837. if ( targetObject[ objectName ] === undefined ) {
  36838. console.error( 'THREE.PropertyBinding: Can not bind to objectName of node undefined.', this );
  36839. return;
  36840. }
  36841. targetObject = targetObject[ objectName ];
  36842. }
  36843. if ( objectIndex !== undefined ) {
  36844. if ( targetObject[ objectIndex ] === undefined ) {
  36845. console.error( 'THREE.PropertyBinding: Trying to bind to objectIndex of objectName, but is undefined.', this, targetObject );
  36846. return;
  36847. }
  36848. targetObject = targetObject[ objectIndex ];
  36849. }
  36850. }
  36851. // resolve property
  36852. const nodeProperty = targetObject[ propertyName ];
  36853. if ( nodeProperty === undefined ) {
  36854. const nodeName = parsedPath.nodeName;
  36855. console.error( 'THREE.PropertyBinding: Trying to update property for track: ' + nodeName +
  36856. '.' + propertyName + ' but it wasn\'t found.', targetObject );
  36857. return;
  36858. }
  36859. // determine versioning scheme
  36860. let versioning = this.Versioning.None;
  36861. this.targetObject = targetObject;
  36862. if ( targetObject.isMaterial === true ) {
  36863. versioning = this.Versioning.NeedsUpdate;
  36864. } else if ( targetObject.isObject3D === true ) {
  36865. versioning = this.Versioning.MatrixWorldNeedsUpdate;
  36866. }
  36867. // determine how the property gets bound
  36868. let bindingType = this.BindingType.Direct;
  36869. if ( propertyIndex !== undefined ) {
  36870. // access a sub element of the property array (only primitives are supported right now)
  36871. if ( propertyName === 'morphTargetInfluences' ) {
  36872. // potential optimization, skip this if propertyIndex is already an integer, and convert the integer string to a true integer.
  36873. // support resolving morphTarget names into indices.
  36874. if ( ! targetObject.geometry ) {
  36875. console.error( 'THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.', this );
  36876. return;
  36877. }
  36878. if ( ! targetObject.geometry.morphAttributes ) {
  36879. console.error( 'THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.morphAttributes.', this );
  36880. return;
  36881. }
  36882. if ( targetObject.morphTargetDictionary[ propertyIndex ] !== undefined ) {
  36883. propertyIndex = targetObject.morphTargetDictionary[ propertyIndex ];
  36884. }
  36885. }
  36886. bindingType = this.BindingType.ArrayElement;
  36887. this.resolvedProperty = nodeProperty;
  36888. this.propertyIndex = propertyIndex;
  36889. } else if ( nodeProperty.fromArray !== undefined && nodeProperty.toArray !== undefined ) {
  36890. // must use copy for Object3D.Euler/Quaternion
  36891. bindingType = this.BindingType.HasFromToArray;
  36892. this.resolvedProperty = nodeProperty;
  36893. } else if ( Array.isArray( nodeProperty ) ) {
  36894. bindingType = this.BindingType.EntireArray;
  36895. this.resolvedProperty = nodeProperty;
  36896. } else {
  36897. this.propertyName = propertyName;
  36898. }
  36899. // select getter / setter
  36900. this.getValue = this.GetterByBindingType[ bindingType ];
  36901. this.setValue = this.SetterByBindingTypeAndVersioning[ bindingType ][ versioning ];
  36902. }
  36903. /**
  36904. * Unbinds the property.
  36905. */
  36906. unbind() {
  36907. this.node = null;
  36908. // back to the prototype version of getValue / setValue
  36909. // note: avoiding to mutate the shape of 'this' via 'delete'
  36910. this.getValue = this._getValue_unbound;
  36911. this.setValue = this._setValue_unbound;
  36912. }
  36913. }
  36914. PropertyBinding.Composite = Composite;
  36915. PropertyBinding.prototype.BindingType = {
  36916. Direct: 0,
  36917. EntireArray: 1,
  36918. ArrayElement: 2,
  36919. HasFromToArray: 3
  36920. };
  36921. PropertyBinding.prototype.Versioning = {
  36922. None: 0,
  36923. NeedsUpdate: 1,
  36924. MatrixWorldNeedsUpdate: 2
  36925. };
  36926. PropertyBinding.prototype.GetterByBindingType = [
  36927. PropertyBinding.prototype._getValue_direct,
  36928. PropertyBinding.prototype._getValue_array,
  36929. PropertyBinding.prototype._getValue_arrayElement,
  36930. PropertyBinding.prototype._getValue_toArray,
  36931. ];
  36932. PropertyBinding.prototype.SetterByBindingTypeAndVersioning = [
  36933. [
  36934. // Direct
  36935. PropertyBinding.prototype._setValue_direct,
  36936. PropertyBinding.prototype._setValue_direct_setNeedsUpdate,
  36937. PropertyBinding.prototype._setValue_direct_setMatrixWorldNeedsUpdate,
  36938. ], [
  36939. // EntireArray
  36940. PropertyBinding.prototype._setValue_array,
  36941. PropertyBinding.prototype._setValue_array_setNeedsUpdate,
  36942. PropertyBinding.prototype._setValue_array_setMatrixWorldNeedsUpdate,
  36943. ], [
  36944. // ArrayElement
  36945. PropertyBinding.prototype._setValue_arrayElement,
  36946. PropertyBinding.prototype._setValue_arrayElement_setNeedsUpdate,
  36947. PropertyBinding.prototype._setValue_arrayElement_setMatrixWorldNeedsUpdate,
  36948. ], [
  36949. // HasToFromArray
  36950. PropertyBinding.prototype._setValue_fromArray,
  36951. PropertyBinding.prototype._setValue_fromArray_setNeedsUpdate,
  36952. PropertyBinding.prototype._setValue_fromArray_setMatrixWorldNeedsUpdate,
  36953. ]
  36954. ];
  36955. /**
  36956. * A group of objects that receives a shared animation state.
  36957. *
  36958. * Usage:
  36959. *
  36960. * - Add objects you would otherwise pass as 'root' to the
  36961. * constructor or the .clipAction method of AnimationMixer.
  36962. * - Instead pass this object as 'root'.
  36963. * - You can also add and remove objects later when the mixer is running.
  36964. *
  36965. * Note:
  36966. *
  36967. * - Objects of this class appear as one object to the mixer,
  36968. * so cache control of the individual objects must be done on the group.
  36969. *
  36970. * Limitation:
  36971. *
  36972. * - The animated properties must be compatible among the all objects in the group.
  36973. * - A single property can either be controlled through a target group or directly, but not both.
  36974. */
  36975. class AnimationObjectGroup {
  36976. /**
  36977. * Constructs a new animation group.
  36978. *
  36979. * @param {...Object3D} arguments - An arbitrary number of 3D objects that share the same animation state.
  36980. */
  36981. constructor() {
  36982. /**
  36983. * This flag can be used for type testing.
  36984. *
  36985. * @type {boolean}
  36986. * @readonly
  36987. * @default true
  36988. */
  36989. this.isAnimationObjectGroup = true;
  36990. /**
  36991. * The UUID of the 3D object.
  36992. *
  36993. * @type {string}
  36994. * @readonly
  36995. */
  36996. this.uuid = generateUUID();
  36997. // cached objects followed by the active ones
  36998. this._objects = Array.prototype.slice.call( arguments );
  36999. this.nCachedObjects_ = 0; // threshold
  37000. // note: read by PropertyBinding.Composite
  37001. const indices = {};
  37002. this._indicesByUUID = indices; // for bookkeeping
  37003. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  37004. indices[ arguments[ i ].uuid ] = i;
  37005. }
  37006. this._paths = []; // inside: string
  37007. this._parsedPaths = []; // inside: { we don't care, here }
  37008. this._bindings = []; // inside: Array< PropertyBinding >
  37009. this._bindingsIndicesByPath = {}; // inside: indices in these arrays
  37010. const scope = this;
  37011. this.stats = {
  37012. objects: {
  37013. get total() {
  37014. return scope._objects.length;
  37015. },
  37016. get inUse() {
  37017. return this.total - scope.nCachedObjects_;
  37018. }
  37019. },
  37020. get bindingsPerObject() {
  37021. return scope._bindings.length;
  37022. }
  37023. };
  37024. }
  37025. /**
  37026. * Adds an arbitrary number of objects to this animation group.
  37027. *
  37028. * @param {...Object3D} arguments - The 3D objects to add.
  37029. */
  37030. add() {
  37031. const objects = this._objects,
  37032. indicesByUUID = this._indicesByUUID,
  37033. paths = this._paths,
  37034. parsedPaths = this._parsedPaths,
  37035. bindings = this._bindings,
  37036. nBindings = bindings.length;
  37037. let knownObject = undefined,
  37038. nObjects = objects.length,
  37039. nCachedObjects = this.nCachedObjects_;
  37040. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  37041. const object = arguments[ i ],
  37042. uuid = object.uuid;
  37043. let index = indicesByUUID[ uuid ];
  37044. if ( index === undefined ) {
  37045. // unknown object -> add it to the ACTIVE region
  37046. index = nObjects ++;
  37047. indicesByUUID[ uuid ] = index;
  37048. objects.push( object );
  37049. // accounting is done, now do the same for all bindings
  37050. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  37051. bindings[ j ].push( new PropertyBinding( object, paths[ j ], parsedPaths[ j ] ) );
  37052. }
  37053. } else if ( index < nCachedObjects ) {
  37054. knownObject = objects[ index ];
  37055. // move existing object to the ACTIVE region
  37056. const firstActiveIndex = -- nCachedObjects,
  37057. lastCachedObject = objects[ firstActiveIndex ];
  37058. indicesByUUID[ lastCachedObject.uuid ] = index;
  37059. objects[ index ] = lastCachedObject;
  37060. indicesByUUID[ uuid ] = firstActiveIndex;
  37061. objects[ firstActiveIndex ] = object;
  37062. // accounting is done, now do the same for all bindings
  37063. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  37064. const bindingsForPath = bindings[ j ],
  37065. lastCached = bindingsForPath[ firstActiveIndex ];
  37066. let binding = bindingsForPath[ index ];
  37067. bindingsForPath[ index ] = lastCached;
  37068. if ( binding === undefined ) {
  37069. // since we do not bother to create new bindings
  37070. // for objects that are cached, the binding may
  37071. // or may not exist
  37072. binding = new PropertyBinding( object, paths[ j ], parsedPaths[ j ] );
  37073. }
  37074. bindingsForPath[ firstActiveIndex ] = binding;
  37075. }
  37076. } else if ( objects[ index ] !== knownObject ) {
  37077. console.error( 'THREE.AnimationObjectGroup: Different objects with the same UUID ' +
  37078. 'detected. Clean the caches or recreate your infrastructure when reloading scenes.' );
  37079. } // else the object is already where we want it to be
  37080. } // for arguments
  37081. this.nCachedObjects_ = nCachedObjects;
  37082. }
  37083. /**
  37084. * Removes an arbitrary number of objects to this animation group
  37085. *
  37086. * @param {...Object3D} arguments - The 3D objects to remove.
  37087. */
  37088. remove() {
  37089. const objects = this._objects,
  37090. indicesByUUID = this._indicesByUUID,
  37091. bindings = this._bindings,
  37092. nBindings = bindings.length;
  37093. let nCachedObjects = this.nCachedObjects_;
  37094. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  37095. const object = arguments[ i ],
  37096. uuid = object.uuid,
  37097. index = indicesByUUID[ uuid ];
  37098. if ( index !== undefined && index >= nCachedObjects ) {
  37099. // move existing object into the CACHED region
  37100. const lastCachedIndex = nCachedObjects ++,
  37101. firstActiveObject = objects[ lastCachedIndex ];
  37102. indicesByUUID[ firstActiveObject.uuid ] = index;
  37103. objects[ index ] = firstActiveObject;
  37104. indicesByUUID[ uuid ] = lastCachedIndex;
  37105. objects[ lastCachedIndex ] = object;
  37106. // accounting is done, now do the same for all bindings
  37107. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  37108. const bindingsForPath = bindings[ j ],
  37109. firstActive = bindingsForPath[ lastCachedIndex ],
  37110. binding = bindingsForPath[ index ];
  37111. bindingsForPath[ index ] = firstActive;
  37112. bindingsForPath[ lastCachedIndex ] = binding;
  37113. }
  37114. }
  37115. } // for arguments
  37116. this.nCachedObjects_ = nCachedObjects;
  37117. }
  37118. /**
  37119. * Deallocates all memory resources for the passed 3D objects of this animation group.
  37120. *
  37121. * @param {...Object3D} arguments - The 3D objects to uncache.
  37122. */
  37123. uncache() {
  37124. const objects = this._objects,
  37125. indicesByUUID = this._indicesByUUID,
  37126. bindings = this._bindings,
  37127. nBindings = bindings.length;
  37128. let nCachedObjects = this.nCachedObjects_,
  37129. nObjects = objects.length;
  37130. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  37131. const object = arguments[ i ],
  37132. uuid = object.uuid,
  37133. index = indicesByUUID[ uuid ];
  37134. if ( index !== undefined ) {
  37135. delete indicesByUUID[ uuid ];
  37136. if ( index < nCachedObjects ) {
  37137. // object is cached, shrink the CACHED region
  37138. const firstActiveIndex = -- nCachedObjects,
  37139. lastCachedObject = objects[ firstActiveIndex ],
  37140. lastIndex = -- nObjects,
  37141. lastObject = objects[ lastIndex ];
  37142. // last cached object takes this object's place
  37143. indicesByUUID[ lastCachedObject.uuid ] = index;
  37144. objects[ index ] = lastCachedObject;
  37145. // last object goes to the activated slot and pop
  37146. indicesByUUID[ lastObject.uuid ] = firstActiveIndex;
  37147. objects[ firstActiveIndex ] = lastObject;
  37148. objects.pop();
  37149. // accounting is done, now do the same for all bindings
  37150. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  37151. const bindingsForPath = bindings[ j ],
  37152. lastCached = bindingsForPath[ firstActiveIndex ],
  37153. last = bindingsForPath[ lastIndex ];
  37154. bindingsForPath[ index ] = lastCached;
  37155. bindingsForPath[ firstActiveIndex ] = last;
  37156. bindingsForPath.pop();
  37157. }
  37158. } else {
  37159. // object is active, just swap with the last and pop
  37160. const lastIndex = -- nObjects,
  37161. lastObject = objects[ lastIndex ];
  37162. if ( lastIndex > 0 ) {
  37163. indicesByUUID[ lastObject.uuid ] = index;
  37164. }
  37165. objects[ index ] = lastObject;
  37166. objects.pop();
  37167. // accounting is done, now do the same for all bindings
  37168. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  37169. const bindingsForPath = bindings[ j ];
  37170. bindingsForPath[ index ] = bindingsForPath[ lastIndex ];
  37171. bindingsForPath.pop();
  37172. }
  37173. } // cached or active
  37174. } // if object is known
  37175. } // for arguments
  37176. this.nCachedObjects_ = nCachedObjects;
  37177. }
  37178. // Internal interface used by befriended PropertyBinding.Composite:
  37179. subscribe_( path, parsedPath ) {
  37180. // returns an array of bindings for the given path that is changed
  37181. // according to the contained objects in the group
  37182. const indicesByPath = this._bindingsIndicesByPath;
  37183. let index = indicesByPath[ path ];
  37184. const bindings = this._bindings;
  37185. if ( index !== undefined ) return bindings[ index ];
  37186. const paths = this._paths,
  37187. parsedPaths = this._parsedPaths,
  37188. objects = this._objects,
  37189. nObjects = objects.length,
  37190. nCachedObjects = this.nCachedObjects_,
  37191. bindingsForPath = new Array( nObjects );
  37192. index = bindings.length;
  37193. indicesByPath[ path ] = index;
  37194. paths.push( path );
  37195. parsedPaths.push( parsedPath );
  37196. bindings.push( bindingsForPath );
  37197. for ( let i = nCachedObjects, n = objects.length; i !== n; ++ i ) {
  37198. const object = objects[ i ];
  37199. bindingsForPath[ i ] = new PropertyBinding( object, path, parsedPath );
  37200. }
  37201. return bindingsForPath;
  37202. }
  37203. unsubscribe_( path ) {
  37204. // tells the group to forget about a property path and no longer
  37205. // update the array previously obtained with 'subscribe_'
  37206. const indicesByPath = this._bindingsIndicesByPath,
  37207. index = indicesByPath[ path ];
  37208. if ( index !== undefined ) {
  37209. const paths = this._paths,
  37210. parsedPaths = this._parsedPaths,
  37211. bindings = this._bindings,
  37212. lastBindingsIndex = bindings.length - 1,
  37213. lastBindings = bindings[ lastBindingsIndex ],
  37214. lastBindingsPath = path[ lastBindingsIndex ];
  37215. indicesByPath[ lastBindingsPath ] = index;
  37216. bindings[ index ] = lastBindings;
  37217. bindings.pop();
  37218. parsedPaths[ index ] = parsedPaths[ lastBindingsIndex ];
  37219. parsedPaths.pop();
  37220. paths[ index ] = paths[ lastBindingsIndex ];
  37221. paths.pop();
  37222. }
  37223. }
  37224. }
  37225. /**
  37226. * An instance of `AnimationAction` schedules the playback of an animation which is
  37227. * stored in {@link AnimationClip}.
  37228. */
  37229. class AnimationAction {
  37230. /**
  37231. * Constructs a new animation action.
  37232. *
  37233. * @param {AnimationMixer} mixer - The mixer that is controlled by this action.
  37234. * @param {AnimationClip} clip - The animation clip that holds the actual keyframes.
  37235. * @param {?Object3D} [localRoot=null] - The root object on which this action is performed.
  37236. * @param {(NormalAnimationBlendMode|AdditiveAnimationBlendMode)} [blendMode] - The blend mode.
  37237. */
  37238. constructor( mixer, clip, localRoot = null, blendMode = clip.blendMode ) {
  37239. this._mixer = mixer;
  37240. this._clip = clip;
  37241. this._localRoot = localRoot;
  37242. /**
  37243. * Defines how the animation is blended/combined when two or more animations
  37244. * are simultaneously played.
  37245. *
  37246. * @type {(NormalAnimationBlendMode|AdditiveAnimationBlendMode)}
  37247. */
  37248. this.blendMode = blendMode;
  37249. const tracks = clip.tracks,
  37250. nTracks = tracks.length,
  37251. interpolants = new Array( nTracks );
  37252. const interpolantSettings = {
  37253. endingStart: ZeroCurvatureEnding,
  37254. endingEnd: ZeroCurvatureEnding
  37255. };
  37256. for ( let i = 0; i !== nTracks; ++ i ) {
  37257. const interpolant = tracks[ i ].createInterpolant( null );
  37258. interpolants[ i ] = interpolant;
  37259. interpolant.settings = interpolantSettings;
  37260. }
  37261. this._interpolantSettings = interpolantSettings;
  37262. this._interpolants = interpolants; // bound by the mixer
  37263. // inside: PropertyMixer (managed by the mixer)
  37264. this._propertyBindings = new Array( nTracks );
  37265. this._cacheIndex = null; // for the memory manager
  37266. this._byClipCacheIndex = null; // for the memory manager
  37267. this._timeScaleInterpolant = null;
  37268. this._weightInterpolant = null;
  37269. /**
  37270. * The loop mode, set via {@link AnimationAction#setLoop}.
  37271. *
  37272. * @type {(LoopRepeat|LoopOnce|LoopPingPong)}
  37273. * @default LoopRepeat
  37274. */
  37275. this.loop = LoopRepeat;
  37276. this._loopCount = -1;
  37277. // global mixer time when the action is to be started
  37278. // it's set back to 'null' upon start of the action
  37279. this._startTime = null;
  37280. /**
  37281. * The local time of this action (in seconds, starting with `0`).
  37282. *
  37283. * The value gets clamped or wrapped to `[0,clip.duration]` (according to the
  37284. * loop state).
  37285. *
  37286. * @type {number}
  37287. * @default Infinity
  37288. */
  37289. this.time = 0;
  37290. /**
  37291. * Scaling factor for the {@link AnimationAction#time}. A value of `0` causes the
  37292. * animation to pause. Negative values cause the animation to play backwards.
  37293. *
  37294. * @type {number}
  37295. * @default 1
  37296. */
  37297. this.timeScale = 1;
  37298. this._effectiveTimeScale = 1;
  37299. /**
  37300. * The degree of influence of this action (in the interval `[0, 1]`). Values
  37301. * between `0` (no impact) and `1` (full impact) can be used to blend between
  37302. * several actions.
  37303. *
  37304. * @type {number}
  37305. * @default 1
  37306. */
  37307. this.weight = 1;
  37308. this._effectiveWeight = 1;
  37309. /**
  37310. * The number of repetitions of the performed clip over the course of this action.
  37311. * Can be set via {@link AnimationAction#setLoop}.
  37312. *
  37313. * Setting this number has no effect if {@link AnimationAction#loop} is set to
  37314. * `THREE:LoopOnce`.
  37315. *
  37316. * @type {number}
  37317. * @default Infinity
  37318. */
  37319. this.repetitions = Infinity;
  37320. /**
  37321. * If set to `true`, the playback of the action is paused.
  37322. *
  37323. * @type {boolean}
  37324. * @default false
  37325. */
  37326. this.paused = false;
  37327. /**
  37328. * If set to `false`, the action is disabled so it has no impact.
  37329. *
  37330. * When the action is re-enabled, the animation continues from its current
  37331. * time (setting `enabled` to `false` doesn't reset the action).
  37332. *
  37333. * @type {boolean}
  37334. * @default true
  37335. */
  37336. this.enabled = true;
  37337. /**
  37338. * If set to true the animation will automatically be paused on its last frame.
  37339. *
  37340. * If set to false, {@link AnimationAction#enabled} will automatically be switched
  37341. * to `false` when the last loop of the action has finished, so that this action has
  37342. * no further impact.
  37343. *
  37344. * Note: This member has no impact if the action is interrupted (it
  37345. * has only an effect if its last loop has really finished).
  37346. *
  37347. * @type {boolean}
  37348. * @default false
  37349. */
  37350. this.clampWhenFinished = false;
  37351. /**
  37352. * Enables smooth interpolation without separate clips for start, loop and end.
  37353. *
  37354. * @type {boolean}
  37355. * @default true
  37356. */
  37357. this.zeroSlopeAtStart = true;
  37358. /**
  37359. * Enables smooth interpolation without separate clips for start, loop and end.
  37360. *
  37361. * @type {boolean}
  37362. * @default true
  37363. */
  37364. this.zeroSlopeAtEnd = true;
  37365. }
  37366. /**
  37367. * Starts the playback of the animation.
  37368. *
  37369. * @return {AnimationAction} A reference to this animation action.
  37370. */
  37371. play() {
  37372. this._mixer._activateAction( this );
  37373. return this;
  37374. }
  37375. /**
  37376. * Stops the playback of the animation.
  37377. *
  37378. * @return {AnimationAction} A reference to this animation action.
  37379. */
  37380. stop() {
  37381. this._mixer._deactivateAction( this );
  37382. return this.reset();
  37383. }
  37384. /**
  37385. * Resets the playback of the animation.
  37386. *
  37387. * @return {AnimationAction} A reference to this animation action.
  37388. */
  37389. reset() {
  37390. this.paused = false;
  37391. this.enabled = true;
  37392. this.time = 0; // restart clip
  37393. this._loopCount = -1;// forget previous loops
  37394. this._startTime = null;// forget scheduling
  37395. return this.stopFading().stopWarping();
  37396. }
  37397. /**
  37398. * Returns `true` if the animation is running.
  37399. *
  37400. * @return {boolean} Whether the animation is running or not.
  37401. */
  37402. isRunning() {
  37403. return this.enabled && ! this.paused && this.timeScale !== 0 &&
  37404. this._startTime === null && this._mixer._isActiveAction( this );
  37405. }
  37406. /**
  37407. * Returns `true` when {@link AnimationAction#play} has been called.
  37408. *
  37409. * @return {boolean} Whether the animation is scheduled or not.
  37410. */
  37411. isScheduled() {
  37412. return this._mixer._isActiveAction( this );
  37413. }
  37414. /**
  37415. * Defines the time when the animation should start.
  37416. *
  37417. * @param {number} time - The start time in seconds.
  37418. * @return {AnimationAction} A reference to this animation action.
  37419. */
  37420. startAt( time ) {
  37421. this._startTime = time;
  37422. return this;
  37423. }
  37424. /**
  37425. * Configures the loop settings for this action.
  37426. *
  37427. * @param {(LoopRepeat|LoopOnce|LoopPingPong)} mode - The loop mode.
  37428. * @param {number} repetitions - The number of repetitions.
  37429. * @return {AnimationAction} A reference to this animation action.
  37430. */
  37431. setLoop( mode, repetitions ) {
  37432. this.loop = mode;
  37433. this.repetitions = repetitions;
  37434. return this;
  37435. }
  37436. /**
  37437. * Sets the effective weight of this action.
  37438. *
  37439. * An action has no effect and thus an effective weight of zero when the
  37440. * action is disabled.
  37441. *
  37442. * @param {number} weight - The weight to set.
  37443. * @return {AnimationAction} A reference to this animation action.
  37444. */
  37445. setEffectiveWeight( weight ) {
  37446. this.weight = weight;
  37447. // note: same logic as when updated at runtime
  37448. this._effectiveWeight = this.enabled ? weight : 0;
  37449. return this.stopFading();
  37450. }
  37451. /**
  37452. * Returns the effective weight of this action.
  37453. *
  37454. * @return {number} The effective weight.
  37455. */
  37456. getEffectiveWeight() {
  37457. return this._effectiveWeight;
  37458. }
  37459. /**
  37460. * Fades the animation in by increasing its weight gradually from `0` to `1`,
  37461. * within the passed time interval.
  37462. *
  37463. * @param {number} duration - The duration of the fade.
  37464. * @return {AnimationAction} A reference to this animation action.
  37465. */
  37466. fadeIn( duration ) {
  37467. return this._scheduleFading( duration, 0, 1 );
  37468. }
  37469. /**
  37470. * Fades the animation out by decreasing its weight gradually from `1` to `0`,
  37471. * within the passed time interval.
  37472. *
  37473. * @param {number} duration - The duration of the fade.
  37474. * @return {AnimationAction} A reference to this animation action.
  37475. */
  37476. fadeOut( duration ) {
  37477. return this._scheduleFading( duration, 1, 0 );
  37478. }
  37479. /**
  37480. * Causes this action to fade in and the given action to fade out,
  37481. * within the passed time interval.
  37482. *
  37483. * @param {AnimationAction} fadeOutAction - The animation action to fade out.
  37484. * @param {number} duration - The duration of the fade.
  37485. * @param {boolean} [warp=false] - Whether warping should be used or not.
  37486. * @return {AnimationAction} A reference to this animation action.
  37487. */
  37488. crossFadeFrom( fadeOutAction, duration, warp = false ) {
  37489. fadeOutAction.fadeOut( duration );
  37490. this.fadeIn( duration );
  37491. if ( warp === true ) {
  37492. const fadeInDuration = this._clip.duration,
  37493. fadeOutDuration = fadeOutAction._clip.duration,
  37494. startEndRatio = fadeOutDuration / fadeInDuration,
  37495. endStartRatio = fadeInDuration / fadeOutDuration;
  37496. fadeOutAction.warp( 1.0, startEndRatio, duration );
  37497. this.warp( endStartRatio, 1.0, duration );
  37498. }
  37499. return this;
  37500. }
  37501. /**
  37502. * Causes this action to fade out and the given action to fade in,
  37503. * within the passed time interval.
  37504. *
  37505. * @param {AnimationAction} fadeInAction - The animation action to fade in.
  37506. * @param {number} duration - The duration of the fade.
  37507. * @param {boolean} [warp=false] - Whether warping should be used or not.
  37508. * @return {AnimationAction} A reference to this animation action.
  37509. */
  37510. crossFadeTo( fadeInAction, duration, warp = false ) {
  37511. return fadeInAction.crossFadeFrom( this, duration, warp );
  37512. }
  37513. /**
  37514. * Stops any fading which is applied to this action.
  37515. *
  37516. * @return {AnimationAction} A reference to this animation action.
  37517. */
  37518. stopFading() {
  37519. const weightInterpolant = this._weightInterpolant;
  37520. if ( weightInterpolant !== null ) {
  37521. this._weightInterpolant = null;
  37522. this._mixer._takeBackControlInterpolant( weightInterpolant );
  37523. }
  37524. return this;
  37525. }
  37526. /**
  37527. * Sets the effective time scale of this action.
  37528. *
  37529. * An action has no effect and thus an effective time scale of zero when the
  37530. * action is paused.
  37531. *
  37532. * @param {number} timeScale - The time scale to set.
  37533. * @return {AnimationAction} A reference to this animation action.
  37534. */
  37535. setEffectiveTimeScale( timeScale ) {
  37536. this.timeScale = timeScale;
  37537. this._effectiveTimeScale = this.paused ? 0 : timeScale;
  37538. return this.stopWarping();
  37539. }
  37540. /**
  37541. * Returns the effective time scale of this action.
  37542. *
  37543. * @return {number} The effective time scale.
  37544. */
  37545. getEffectiveTimeScale() {
  37546. return this._effectiveTimeScale;
  37547. }
  37548. /**
  37549. * Sets the duration for a single loop of this action.
  37550. *
  37551. * @param {number} duration - The duration to set.
  37552. * @return {AnimationAction} A reference to this animation action.
  37553. */
  37554. setDuration( duration ) {
  37555. this.timeScale = this._clip.duration / duration;
  37556. return this.stopWarping();
  37557. }
  37558. /**
  37559. * Synchronizes this action with the passed other action.
  37560. *
  37561. * @param {AnimationAction} action - The action to sync with.
  37562. * @return {AnimationAction} A reference to this animation action.
  37563. */
  37564. syncWith( action ) {
  37565. this.time = action.time;
  37566. this.timeScale = action.timeScale;
  37567. return this.stopWarping();
  37568. }
  37569. /**
  37570. * Decelerates this animation's speed to `0` within the passed time interval.
  37571. *
  37572. * @param {number} duration - The duration.
  37573. * @return {AnimationAction} A reference to this animation action.
  37574. */
  37575. halt( duration ) {
  37576. return this.warp( this._effectiveTimeScale, 0, duration );
  37577. }
  37578. /**
  37579. * Changes the playback speed, within the passed time interval, by modifying
  37580. * {@link AnimationAction#timeScale} gradually from `startTimeScale` to
  37581. * `endTimeScale`.
  37582. *
  37583. * @param {number} startTimeScale - The start time scale.
  37584. * @param {number} endTimeScale - The end time scale.
  37585. * @param {number} duration - The duration.
  37586. * @return {AnimationAction} A reference to this animation action.
  37587. */
  37588. warp( startTimeScale, endTimeScale, duration ) {
  37589. const mixer = this._mixer,
  37590. now = mixer.time,
  37591. timeScale = this.timeScale;
  37592. let interpolant = this._timeScaleInterpolant;
  37593. if ( interpolant === null ) {
  37594. interpolant = mixer._lendControlInterpolant();
  37595. this._timeScaleInterpolant = interpolant;
  37596. }
  37597. const times = interpolant.parameterPositions,
  37598. values = interpolant.sampleValues;
  37599. times[ 0 ] = now;
  37600. times[ 1 ] = now + duration;
  37601. values[ 0 ] = startTimeScale / timeScale;
  37602. values[ 1 ] = endTimeScale / timeScale;
  37603. return this;
  37604. }
  37605. /**
  37606. * Stops any scheduled warping which is applied to this action.
  37607. *
  37608. * @return {AnimationAction} A reference to this animation action.
  37609. */
  37610. stopWarping() {
  37611. const timeScaleInterpolant = this._timeScaleInterpolant;
  37612. if ( timeScaleInterpolant !== null ) {
  37613. this._timeScaleInterpolant = null;
  37614. this._mixer._takeBackControlInterpolant( timeScaleInterpolant );
  37615. }
  37616. return this;
  37617. }
  37618. /**
  37619. * Returns the animation mixer of this animation action.
  37620. *
  37621. * @return {AnimationMixer} The animation mixer.
  37622. */
  37623. getMixer() {
  37624. return this._mixer;
  37625. }
  37626. /**
  37627. * Returns the animation clip of this animation action.
  37628. *
  37629. * @return {AnimationClip} The animation clip.
  37630. */
  37631. getClip() {
  37632. return this._clip;
  37633. }
  37634. /**
  37635. * Returns the root object of this animation action.
  37636. *
  37637. * @return {Object3D} The root object.
  37638. */
  37639. getRoot() {
  37640. return this._localRoot || this._mixer._root;
  37641. }
  37642. // Interna
  37643. _update( time, deltaTime, timeDirection, accuIndex ) {
  37644. // called by the mixer
  37645. if ( ! this.enabled ) {
  37646. // call ._updateWeight() to update ._effectiveWeight
  37647. this._updateWeight( time );
  37648. return;
  37649. }
  37650. const startTime = this._startTime;
  37651. if ( startTime !== null ) {
  37652. // check for scheduled start of action
  37653. const timeRunning = ( time - startTime ) * timeDirection;
  37654. if ( timeRunning < 0 || timeDirection === 0 ) {
  37655. deltaTime = 0;
  37656. } else {
  37657. this._startTime = null; // unschedule
  37658. deltaTime = timeDirection * timeRunning;
  37659. }
  37660. }
  37661. // apply time scale and advance time
  37662. deltaTime *= this._updateTimeScale( time );
  37663. const clipTime = this._updateTime( deltaTime );
  37664. // note: _updateTime may disable the action resulting in
  37665. // an effective weight of 0
  37666. const weight = this._updateWeight( time );
  37667. if ( weight > 0 ) {
  37668. const interpolants = this._interpolants;
  37669. const propertyMixers = this._propertyBindings;
  37670. switch ( this.blendMode ) {
  37671. case AdditiveAnimationBlendMode:
  37672. for ( let j = 0, m = interpolants.length; j !== m; ++ j ) {
  37673. interpolants[ j ].evaluate( clipTime );
  37674. propertyMixers[ j ].accumulateAdditive( weight );
  37675. }
  37676. break;
  37677. case NormalAnimationBlendMode:
  37678. default:
  37679. for ( let j = 0, m = interpolants.length; j !== m; ++ j ) {
  37680. interpolants[ j ].evaluate( clipTime );
  37681. propertyMixers[ j ].accumulate( accuIndex, weight );
  37682. }
  37683. }
  37684. }
  37685. }
  37686. _updateWeight( time ) {
  37687. let weight = 0;
  37688. if ( this.enabled ) {
  37689. weight = this.weight;
  37690. const interpolant = this._weightInterpolant;
  37691. if ( interpolant !== null ) {
  37692. const interpolantValue = interpolant.evaluate( time )[ 0 ];
  37693. weight *= interpolantValue;
  37694. if ( time > interpolant.parameterPositions[ 1 ] ) {
  37695. this.stopFading();
  37696. if ( interpolantValue === 0 ) {
  37697. // faded out, disable
  37698. this.enabled = false;
  37699. }
  37700. }
  37701. }
  37702. }
  37703. this._effectiveWeight = weight;
  37704. return weight;
  37705. }
  37706. _updateTimeScale( time ) {
  37707. let timeScale = 0;
  37708. if ( ! this.paused ) {
  37709. timeScale = this.timeScale;
  37710. const interpolant = this._timeScaleInterpolant;
  37711. if ( interpolant !== null ) {
  37712. const interpolantValue = interpolant.evaluate( time )[ 0 ];
  37713. timeScale *= interpolantValue;
  37714. if ( time > interpolant.parameterPositions[ 1 ] ) {
  37715. this.stopWarping();
  37716. if ( timeScale === 0 ) {
  37717. // motion has halted, pause
  37718. this.paused = true;
  37719. } else {
  37720. // warp done - apply final time scale
  37721. this.timeScale = timeScale;
  37722. }
  37723. }
  37724. }
  37725. }
  37726. this._effectiveTimeScale = timeScale;
  37727. return timeScale;
  37728. }
  37729. _updateTime( deltaTime ) {
  37730. const duration = this._clip.duration;
  37731. const loop = this.loop;
  37732. let time = this.time + deltaTime;
  37733. let loopCount = this._loopCount;
  37734. const pingPong = ( loop === LoopPingPong );
  37735. if ( deltaTime === 0 ) {
  37736. if ( loopCount === -1 ) return time;
  37737. return ( pingPong && ( loopCount & 1 ) === 1 ) ? duration - time : time;
  37738. }
  37739. if ( loop === LoopOnce ) {
  37740. if ( loopCount === -1 ) {
  37741. // just started
  37742. this._loopCount = 0;
  37743. this._setEndings( true, true, false );
  37744. }
  37745. handle_stop: {
  37746. if ( time >= duration ) {
  37747. time = duration;
  37748. } else if ( time < 0 ) {
  37749. time = 0;
  37750. } else {
  37751. this.time = time;
  37752. break handle_stop;
  37753. }
  37754. if ( this.clampWhenFinished ) this.paused = true;
  37755. else this.enabled = false;
  37756. this.time = time;
  37757. this._mixer.dispatchEvent( {
  37758. type: 'finished', action: this,
  37759. direction: deltaTime < 0 ? -1 : 1
  37760. } );
  37761. }
  37762. } else { // repetitive Repeat or PingPong
  37763. if ( loopCount === -1 ) {
  37764. // just started
  37765. if ( deltaTime >= 0 ) {
  37766. loopCount = 0;
  37767. this._setEndings( true, this.repetitions === 0, pingPong );
  37768. } else {
  37769. // when looping in reverse direction, the initial
  37770. // transition through zero counts as a repetition,
  37771. // so leave loopCount at -1
  37772. this._setEndings( this.repetitions === 0, true, pingPong );
  37773. }
  37774. }
  37775. if ( time >= duration || time < 0 ) {
  37776. // wrap around
  37777. const loopDelta = Math.floor( time / duration ); // signed
  37778. time -= duration * loopDelta;
  37779. loopCount += Math.abs( loopDelta );
  37780. const pending = this.repetitions - loopCount;
  37781. if ( pending <= 0 ) {
  37782. // have to stop (switch state, clamp time, fire event)
  37783. if ( this.clampWhenFinished ) this.paused = true;
  37784. else this.enabled = false;
  37785. time = deltaTime > 0 ? duration : 0;
  37786. this.time = time;
  37787. this._mixer.dispatchEvent( {
  37788. type: 'finished', action: this,
  37789. direction: deltaTime > 0 ? 1 : -1
  37790. } );
  37791. } else {
  37792. // keep running
  37793. if ( pending === 1 ) {
  37794. // entering the last round
  37795. const atStart = deltaTime < 0;
  37796. this._setEndings( atStart, ! atStart, pingPong );
  37797. } else {
  37798. this._setEndings( false, false, pingPong );
  37799. }
  37800. this._loopCount = loopCount;
  37801. this.time = time;
  37802. this._mixer.dispatchEvent( {
  37803. type: 'loop', action: this, loopDelta: loopDelta
  37804. } );
  37805. }
  37806. } else {
  37807. this.time = time;
  37808. }
  37809. if ( pingPong && ( loopCount & 1 ) === 1 ) {
  37810. // invert time for the "pong round"
  37811. return duration - time;
  37812. }
  37813. }
  37814. return time;
  37815. }
  37816. _setEndings( atStart, atEnd, pingPong ) {
  37817. const settings = this._interpolantSettings;
  37818. if ( pingPong ) {
  37819. settings.endingStart = ZeroSlopeEnding;
  37820. settings.endingEnd = ZeroSlopeEnding;
  37821. } else {
  37822. // assuming for LoopOnce atStart == atEnd == true
  37823. if ( atStart ) {
  37824. settings.endingStart = this.zeroSlopeAtStart ? ZeroSlopeEnding : ZeroCurvatureEnding;
  37825. } else {
  37826. settings.endingStart = WrapAroundEnding;
  37827. }
  37828. if ( atEnd ) {
  37829. settings.endingEnd = this.zeroSlopeAtEnd ? ZeroSlopeEnding : ZeroCurvatureEnding;
  37830. } else {
  37831. settings.endingEnd = WrapAroundEnding;
  37832. }
  37833. }
  37834. }
  37835. _scheduleFading( duration, weightNow, weightThen ) {
  37836. const mixer = this._mixer, now = mixer.time;
  37837. let interpolant = this._weightInterpolant;
  37838. if ( interpolant === null ) {
  37839. interpolant = mixer._lendControlInterpolant();
  37840. this._weightInterpolant = interpolant;
  37841. }
  37842. const times = interpolant.parameterPositions,
  37843. values = interpolant.sampleValues;
  37844. times[ 0 ] = now;
  37845. values[ 0 ] = weightNow;
  37846. times[ 1 ] = now + duration;
  37847. values[ 1 ] = weightThen;
  37848. return this;
  37849. }
  37850. }
  37851. const _controlInterpolantsResultBuffer = new Float32Array( 1 );
  37852. /**
  37853. * `AnimationMixer` is a player for animations on a particular object in
  37854. * the scene. When multiple objects in the scene are animated independently,
  37855. * one `AnimationMixer` may be used for each object.
  37856. */
  37857. class AnimationMixer extends EventDispatcher {
  37858. /**
  37859. * Constructs a new animation mixer.
  37860. *
  37861. * @param {Object3D} root - The object whose animations shall be played by this mixer.
  37862. */
  37863. constructor( root ) {
  37864. super();
  37865. this._root = root;
  37866. this._initMemoryManager();
  37867. this._accuIndex = 0;
  37868. /**
  37869. * The global mixer time (in seconds; starting with `0` on the mixer's creation).
  37870. *
  37871. * @type {number}
  37872. * @default 0
  37873. */
  37874. this.time = 0;
  37875. /**
  37876. * A scaling factor for the global time.
  37877. *
  37878. * Note: Setting this member to `0` and later back to `1` is a
  37879. * possibility to pause/unpause all actions that are controlled by this
  37880. * mixer.
  37881. *
  37882. * @type {number}
  37883. * @default 1
  37884. */
  37885. this.timeScale = 1.0;
  37886. }
  37887. _bindAction( action, prototypeAction ) {
  37888. const root = action._localRoot || this._root,
  37889. tracks = action._clip.tracks,
  37890. nTracks = tracks.length,
  37891. bindings = action._propertyBindings,
  37892. interpolants = action._interpolants,
  37893. rootUuid = root.uuid,
  37894. bindingsByRoot = this._bindingsByRootAndName;
  37895. let bindingsByName = bindingsByRoot[ rootUuid ];
  37896. if ( bindingsByName === undefined ) {
  37897. bindingsByName = {};
  37898. bindingsByRoot[ rootUuid ] = bindingsByName;
  37899. }
  37900. for ( let i = 0; i !== nTracks; ++ i ) {
  37901. const track = tracks[ i ],
  37902. trackName = track.name;
  37903. let binding = bindingsByName[ trackName ];
  37904. if ( binding !== undefined ) {
  37905. ++ binding.referenceCount;
  37906. bindings[ i ] = binding;
  37907. } else {
  37908. binding = bindings[ i ];
  37909. if ( binding !== undefined ) {
  37910. // existing binding, make sure the cache knows
  37911. if ( binding._cacheIndex === null ) {
  37912. ++ binding.referenceCount;
  37913. this._addInactiveBinding( binding, rootUuid, trackName );
  37914. }
  37915. continue;
  37916. }
  37917. const path = prototypeAction && prototypeAction.
  37918. _propertyBindings[ i ].binding.parsedPath;
  37919. binding = new PropertyMixer(
  37920. PropertyBinding.create( root, trackName, path ),
  37921. track.ValueTypeName, track.getValueSize() );
  37922. ++ binding.referenceCount;
  37923. this._addInactiveBinding( binding, rootUuid, trackName );
  37924. bindings[ i ] = binding;
  37925. }
  37926. interpolants[ i ].resultBuffer = binding.buffer;
  37927. }
  37928. }
  37929. _activateAction( action ) {
  37930. if ( ! this._isActiveAction( action ) ) {
  37931. if ( action._cacheIndex === null ) {
  37932. // this action has been forgotten by the cache, but the user
  37933. // appears to be still using it -> rebind
  37934. const rootUuid = ( action._localRoot || this._root ).uuid,
  37935. clipUuid = action._clip.uuid,
  37936. actionsForClip = this._actionsByClip[ clipUuid ];
  37937. this._bindAction( action,
  37938. actionsForClip && actionsForClip.knownActions[ 0 ] );
  37939. this._addInactiveAction( action, clipUuid, rootUuid );
  37940. }
  37941. const bindings = action._propertyBindings;
  37942. // increment reference counts / sort out state
  37943. for ( let i = 0, n = bindings.length; i !== n; ++ i ) {
  37944. const binding = bindings[ i ];
  37945. if ( binding.useCount ++ === 0 ) {
  37946. this._lendBinding( binding );
  37947. binding.saveOriginalState();
  37948. }
  37949. }
  37950. this._lendAction( action );
  37951. }
  37952. }
  37953. _deactivateAction( action ) {
  37954. if ( this._isActiveAction( action ) ) {
  37955. const bindings = action._propertyBindings;
  37956. // decrement reference counts / sort out state
  37957. for ( let i = 0, n = bindings.length; i !== n; ++ i ) {
  37958. const binding = bindings[ i ];
  37959. if ( -- binding.useCount === 0 ) {
  37960. binding.restoreOriginalState();
  37961. this._takeBackBinding( binding );
  37962. }
  37963. }
  37964. this._takeBackAction( action );
  37965. }
  37966. }
  37967. // Memory manager
  37968. _initMemoryManager() {
  37969. this._actions = []; // 'nActiveActions' followed by inactive ones
  37970. this._nActiveActions = 0;
  37971. this._actionsByClip = {};
  37972. // inside:
  37973. // {
  37974. // knownActions: Array< AnimationAction > - used as prototypes
  37975. // actionByRoot: AnimationAction - lookup
  37976. // }
  37977. this._bindings = []; // 'nActiveBindings' followed by inactive ones
  37978. this._nActiveBindings = 0;
  37979. this._bindingsByRootAndName = {}; // inside: Map< name, PropertyMixer >
  37980. this._controlInterpolants = []; // same game as above
  37981. this._nActiveControlInterpolants = 0;
  37982. const scope = this;
  37983. this.stats = {
  37984. actions: {
  37985. get total() {
  37986. return scope._actions.length;
  37987. },
  37988. get inUse() {
  37989. return scope._nActiveActions;
  37990. }
  37991. },
  37992. bindings: {
  37993. get total() {
  37994. return scope._bindings.length;
  37995. },
  37996. get inUse() {
  37997. return scope._nActiveBindings;
  37998. }
  37999. },
  38000. controlInterpolants: {
  38001. get total() {
  38002. return scope._controlInterpolants.length;
  38003. },
  38004. get inUse() {
  38005. return scope._nActiveControlInterpolants;
  38006. }
  38007. }
  38008. };
  38009. }
  38010. // Memory management for AnimationAction objects
  38011. _isActiveAction( action ) {
  38012. const index = action._cacheIndex;
  38013. return index !== null && index < this._nActiveActions;
  38014. }
  38015. _addInactiveAction( action, clipUuid, rootUuid ) {
  38016. const actions = this._actions,
  38017. actionsByClip = this._actionsByClip;
  38018. let actionsForClip = actionsByClip[ clipUuid ];
  38019. if ( actionsForClip === undefined ) {
  38020. actionsForClip = {
  38021. knownActions: [ action ],
  38022. actionByRoot: {}
  38023. };
  38024. action._byClipCacheIndex = 0;
  38025. actionsByClip[ clipUuid ] = actionsForClip;
  38026. } else {
  38027. const knownActions = actionsForClip.knownActions;
  38028. action._byClipCacheIndex = knownActions.length;
  38029. knownActions.push( action );
  38030. }
  38031. action._cacheIndex = actions.length;
  38032. actions.push( action );
  38033. actionsForClip.actionByRoot[ rootUuid ] = action;
  38034. }
  38035. _removeInactiveAction( action ) {
  38036. const actions = this._actions,
  38037. lastInactiveAction = actions[ actions.length - 1 ],
  38038. cacheIndex = action._cacheIndex;
  38039. lastInactiveAction._cacheIndex = cacheIndex;
  38040. actions[ cacheIndex ] = lastInactiveAction;
  38041. actions.pop();
  38042. action._cacheIndex = null;
  38043. const clipUuid = action._clip.uuid,
  38044. actionsByClip = this._actionsByClip,
  38045. actionsForClip = actionsByClip[ clipUuid ],
  38046. knownActionsForClip = actionsForClip.knownActions,
  38047. lastKnownAction =
  38048. knownActionsForClip[ knownActionsForClip.length - 1 ],
  38049. byClipCacheIndex = action._byClipCacheIndex;
  38050. lastKnownAction._byClipCacheIndex = byClipCacheIndex;
  38051. knownActionsForClip[ byClipCacheIndex ] = lastKnownAction;
  38052. knownActionsForClip.pop();
  38053. action._byClipCacheIndex = null;
  38054. const actionByRoot = actionsForClip.actionByRoot,
  38055. rootUuid = ( action._localRoot || this._root ).uuid;
  38056. delete actionByRoot[ rootUuid ];
  38057. if ( knownActionsForClip.length === 0 ) {
  38058. delete actionsByClip[ clipUuid ];
  38059. }
  38060. this._removeInactiveBindingsForAction( action );
  38061. }
  38062. _removeInactiveBindingsForAction( action ) {
  38063. const bindings = action._propertyBindings;
  38064. for ( let i = 0, n = bindings.length; i !== n; ++ i ) {
  38065. const binding = bindings[ i ];
  38066. if ( -- binding.referenceCount === 0 ) {
  38067. this._removeInactiveBinding( binding );
  38068. }
  38069. }
  38070. }
  38071. _lendAction( action ) {
  38072. // [ active actions | inactive actions ]
  38073. // [ active actions >| inactive actions ]
  38074. // s a
  38075. // <-swap->
  38076. // a s
  38077. const actions = this._actions,
  38078. prevIndex = action._cacheIndex,
  38079. lastActiveIndex = this._nActiveActions ++,
  38080. firstInactiveAction = actions[ lastActiveIndex ];
  38081. action._cacheIndex = lastActiveIndex;
  38082. actions[ lastActiveIndex ] = action;
  38083. firstInactiveAction._cacheIndex = prevIndex;
  38084. actions[ prevIndex ] = firstInactiveAction;
  38085. }
  38086. _takeBackAction( action ) {
  38087. // [ active actions | inactive actions ]
  38088. // [ active actions |< inactive actions ]
  38089. // a s
  38090. // <-swap->
  38091. // s a
  38092. const actions = this._actions,
  38093. prevIndex = action._cacheIndex,
  38094. firstInactiveIndex = -- this._nActiveActions,
  38095. lastActiveAction = actions[ firstInactiveIndex ];
  38096. action._cacheIndex = firstInactiveIndex;
  38097. actions[ firstInactiveIndex ] = action;
  38098. lastActiveAction._cacheIndex = prevIndex;
  38099. actions[ prevIndex ] = lastActiveAction;
  38100. }
  38101. // Memory management for PropertyMixer objects
  38102. _addInactiveBinding( binding, rootUuid, trackName ) {
  38103. const bindingsByRoot = this._bindingsByRootAndName,
  38104. bindings = this._bindings;
  38105. let bindingByName = bindingsByRoot[ rootUuid ];
  38106. if ( bindingByName === undefined ) {
  38107. bindingByName = {};
  38108. bindingsByRoot[ rootUuid ] = bindingByName;
  38109. }
  38110. bindingByName[ trackName ] = binding;
  38111. binding._cacheIndex = bindings.length;
  38112. bindings.push( binding );
  38113. }
  38114. _removeInactiveBinding( binding ) {
  38115. const bindings = this._bindings,
  38116. propBinding = binding.binding,
  38117. rootUuid = propBinding.rootNode.uuid,
  38118. trackName = propBinding.path,
  38119. bindingsByRoot = this._bindingsByRootAndName,
  38120. bindingByName = bindingsByRoot[ rootUuid ],
  38121. lastInactiveBinding = bindings[ bindings.length - 1 ],
  38122. cacheIndex = binding._cacheIndex;
  38123. lastInactiveBinding._cacheIndex = cacheIndex;
  38124. bindings[ cacheIndex ] = lastInactiveBinding;
  38125. bindings.pop();
  38126. delete bindingByName[ trackName ];
  38127. if ( Object.keys( bindingByName ).length === 0 ) {
  38128. delete bindingsByRoot[ rootUuid ];
  38129. }
  38130. }
  38131. _lendBinding( binding ) {
  38132. const bindings = this._bindings,
  38133. prevIndex = binding._cacheIndex,
  38134. lastActiveIndex = this._nActiveBindings ++,
  38135. firstInactiveBinding = bindings[ lastActiveIndex ];
  38136. binding._cacheIndex = lastActiveIndex;
  38137. bindings[ lastActiveIndex ] = binding;
  38138. firstInactiveBinding._cacheIndex = prevIndex;
  38139. bindings[ prevIndex ] = firstInactiveBinding;
  38140. }
  38141. _takeBackBinding( binding ) {
  38142. const bindings = this._bindings,
  38143. prevIndex = binding._cacheIndex,
  38144. firstInactiveIndex = -- this._nActiveBindings,
  38145. lastActiveBinding = bindings[ firstInactiveIndex ];
  38146. binding._cacheIndex = firstInactiveIndex;
  38147. bindings[ firstInactiveIndex ] = binding;
  38148. lastActiveBinding._cacheIndex = prevIndex;
  38149. bindings[ prevIndex ] = lastActiveBinding;
  38150. }
  38151. // Memory management of Interpolants for weight and time scale
  38152. _lendControlInterpolant() {
  38153. const interpolants = this._controlInterpolants,
  38154. lastActiveIndex = this._nActiveControlInterpolants ++;
  38155. let interpolant = interpolants[ lastActiveIndex ];
  38156. if ( interpolant === undefined ) {
  38157. interpolant = new LinearInterpolant(
  38158. new Float32Array( 2 ), new Float32Array( 2 ),
  38159. 1, _controlInterpolantsResultBuffer );
  38160. interpolant.__cacheIndex = lastActiveIndex;
  38161. interpolants[ lastActiveIndex ] = interpolant;
  38162. }
  38163. return interpolant;
  38164. }
  38165. _takeBackControlInterpolant( interpolant ) {
  38166. const interpolants = this._controlInterpolants,
  38167. prevIndex = interpolant.__cacheIndex,
  38168. firstInactiveIndex = -- this._nActiveControlInterpolants,
  38169. lastActiveInterpolant = interpolants[ firstInactiveIndex ];
  38170. interpolant.__cacheIndex = firstInactiveIndex;
  38171. interpolants[ firstInactiveIndex ] = interpolant;
  38172. lastActiveInterpolant.__cacheIndex = prevIndex;
  38173. interpolants[ prevIndex ] = lastActiveInterpolant;
  38174. }
  38175. /**
  38176. * Returns an instance of {@link AnimationAction} for the passed clip.
  38177. *
  38178. * If an action fitting the clip and root parameters doesn't yet exist, it
  38179. * will be created by this method. Calling this method several times with the
  38180. * same clip and root parameters always returns the same action.
  38181. *
  38182. * @param {AnimationClip|string} clip - An animation clip or alternatively the name of the animation clip.
  38183. * @param {Object3D} [optionalRoot] - An alternative root object.
  38184. * @param {(NormalAnimationBlendMode|AdditiveAnimationBlendMode)} [blendMode] - The blend mode.
  38185. * @return {?AnimationAction} The animation action.
  38186. */
  38187. clipAction( clip, optionalRoot, blendMode ) {
  38188. const root = optionalRoot || this._root,
  38189. rootUuid = root.uuid;
  38190. let clipObject = typeof clip === 'string' ? AnimationClip.findByName( root, clip ) : clip;
  38191. const clipUuid = clipObject !== null ? clipObject.uuid : clip;
  38192. const actionsForClip = this._actionsByClip[ clipUuid ];
  38193. let prototypeAction = null;
  38194. if ( blendMode === undefined ) {
  38195. if ( clipObject !== null ) {
  38196. blendMode = clipObject.blendMode;
  38197. } else {
  38198. blendMode = NormalAnimationBlendMode;
  38199. }
  38200. }
  38201. if ( actionsForClip !== undefined ) {
  38202. const existingAction = actionsForClip.actionByRoot[ rootUuid ];
  38203. if ( existingAction !== undefined && existingAction.blendMode === blendMode ) {
  38204. return existingAction;
  38205. }
  38206. // we know the clip, so we don't have to parse all
  38207. // the bindings again but can just copy
  38208. prototypeAction = actionsForClip.knownActions[ 0 ];
  38209. // also, take the clip from the prototype action
  38210. if ( clipObject === null )
  38211. clipObject = prototypeAction._clip;
  38212. }
  38213. // clip must be known when specified via string
  38214. if ( clipObject === null ) return null;
  38215. // allocate all resources required to run it
  38216. const newAction = new AnimationAction( this, clipObject, optionalRoot, blendMode );
  38217. this._bindAction( newAction, prototypeAction );
  38218. // and make the action known to the memory manager
  38219. this._addInactiveAction( newAction, clipUuid, rootUuid );
  38220. return newAction;
  38221. }
  38222. /**
  38223. * Returns an existing animation action for the passed clip.
  38224. *
  38225. * @param {AnimationClip|string} clip - An animation clip or alternatively the name of the animation clip.
  38226. * @param {Object3D} [optionalRoot] - An alternative root object.
  38227. * @return {?AnimationAction} The animation action. Returns `null` if no action was found.
  38228. */
  38229. existingAction( clip, optionalRoot ) {
  38230. const root = optionalRoot || this._root,
  38231. rootUuid = root.uuid,
  38232. clipObject = typeof clip === 'string' ?
  38233. AnimationClip.findByName( root, clip ) : clip,
  38234. clipUuid = clipObject ? clipObject.uuid : clip,
  38235. actionsForClip = this._actionsByClip[ clipUuid ];
  38236. if ( actionsForClip !== undefined ) {
  38237. return actionsForClip.actionByRoot[ rootUuid ] || null;
  38238. }
  38239. return null;
  38240. }
  38241. /**
  38242. * Deactivates all previously scheduled actions on this mixer.
  38243. *
  38244. * @return {AnimationMixer} A reference to thi animation mixer.
  38245. */
  38246. stopAllAction() {
  38247. const actions = this._actions,
  38248. nActions = this._nActiveActions;
  38249. for ( let i = nActions - 1; i >= 0; -- i ) {
  38250. actions[ i ].stop();
  38251. }
  38252. return this;
  38253. }
  38254. /**
  38255. * Advances the global mixer time and updates the animation.
  38256. *
  38257. * This is usually done in the render loop by passing the delta
  38258. * time from {@link Clock} or {@link Timer}.
  38259. *
  38260. * @param {number} deltaTime - The delta time in seconds.
  38261. * @return {AnimationMixer} A reference to thi animation mixer.
  38262. */
  38263. update( deltaTime ) {
  38264. deltaTime *= this.timeScale;
  38265. const actions = this._actions,
  38266. nActions = this._nActiveActions,
  38267. time = this.time += deltaTime,
  38268. timeDirection = Math.sign( deltaTime ),
  38269. accuIndex = this._accuIndex ^= 1;
  38270. // run active actions
  38271. for ( let i = 0; i !== nActions; ++ i ) {
  38272. const action = actions[ i ];
  38273. action._update( time, deltaTime, timeDirection, accuIndex );
  38274. }
  38275. // update scene graph
  38276. const bindings = this._bindings,
  38277. nBindings = this._nActiveBindings;
  38278. for ( let i = 0; i !== nBindings; ++ i ) {
  38279. bindings[ i ].apply( accuIndex );
  38280. }
  38281. return this;
  38282. }
  38283. /**
  38284. * Sets the global mixer to a specific time and updates the animation accordingly.
  38285. *
  38286. * This is useful when you need to jump to an exact time in an animation. The
  38287. * input parameter will be scaled by {@link AnimationMixer#timeScale}
  38288. *
  38289. * @param {number} time - The time to set in seconds.
  38290. * @return {AnimationMixer} A reference to thi animation mixer.
  38291. */
  38292. setTime( time ) {
  38293. this.time = 0; // Zero out time attribute for AnimationMixer object;
  38294. for ( let i = 0; i < this._actions.length; i ++ ) {
  38295. this._actions[ i ].time = 0; // Zero out time attribute for all associated AnimationAction objects.
  38296. }
  38297. return this.update( time ); // Update used to set exact time. Returns "this" AnimationMixer object.
  38298. }
  38299. /**
  38300. * Returns this mixer's root object.
  38301. *
  38302. * @return {Object3D} The mixer's root object.
  38303. */
  38304. getRoot() {
  38305. return this._root;
  38306. }
  38307. /**
  38308. * Deallocates all memory resources for a clip. Before using this method make
  38309. * sure to call {@link AnimationAction#stop} for all related actions.
  38310. *
  38311. * @param {AnimationClip} clip - The clip to uncache.
  38312. */
  38313. uncacheClip( clip ) {
  38314. const actions = this._actions,
  38315. clipUuid = clip.uuid,
  38316. actionsByClip = this._actionsByClip,
  38317. actionsForClip = actionsByClip[ clipUuid ];
  38318. if ( actionsForClip !== undefined ) {
  38319. // note: just calling _removeInactiveAction would mess up the
  38320. // iteration state and also require updating the state we can
  38321. // just throw away
  38322. const actionsToRemove = actionsForClip.knownActions;
  38323. for ( let i = 0, n = actionsToRemove.length; i !== n; ++ i ) {
  38324. const action = actionsToRemove[ i ];
  38325. this._deactivateAction( action );
  38326. const cacheIndex = action._cacheIndex,
  38327. lastInactiveAction = actions[ actions.length - 1 ];
  38328. action._cacheIndex = null;
  38329. action._byClipCacheIndex = null;
  38330. lastInactiveAction._cacheIndex = cacheIndex;
  38331. actions[ cacheIndex ] = lastInactiveAction;
  38332. actions.pop();
  38333. this._removeInactiveBindingsForAction( action );
  38334. }
  38335. delete actionsByClip[ clipUuid ];
  38336. }
  38337. }
  38338. /**
  38339. * Deallocates all memory resources for a root object. Before using this
  38340. * method make sure to call {@link AnimationAction#stop} for all related
  38341. * actions or alternatively {@link AnimationMixer#stopAllAction} when the
  38342. * mixer operates on a single root.
  38343. *
  38344. * @param {Object3D} root - The root object to uncache.
  38345. */
  38346. uncacheRoot( root ) {
  38347. const rootUuid = root.uuid,
  38348. actionsByClip = this._actionsByClip;
  38349. for ( const clipUuid in actionsByClip ) {
  38350. const actionByRoot = actionsByClip[ clipUuid ].actionByRoot,
  38351. action = actionByRoot[ rootUuid ];
  38352. if ( action !== undefined ) {
  38353. this._deactivateAction( action );
  38354. this._removeInactiveAction( action );
  38355. }
  38356. }
  38357. const bindingsByRoot = this._bindingsByRootAndName,
  38358. bindingByName = bindingsByRoot[ rootUuid ];
  38359. if ( bindingByName !== undefined ) {
  38360. for ( const trackName in bindingByName ) {
  38361. const binding = bindingByName[ trackName ];
  38362. binding.restoreOriginalState();
  38363. this._removeInactiveBinding( binding );
  38364. }
  38365. }
  38366. }
  38367. /**
  38368. * Deallocates all memory resources for an action. The action is identified by the
  38369. * given clip and an optional root object. Before using this method make
  38370. * sure to call {@link AnimationAction#stop} to deactivate the action.
  38371. *
  38372. * @param {AnimationClip|string} clip - An animation clip or alternatively the name of the animation clip.
  38373. * @param {Object3D} [optionalRoot] - An alternative root object.
  38374. */
  38375. uncacheAction( clip, optionalRoot ) {
  38376. const action = this.existingAction( clip, optionalRoot );
  38377. if ( action !== null ) {
  38378. this._deactivateAction( action );
  38379. this._removeInactiveAction( action );
  38380. }
  38381. }
  38382. }
  38383. /**
  38384. * Represents a 3D render target.
  38385. *
  38386. * @augments RenderTarget
  38387. */
  38388. class RenderTarget3D extends RenderTarget {
  38389. /**
  38390. * Constructs a new 3D render target.
  38391. *
  38392. * @param {number} [width=1] - The width of the render target.
  38393. * @param {number} [height=1] - The height of the render target.
  38394. * @param {number} [depth=1] - The height of the render target.
  38395. * @param {RenderTarget~Options} [options] - The configuration object.
  38396. */
  38397. constructor( width = 1, height = 1, depth = 1, options = {} ) {
  38398. super( width, height, options );
  38399. /**
  38400. * This flag can be used for type testing.
  38401. *
  38402. * @type {boolean}
  38403. * @readonly
  38404. * @default true
  38405. */
  38406. this.isRenderTarget3D = true;
  38407. this.depth = depth;
  38408. /**
  38409. * Overwritten with a different texture type.
  38410. *
  38411. * @type {Data3DTexture}
  38412. */
  38413. this.texture = new Data3DTexture( null, width, height, depth );
  38414. this.texture.isRenderTargetTexture = true;
  38415. }
  38416. }
  38417. /**
  38418. * Represents an array render target.
  38419. *
  38420. * @augments RenderTarget
  38421. */
  38422. class RenderTargetArray extends RenderTarget {
  38423. /**
  38424. * Constructs a new 3D render target.
  38425. *
  38426. * @param {number} [width=1] - The width of the render target.
  38427. * @param {number} [height=1] - The height of the render target.
  38428. * @param {number} [depth=1] - The height of the render target.
  38429. * @param {RenderTarget~Options} [options] - The configuration object.
  38430. */
  38431. constructor( width = 1, height = 1, depth = 1, options = {} ) {
  38432. super( width, height, options );
  38433. this.isRenderTargetArray = true;
  38434. this.depth = depth;
  38435. /**
  38436. * Overwritten with a different texture type.
  38437. *
  38438. * @type {DataArrayTexture}
  38439. */
  38440. this.texture = new DataArrayTexture( null, width, height, depth );
  38441. this.texture.isRenderTargetTexture = true;
  38442. }
  38443. }
  38444. /**
  38445. * Represents a uniform which is a global shader variable. They are passed to shader programs.
  38446. *
  38447. * When declaring a uniform of a {@link ShaderMaterial}, it is declared by value or by object.
  38448. * ```js
  38449. * uniforms: {
  38450. * time: { value: 1.0 },
  38451. * resolution: new Uniform( new Vector2() )
  38452. * };
  38453. * ```
  38454. * Since this class can only be used in context of {@link ShaderMaterial}, it is only supported
  38455. * in {@link WebGLRenderer}.
  38456. */
  38457. class Uniform {
  38458. /**
  38459. * Constructs a new uniform.
  38460. *
  38461. * @param {any} value - The uniform value.
  38462. */
  38463. constructor( value ) {
  38464. /**
  38465. * The uniform value.
  38466. *
  38467. * @type {any}
  38468. */
  38469. this.value = value;
  38470. }
  38471. /**
  38472. * Returns a new uniform with copied values from this instance.
  38473. * If the value has a `clone()` method, the value is cloned as well.
  38474. *
  38475. * @return {Uniform} A clone of this instance.
  38476. */
  38477. clone() {
  38478. return new Uniform( this.value.clone === undefined ? this.value : this.value.clone() );
  38479. }
  38480. }
  38481. let _id = 0;
  38482. /**
  38483. * A class for managing multiple uniforms in a single group. The renderer will process
  38484. * such a definition as a single UBO.
  38485. *
  38486. * Since this class can only be used in context of {@link ShaderMaterial}, it is only supported
  38487. * in {@link WebGLRenderer}.
  38488. *
  38489. * @augments EventDispatcher
  38490. */
  38491. class UniformsGroup extends EventDispatcher {
  38492. /**
  38493. * Constructs a new uniforms group.
  38494. */
  38495. constructor() {
  38496. super();
  38497. /**
  38498. * This flag can be used for type testing.
  38499. *
  38500. * @type {boolean}
  38501. * @readonly
  38502. * @default true
  38503. */
  38504. this.isUniformsGroup = true;
  38505. /**
  38506. * The ID of the 3D object.
  38507. *
  38508. * @name UniformsGroup#id
  38509. * @type {number}
  38510. * @readonly
  38511. */
  38512. Object.defineProperty( this, 'id', { value: _id ++ } );
  38513. /**
  38514. * The name of the uniforms group.
  38515. *
  38516. * @type {string}
  38517. */
  38518. this.name = '';
  38519. /**
  38520. * The buffer usage.
  38521. *
  38522. * @type {(StaticDrawUsage|DynamicDrawUsage|StreamDrawUsage|StaticReadUsage|DynamicReadUsage|StreamReadUsage|StaticCopyUsage|DynamicCopyUsage|StreamCopyUsage)}
  38523. * @default StaticDrawUsage
  38524. */
  38525. this.usage = StaticDrawUsage;
  38526. /**
  38527. * An array holding the uniforms.
  38528. *
  38529. * @type {Array<Uniform>}
  38530. */
  38531. this.uniforms = [];
  38532. }
  38533. /**
  38534. * Adds the given uniform to this uniforms group.
  38535. *
  38536. * @param {Uniform} uniform - The uniform to add.
  38537. * @return {UniformsGroup} A reference to this uniforms group.
  38538. */
  38539. add( uniform ) {
  38540. this.uniforms.push( uniform );
  38541. return this;
  38542. }
  38543. /**
  38544. * Removes the given uniform from this uniforms group.
  38545. *
  38546. * @param {Uniform} uniform - The uniform to remove.
  38547. * @return {UniformsGroup} A reference to this uniforms group.
  38548. */
  38549. remove( uniform ) {
  38550. const index = this.uniforms.indexOf( uniform );
  38551. if ( index !== -1 ) this.uniforms.splice( index, 1 );
  38552. return this;
  38553. }
  38554. /**
  38555. * Sets the name of this uniforms group.
  38556. *
  38557. * @param {string} name - The name to set.
  38558. * @return {UniformsGroup} A reference to this uniforms group.
  38559. */
  38560. setName( name ) {
  38561. this.name = name;
  38562. return this;
  38563. }
  38564. /**
  38565. * Sets the usage of this uniforms group.
  38566. *
  38567. * @param {(StaticDrawUsage|DynamicDrawUsage|StreamDrawUsage|StaticReadUsage|DynamicReadUsage|StreamReadUsage|StaticCopyUsage|DynamicCopyUsage|StreamCopyUsage)} value - The usage to set.
  38568. * @return {UniformsGroup} A reference to this uniforms group.
  38569. */
  38570. setUsage( value ) {
  38571. this.usage = value;
  38572. return this;
  38573. }
  38574. /**
  38575. * Frees the GPU-related resources allocated by this instance. Call this
  38576. * method whenever this instance is no longer used in your app.
  38577. *
  38578. * @fires Texture#dispose
  38579. */
  38580. dispose() {
  38581. this.dispatchEvent( { type: 'dispose' } );
  38582. }
  38583. /**
  38584. * Copies the values of the given uniforms group to this instance.
  38585. *
  38586. * @param {UniformsGroup} source - The uniforms group to copy.
  38587. * @return {UniformsGroup} A reference to this uniforms group.
  38588. */
  38589. copy( source ) {
  38590. this.name = source.name;
  38591. this.usage = source.usage;
  38592. const uniformsSource = source.uniforms;
  38593. this.uniforms.length = 0;
  38594. for ( let i = 0, l = uniformsSource.length; i < l; i ++ ) {
  38595. const uniforms = Array.isArray( uniformsSource[ i ] ) ? uniformsSource[ i ] : [ uniformsSource[ i ] ];
  38596. for ( let j = 0; j < uniforms.length; j ++ ) {
  38597. this.uniforms.push( uniforms[ j ].clone() );
  38598. }
  38599. }
  38600. return this;
  38601. }
  38602. /**
  38603. * Returns a new uniforms group with copied values from this instance.
  38604. *
  38605. * @return {UniformsGroup} A clone of this instance.
  38606. */
  38607. clone() {
  38608. return new this.constructor().copy( this );
  38609. }
  38610. }
  38611. /**
  38612. * An instanced version of an interleaved buffer.
  38613. *
  38614. * @augments InterleavedBuffer
  38615. */
  38616. class InstancedInterleavedBuffer extends InterleavedBuffer {
  38617. /**
  38618. * Constructs a new instanced interleaved buffer.
  38619. *
  38620. * @param {TypedArray} array - A typed array with a shared buffer storing attribute data.
  38621. * @param {number} stride - The number of typed-array elements per vertex.
  38622. * @param {number} [meshPerAttribute=1] - Defines how often a value of this interleaved buffer should be repeated.
  38623. */
  38624. constructor( array, stride, meshPerAttribute = 1 ) {
  38625. super( array, stride );
  38626. /**
  38627. * This flag can be used for type testing.
  38628. *
  38629. * @type {boolean}
  38630. * @readonly
  38631. * @default true
  38632. */
  38633. this.isInstancedInterleavedBuffer = true;
  38634. /**
  38635. * Defines how often a value of this buffer attribute should be repeated,
  38636. * see {@link InstancedBufferAttribute#meshPerAttribute}.
  38637. *
  38638. * @type {number}
  38639. * @default 1
  38640. */
  38641. this.meshPerAttribute = meshPerAttribute;
  38642. }
  38643. copy( source ) {
  38644. super.copy( source );
  38645. this.meshPerAttribute = source.meshPerAttribute;
  38646. return this;
  38647. }
  38648. clone( data ) {
  38649. const ib = super.clone( data );
  38650. ib.meshPerAttribute = this.meshPerAttribute;
  38651. return ib;
  38652. }
  38653. toJSON( data ) {
  38654. const json = super.toJSON( data );
  38655. json.isInstancedInterleavedBuffer = true;
  38656. json.meshPerAttribute = this.meshPerAttribute;
  38657. return json;
  38658. }
  38659. }
  38660. /**
  38661. * An alternative version of a buffer attribute with more control over the VBO.
  38662. *
  38663. * The renderer does not construct a VBO for this kind of attribute. Instead, it uses
  38664. * whatever VBO is passed in constructor and can later be altered via the `buffer` property.
  38665. *
  38666. * The most common use case for this class is when some kind of GPGPU calculation interferes
  38667. * or even produces the VBOs in question.
  38668. *
  38669. * Notice that this class can only be used with {@link WebGLRenderer}.
  38670. */
  38671. class GLBufferAttribute {
  38672. /**
  38673. * Constructs a new GL buffer attribute.
  38674. *
  38675. * @param {WebGLBuffer} buffer - The native WebGL buffer.
  38676. * @param {number} type - The native data type (e.g. `gl.FLOAT`).
  38677. * @param {number} itemSize - The item size.
  38678. * @param {number} elementSize - The corresponding size (in bytes) for the given `type` parameter.
  38679. * @param {number} count - The expected number of vertices in VBO.
  38680. */
  38681. constructor( buffer, type, itemSize, elementSize, count ) {
  38682. /**
  38683. * This flag can be used for type testing.
  38684. *
  38685. * @type {boolean}
  38686. * @readonly
  38687. * @default true
  38688. */
  38689. this.isGLBufferAttribute = true;
  38690. /**
  38691. * The name of the buffer attribute.
  38692. *
  38693. * @type {string}
  38694. */
  38695. this.name = '';
  38696. /**
  38697. * The native WebGL buffer.
  38698. *
  38699. * @type {WebGLBuffer}
  38700. */
  38701. this.buffer = buffer;
  38702. /**
  38703. * The native data type.
  38704. *
  38705. * @type {number}
  38706. */
  38707. this.type = type;
  38708. /**
  38709. * The item size, see {@link BufferAttribute#itemSize}.
  38710. *
  38711. * @type {number}
  38712. */
  38713. this.itemSize = itemSize;
  38714. /**
  38715. * The corresponding size (in bytes) for the given `type` parameter.
  38716. *
  38717. * @type {number}
  38718. */
  38719. this.elementSize = elementSize;
  38720. /**
  38721. * The expected number of vertices in VBO.
  38722. *
  38723. * @type {number}
  38724. */
  38725. this.count = count;
  38726. /**
  38727. * A version number, incremented every time the `needsUpdate` is set to `true`.
  38728. *
  38729. * @type {number}
  38730. */
  38731. this.version = 0;
  38732. }
  38733. /**
  38734. * Flag to indicate that this attribute has changed and should be re-sent to
  38735. * the GPU. Set this to `true` when you modify the value of the array.
  38736. *
  38737. * @type {number}
  38738. * @default false
  38739. * @param {boolean} value
  38740. */
  38741. set needsUpdate( value ) {
  38742. if ( value === true ) this.version ++;
  38743. }
  38744. /**
  38745. * Sets the given native WebGL buffer.
  38746. *
  38747. * @param {WebGLBuffer} buffer - The buffer to set.
  38748. * @return {BufferAttribute} A reference to this instance.
  38749. */
  38750. setBuffer( buffer ) {
  38751. this.buffer = buffer;
  38752. return this;
  38753. }
  38754. /**
  38755. * Sets the given native data type and element size.
  38756. *
  38757. * @param {number} type - The native data type (e.g. `gl.FLOAT`).
  38758. * @param {number} elementSize - The corresponding size (in bytes) for the given `type` parameter.
  38759. * @return {BufferAttribute} A reference to this instance.
  38760. */
  38761. setType( type, elementSize ) {
  38762. this.type = type;
  38763. this.elementSize = elementSize;
  38764. return this;
  38765. }
  38766. /**
  38767. * Sets the item size.
  38768. *
  38769. * @param {number} itemSize - The item size.
  38770. * @return {BufferAttribute} A reference to this instance.
  38771. */
  38772. setItemSize( itemSize ) {
  38773. this.itemSize = itemSize;
  38774. return this;
  38775. }
  38776. /**
  38777. * Sets the count (the expected number of vertices in VBO).
  38778. *
  38779. * @param {number} count - The count.
  38780. * @return {BufferAttribute} A reference to this instance.
  38781. */
  38782. setCount( count ) {
  38783. this.count = count;
  38784. return this;
  38785. }
  38786. }
  38787. const _matrix = /*@__PURE__*/ new Matrix4();
  38788. /**
  38789. * This class is designed to assist with raycasting. Raycasting is used for
  38790. * mouse picking (working out what objects in the 3d space the mouse is over)
  38791. * amongst other things.
  38792. */
  38793. class Raycaster {
  38794. /**
  38795. * Constructs a new raycaster.
  38796. *
  38797. * @param {Vector3} origin - The origin vector where the ray casts from.
  38798. * @param {Vector3} direction - The (normalized) direction vector that gives direction to the ray.
  38799. * @param {number} [near=0] - All results returned are further away than near. Near can't be negative.
  38800. * @param {number} [far=Infinity] - All results returned are closer than far. Far can't be lower than near.
  38801. */
  38802. constructor( origin, direction, near = 0, far = Infinity ) {
  38803. /**
  38804. * The ray used for raycasting.
  38805. *
  38806. * @type {Ray}
  38807. */
  38808. this.ray = new Ray( origin, direction );
  38809. /**
  38810. * All results returned are further away than near. Near can't be negative.
  38811. *
  38812. * @type {number}
  38813. * @default 0
  38814. */
  38815. this.near = near;
  38816. /**
  38817. * All results returned are further away than near. Near can't be negative.
  38818. *
  38819. * @type {number}
  38820. * @default Infinity
  38821. */
  38822. this.far = far;
  38823. /**
  38824. * The camera to use when raycasting against view-dependent objects such as
  38825. * billboarded objects like sprites. This field can be set manually or
  38826. * is set when calling `setFromCamera()`.
  38827. *
  38828. * @type {?Camera}
  38829. * @default null
  38830. */
  38831. this.camera = null;
  38832. /**
  38833. * Allows to selectively ignore 3D objects when performing intersection tests.
  38834. * The following code example ensures that only 3D objects on layer `1` will be
  38835. * honored by raycaster.
  38836. * ```js
  38837. * raycaster.layers.set( 1 );
  38838. * object.layers.enable( 1 );
  38839. * ```
  38840. *
  38841. * @type {Layers}
  38842. */
  38843. this.layers = new Layers();
  38844. /**
  38845. * A parameter object that configures the raycasting. It has the structure:
  38846. *
  38847. * ```
  38848. * {
  38849. * Mesh: {},
  38850. * Line: { threshold: 1 },
  38851. * LOD: {},
  38852. * Points: { threshold: 1 },
  38853. * Sprite: {}
  38854. * }
  38855. * ```
  38856. * Where `threshold` is the precision of the raycaster when intersecting objects, in world units.
  38857. *
  38858. * @type {Object}
  38859. */
  38860. this.params = {
  38861. Mesh: {},
  38862. Line: { threshold: 1 },
  38863. LOD: {},
  38864. Points: { threshold: 1 },
  38865. Sprite: {}
  38866. };
  38867. }
  38868. /**
  38869. * Updates the ray with a new origin and direction by copying the values from the arguments.
  38870. *
  38871. * @param {Vector3} origin - The origin vector where the ray casts from.
  38872. * @param {Vector3} direction - The (normalized) direction vector that gives direction to the ray.
  38873. */
  38874. set( origin, direction ) {
  38875. // direction is assumed to be normalized (for accurate distance calculations)
  38876. this.ray.set( origin, direction );
  38877. }
  38878. /**
  38879. * Uses the given coordinates and camera to compute a new origin and direction for the internal ray.
  38880. *
  38881. * @param {Vector2} coords - 2D coordinates of the mouse, in normalized device coordinates (NDC).
  38882. * X and Y components should be between `-1` and `1`.
  38883. * @param {Camera} camera - The camera from which the ray should originate.
  38884. */
  38885. setFromCamera( coords, camera ) {
  38886. if ( camera.isPerspectiveCamera ) {
  38887. this.ray.origin.setFromMatrixPosition( camera.matrixWorld );
  38888. this.ray.direction.set( coords.x, coords.y, 0.5 ).unproject( camera ).sub( this.ray.origin ).normalize();
  38889. this.camera = camera;
  38890. } else if ( camera.isOrthographicCamera ) {
  38891. this.ray.origin.set( coords.x, coords.y, ( camera.near + camera.far ) / ( camera.near - camera.far ) ).unproject( camera ); // set origin in plane of camera
  38892. this.ray.direction.set( 0, 0, -1 ).transformDirection( camera.matrixWorld );
  38893. this.camera = camera;
  38894. } else {
  38895. console.error( 'THREE.Raycaster: Unsupported camera type: ' + camera.type );
  38896. }
  38897. }
  38898. /**
  38899. * Uses the given WebXR controller to compute a new origin and direction for the internal ray.
  38900. *
  38901. * @param {WebXRController} controller - The controller to copy the position and direction from.
  38902. * @return {Raycaster} A reference to this raycaster.
  38903. */
  38904. setFromXRController( controller ) {
  38905. _matrix.identity().extractRotation( controller.matrixWorld );
  38906. this.ray.origin.setFromMatrixPosition( controller.matrixWorld );
  38907. this.ray.direction.set( 0, 0, -1 ).applyMatrix4( _matrix );
  38908. return this;
  38909. }
  38910. /**
  38911. * The intersection point of a raycaster intersection test.
  38912. * @typedef {Object} Raycaster~Intersection
  38913. * @property {number} distance - The distance from the ray's origin to the intersection point.
  38914. * @property {number} distanceToRay - Some 3D objects e.g. {@link Points} provide the distance of the
  38915. * intersection to the nearest point on the ray. For other objects it will be `undefined`.
  38916. * @property {Vector3} point - The intersection point, in world coordinates.
  38917. * @property {Object} face - The face that has been intersected.
  38918. * @property {number} faceIndex - The face index.
  38919. * @property {Object3D} object - The 3D object that has been intersected.
  38920. * @property {Vector2} uv - U,V coordinates at point of intersection.
  38921. * @property {Vector2} uv1 - Second set of U,V coordinates at point of intersection.
  38922. * @property {Vector3} uv1 - Interpolated normal vector at point of intersection.
  38923. * @property {number} instanceId - The index number of the instance where the ray
  38924. * intersects the {@link InstancedMesh}.
  38925. */
  38926. /**
  38927. * Checks all intersection between the ray and the object with or without the
  38928. * descendants. Intersections are returned sorted by distance, closest first.
  38929. *
  38930. * `Raycaster` delegates to the `raycast()` method of the passed 3D object, when
  38931. * evaluating whether the ray intersects the object or not. This allows meshes to respond
  38932. * differently to ray casting than lines or points.
  38933. *
  38934. * Note that for meshes, faces must be pointed towards the origin of the ray in order
  38935. * to be detected; intersections of the ray passing through the back of a face will not
  38936. * be detected. To raycast against both faces of an object, you'll want to set {@link Material#side}
  38937. * to `THREE.DoubleSide`.
  38938. *
  38939. * @param {Object3D} object - The 3D object to check for intersection with the ray.
  38940. * @param {boolean} [recursive=true] - If set to `true`, it also checks all descendants.
  38941. * Otherwise it only checks intersection with the object.
  38942. * @param {Array<Raycaster~Intersection>} [intersects=[]] The target array that holds the result of the method.
  38943. * @return {Array<Raycaster~Intersection>} An array holding the intersection points.
  38944. */
  38945. intersectObject( object, recursive = true, intersects = [] ) {
  38946. intersect( object, this, intersects, recursive );
  38947. intersects.sort( ascSort );
  38948. return intersects;
  38949. }
  38950. /**
  38951. * Checks all intersection between the ray and the objects with or without
  38952. * the descendants. Intersections are returned sorted by distance, closest first.
  38953. *
  38954. * @param {Array<Object3D>} objects - The 3D objects to check for intersection with the ray.
  38955. * @param {boolean} [recursive=true] - If set to `true`, it also checks all descendants.
  38956. * Otherwise it only checks intersection with the object.
  38957. * @param {Array<Raycaster~Intersection>} [intersects=[]] The target array that holds the result of the method.
  38958. * @return {Array<Raycaster~Intersection>} An array holding the intersection points.
  38959. */
  38960. intersectObjects( objects, recursive = true, intersects = [] ) {
  38961. for ( let i = 0, l = objects.length; i < l; i ++ ) {
  38962. intersect( objects[ i ], this, intersects, recursive );
  38963. }
  38964. intersects.sort( ascSort );
  38965. return intersects;
  38966. }
  38967. }
  38968. function ascSort( a, b ) {
  38969. return a.distance - b.distance;
  38970. }
  38971. function intersect( object, raycaster, intersects, recursive ) {
  38972. let propagate = true;
  38973. if ( object.layers.test( raycaster.layers ) ) {
  38974. const result = object.raycast( raycaster, intersects );
  38975. if ( result === false ) propagate = false;
  38976. }
  38977. if ( propagate === true && recursive === true ) {
  38978. const children = object.children;
  38979. for ( let i = 0, l = children.length; i < l; i ++ ) {
  38980. intersect( children[ i ], raycaster, intersects, true );
  38981. }
  38982. }
  38983. }
  38984. /**
  38985. * This class can be used to represent points in 3D space as
  38986. * [Spherical coordinates]{@link https://en.wikipedia.org/wiki/Spherical_coordinate_system}.
  38987. */
  38988. class Spherical {
  38989. /**
  38990. * Constructs a new spherical.
  38991. *
  38992. * @param {number} [radius=1] - The radius, or the Euclidean distance (straight-line distance) from the point to the origin.
  38993. * @param {number} [phi=0] - The polar angle in radians from the y (up) axis.
  38994. * @param {number} [theta=0] - The equator/azimuthal angle in radians around the y (up) axis.
  38995. */
  38996. constructor( radius = 1, phi = 0, theta = 0 ) {
  38997. /**
  38998. * The radius, or the Euclidean distance (straight-line distance) from the point to the origin.
  38999. *
  39000. * @type {number}
  39001. * @default 1
  39002. */
  39003. this.radius = radius;
  39004. /**
  39005. * The polar angle in radians from the y (up) axis.
  39006. *
  39007. * @type {number}
  39008. * @default 0
  39009. */
  39010. this.phi = phi;
  39011. /**
  39012. * The equator/azimuthal angle in radians around the y (up) axis.
  39013. *
  39014. * @type {number}
  39015. * @default 0
  39016. */
  39017. this.theta = theta;
  39018. }
  39019. /**
  39020. * Sets the spherical components by copying the given values.
  39021. *
  39022. * @param {number} radius - The radius.
  39023. * @param {number} phi - The polar angle.
  39024. * @param {number} theta - The azimuthal angle.
  39025. * @return {Spherical} A reference to this spherical.
  39026. */
  39027. set( radius, phi, theta ) {
  39028. this.radius = radius;
  39029. this.phi = phi;
  39030. this.theta = theta;
  39031. return this;
  39032. }
  39033. /**
  39034. * Copies the values of the given spherical to this instance.
  39035. *
  39036. * @param {Spherical} other - The spherical to copy.
  39037. * @return {Spherical} A reference to this spherical.
  39038. */
  39039. copy( other ) {
  39040. this.radius = other.radius;
  39041. this.phi = other.phi;
  39042. this.theta = other.theta;
  39043. return this;
  39044. }
  39045. /**
  39046. * Restricts the polar angle [page:.phi phi] to be between `0.000001` and pi -
  39047. * `0.000001`.
  39048. *
  39049. * @return {Spherical} A reference to this spherical.
  39050. */
  39051. makeSafe() {
  39052. const EPS = 0.000001;
  39053. this.phi = clamp( this.phi, EPS, Math.PI - EPS );
  39054. return this;
  39055. }
  39056. /**
  39057. * Sets the spherical components from the given vector which is assumed to hold
  39058. * Cartesian coordinates.
  39059. *
  39060. * @param {Vector3} v - The vector to set.
  39061. * @return {Spherical} A reference to this spherical.
  39062. */
  39063. setFromVector3( v ) {
  39064. return this.setFromCartesianCoords( v.x, v.y, v.z );
  39065. }
  39066. /**
  39067. * Sets the spherical components from the given Cartesian coordinates.
  39068. *
  39069. * @param {number} x - The x value.
  39070. * @param {number} y - The x value.
  39071. * @param {number} z - The x value.
  39072. * @return {Spherical} A reference to this spherical.
  39073. */
  39074. setFromCartesianCoords( x, y, z ) {
  39075. this.radius = Math.sqrt( x * x + y * y + z * z );
  39076. if ( this.radius === 0 ) {
  39077. this.theta = 0;
  39078. this.phi = 0;
  39079. } else {
  39080. this.theta = Math.atan2( x, z );
  39081. this.phi = Math.acos( clamp( y / this.radius, -1, 1 ) );
  39082. }
  39083. return this;
  39084. }
  39085. /**
  39086. * Returns a new spherical with copied values from this instance.
  39087. *
  39088. * @return {Spherical} A clone of this instance.
  39089. */
  39090. clone() {
  39091. return new this.constructor().copy( this );
  39092. }
  39093. }
  39094. /**
  39095. * This class can be used to represent points in 3D space as
  39096. * [Cylindrical coordinates]{@link https://en.wikipedia.org/wiki/Cylindrical_coordinate_system}.
  39097. */
  39098. class Cylindrical {
  39099. /**
  39100. * Constructs a new cylindrical.
  39101. *
  39102. * @param {number} [radius=1] - The distance from the origin to a point in the x-z plane.
  39103. * @param {number} [theta=0] - A counterclockwise angle in the x-z plane measured in radians from the positive z-axis.
  39104. * @param {number} [y=0] - The height above the x-z plane.
  39105. */
  39106. constructor( radius = 1, theta = 0, y = 0 ) {
  39107. /**
  39108. * The distance from the origin to a point in the x-z plane.
  39109. *
  39110. * @type {number}
  39111. * @default 1
  39112. */
  39113. this.radius = radius;
  39114. /**
  39115. * A counterclockwise angle in the x-z plane measured in radians from the positive z-axis.
  39116. *
  39117. * @type {number}
  39118. * @default 0
  39119. */
  39120. this.theta = theta;
  39121. /**
  39122. * The height above the x-z plane.
  39123. *
  39124. * @type {number}
  39125. * @default 0
  39126. */
  39127. this.y = y;
  39128. }
  39129. /**
  39130. * Sets the cylindrical components by copying the given values.
  39131. *
  39132. * @param {number} radius - The radius.
  39133. * @param {number} theta - The theta angle.
  39134. * @param {number} y - The height value.
  39135. * @return {Cylindrical} A reference to this cylindrical.
  39136. */
  39137. set( radius, theta, y ) {
  39138. this.radius = radius;
  39139. this.theta = theta;
  39140. this.y = y;
  39141. return this;
  39142. }
  39143. /**
  39144. * Copies the values of the given cylindrical to this instance.
  39145. *
  39146. * @param {Cylindrical} other - The cylindrical to copy.
  39147. * @return {Cylindrical} A reference to this cylindrical.
  39148. */
  39149. copy( other ) {
  39150. this.radius = other.radius;
  39151. this.theta = other.theta;
  39152. this.y = other.y;
  39153. return this;
  39154. }
  39155. /**
  39156. * Sets the cylindrical components from the given vector which is assumed to hold
  39157. * Cartesian coordinates.
  39158. *
  39159. * @param {Vector3} v - The vector to set.
  39160. * @return {Cylindrical} A reference to this cylindrical.
  39161. */
  39162. setFromVector3( v ) {
  39163. return this.setFromCartesianCoords( v.x, v.y, v.z );
  39164. }
  39165. /**
  39166. * Sets the cylindrical components from the given Cartesian coordinates.
  39167. *
  39168. * @param {number} x - The x value.
  39169. * @param {number} y - The x value.
  39170. * @param {number} z - The x value.
  39171. * @return {Cylindrical} A reference to this cylindrical.
  39172. */
  39173. setFromCartesianCoords( x, y, z ) {
  39174. this.radius = Math.sqrt( x * x + z * z );
  39175. this.theta = Math.atan2( x, z );
  39176. this.y = y;
  39177. return this;
  39178. }
  39179. /**
  39180. * Returns a new cylindrical with copied values from this instance.
  39181. *
  39182. * @return {Cylindrical} A clone of this instance.
  39183. */
  39184. clone() {
  39185. return new this.constructor().copy( this );
  39186. }
  39187. }
  39188. /**
  39189. * Represents a 2x2 matrix.
  39190. *
  39191. * A Note on Row-Major and Column-Major Ordering:
  39192. *
  39193. * The constructor and {@link Matrix2#set} method take arguments in
  39194. * [row-major]{@link https://en.wikipedia.org/wiki/Row-_and_column-major_order#Column-major_order}
  39195. * order, while internally they are stored in the {@link Matrix2#elements} array in column-major order.
  39196. * This means that calling:
  39197. * ```js
  39198. * const m = new THREE.Matrix2();
  39199. * m.set( 11, 12,
  39200. * 21, 22 );
  39201. * ```
  39202. * will result in the elements array containing:
  39203. * ```js
  39204. * m.elements = [ 11, 21,
  39205. * 12, 22 ];
  39206. * ```
  39207. * and internally all calculations are performed using column-major ordering.
  39208. * However, as the actual ordering makes no difference mathematically and
  39209. * most people are used to thinking about matrices in row-major order, the
  39210. * three.js documentation shows matrices in row-major order. Just bear in
  39211. * mind that if you are reading the source code, you'll have to take the
  39212. * transpose of any matrices outlined here to make sense of the calculations.
  39213. */
  39214. class Matrix2 {
  39215. /**
  39216. * Constructs a new 2x2 matrix. The arguments are supposed to be
  39217. * in row-major order. If no arguments are provided, the constructor
  39218. * initializes the matrix as an identity matrix.
  39219. *
  39220. * @param {number} [n11] - 1-1 matrix element.
  39221. * @param {number} [n12] - 1-2 matrix element.
  39222. * @param {number} [n21] - 2-1 matrix element.
  39223. * @param {number} [n22] - 2-2 matrix element.
  39224. */
  39225. constructor( n11, n12, n21, n22 ) {
  39226. /**
  39227. * This flag can be used for type testing.
  39228. *
  39229. * @type {boolean}
  39230. * @readonly
  39231. * @default true
  39232. */
  39233. Matrix2.prototype.isMatrix2 = true;
  39234. /**
  39235. * A column-major list of matrix values.
  39236. *
  39237. * @type {Array<number>}
  39238. */
  39239. this.elements = [
  39240. 1, 0,
  39241. 0, 1,
  39242. ];
  39243. if ( n11 !== undefined ) {
  39244. this.set( n11, n12, n21, n22 );
  39245. }
  39246. }
  39247. /**
  39248. * Sets this matrix to the 2x2 identity matrix.
  39249. *
  39250. * @return {Matrix2} A reference to this matrix.
  39251. */
  39252. identity() {
  39253. this.set(
  39254. 1, 0,
  39255. 0, 1,
  39256. );
  39257. return this;
  39258. }
  39259. /**
  39260. * Sets the elements of the matrix from the given array.
  39261. *
  39262. * @param {Array<number>} array - The matrix elements in column-major order.
  39263. * @param {number} [offset=0] - Index of the first element in the array.
  39264. * @return {Matrix2} A reference to this matrix.
  39265. */
  39266. fromArray( array, offset = 0 ) {
  39267. for ( let i = 0; i < 4; i ++ ) {
  39268. this.elements[ i ] = array[ i + offset ];
  39269. }
  39270. return this;
  39271. }
  39272. /**
  39273. * Sets the elements of the matrix.The arguments are supposed to be
  39274. * in row-major order.
  39275. *
  39276. * @param {number} n11 - 1-1 matrix element.
  39277. * @param {number} n12 - 1-2 matrix element.
  39278. * @param {number} n21 - 2-1 matrix element.
  39279. * @param {number} n22 - 2-2 matrix element.
  39280. * @return {Matrix2} A reference to this matrix.
  39281. */
  39282. set( n11, n12, n21, n22 ) {
  39283. const te = this.elements;
  39284. te[ 0 ] = n11; te[ 2 ] = n12;
  39285. te[ 1 ] = n21; te[ 3 ] = n22;
  39286. return this;
  39287. }
  39288. }
  39289. const _vector$4 = /*@__PURE__*/ new Vector2();
  39290. /**
  39291. * Represents an axis-aligned bounding box (AABB) in 2D space.
  39292. */
  39293. class Box2 {
  39294. /**
  39295. * Constructs a new bounding box.
  39296. *
  39297. * @param {Vector2} [min=(Infinity,Infinity)] - A vector representing the lower boundary of the box.
  39298. * @param {Vector2} [max=(-Infinity,-Infinity)] - A vector representing the upper boundary of the box.
  39299. */
  39300. constructor( min = new Vector2( + Infinity, + Infinity ), max = new Vector2( - Infinity, - Infinity ) ) {
  39301. /**
  39302. * This flag can be used for type testing.
  39303. *
  39304. * @type {boolean}
  39305. * @readonly
  39306. * @default true
  39307. */
  39308. this.isBox2 = true;
  39309. /**
  39310. * The lower boundary of the box.
  39311. *
  39312. * @type {Vector2}
  39313. */
  39314. this.min = min;
  39315. /**
  39316. * The upper boundary of the box.
  39317. *
  39318. * @type {Vector2}
  39319. */
  39320. this.max = max;
  39321. }
  39322. /**
  39323. * Sets the lower and upper boundaries of this box.
  39324. * Please note that this method only copies the values from the given objects.
  39325. *
  39326. * @param {Vector2} min - The lower boundary of the box.
  39327. * @param {Vector2} max - The upper boundary of the box.
  39328. * @return {Box2} A reference to this bounding box.
  39329. */
  39330. set( min, max ) {
  39331. this.min.copy( min );
  39332. this.max.copy( max );
  39333. return this;
  39334. }
  39335. /**
  39336. * Sets the upper and lower bounds of this box so it encloses the position data
  39337. * in the given array.
  39338. *
  39339. * @param {Array<Vector2>} points - An array holding 2D position data as instances of {@link Vector2}.
  39340. * @return {Box2} A reference to this bounding box.
  39341. */
  39342. setFromPoints( points ) {
  39343. this.makeEmpty();
  39344. for ( let i = 0, il = points.length; i < il; i ++ ) {
  39345. this.expandByPoint( points[ i ] );
  39346. }
  39347. return this;
  39348. }
  39349. /**
  39350. * Centers this box on the given center vector and sets this box's width, height and
  39351. * depth to the given size values.
  39352. *
  39353. * @param {Vector2} center - The center of the box.
  39354. * @param {Vector2} size - The x and y dimensions of the box.
  39355. * @return {Box2} A reference to this bounding box.
  39356. */
  39357. setFromCenterAndSize( center, size ) {
  39358. const halfSize = _vector$4.copy( size ).multiplyScalar( 0.5 );
  39359. this.min.copy( center ).sub( halfSize );
  39360. this.max.copy( center ).add( halfSize );
  39361. return this;
  39362. }
  39363. /**
  39364. * Returns a new box with copied values from this instance.
  39365. *
  39366. * @return {Box2} A clone of this instance.
  39367. */
  39368. clone() {
  39369. return new this.constructor().copy( this );
  39370. }
  39371. /**
  39372. * Copies the values of the given box to this instance.
  39373. *
  39374. * @param {Box2} box - The box to copy.
  39375. * @return {Box2} A reference to this bounding box.
  39376. */
  39377. copy( box ) {
  39378. this.min.copy( box.min );
  39379. this.max.copy( box.max );
  39380. return this;
  39381. }
  39382. /**
  39383. * Makes this box empty which means in encloses a zero space in 2D.
  39384. *
  39385. * @return {Box2} A reference to this bounding box.
  39386. */
  39387. makeEmpty() {
  39388. this.min.x = this.min.y = + Infinity;
  39389. this.max.x = this.max.y = - Infinity;
  39390. return this;
  39391. }
  39392. /**
  39393. * Returns true if this box includes zero points within its bounds.
  39394. * Note that a box with equal lower and upper bounds still includes one
  39395. * point, the one both bounds share.
  39396. *
  39397. * @return {boolean} Whether this box is empty or not.
  39398. */
  39399. isEmpty() {
  39400. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  39401. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y );
  39402. }
  39403. /**
  39404. * Returns the center point of this box.
  39405. *
  39406. * @param {Vector2} target - The target vector that is used to store the method's result.
  39407. * @return {Vector2} The center point.
  39408. */
  39409. getCenter( target ) {
  39410. return this.isEmpty() ? target.set( 0, 0 ) : target.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  39411. }
  39412. /**
  39413. * Returns the dimensions of this box.
  39414. *
  39415. * @param {Vector2} target - The target vector that is used to store the method's result.
  39416. * @return {Vector2} The size.
  39417. */
  39418. getSize( target ) {
  39419. return this.isEmpty() ? target.set( 0, 0 ) : target.subVectors( this.max, this.min );
  39420. }
  39421. /**
  39422. * Expands the boundaries of this box to include the given point.
  39423. *
  39424. * @param {Vector2} point - The point that should be included by the bounding box.
  39425. * @return {Box2} A reference to this bounding box.
  39426. */
  39427. expandByPoint( point ) {
  39428. this.min.min( point );
  39429. this.max.max( point );
  39430. return this;
  39431. }
  39432. /**
  39433. * Expands this box equilaterally by the given vector. The width of this
  39434. * box will be expanded by the x component of the vector in both
  39435. * directions. The height of this box will be expanded by the y component of
  39436. * the vector in both directions.
  39437. *
  39438. * @param {Vector2} vector - The vector that should expand the bounding box.
  39439. * @return {Box2} A reference to this bounding box.
  39440. */
  39441. expandByVector( vector ) {
  39442. this.min.sub( vector );
  39443. this.max.add( vector );
  39444. return this;
  39445. }
  39446. /**
  39447. * Expands each dimension of the box by the given scalar. If negative, the
  39448. * dimensions of the box will be contracted.
  39449. *
  39450. * @param {number} scalar - The scalar value that should expand the bounding box.
  39451. * @return {Box2} A reference to this bounding box.
  39452. */
  39453. expandByScalar( scalar ) {
  39454. this.min.addScalar( - scalar );
  39455. this.max.addScalar( scalar );
  39456. return this;
  39457. }
  39458. /**
  39459. * Returns `true` if the given point lies within or on the boundaries of this box.
  39460. *
  39461. * @param {Vector2} point - The point to test.
  39462. * @return {boolean} Whether the bounding box contains the given point or not.
  39463. */
  39464. containsPoint( point ) {
  39465. return point.x >= this.min.x && point.x <= this.max.x &&
  39466. point.y >= this.min.y && point.y <= this.max.y;
  39467. }
  39468. /**
  39469. * Returns `true` if this bounding box includes the entirety of the given bounding box.
  39470. * If this box and the given one are identical, this function also returns `true`.
  39471. *
  39472. * @param {Box2} box - The bounding box to test.
  39473. * @return {boolean} Whether the bounding box contains the given bounding box or not.
  39474. */
  39475. containsBox( box ) {
  39476. return this.min.x <= box.min.x && box.max.x <= this.max.x &&
  39477. this.min.y <= box.min.y && box.max.y <= this.max.y;
  39478. }
  39479. /**
  39480. * Returns a point as a proportion of this box's width and height.
  39481. *
  39482. * @param {Vector2} point - A point in 2D space.
  39483. * @param {Vector2} target - The target vector that is used to store the method's result.
  39484. * @return {Vector2} A point as a proportion of this box's width and height.
  39485. */
  39486. getParameter( point, target ) {
  39487. // This can potentially have a divide by zero if the box
  39488. // has a size dimension of 0.
  39489. return target.set(
  39490. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  39491. ( point.y - this.min.y ) / ( this.max.y - this.min.y )
  39492. );
  39493. }
  39494. /**
  39495. * Returns `true` if the given bounding box intersects with this bounding box.
  39496. *
  39497. * @param {Box2} box - The bounding box to test.
  39498. * @return {boolean} Whether the given bounding box intersects with this bounding box.
  39499. */
  39500. intersectsBox( box ) {
  39501. // using 4 splitting planes to rule out intersections
  39502. return box.max.x >= this.min.x && box.min.x <= this.max.x &&
  39503. box.max.y >= this.min.y && box.min.y <= this.max.y;
  39504. }
  39505. /**
  39506. * Clamps the given point within the bounds of this box.
  39507. *
  39508. * @param {Vector2} point - The point to clamp.
  39509. * @param {Vector2} target - The target vector that is used to store the method's result.
  39510. * @return {Vector2} The clamped point.
  39511. */
  39512. clampPoint( point, target ) {
  39513. return target.copy( point ).clamp( this.min, this.max );
  39514. }
  39515. /**
  39516. * Returns the euclidean distance from any edge of this box to the specified point. If
  39517. * the given point lies inside of this box, the distance will be `0`.
  39518. *
  39519. * @param {Vector2} point - The point to compute the distance to.
  39520. * @return {number} The euclidean distance.
  39521. */
  39522. distanceToPoint( point ) {
  39523. return this.clampPoint( point, _vector$4 ).distanceTo( point );
  39524. }
  39525. /**
  39526. * Computes the intersection of this bounding box and the given one, setting the upper
  39527. * bound of this box to the lesser of the two boxes' upper bounds and the
  39528. * lower bound of this box to the greater of the two boxes' lower bounds. If
  39529. * there's no overlap, makes this box empty.
  39530. *
  39531. * @param {Box2} box - The bounding box to intersect with.
  39532. * @return {Box2} A reference to this bounding box.
  39533. */
  39534. intersect( box ) {
  39535. this.min.max( box.min );
  39536. this.max.min( box.max );
  39537. if ( this.isEmpty() ) this.makeEmpty();
  39538. return this;
  39539. }
  39540. /**
  39541. * Computes the union of this box and another and the given one, setting the upper
  39542. * bound of this box to the greater of the two boxes' upper bounds and the
  39543. * lower bound of this box to the lesser of the two boxes' lower bounds.
  39544. *
  39545. * @param {Box2} box - The bounding box that will be unioned with this instance.
  39546. * @return {Box2} A reference to this bounding box.
  39547. */
  39548. union( box ) {
  39549. this.min.min( box.min );
  39550. this.max.max( box.max );
  39551. return this;
  39552. }
  39553. /**
  39554. * Adds the given offset to both the upper and lower bounds of this bounding box,
  39555. * effectively moving it in 2D space.
  39556. *
  39557. * @param {Vector2} offset - The offset that should be used to translate the bounding box.
  39558. * @return {Box2} A reference to this bounding box.
  39559. */
  39560. translate( offset ) {
  39561. this.min.add( offset );
  39562. this.max.add( offset );
  39563. return this;
  39564. }
  39565. /**
  39566. * Returns `true` if this bounding box is equal with the given one.
  39567. *
  39568. * @param {Box2} box - The box to test for equality.
  39569. * @return {boolean} Whether this bounding box is equal with the given one.
  39570. */
  39571. equals( box ) {
  39572. return box.min.equals( this.min ) && box.max.equals( this.max );
  39573. }
  39574. }
  39575. const _startP = /*@__PURE__*/ new Vector3();
  39576. const _startEnd = /*@__PURE__*/ new Vector3();
  39577. /**
  39578. * An analytical line segment in 3D space represented by a start and end point.
  39579. */
  39580. class Line3 {
  39581. /**
  39582. * Constructs a new line segment.
  39583. *
  39584. * @param {Vector3} [start=(0,0,0)] - Start of the line segment.
  39585. * @param {Vector3} [end=(0,0,0)] - End of the line segment.
  39586. */
  39587. constructor( start = new Vector3(), end = new Vector3() ) {
  39588. /**
  39589. * Start of the line segment.
  39590. *
  39591. * @type {Vector3}
  39592. */
  39593. this.start = start;
  39594. /**
  39595. * End of the line segment.
  39596. *
  39597. * @type {Vector3}
  39598. */
  39599. this.end = end;
  39600. }
  39601. /**
  39602. * Sets the start and end values by copying the given vectors.
  39603. *
  39604. * @param {Vector3} start - The start point.
  39605. * @param {Vector3} end - The end point.
  39606. * @return {Line3} A reference to this line segment.
  39607. */
  39608. set( start, end ) {
  39609. this.start.copy( start );
  39610. this.end.copy( end );
  39611. return this;
  39612. }
  39613. /**
  39614. * Copies the values of the given line segment to this instance.
  39615. *
  39616. * @param {Line3} line - The line segment to copy.
  39617. * @return {Line3} A reference to this line segment.
  39618. */
  39619. copy( line ) {
  39620. this.start.copy( line.start );
  39621. this.end.copy( line.end );
  39622. return this;
  39623. }
  39624. /**
  39625. * Returns the center of the line segment.
  39626. *
  39627. * @param {Vector3} target - The target vector that is used to store the method's result.
  39628. * @return {Vector3} The center point.
  39629. */
  39630. getCenter( target ) {
  39631. return target.addVectors( this.start, this.end ).multiplyScalar( 0.5 );
  39632. }
  39633. /**
  39634. * Returns the delta vector of the line segment's start and end point.
  39635. *
  39636. * @param {Vector3} target - The target vector that is used to store the method's result.
  39637. * @return {Vector3} The delta vector.
  39638. */
  39639. delta( target ) {
  39640. return target.subVectors( this.end, this.start );
  39641. }
  39642. /**
  39643. * Returns the squared Euclidean distance between the line' start and end point.
  39644. *
  39645. * @return {number} The squared Euclidean distance.
  39646. */
  39647. distanceSq() {
  39648. return this.start.distanceToSquared( this.end );
  39649. }
  39650. /**
  39651. * Returns the Euclidean distance between the line' start and end point.
  39652. *
  39653. * @return {number} The Euclidean distance.
  39654. */
  39655. distance() {
  39656. return this.start.distanceTo( this.end );
  39657. }
  39658. /**
  39659. * Returns a vector at a certain position along the line segment.
  39660. *
  39661. * @param {number} t - A value between `[0,1]` to represent a position along the line segment.
  39662. * @param {Vector3} target - The target vector that is used to store the method's result.
  39663. * @return {Vector3} The delta vector.
  39664. */
  39665. at( t, target ) {
  39666. return this.delta( target ).multiplyScalar( t ).add( this.start );
  39667. }
  39668. /**
  39669. * Returns a point parameter based on the closest point as projected on the line segment.
  39670. *
  39671. * @param {Vector3} point - The point for which to return a point parameter.
  39672. * @param {boolean} clampToLine - Whether to clamp the result to the range `[0,1]` or not.
  39673. * @return {number} The point parameter.
  39674. */
  39675. closestPointToPointParameter( point, clampToLine ) {
  39676. _startP.subVectors( point, this.start );
  39677. _startEnd.subVectors( this.end, this.start );
  39678. const startEnd2 = _startEnd.dot( _startEnd );
  39679. const startEnd_startP = _startEnd.dot( _startP );
  39680. let t = startEnd_startP / startEnd2;
  39681. if ( clampToLine ) {
  39682. t = clamp( t, 0, 1 );
  39683. }
  39684. return t;
  39685. }
  39686. /**
  39687. * Returns the closets point on the line for a given point.
  39688. *
  39689. * @param {Vector3} point - The point to compute the closest point on the line for.
  39690. * @param {boolean} clampToLine - Whether to clamp the result to the range `[0,1]` or not.
  39691. * @param {Vector3} target - The target vector that is used to store the method's result.
  39692. * @return {Vector3} The closest point on the line.
  39693. */
  39694. closestPointToPoint( point, clampToLine, target ) {
  39695. const t = this.closestPointToPointParameter( point, clampToLine );
  39696. return this.delta( target ).multiplyScalar( t ).add( this.start );
  39697. }
  39698. /**
  39699. * Applies a 4x4 transformation matrix to this line segment.
  39700. *
  39701. * @param {Matrix4} matrix - The transformation matrix.
  39702. * @return {Line3} A reference to this line segment.
  39703. */
  39704. applyMatrix4( matrix ) {
  39705. this.start.applyMatrix4( matrix );
  39706. this.end.applyMatrix4( matrix );
  39707. return this;
  39708. }
  39709. /**
  39710. * Returns `true` if this line segment is equal with the given one.
  39711. *
  39712. * @param {Line3} line - The line segment to test for equality.
  39713. * @return {boolean} Whether this line segment is equal with the given one.
  39714. */
  39715. equals( line ) {
  39716. return line.start.equals( this.start ) && line.end.equals( this.end );
  39717. }
  39718. /**
  39719. * Returns a new line segment with copied values from this instance.
  39720. *
  39721. * @return {Line3} A clone of this instance.
  39722. */
  39723. clone() {
  39724. return new this.constructor().copy( this );
  39725. }
  39726. }
  39727. const _vector$3 = /*@__PURE__*/ new Vector3();
  39728. /**
  39729. * This displays a cone shaped helper object for a {@link SpotLight}.
  39730. *
  39731. * ```js
  39732. * const spotLight = new THREE.SpotLight( 0xffffff );
  39733. * spotLight.position.set( 10, 10, 10 );
  39734. * scene.add( spotLight );
  39735. *
  39736. * const spotLightHelper = new THREE.SpotLightHelper( spotLight );
  39737. * scene.add( spotLightHelper );
  39738. * ```
  39739. *
  39740. * @augments Object3D
  39741. */
  39742. class SpotLightHelper extends Object3D {
  39743. /**
  39744. * Constructs a new spot light helper.
  39745. *
  39746. * @param {HemisphereLight} light - The light to be visualized.
  39747. * @param {number|Color|string} [color] - The helper's color. If not set, the helper will take
  39748. * the color of the light.
  39749. */
  39750. constructor( light, color ) {
  39751. super();
  39752. /**
  39753. * The light being visualized.
  39754. *
  39755. * @type {SpotLight}
  39756. */
  39757. this.light = light;
  39758. this.matrixAutoUpdate = false;
  39759. /**
  39760. * The color parameter passed in the constructor.
  39761. * If not set, the helper will take the color of the light.
  39762. *
  39763. * @type {number|Color|string}
  39764. */
  39765. this.color = color;
  39766. this.type = 'SpotLightHelper';
  39767. const geometry = new BufferGeometry();
  39768. const positions = [
  39769. 0, 0, 0, 0, 0, 1,
  39770. 0, 0, 0, 1, 0, 1,
  39771. 0, 0, 0, -1, 0, 1,
  39772. 0, 0, 0, 0, 1, 1,
  39773. 0, 0, 0, 0, -1, 1
  39774. ];
  39775. for ( let i = 0, j = 1, l = 32; i < l; i ++, j ++ ) {
  39776. const p1 = ( i / l ) * Math.PI * 2;
  39777. const p2 = ( j / l ) * Math.PI * 2;
  39778. positions.push(
  39779. Math.cos( p1 ), Math.sin( p1 ), 1,
  39780. Math.cos( p2 ), Math.sin( p2 ), 1
  39781. );
  39782. }
  39783. geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  39784. const material = new LineBasicMaterial( { fog: false, toneMapped: false } );
  39785. this.cone = new LineSegments( geometry, material );
  39786. this.add( this.cone );
  39787. this.update();
  39788. }
  39789. /**
  39790. * Frees the GPU-related resources allocated by this instance. Call this
  39791. * method whenever this instance is no longer used in your app.
  39792. */
  39793. dispose() {
  39794. this.cone.geometry.dispose();
  39795. this.cone.material.dispose();
  39796. }
  39797. /**
  39798. * Updates the helper to match the position and direction of the
  39799. * light being visualized.
  39800. */
  39801. update() {
  39802. this.light.updateWorldMatrix( true, false );
  39803. this.light.target.updateWorldMatrix( true, false );
  39804. // update the local matrix based on the parent and light target transforms
  39805. if ( this.parent ) {
  39806. this.parent.updateWorldMatrix( true );
  39807. this.matrix
  39808. .copy( this.parent.matrixWorld )
  39809. .invert()
  39810. .multiply( this.light.matrixWorld );
  39811. } else {
  39812. this.matrix.copy( this.light.matrixWorld );
  39813. }
  39814. this.matrixWorld.copy( this.light.matrixWorld );
  39815. const coneLength = this.light.distance ? this.light.distance : 1000;
  39816. const coneWidth = coneLength * Math.tan( this.light.angle );
  39817. this.cone.scale.set( coneWidth, coneWidth, coneLength );
  39818. _vector$3.setFromMatrixPosition( this.light.target.matrixWorld );
  39819. this.cone.lookAt( _vector$3 );
  39820. if ( this.color !== undefined ) {
  39821. this.cone.material.color.set( this.color );
  39822. } else {
  39823. this.cone.material.color.copy( this.light.color );
  39824. }
  39825. }
  39826. }
  39827. const _vector$2 = /*@__PURE__*/ new Vector3();
  39828. const _boneMatrix = /*@__PURE__*/ new Matrix4();
  39829. const _matrixWorldInv = /*@__PURE__*/ new Matrix4();
  39830. /**
  39831. * A helper object to assist with visualizing a {@link Skeleton}.
  39832. *
  39833. * ```js
  39834. * const helper = new THREE.SkeletonHelper( skinnedMesh );
  39835. * scene.add( helper );
  39836. * ```
  39837. *
  39838. * @augments LineSegments
  39839. */
  39840. class SkeletonHelper extends LineSegments {
  39841. /**
  39842. * Constructs a new hemisphere light helper.
  39843. *
  39844. * @param {Object3D} object - Usually an instance of {@link SkinnedMesh}. However, any 3D object
  39845. * can be used if it represents a hierarchy of bones (see {@link Bone}).
  39846. */
  39847. constructor( object ) {
  39848. const bones = getBoneList( object );
  39849. const geometry = new BufferGeometry();
  39850. const vertices = [];
  39851. const colors = [];
  39852. const color1 = new Color( 0, 0, 1 );
  39853. const color2 = new Color( 0, 1, 0 );
  39854. for ( let i = 0; i < bones.length; i ++ ) {
  39855. const bone = bones[ i ];
  39856. if ( bone.parent && bone.parent.isBone ) {
  39857. vertices.push( 0, 0, 0 );
  39858. vertices.push( 0, 0, 0 );
  39859. colors.push( color1.r, color1.g, color1.b );
  39860. colors.push( color2.r, color2.g, color2.b );
  39861. }
  39862. }
  39863. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  39864. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  39865. const material = new LineBasicMaterial( { vertexColors: true, depthTest: false, depthWrite: false, toneMapped: false, transparent: true } );
  39866. super( geometry, material );
  39867. /**
  39868. * This flag can be used for type testing.
  39869. *
  39870. * @type {boolean}
  39871. * @readonly
  39872. * @default true
  39873. */
  39874. this.isSkeletonHelper = true;
  39875. this.type = 'SkeletonHelper';
  39876. /**
  39877. * The object being visualized.
  39878. *
  39879. * @type {Object3D}
  39880. */
  39881. this.root = object;
  39882. /**
  39883. * he list of bones that the helper visualizes.
  39884. *
  39885. * @type {Array<Bone>}
  39886. */
  39887. this.bones = bones;
  39888. this.matrix = object.matrixWorld;
  39889. this.matrixAutoUpdate = false;
  39890. }
  39891. updateMatrixWorld( force ) {
  39892. const bones = this.bones;
  39893. const geometry = this.geometry;
  39894. const position = geometry.getAttribute( 'position' );
  39895. _matrixWorldInv.copy( this.root.matrixWorld ).invert();
  39896. for ( let i = 0, j = 0; i < bones.length; i ++ ) {
  39897. const bone = bones[ i ];
  39898. if ( bone.parent && bone.parent.isBone ) {
  39899. _boneMatrix.multiplyMatrices( _matrixWorldInv, bone.matrixWorld );
  39900. _vector$2.setFromMatrixPosition( _boneMatrix );
  39901. position.setXYZ( j, _vector$2.x, _vector$2.y, _vector$2.z );
  39902. _boneMatrix.multiplyMatrices( _matrixWorldInv, bone.parent.matrixWorld );
  39903. _vector$2.setFromMatrixPosition( _boneMatrix );
  39904. position.setXYZ( j + 1, _vector$2.x, _vector$2.y, _vector$2.z );
  39905. j += 2;
  39906. }
  39907. }
  39908. geometry.getAttribute( 'position' ).needsUpdate = true;
  39909. super.updateMatrixWorld( force );
  39910. }
  39911. /**
  39912. * Frees the GPU-related resources allocated by this instance. Call this
  39913. * method whenever this instance is no longer used in your app.
  39914. */
  39915. dispose() {
  39916. this.geometry.dispose();
  39917. this.material.dispose();
  39918. }
  39919. }
  39920. function getBoneList( object ) {
  39921. const boneList = [];
  39922. if ( object.isBone === true ) {
  39923. boneList.push( object );
  39924. }
  39925. for ( let i = 0; i < object.children.length; i ++ ) {
  39926. boneList.push( ...getBoneList( object.children[ i ] ) );
  39927. }
  39928. return boneList;
  39929. }
  39930. /**
  39931. * This displays a helper object consisting of a spherical mesh for
  39932. * visualizing an instance of {@link PointLight}.
  39933. *
  39934. * ```js
  39935. * const pointLight = new THREE.PointLight( 0xff0000, 1, 100 );
  39936. * pointLight.position.set( 10, 10, 10 );
  39937. * scene.add( pointLight );
  39938. *
  39939. * const sphereSize = 1;
  39940. * const pointLightHelper = new THREE.PointLightHelper( pointLight, sphereSize );
  39941. * scene.add( pointLightHelper );
  39942. * ```
  39943. *
  39944. * @augments Mesh
  39945. */
  39946. class PointLightHelper extends Mesh {
  39947. /**
  39948. * Constructs a new point light helper.
  39949. *
  39950. * @param {PointLight} light - The light to be visualized.
  39951. * @param {number} [sphereSize=1] - The size of the sphere helper.
  39952. * @param {number|Color|string} [color] - The helper's color. If not set, the helper will take
  39953. * the color of the light.
  39954. */
  39955. constructor( light, sphereSize, color ) {
  39956. const geometry = new SphereGeometry( sphereSize, 4, 2 );
  39957. const material = new MeshBasicMaterial( { wireframe: true, fog: false, toneMapped: false } );
  39958. super( geometry, material );
  39959. /**
  39960. * The light being visualized.
  39961. *
  39962. * @type {HemisphereLight}
  39963. */
  39964. this.light = light;
  39965. /**
  39966. * The color parameter passed in the constructor.
  39967. * If not set, the helper will take the color of the light.
  39968. *
  39969. * @type {number|Color|string}
  39970. */
  39971. this.color = color;
  39972. this.type = 'PointLightHelper';
  39973. this.matrix = this.light.matrixWorld;
  39974. this.matrixAutoUpdate = false;
  39975. this.update();
  39976. /*
  39977. // TODO: delete this comment?
  39978. const distanceGeometry = new THREE.IcosahedronGeometry( 1, 2 );
  39979. const distanceMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false, wireframe: true, opacity: 0.1, transparent: true } );
  39980. this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial );
  39981. this.lightDistance = new THREE.Mesh( distanceGeometry, distanceMaterial );
  39982. const d = light.distance;
  39983. if ( d === 0.0 ) {
  39984. this.lightDistance.visible = false;
  39985. } else {
  39986. this.lightDistance.scale.set( d, d, d );
  39987. }
  39988. this.add( this.lightDistance );
  39989. */
  39990. }
  39991. /**
  39992. * Frees the GPU-related resources allocated by this instance. Call this
  39993. * method whenever this instance is no longer used in your app.
  39994. */
  39995. dispose() {
  39996. this.geometry.dispose();
  39997. this.material.dispose();
  39998. }
  39999. /**
  40000. * Updates the helper to match the position of the
  40001. * light being visualized.
  40002. */
  40003. update() {
  40004. this.light.updateWorldMatrix( true, false );
  40005. if ( this.color !== undefined ) {
  40006. this.material.color.set( this.color );
  40007. } else {
  40008. this.material.color.copy( this.light.color );
  40009. }
  40010. /*
  40011. const d = this.light.distance;
  40012. if ( d === 0.0 ) {
  40013. this.lightDistance.visible = false;
  40014. } else {
  40015. this.lightDistance.visible = true;
  40016. this.lightDistance.scale.set( d, d, d );
  40017. }
  40018. */
  40019. }
  40020. }
  40021. const _vector$1 = /*@__PURE__*/ new Vector3();
  40022. const _color1 = /*@__PURE__*/ new Color();
  40023. const _color2 = /*@__PURE__*/ new Color();
  40024. /**
  40025. * Creates a visual aid consisting of a spherical mesh for a
  40026. * given {@link HemisphereLight}.
  40027. *
  40028. * ```js
  40029. * const light = new THREE.HemisphereLight( 0xffffbb, 0x080820, 1 );
  40030. * const helper = new THREE.HemisphereLightHelper( light, 5 );
  40031. * scene.add( helper );
  40032. * ```
  40033. *
  40034. * @augments Object3D
  40035. */
  40036. class HemisphereLightHelper extends Object3D {
  40037. /**
  40038. * Constructs a new hemisphere light helper.
  40039. *
  40040. * @param {HemisphereLight} light - The light to be visualized.
  40041. * @param {number} [size=1] - The size of the mesh used to visualize the light.
  40042. * @param {number|Color|string} [color] - The helper's color. If not set, the helper will take
  40043. * the color of the light.
  40044. */
  40045. constructor( light, size, color ) {
  40046. super();
  40047. /**
  40048. * The light being visualized.
  40049. *
  40050. * @type {HemisphereLight}
  40051. */
  40052. this.light = light;
  40053. this.matrix = light.matrixWorld;
  40054. this.matrixAutoUpdate = false;
  40055. /**
  40056. * The color parameter passed in the constructor.
  40057. * If not set, the helper will take the color of the light.
  40058. *
  40059. * @type {number|Color|string}
  40060. */
  40061. this.color = color;
  40062. this.type = 'HemisphereLightHelper';
  40063. const geometry = new OctahedronGeometry( size );
  40064. geometry.rotateY( Math.PI * 0.5 );
  40065. this.material = new MeshBasicMaterial( { wireframe: true, fog: false, toneMapped: false } );
  40066. if ( this.color === undefined ) this.material.vertexColors = true;
  40067. const position = geometry.getAttribute( 'position' );
  40068. const colors = new Float32Array( position.count * 3 );
  40069. geometry.setAttribute( 'color', new BufferAttribute( colors, 3 ) );
  40070. this.add( new Mesh( geometry, this.material ) );
  40071. this.update();
  40072. }
  40073. /**
  40074. * Frees the GPU-related resources allocated by this instance. Call this
  40075. * method whenever this instance is no longer used in your app.
  40076. */
  40077. dispose() {
  40078. this.children[ 0 ].geometry.dispose();
  40079. this.children[ 0 ].material.dispose();
  40080. }
  40081. /**
  40082. * Updates the helper to match the position and direction of the
  40083. * light being visualized.
  40084. */
  40085. update() {
  40086. const mesh = this.children[ 0 ];
  40087. if ( this.color !== undefined ) {
  40088. this.material.color.set( this.color );
  40089. } else {
  40090. const colors = mesh.geometry.getAttribute( 'color' );
  40091. _color1.copy( this.light.color );
  40092. _color2.copy( this.light.groundColor );
  40093. for ( let i = 0, l = colors.count; i < l; i ++ ) {
  40094. const color = ( i < ( l / 2 ) ) ? _color1 : _color2;
  40095. colors.setXYZ( i, color.r, color.g, color.b );
  40096. }
  40097. colors.needsUpdate = true;
  40098. }
  40099. this.light.updateWorldMatrix( true, false );
  40100. mesh.lookAt( _vector$1.setFromMatrixPosition( this.light.matrixWorld ).negate() );
  40101. }
  40102. }
  40103. /**
  40104. * The helper is an object to define grids. Grids are two-dimensional
  40105. * arrays of lines.
  40106. *
  40107. * ```js
  40108. * const size = 10;
  40109. * const divisions = 10;
  40110. *
  40111. * const gridHelper = new THREE.GridHelper( size, divisions );
  40112. * scene.add( gridHelper );
  40113. * ```
  40114. *
  40115. * @augments LineSegments
  40116. */
  40117. class GridHelper extends LineSegments {
  40118. /**
  40119. * Constructs a new grid helper.
  40120. *
  40121. * @param {number} [size=10] - The size of the grid.
  40122. * @param {number} [divisions=10] - The number of divisions across the grid.
  40123. * @param {number|Color|string} [color1=0x444444] - The color of the center line.
  40124. * @param {number|Color|string} [color2=0x888888] - The color of the lines of the grid.
  40125. */
  40126. constructor( size = 10, divisions = 10, color1 = 0x444444, color2 = 0x888888 ) {
  40127. color1 = new Color( color1 );
  40128. color2 = new Color( color2 );
  40129. const center = divisions / 2;
  40130. const step = size / divisions;
  40131. const halfSize = size / 2;
  40132. const vertices = [], colors = [];
  40133. for ( let i = 0, j = 0, k = - halfSize; i <= divisions; i ++, k += step ) {
  40134. vertices.push( - halfSize, 0, k, halfSize, 0, k );
  40135. vertices.push( k, 0, - halfSize, k, 0, halfSize );
  40136. const color = i === center ? color1 : color2;
  40137. color.toArray( colors, j ); j += 3;
  40138. color.toArray( colors, j ); j += 3;
  40139. color.toArray( colors, j ); j += 3;
  40140. color.toArray( colors, j ); j += 3;
  40141. }
  40142. const geometry = new BufferGeometry();
  40143. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  40144. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  40145. const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
  40146. super( geometry, material );
  40147. this.type = 'GridHelper';
  40148. }
  40149. /**
  40150. * Frees the GPU-related resources allocated by this instance. Call this
  40151. * method whenever this instance is no longer used in your app.
  40152. */
  40153. dispose() {
  40154. this.geometry.dispose();
  40155. this.material.dispose();
  40156. }
  40157. }
  40158. /**
  40159. * This helper is an object to define polar grids. Grids are
  40160. * two-dimensional arrays of lines.
  40161. *
  40162. * ```js
  40163. * const radius = 10;
  40164. * const sectors = 16;
  40165. * const rings = 8;
  40166. * const divisions = 64;
  40167. *
  40168. * const helper = new THREE.PolarGridHelper( radius, sectors, rings, divisions );
  40169. * scene.add( helper );
  40170. * ```
  40171. *
  40172. * @augments LineSegments
  40173. */
  40174. class PolarGridHelper extends LineSegments {
  40175. /**
  40176. * Constructs a new polar grid helper.
  40177. *
  40178. * @param {number} [radius=10] - The radius of the polar grid. This can be any positive number.
  40179. * @param {number} [sectors=16] - The number of sectors the grid will be divided into. This can be any positive integer.
  40180. * @param {number} [rings=16] - The number of rings. This can be any positive integer.
  40181. * @param {number} [divisions=64] - The number of line segments used for each circle. This can be any positive integer.
  40182. * @param {number|Color|string} [color1=0x444444] - The first color used for grid elements.
  40183. * @param {number|Color|string} [color2=0x888888] - The second color used for grid elements.
  40184. */
  40185. constructor( radius = 10, sectors = 16, rings = 8, divisions = 64, color1 = 0x444444, color2 = 0x888888 ) {
  40186. color1 = new Color( color1 );
  40187. color2 = new Color( color2 );
  40188. const vertices = [];
  40189. const colors = [];
  40190. // create the sectors
  40191. if ( sectors > 1 ) {
  40192. for ( let i = 0; i < sectors; i ++ ) {
  40193. const v = ( i / sectors ) * ( Math.PI * 2 );
  40194. const x = Math.sin( v ) * radius;
  40195. const z = Math.cos( v ) * radius;
  40196. vertices.push( 0, 0, 0 );
  40197. vertices.push( x, 0, z );
  40198. const color = ( i & 1 ) ? color1 : color2;
  40199. colors.push( color.r, color.g, color.b );
  40200. colors.push( color.r, color.g, color.b );
  40201. }
  40202. }
  40203. // create the rings
  40204. for ( let i = 0; i < rings; i ++ ) {
  40205. const color = ( i & 1 ) ? color1 : color2;
  40206. const r = radius - ( radius / rings * i );
  40207. for ( let j = 0; j < divisions; j ++ ) {
  40208. // first vertex
  40209. let v = ( j / divisions ) * ( Math.PI * 2 );
  40210. let x = Math.sin( v ) * r;
  40211. let z = Math.cos( v ) * r;
  40212. vertices.push( x, 0, z );
  40213. colors.push( color.r, color.g, color.b );
  40214. // second vertex
  40215. v = ( ( j + 1 ) / divisions ) * ( Math.PI * 2 );
  40216. x = Math.sin( v ) * r;
  40217. z = Math.cos( v ) * r;
  40218. vertices.push( x, 0, z );
  40219. colors.push( color.r, color.g, color.b );
  40220. }
  40221. }
  40222. const geometry = new BufferGeometry();
  40223. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  40224. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  40225. const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
  40226. super( geometry, material );
  40227. this.type = 'PolarGridHelper';
  40228. }
  40229. /**
  40230. * Frees the GPU-related resources allocated by this instance. Call this
  40231. * method whenever this instance is no longer used in your app.
  40232. */
  40233. dispose() {
  40234. this.geometry.dispose();
  40235. this.material.dispose();
  40236. }
  40237. }
  40238. const _v1 = /*@__PURE__*/ new Vector3();
  40239. const _v2 = /*@__PURE__*/ new Vector3();
  40240. const _v3 = /*@__PURE__*/ new Vector3();
  40241. /**
  40242. * Helper object to assist with visualizing a {@link DirectionalLight}'s
  40243. * effect on the scene. This consists of plane and a line representing the
  40244. * light's position and direction.
  40245. *
  40246. * ```js
  40247. * const light = new THREE.DirectionalLight( 0xFFFFFF );
  40248. * scene.add( light );
  40249. *
  40250. * const helper = new THREE.DirectionalLightHelper( light, 5 );
  40251. * scene.add( helper );
  40252. * ```
  40253. *
  40254. * @augments Object3D
  40255. */
  40256. class DirectionalLightHelper extends Object3D {
  40257. /**
  40258. * Constructs a new directional light helper.
  40259. *
  40260. * @param {DirectionalLight} light - The light to be visualized.
  40261. * @param {number} [size=1] - The dimensions of the plane.
  40262. * @param {number|Color|string} [color] - The helper's color. If not set, the helper will take
  40263. * the color of the light.
  40264. */
  40265. constructor( light, size, color ) {
  40266. super();
  40267. /**
  40268. * The light being visualized.
  40269. *
  40270. * @type {DirectionalLight}
  40271. */
  40272. this.light = light;
  40273. this.matrix = light.matrixWorld;
  40274. this.matrixAutoUpdate = false;
  40275. /**
  40276. * The color parameter passed in the constructor.
  40277. * If not set, the helper will take the color of the light.
  40278. *
  40279. * @type {number|Color|string}
  40280. */
  40281. this.color = color;
  40282. this.type = 'DirectionalLightHelper';
  40283. if ( size === undefined ) size = 1;
  40284. let geometry = new BufferGeometry();
  40285. geometry.setAttribute( 'position', new Float32BufferAttribute( [
  40286. - size, size, 0,
  40287. size, size, 0,
  40288. size, - size, 0,
  40289. - size, - size, 0,
  40290. - size, size, 0
  40291. ], 3 ) );
  40292. const material = new LineBasicMaterial( { fog: false, toneMapped: false } );
  40293. /**
  40294. * Contains the line showing the location of the directional light.
  40295. *
  40296. * @type {Line}
  40297. */
  40298. this.lightPlane = new Line( geometry, material );
  40299. this.add( this.lightPlane );
  40300. geometry = new BufferGeometry();
  40301. geometry.setAttribute( 'position', new Float32BufferAttribute( [ 0, 0, 0, 0, 0, 1 ], 3 ) );
  40302. /**
  40303. * Represents the target line of the directional light.
  40304. *
  40305. * @type {Line}
  40306. */
  40307. this.targetLine = new Line( geometry, material );
  40308. this.add( this.targetLine );
  40309. this.update();
  40310. }
  40311. /**
  40312. * Frees the GPU-related resources allocated by this instance. Call this
  40313. * method whenever this instance is no longer used in your app.
  40314. */
  40315. dispose() {
  40316. this.lightPlane.geometry.dispose();
  40317. this.lightPlane.material.dispose();
  40318. this.targetLine.geometry.dispose();
  40319. this.targetLine.material.dispose();
  40320. }
  40321. /**
  40322. * Updates the helper to match the position and direction of the
  40323. * light being visualized.
  40324. */
  40325. update() {
  40326. this.light.updateWorldMatrix( true, false );
  40327. this.light.target.updateWorldMatrix( true, false );
  40328. _v1.setFromMatrixPosition( this.light.matrixWorld );
  40329. _v2.setFromMatrixPosition( this.light.target.matrixWorld );
  40330. _v3.subVectors( _v2, _v1 );
  40331. this.lightPlane.lookAt( _v2 );
  40332. if ( this.color !== undefined ) {
  40333. this.lightPlane.material.color.set( this.color );
  40334. this.targetLine.material.color.set( this.color );
  40335. } else {
  40336. this.lightPlane.material.color.copy( this.light.color );
  40337. this.targetLine.material.color.copy( this.light.color );
  40338. }
  40339. this.targetLine.lookAt( _v2 );
  40340. this.targetLine.scale.z = _v3.length();
  40341. }
  40342. }
  40343. const _vector = /*@__PURE__*/ new Vector3();
  40344. const _camera = /*@__PURE__*/ new Camera();
  40345. /**
  40346. * This helps with visualizing what a camera contains in its frustum. It
  40347. * visualizes the frustum of a camera using a line segments.
  40348. *
  40349. * Based on frustum visualization in [lightgl.js shadowmap example]{@link https://github.com/evanw/lightgl.js/blob/master/tests/shadowmap.html}.
  40350. *
  40351. * `CameraHelper` must be a child of the scene.
  40352. *
  40353. * ```js
  40354. * const camera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 0.1, 1000 );
  40355. * const helper = new THREE.CameraHelper( camera );
  40356. * scene.add( helper );
  40357. * ```
  40358. *
  40359. * @augments LineSegments
  40360. */
  40361. class CameraHelper extends LineSegments {
  40362. /**
  40363. * Constructs a new arrow helper.
  40364. *
  40365. * @param {Camera} camera - The camera to visualize.
  40366. */
  40367. constructor( camera ) {
  40368. const geometry = new BufferGeometry();
  40369. const material = new LineBasicMaterial( { color: 0xffffff, vertexColors: true, toneMapped: false } );
  40370. const vertices = [];
  40371. const colors = [];
  40372. const pointMap = {};
  40373. // near
  40374. addLine( 'n1', 'n2' );
  40375. addLine( 'n2', 'n4' );
  40376. addLine( 'n4', 'n3' );
  40377. addLine( 'n3', 'n1' );
  40378. // far
  40379. addLine( 'f1', 'f2' );
  40380. addLine( 'f2', 'f4' );
  40381. addLine( 'f4', 'f3' );
  40382. addLine( 'f3', 'f1' );
  40383. // sides
  40384. addLine( 'n1', 'f1' );
  40385. addLine( 'n2', 'f2' );
  40386. addLine( 'n3', 'f3' );
  40387. addLine( 'n4', 'f4' );
  40388. // cone
  40389. addLine( 'p', 'n1' );
  40390. addLine( 'p', 'n2' );
  40391. addLine( 'p', 'n3' );
  40392. addLine( 'p', 'n4' );
  40393. // up
  40394. addLine( 'u1', 'u2' );
  40395. addLine( 'u2', 'u3' );
  40396. addLine( 'u3', 'u1' );
  40397. // target
  40398. addLine( 'c', 't' );
  40399. addLine( 'p', 'c' );
  40400. // cross
  40401. addLine( 'cn1', 'cn2' );
  40402. addLine( 'cn3', 'cn4' );
  40403. addLine( 'cf1', 'cf2' );
  40404. addLine( 'cf3', 'cf4' );
  40405. function addLine( a, b ) {
  40406. addPoint( a );
  40407. addPoint( b );
  40408. }
  40409. function addPoint( id ) {
  40410. vertices.push( 0, 0, 0 );
  40411. colors.push( 0, 0, 0 );
  40412. if ( pointMap[ id ] === undefined ) {
  40413. pointMap[ id ] = [];
  40414. }
  40415. pointMap[ id ].push( ( vertices.length / 3 ) - 1 );
  40416. }
  40417. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  40418. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  40419. super( geometry, material );
  40420. this.type = 'CameraHelper';
  40421. /**
  40422. * The camera being visualized.
  40423. *
  40424. * @type {Camera}
  40425. */
  40426. this.camera = camera;
  40427. if ( this.camera.updateProjectionMatrix ) this.camera.updateProjectionMatrix();
  40428. this.matrix = camera.matrixWorld;
  40429. this.matrixAutoUpdate = false;
  40430. /**
  40431. * This contains the points used to visualize the camera.
  40432. *
  40433. * @type {Object<string,Array<number>>}
  40434. */
  40435. this.pointMap = pointMap;
  40436. this.update();
  40437. // colors
  40438. const colorFrustum = new Color( 0xffaa00 );
  40439. const colorCone = new Color( 0xff0000 );
  40440. const colorUp = new Color( 0x00aaff );
  40441. const colorTarget = new Color( 0xffffff );
  40442. const colorCross = new Color( 0x333333 );
  40443. this.setColors( colorFrustum, colorCone, colorUp, colorTarget, colorCross );
  40444. }
  40445. /**
  40446. * Defines the colors of the helper.
  40447. *
  40448. * @param {Color} frustum - The frustum line color.
  40449. * @param {Color} cone - The cone line color.
  40450. * @param {Color} up - The up line color.
  40451. * @param {Color} target - The target line color.
  40452. * @param {Color} cross - The cross line color.
  40453. */
  40454. setColors( frustum, cone, up, target, cross ) {
  40455. const geometry = this.geometry;
  40456. const colorAttribute = geometry.getAttribute( 'color' );
  40457. // near
  40458. colorAttribute.setXYZ( 0, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 1, frustum.r, frustum.g, frustum.b ); // n1, n2
  40459. colorAttribute.setXYZ( 2, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 3, frustum.r, frustum.g, frustum.b ); // n2, n4
  40460. colorAttribute.setXYZ( 4, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 5, frustum.r, frustum.g, frustum.b ); // n4, n3
  40461. colorAttribute.setXYZ( 6, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 7, frustum.r, frustum.g, frustum.b ); // n3, n1
  40462. // far
  40463. colorAttribute.setXYZ( 8, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 9, frustum.r, frustum.g, frustum.b ); // f1, f2
  40464. colorAttribute.setXYZ( 10, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 11, frustum.r, frustum.g, frustum.b ); // f2, f4
  40465. colorAttribute.setXYZ( 12, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 13, frustum.r, frustum.g, frustum.b ); // f4, f3
  40466. colorAttribute.setXYZ( 14, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 15, frustum.r, frustum.g, frustum.b ); // f3, f1
  40467. // sides
  40468. colorAttribute.setXYZ( 16, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 17, frustum.r, frustum.g, frustum.b ); // n1, f1
  40469. colorAttribute.setXYZ( 18, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 19, frustum.r, frustum.g, frustum.b ); // n2, f2
  40470. colorAttribute.setXYZ( 20, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 21, frustum.r, frustum.g, frustum.b ); // n3, f3
  40471. colorAttribute.setXYZ( 22, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 23, frustum.r, frustum.g, frustum.b ); // n4, f4
  40472. // cone
  40473. colorAttribute.setXYZ( 24, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 25, cone.r, cone.g, cone.b ); // p, n1
  40474. colorAttribute.setXYZ( 26, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 27, cone.r, cone.g, cone.b ); // p, n2
  40475. colorAttribute.setXYZ( 28, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 29, cone.r, cone.g, cone.b ); // p, n3
  40476. colorAttribute.setXYZ( 30, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 31, cone.r, cone.g, cone.b ); // p, n4
  40477. // up
  40478. colorAttribute.setXYZ( 32, up.r, up.g, up.b ); colorAttribute.setXYZ( 33, up.r, up.g, up.b ); // u1, u2
  40479. colorAttribute.setXYZ( 34, up.r, up.g, up.b ); colorAttribute.setXYZ( 35, up.r, up.g, up.b ); // u2, u3
  40480. colorAttribute.setXYZ( 36, up.r, up.g, up.b ); colorAttribute.setXYZ( 37, up.r, up.g, up.b ); // u3, u1
  40481. // target
  40482. colorAttribute.setXYZ( 38, target.r, target.g, target.b ); colorAttribute.setXYZ( 39, target.r, target.g, target.b ); // c, t
  40483. colorAttribute.setXYZ( 40, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 41, cross.r, cross.g, cross.b ); // p, c
  40484. // cross
  40485. colorAttribute.setXYZ( 42, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 43, cross.r, cross.g, cross.b ); // cn1, cn2
  40486. colorAttribute.setXYZ( 44, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 45, cross.r, cross.g, cross.b ); // cn3, cn4
  40487. colorAttribute.setXYZ( 46, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 47, cross.r, cross.g, cross.b ); // cf1, cf2
  40488. colorAttribute.setXYZ( 48, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 49, cross.r, cross.g, cross.b ); // cf3, cf4
  40489. colorAttribute.needsUpdate = true;
  40490. }
  40491. /**
  40492. * Updates the helper based on the projection matrix of the camera.
  40493. */
  40494. update() {
  40495. const geometry = this.geometry;
  40496. const pointMap = this.pointMap;
  40497. const w = 1, h = 1;
  40498. // we need just camera projection matrix inverse
  40499. // world matrix must be identity
  40500. _camera.projectionMatrixInverse.copy( this.camera.projectionMatrixInverse );
  40501. // Adjust z values based on coordinate system
  40502. const nearZ = this.camera.coordinateSystem === WebGLCoordinateSystem ? -1 : 0;
  40503. // center / target
  40504. setPoint( 'c', pointMap, geometry, _camera, 0, 0, nearZ );
  40505. setPoint( 't', pointMap, geometry, _camera, 0, 0, 1 );
  40506. // near
  40507. setPoint( 'n1', pointMap, geometry, _camera, -1, -1, nearZ );
  40508. setPoint( 'n2', pointMap, geometry, _camera, w, -1, nearZ );
  40509. setPoint( 'n3', pointMap, geometry, _camera, -1, h, nearZ );
  40510. setPoint( 'n4', pointMap, geometry, _camera, w, h, nearZ );
  40511. // far
  40512. setPoint( 'f1', pointMap, geometry, _camera, -1, -1, 1 );
  40513. setPoint( 'f2', pointMap, geometry, _camera, w, -1, 1 );
  40514. setPoint( 'f3', pointMap, geometry, _camera, -1, h, 1 );
  40515. setPoint( 'f4', pointMap, geometry, _camera, w, h, 1 );
  40516. // up
  40517. setPoint( 'u1', pointMap, geometry, _camera, w * 0.7, h * 1.1, nearZ );
  40518. setPoint( 'u2', pointMap, geometry, _camera, -1 * 0.7, h * 1.1, nearZ );
  40519. setPoint( 'u3', pointMap, geometry, _camera, 0, h * 2, nearZ );
  40520. // cross
  40521. setPoint( 'cf1', pointMap, geometry, _camera, -1, 0, 1 );
  40522. setPoint( 'cf2', pointMap, geometry, _camera, w, 0, 1 );
  40523. setPoint( 'cf3', pointMap, geometry, _camera, 0, -1, 1 );
  40524. setPoint( 'cf4', pointMap, geometry, _camera, 0, h, 1 );
  40525. setPoint( 'cn1', pointMap, geometry, _camera, -1, 0, nearZ );
  40526. setPoint( 'cn2', pointMap, geometry, _camera, w, 0, nearZ );
  40527. setPoint( 'cn3', pointMap, geometry, _camera, 0, -1, nearZ );
  40528. setPoint( 'cn4', pointMap, geometry, _camera, 0, h, nearZ );
  40529. geometry.getAttribute( 'position' ).needsUpdate = true;
  40530. }
  40531. /**
  40532. * Frees the GPU-related resources allocated by this instance. Call this
  40533. * method whenever this instance is no longer used in your app.
  40534. */
  40535. dispose() {
  40536. this.geometry.dispose();
  40537. this.material.dispose();
  40538. }
  40539. }
  40540. function setPoint( point, pointMap, geometry, camera, x, y, z ) {
  40541. _vector.set( x, y, z ).unproject( camera );
  40542. const points = pointMap[ point ];
  40543. if ( points !== undefined ) {
  40544. const position = geometry.getAttribute( 'position' );
  40545. for ( let i = 0, l = points.length; i < l; i ++ ) {
  40546. position.setXYZ( points[ i ], _vector.x, _vector.y, _vector.z );
  40547. }
  40548. }
  40549. }
  40550. const _box = /*@__PURE__*/ new Box3();
  40551. /**
  40552. * Helper object to graphically show the world-axis-aligned bounding box
  40553. * around an object. The actual bounding box is handled with {@link Box3},
  40554. * this is just a visual helper for debugging. It can be automatically
  40555. * resized with {@link BoxHelper#update} when the object it's created from
  40556. * is transformed. Note that the object must have a geometry for this to work,
  40557. * so it won't work with sprites.
  40558. *
  40559. * ```js
  40560. * const sphere = new THREE.SphereGeometry();
  40561. * const object = new THREE.Mesh( sphere, new THREE.MeshBasicMaterial( 0xff0000 ) );
  40562. * const box = new THREE.BoxHelper( object, 0xffff00 );
  40563. * scene.add( box );
  40564. * ```
  40565. *
  40566. * @augments LineSegments
  40567. */
  40568. class BoxHelper extends LineSegments {
  40569. /**
  40570. * Constructs a new box helper.
  40571. *
  40572. * @param {Object3D} [object] - The 3D object to show the world-axis-aligned bounding box.
  40573. * @param {number|Color|string} [color=0xffff00] - The box's color.
  40574. */
  40575. constructor( object, color = 0xffff00 ) {
  40576. 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 ] );
  40577. const positions = new Float32Array( 8 * 3 );
  40578. const geometry = new BufferGeometry();
  40579. geometry.setIndex( new BufferAttribute( indices, 1 ) );
  40580. geometry.setAttribute( 'position', new BufferAttribute( positions, 3 ) );
  40581. super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  40582. /**
  40583. * The 3D object being visualized.
  40584. *
  40585. * @type {Object3D}
  40586. */
  40587. this.object = object;
  40588. this.type = 'BoxHelper';
  40589. this.matrixAutoUpdate = false;
  40590. this.update();
  40591. }
  40592. /**
  40593. * Updates the helper's geometry to match the dimensions of the object,
  40594. * including any children.
  40595. */
  40596. update() {
  40597. if ( this.object !== undefined ) {
  40598. _box.setFromObject( this.object );
  40599. }
  40600. if ( _box.isEmpty() ) return;
  40601. const min = _box.min;
  40602. const max = _box.max;
  40603. /*
  40604. 5____4
  40605. 1/___0/|
  40606. | 6__|_7
  40607. 2/___3/
  40608. 0: max.x, max.y, max.z
  40609. 1: min.x, max.y, max.z
  40610. 2: min.x, min.y, max.z
  40611. 3: max.x, min.y, max.z
  40612. 4: max.x, max.y, min.z
  40613. 5: min.x, max.y, min.z
  40614. 6: min.x, min.y, min.z
  40615. 7: max.x, min.y, min.z
  40616. */
  40617. const position = this.geometry.attributes.position;
  40618. const array = position.array;
  40619. array[ 0 ] = max.x; array[ 1 ] = max.y; array[ 2 ] = max.z;
  40620. array[ 3 ] = min.x; array[ 4 ] = max.y; array[ 5 ] = max.z;
  40621. array[ 6 ] = min.x; array[ 7 ] = min.y; array[ 8 ] = max.z;
  40622. array[ 9 ] = max.x; array[ 10 ] = min.y; array[ 11 ] = max.z;
  40623. array[ 12 ] = max.x; array[ 13 ] = max.y; array[ 14 ] = min.z;
  40624. array[ 15 ] = min.x; array[ 16 ] = max.y; array[ 17 ] = min.z;
  40625. array[ 18 ] = min.x; array[ 19 ] = min.y; array[ 20 ] = min.z;
  40626. array[ 21 ] = max.x; array[ 22 ] = min.y; array[ 23 ] = min.z;
  40627. position.needsUpdate = true;
  40628. this.geometry.computeBoundingSphere();
  40629. }
  40630. /**
  40631. * Updates the wireframe box for the passed object.
  40632. *
  40633. * @param {Object3D} object - The 3D object to create the helper for.
  40634. * @return {BoxHelper} A reference to this instance.
  40635. */
  40636. setFromObject( object ) {
  40637. this.object = object;
  40638. this.update();
  40639. return this;
  40640. }
  40641. copy( source, recursive ) {
  40642. super.copy( source, recursive );
  40643. this.object = source.object;
  40644. return this;
  40645. }
  40646. /**
  40647. * Frees the GPU-related resources allocated by this instance. Call this
  40648. * method whenever this instance is no longer used in your app.
  40649. */
  40650. dispose() {
  40651. this.geometry.dispose();
  40652. this.material.dispose();
  40653. }
  40654. }
  40655. /**
  40656. * A helper object to visualize an instance of {@link Box3}.
  40657. *
  40658. * ```js
  40659. * const box = new THREE.Box3();
  40660. * box.setFromCenterAndSize( new THREE.Vector3( 1, 1, 1 ), new THREE.Vector3( 2, 1, 3 ) );
  40661. *
  40662. * const helper = new THREE.Box3Helper( box, 0xffff00 );
  40663. * scene.add( helper )
  40664. * ```
  40665. *
  40666. * @augments LineSegments
  40667. */
  40668. class Box3Helper extends LineSegments {
  40669. /**
  40670. * Constructs a new box3 helper.
  40671. *
  40672. * @param {Box3} box - The box to visualize.
  40673. * @param {number|Color|string} [color=0xffff00] - The box's color.
  40674. */
  40675. constructor( box, color = 0xffff00 ) {
  40676. 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 ] );
  40677. 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 ];
  40678. const geometry = new BufferGeometry();
  40679. geometry.setIndex( new BufferAttribute( indices, 1 ) );
  40680. geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  40681. super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  40682. /**
  40683. * The box being visualized.
  40684. *
  40685. * @type {Box3}
  40686. */
  40687. this.box = box;
  40688. this.type = 'Box3Helper';
  40689. this.geometry.computeBoundingSphere();
  40690. }
  40691. updateMatrixWorld( force ) {
  40692. const box = this.box;
  40693. if ( box.isEmpty() ) return;
  40694. box.getCenter( this.position );
  40695. box.getSize( this.scale );
  40696. this.scale.multiplyScalar( 0.5 );
  40697. super.updateMatrixWorld( force );
  40698. }
  40699. /**
  40700. * Frees the GPU-related resources allocated by this instance. Call this
  40701. * method whenever this instance is no longer used in your app.
  40702. */
  40703. dispose() {
  40704. this.geometry.dispose();
  40705. this.material.dispose();
  40706. }
  40707. }
  40708. /**
  40709. * A helper object to visualize an instance of {@link Plane}.
  40710. *
  40711. * ```js
  40712. * const plane = new THREE.Plane( new THREE.Vector3( 1, 1, 0.2 ), 3 );
  40713. * const helper = new THREE.PlaneHelper( plane, 1, 0xffff00 );
  40714. * scene.add( helper );
  40715. * ```
  40716. *
  40717. * @augments Line
  40718. */
  40719. class PlaneHelper extends Line {
  40720. /**
  40721. * Constructs a new plane helper.
  40722. *
  40723. * @param {Plane} plane - The plane to be visualized.
  40724. * @param {number} [size=1] - The side length of plane helper.
  40725. * @param {number|Color|string} [hex=0xffff00] - The helper's color.
  40726. */
  40727. constructor( plane, size = 1, hex = 0xffff00 ) {
  40728. const color = hex;
  40729. 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 ];
  40730. const geometry = new BufferGeometry();
  40731. geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  40732. geometry.computeBoundingSphere();
  40733. super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  40734. this.type = 'PlaneHelper';
  40735. /**
  40736. * The plane being visualized.
  40737. *
  40738. * @type {Plane}
  40739. */
  40740. this.plane = plane;
  40741. /**
  40742. * The side length of plane helper.
  40743. *
  40744. * @type {number}
  40745. * @default 1
  40746. */
  40747. this.size = size;
  40748. const positions2 = [ 1, 1, 0, -1, 1, 0, -1, -1, 0, 1, 1, 0, -1, -1, 0, 1, -1, 0 ];
  40749. const geometry2 = new BufferGeometry();
  40750. geometry2.setAttribute( 'position', new Float32BufferAttribute( positions2, 3 ) );
  40751. geometry2.computeBoundingSphere();
  40752. this.add( new Mesh( geometry2, new MeshBasicMaterial( { color: color, opacity: 0.2, transparent: true, depthWrite: false, toneMapped: false } ) ) );
  40753. }
  40754. updateMatrixWorld( force ) {
  40755. this.position.set( 0, 0, 0 );
  40756. this.scale.set( 0.5 * this.size, 0.5 * this.size, 1 );
  40757. this.lookAt( this.plane.normal );
  40758. this.translateZ( - this.plane.constant );
  40759. super.updateMatrixWorld( force );
  40760. }
  40761. /**
  40762. * Updates the helper to match the position and direction of the
  40763. * light being visualized.
  40764. */
  40765. dispose() {
  40766. this.geometry.dispose();
  40767. this.material.dispose();
  40768. this.children[ 0 ].geometry.dispose();
  40769. this.children[ 0 ].material.dispose();
  40770. }
  40771. }
  40772. const _axis = /*@__PURE__*/ new Vector3();
  40773. let _lineGeometry, _coneGeometry;
  40774. /**
  40775. * An 3D arrow object for visualizing directions.
  40776. *
  40777. * ```js
  40778. * const dir = new THREE.Vector3( 1, 2, 0 );
  40779. *
  40780. * //normalize the direction vector (convert to vector of length 1)
  40781. * dir.normalize();
  40782. *
  40783. * const origin = new THREE.Vector3( 0, 0, 0 );
  40784. * const length = 1;
  40785. * const hex = 0xffff00;
  40786. *
  40787. * const arrowHelper = new THREE.ArrowHelper( dir, origin, length, hex );
  40788. * scene.add( arrowHelper );
  40789. * ```
  40790. *
  40791. * @augments Object3D
  40792. */
  40793. class ArrowHelper extends Object3D {
  40794. /**
  40795. * Constructs a new arrow helper.
  40796. *
  40797. * @param {Vector3} [dir=(0, 0, 1)] - The (normalized) direction vector.
  40798. * @param {Vector3} [origin=(0, 0, 0)] - Point at which the arrow starts.
  40799. * @param {number} [length=1] - Length of the arrow in world units.
  40800. * @param {(number|Color|string)} [color=0xffff00] - Color of the arrow.
  40801. * @param {number} [headLength=length*0.2] - The length of the head of the arrow.
  40802. * @param {number} [headWidth=headLength*0.2] - The width of the head of the arrow.
  40803. */
  40804. 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 ) {
  40805. super();
  40806. this.type = 'ArrowHelper';
  40807. if ( _lineGeometry === undefined ) {
  40808. _lineGeometry = new BufferGeometry();
  40809. _lineGeometry.setAttribute( 'position', new Float32BufferAttribute( [ 0, 0, 0, 0, 1, 0 ], 3 ) );
  40810. _coneGeometry = new CylinderGeometry( 0, 0.5, 1, 5, 1 );
  40811. _coneGeometry.translate( 0, -0.5, 0 );
  40812. }
  40813. this.position.copy( origin );
  40814. /**
  40815. * The line part of the arrow helper.
  40816. *
  40817. * @type {Line}
  40818. */
  40819. this.line = new Line( _lineGeometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  40820. this.line.matrixAutoUpdate = false;
  40821. this.add( this.line );
  40822. /**
  40823. * The cone part of the arrow helper.
  40824. *
  40825. * @type {Mesh}
  40826. */
  40827. this.cone = new Mesh( _coneGeometry, new MeshBasicMaterial( { color: color, toneMapped: false } ) );
  40828. this.cone.matrixAutoUpdate = false;
  40829. this.add( this.cone );
  40830. this.setDirection( dir );
  40831. this.setLength( length, headLength, headWidth );
  40832. }
  40833. /**
  40834. * Sets the direction of the helper.
  40835. *
  40836. * @param {Vector3} dir - The normalized direction vector.
  40837. */
  40838. setDirection( dir ) {
  40839. // dir is assumed to be normalized
  40840. if ( dir.y > 0.99999 ) {
  40841. this.quaternion.set( 0, 0, 0, 1 );
  40842. } else if ( dir.y < -0.99999 ) {
  40843. this.quaternion.set( 1, 0, 0, 0 );
  40844. } else {
  40845. _axis.set( dir.z, 0, - dir.x ).normalize();
  40846. const radians = Math.acos( dir.y );
  40847. this.quaternion.setFromAxisAngle( _axis, radians );
  40848. }
  40849. }
  40850. /**
  40851. * Sets the length of the helper.
  40852. *
  40853. * @param {number} length - Length of the arrow in world units.
  40854. * @param {number} [headLength=length*0.2] - The length of the head of the arrow.
  40855. * @param {number} [headWidth=headLength*0.2] - The width of the head of the arrow.
  40856. */
  40857. setLength( length, headLength = length * 0.2, headWidth = headLength * 0.2 ) {
  40858. this.line.scale.set( 1, Math.max( 0.0001, length - headLength ), 1 ); // see #17458
  40859. this.line.updateMatrix();
  40860. this.cone.scale.set( headWidth, headLength, headWidth );
  40861. this.cone.position.y = length;
  40862. this.cone.updateMatrix();
  40863. }
  40864. /**
  40865. * Sets the color of the helper.
  40866. *
  40867. * @param {number|Color|string} color - The color to set.
  40868. */
  40869. setColor( color ) {
  40870. this.line.material.color.set( color );
  40871. this.cone.material.color.set( color );
  40872. }
  40873. copy( source ) {
  40874. super.copy( source, false );
  40875. this.line.copy( source.line );
  40876. this.cone.copy( source.cone );
  40877. return this;
  40878. }
  40879. /**
  40880. * Frees the GPU-related resources allocated by this instance. Call this
  40881. * method whenever this instance is no longer used in your app.
  40882. */
  40883. dispose() {
  40884. this.line.geometry.dispose();
  40885. this.line.material.dispose();
  40886. this.cone.geometry.dispose();
  40887. this.cone.material.dispose();
  40888. }
  40889. }
  40890. /**
  40891. * An axis object to visualize the 3 axes in a simple way.
  40892. * The X axis is red. The Y axis is green. The Z axis is blue.
  40893. *
  40894. * ```js
  40895. * const axesHelper = new THREE.AxesHelper( 5 );
  40896. * scene.add( axesHelper );
  40897. * ```
  40898. *
  40899. * @augments LineSegments
  40900. */
  40901. class AxesHelper extends LineSegments {
  40902. /**
  40903. * Constructs a new axes helper.
  40904. *
  40905. * @param {number} [size=1] - Size of the lines representing the axes.
  40906. */
  40907. constructor( size = 1 ) {
  40908. const vertices = [
  40909. 0, 0, 0, size, 0, 0,
  40910. 0, 0, 0, 0, size, 0,
  40911. 0, 0, 0, 0, 0, size
  40912. ];
  40913. const colors = [
  40914. 1, 0, 0, 1, 0.6, 0,
  40915. 0, 1, 0, 0.6, 1, 0,
  40916. 0, 0, 1, 0, 0.6, 1
  40917. ];
  40918. const geometry = new BufferGeometry();
  40919. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  40920. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  40921. const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
  40922. super( geometry, material );
  40923. this.type = 'AxesHelper';
  40924. }
  40925. /**
  40926. * Defines the colors of the axes helper.
  40927. *
  40928. * @param {number|Color|string} xAxisColor - The color for the x axis.
  40929. * @param {number|Color|string} yAxisColor - The color for the y axis.
  40930. * @param {number|Color|string} zAxisColor - The color for the z axis.
  40931. * @return {AxesHelper} A reference to this axes helper.
  40932. */
  40933. setColors( xAxisColor, yAxisColor, zAxisColor ) {
  40934. const color = new Color();
  40935. const array = this.geometry.attributes.color.array;
  40936. color.set( xAxisColor );
  40937. color.toArray( array, 0 );
  40938. color.toArray( array, 3 );
  40939. color.set( yAxisColor );
  40940. color.toArray( array, 6 );
  40941. color.toArray( array, 9 );
  40942. color.set( zAxisColor );
  40943. color.toArray( array, 12 );
  40944. color.toArray( array, 15 );
  40945. this.geometry.attributes.color.needsUpdate = true;
  40946. return this;
  40947. }
  40948. /**
  40949. * Frees the GPU-related resources allocated by this instance. Call this
  40950. * method whenever this instance is no longer used in your app.
  40951. */
  40952. dispose() {
  40953. this.geometry.dispose();
  40954. this.material.dispose();
  40955. }
  40956. }
  40957. /**
  40958. * This class is used to convert a series of paths to an array of
  40959. * shapes. It is specifically used in context of fonts and SVG.
  40960. */
  40961. class ShapePath {
  40962. /**
  40963. * Constructs a new shape path.
  40964. */
  40965. constructor() {
  40966. this.type = 'ShapePath';
  40967. /**
  40968. * The color of the shape.
  40969. *
  40970. * @type {Color}
  40971. */
  40972. this.color = new Color();
  40973. /**
  40974. * The paths that have been generated for this shape.
  40975. *
  40976. * @type {Array<Path>}
  40977. * @default null
  40978. */
  40979. this.subPaths = [];
  40980. /**
  40981. * The current path that is being generated.
  40982. *
  40983. * @type {?Path}
  40984. * @default null
  40985. */
  40986. this.currentPath = null;
  40987. }
  40988. /**
  40989. * Creates a new path and moves it current point to the given one.
  40990. *
  40991. * @param {number} x - The x coordinate.
  40992. * @param {number} y - The y coordinate.
  40993. * @return {ShapePath} A reference to this shape path.
  40994. */
  40995. moveTo( x, y ) {
  40996. this.currentPath = new Path();
  40997. this.subPaths.push( this.currentPath );
  40998. this.currentPath.moveTo( x, y );
  40999. return this;
  41000. }
  41001. /**
  41002. * Adds an instance of {@link LineCurve} to the path by connecting
  41003. * the current point with the given one.
  41004. *
  41005. * @param {number} x - The x coordinate of the end point.
  41006. * @param {number} y - The y coordinate of the end point.
  41007. * @return {ShapePath} A reference to this shape path.
  41008. */
  41009. lineTo( x, y ) {
  41010. this.currentPath.lineTo( x, y );
  41011. return this;
  41012. }
  41013. /**
  41014. * Adds an instance of {@link QuadraticBezierCurve} to the path by connecting
  41015. * the current point with the given one.
  41016. *
  41017. * @param {number} aCPx - The x coordinate of the control point.
  41018. * @param {number} aCPy - The y coordinate of the control point.
  41019. * @param {number} aX - The x coordinate of the end point.
  41020. * @param {number} aY - The y coordinate of the end point.
  41021. * @return {ShapePath} A reference to this shape path.
  41022. */
  41023. quadraticCurveTo( aCPx, aCPy, aX, aY ) {
  41024. this.currentPath.quadraticCurveTo( aCPx, aCPy, aX, aY );
  41025. return this;
  41026. }
  41027. /**
  41028. * Adds an instance of {@link CubicBezierCurve} to the path by connecting
  41029. * the current point with the given one.
  41030. *
  41031. * @param {number} aCP1x - The x coordinate of the first control point.
  41032. * @param {number} aCP1y - The y coordinate of the first control point.
  41033. * @param {number} aCP2x - The x coordinate of the second control point.
  41034. * @param {number} aCP2y - The y coordinate of the second control point.
  41035. * @param {number} aX - The x coordinate of the end point.
  41036. * @param {number} aY - The y coordinate of the end point.
  41037. * @return {ShapePath} A reference to this shape path.
  41038. */
  41039. bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) {
  41040. this.currentPath.bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY );
  41041. return this;
  41042. }
  41043. /**
  41044. * Adds an instance of {@link SplineCurve} to the path by connecting
  41045. * the current point with the given list of points.
  41046. *
  41047. * @param {Array<Vector2>} pts - An array of points in 2D space.
  41048. * @return {ShapePath} A reference to this shape path.
  41049. */
  41050. splineThru( pts ) {
  41051. this.currentPath.splineThru( pts );
  41052. return this;
  41053. }
  41054. /**
  41055. * Converts the paths into an array of shapes.
  41056. *
  41057. * @param {boolean} isCCW - By default solid shapes are defined clockwise (CW) and holes are defined counterclockwise (CCW).
  41058. * If this flag is set to `true`, then those are flipped.
  41059. * @return {Array<Shape>} An array of shapes.
  41060. */
  41061. toShapes( isCCW ) {
  41062. function toShapesNoHoles( inSubpaths ) {
  41063. const shapes = [];
  41064. for ( let i = 0, l = inSubpaths.length; i < l; i ++ ) {
  41065. const tmpPath = inSubpaths[ i ];
  41066. const tmpShape = new Shape();
  41067. tmpShape.curves = tmpPath.curves;
  41068. shapes.push( tmpShape );
  41069. }
  41070. return shapes;
  41071. }
  41072. function isPointInsidePolygon( inPt, inPolygon ) {
  41073. const polyLen = inPolygon.length;
  41074. // inPt on polygon contour => immediate success or
  41075. // toggling of inside/outside at every single! intersection point of an edge
  41076. // with the horizontal line through inPt, left of inPt
  41077. // not counting lowerY endpoints of edges and whole edges on that line
  41078. let inside = false;
  41079. for ( let p = polyLen - 1, q = 0; q < polyLen; p = q ++ ) {
  41080. let edgeLowPt = inPolygon[ p ];
  41081. let edgeHighPt = inPolygon[ q ];
  41082. let edgeDx = edgeHighPt.x - edgeLowPt.x;
  41083. let edgeDy = edgeHighPt.y - edgeLowPt.y;
  41084. if ( Math.abs( edgeDy ) > Number.EPSILON ) {
  41085. // not parallel
  41086. if ( edgeDy < 0 ) {
  41087. edgeLowPt = inPolygon[ q ]; edgeDx = - edgeDx;
  41088. edgeHighPt = inPolygon[ p ]; edgeDy = - edgeDy;
  41089. }
  41090. if ( ( inPt.y < edgeLowPt.y ) || ( inPt.y > edgeHighPt.y ) ) continue;
  41091. if ( inPt.y === edgeLowPt.y ) {
  41092. if ( inPt.x === edgeLowPt.x ) return true; // inPt is on contour ?
  41093. // continue; // no intersection or edgeLowPt => doesn't count !!!
  41094. } else {
  41095. const perpEdge = edgeDy * ( inPt.x - edgeLowPt.x ) - edgeDx * ( inPt.y - edgeLowPt.y );
  41096. if ( perpEdge === 0 ) return true; // inPt is on contour ?
  41097. if ( perpEdge < 0 ) continue;
  41098. inside = ! inside; // true intersection left of inPt
  41099. }
  41100. } else {
  41101. // parallel or collinear
  41102. if ( inPt.y !== edgeLowPt.y ) continue; // parallel
  41103. // edge lies on the same horizontal line as inPt
  41104. if ( ( ( edgeHighPt.x <= inPt.x ) && ( inPt.x <= edgeLowPt.x ) ) ||
  41105. ( ( edgeLowPt.x <= inPt.x ) && ( inPt.x <= edgeHighPt.x ) ) ) return true; // inPt: Point on contour !
  41106. // continue;
  41107. }
  41108. }
  41109. return inside;
  41110. }
  41111. const isClockWise = ShapeUtils.isClockWise;
  41112. const subPaths = this.subPaths;
  41113. if ( subPaths.length === 0 ) return [];
  41114. let solid, tmpPath, tmpShape;
  41115. const shapes = [];
  41116. if ( subPaths.length === 1 ) {
  41117. tmpPath = subPaths[ 0 ];
  41118. tmpShape = new Shape();
  41119. tmpShape.curves = tmpPath.curves;
  41120. shapes.push( tmpShape );
  41121. return shapes;
  41122. }
  41123. let holesFirst = ! isClockWise( subPaths[ 0 ].getPoints() );
  41124. holesFirst = isCCW ? ! holesFirst : holesFirst;
  41125. // console.log("Holes first", holesFirst);
  41126. const betterShapeHoles = [];
  41127. const newShapes = [];
  41128. let newShapeHoles = [];
  41129. let mainIdx = 0;
  41130. let tmpPoints;
  41131. newShapes[ mainIdx ] = undefined;
  41132. newShapeHoles[ mainIdx ] = [];
  41133. for ( let i = 0, l = subPaths.length; i < l; i ++ ) {
  41134. tmpPath = subPaths[ i ];
  41135. tmpPoints = tmpPath.getPoints();
  41136. solid = isClockWise( tmpPoints );
  41137. solid = isCCW ? ! solid : solid;
  41138. if ( solid ) {
  41139. if ( ( ! holesFirst ) && ( newShapes[ mainIdx ] ) ) mainIdx ++;
  41140. newShapes[ mainIdx ] = { s: new Shape(), p: tmpPoints };
  41141. newShapes[ mainIdx ].s.curves = tmpPath.curves;
  41142. if ( holesFirst ) mainIdx ++;
  41143. newShapeHoles[ mainIdx ] = [];
  41144. //console.log('cw', i);
  41145. } else {
  41146. newShapeHoles[ mainIdx ].push( { h: tmpPath, p: tmpPoints[ 0 ] } );
  41147. //console.log('ccw', i);
  41148. }
  41149. }
  41150. // only Holes? -> probably all Shapes with wrong orientation
  41151. if ( ! newShapes[ 0 ] ) return toShapesNoHoles( subPaths );
  41152. if ( newShapes.length > 1 ) {
  41153. let ambiguous = false;
  41154. let toChange = 0;
  41155. for ( let sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) {
  41156. betterShapeHoles[ sIdx ] = [];
  41157. }
  41158. for ( let sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) {
  41159. const sho = newShapeHoles[ sIdx ];
  41160. for ( let hIdx = 0; hIdx < sho.length; hIdx ++ ) {
  41161. const ho = sho[ hIdx ];
  41162. let hole_unassigned = true;
  41163. for ( let s2Idx = 0; s2Idx < newShapes.length; s2Idx ++ ) {
  41164. if ( isPointInsidePolygon( ho.p, newShapes[ s2Idx ].p ) ) {
  41165. if ( sIdx !== s2Idx ) toChange ++;
  41166. if ( hole_unassigned ) {
  41167. hole_unassigned = false;
  41168. betterShapeHoles[ s2Idx ].push( ho );
  41169. } else {
  41170. ambiguous = true;
  41171. }
  41172. }
  41173. }
  41174. if ( hole_unassigned ) {
  41175. betterShapeHoles[ sIdx ].push( ho );
  41176. }
  41177. }
  41178. }
  41179. if ( toChange > 0 && ambiguous === false ) {
  41180. newShapeHoles = betterShapeHoles;
  41181. }
  41182. }
  41183. let tmpHoles;
  41184. for ( let i = 0, il = newShapes.length; i < il; i ++ ) {
  41185. tmpShape = newShapes[ i ].s;
  41186. shapes.push( tmpShape );
  41187. tmpHoles = newShapeHoles[ i ];
  41188. for ( let j = 0, jl = tmpHoles.length; j < jl; j ++ ) {
  41189. tmpShape.holes.push( tmpHoles[ j ].h );
  41190. }
  41191. }
  41192. //console.log("shape", shapes);
  41193. return shapes;
  41194. }
  41195. }
  41196. /**
  41197. * Abstract base class for controls.
  41198. *
  41199. * @abstract
  41200. * @augments EventDispatcher
  41201. */
  41202. class Controls extends EventDispatcher {
  41203. /**
  41204. * Constructs a new controls instance.
  41205. *
  41206. * @param {Object3D} object - The object that is managed by the controls.
  41207. * @param {?HTMLDOMElement} domElement - The HTML element used for event listeners.
  41208. */
  41209. constructor( object, domElement = null ) {
  41210. super();
  41211. /**
  41212. * The object that is managed by the controls.
  41213. *
  41214. * @type {Object3D}
  41215. */
  41216. this.object = object;
  41217. /**
  41218. * The HTML element used for event listeners.
  41219. *
  41220. * @type {?HTMLDOMElement}
  41221. * @default null
  41222. */
  41223. this.domElement = domElement;
  41224. /**
  41225. * Whether the controls responds to user input or not.
  41226. *
  41227. * @type {boolean}
  41228. * @default true
  41229. */
  41230. this.enabled = true;
  41231. /**
  41232. * The internal state of the controls.
  41233. *
  41234. * @type {number}
  41235. * @default -1
  41236. */
  41237. this.state = -1;
  41238. /**
  41239. * This object defines the keyboard input of the controls.
  41240. *
  41241. * @type {Object}
  41242. */
  41243. this.keys = {};
  41244. /**
  41245. * This object defines what type of actions are assigned to the available mouse buttons.
  41246. * It depends on the control implementation what kind of mouse buttons and actions are supported.
  41247. *
  41248. * @type {{LEFT: ?number, MIDDLE: ?number, RIGHT: ?number}}
  41249. */
  41250. this.mouseButtons = { LEFT: null, MIDDLE: null, RIGHT: null };
  41251. /**
  41252. * This object defines what type of actions are assigned to what kind of touch interaction.
  41253. * It depends on the control implementation what kind of touch interaction and actions are supported.
  41254. *
  41255. * @type {{ONE: ?number, TWO: ?number}}
  41256. */
  41257. this.touches = { ONE: null, TWO: null };
  41258. }
  41259. /**
  41260. * Connects the controls to the DOM. This method has so called "side effects" since
  41261. * it adds the module's event listeners to the DOM.
  41262. */
  41263. connect() {}
  41264. /**
  41265. * Disconnects the controls from the DOM.
  41266. */
  41267. disconnect() {}
  41268. /**
  41269. * Call this method if you no longer want use to the controls. It frees all internal
  41270. * resources and removes all event listeners.
  41271. */
  41272. dispose() {}
  41273. /**
  41274. * Controls should implement this method if they have to update their internal state
  41275. * per simulation step.
  41276. *
  41277. * @param {number} [delta] - The time delta in seconds.
  41278. */
  41279. update( /* delta */ ) {}
  41280. }
  41281. /**
  41282. * Scales the texture as large as possible within its surface without cropping
  41283. * or stretching the texture. The method preserves the original aspect ratio of
  41284. * the texture. Akin to CSS `object-fit: contain`
  41285. *
  41286. * @param {Texture} texture - The texture.
  41287. * @param {number} aspect - The texture's aspect ratio.
  41288. * @return {Texture} The updated texture.
  41289. */
  41290. function contain( texture, aspect ) {
  41291. const imageAspect = ( texture.image && texture.image.width ) ? texture.image.width / texture.image.height : 1;
  41292. if ( imageAspect > aspect ) {
  41293. texture.repeat.x = 1;
  41294. texture.repeat.y = imageAspect / aspect;
  41295. texture.offset.x = 0;
  41296. texture.offset.y = ( 1 - texture.repeat.y ) / 2;
  41297. } else {
  41298. texture.repeat.x = aspect / imageAspect;
  41299. texture.repeat.y = 1;
  41300. texture.offset.x = ( 1 - texture.repeat.x ) / 2;
  41301. texture.offset.y = 0;
  41302. }
  41303. return texture;
  41304. }
  41305. /**
  41306. * Scales the texture to the smallest possible size to fill the surface, leaving
  41307. * no empty space. The method preserves the original aspect ratio of the texture.
  41308. * Akin to CSS `object-fit: cover`.
  41309. *
  41310. * @param {Texture} texture - The texture.
  41311. * @param {number} aspect - The texture's aspect ratio.
  41312. * @return {Texture} The updated texture.
  41313. */
  41314. function cover( texture, aspect ) {
  41315. const imageAspect = ( texture.image && texture.image.width ) ? texture.image.width / texture.image.height : 1;
  41316. if ( imageAspect > aspect ) {
  41317. texture.repeat.x = aspect / imageAspect;
  41318. texture.repeat.y = 1;
  41319. texture.offset.x = ( 1 - texture.repeat.x ) / 2;
  41320. texture.offset.y = 0;
  41321. } else {
  41322. texture.repeat.x = 1;
  41323. texture.repeat.y = imageAspect / aspect;
  41324. texture.offset.x = 0;
  41325. texture.offset.y = ( 1 - texture.repeat.y ) / 2;
  41326. }
  41327. return texture;
  41328. }
  41329. /**
  41330. * Configures the texture to the default transformation. Akin to CSS `object-fit: fill`.
  41331. *
  41332. * @param {Texture} texture - The texture.
  41333. * @return {Texture} The updated texture.
  41334. */
  41335. function fill( texture ) {
  41336. texture.repeat.x = 1;
  41337. texture.repeat.y = 1;
  41338. texture.offset.x = 0;
  41339. texture.offset.y = 0;
  41340. return texture;
  41341. }
  41342. /**
  41343. * Determines how many bytes must be used to represent the texture.
  41344. *
  41345. * @param {number} width - The width of the texture.
  41346. * @param {number} height - The height of the texture.
  41347. * @param {number} format - The texture's format.
  41348. * @param {number} type - The texture's type.
  41349. * @return {number} The byte length.
  41350. */
  41351. function getByteLength( width, height, format, type ) {
  41352. const typeByteLength = getTextureTypeByteLength( type );
  41353. switch ( format ) {
  41354. // https://registry.khronos.org/OpenGL-Refpages/es3.0/html/glTexImage2D.xhtml
  41355. case AlphaFormat:
  41356. return width * height;
  41357. case LuminanceFormat:
  41358. return width * height;
  41359. case LuminanceAlphaFormat:
  41360. return width * height * 2;
  41361. case RedFormat:
  41362. return ( ( width * height ) / typeByteLength.components ) * typeByteLength.byteLength;
  41363. case RedIntegerFormat:
  41364. return ( ( width * height ) / typeByteLength.components ) * typeByteLength.byteLength;
  41365. case RGFormat:
  41366. return ( ( width * height * 2 ) / typeByteLength.components ) * typeByteLength.byteLength;
  41367. case RGIntegerFormat:
  41368. return ( ( width * height * 2 ) / typeByteLength.components ) * typeByteLength.byteLength;
  41369. case RGBFormat:
  41370. return ( ( width * height * 3 ) / typeByteLength.components ) * typeByteLength.byteLength;
  41371. case RGBAFormat:
  41372. return ( ( width * height * 4 ) / typeByteLength.components ) * typeByteLength.byteLength;
  41373. case RGBAIntegerFormat:
  41374. return ( ( width * height * 4 ) / typeByteLength.components ) * typeByteLength.byteLength;
  41375. // https://registry.khronos.org/webgl/extensions/WEBGL_compressed_texture_s3tc_srgb/
  41376. case RGB_S3TC_DXT1_Format:
  41377. case RGBA_S3TC_DXT1_Format:
  41378. return Math.floor( ( width + 3 ) / 4 ) * Math.floor( ( height + 3 ) / 4 ) * 8;
  41379. case RGBA_S3TC_DXT3_Format:
  41380. case RGBA_S3TC_DXT5_Format:
  41381. return Math.floor( ( width + 3 ) / 4 ) * Math.floor( ( height + 3 ) / 4 ) * 16;
  41382. // https://registry.khronos.org/webgl/extensions/WEBGL_compressed_texture_pvrtc/
  41383. case RGB_PVRTC_2BPPV1_Format:
  41384. case RGBA_PVRTC_2BPPV1_Format:
  41385. return ( Math.max( width, 16 ) * Math.max( height, 8 ) ) / 4;
  41386. case RGB_PVRTC_4BPPV1_Format:
  41387. case RGBA_PVRTC_4BPPV1_Format:
  41388. return ( Math.max( width, 8 ) * Math.max( height, 8 ) ) / 2;
  41389. // https://registry.khronos.org/webgl/extensions/WEBGL_compressed_texture_etc/
  41390. case RGB_ETC1_Format:
  41391. case RGB_ETC2_Format:
  41392. return Math.floor( ( width + 3 ) / 4 ) * Math.floor( ( height + 3 ) / 4 ) * 8;
  41393. case RGBA_ETC2_EAC_Format:
  41394. return Math.floor( ( width + 3 ) / 4 ) * Math.floor( ( height + 3 ) / 4 ) * 16;
  41395. // https://registry.khronos.org/webgl/extensions/WEBGL_compressed_texture_astc/
  41396. case RGBA_ASTC_4x4_Format:
  41397. return Math.floor( ( width + 3 ) / 4 ) * Math.floor( ( height + 3 ) / 4 ) * 16;
  41398. case RGBA_ASTC_5x4_Format:
  41399. return Math.floor( ( width + 4 ) / 5 ) * Math.floor( ( height + 3 ) / 4 ) * 16;
  41400. case RGBA_ASTC_5x5_Format:
  41401. return Math.floor( ( width + 4 ) / 5 ) * Math.floor( ( height + 4 ) / 5 ) * 16;
  41402. case RGBA_ASTC_6x5_Format:
  41403. return Math.floor( ( width + 5 ) / 6 ) * Math.floor( ( height + 4 ) / 5 ) * 16;
  41404. case RGBA_ASTC_6x6_Format:
  41405. return Math.floor( ( width + 5 ) / 6 ) * Math.floor( ( height + 5 ) / 6 ) * 16;
  41406. case RGBA_ASTC_8x5_Format:
  41407. return Math.floor( ( width + 7 ) / 8 ) * Math.floor( ( height + 4 ) / 5 ) * 16;
  41408. case RGBA_ASTC_8x6_Format:
  41409. return Math.floor( ( width + 7 ) / 8 ) * Math.floor( ( height + 5 ) / 6 ) * 16;
  41410. case RGBA_ASTC_8x8_Format:
  41411. return Math.floor( ( width + 7 ) / 8 ) * Math.floor( ( height + 7 ) / 8 ) * 16;
  41412. case RGBA_ASTC_10x5_Format:
  41413. return Math.floor( ( width + 9 ) / 10 ) * Math.floor( ( height + 4 ) / 5 ) * 16;
  41414. case RGBA_ASTC_10x6_Format:
  41415. return Math.floor( ( width + 9 ) / 10 ) * Math.floor( ( height + 5 ) / 6 ) * 16;
  41416. case RGBA_ASTC_10x8_Format:
  41417. return Math.floor( ( width + 9 ) / 10 ) * Math.floor( ( height + 7 ) / 8 ) * 16;
  41418. case RGBA_ASTC_10x10_Format:
  41419. return Math.floor( ( width + 9 ) / 10 ) * Math.floor( ( height + 9 ) / 10 ) * 16;
  41420. case RGBA_ASTC_12x10_Format:
  41421. return Math.floor( ( width + 11 ) / 12 ) * Math.floor( ( height + 9 ) / 10 ) * 16;
  41422. case RGBA_ASTC_12x12_Format:
  41423. return Math.floor( ( width + 11 ) / 12 ) * Math.floor( ( height + 11 ) / 12 ) * 16;
  41424. // https://registry.khronos.org/webgl/extensions/EXT_texture_compression_bptc/
  41425. case RGBA_BPTC_Format:
  41426. case RGB_BPTC_SIGNED_Format:
  41427. case RGB_BPTC_UNSIGNED_Format:
  41428. return Math.ceil( width / 4 ) * Math.ceil( height / 4 ) * 16;
  41429. // https://registry.khronos.org/webgl/extensions/EXT_texture_compression_rgtc/
  41430. case RED_RGTC1_Format:
  41431. case SIGNED_RED_RGTC1_Format:
  41432. return Math.ceil( width / 4 ) * Math.ceil( height / 4 ) * 8;
  41433. case RED_GREEN_RGTC2_Format:
  41434. case SIGNED_RED_GREEN_RGTC2_Format:
  41435. return Math.ceil( width / 4 ) * Math.ceil( height / 4 ) * 16;
  41436. }
  41437. throw new Error(
  41438. `Unable to determine texture byte length for ${format} format.`,
  41439. );
  41440. }
  41441. function getTextureTypeByteLength( type ) {
  41442. switch ( type ) {
  41443. case UnsignedByteType:
  41444. case ByteType:
  41445. return { byteLength: 1, components: 1 };
  41446. case UnsignedShortType:
  41447. case ShortType:
  41448. case HalfFloatType:
  41449. return { byteLength: 2, components: 1 };
  41450. case UnsignedShort4444Type:
  41451. case UnsignedShort5551Type:
  41452. return { byteLength: 2, components: 4 };
  41453. case UnsignedIntType:
  41454. case IntType:
  41455. case FloatType:
  41456. return { byteLength: 4, components: 1 };
  41457. case UnsignedInt5999Type:
  41458. return { byteLength: 4, components: 3 };
  41459. }
  41460. throw new Error( `Unknown texture type ${type}.` );
  41461. }
  41462. /**
  41463. * A class containing utility functions for textures.
  41464. *
  41465. * @hideconstructor
  41466. */
  41467. class TextureUtils {
  41468. /**
  41469. * Scales the texture as large as possible within its surface without cropping
  41470. * or stretching the texture. The method preserves the original aspect ratio of
  41471. * the texture. Akin to CSS `object-fit: contain`
  41472. *
  41473. * @param {Texture} texture - The texture.
  41474. * @param {number} aspect - The texture's aspect ratio.
  41475. * @return {Texture} The updated texture.
  41476. */
  41477. static contain( texture, aspect ) {
  41478. return contain( texture, aspect );
  41479. }
  41480. /**
  41481. * Scales the texture to the smallest possible size to fill the surface, leaving
  41482. * no empty space. The method preserves the original aspect ratio of the texture.
  41483. * Akin to CSS `object-fit: cover`.
  41484. *
  41485. * @param {Texture} texture - The texture.
  41486. * @param {number} aspect - The texture's aspect ratio.
  41487. * @return {Texture} The updated texture.
  41488. */
  41489. static cover( texture, aspect ) {
  41490. return cover( texture, aspect );
  41491. }
  41492. /**
  41493. * Configures the texture to the default transformation. Akin to CSS `object-fit: fill`.
  41494. *
  41495. * @param {Texture} texture - The texture.
  41496. * @return {Texture} The updated texture.
  41497. */
  41498. static fill( texture ) {
  41499. return fill( texture );
  41500. }
  41501. /**
  41502. * Determines how many bytes must be used to represent the texture.
  41503. *
  41504. * @param {number} width - The width of the texture.
  41505. * @param {number} height - The height of the texture.
  41506. * @param {number} format - The texture's format.
  41507. * @param {number} type - The texture's type.
  41508. * @return {number} The byte length.
  41509. */
  41510. static getByteLength( width, height, format, type ) {
  41511. return getByteLength( width, height, format, type );
  41512. }
  41513. }
  41514. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  41515. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'register', { detail: {
  41516. revision: REVISION,
  41517. } } ) );
  41518. }
  41519. if ( typeof window !== 'undefined' ) {
  41520. if ( window.__THREE__ ) {
  41521. console.warn( 'WARNING: Multiple instances of Three.js being imported.' );
  41522. } else {
  41523. window.__THREE__ = REVISION;
  41524. }
  41525. }
  41526. 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, ExtrudeGeometry, FileLoader, Float16BufferAttribute, Float32BufferAttribute, FloatType, Fog, FogExp2, FramebufferTexture, FrontSide, Frustum, 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, 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, LuminanceAlphaFormat, LuminanceFormat, 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, RenderTargetArray, 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, TimestampQuery, TorusGeometry, TorusKnotGeometry, Triangle, TriangleFanDrawMode, TriangleStripDrawMode, TrianglesDrawMode, TubeGeometry, UVMapping, Uint16BufferAttribute, Uint32BufferAttribute, Uint8BufferAttribute, Uint8ClampedBufferAttribute, Uniform, UniformsGroup, UniformsUtils, UnsignedByteType, 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, toNormalizedProjectionMatrix, toReversedProjectionMatrix, warnOnce };
粤ICP备19079148号