three.core.js 1.3 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080
  1. /**
  2. * @license
  3. * Copyright 2010-2025 Three.js Authors
  4. * SPDX-License-Identifier: MIT
  5. */
  6. const REVISION = '177dev';
  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 depth value, converts it to floating point, and clamps to the range `[0,1]`.
  664. *
  665. * @type {number}
  666. * @constant
  667. */
  668. const DepthFormat = 1026;
  669. /**
  670. * Reads each element is a pair of depth and stencil values. The depth component of the pair is interpreted as
  671. * in `DepthFormat`. The stencil component is interpreted based on the depth + stencil internal format.
  672. *
  673. * @type {number}
  674. * @constant
  675. */
  676. const DepthStencilFormat = 1027;
  677. /**
  678. * Discards the green, blue and alpha components and reads just the red component.
  679. *
  680. * @type {number}
  681. * @constant
  682. */
  683. const RedFormat = 1028;
  684. /**
  685. * Discards the green, blue and alpha components and reads just the red component. The texels are read as integers instead of floating point.
  686. *
  687. * @type {number}
  688. * @constant
  689. */
  690. const RedIntegerFormat = 1029;
  691. /**
  692. * Discards the alpha, and blue components and reads the red, and green components.
  693. *
  694. * @type {number}
  695. * @constant
  696. */
  697. const RGFormat = 1030;
  698. /**
  699. * Discards the alpha, and blue components and reads the red, and green components. The texels are read as integers instead of floating point.
  700. *
  701. * @type {number}
  702. * @constant
  703. */
  704. const RGIntegerFormat = 1031;
  705. /**
  706. * Discards the alpha component and reads the red, green and blue component. The texels are read as integers instead of floating point.
  707. *
  708. * @type {number}
  709. * @constant
  710. */
  711. const RGBIntegerFormat = 1032;
  712. /**
  713. * Reads the red, green, blue and alpha components. The texels are read as integers instead of floating point.
  714. *
  715. * @type {number}
  716. * @constant
  717. */
  718. const RGBAIntegerFormat = 1033;
  719. /**
  720. * A DXT1-compressed image in an RGB image format.
  721. *
  722. * @type {number}
  723. * @constant
  724. */
  725. const RGB_S3TC_DXT1_Format = 33776;
  726. /**
  727. * A DXT1-compressed image in an RGB image format with a simple on/off alpha value.
  728. *
  729. * @type {number}
  730. * @constant
  731. */
  732. const RGBA_S3TC_DXT1_Format = 33777;
  733. /**
  734. * A DXT3-compressed image in an RGBA image format. Compared to a 32-bit RGBA texture, it offers 4:1 compression.
  735. *
  736. * @type {number}
  737. * @constant
  738. */
  739. const RGBA_S3TC_DXT3_Format = 33778;
  740. /**
  741. * A DXT5-compressed image in an RGBA image format. It also provides a 4:1 compression, but differs to the DXT3
  742. * compression in how the alpha compression is done.
  743. *
  744. * @type {number}
  745. * @constant
  746. */
  747. const RGBA_S3TC_DXT5_Format = 33779;
  748. /**
  749. * PVRTC RGB compression in 4-bit mode. One block for each 4×4 pixels.
  750. *
  751. * @type {number}
  752. * @constant
  753. */
  754. const RGB_PVRTC_4BPPV1_Format = 35840;
  755. /**
  756. * PVRTC RGB compression in 2-bit mode. One block for each 8×4 pixels.
  757. *
  758. * @type {number}
  759. * @constant
  760. */
  761. const RGB_PVRTC_2BPPV1_Format = 35841;
  762. /**
  763. * PVRTC RGBA compression in 4-bit mode. One block for each 4×4 pixels.
  764. *
  765. * @type {number}
  766. * @constant
  767. */
  768. const RGBA_PVRTC_4BPPV1_Format = 35842;
  769. /**
  770. * PVRTC RGBA compression in 2-bit mode. One block for each 8×4 pixels.
  771. *
  772. * @type {number}
  773. * @constant
  774. */
  775. const RGBA_PVRTC_2BPPV1_Format = 35843;
  776. /**
  777. * ETC1 RGB format.
  778. *
  779. * @type {number}
  780. * @constant
  781. */
  782. const RGB_ETC1_Format = 36196;
  783. /**
  784. * ETC2 RGB format.
  785. *
  786. * @type {number}
  787. * @constant
  788. */
  789. const RGB_ETC2_Format = 37492;
  790. /**
  791. * ETC2 RGBA format.
  792. *
  793. * @type {number}
  794. * @constant
  795. */
  796. const RGBA_ETC2_EAC_Format = 37496;
  797. /**
  798. * ASTC RGBA 4x4 format.
  799. *
  800. * @type {number}
  801. * @constant
  802. */
  803. const RGBA_ASTC_4x4_Format = 37808;
  804. /**
  805. * ASTC RGBA 5x4 format.
  806. *
  807. * @type {number}
  808. * @constant
  809. */
  810. const RGBA_ASTC_5x4_Format = 37809;
  811. /**
  812. * ASTC RGBA 5x5 format.
  813. *
  814. * @type {number}
  815. * @constant
  816. */
  817. const RGBA_ASTC_5x5_Format = 37810;
  818. /**
  819. * ASTC RGBA 6x5 format.
  820. *
  821. * @type {number}
  822. * @constant
  823. */
  824. const RGBA_ASTC_6x5_Format = 37811;
  825. /**
  826. * ASTC RGBA 6x6 format.
  827. *
  828. * @type {number}
  829. * @constant
  830. */
  831. const RGBA_ASTC_6x6_Format = 37812;
  832. /**
  833. * ASTC RGBA 8x5 format.
  834. *
  835. * @type {number}
  836. * @constant
  837. */
  838. const RGBA_ASTC_8x5_Format = 37813;
  839. /**
  840. * ASTC RGBA 8x6 format.
  841. *
  842. * @type {number}
  843. * @constant
  844. */
  845. const RGBA_ASTC_8x6_Format = 37814;
  846. /**
  847. * ASTC RGBA 8x8 format.
  848. *
  849. * @type {number}
  850. * @constant
  851. */
  852. const RGBA_ASTC_8x8_Format = 37815;
  853. /**
  854. * ASTC RGBA 10x5 format.
  855. *
  856. * @type {number}
  857. * @constant
  858. */
  859. const RGBA_ASTC_10x5_Format = 37816;
  860. /**
  861. * ASTC RGBA 10x6 format.
  862. *
  863. * @type {number}
  864. * @constant
  865. */
  866. const RGBA_ASTC_10x6_Format = 37817;
  867. /**
  868. * ASTC RGBA 10x8 format.
  869. *
  870. * @type {number}
  871. * @constant
  872. */
  873. const RGBA_ASTC_10x8_Format = 37818;
  874. /**
  875. * ASTC RGBA 10x10 format.
  876. *
  877. * @type {number}
  878. * @constant
  879. */
  880. const RGBA_ASTC_10x10_Format = 37819;
  881. /**
  882. * ASTC RGBA 12x10 format.
  883. *
  884. * @type {number}
  885. * @constant
  886. */
  887. const RGBA_ASTC_12x10_Format = 37820;
  888. /**
  889. * ASTC RGBA 12x12 format.
  890. *
  891. * @type {number}
  892. * @constant
  893. */
  894. const RGBA_ASTC_12x12_Format = 37821;
  895. /**
  896. * BPTC RGBA format.
  897. *
  898. * @type {number}
  899. * @constant
  900. */
  901. const RGBA_BPTC_Format = 36492;
  902. /**
  903. * BPTC Signed RGB format.
  904. *
  905. * @type {number}
  906. * @constant
  907. */
  908. const RGB_BPTC_SIGNED_Format = 36494;
  909. /**
  910. * BPTC Unsigned RGB format.
  911. *
  912. * @type {number}
  913. * @constant
  914. */
  915. const RGB_BPTC_UNSIGNED_Format = 36495;
  916. /**
  917. * RGTC1 Red format.
  918. *
  919. * @type {number}
  920. * @constant
  921. */
  922. const RED_RGTC1_Format = 36283;
  923. /**
  924. * RGTC1 Signed Red format.
  925. *
  926. * @type {number}
  927. * @constant
  928. */
  929. const SIGNED_RED_RGTC1_Format = 36284;
  930. /**
  931. * RGTC2 Red Green format.
  932. *
  933. * @type {number}
  934. * @constant
  935. */
  936. const RED_GREEN_RGTC2_Format = 36285;
  937. /**
  938. * RGTC2 Signed Red Green format.
  939. *
  940. * @type {number}
  941. * @constant
  942. */
  943. const SIGNED_RED_GREEN_RGTC2_Format = 36286;
  944. /**
  945. * Animations are played once.
  946. *
  947. * @type {number}
  948. * @constant
  949. */
  950. const LoopOnce = 2200;
  951. /**
  952. * Animations are played with a chosen number of repetitions, each time jumping from
  953. * the end of the clip directly to its beginning.
  954. *
  955. * @type {number}
  956. * @constant
  957. */
  958. const LoopRepeat = 2201;
  959. /**
  960. * Animations are played with a chosen number of repetitions, alternately playing forward
  961. * and backward.
  962. *
  963. * @type {number}
  964. * @constant
  965. */
  966. const LoopPingPong = 2202;
  967. /**
  968. * Discrete interpolation mode for keyframe tracks.
  969. *
  970. * @type {number}
  971. * @constant
  972. */
  973. const InterpolateDiscrete = 2300;
  974. /**
  975. * Linear interpolation mode for keyframe tracks.
  976. *
  977. * @type {number}
  978. * @constant
  979. */
  980. const InterpolateLinear = 2301;
  981. /**
  982. * Smooth interpolation mode for keyframe tracks.
  983. *
  984. * @type {number}
  985. * @constant
  986. */
  987. const InterpolateSmooth = 2302;
  988. /**
  989. * Zero curvature ending for animations.
  990. *
  991. * @type {number}
  992. * @constant
  993. */
  994. const ZeroCurvatureEnding = 2400;
  995. /**
  996. * Zero slope ending for animations.
  997. *
  998. * @type {number}
  999. * @constant
  1000. */
  1001. const ZeroSlopeEnding = 2401;
  1002. /**
  1003. * Wrap around ending for animations.
  1004. *
  1005. * @type {number}
  1006. * @constant
  1007. */
  1008. const WrapAroundEnding = 2402;
  1009. /**
  1010. * Default animation blend mode.
  1011. *
  1012. * @type {number}
  1013. * @constant
  1014. */
  1015. const NormalAnimationBlendMode = 2500;
  1016. /**
  1017. * Additive animation blend mode. Can be used to layer motions on top of
  1018. * each other to build complex performances from smaller re-usable assets.
  1019. *
  1020. * @type {number}
  1021. * @constant
  1022. */
  1023. const AdditiveAnimationBlendMode = 2501;
  1024. /**
  1025. * For every three vertices draw a single triangle.
  1026. *
  1027. * @type {number}
  1028. * @constant
  1029. */
  1030. const TrianglesDrawMode = 0;
  1031. /**
  1032. * For each vertex draw a triangle from the last three vertices.
  1033. *
  1034. * @type {number}
  1035. * @constant
  1036. */
  1037. const TriangleStripDrawMode = 1;
  1038. /**
  1039. * For each vertex draw a triangle from the first vertex and the last two vertices.
  1040. *
  1041. * @type {number}
  1042. * @constant
  1043. */
  1044. const TriangleFanDrawMode = 2;
  1045. /**
  1046. * Basic depth packing.
  1047. *
  1048. * @type {number}
  1049. * @constant
  1050. */
  1051. const BasicDepthPacking = 3200;
  1052. /**
  1053. * A depth value is packed into 32 bit RGBA.
  1054. *
  1055. * @type {number}
  1056. * @constant
  1057. */
  1058. const RGBADepthPacking = 3201;
  1059. /**
  1060. * A depth value is packed into 24 bit RGB.
  1061. *
  1062. * @type {number}
  1063. * @constant
  1064. */
  1065. const RGBDepthPacking = 3202;
  1066. /**
  1067. * A depth value is packed into 16 bit RG.
  1068. *
  1069. * @type {number}
  1070. * @constant
  1071. */
  1072. const RGDepthPacking = 3203;
  1073. /**
  1074. * Normal information is relative to the underlying surface.
  1075. *
  1076. * @type {number}
  1077. * @constant
  1078. */
  1079. const TangentSpaceNormalMap = 0;
  1080. /**
  1081. * Normal information is relative to the object orientation.
  1082. *
  1083. * @type {number}
  1084. * @constant
  1085. */
  1086. const ObjectSpaceNormalMap = 1;
  1087. // Color space string identifiers, matching CSS Color Module Level 4 and WebGPU names where available.
  1088. /**
  1089. * No color space.
  1090. *
  1091. * @type {string}
  1092. * @constant
  1093. */
  1094. const NoColorSpace = '';
  1095. /**
  1096. * sRGB color space.
  1097. *
  1098. * @type {string}
  1099. * @constant
  1100. */
  1101. const SRGBColorSpace = 'srgb';
  1102. /**
  1103. * sRGB-linear color space.
  1104. *
  1105. * @type {string}
  1106. * @constant
  1107. */
  1108. const LinearSRGBColorSpace = 'srgb-linear';
  1109. /**
  1110. * Linear transfer function.
  1111. *
  1112. * @type {string}
  1113. * @constant
  1114. */
  1115. const LinearTransfer = 'linear';
  1116. /**
  1117. * sRGB transfer function.
  1118. *
  1119. * @type {string}
  1120. * @constant
  1121. */
  1122. const SRGBTransfer = 'srgb';
  1123. /**
  1124. * Sets the stencil buffer value to `0`.
  1125. *
  1126. * @type {number}
  1127. * @constant
  1128. */
  1129. const ZeroStencilOp = 0;
  1130. /**
  1131. * Keeps the current value.
  1132. *
  1133. * @type {number}
  1134. * @constant
  1135. */
  1136. const KeepStencilOp = 7680;
  1137. /**
  1138. * Sets the stencil buffer value to the specified reference value.
  1139. *
  1140. * @type {number}
  1141. * @constant
  1142. */
  1143. const ReplaceStencilOp = 7681;
  1144. /**
  1145. * Increments the current stencil buffer value. Clamps to the maximum representable unsigned value.
  1146. *
  1147. * @type {number}
  1148. * @constant
  1149. */
  1150. const IncrementStencilOp = 7682;
  1151. /**
  1152. * Decrements the current stencil buffer value. Clamps to `0`.
  1153. *
  1154. * @type {number}
  1155. * @constant
  1156. */
  1157. const DecrementStencilOp = 7683;
  1158. /**
  1159. * Increments the current stencil buffer value. Wraps stencil buffer value to zero when incrementing
  1160. * the maximum representable unsigned value.
  1161. *
  1162. * @type {number}
  1163. * @constant
  1164. */
  1165. const IncrementWrapStencilOp = 34055;
  1166. /**
  1167. * Decrements the current stencil buffer value. Wraps stencil buffer value to the maximum representable
  1168. * unsigned value when decrementing a stencil buffer value of `0`.
  1169. *
  1170. * @type {number}
  1171. * @constant
  1172. */
  1173. const DecrementWrapStencilOp = 34056;
  1174. /**
  1175. * Inverts the current stencil buffer value bitwise.
  1176. *
  1177. * @type {number}
  1178. * @constant
  1179. */
  1180. const InvertStencilOp = 5386;
  1181. /**
  1182. * Will never return true.
  1183. *
  1184. * @type {number}
  1185. * @constant
  1186. */
  1187. const NeverStencilFunc = 512;
  1188. /**
  1189. * Will return true if the stencil reference value is less than the current stencil value.
  1190. *
  1191. * @type {number}
  1192. * @constant
  1193. */
  1194. const LessStencilFunc = 513;
  1195. /**
  1196. * Will return true if the stencil reference value is equal to the current stencil value.
  1197. *
  1198. * @type {number}
  1199. * @constant
  1200. */
  1201. const EqualStencilFunc = 514;
  1202. /**
  1203. * Will return true if the stencil reference value is less than or equal to the current stencil value.
  1204. *
  1205. * @type {number}
  1206. * @constant
  1207. */
  1208. const LessEqualStencilFunc = 515;
  1209. /**
  1210. * Will return true if the stencil reference value is greater than the current stencil value.
  1211. *
  1212. * @type {number}
  1213. * @constant
  1214. */
  1215. const GreaterStencilFunc = 516;
  1216. /**
  1217. * Will return true if the stencil reference value is not equal to the current stencil value.
  1218. *
  1219. * @type {number}
  1220. * @constant
  1221. */
  1222. const NotEqualStencilFunc = 517;
  1223. /**
  1224. * Will return true if the stencil reference value is greater than or equal to the current stencil value.
  1225. *
  1226. * @type {number}
  1227. * @constant
  1228. */
  1229. const GreaterEqualStencilFunc = 518;
  1230. /**
  1231. * Will always return true.
  1232. *
  1233. * @type {number}
  1234. * @constant
  1235. */
  1236. const AlwaysStencilFunc = 519;
  1237. /**
  1238. * Never pass.
  1239. *
  1240. * @type {number}
  1241. * @constant
  1242. */
  1243. const NeverCompare = 512;
  1244. /**
  1245. * Pass if the incoming value is less than the texture value.
  1246. *
  1247. * @type {number}
  1248. * @constant
  1249. */
  1250. const LessCompare = 513;
  1251. /**
  1252. * Pass if the incoming value equals the texture value.
  1253. *
  1254. * @type {number}
  1255. * @constant
  1256. */
  1257. const EqualCompare = 514;
  1258. /**
  1259. * Pass if the incoming value is less than or equal to the texture value.
  1260. *
  1261. * @type {number}
  1262. * @constant
  1263. */
  1264. const LessEqualCompare = 515;
  1265. /**
  1266. * Pass if the incoming value is greater than the texture value.
  1267. *
  1268. * @type {number}
  1269. * @constant
  1270. */
  1271. const GreaterCompare = 516;
  1272. /**
  1273. * Pass if the incoming value is not equal to the texture value.
  1274. *
  1275. * @type {number}
  1276. * @constant
  1277. */
  1278. const NotEqualCompare = 517;
  1279. /**
  1280. * Pass if the incoming value is greater than or equal to the texture value.
  1281. *
  1282. * @type {number}
  1283. * @constant
  1284. */
  1285. const GreaterEqualCompare = 518;
  1286. /**
  1287. * Always pass.
  1288. *
  1289. * @type {number}
  1290. * @constant
  1291. */
  1292. const AlwaysCompare = 519;
  1293. /**
  1294. * The contents are intended to be specified once by the application, and used many
  1295. * times as the source for drawing and image specification commands.
  1296. *
  1297. * @type {number}
  1298. * @constant
  1299. */
  1300. const StaticDrawUsage = 35044;
  1301. /**
  1302. * The contents are intended to be respecified repeatedly by the application, and
  1303. * used many times as the source for drawing and image specification commands.
  1304. *
  1305. * @type {number}
  1306. * @constant
  1307. */
  1308. const DynamicDrawUsage = 35048;
  1309. /**
  1310. * The contents are intended to be specified once by the application, and used at most
  1311. * a few times as the source for drawing and image specification commands.
  1312. *
  1313. * @type {number}
  1314. * @constant
  1315. */
  1316. const StreamDrawUsage = 35040;
  1317. /**
  1318. * The contents are intended to be specified once by reading data from the 3D API, and queried
  1319. * many times by the application.
  1320. *
  1321. * @type {number}
  1322. * @constant
  1323. */
  1324. const StaticReadUsage = 35045;
  1325. /**
  1326. * The contents are intended to be respecified repeatedly by reading data from the 3D API, and queried
  1327. * many times by the application.
  1328. *
  1329. * @type {number}
  1330. * @constant
  1331. */
  1332. const DynamicReadUsage = 35049;
  1333. /**
  1334. * The contents are intended to be specified once by reading data from the 3D API, and queried at most
  1335. * a few times by the application
  1336. *
  1337. * @type {number}
  1338. * @constant
  1339. */
  1340. const StreamReadUsage = 35041;
  1341. /**
  1342. * The contents are intended to be specified once by reading data from the 3D API, and used many times as
  1343. * the source for WebGL drawing and image specification commands.
  1344. *
  1345. * @type {number}
  1346. * @constant
  1347. */
  1348. const StaticCopyUsage = 35046;
  1349. /**
  1350. * The contents are intended to be respecified repeatedly by reading data from the 3D API, and used many times
  1351. * as the source for WebGL drawing and image specification commands.
  1352. *
  1353. * @type {number}
  1354. * @constant
  1355. */
  1356. const DynamicCopyUsage = 35050;
  1357. /**
  1358. * The contents are intended to be specified once by reading data from the 3D API, and used at most a few times
  1359. * as the source for WebGL drawing and image specification commands.
  1360. *
  1361. * @type {number}
  1362. * @constant
  1363. */
  1364. const StreamCopyUsage = 35042;
  1365. /**
  1366. * GLSL 1 shader code.
  1367. *
  1368. * @type {string}
  1369. * @constant
  1370. */
  1371. const GLSL1 = '100';
  1372. /**
  1373. * GLSL 3 shader code.
  1374. *
  1375. * @type {string}
  1376. * @constant
  1377. */
  1378. const GLSL3 = '300 es';
  1379. /**
  1380. * WebGL coordinate system.
  1381. *
  1382. * @type {number}
  1383. * @constant
  1384. */
  1385. const WebGLCoordinateSystem = 2000;
  1386. /**
  1387. * WebGPU coordinate system.
  1388. *
  1389. * @type {number}
  1390. * @constant
  1391. */
  1392. const WebGPUCoordinateSystem = 2001;
  1393. /**
  1394. * Represents the different timestamp query types.
  1395. *
  1396. * @type {ConstantsTimestampQuery}
  1397. * @constant
  1398. */
  1399. const TimestampQuery = {
  1400. COMPUTE: 'compute',
  1401. RENDER: 'render'
  1402. };
  1403. /**
  1404. * Represents mouse buttons and interaction types in context of controls.
  1405. *
  1406. * @type {ConstantsInterpolationSamplingType}
  1407. * @constant
  1408. */
  1409. const InterpolationSamplingType = {
  1410. PERSPECTIVE: 'perspective',
  1411. LINEAR: 'linear',
  1412. FLAT: 'flat'
  1413. };
  1414. /**
  1415. * Represents the different interpolation sampling modes.
  1416. *
  1417. * @type {ConstantsInterpolationSamplingMode}
  1418. * @constant
  1419. */
  1420. const InterpolationSamplingMode = {
  1421. NORMAL: 'normal',
  1422. CENTROID: 'centroid',
  1423. SAMPLE: 'sample',
  1424. FLAT_FIRST: 'flat first',
  1425. FLAT_EITHER: 'flat either'
  1426. };
  1427. /**
  1428. * This type represents mouse buttons and interaction types in context of controls.
  1429. *
  1430. * @typedef {Object} ConstantsMouse
  1431. * @property {number} MIDDLE - The left mouse button.
  1432. * @property {number} LEFT - The middle mouse button.
  1433. * @property {number} RIGHT - The right mouse button.
  1434. * @property {number} ROTATE - A rotate interaction.
  1435. * @property {number} DOLLY - A dolly interaction.
  1436. * @property {number} PAN - A pan interaction.
  1437. **/
  1438. /**
  1439. * This type represents touch interaction types in context of controls.
  1440. *
  1441. * @typedef {Object} ConstantsTouch
  1442. * @property {number} ROTATE - A rotate interaction.
  1443. * @property {number} PAN - A pan interaction.
  1444. * @property {number} DOLLY_PAN - The dolly-pan interaction.
  1445. * @property {number} DOLLY_ROTATE - A dolly-rotate interaction.
  1446. **/
  1447. /**
  1448. * This type represents the different timestamp query types.
  1449. *
  1450. * @typedef {Object} ConstantsTimestampQuery
  1451. * @property {string} COMPUTE - A `compute` timestamp query.
  1452. * @property {string} RENDER - A `render` timestamp query.
  1453. **/
  1454. /**
  1455. * Represents the different interpolation sampling types.
  1456. *
  1457. * @typedef {Object} ConstantsInterpolationSamplingType
  1458. * @property {string} PERSPECTIVE - Perspective-correct interpolation.
  1459. * @property {string} LINEAR - Linear interpolation.
  1460. * @property {string} FLAT - Flat interpolation.
  1461. */
  1462. /**
  1463. * Represents the different interpolation sampling modes.
  1464. *
  1465. * @typedef {Object} ConstantsInterpolationSamplingMode
  1466. * @property {string} NORMAL - Normal sampling mode.
  1467. * @property {string} CENTROID - Centroid sampling mode.
  1468. * @property {string} SAMPLE - Sample-specific sampling mode.
  1469. * @property {string} FLAT_FIRST - Flat interpolation using the first vertex.
  1470. * @property {string} FLAT_EITHER - Flat interpolation using either vertex.
  1471. */
  1472. /**
  1473. * This modules allows to dispatch event objects on custom JavaScript objects.
  1474. *
  1475. * Main repository: [eventdispatcher.js]{@link https://github.com/mrdoob/eventdispatcher.js/}
  1476. *
  1477. * Code Example:
  1478. * ```js
  1479. * class Car extends EventDispatcher {
  1480. * start() {
  1481. * this.dispatchEvent( { type: 'start', message: 'vroom vroom!' } );
  1482. * }
  1483. *};
  1484. *
  1485. * // Using events with the custom object
  1486. * const car = new Car();
  1487. * car.addEventListener( 'start', function ( event ) {
  1488. * alert( event.message );
  1489. * } );
  1490. *
  1491. * car.start();
  1492. * ```
  1493. */
  1494. class EventDispatcher {
  1495. /**
  1496. * Adds the given event listener to the given event type.
  1497. *
  1498. * @param {string} type - The type of event to listen to.
  1499. * @param {Function} listener - The function that gets called when the event is fired.
  1500. */
  1501. addEventListener( type, listener ) {
  1502. if ( this._listeners === undefined ) this._listeners = {};
  1503. const listeners = this._listeners;
  1504. if ( listeners[ type ] === undefined ) {
  1505. listeners[ type ] = [];
  1506. }
  1507. if ( listeners[ type ].indexOf( listener ) === -1 ) {
  1508. listeners[ type ].push( listener );
  1509. }
  1510. }
  1511. /**
  1512. * Returns `true` if the given event listener has been added to the given event type.
  1513. *
  1514. * @param {string} type - The type of event.
  1515. * @param {Function} listener - The listener to check.
  1516. * @return {boolean} Whether the given event listener has been added to the given event type.
  1517. */
  1518. hasEventListener( type, listener ) {
  1519. const listeners = this._listeners;
  1520. if ( listeners === undefined ) return false;
  1521. return listeners[ type ] !== undefined && listeners[ type ].indexOf( listener ) !== -1;
  1522. }
  1523. /**
  1524. * Removes the given event listener from the given event type.
  1525. *
  1526. * @param {string} type - The type of event.
  1527. * @param {Function} listener - The listener to remove.
  1528. */
  1529. removeEventListener( type, listener ) {
  1530. const listeners = this._listeners;
  1531. if ( listeners === undefined ) return;
  1532. const listenerArray = listeners[ type ];
  1533. if ( listenerArray !== undefined ) {
  1534. const index = listenerArray.indexOf( listener );
  1535. if ( index !== -1 ) {
  1536. listenerArray.splice( index, 1 );
  1537. }
  1538. }
  1539. }
  1540. /**
  1541. * Dispatches an event object.
  1542. *
  1543. * @param {Object} event - The event that gets fired.
  1544. */
  1545. dispatchEvent( event ) {
  1546. const listeners = this._listeners;
  1547. if ( listeners === undefined ) return;
  1548. const listenerArray = listeners[ event.type ];
  1549. if ( listenerArray !== undefined ) {
  1550. event.target = this;
  1551. // Make a copy, in case listeners are removed while iterating.
  1552. const array = listenerArray.slice( 0 );
  1553. for ( let i = 0, l = array.length; i < l; i ++ ) {
  1554. array[ i ].call( this, event );
  1555. }
  1556. event.target = null;
  1557. }
  1558. }
  1559. }
  1560. 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' ];
  1561. let _seed = 1234567;
  1562. const DEG2RAD = Math.PI / 180;
  1563. const RAD2DEG = 180 / Math.PI;
  1564. /**
  1565. * Generate a [UUID]{@link https://en.wikipedia.org/wiki/Universally_unique_identifier}
  1566. * (universally unique identifier).
  1567. *
  1568. * @return {string} The UUID.
  1569. */
  1570. function generateUUID() {
  1571. // http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/21963136#21963136
  1572. const d0 = Math.random() * 0xffffffff | 0;
  1573. const d1 = Math.random() * 0xffffffff | 0;
  1574. const d2 = Math.random() * 0xffffffff | 0;
  1575. const d3 = Math.random() * 0xffffffff | 0;
  1576. const uuid = _lut[ d0 & 0xff ] + _lut[ d0 >> 8 & 0xff ] + _lut[ d0 >> 16 & 0xff ] + _lut[ d0 >> 24 & 0xff ] + '-' +
  1577. _lut[ d1 & 0xff ] + _lut[ d1 >> 8 & 0xff ] + '-' + _lut[ d1 >> 16 & 0x0f | 0x40 ] + _lut[ d1 >> 24 & 0xff ] + '-' +
  1578. _lut[ d2 & 0x3f | 0x80 ] + _lut[ d2 >> 8 & 0xff ] + '-' + _lut[ d2 >> 16 & 0xff ] + _lut[ d2 >> 24 & 0xff ] +
  1579. _lut[ d3 & 0xff ] + _lut[ d3 >> 8 & 0xff ] + _lut[ d3 >> 16 & 0xff ] + _lut[ d3 >> 24 & 0xff ];
  1580. // .toLowerCase() here flattens concatenated strings to save heap memory space.
  1581. return uuid.toLowerCase();
  1582. }
  1583. /**
  1584. * Clamps the given value between min and max.
  1585. *
  1586. * @param {number} value - The value to clamp.
  1587. * @param {number} min - The min value.
  1588. * @param {number} max - The max value.
  1589. * @return {number} The clamped value.
  1590. */
  1591. function clamp( value, min, max ) {
  1592. return Math.max( min, Math.min( max, value ) );
  1593. }
  1594. /**
  1595. * Computes the Euclidean modulo of the given parameters that
  1596. * is `( ( n % m ) + m ) % m`.
  1597. *
  1598. * @param {number} n - The first parameter.
  1599. * @param {number} m - The second parameter.
  1600. * @return {number} The Euclidean modulo.
  1601. */
  1602. function euclideanModulo( n, m ) {
  1603. // https://en.wikipedia.org/wiki/Modulo_operation
  1604. return ( ( n % m ) + m ) % m;
  1605. }
  1606. /**
  1607. * Performs a linear mapping from range `<a1, a2>` to range `<b1, b2>`
  1608. * for the given value.
  1609. *
  1610. * @param {number} x - The value to be mapped.
  1611. * @param {number} a1 - Minimum value for range A.
  1612. * @param {number} a2 - Maximum value for range A.
  1613. * @param {number} b1 - Minimum value for range B.
  1614. * @param {number} b2 - Maximum value for range B.
  1615. * @return {number} The mapped value.
  1616. */
  1617. function mapLinear( x, a1, a2, b1, b2 ) {
  1618. return b1 + ( x - a1 ) * ( b2 - b1 ) / ( a2 - a1 );
  1619. }
  1620. /**
  1621. * Returns the percentage in the closed interval `[0, 1]` of the given value
  1622. * between the start and end point.
  1623. *
  1624. * @param {number} x - The start point
  1625. * @param {number} y - The end point.
  1626. * @param {number} value - A value between start and end.
  1627. * @return {number} The interpolation factor.
  1628. */
  1629. function inverseLerp( x, y, value ) {
  1630. // https://www.gamedev.net/tutorials/programming/general-and-gameplay-programming/inverse-lerp-a-super-useful-yet-often-overlooked-function-r5230/
  1631. if ( x !== y ) {
  1632. return ( value - x ) / ( y - x );
  1633. } else {
  1634. return 0;
  1635. }
  1636. }
  1637. /**
  1638. * Returns a value linearly interpolated from two known points based on the given interval -
  1639. * `t = 0` will return `x` and `t = 1` will return `y`.
  1640. *
  1641. * @param {number} x - The start point
  1642. * @param {number} y - The end point.
  1643. * @param {number} t - The interpolation factor in the closed interval `[0, 1]`.
  1644. * @return {number} The interpolated value.
  1645. */
  1646. function lerp( x, y, t ) {
  1647. return ( 1 - t ) * x + t * y;
  1648. }
  1649. /**
  1650. * Smoothly interpolate a number from `x` to `y` in a spring-like manner using a delta
  1651. * time to maintain frame rate independent movement. For details, see
  1652. * [Frame rate independent damping using lerp]{@link http://www.rorydriscoll.com/2016/03/07/frame-rate-independent-damping-using-lerp/}.
  1653. *
  1654. * @param {number} x - The current point.
  1655. * @param {number} y - The target point.
  1656. * @param {number} lambda - A higher lambda value will make the movement more sudden,
  1657. * and a lower value will make the movement more gradual.
  1658. * @param {number} dt - Delta time in seconds.
  1659. * @return {number} The interpolated value.
  1660. */
  1661. function damp( x, y, lambda, dt ) {
  1662. return lerp( x, y, 1 - Math.exp( - lambda * dt ) );
  1663. }
  1664. /**
  1665. * Returns a value that alternates between `0` and the given `length` parameter.
  1666. *
  1667. * @param {number} x - The value to pingpong.
  1668. * @param {number} [length=1] - The positive value the function will pingpong to.
  1669. * @return {number} The alternated value.
  1670. */
  1671. function pingpong( x, length = 1 ) {
  1672. // https://www.desmos.com/calculator/vcsjnyz7x4
  1673. return length - Math.abs( euclideanModulo( x, length * 2 ) - length );
  1674. }
  1675. /**
  1676. * Returns a value in the range `[0,1]` that represents the percentage that `x` has
  1677. * moved between `min` and `max`, but smoothed or slowed down the closer `x` is to
  1678. * the `min` and `max`.
  1679. *
  1680. * See [Smoothstep]{@link http://en.wikipedia.org/wiki/Smoothstep} for more details.
  1681. *
  1682. * @param {number} x - The value to evaluate based on its position between min and max.
  1683. * @param {number} min - The min value. Any x value below min will be `0`.
  1684. * @param {number} max - The max value. Any x value above max will be `1`.
  1685. * @return {number} The alternated value.
  1686. */
  1687. function smoothstep( x, min, max ) {
  1688. if ( x <= min ) return 0;
  1689. if ( x >= max ) return 1;
  1690. x = ( x - min ) / ( max - min );
  1691. return x * x * ( 3 - 2 * x );
  1692. }
  1693. /**
  1694. * A [variation on smoothstep]{@link https://en.wikipedia.org/wiki/Smoothstep#Variations}
  1695. * that has zero 1st and 2nd order derivatives at x=0 and x=1.
  1696. *
  1697. * @param {number} x - The value to evaluate based on its position between min and max.
  1698. * @param {number} min - The min value. Any x value below min will be `0`.
  1699. * @param {number} max - The max value. Any x value above max will be `1`.
  1700. * @return {number} The alternated value.
  1701. */
  1702. function smootherstep( x, min, max ) {
  1703. if ( x <= min ) return 0;
  1704. if ( x >= max ) return 1;
  1705. x = ( x - min ) / ( max - min );
  1706. return x * x * x * ( x * ( x * 6 - 15 ) + 10 );
  1707. }
  1708. /**
  1709. * Returns a random integer from `<low, high>` interval.
  1710. *
  1711. * @param {number} low - The lower value boundary.
  1712. * @param {number} high - The upper value boundary
  1713. * @return {number} A random integer.
  1714. */
  1715. function randInt( low, high ) {
  1716. return low + Math.floor( Math.random() * ( high - low + 1 ) );
  1717. }
  1718. /**
  1719. * Returns a random float from `<low, high>` interval.
  1720. *
  1721. * @param {number} low - The lower value boundary.
  1722. * @param {number} high - The upper value boundary
  1723. * @return {number} A random float.
  1724. */
  1725. function randFloat( low, high ) {
  1726. return low + Math.random() * ( high - low );
  1727. }
  1728. /**
  1729. * Returns a random integer from `<-range/2, range/2>` interval.
  1730. *
  1731. * @param {number} range - Defines the value range.
  1732. * @return {number} A random float.
  1733. */
  1734. function randFloatSpread( range ) {
  1735. return range * ( 0.5 - Math.random() );
  1736. }
  1737. /**
  1738. * Returns a deterministic pseudo-random float in the interval `[0, 1]`.
  1739. *
  1740. * @param {number} [s] - The integer seed.
  1741. * @return {number} A random float.
  1742. */
  1743. function seededRandom( s ) {
  1744. if ( s !== undefined ) _seed = s;
  1745. // Mulberry32 generator
  1746. let t = _seed += 0x6D2B79F5;
  1747. t = Math.imul( t ^ t >>> 15, t | 1 );
  1748. t ^= t + Math.imul( t ^ t >>> 7, t | 61 );
  1749. return ( ( t ^ t >>> 14 ) >>> 0 ) / 4294967296;
  1750. }
  1751. /**
  1752. * Converts degrees to radians.
  1753. *
  1754. * @param {number} degrees - A value in degrees.
  1755. * @return {number} The converted value in radians.
  1756. */
  1757. function degToRad( degrees ) {
  1758. return degrees * DEG2RAD;
  1759. }
  1760. /**
  1761. * Converts radians to degrees.
  1762. *
  1763. * @param {number} radians - A value in radians.
  1764. * @return {number} The converted value in degrees.
  1765. */
  1766. function radToDeg( radians ) {
  1767. return radians * RAD2DEG;
  1768. }
  1769. /**
  1770. * Returns `true` if the given number is a power of two.
  1771. *
  1772. * @param {number} value - The value to check.
  1773. * @return {boolean} Whether the given number is a power of two or not.
  1774. */
  1775. function isPowerOfTwo( value ) {
  1776. return ( value & ( value - 1 ) ) === 0 && value !== 0;
  1777. }
  1778. /**
  1779. * Returns the smallest power of two that is greater than or equal to the given number.
  1780. *
  1781. * @param {number} value - The value to find a POT for.
  1782. * @return {number} The smallest power of two that is greater than or equal to the given number.
  1783. */
  1784. function ceilPowerOfTwo( value ) {
  1785. return Math.pow( 2, Math.ceil( Math.log( value ) / Math.LN2 ) );
  1786. }
  1787. /**
  1788. * Returns the largest power of two that is less than or equal to the given number.
  1789. *
  1790. * @param {number} value - The value to find a POT for.
  1791. * @return {number} The largest power of two that is less than or equal to the given number.
  1792. */
  1793. function floorPowerOfTwo( value ) {
  1794. return Math.pow( 2, Math.floor( Math.log( value ) / Math.LN2 ) );
  1795. }
  1796. /**
  1797. * Sets the given quaternion from the [Intrinsic Proper Euler Angles]{@link https://en.wikipedia.org/wiki/Euler_angles}
  1798. * defined by the given angles and order.
  1799. *
  1800. * Rotations are applied to the axes in the order specified by order:
  1801. * rotation by angle `a` is applied first, then by angle `b`, then by angle `c`.
  1802. *
  1803. * @param {Quaternion} q - The quaternion to set.
  1804. * @param {number} a - The rotation applied to the first axis, in radians.
  1805. * @param {number} b - The rotation applied to the second axis, in radians.
  1806. * @param {number} c - The rotation applied to the third axis, in radians.
  1807. * @param {('XYX'|'XZX'|'YXY'|'YZY'|'ZXZ'|'ZYZ')} order - A string specifying the axes order.
  1808. */
  1809. function setQuaternionFromProperEuler( q, a, b, c, order ) {
  1810. const cos = Math.cos;
  1811. const sin = Math.sin;
  1812. const c2 = cos( b / 2 );
  1813. const s2 = sin( b / 2 );
  1814. const c13 = cos( ( a + c ) / 2 );
  1815. const s13 = sin( ( a + c ) / 2 );
  1816. const c1_3 = cos( ( a - c ) / 2 );
  1817. const s1_3 = sin( ( a - c ) / 2 );
  1818. const c3_1 = cos( ( c - a ) / 2 );
  1819. const s3_1 = sin( ( c - a ) / 2 );
  1820. switch ( order ) {
  1821. case 'XYX':
  1822. q.set( c2 * s13, s2 * c1_3, s2 * s1_3, c2 * c13 );
  1823. break;
  1824. case 'YZY':
  1825. q.set( s2 * s1_3, c2 * s13, s2 * c1_3, c2 * c13 );
  1826. break;
  1827. case 'ZXZ':
  1828. q.set( s2 * c1_3, s2 * s1_3, c2 * s13, c2 * c13 );
  1829. break;
  1830. case 'XZX':
  1831. q.set( c2 * s13, s2 * s3_1, s2 * c3_1, c2 * c13 );
  1832. break;
  1833. case 'YXY':
  1834. q.set( s2 * c3_1, c2 * s13, s2 * s3_1, c2 * c13 );
  1835. break;
  1836. case 'ZYZ':
  1837. q.set( s2 * s3_1, s2 * c3_1, c2 * s13, c2 * c13 );
  1838. break;
  1839. default:
  1840. console.warn( 'THREE.MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: ' + order );
  1841. }
  1842. }
  1843. /**
  1844. * Denormalizes the given value according to the given typed array.
  1845. *
  1846. * @param {number} value - The value to denormalize.
  1847. * @param {TypedArray} array - The typed array that defines the data type of the value.
  1848. * @return {number} The denormalize (float) value in the range `[0,1]`.
  1849. */
  1850. function denormalize( value, array ) {
  1851. switch ( array.constructor ) {
  1852. case Float32Array:
  1853. return value;
  1854. case Uint32Array:
  1855. return value / 4294967295.0;
  1856. case Uint16Array:
  1857. return value / 65535.0;
  1858. case Uint8Array:
  1859. return value / 255.0;
  1860. case Int32Array:
  1861. return Math.max( value / 2147483647.0, -1 );
  1862. case Int16Array:
  1863. return Math.max( value / 32767.0, -1 );
  1864. case Int8Array:
  1865. return Math.max( value / 127.0, -1 );
  1866. default:
  1867. throw new Error( 'Invalid component type.' );
  1868. }
  1869. }
  1870. /**
  1871. * Normalizes the given value according to the given typed array.
  1872. *
  1873. * @param {number} value - The float value in the range `[0,1]` to normalize.
  1874. * @param {TypedArray} array - The typed array that defines the data type of the value.
  1875. * @return {number} The normalize value.
  1876. */
  1877. function normalize( value, array ) {
  1878. switch ( array.constructor ) {
  1879. case Float32Array:
  1880. return value;
  1881. case Uint32Array:
  1882. return Math.round( value * 4294967295.0 );
  1883. case Uint16Array:
  1884. return Math.round( value * 65535.0 );
  1885. case Uint8Array:
  1886. return Math.round( value * 255.0 );
  1887. case Int32Array:
  1888. return Math.round( value * 2147483647.0 );
  1889. case Int16Array:
  1890. return Math.round( value * 32767.0 );
  1891. case Int8Array:
  1892. return Math.round( value * 127.0 );
  1893. default:
  1894. throw new Error( 'Invalid component type.' );
  1895. }
  1896. }
  1897. /**
  1898. * @class
  1899. * @classdesc A collection of math utility functions.
  1900. * @hideconstructor
  1901. */
  1902. const MathUtils = {
  1903. DEG2RAD: DEG2RAD,
  1904. RAD2DEG: RAD2DEG,
  1905. /**
  1906. * Generate a [UUID]{@link https://en.wikipedia.org/wiki/Universally_unique_identifier}
  1907. * (universally unique identifier).
  1908. *
  1909. * @static
  1910. * @method
  1911. * @return {string} The UUID.
  1912. */
  1913. generateUUID: generateUUID,
  1914. /**
  1915. * Clamps the given value between min and max.
  1916. *
  1917. * @static
  1918. * @method
  1919. * @param {number} value - The value to clamp.
  1920. * @param {number} min - The min value.
  1921. * @param {number} max - The max value.
  1922. * @return {number} The clamped value.
  1923. */
  1924. clamp: clamp,
  1925. /**
  1926. * Computes the Euclidean modulo of the given parameters that
  1927. * is `( ( n % m ) + m ) % m`.
  1928. *
  1929. * @static
  1930. * @method
  1931. * @param {number} n - The first parameter.
  1932. * @param {number} m - The second parameter.
  1933. * @return {number} The Euclidean modulo.
  1934. */
  1935. euclideanModulo: euclideanModulo,
  1936. /**
  1937. * Performs a linear mapping from range `<a1, a2>` to range `<b1, b2>`
  1938. * for the given value.
  1939. *
  1940. * @static
  1941. * @method
  1942. * @param {number} x - The value to be mapped.
  1943. * @param {number} a1 - Minimum value for range A.
  1944. * @param {number} a2 - Maximum value for range A.
  1945. * @param {number} b1 - Minimum value for range B.
  1946. * @param {number} b2 - Maximum value for range B.
  1947. * @return {number} The mapped value.
  1948. */
  1949. mapLinear: mapLinear,
  1950. /**
  1951. * Returns the percentage in the closed interval `[0, 1]` of the given value
  1952. * between the start and end point.
  1953. *
  1954. * @static
  1955. * @method
  1956. * @param {number} x - The start point
  1957. * @param {number} y - The end point.
  1958. * @param {number} value - A value between start and end.
  1959. * @return {number} The interpolation factor.
  1960. */
  1961. inverseLerp: inverseLerp,
  1962. /**
  1963. * Returns a value linearly interpolated from two known points based on the given interval -
  1964. * `t = 0` will return `x` and `t = 1` will return `y`.
  1965. *
  1966. * @static
  1967. * @method
  1968. * @param {number} x - The start point
  1969. * @param {number} y - The end point.
  1970. * @param {number} t - The interpolation factor in the closed interval `[0, 1]`.
  1971. * @return {number} The interpolated value.
  1972. */
  1973. lerp: lerp,
  1974. /**
  1975. * Smoothly interpolate a number from `x` to `y` in a spring-like manner using a delta
  1976. * time to maintain frame rate independent movement. For details, see
  1977. * [Frame rate independent damping using lerp]{@link http://www.rorydriscoll.com/2016/03/07/frame-rate-independent-damping-using-lerp/}.
  1978. *
  1979. * @static
  1980. * @method
  1981. * @param {number} x - The current point.
  1982. * @param {number} y - The target point.
  1983. * @param {number} lambda - A higher lambda value will make the movement more sudden,
  1984. * and a lower value will make the movement more gradual.
  1985. * @param {number} dt - Delta time in seconds.
  1986. * @return {number} The interpolated value.
  1987. */
  1988. damp: damp,
  1989. /**
  1990. * Returns a value that alternates between `0` and the given `length` parameter.
  1991. *
  1992. * @static
  1993. * @method
  1994. * @param {number} x - The value to pingpong.
  1995. * @param {number} [length=1] - The positive value the function will pingpong to.
  1996. * @return {number} The alternated value.
  1997. */
  1998. pingpong: pingpong,
  1999. /**
  2000. * Returns a value in the range `[0,1]` that represents the percentage that `x` has
  2001. * moved between `min` and `max`, but smoothed or slowed down the closer `x` is to
  2002. * the `min` and `max`.
  2003. *
  2004. * See [Smoothstep]{@link http://en.wikipedia.org/wiki/Smoothstep} for more details.
  2005. *
  2006. * @static
  2007. * @method
  2008. * @param {number} x - The value to evaluate based on its position between min and max.
  2009. * @param {number} min - The min value. Any x value below min will be `0`.
  2010. * @param {number} max - The max value. Any x value above max will be `1`.
  2011. * @return {number} The alternated value.
  2012. */
  2013. smoothstep: smoothstep,
  2014. /**
  2015. * A [variation on smoothstep]{@link https://en.wikipedia.org/wiki/Smoothstep#Variations}
  2016. * that has zero 1st and 2nd order derivatives at x=0 and x=1.
  2017. *
  2018. * @static
  2019. * @method
  2020. * @param {number} x - The value to evaluate based on its position between min and max.
  2021. * @param {number} min - The min value. Any x value below min will be `0`.
  2022. * @param {number} max - The max value. Any x value above max will be `1`.
  2023. * @return {number} The alternated value.
  2024. */
  2025. smootherstep: smootherstep,
  2026. /**
  2027. * Returns a random integer from `<low, high>` interval.
  2028. *
  2029. * @static
  2030. * @method
  2031. * @param {number} low - The lower value boundary.
  2032. * @param {number} high - The upper value boundary
  2033. * @return {number} A random integer.
  2034. */
  2035. randInt: randInt,
  2036. /**
  2037. * Returns a random float from `<low, high>` interval.
  2038. *
  2039. * @static
  2040. * @method
  2041. * @param {number} low - The lower value boundary.
  2042. * @param {number} high - The upper value boundary
  2043. * @return {number} A random float.
  2044. */
  2045. randFloat: randFloat,
  2046. /**
  2047. * Returns a random integer from `<-range/2, range/2>` interval.
  2048. *
  2049. * @static
  2050. * @method
  2051. * @param {number} range - Defines the value range.
  2052. * @return {number} A random float.
  2053. */
  2054. randFloatSpread: randFloatSpread,
  2055. /**
  2056. * Returns a deterministic pseudo-random float in the interval `[0, 1]`.
  2057. *
  2058. * @static
  2059. * @method
  2060. * @param {number} [s] - The integer seed.
  2061. * @return {number} A random float.
  2062. */
  2063. seededRandom: seededRandom,
  2064. /**
  2065. * Converts degrees to radians.
  2066. *
  2067. * @static
  2068. * @method
  2069. * @param {number} degrees - A value in degrees.
  2070. * @return {number} The converted value in radians.
  2071. */
  2072. degToRad: degToRad,
  2073. /**
  2074. * Converts radians to degrees.
  2075. *
  2076. * @static
  2077. * @method
  2078. * @param {number} radians - A value in radians.
  2079. * @return {number} The converted value in degrees.
  2080. */
  2081. radToDeg: radToDeg,
  2082. /**
  2083. * Returns `true` if the given number is a power of two.
  2084. *
  2085. * @static
  2086. * @method
  2087. * @param {number} value - The value to check.
  2088. * @return {boolean} Whether the given number is a power of two or not.
  2089. */
  2090. isPowerOfTwo: isPowerOfTwo,
  2091. /**
  2092. * Returns the smallest power of two that is greater than or equal to the given number.
  2093. *
  2094. * @static
  2095. * @method
  2096. * @param {number} value - The value to find a POT for.
  2097. * @return {number} The smallest power of two that is greater than or equal to the given number.
  2098. */
  2099. ceilPowerOfTwo: ceilPowerOfTwo,
  2100. /**
  2101. * Returns the largest power of two that is less than or equal to the given number.
  2102. *
  2103. * @static
  2104. * @method
  2105. * @param {number} value - The value to find a POT for.
  2106. * @return {number} The largest power of two that is less than or equal to the given number.
  2107. */
  2108. floorPowerOfTwo: floorPowerOfTwo,
  2109. /**
  2110. * Sets the given quaternion from the [Intrinsic Proper Euler Angles]{@link https://en.wikipedia.org/wiki/Euler_angles}
  2111. * defined by the given angles and order.
  2112. *
  2113. * Rotations are applied to the axes in the order specified by order:
  2114. * rotation by angle `a` is applied first, then by angle `b`, then by angle `c`.
  2115. *
  2116. * @static
  2117. * @method
  2118. * @param {Quaternion} q - The quaternion to set.
  2119. * @param {number} a - The rotation applied to the first axis, in radians.
  2120. * @param {number} b - The rotation applied to the second axis, in radians.
  2121. * @param {number} c - The rotation applied to the third axis, in radians.
  2122. * @param {('XYX'|'XZX'|'YXY'|'YZY'|'ZXZ'|'ZYZ')} order - A string specifying the axes order.
  2123. */
  2124. setQuaternionFromProperEuler: setQuaternionFromProperEuler,
  2125. /**
  2126. * Normalizes the given value according to the given typed array.
  2127. *
  2128. * @static
  2129. * @method
  2130. * @param {number} value - The float value in the range `[0,1]` to normalize.
  2131. * @param {TypedArray} array - The typed array that defines the data type of the value.
  2132. * @return {number} The normalize value.
  2133. */
  2134. normalize: normalize,
  2135. /**
  2136. * Denormalizes the given value according to the given typed array.
  2137. *
  2138. * @static
  2139. * @method
  2140. * @param {number} value - The value to denormalize.
  2141. * @param {TypedArray} array - The typed array that defines the data type of the value.
  2142. * @return {number} The denormalize (float) value in the range `[0,1]`.
  2143. */
  2144. denormalize: denormalize
  2145. };
  2146. /**
  2147. * Class representing a 2D vector. A 2D vector is an ordered pair of numbers
  2148. * (labeled x and y), which can be used to represent a number of things, such as:
  2149. *
  2150. * - A point in 2D space (i.e. a position on a plane).
  2151. * - A direction and length across a plane. In three.js the length will
  2152. * always be the Euclidean distance(straight-line distance) from `(0, 0)` to `(x, y)`
  2153. * and the direction is also measured from `(0, 0)` towards `(x, y)`.
  2154. * - Any arbitrary ordered pair of numbers.
  2155. *
  2156. * There are other things a 2D vector can be used to represent, such as
  2157. * momentum vectors, complex numbers and so on, however these are the most
  2158. * common uses in three.js.
  2159. *
  2160. * Iterating through a vector instance will yield its components `(x, y)` in
  2161. * the corresponding order.
  2162. * ```js
  2163. * const a = new THREE.Vector2( 0, 1 );
  2164. *
  2165. * //no arguments; will be initialised to (0, 0)
  2166. * const b = new THREE.Vector2( );
  2167. *
  2168. * const d = a.distanceTo( b );
  2169. * ```
  2170. */
  2171. class Vector2 {
  2172. /**
  2173. * Constructs a new 2D vector.
  2174. *
  2175. * @param {number} [x=0] - The x value of this vector.
  2176. * @param {number} [y=0] - The y value of this vector.
  2177. */
  2178. constructor( x = 0, y = 0 ) {
  2179. /**
  2180. * This flag can be used for type testing.
  2181. *
  2182. * @type {boolean}
  2183. * @readonly
  2184. * @default true
  2185. */
  2186. Vector2.prototype.isVector2 = true;
  2187. /**
  2188. * The x value of this vector.
  2189. *
  2190. * @type {number}
  2191. */
  2192. this.x = x;
  2193. /**
  2194. * The y value of this vector.
  2195. *
  2196. * @type {number}
  2197. */
  2198. this.y = y;
  2199. }
  2200. /**
  2201. * Alias for {@link Vector2#x}.
  2202. *
  2203. * @type {number}
  2204. */
  2205. get width() {
  2206. return this.x;
  2207. }
  2208. set width( value ) {
  2209. this.x = value;
  2210. }
  2211. /**
  2212. * Alias for {@link Vector2#y}.
  2213. *
  2214. * @type {number}
  2215. */
  2216. get height() {
  2217. return this.y;
  2218. }
  2219. set height( value ) {
  2220. this.y = value;
  2221. }
  2222. /**
  2223. * Sets the vector components.
  2224. *
  2225. * @param {number} x - The value of the x component.
  2226. * @param {number} y - The value of the y component.
  2227. * @return {Vector2} A reference to this vector.
  2228. */
  2229. set( x, y ) {
  2230. this.x = x;
  2231. this.y = y;
  2232. return this;
  2233. }
  2234. /**
  2235. * Sets the vector components to the same value.
  2236. *
  2237. * @param {number} scalar - The value to set for all vector components.
  2238. * @return {Vector2} A reference to this vector.
  2239. */
  2240. setScalar( scalar ) {
  2241. this.x = scalar;
  2242. this.y = scalar;
  2243. return this;
  2244. }
  2245. /**
  2246. * Sets the vector's x component to the given value
  2247. *
  2248. * @param {number} x - The value to set.
  2249. * @return {Vector2} A reference to this vector.
  2250. */
  2251. setX( x ) {
  2252. this.x = x;
  2253. return this;
  2254. }
  2255. /**
  2256. * Sets the vector's y component to the given value
  2257. *
  2258. * @param {number} y - The value to set.
  2259. * @return {Vector2} A reference to this vector.
  2260. */
  2261. setY( y ) {
  2262. this.y = y;
  2263. return this;
  2264. }
  2265. /**
  2266. * Allows to set a vector component with an index.
  2267. *
  2268. * @param {number} index - The component index. `0` equals to x, `1` equals to y.
  2269. * @param {number} value - The value to set.
  2270. * @return {Vector2} A reference to this vector.
  2271. */
  2272. setComponent( index, value ) {
  2273. switch ( index ) {
  2274. case 0: this.x = value; break;
  2275. case 1: this.y = value; break;
  2276. default: throw new Error( 'index is out of range: ' + index );
  2277. }
  2278. return this;
  2279. }
  2280. /**
  2281. * Returns the value of the vector component which matches the given index.
  2282. *
  2283. * @param {number} index - The component index. `0` equals to x, `1` equals to y.
  2284. * @return {number} A vector component value.
  2285. */
  2286. getComponent( index ) {
  2287. switch ( index ) {
  2288. case 0: return this.x;
  2289. case 1: return this.y;
  2290. default: throw new Error( 'index is out of range: ' + index );
  2291. }
  2292. }
  2293. /**
  2294. * Returns a new vector with copied values from this instance.
  2295. *
  2296. * @return {Vector2} A clone of this instance.
  2297. */
  2298. clone() {
  2299. return new this.constructor( this.x, this.y );
  2300. }
  2301. /**
  2302. * Copies the values of the given vector to this instance.
  2303. *
  2304. * @param {Vector2} v - The vector to copy.
  2305. * @return {Vector2} A reference to this vector.
  2306. */
  2307. copy( v ) {
  2308. this.x = v.x;
  2309. this.y = v.y;
  2310. return this;
  2311. }
  2312. /**
  2313. * Adds the given vector to this instance.
  2314. *
  2315. * @param {Vector2} v - The vector to add.
  2316. * @return {Vector2} A reference to this vector.
  2317. */
  2318. add( v ) {
  2319. this.x += v.x;
  2320. this.y += v.y;
  2321. return this;
  2322. }
  2323. /**
  2324. * Adds the given scalar value to all components of this instance.
  2325. *
  2326. * @param {number} s - The scalar to add.
  2327. * @return {Vector2} A reference to this vector.
  2328. */
  2329. addScalar( s ) {
  2330. this.x += s;
  2331. this.y += s;
  2332. return this;
  2333. }
  2334. /**
  2335. * Adds the given vectors and stores the result in this instance.
  2336. *
  2337. * @param {Vector2} a - The first vector.
  2338. * @param {Vector2} b - The second vector.
  2339. * @return {Vector2} A reference to this vector.
  2340. */
  2341. addVectors( a, b ) {
  2342. this.x = a.x + b.x;
  2343. this.y = a.y + b.y;
  2344. return this;
  2345. }
  2346. /**
  2347. * Adds the given vector scaled by the given factor to this instance.
  2348. *
  2349. * @param {Vector2} v - The vector.
  2350. * @param {number} s - The factor that scales `v`.
  2351. * @return {Vector2} A reference to this vector.
  2352. */
  2353. addScaledVector( v, s ) {
  2354. this.x += v.x * s;
  2355. this.y += v.y * s;
  2356. return this;
  2357. }
  2358. /**
  2359. * Subtracts the given vector from this instance.
  2360. *
  2361. * @param {Vector2} v - The vector to subtract.
  2362. * @return {Vector2} A reference to this vector.
  2363. */
  2364. sub( v ) {
  2365. this.x -= v.x;
  2366. this.y -= v.y;
  2367. return this;
  2368. }
  2369. /**
  2370. * Subtracts the given scalar value from all components of this instance.
  2371. *
  2372. * @param {number} s - The scalar to subtract.
  2373. * @return {Vector2} A reference to this vector.
  2374. */
  2375. subScalar( s ) {
  2376. this.x -= s;
  2377. this.y -= s;
  2378. return this;
  2379. }
  2380. /**
  2381. * Subtracts the given vectors and stores the result in this instance.
  2382. *
  2383. * @param {Vector2} a - The first vector.
  2384. * @param {Vector2} b - The second vector.
  2385. * @return {Vector2} A reference to this vector.
  2386. */
  2387. subVectors( a, b ) {
  2388. this.x = a.x - b.x;
  2389. this.y = a.y - b.y;
  2390. return this;
  2391. }
  2392. /**
  2393. * Multiplies the given vector with this instance.
  2394. *
  2395. * @param {Vector2} v - The vector to multiply.
  2396. * @return {Vector2} A reference to this vector.
  2397. */
  2398. multiply( v ) {
  2399. this.x *= v.x;
  2400. this.y *= v.y;
  2401. return this;
  2402. }
  2403. /**
  2404. * Multiplies the given scalar value with all components of this instance.
  2405. *
  2406. * @param {number} scalar - The scalar to multiply.
  2407. * @return {Vector2} A reference to this vector.
  2408. */
  2409. multiplyScalar( scalar ) {
  2410. this.x *= scalar;
  2411. this.y *= scalar;
  2412. return this;
  2413. }
  2414. /**
  2415. * Divides this instance by the given vector.
  2416. *
  2417. * @param {Vector2} v - The vector to divide.
  2418. * @return {Vector2} A reference to this vector.
  2419. */
  2420. divide( v ) {
  2421. this.x /= v.x;
  2422. this.y /= v.y;
  2423. return this;
  2424. }
  2425. /**
  2426. * Divides this vector by the given scalar.
  2427. *
  2428. * @param {number} scalar - The scalar to divide.
  2429. * @return {Vector2} A reference to this vector.
  2430. */
  2431. divideScalar( scalar ) {
  2432. return this.multiplyScalar( 1 / scalar );
  2433. }
  2434. /**
  2435. * Multiplies this vector (with an implicit 1 as the 3rd component) by
  2436. * the given 3x3 matrix.
  2437. *
  2438. * @param {Matrix3} m - The matrix to apply.
  2439. * @return {Vector2} A reference to this vector.
  2440. */
  2441. applyMatrix3( m ) {
  2442. const x = this.x, y = this.y;
  2443. const e = m.elements;
  2444. this.x = e[ 0 ] * x + e[ 3 ] * y + e[ 6 ];
  2445. this.y = e[ 1 ] * x + e[ 4 ] * y + e[ 7 ];
  2446. return this;
  2447. }
  2448. /**
  2449. * If this vector's x or y value is greater than the given vector's x or y
  2450. * value, replace that value with the corresponding min value.
  2451. *
  2452. * @param {Vector2} v - The vector.
  2453. * @return {Vector2} A reference to this vector.
  2454. */
  2455. min( v ) {
  2456. this.x = Math.min( this.x, v.x );
  2457. this.y = Math.min( this.y, v.y );
  2458. return this;
  2459. }
  2460. /**
  2461. * If this vector's x or y value is less than the given vector's x or y
  2462. * value, replace that value with the corresponding max value.
  2463. *
  2464. * @param {Vector2} v - The vector.
  2465. * @return {Vector2} A reference to this vector.
  2466. */
  2467. max( v ) {
  2468. this.x = Math.max( this.x, v.x );
  2469. this.y = Math.max( this.y, v.y );
  2470. return this;
  2471. }
  2472. /**
  2473. * If this vector's x or y value is greater than the max vector's x or y
  2474. * value, it is replaced by the corresponding value.
  2475. * If this vector's x or y value is less than the min vector's x or y value,
  2476. * it is replaced by the corresponding value.
  2477. *
  2478. * @param {Vector2} min - The minimum x and y values.
  2479. * @param {Vector2} max - The maximum x and y values in the desired range.
  2480. * @return {Vector2} A reference to this vector.
  2481. */
  2482. clamp( min, max ) {
  2483. // assumes min < max, componentwise
  2484. this.x = clamp( this.x, min.x, max.x );
  2485. this.y = clamp( this.y, min.y, max.y );
  2486. return this;
  2487. }
  2488. /**
  2489. * If this vector's x or y values are greater than the max value, they are
  2490. * replaced by the max value.
  2491. * If this vector's x or y values are less than the min value, they are
  2492. * replaced by the min value.
  2493. *
  2494. * @param {number} minVal - The minimum value the components will be clamped to.
  2495. * @param {number} maxVal - The maximum value the components will be clamped to.
  2496. * @return {Vector2} A reference to this vector.
  2497. */
  2498. clampScalar( minVal, maxVal ) {
  2499. this.x = clamp( this.x, minVal, maxVal );
  2500. this.y = clamp( this.y, minVal, maxVal );
  2501. return this;
  2502. }
  2503. /**
  2504. * If this vector's length is greater than the max value, it is replaced by
  2505. * the max value.
  2506. * If this vector's length is less than the min value, it is replaced by the
  2507. * min value.
  2508. *
  2509. * @param {number} min - The minimum value the vector length will be clamped to.
  2510. * @param {number} max - The maximum value the vector length will be clamped to.
  2511. * @return {Vector2} A reference to this vector.
  2512. */
  2513. clampLength( min, max ) {
  2514. const length = this.length();
  2515. return this.divideScalar( length || 1 ).multiplyScalar( clamp( length, min, max ) );
  2516. }
  2517. /**
  2518. * The components of this vector are rounded down to the nearest integer value.
  2519. *
  2520. * @return {Vector2} A reference to this vector.
  2521. */
  2522. floor() {
  2523. this.x = Math.floor( this.x );
  2524. this.y = Math.floor( this.y );
  2525. return this;
  2526. }
  2527. /**
  2528. * The components of this vector are rounded up to the nearest integer value.
  2529. *
  2530. * @return {Vector2} A reference to this vector.
  2531. */
  2532. ceil() {
  2533. this.x = Math.ceil( this.x );
  2534. this.y = Math.ceil( this.y );
  2535. return this;
  2536. }
  2537. /**
  2538. * The components of this vector are rounded to the nearest integer value
  2539. *
  2540. * @return {Vector2} A reference to this vector.
  2541. */
  2542. round() {
  2543. this.x = Math.round( this.x );
  2544. this.y = Math.round( this.y );
  2545. return this;
  2546. }
  2547. /**
  2548. * The components of this vector are rounded towards zero (up if negative,
  2549. * down if positive) to an integer value.
  2550. *
  2551. * @return {Vector2} A reference to this vector.
  2552. */
  2553. roundToZero() {
  2554. this.x = Math.trunc( this.x );
  2555. this.y = Math.trunc( this.y );
  2556. return this;
  2557. }
  2558. /**
  2559. * Inverts this vector - i.e. sets x = -x and y = -y.
  2560. *
  2561. * @return {Vector2} A reference to this vector.
  2562. */
  2563. negate() {
  2564. this.x = - this.x;
  2565. this.y = - this.y;
  2566. return this;
  2567. }
  2568. /**
  2569. * Calculates the dot product of the given vector with this instance.
  2570. *
  2571. * @param {Vector2} v - The vector to compute the dot product with.
  2572. * @return {number} The result of the dot product.
  2573. */
  2574. dot( v ) {
  2575. return this.x * v.x + this.y * v.y;
  2576. }
  2577. /**
  2578. * Calculates the cross product of the given vector with this instance.
  2579. *
  2580. * @param {Vector2} v - The vector to compute the cross product with.
  2581. * @return {number} The result of the cross product.
  2582. */
  2583. cross( v ) {
  2584. return this.x * v.y - this.y * v.x;
  2585. }
  2586. /**
  2587. * Computes the square of the Euclidean length (straight-line length) from
  2588. * (0, 0) to (x, y). If you are comparing the lengths of vectors, you should
  2589. * compare the length squared instead as it is slightly more efficient to calculate.
  2590. *
  2591. * @return {number} The square length of this vector.
  2592. */
  2593. lengthSq() {
  2594. return this.x * this.x + this.y * this.y;
  2595. }
  2596. /**
  2597. * Computes the Euclidean length (straight-line length) from (0, 0) to (x, y).
  2598. *
  2599. * @return {number} The length of this vector.
  2600. */
  2601. length() {
  2602. return Math.sqrt( this.x * this.x + this.y * this.y );
  2603. }
  2604. /**
  2605. * Computes the Manhattan length of this vector.
  2606. *
  2607. * @return {number} The length of this vector.
  2608. */
  2609. manhattanLength() {
  2610. return Math.abs( this.x ) + Math.abs( this.y );
  2611. }
  2612. /**
  2613. * Converts this vector to a unit vector - that is, sets it equal to a vector
  2614. * with the same direction as this one, but with a vector length of `1`.
  2615. *
  2616. * @return {Vector2} A reference to this vector.
  2617. */
  2618. normalize() {
  2619. return this.divideScalar( this.length() || 1 );
  2620. }
  2621. /**
  2622. * Computes the angle in radians of this vector with respect to the positive x-axis.
  2623. *
  2624. * @return {number} The angle in radians.
  2625. */
  2626. angle() {
  2627. const angle = Math.atan2( - this.y, - this.x ) + Math.PI;
  2628. return angle;
  2629. }
  2630. /**
  2631. * Returns the angle between the given vector and this instance in radians.
  2632. *
  2633. * @param {Vector2} v - The vector to compute the angle with.
  2634. * @return {number} The angle in radians.
  2635. */
  2636. angleTo( v ) {
  2637. const denominator = Math.sqrt( this.lengthSq() * v.lengthSq() );
  2638. if ( denominator === 0 ) return Math.PI / 2;
  2639. const theta = this.dot( v ) / denominator;
  2640. // clamp, to handle numerical problems
  2641. return Math.acos( clamp( theta, -1, 1 ) );
  2642. }
  2643. /**
  2644. * Computes the distance from the given vector to this instance.
  2645. *
  2646. * @param {Vector2} v - The vector to compute the distance to.
  2647. * @return {number} The distance.
  2648. */
  2649. distanceTo( v ) {
  2650. return Math.sqrt( this.distanceToSquared( v ) );
  2651. }
  2652. /**
  2653. * Computes the squared distance from the given vector to this instance.
  2654. * If you are just comparing the distance with another distance, you should compare
  2655. * the distance squared instead as it is slightly more efficient to calculate.
  2656. *
  2657. * @param {Vector2} v - The vector to compute the squared distance to.
  2658. * @return {number} The squared distance.
  2659. */
  2660. distanceToSquared( v ) {
  2661. const dx = this.x - v.x, dy = this.y - v.y;
  2662. return dx * dx + dy * dy;
  2663. }
  2664. /**
  2665. * Computes the Manhattan distance from the given vector to this instance.
  2666. *
  2667. * @param {Vector2} v - The vector to compute the Manhattan distance to.
  2668. * @return {number} The Manhattan distance.
  2669. */
  2670. manhattanDistanceTo( v ) {
  2671. return Math.abs( this.x - v.x ) + Math.abs( this.y - v.y );
  2672. }
  2673. /**
  2674. * Sets this vector to a vector with the same direction as this one, but
  2675. * with the specified length.
  2676. *
  2677. * @param {number} length - The new length of this vector.
  2678. * @return {Vector2} A reference to this vector.
  2679. */
  2680. setLength( length ) {
  2681. return this.normalize().multiplyScalar( length );
  2682. }
  2683. /**
  2684. * Linearly interpolates between the given vector and this instance, where
  2685. * alpha is the percent distance along the line - alpha = 0 will be this
  2686. * vector, and alpha = 1 will be the given one.
  2687. *
  2688. * @param {Vector2} v - The vector to interpolate towards.
  2689. * @param {number} alpha - The interpolation factor, typically in the closed interval `[0, 1]`.
  2690. * @return {Vector2} A reference to this vector.
  2691. */
  2692. lerp( v, alpha ) {
  2693. this.x += ( v.x - this.x ) * alpha;
  2694. this.y += ( v.y - this.y ) * alpha;
  2695. return this;
  2696. }
  2697. /**
  2698. * Linearly interpolates between the given vectors, where alpha is the percent
  2699. * distance along the line - alpha = 0 will be first vector, and alpha = 1 will
  2700. * be the second one. The result is stored in this instance.
  2701. *
  2702. * @param {Vector2} v1 - The first vector.
  2703. * @param {Vector2} v2 - The second vector.
  2704. * @param {number} alpha - The interpolation factor, typically in the closed interval `[0, 1]`.
  2705. * @return {Vector2} A reference to this vector.
  2706. */
  2707. lerpVectors( v1, v2, alpha ) {
  2708. this.x = v1.x + ( v2.x - v1.x ) * alpha;
  2709. this.y = v1.y + ( v2.y - v1.y ) * alpha;
  2710. return this;
  2711. }
  2712. /**
  2713. * Returns `true` if this vector is equal with the given one.
  2714. *
  2715. * @param {Vector2} v - The vector to test for equality.
  2716. * @return {boolean} Whether this vector is equal with the given one.
  2717. */
  2718. equals( v ) {
  2719. return ( ( v.x === this.x ) && ( v.y === this.y ) );
  2720. }
  2721. /**
  2722. * Sets this vector's x value to be `array[ offset ]` and y
  2723. * value to be `array[ offset + 1 ]`.
  2724. *
  2725. * @param {Array<number>} array - An array holding the vector component values.
  2726. * @param {number} [offset=0] - The offset into the array.
  2727. * @return {Vector2} A reference to this vector.
  2728. */
  2729. fromArray( array, offset = 0 ) {
  2730. this.x = array[ offset ];
  2731. this.y = array[ offset + 1 ];
  2732. return this;
  2733. }
  2734. /**
  2735. * Writes the components of this vector to the given array. If no array is provided,
  2736. * the method returns a new instance.
  2737. *
  2738. * @param {Array<number>} [array=[]] - The target array holding the vector components.
  2739. * @param {number} [offset=0] - Index of the first element in the array.
  2740. * @return {Array<number>} The vector components.
  2741. */
  2742. toArray( array = [], offset = 0 ) {
  2743. array[ offset ] = this.x;
  2744. array[ offset + 1 ] = this.y;
  2745. return array;
  2746. }
  2747. /**
  2748. * Sets the components of this vector from the given buffer attribute.
  2749. *
  2750. * @param {BufferAttribute} attribute - The buffer attribute holding vector data.
  2751. * @param {number} index - The index into the attribute.
  2752. * @return {Vector2} A reference to this vector.
  2753. */
  2754. fromBufferAttribute( attribute, index ) {
  2755. this.x = attribute.getX( index );
  2756. this.y = attribute.getY( index );
  2757. return this;
  2758. }
  2759. /**
  2760. * Rotates this vector around the given center by the given angle.
  2761. *
  2762. * @param {Vector2} center - The point around which to rotate.
  2763. * @param {number} angle - The angle to rotate, in radians.
  2764. * @return {Vector2} A reference to this vector.
  2765. */
  2766. rotateAround( center, angle ) {
  2767. const c = Math.cos( angle ), s = Math.sin( angle );
  2768. const x = this.x - center.x;
  2769. const y = this.y - center.y;
  2770. this.x = x * c - y * s + center.x;
  2771. this.y = x * s + y * c + center.y;
  2772. return this;
  2773. }
  2774. /**
  2775. * Sets each component of this vector to a pseudo-random value between `0` and
  2776. * `1`, excluding `1`.
  2777. *
  2778. * @return {Vector2} A reference to this vector.
  2779. */
  2780. random() {
  2781. this.x = Math.random();
  2782. this.y = Math.random();
  2783. return this;
  2784. }
  2785. *[ Symbol.iterator ]() {
  2786. yield this.x;
  2787. yield this.y;
  2788. }
  2789. }
  2790. /**
  2791. * Class for representing a Quaternion. Quaternions are used in three.js to represent rotations.
  2792. *
  2793. * Iterating through a vector instance will yield its components `(x, y, z, w)` in
  2794. * the corresponding order.
  2795. *
  2796. * Note that three.js expects Quaternions to be normalized.
  2797. * ```js
  2798. * const quaternion = new THREE.Quaternion();
  2799. * quaternion.setFromAxisAngle( new THREE.Vector3( 0, 1, 0 ), Math.PI / 2 );
  2800. *
  2801. * const vector = new THREE.Vector3( 1, 0, 0 );
  2802. * vector.applyQuaternion( quaternion );
  2803. * ```
  2804. */
  2805. class Quaternion {
  2806. /**
  2807. * Constructs a new quaternion.
  2808. *
  2809. * @param {number} [x=0] - The x value of this quaternion.
  2810. * @param {number} [y=0] - The y value of this quaternion.
  2811. * @param {number} [z=0] - The z value of this quaternion.
  2812. * @param {number} [w=1] - The w value of this quaternion.
  2813. */
  2814. constructor( x = 0, y = 0, z = 0, w = 1 ) {
  2815. /**
  2816. * This flag can be used for type testing.
  2817. *
  2818. * @type {boolean}
  2819. * @readonly
  2820. * @default true
  2821. */
  2822. this.isQuaternion = true;
  2823. this._x = x;
  2824. this._y = y;
  2825. this._z = z;
  2826. this._w = w;
  2827. }
  2828. /**
  2829. * Interpolates between two quaternions via SLERP. This implementation assumes the
  2830. * quaternion data are managed in flat arrays.
  2831. *
  2832. * @param {Array<number>} dst - The destination array.
  2833. * @param {number} dstOffset - An offset into the destination array.
  2834. * @param {Array<number>} src0 - The source array of the first quaternion.
  2835. * @param {number} srcOffset0 - An offset into the first source array.
  2836. * @param {Array<number>} src1 - The source array of the second quaternion.
  2837. * @param {number} srcOffset1 - An offset into the second source array.
  2838. * @param {number} t - The interpolation factor in the range `[0,1]`.
  2839. * @see {@link Quaternion#slerp}
  2840. */
  2841. static slerpFlat( dst, dstOffset, src0, srcOffset0, src1, srcOffset1, t ) {
  2842. // fuzz-free, array-based Quaternion SLERP operation
  2843. let x0 = src0[ srcOffset0 + 0 ],
  2844. y0 = src0[ srcOffset0 + 1 ],
  2845. z0 = src0[ srcOffset0 + 2 ],
  2846. w0 = src0[ srcOffset0 + 3 ];
  2847. const x1 = src1[ srcOffset1 + 0 ],
  2848. y1 = src1[ srcOffset1 + 1 ],
  2849. z1 = src1[ srcOffset1 + 2 ],
  2850. w1 = src1[ srcOffset1 + 3 ];
  2851. if ( t === 0 ) {
  2852. dst[ dstOffset + 0 ] = x0;
  2853. dst[ dstOffset + 1 ] = y0;
  2854. dst[ dstOffset + 2 ] = z0;
  2855. dst[ dstOffset + 3 ] = w0;
  2856. return;
  2857. }
  2858. if ( t === 1 ) {
  2859. dst[ dstOffset + 0 ] = x1;
  2860. dst[ dstOffset + 1 ] = y1;
  2861. dst[ dstOffset + 2 ] = z1;
  2862. dst[ dstOffset + 3 ] = w1;
  2863. return;
  2864. }
  2865. if ( w0 !== w1 || x0 !== x1 || y0 !== y1 || z0 !== z1 ) {
  2866. let s = 1 - t;
  2867. const cos = x0 * x1 + y0 * y1 + z0 * z1 + w0 * w1,
  2868. dir = ( cos >= 0 ? 1 : -1 ),
  2869. sqrSin = 1 - cos * cos;
  2870. // Skip the Slerp for tiny steps to avoid numeric problems:
  2871. if ( sqrSin > Number.EPSILON ) {
  2872. const sin = Math.sqrt( sqrSin ),
  2873. len = Math.atan2( sin, cos * dir );
  2874. s = Math.sin( s * len ) / sin;
  2875. t = Math.sin( t * len ) / sin;
  2876. }
  2877. const tDir = t * dir;
  2878. x0 = x0 * s + x1 * tDir;
  2879. y0 = y0 * s + y1 * tDir;
  2880. z0 = z0 * s + z1 * tDir;
  2881. w0 = w0 * s + w1 * tDir;
  2882. // Normalize in case we just did a lerp:
  2883. if ( s === 1 - t ) {
  2884. const f = 1 / Math.sqrt( x0 * x0 + y0 * y0 + z0 * z0 + w0 * w0 );
  2885. x0 *= f;
  2886. y0 *= f;
  2887. z0 *= f;
  2888. w0 *= f;
  2889. }
  2890. }
  2891. dst[ dstOffset ] = x0;
  2892. dst[ dstOffset + 1 ] = y0;
  2893. dst[ dstOffset + 2 ] = z0;
  2894. dst[ dstOffset + 3 ] = w0;
  2895. }
  2896. /**
  2897. * Multiplies two quaternions. This implementation assumes the quaternion data are managed
  2898. * in flat arrays.
  2899. *
  2900. * @param {Array<number>} dst - The destination array.
  2901. * @param {number} dstOffset - An offset into the destination array.
  2902. * @param {Array<number>} src0 - The source array of the first quaternion.
  2903. * @param {number} srcOffset0 - An offset into the first source array.
  2904. * @param {Array<number>} src1 - The source array of the second quaternion.
  2905. * @param {number} srcOffset1 - An offset into the second source array.
  2906. * @return {Array<number>} The destination array.
  2907. * @see {@link Quaternion#multiplyQuaternions}.
  2908. */
  2909. static multiplyQuaternionsFlat( dst, dstOffset, src0, srcOffset0, src1, srcOffset1 ) {
  2910. const x0 = src0[ srcOffset0 ];
  2911. const y0 = src0[ srcOffset0 + 1 ];
  2912. const z0 = src0[ srcOffset0 + 2 ];
  2913. const w0 = src0[ srcOffset0 + 3 ];
  2914. const x1 = src1[ srcOffset1 ];
  2915. const y1 = src1[ srcOffset1 + 1 ];
  2916. const z1 = src1[ srcOffset1 + 2 ];
  2917. const w1 = src1[ srcOffset1 + 3 ];
  2918. dst[ dstOffset ] = x0 * w1 + w0 * x1 + y0 * z1 - z0 * y1;
  2919. dst[ dstOffset + 1 ] = y0 * w1 + w0 * y1 + z0 * x1 - x0 * z1;
  2920. dst[ dstOffset + 2 ] = z0 * w1 + w0 * z1 + x0 * y1 - y0 * x1;
  2921. dst[ dstOffset + 3 ] = w0 * w1 - x0 * x1 - y0 * y1 - z0 * z1;
  2922. return dst;
  2923. }
  2924. /**
  2925. * The x value of this quaternion.
  2926. *
  2927. * @type {number}
  2928. * @default 0
  2929. */
  2930. get x() {
  2931. return this._x;
  2932. }
  2933. set x( value ) {
  2934. this._x = value;
  2935. this._onChangeCallback();
  2936. }
  2937. /**
  2938. * The y value of this quaternion.
  2939. *
  2940. * @type {number}
  2941. * @default 0
  2942. */
  2943. get y() {
  2944. return this._y;
  2945. }
  2946. set y( value ) {
  2947. this._y = value;
  2948. this._onChangeCallback();
  2949. }
  2950. /**
  2951. * The z value of this quaternion.
  2952. *
  2953. * @type {number}
  2954. * @default 0
  2955. */
  2956. get z() {
  2957. return this._z;
  2958. }
  2959. set z( value ) {
  2960. this._z = value;
  2961. this._onChangeCallback();
  2962. }
  2963. /**
  2964. * The w value of this quaternion.
  2965. *
  2966. * @type {number}
  2967. * @default 1
  2968. */
  2969. get w() {
  2970. return this._w;
  2971. }
  2972. set w( value ) {
  2973. this._w = value;
  2974. this._onChangeCallback();
  2975. }
  2976. /**
  2977. * Sets the quaternion components.
  2978. *
  2979. * @param {number} x - The x value of this quaternion.
  2980. * @param {number} y - The y value of this quaternion.
  2981. * @param {number} z - The z value of this quaternion.
  2982. * @param {number} w - The w value of this quaternion.
  2983. * @return {Quaternion} A reference to this quaternion.
  2984. */
  2985. set( x, y, z, w ) {
  2986. this._x = x;
  2987. this._y = y;
  2988. this._z = z;
  2989. this._w = w;
  2990. this._onChangeCallback();
  2991. return this;
  2992. }
  2993. /**
  2994. * Returns a new quaternion with copied values from this instance.
  2995. *
  2996. * @return {Quaternion} A clone of this instance.
  2997. */
  2998. clone() {
  2999. return new this.constructor( this._x, this._y, this._z, this._w );
  3000. }
  3001. /**
  3002. * Copies the values of the given quaternion to this instance.
  3003. *
  3004. * @param {Quaternion} quaternion - The quaternion to copy.
  3005. * @return {Quaternion} A reference to this quaternion.
  3006. */
  3007. copy( quaternion ) {
  3008. this._x = quaternion.x;
  3009. this._y = quaternion.y;
  3010. this._z = quaternion.z;
  3011. this._w = quaternion.w;
  3012. this._onChangeCallback();
  3013. return this;
  3014. }
  3015. /**
  3016. * Sets this quaternion from the rotation specified by the given
  3017. * Euler angles.
  3018. *
  3019. * @param {Euler} euler - The Euler angles.
  3020. * @param {boolean} [update=true] - Whether the internal `onChange` callback should be executed or not.
  3021. * @return {Quaternion} A reference to this quaternion.
  3022. */
  3023. setFromEuler( euler, update = true ) {
  3024. const x = euler._x, y = euler._y, z = euler._z, order = euler._order;
  3025. // http://www.mathworks.com/matlabcentral/fileexchange/
  3026. // 20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/
  3027. // content/SpinCalc.m
  3028. const cos = Math.cos;
  3029. const sin = Math.sin;
  3030. const c1 = cos( x / 2 );
  3031. const c2 = cos( y / 2 );
  3032. const c3 = cos( z / 2 );
  3033. const s1 = sin( x / 2 );
  3034. const s2 = sin( y / 2 );
  3035. const s3 = sin( z / 2 );
  3036. switch ( order ) {
  3037. case 'XYZ':
  3038. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  3039. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  3040. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  3041. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  3042. break;
  3043. case 'YXZ':
  3044. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  3045. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  3046. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  3047. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  3048. break;
  3049. case 'ZXY':
  3050. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  3051. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  3052. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  3053. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  3054. break;
  3055. case 'ZYX':
  3056. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  3057. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  3058. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  3059. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  3060. break;
  3061. case 'YZX':
  3062. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  3063. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  3064. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  3065. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  3066. break;
  3067. case 'XZY':
  3068. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  3069. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  3070. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  3071. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  3072. break;
  3073. default:
  3074. console.warn( 'THREE.Quaternion: .setFromEuler() encountered an unknown order: ' + order );
  3075. }
  3076. if ( update === true ) this._onChangeCallback();
  3077. return this;
  3078. }
  3079. /**
  3080. * Sets this quaternion from the given axis and angle.
  3081. *
  3082. * @param {Vector3} axis - The normalized axis.
  3083. * @param {number} angle - The angle in radians.
  3084. * @return {Quaternion} A reference to this quaternion.
  3085. */
  3086. setFromAxisAngle( axis, angle ) {
  3087. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm
  3088. const halfAngle = angle / 2, s = Math.sin( halfAngle );
  3089. this._x = axis.x * s;
  3090. this._y = axis.y * s;
  3091. this._z = axis.z * s;
  3092. this._w = Math.cos( halfAngle );
  3093. this._onChangeCallback();
  3094. return this;
  3095. }
  3096. /**
  3097. * Sets this quaternion from the given rotation matrix.
  3098. *
  3099. * @param {Matrix4} m - A 4x4 matrix of which the upper 3x3 of matrix is a pure rotation matrix (i.e. unscaled).
  3100. * @return {Quaternion} A reference to this quaternion.
  3101. */
  3102. setFromRotationMatrix( m ) {
  3103. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm
  3104. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  3105. const te = m.elements,
  3106. m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ],
  3107. m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ],
  3108. m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ],
  3109. trace = m11 + m22 + m33;
  3110. if ( trace > 0 ) {
  3111. const s = 0.5 / Math.sqrt( trace + 1.0 );
  3112. this._w = 0.25 / s;
  3113. this._x = ( m32 - m23 ) * s;
  3114. this._y = ( m13 - m31 ) * s;
  3115. this._z = ( m21 - m12 ) * s;
  3116. } else if ( m11 > m22 && m11 > m33 ) {
  3117. const s = 2.0 * Math.sqrt( 1.0 + m11 - m22 - m33 );
  3118. this._w = ( m32 - m23 ) / s;
  3119. this._x = 0.25 * s;
  3120. this._y = ( m12 + m21 ) / s;
  3121. this._z = ( m13 + m31 ) / s;
  3122. } else if ( m22 > m33 ) {
  3123. const s = 2.0 * Math.sqrt( 1.0 + m22 - m11 - m33 );
  3124. this._w = ( m13 - m31 ) / s;
  3125. this._x = ( m12 + m21 ) / s;
  3126. this._y = 0.25 * s;
  3127. this._z = ( m23 + m32 ) / s;
  3128. } else {
  3129. const s = 2.0 * Math.sqrt( 1.0 + m33 - m11 - m22 );
  3130. this._w = ( m21 - m12 ) / s;
  3131. this._x = ( m13 + m31 ) / s;
  3132. this._y = ( m23 + m32 ) / s;
  3133. this._z = 0.25 * s;
  3134. }
  3135. this._onChangeCallback();
  3136. return this;
  3137. }
  3138. /**
  3139. * Sets this quaternion to the rotation required to rotate the direction vector
  3140. * `vFrom` to the direction vector `vTo`.
  3141. *
  3142. * @param {Vector3} vFrom - The first (normalized) direction vector.
  3143. * @param {Vector3} vTo - The second (normalized) direction vector.
  3144. * @return {Quaternion} A reference to this quaternion.
  3145. */
  3146. setFromUnitVectors( vFrom, vTo ) {
  3147. // assumes direction vectors vFrom and vTo are normalized
  3148. let r = vFrom.dot( vTo ) + 1;
  3149. if ( r < Number.EPSILON ) {
  3150. // vFrom and vTo point in opposite directions
  3151. r = 0;
  3152. if ( Math.abs( vFrom.x ) > Math.abs( vFrom.z ) ) {
  3153. this._x = - vFrom.y;
  3154. this._y = vFrom.x;
  3155. this._z = 0;
  3156. this._w = r;
  3157. } else {
  3158. this._x = 0;
  3159. this._y = - vFrom.z;
  3160. this._z = vFrom.y;
  3161. this._w = r;
  3162. }
  3163. } else {
  3164. // crossVectors( vFrom, vTo ); // inlined to avoid cyclic dependency on Vector3
  3165. this._x = vFrom.y * vTo.z - vFrom.z * vTo.y;
  3166. this._y = vFrom.z * vTo.x - vFrom.x * vTo.z;
  3167. this._z = vFrom.x * vTo.y - vFrom.y * vTo.x;
  3168. this._w = r;
  3169. }
  3170. return this.normalize();
  3171. }
  3172. /**
  3173. * Returns the angle between this quaternion and the given one in radians.
  3174. *
  3175. * @param {Quaternion} q - The quaternion to compute the angle with.
  3176. * @return {number} The angle in radians.
  3177. */
  3178. angleTo( q ) {
  3179. return 2 * Math.acos( Math.abs( clamp( this.dot( q ), -1, 1 ) ) );
  3180. }
  3181. /**
  3182. * Rotates this quaternion by a given angular step to the given quaternion.
  3183. * The method ensures that the final quaternion will not overshoot `q`.
  3184. *
  3185. * @param {Quaternion} q - The target quaternion.
  3186. * @param {number} step - The angular step in radians.
  3187. * @return {Quaternion} A reference to this quaternion.
  3188. */
  3189. rotateTowards( q, step ) {
  3190. const angle = this.angleTo( q );
  3191. if ( angle === 0 ) return this;
  3192. const t = Math.min( 1, step / angle );
  3193. this.slerp( q, t );
  3194. return this;
  3195. }
  3196. /**
  3197. * Sets this quaternion to the identity quaternion; that is, to the
  3198. * quaternion that represents "no rotation".
  3199. *
  3200. * @return {Quaternion} A reference to this quaternion.
  3201. */
  3202. identity() {
  3203. return this.set( 0, 0, 0, 1 );
  3204. }
  3205. /**
  3206. * Inverts this quaternion via {@link Quaternion#conjugate}. The
  3207. * quaternion is assumed to have unit length.
  3208. *
  3209. * @return {Quaternion} A reference to this quaternion.
  3210. */
  3211. invert() {
  3212. return this.conjugate();
  3213. }
  3214. /**
  3215. * Returns the rotational conjugate of this quaternion. The conjugate of a
  3216. * quaternion represents the same rotation in the opposite direction about
  3217. * the rotational axis.
  3218. *
  3219. * @return {Quaternion} A reference to this quaternion.
  3220. */
  3221. conjugate() {
  3222. this._x *= -1;
  3223. this._y *= -1;
  3224. this._z *= -1;
  3225. this._onChangeCallback();
  3226. return this;
  3227. }
  3228. /**
  3229. * Calculates the dot product of this quaternion and the given one.
  3230. *
  3231. * @param {Quaternion} v - The quaternion to compute the dot product with.
  3232. * @return {number} The result of the dot product.
  3233. */
  3234. dot( v ) {
  3235. return this._x * v._x + this._y * v._y + this._z * v._z + this._w * v._w;
  3236. }
  3237. /**
  3238. * Computes the squared Euclidean length (straight-line length) of this quaternion,
  3239. * considered as a 4 dimensional vector. This can be useful if you are comparing the
  3240. * lengths of two quaternions, as this is a slightly more efficient calculation than
  3241. * {@link Quaternion#length}.
  3242. *
  3243. * @return {number} The squared Euclidean length.
  3244. */
  3245. lengthSq() {
  3246. return this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w;
  3247. }
  3248. /**
  3249. * Computes the Euclidean length (straight-line length) of this quaternion,
  3250. * considered as a 4 dimensional vector.
  3251. *
  3252. * @return {number} The Euclidean length.
  3253. */
  3254. length() {
  3255. return Math.sqrt( this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w );
  3256. }
  3257. /**
  3258. * Normalizes this quaternion - that is, calculated the quaternion that performs
  3259. * the same rotation as this one, but has a length equal to `1`.
  3260. *
  3261. * @return {Quaternion} A reference to this quaternion.
  3262. */
  3263. normalize() {
  3264. let l = this.length();
  3265. if ( l === 0 ) {
  3266. this._x = 0;
  3267. this._y = 0;
  3268. this._z = 0;
  3269. this._w = 1;
  3270. } else {
  3271. l = 1 / l;
  3272. this._x = this._x * l;
  3273. this._y = this._y * l;
  3274. this._z = this._z * l;
  3275. this._w = this._w * l;
  3276. }
  3277. this._onChangeCallback();
  3278. return this;
  3279. }
  3280. /**
  3281. * Multiplies this quaternion by the given one.
  3282. *
  3283. * @param {Quaternion} q - The quaternion.
  3284. * @return {Quaternion} A reference to this quaternion.
  3285. */
  3286. multiply( q ) {
  3287. return this.multiplyQuaternions( this, q );
  3288. }
  3289. /**
  3290. * Pre-multiplies this quaternion by the given one.
  3291. *
  3292. * @param {Quaternion} q - The quaternion.
  3293. * @return {Quaternion} A reference to this quaternion.
  3294. */
  3295. premultiply( q ) {
  3296. return this.multiplyQuaternions( q, this );
  3297. }
  3298. /**
  3299. * Multiplies the given quaternions and stores the result in this instance.
  3300. *
  3301. * @param {Quaternion} a - The first quaternion.
  3302. * @param {Quaternion} b - The second quaternion.
  3303. * @return {Quaternion} A reference to this quaternion.
  3304. */
  3305. multiplyQuaternions( a, b ) {
  3306. // from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm
  3307. const qax = a._x, qay = a._y, qaz = a._z, qaw = a._w;
  3308. const qbx = b._x, qby = b._y, qbz = b._z, qbw = b._w;
  3309. this._x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby;
  3310. this._y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz;
  3311. this._z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx;
  3312. this._w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz;
  3313. this._onChangeCallback();
  3314. return this;
  3315. }
  3316. /**
  3317. * Performs a spherical linear interpolation between quaternions.
  3318. *
  3319. * @param {Quaternion} qb - The target quaternion.
  3320. * @param {number} t - The interpolation factor in the closed interval `[0, 1]`.
  3321. * @return {Quaternion} A reference to this quaternion.
  3322. */
  3323. slerp( qb, t ) {
  3324. if ( t === 0 ) return this;
  3325. if ( t === 1 ) return this.copy( qb );
  3326. const x = this._x, y = this._y, z = this._z, w = this._w;
  3327. // http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/
  3328. let cosHalfTheta = w * qb._w + x * qb._x + y * qb._y + z * qb._z;
  3329. if ( cosHalfTheta < 0 ) {
  3330. this._w = - qb._w;
  3331. this._x = - qb._x;
  3332. this._y = - qb._y;
  3333. this._z = - qb._z;
  3334. cosHalfTheta = - cosHalfTheta;
  3335. } else {
  3336. this.copy( qb );
  3337. }
  3338. if ( cosHalfTheta >= 1.0 ) {
  3339. this._w = w;
  3340. this._x = x;
  3341. this._y = y;
  3342. this._z = z;
  3343. return this;
  3344. }
  3345. const sqrSinHalfTheta = 1.0 - cosHalfTheta * cosHalfTheta;
  3346. if ( sqrSinHalfTheta <= Number.EPSILON ) {
  3347. const s = 1 - t;
  3348. this._w = s * w + t * this._w;
  3349. this._x = s * x + t * this._x;
  3350. this._y = s * y + t * this._y;
  3351. this._z = s * z + t * this._z;
  3352. this.normalize(); // normalize calls _onChangeCallback()
  3353. return this;
  3354. }
  3355. const sinHalfTheta = Math.sqrt( sqrSinHalfTheta );
  3356. const halfTheta = Math.atan2( sinHalfTheta, cosHalfTheta );
  3357. const ratioA = Math.sin( ( 1 - t ) * halfTheta ) / sinHalfTheta,
  3358. ratioB = Math.sin( t * halfTheta ) / sinHalfTheta;
  3359. this._w = ( w * ratioA + this._w * ratioB );
  3360. this._x = ( x * ratioA + this._x * ratioB );
  3361. this._y = ( y * ratioA + this._y * ratioB );
  3362. this._z = ( z * ratioA + this._z * ratioB );
  3363. this._onChangeCallback();
  3364. return this;
  3365. }
  3366. /**
  3367. * Performs a spherical linear interpolation between the given quaternions
  3368. * and stores the result in this quaternion.
  3369. *
  3370. * @param {Quaternion} qa - The source quaternion.
  3371. * @param {Quaternion} qb - The target quaternion.
  3372. * @param {number} t - The interpolation factor in the closed interval `[0, 1]`.
  3373. * @return {Quaternion} A reference to this quaternion.
  3374. */
  3375. slerpQuaternions( qa, qb, t ) {
  3376. return this.copy( qa ).slerp( qb, t );
  3377. }
  3378. /**
  3379. * Sets this quaternion to a uniformly random, normalized quaternion.
  3380. *
  3381. * @return {Quaternion} A reference to this quaternion.
  3382. */
  3383. random() {
  3384. // Ken Shoemake
  3385. // Uniform random rotations
  3386. // D. Kirk, editor, Graphics Gems III, pages 124-132. Academic Press, New York, 1992.
  3387. const theta1 = 2 * Math.PI * Math.random();
  3388. const theta2 = 2 * Math.PI * Math.random();
  3389. const x0 = Math.random();
  3390. const r1 = Math.sqrt( 1 - x0 );
  3391. const r2 = Math.sqrt( x0 );
  3392. return this.set(
  3393. r1 * Math.sin( theta1 ),
  3394. r1 * Math.cos( theta1 ),
  3395. r2 * Math.sin( theta2 ),
  3396. r2 * Math.cos( theta2 ),
  3397. );
  3398. }
  3399. /**
  3400. * Returns `true` if this quaternion is equal with the given one.
  3401. *
  3402. * @param {Quaternion} quaternion - The quaternion to test for equality.
  3403. * @return {boolean} Whether this quaternion is equal with the given one.
  3404. */
  3405. equals( quaternion ) {
  3406. return ( quaternion._x === this._x ) && ( quaternion._y === this._y ) && ( quaternion._z === this._z ) && ( quaternion._w === this._w );
  3407. }
  3408. /**
  3409. * Sets this quaternion's components from the given array.
  3410. *
  3411. * @param {Array<number>} array - An array holding the quaternion component values.
  3412. * @param {number} [offset=0] - The offset into the array.
  3413. * @return {Quaternion} A reference to this quaternion.
  3414. */
  3415. fromArray( array, offset = 0 ) {
  3416. this._x = array[ offset ];
  3417. this._y = array[ offset + 1 ];
  3418. this._z = array[ offset + 2 ];
  3419. this._w = array[ offset + 3 ];
  3420. this._onChangeCallback();
  3421. return this;
  3422. }
  3423. /**
  3424. * Writes the components of this quaternion to the given array. If no array is provided,
  3425. * the method returns a new instance.
  3426. *
  3427. * @param {Array<number>} [array=[]] - The target array holding the quaternion components.
  3428. * @param {number} [offset=0] - Index of the first element in the array.
  3429. * @return {Array<number>} The quaternion components.
  3430. */
  3431. toArray( array = [], offset = 0 ) {
  3432. array[ offset ] = this._x;
  3433. array[ offset + 1 ] = this._y;
  3434. array[ offset + 2 ] = this._z;
  3435. array[ offset + 3 ] = this._w;
  3436. return array;
  3437. }
  3438. /**
  3439. * Sets the components of this quaternion from the given buffer attribute.
  3440. *
  3441. * @param {BufferAttribute} attribute - The buffer attribute holding quaternion data.
  3442. * @param {number} index - The index into the attribute.
  3443. * @return {Quaternion} A reference to this quaternion.
  3444. */
  3445. fromBufferAttribute( attribute, index ) {
  3446. this._x = attribute.getX( index );
  3447. this._y = attribute.getY( index );
  3448. this._z = attribute.getZ( index );
  3449. this._w = attribute.getW( index );
  3450. this._onChangeCallback();
  3451. return this;
  3452. }
  3453. /**
  3454. * This methods defines the serialization result of this class. Returns the
  3455. * numerical elements of this quaternion in an array of format `[x, y, z, w]`.
  3456. *
  3457. * @return {Array<number>} The serialized quaternion.
  3458. */
  3459. toJSON() {
  3460. return this.toArray();
  3461. }
  3462. _onChange( callback ) {
  3463. this._onChangeCallback = callback;
  3464. return this;
  3465. }
  3466. _onChangeCallback() {}
  3467. *[ Symbol.iterator ]() {
  3468. yield this._x;
  3469. yield this._y;
  3470. yield this._z;
  3471. yield this._w;
  3472. }
  3473. }
  3474. /**
  3475. * Class representing a 3D vector. A 3D vector is an ordered triplet of numbers
  3476. * (labeled x, y and z), which can be used to represent a number of things, such as:
  3477. *
  3478. * - A point in 3D space.
  3479. * - A direction and length in 3D space. In three.js the length will
  3480. * always be the Euclidean distance(straight-line distance) from `(0, 0, 0)` to `(x, y, z)`
  3481. * and the direction is also measured from `(0, 0, 0)` towards `(x, y, z)`.
  3482. * - Any arbitrary ordered triplet of numbers.
  3483. *
  3484. * There are other things a 3D vector can be used to represent, such as
  3485. * momentum vectors and so on, however these are the most
  3486. * common uses in three.js.
  3487. *
  3488. * Iterating through a vector instance will yield its components `(x, y, z)` in
  3489. * the corresponding order.
  3490. * ```js
  3491. * const a = new THREE.Vector3( 0, 1, 0 );
  3492. *
  3493. * //no arguments; will be initialised to (0, 0, 0)
  3494. * const b = new THREE.Vector3( );
  3495. *
  3496. * const d = a.distanceTo( b );
  3497. * ```
  3498. */
  3499. class Vector3 {
  3500. /**
  3501. * Constructs a new 3D vector.
  3502. *
  3503. * @param {number} [x=0] - The x value of this vector.
  3504. * @param {number} [y=0] - The y value of this vector.
  3505. * @param {number} [z=0] - The z value of this vector.
  3506. */
  3507. constructor( x = 0, y = 0, z = 0 ) {
  3508. /**
  3509. * This flag can be used for type testing.
  3510. *
  3511. * @type {boolean}
  3512. * @readonly
  3513. * @default true
  3514. */
  3515. Vector3.prototype.isVector3 = true;
  3516. /**
  3517. * The x value of this vector.
  3518. *
  3519. * @type {number}
  3520. */
  3521. this.x = x;
  3522. /**
  3523. * The y value of this vector.
  3524. *
  3525. * @type {number}
  3526. */
  3527. this.y = y;
  3528. /**
  3529. * The z value of this vector.
  3530. *
  3531. * @type {number}
  3532. */
  3533. this.z = z;
  3534. }
  3535. /**
  3536. * Sets the vector components.
  3537. *
  3538. * @param {number} x - The value of the x component.
  3539. * @param {number} y - The value of the y component.
  3540. * @param {number} z - The value of the z component.
  3541. * @return {Vector3} A reference to this vector.
  3542. */
  3543. set( x, y, z ) {
  3544. if ( z === undefined ) z = this.z; // sprite.scale.set(x,y)
  3545. this.x = x;
  3546. this.y = y;
  3547. this.z = z;
  3548. return this;
  3549. }
  3550. /**
  3551. * Sets the vector components to the same value.
  3552. *
  3553. * @param {number} scalar - The value to set for all vector components.
  3554. * @return {Vector3} A reference to this vector.
  3555. */
  3556. setScalar( scalar ) {
  3557. this.x = scalar;
  3558. this.y = scalar;
  3559. this.z = scalar;
  3560. return this;
  3561. }
  3562. /**
  3563. * Sets the vector's x component to the given value
  3564. *
  3565. * @param {number} x - The value to set.
  3566. * @return {Vector3} A reference to this vector.
  3567. */
  3568. setX( x ) {
  3569. this.x = x;
  3570. return this;
  3571. }
  3572. /**
  3573. * Sets the vector's y component to the given value
  3574. *
  3575. * @param {number} y - The value to set.
  3576. * @return {Vector3} A reference to this vector.
  3577. */
  3578. setY( y ) {
  3579. this.y = y;
  3580. return this;
  3581. }
  3582. /**
  3583. * Sets the vector's z component to the given value
  3584. *
  3585. * @param {number} z - The value to set.
  3586. * @return {Vector3} A reference to this vector.
  3587. */
  3588. setZ( z ) {
  3589. this.z = z;
  3590. return this;
  3591. }
  3592. /**
  3593. * Allows to set a vector component with an index.
  3594. *
  3595. * @param {number} index - The component index. `0` equals to x, `1` equals to y, `2` equals to z.
  3596. * @param {number} value - The value to set.
  3597. * @return {Vector3} A reference to this vector.
  3598. */
  3599. setComponent( index, value ) {
  3600. switch ( index ) {
  3601. case 0: this.x = value; break;
  3602. case 1: this.y = value; break;
  3603. case 2: this.z = value; break;
  3604. default: throw new Error( 'index is out of range: ' + index );
  3605. }
  3606. return this;
  3607. }
  3608. /**
  3609. * Returns the value of the vector component which matches the given index.
  3610. *
  3611. * @param {number} index - The component index. `0` equals to x, `1` equals to y, `2` equals to z.
  3612. * @return {number} A vector component value.
  3613. */
  3614. getComponent( index ) {
  3615. switch ( index ) {
  3616. case 0: return this.x;
  3617. case 1: return this.y;
  3618. case 2: return this.z;
  3619. default: throw new Error( 'index is out of range: ' + index );
  3620. }
  3621. }
  3622. /**
  3623. * Returns a new vector with copied values from this instance.
  3624. *
  3625. * @return {Vector3} A clone of this instance.
  3626. */
  3627. clone() {
  3628. return new this.constructor( this.x, this.y, this.z );
  3629. }
  3630. /**
  3631. * Copies the values of the given vector to this instance.
  3632. *
  3633. * @param {Vector3} v - The vector to copy.
  3634. * @return {Vector3} A reference to this vector.
  3635. */
  3636. copy( v ) {
  3637. this.x = v.x;
  3638. this.y = v.y;
  3639. this.z = v.z;
  3640. return this;
  3641. }
  3642. /**
  3643. * Adds the given vector to this instance.
  3644. *
  3645. * @param {Vector3} v - The vector to add.
  3646. * @return {Vector3} A reference to this vector.
  3647. */
  3648. add( v ) {
  3649. this.x += v.x;
  3650. this.y += v.y;
  3651. this.z += v.z;
  3652. return this;
  3653. }
  3654. /**
  3655. * Adds the given scalar value to all components of this instance.
  3656. *
  3657. * @param {number} s - The scalar to add.
  3658. * @return {Vector3} A reference to this vector.
  3659. */
  3660. addScalar( s ) {
  3661. this.x += s;
  3662. this.y += s;
  3663. this.z += s;
  3664. return this;
  3665. }
  3666. /**
  3667. * Adds the given vectors and stores the result in this instance.
  3668. *
  3669. * @param {Vector3} a - The first vector.
  3670. * @param {Vector3} b - The second vector.
  3671. * @return {Vector3} A reference to this vector.
  3672. */
  3673. addVectors( a, b ) {
  3674. this.x = a.x + b.x;
  3675. this.y = a.y + b.y;
  3676. this.z = a.z + b.z;
  3677. return this;
  3678. }
  3679. /**
  3680. * Adds the given vector scaled by the given factor to this instance.
  3681. *
  3682. * @param {Vector3|Vector4} v - The vector.
  3683. * @param {number} s - The factor that scales `v`.
  3684. * @return {Vector3} A reference to this vector.
  3685. */
  3686. addScaledVector( v, s ) {
  3687. this.x += v.x * s;
  3688. this.y += v.y * s;
  3689. this.z += v.z * s;
  3690. return this;
  3691. }
  3692. /**
  3693. * Subtracts the given vector from this instance.
  3694. *
  3695. * @param {Vector3} v - The vector to subtract.
  3696. * @return {Vector3} A reference to this vector.
  3697. */
  3698. sub( v ) {
  3699. this.x -= v.x;
  3700. this.y -= v.y;
  3701. this.z -= v.z;
  3702. return this;
  3703. }
  3704. /**
  3705. * Subtracts the given scalar value from all components of this instance.
  3706. *
  3707. * @param {number} s - The scalar to subtract.
  3708. * @return {Vector3} A reference to this vector.
  3709. */
  3710. subScalar( s ) {
  3711. this.x -= s;
  3712. this.y -= s;
  3713. this.z -= s;
  3714. return this;
  3715. }
  3716. /**
  3717. * Subtracts the given vectors and stores the result in this instance.
  3718. *
  3719. * @param {Vector3} a - The first vector.
  3720. * @param {Vector3} b - The second vector.
  3721. * @return {Vector3} A reference to this vector.
  3722. */
  3723. subVectors( a, b ) {
  3724. this.x = a.x - b.x;
  3725. this.y = a.y - b.y;
  3726. this.z = a.z - b.z;
  3727. return this;
  3728. }
  3729. /**
  3730. * Multiplies the given vector with this instance.
  3731. *
  3732. * @param {Vector3} v - The vector to multiply.
  3733. * @return {Vector3} A reference to this vector.
  3734. */
  3735. multiply( v ) {
  3736. this.x *= v.x;
  3737. this.y *= v.y;
  3738. this.z *= v.z;
  3739. return this;
  3740. }
  3741. /**
  3742. * Multiplies the given scalar value with all components of this instance.
  3743. *
  3744. * @param {number} scalar - The scalar to multiply.
  3745. * @return {Vector3} A reference to this vector.
  3746. */
  3747. multiplyScalar( scalar ) {
  3748. this.x *= scalar;
  3749. this.y *= scalar;
  3750. this.z *= scalar;
  3751. return this;
  3752. }
  3753. /**
  3754. * Multiplies the given vectors and stores the result in this instance.
  3755. *
  3756. * @param {Vector3} a - The first vector.
  3757. * @param {Vector3} b - The second vector.
  3758. * @return {Vector3} A reference to this vector.
  3759. */
  3760. multiplyVectors( a, b ) {
  3761. this.x = a.x * b.x;
  3762. this.y = a.y * b.y;
  3763. this.z = a.z * b.z;
  3764. return this;
  3765. }
  3766. /**
  3767. * Applies the given Euler rotation to this vector.
  3768. *
  3769. * @param {Euler} euler - The Euler angles.
  3770. * @return {Vector3} A reference to this vector.
  3771. */
  3772. applyEuler( euler ) {
  3773. return this.applyQuaternion( _quaternion$4.setFromEuler( euler ) );
  3774. }
  3775. /**
  3776. * Applies a rotation specified by an axis and an angle to this vector.
  3777. *
  3778. * @param {Vector3} axis - A normalized vector representing the rotation axis.
  3779. * @param {number} angle - The angle in radians.
  3780. * @return {Vector3} A reference to this vector.
  3781. */
  3782. applyAxisAngle( axis, angle ) {
  3783. return this.applyQuaternion( _quaternion$4.setFromAxisAngle( axis, angle ) );
  3784. }
  3785. /**
  3786. * Multiplies this vector with the given 3x3 matrix.
  3787. *
  3788. * @param {Matrix3} m - The 3x3 matrix.
  3789. * @return {Vector3} A reference to this vector.
  3790. */
  3791. applyMatrix3( m ) {
  3792. const x = this.x, y = this.y, z = this.z;
  3793. const e = m.elements;
  3794. this.x = e[ 0 ] * x + e[ 3 ] * y + e[ 6 ] * z;
  3795. this.y = e[ 1 ] * x + e[ 4 ] * y + e[ 7 ] * z;
  3796. this.z = e[ 2 ] * x + e[ 5 ] * y + e[ 8 ] * z;
  3797. return this;
  3798. }
  3799. /**
  3800. * Multiplies this vector by the given normal matrix and normalizes
  3801. * the result.
  3802. *
  3803. * @param {Matrix3} m - The normal matrix.
  3804. * @return {Vector3} A reference to this vector.
  3805. */
  3806. applyNormalMatrix( m ) {
  3807. return this.applyMatrix3( m ).normalize();
  3808. }
  3809. /**
  3810. * Multiplies this vector (with an implicit 1 in the 4th dimension) by m, and
  3811. * divides by perspective.
  3812. *
  3813. * @param {Matrix4} m - The matrix to apply.
  3814. * @return {Vector3} A reference to this vector.
  3815. */
  3816. applyMatrix4( m ) {
  3817. const x = this.x, y = this.y, z = this.z;
  3818. const e = m.elements;
  3819. const w = 1 / ( e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] );
  3820. this.x = ( e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] ) * w;
  3821. this.y = ( e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] ) * w;
  3822. this.z = ( e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] ) * w;
  3823. return this;
  3824. }
  3825. /**
  3826. * Applies the given Quaternion to this vector.
  3827. *
  3828. * @param {Quaternion} q - The Quaternion.
  3829. * @return {Vector3} A reference to this vector.
  3830. */
  3831. applyQuaternion( q ) {
  3832. // quaternion q is assumed to have unit length
  3833. const vx = this.x, vy = this.y, vz = this.z;
  3834. const qx = q.x, qy = q.y, qz = q.z, qw = q.w;
  3835. // t = 2 * cross( q.xyz, v );
  3836. const tx = 2 * ( qy * vz - qz * vy );
  3837. const ty = 2 * ( qz * vx - qx * vz );
  3838. const tz = 2 * ( qx * vy - qy * vx );
  3839. // v + q.w * t + cross( q.xyz, t );
  3840. this.x = vx + qw * tx + qy * tz - qz * ty;
  3841. this.y = vy + qw * ty + qz * tx - qx * tz;
  3842. this.z = vz + qw * tz + qx * ty - qy * tx;
  3843. return this;
  3844. }
  3845. /**
  3846. * Projects this vector from world space into the camera's normalized
  3847. * device coordinate (NDC) space.
  3848. *
  3849. * @param {Camera} camera - The camera.
  3850. * @return {Vector3} A reference to this vector.
  3851. */
  3852. project( camera ) {
  3853. return this.applyMatrix4( camera.matrixWorldInverse ).applyMatrix4( camera.projectionMatrix );
  3854. }
  3855. /**
  3856. * Unprojects this vector from the camera's normalized device coordinate (NDC)
  3857. * space into world space.
  3858. *
  3859. * @param {Camera} camera - The camera.
  3860. * @return {Vector3} A reference to this vector.
  3861. */
  3862. unproject( camera ) {
  3863. return this.applyMatrix4( camera.projectionMatrixInverse ).applyMatrix4( camera.matrixWorld );
  3864. }
  3865. /**
  3866. * Transforms the direction of this vector by a matrix (the upper left 3 x 3
  3867. * subset of the given 4x4 matrix and then normalizes the result.
  3868. *
  3869. * @param {Matrix4} m - The matrix.
  3870. * @return {Vector3} A reference to this vector.
  3871. */
  3872. transformDirection( m ) {
  3873. // input: THREE.Matrix4 affine matrix
  3874. // vector interpreted as a direction
  3875. const x = this.x, y = this.y, z = this.z;
  3876. const e = m.elements;
  3877. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z;
  3878. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z;
  3879. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z;
  3880. return this.normalize();
  3881. }
  3882. /**
  3883. * Divides this instance by the given vector.
  3884. *
  3885. * @param {Vector3} v - The vector to divide.
  3886. * @return {Vector3} A reference to this vector.
  3887. */
  3888. divide( v ) {
  3889. this.x /= v.x;
  3890. this.y /= v.y;
  3891. this.z /= v.z;
  3892. return this;
  3893. }
  3894. /**
  3895. * Divides this vector by the given scalar.
  3896. *
  3897. * @param {number} scalar - The scalar to divide.
  3898. * @return {Vector3} A reference to this vector.
  3899. */
  3900. divideScalar( scalar ) {
  3901. return this.multiplyScalar( 1 / scalar );
  3902. }
  3903. /**
  3904. * If this vector's x, y or z value is greater than the given vector's x, y or z
  3905. * value, replace that value with the corresponding min value.
  3906. *
  3907. * @param {Vector3} v - The vector.
  3908. * @return {Vector3} A reference to this vector.
  3909. */
  3910. min( v ) {
  3911. this.x = Math.min( this.x, v.x );
  3912. this.y = Math.min( this.y, v.y );
  3913. this.z = Math.min( this.z, v.z );
  3914. return this;
  3915. }
  3916. /**
  3917. * If this vector's x, y or z value is less than the given vector's x, y or z
  3918. * value, replace that value with the corresponding max value.
  3919. *
  3920. * @param {Vector3} v - The vector.
  3921. * @return {Vector3} A reference to this vector.
  3922. */
  3923. max( v ) {
  3924. this.x = Math.max( this.x, v.x );
  3925. this.y = Math.max( this.y, v.y );
  3926. this.z = Math.max( this.z, v.z );
  3927. return this;
  3928. }
  3929. /**
  3930. * If this vector's x, y or z value is greater than the max vector's x, y or z
  3931. * value, it is replaced by the corresponding value.
  3932. * If this vector's x, y or z value is less than the min vector's x, y or z value,
  3933. * it is replaced by the corresponding value.
  3934. *
  3935. * @param {Vector3} min - The minimum x, y and z values.
  3936. * @param {Vector3} max - The maximum x, y and z values in the desired range.
  3937. * @return {Vector3} A reference to this vector.
  3938. */
  3939. clamp( min, max ) {
  3940. // assumes min < max, componentwise
  3941. this.x = clamp( this.x, min.x, max.x );
  3942. this.y = clamp( this.y, min.y, max.y );
  3943. this.z = clamp( this.z, min.z, max.z );
  3944. return this;
  3945. }
  3946. /**
  3947. * If this vector's x, y or z values are greater than the max value, they are
  3948. * replaced by the max value.
  3949. * If this vector's x, y or z values are less than the min value, they are
  3950. * replaced by the min value.
  3951. *
  3952. * @param {number} minVal - The minimum value the components will be clamped to.
  3953. * @param {number} maxVal - The maximum value the components will be clamped to.
  3954. * @return {Vector3} A reference to this vector.
  3955. */
  3956. clampScalar( minVal, maxVal ) {
  3957. this.x = clamp( this.x, minVal, maxVal );
  3958. this.y = clamp( this.y, minVal, maxVal );
  3959. this.z = clamp( this.z, minVal, maxVal );
  3960. return this;
  3961. }
  3962. /**
  3963. * If this vector's length is greater than the max value, it is replaced by
  3964. * the max value.
  3965. * If this vector's length is less than the min value, it is replaced by the
  3966. * min value.
  3967. *
  3968. * @param {number} min - The minimum value the vector length will be clamped to.
  3969. * @param {number} max - The maximum value the vector length will be clamped to.
  3970. * @return {Vector3} A reference to this vector.
  3971. */
  3972. clampLength( min, max ) {
  3973. const length = this.length();
  3974. return this.divideScalar( length || 1 ).multiplyScalar( clamp( length, min, max ) );
  3975. }
  3976. /**
  3977. * The components of this vector are rounded down to the nearest integer value.
  3978. *
  3979. * @return {Vector3} A reference to this vector.
  3980. */
  3981. floor() {
  3982. this.x = Math.floor( this.x );
  3983. this.y = Math.floor( this.y );
  3984. this.z = Math.floor( this.z );
  3985. return this;
  3986. }
  3987. /**
  3988. * The components of this vector are rounded up to the nearest integer value.
  3989. *
  3990. * @return {Vector3} A reference to this vector.
  3991. */
  3992. ceil() {
  3993. this.x = Math.ceil( this.x );
  3994. this.y = Math.ceil( this.y );
  3995. this.z = Math.ceil( this.z );
  3996. return this;
  3997. }
  3998. /**
  3999. * The components of this vector are rounded to the nearest integer value
  4000. *
  4001. * @return {Vector3} A reference to this vector.
  4002. */
  4003. round() {
  4004. this.x = Math.round( this.x );
  4005. this.y = Math.round( this.y );
  4006. this.z = Math.round( this.z );
  4007. return this;
  4008. }
  4009. /**
  4010. * The components of this vector are rounded towards zero (up if negative,
  4011. * down if positive) to an integer value.
  4012. *
  4013. * @return {Vector3} A reference to this vector.
  4014. */
  4015. roundToZero() {
  4016. this.x = Math.trunc( this.x );
  4017. this.y = Math.trunc( this.y );
  4018. this.z = Math.trunc( this.z );
  4019. return this;
  4020. }
  4021. /**
  4022. * Inverts this vector - i.e. sets x = -x, y = -y and z = -z.
  4023. *
  4024. * @return {Vector3} A reference to this vector.
  4025. */
  4026. negate() {
  4027. this.x = - this.x;
  4028. this.y = - this.y;
  4029. this.z = - this.z;
  4030. return this;
  4031. }
  4032. /**
  4033. * Calculates the dot product of the given vector with this instance.
  4034. *
  4035. * @param {Vector3} v - The vector to compute the dot product with.
  4036. * @return {number} The result of the dot product.
  4037. */
  4038. dot( v ) {
  4039. return this.x * v.x + this.y * v.y + this.z * v.z;
  4040. }
  4041. // TODO lengthSquared?
  4042. /**
  4043. * Computes the square of the Euclidean length (straight-line length) from
  4044. * (0, 0, 0) to (x, y, z). If you are comparing the lengths of vectors, you should
  4045. * compare the length squared instead as it is slightly more efficient to calculate.
  4046. *
  4047. * @return {number} The square length of this vector.
  4048. */
  4049. lengthSq() {
  4050. return this.x * this.x + this.y * this.y + this.z * this.z;
  4051. }
  4052. /**
  4053. * Computes the Euclidean length (straight-line length) from (0, 0, 0) to (x, y, z).
  4054. *
  4055. * @return {number} The length of this vector.
  4056. */
  4057. length() {
  4058. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z );
  4059. }
  4060. /**
  4061. * Computes the Manhattan length of this vector.
  4062. *
  4063. * @return {number} The length of this vector.
  4064. */
  4065. manhattanLength() {
  4066. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z );
  4067. }
  4068. /**
  4069. * Converts this vector to a unit vector - that is, sets it equal to a vector
  4070. * with the same direction as this one, but with a vector length of `1`.
  4071. *
  4072. * @return {Vector3} A reference to this vector.
  4073. */
  4074. normalize() {
  4075. return this.divideScalar( this.length() || 1 );
  4076. }
  4077. /**
  4078. * Sets this vector to a vector with the same direction as this one, but
  4079. * with the specified length.
  4080. *
  4081. * @param {number} length - The new length of this vector.
  4082. * @return {Vector3} A reference to this vector.
  4083. */
  4084. setLength( length ) {
  4085. return this.normalize().multiplyScalar( length );
  4086. }
  4087. /**
  4088. * Linearly interpolates between the given vector and this instance, where
  4089. * alpha is the percent distance along the line - alpha = 0 will be this
  4090. * vector, and alpha = 1 will be the given one.
  4091. *
  4092. * @param {Vector3} v - The vector to interpolate towards.
  4093. * @param {number} alpha - The interpolation factor, typically in the closed interval `[0, 1]`.
  4094. * @return {Vector3} A reference to this vector.
  4095. */
  4096. lerp( v, alpha ) {
  4097. this.x += ( v.x - this.x ) * alpha;
  4098. this.y += ( v.y - this.y ) * alpha;
  4099. this.z += ( v.z - this.z ) * alpha;
  4100. return this;
  4101. }
  4102. /**
  4103. * Linearly interpolates between the given vectors, where alpha is the percent
  4104. * distance along the line - alpha = 0 will be first vector, and alpha = 1 will
  4105. * be the second one. The result is stored in this instance.
  4106. *
  4107. * @param {Vector3} v1 - The first vector.
  4108. * @param {Vector3} v2 - The second vector.
  4109. * @param {number} alpha - The interpolation factor, typically in the closed interval `[0, 1]`.
  4110. * @return {Vector3} A reference to this vector.
  4111. */
  4112. lerpVectors( v1, v2, alpha ) {
  4113. this.x = v1.x + ( v2.x - v1.x ) * alpha;
  4114. this.y = v1.y + ( v2.y - v1.y ) * alpha;
  4115. this.z = v1.z + ( v2.z - v1.z ) * alpha;
  4116. return this;
  4117. }
  4118. /**
  4119. * Calculates the cross product of the given vector with this instance.
  4120. *
  4121. * @param {Vector3} v - The vector to compute the cross product with.
  4122. * @return {Vector3} The result of the cross product.
  4123. */
  4124. cross( v ) {
  4125. return this.crossVectors( this, v );
  4126. }
  4127. /**
  4128. * Calculates the cross product of the given vectors and stores the result
  4129. * in this instance.
  4130. *
  4131. * @param {Vector3} a - The first vector.
  4132. * @param {Vector3} b - The second vector.
  4133. * @return {Vector3} A reference to this vector.
  4134. */
  4135. crossVectors( a, b ) {
  4136. const ax = a.x, ay = a.y, az = a.z;
  4137. const bx = b.x, by = b.y, bz = b.z;
  4138. this.x = ay * bz - az * by;
  4139. this.y = az * bx - ax * bz;
  4140. this.z = ax * by - ay * bx;
  4141. return this;
  4142. }
  4143. /**
  4144. * Projects this vector onto the given one.
  4145. *
  4146. * @param {Vector3} v - The vector to project to.
  4147. * @return {Vector3} A reference to this vector.
  4148. */
  4149. projectOnVector( v ) {
  4150. const denominator = v.lengthSq();
  4151. if ( denominator === 0 ) return this.set( 0, 0, 0 );
  4152. const scalar = v.dot( this ) / denominator;
  4153. return this.copy( v ).multiplyScalar( scalar );
  4154. }
  4155. /**
  4156. * Projects this vector onto a plane by subtracting this
  4157. * vector projected onto the plane's normal from this vector.
  4158. *
  4159. * @param {Vector3} planeNormal - The plane normal.
  4160. * @return {Vector3} A reference to this vector.
  4161. */
  4162. projectOnPlane( planeNormal ) {
  4163. _vector$c.copy( this ).projectOnVector( planeNormal );
  4164. return this.sub( _vector$c );
  4165. }
  4166. /**
  4167. * Reflects this vector off a plane orthogonal to the given normal vector.
  4168. *
  4169. * @param {Vector3} normal - The (normalized) normal vector.
  4170. * @return {Vector3} A reference to this vector.
  4171. */
  4172. reflect( normal ) {
  4173. return this.sub( _vector$c.copy( normal ).multiplyScalar( 2 * this.dot( normal ) ) );
  4174. }
  4175. /**
  4176. * Returns the angle between the given vector and this instance in radians.
  4177. *
  4178. * @param {Vector3} v - The vector to compute the angle with.
  4179. * @return {number} The angle in radians.
  4180. */
  4181. angleTo( v ) {
  4182. const denominator = Math.sqrt( this.lengthSq() * v.lengthSq() );
  4183. if ( denominator === 0 ) return Math.PI / 2;
  4184. const theta = this.dot( v ) / denominator;
  4185. // clamp, to handle numerical problems
  4186. return Math.acos( clamp( theta, -1, 1 ) );
  4187. }
  4188. /**
  4189. * Computes the distance from the given vector to this instance.
  4190. *
  4191. * @param {Vector3} v - The vector to compute the distance to.
  4192. * @return {number} The distance.
  4193. */
  4194. distanceTo( v ) {
  4195. return Math.sqrt( this.distanceToSquared( v ) );
  4196. }
  4197. /**
  4198. * Computes the squared distance from the given vector to this instance.
  4199. * If you are just comparing the distance with another distance, you should compare
  4200. * the distance squared instead as it is slightly more efficient to calculate.
  4201. *
  4202. * @param {Vector3} v - The vector to compute the squared distance to.
  4203. * @return {number} The squared distance.
  4204. */
  4205. distanceToSquared( v ) {
  4206. const dx = this.x - v.x, dy = this.y - v.y, dz = this.z - v.z;
  4207. return dx * dx + dy * dy + dz * dz;
  4208. }
  4209. /**
  4210. * Computes the Manhattan distance from the given vector to this instance.
  4211. *
  4212. * @param {Vector3} v - The vector to compute the Manhattan distance to.
  4213. * @return {number} The Manhattan distance.
  4214. */
  4215. manhattanDistanceTo( v ) {
  4216. return Math.abs( this.x - v.x ) + Math.abs( this.y - v.y ) + Math.abs( this.z - v.z );
  4217. }
  4218. /**
  4219. * Sets the vector components from the given spherical coordinates.
  4220. *
  4221. * @param {Spherical} s - The spherical coordinates.
  4222. * @return {Vector3} A reference to this vector.
  4223. */
  4224. setFromSpherical( s ) {
  4225. return this.setFromSphericalCoords( s.radius, s.phi, s.theta );
  4226. }
  4227. /**
  4228. * Sets the vector components from the given spherical coordinates.
  4229. *
  4230. * @param {number} radius - The radius.
  4231. * @param {number} phi - The phi angle in radians.
  4232. * @param {number} theta - The theta angle in radians.
  4233. * @return {Vector3} A reference to this vector.
  4234. */
  4235. setFromSphericalCoords( radius, phi, theta ) {
  4236. const sinPhiRadius = Math.sin( phi ) * radius;
  4237. this.x = sinPhiRadius * Math.sin( theta );
  4238. this.y = Math.cos( phi ) * radius;
  4239. this.z = sinPhiRadius * Math.cos( theta );
  4240. return this;
  4241. }
  4242. /**
  4243. * Sets the vector components from the given cylindrical coordinates.
  4244. *
  4245. * @param {Cylindrical} c - The cylindrical coordinates.
  4246. * @return {Vector3} A reference to this vector.
  4247. */
  4248. setFromCylindrical( c ) {
  4249. return this.setFromCylindricalCoords( c.radius, c.theta, c.y );
  4250. }
  4251. /**
  4252. * Sets the vector components from the given cylindrical coordinates.
  4253. *
  4254. * @param {number} radius - The radius.
  4255. * @param {number} theta - The theta angle in radians.
  4256. * @param {number} y - The y value.
  4257. * @return {Vector3} A reference to this vector.
  4258. */
  4259. setFromCylindricalCoords( radius, theta, y ) {
  4260. this.x = radius * Math.sin( theta );
  4261. this.y = y;
  4262. this.z = radius * Math.cos( theta );
  4263. return this;
  4264. }
  4265. /**
  4266. * Sets the vector components to the position elements of the
  4267. * given transformation matrix.
  4268. *
  4269. * @param {Matrix4} m - The 4x4 matrix.
  4270. * @return {Vector3} A reference to this vector.
  4271. */
  4272. setFromMatrixPosition( m ) {
  4273. const e = m.elements;
  4274. this.x = e[ 12 ];
  4275. this.y = e[ 13 ];
  4276. this.z = e[ 14 ];
  4277. return this;
  4278. }
  4279. /**
  4280. * Sets the vector components to the scale elements of the
  4281. * given transformation matrix.
  4282. *
  4283. * @param {Matrix4} m - The 4x4 matrix.
  4284. * @return {Vector3} A reference to this vector.
  4285. */
  4286. setFromMatrixScale( m ) {
  4287. const sx = this.setFromMatrixColumn( m, 0 ).length();
  4288. const sy = this.setFromMatrixColumn( m, 1 ).length();
  4289. const sz = this.setFromMatrixColumn( m, 2 ).length();
  4290. this.x = sx;
  4291. this.y = sy;
  4292. this.z = sz;
  4293. return this;
  4294. }
  4295. /**
  4296. * Sets the vector components from the specified matrix column.
  4297. *
  4298. * @param {Matrix4} m - The 4x4 matrix.
  4299. * @param {number} index - The column index.
  4300. * @return {Vector3} A reference to this vector.
  4301. */
  4302. setFromMatrixColumn( m, index ) {
  4303. return this.fromArray( m.elements, index * 4 );
  4304. }
  4305. /**
  4306. * Sets the vector components from the specified matrix column.
  4307. *
  4308. * @param {Matrix3} m - The 3x3 matrix.
  4309. * @param {number} index - The column index.
  4310. * @return {Vector3} A reference to this vector.
  4311. */
  4312. setFromMatrix3Column( m, index ) {
  4313. return this.fromArray( m.elements, index * 3 );
  4314. }
  4315. /**
  4316. * Sets the vector components from the given Euler angles.
  4317. *
  4318. * @param {Euler} e - The Euler angles to set.
  4319. * @return {Vector3} A reference to this vector.
  4320. */
  4321. setFromEuler( e ) {
  4322. this.x = e._x;
  4323. this.y = e._y;
  4324. this.z = e._z;
  4325. return this;
  4326. }
  4327. /**
  4328. * Sets the vector components from the RGB components of the
  4329. * given color.
  4330. *
  4331. * @param {Color} c - The color to set.
  4332. * @return {Vector3} A reference to this vector.
  4333. */
  4334. setFromColor( c ) {
  4335. this.x = c.r;
  4336. this.y = c.g;
  4337. this.z = c.b;
  4338. return this;
  4339. }
  4340. /**
  4341. * Returns `true` if this vector is equal with the given one.
  4342. *
  4343. * @param {Vector3} v - The vector to test for equality.
  4344. * @return {boolean} Whether this vector is equal with the given one.
  4345. */
  4346. equals( v ) {
  4347. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) );
  4348. }
  4349. /**
  4350. * Sets this vector's x value to be `array[ offset ]`, y value to be `array[ offset + 1 ]`
  4351. * and z value to be `array[ offset + 2 ]`.
  4352. *
  4353. * @param {Array<number>} array - An array holding the vector component values.
  4354. * @param {number} [offset=0] - The offset into the array.
  4355. * @return {Vector3} A reference to this vector.
  4356. */
  4357. fromArray( array, offset = 0 ) {
  4358. this.x = array[ offset ];
  4359. this.y = array[ offset + 1 ];
  4360. this.z = array[ offset + 2 ];
  4361. return this;
  4362. }
  4363. /**
  4364. * Writes the components of this vector to the given array. If no array is provided,
  4365. * the method returns a new instance.
  4366. *
  4367. * @param {Array<number>} [array=[]] - The target array holding the vector components.
  4368. * @param {number} [offset=0] - Index of the first element in the array.
  4369. * @return {Array<number>} The vector components.
  4370. */
  4371. toArray( array = [], offset = 0 ) {
  4372. array[ offset ] = this.x;
  4373. array[ offset + 1 ] = this.y;
  4374. array[ offset + 2 ] = this.z;
  4375. return array;
  4376. }
  4377. /**
  4378. * Sets the components of this vector from the given buffer attribute.
  4379. *
  4380. * @param {BufferAttribute} attribute - The buffer attribute holding vector data.
  4381. * @param {number} index - The index into the attribute.
  4382. * @return {Vector3} A reference to this vector.
  4383. */
  4384. fromBufferAttribute( attribute, index ) {
  4385. this.x = attribute.getX( index );
  4386. this.y = attribute.getY( index );
  4387. this.z = attribute.getZ( index );
  4388. return this;
  4389. }
  4390. /**
  4391. * Sets each component of this vector to a pseudo-random value between `0` and
  4392. * `1`, excluding `1`.
  4393. *
  4394. * @return {Vector3} A reference to this vector.
  4395. */
  4396. random() {
  4397. this.x = Math.random();
  4398. this.y = Math.random();
  4399. this.z = Math.random();
  4400. return this;
  4401. }
  4402. /**
  4403. * Sets this vector to a uniformly random point on a unit sphere.
  4404. *
  4405. * @return {Vector3} A reference to this vector.
  4406. */
  4407. randomDirection() {
  4408. // https://mathworld.wolfram.com/SpherePointPicking.html
  4409. const theta = Math.random() * Math.PI * 2;
  4410. const u = Math.random() * 2 - 1;
  4411. const c = Math.sqrt( 1 - u * u );
  4412. this.x = c * Math.cos( theta );
  4413. this.y = u;
  4414. this.z = c * Math.sin( theta );
  4415. return this;
  4416. }
  4417. *[ Symbol.iterator ]() {
  4418. yield this.x;
  4419. yield this.y;
  4420. yield this.z;
  4421. }
  4422. }
  4423. const _vector$c = /*@__PURE__*/ new Vector3();
  4424. const _quaternion$4 = /*@__PURE__*/ new Quaternion();
  4425. /**
  4426. * Represents a 3x3 matrix.
  4427. *
  4428. * A Note on Row-Major and Column-Major Ordering:
  4429. *
  4430. * The constructor and {@link Matrix3#set} method take arguments in
  4431. * [row-major]{@link https://en.wikipedia.org/wiki/Row-_and_column-major_order#Column-major_order}
  4432. * order, while internally they are stored in the {@link Matrix3#elements} array in column-major order.
  4433. * This means that calling:
  4434. * ```js
  4435. * const m = new THREE.Matrix();
  4436. * m.set( 11, 12, 13,
  4437. * 21, 22, 23,
  4438. * 31, 32, 33 );
  4439. * ```
  4440. * will result in the elements array containing:
  4441. * ```js
  4442. * m.elements = [ 11, 21, 31,
  4443. * 12, 22, 32,
  4444. * 13, 23, 33 ];
  4445. * ```
  4446. * and internally all calculations are performed using column-major ordering.
  4447. * However, as the actual ordering makes no difference mathematically and
  4448. * most people are used to thinking about matrices in row-major order, the
  4449. * three.js documentation shows matrices in row-major order. Just bear in
  4450. * mind that if you are reading the source code, you'll have to take the
  4451. * transpose of any matrices outlined here to make sense of the calculations.
  4452. */
  4453. class Matrix3 {
  4454. /**
  4455. * Constructs a new 3x3 matrix. The arguments are supposed to be
  4456. * in row-major order. If no arguments are provided, the constructor
  4457. * initializes the matrix as an identity matrix.
  4458. *
  4459. * @param {number} [n11] - 1-1 matrix element.
  4460. * @param {number} [n12] - 1-2 matrix element.
  4461. * @param {number} [n13] - 1-3 matrix element.
  4462. * @param {number} [n21] - 2-1 matrix element.
  4463. * @param {number} [n22] - 2-2 matrix element.
  4464. * @param {number} [n23] - 2-3 matrix element.
  4465. * @param {number} [n31] - 3-1 matrix element.
  4466. * @param {number} [n32] - 3-2 matrix element.
  4467. * @param {number} [n33] - 3-3 matrix element.
  4468. */
  4469. constructor( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) {
  4470. /**
  4471. * This flag can be used for type testing.
  4472. *
  4473. * @type {boolean}
  4474. * @readonly
  4475. * @default true
  4476. */
  4477. Matrix3.prototype.isMatrix3 = true;
  4478. /**
  4479. * A column-major list of matrix values.
  4480. *
  4481. * @type {Array<number>}
  4482. */
  4483. this.elements = [
  4484. 1, 0, 0,
  4485. 0, 1, 0,
  4486. 0, 0, 1
  4487. ];
  4488. if ( n11 !== undefined ) {
  4489. this.set( n11, n12, n13, n21, n22, n23, n31, n32, n33 );
  4490. }
  4491. }
  4492. /**
  4493. * Sets the elements of the matrix.The arguments are supposed to be
  4494. * in row-major order.
  4495. *
  4496. * @param {number} [n11] - 1-1 matrix element.
  4497. * @param {number} [n12] - 1-2 matrix element.
  4498. * @param {number} [n13] - 1-3 matrix element.
  4499. * @param {number} [n21] - 2-1 matrix element.
  4500. * @param {number} [n22] - 2-2 matrix element.
  4501. * @param {number} [n23] - 2-3 matrix element.
  4502. * @param {number} [n31] - 3-1 matrix element.
  4503. * @param {number} [n32] - 3-2 matrix element.
  4504. * @param {number} [n33] - 3-3 matrix element.
  4505. * @return {Matrix3} A reference to this matrix.
  4506. */
  4507. set( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) {
  4508. const te = this.elements;
  4509. te[ 0 ] = n11; te[ 1 ] = n21; te[ 2 ] = n31;
  4510. te[ 3 ] = n12; te[ 4 ] = n22; te[ 5 ] = n32;
  4511. te[ 6 ] = n13; te[ 7 ] = n23; te[ 8 ] = n33;
  4512. return this;
  4513. }
  4514. /**
  4515. * Sets this matrix to the 3x3 identity matrix.
  4516. *
  4517. * @return {Matrix3} A reference to this matrix.
  4518. */
  4519. identity() {
  4520. this.set(
  4521. 1, 0, 0,
  4522. 0, 1, 0,
  4523. 0, 0, 1
  4524. );
  4525. return this;
  4526. }
  4527. /**
  4528. * Copies the values of the given matrix to this instance.
  4529. *
  4530. * @param {Matrix3} m - The matrix to copy.
  4531. * @return {Matrix3} A reference to this matrix.
  4532. */
  4533. copy( m ) {
  4534. const te = this.elements;
  4535. const me = m.elements;
  4536. te[ 0 ] = me[ 0 ]; te[ 1 ] = me[ 1 ]; te[ 2 ] = me[ 2 ];
  4537. te[ 3 ] = me[ 3 ]; te[ 4 ] = me[ 4 ]; te[ 5 ] = me[ 5 ];
  4538. te[ 6 ] = me[ 6 ]; te[ 7 ] = me[ 7 ]; te[ 8 ] = me[ 8 ];
  4539. return this;
  4540. }
  4541. /**
  4542. * Extracts the basis of this matrix into the three axis vectors provided.
  4543. *
  4544. * @param {Vector3} xAxis - The basis's x axis.
  4545. * @param {Vector3} yAxis - The basis's y axis.
  4546. * @param {Vector3} zAxis - The basis's z axis.
  4547. * @return {Matrix3} A reference to this matrix.
  4548. */
  4549. extractBasis( xAxis, yAxis, zAxis ) {
  4550. xAxis.setFromMatrix3Column( this, 0 );
  4551. yAxis.setFromMatrix3Column( this, 1 );
  4552. zAxis.setFromMatrix3Column( this, 2 );
  4553. return this;
  4554. }
  4555. /**
  4556. * Set this matrix to the upper 3x3 matrix of the given 4x4 matrix.
  4557. *
  4558. * @param {Matrix4} m - The 4x4 matrix.
  4559. * @return {Matrix3} A reference to this matrix.
  4560. */
  4561. setFromMatrix4( m ) {
  4562. const me = m.elements;
  4563. this.set(
  4564. me[ 0 ], me[ 4 ], me[ 8 ],
  4565. me[ 1 ], me[ 5 ], me[ 9 ],
  4566. me[ 2 ], me[ 6 ], me[ 10 ]
  4567. );
  4568. return this;
  4569. }
  4570. /**
  4571. * Post-multiplies this matrix by the given 3x3 matrix.
  4572. *
  4573. * @param {Matrix3} m - The matrix to multiply with.
  4574. * @return {Matrix3} A reference to this matrix.
  4575. */
  4576. multiply( m ) {
  4577. return this.multiplyMatrices( this, m );
  4578. }
  4579. /**
  4580. * Pre-multiplies this matrix by the given 3x3 matrix.
  4581. *
  4582. * @param {Matrix3} m - The matrix to multiply with.
  4583. * @return {Matrix3} A reference to this matrix.
  4584. */
  4585. premultiply( m ) {
  4586. return this.multiplyMatrices( m, this );
  4587. }
  4588. /**
  4589. * Multiples the given 3x3 matrices and stores the result
  4590. * in this matrix.
  4591. *
  4592. * @param {Matrix3} a - The first matrix.
  4593. * @param {Matrix3} b - The second matrix.
  4594. * @return {Matrix3} A reference to this matrix.
  4595. */
  4596. multiplyMatrices( a, b ) {
  4597. const ae = a.elements;
  4598. const be = b.elements;
  4599. const te = this.elements;
  4600. const a11 = ae[ 0 ], a12 = ae[ 3 ], a13 = ae[ 6 ];
  4601. const a21 = ae[ 1 ], a22 = ae[ 4 ], a23 = ae[ 7 ];
  4602. const a31 = ae[ 2 ], a32 = ae[ 5 ], a33 = ae[ 8 ];
  4603. const b11 = be[ 0 ], b12 = be[ 3 ], b13 = be[ 6 ];
  4604. const b21 = be[ 1 ], b22 = be[ 4 ], b23 = be[ 7 ];
  4605. const b31 = be[ 2 ], b32 = be[ 5 ], b33 = be[ 8 ];
  4606. te[ 0 ] = a11 * b11 + a12 * b21 + a13 * b31;
  4607. te[ 3 ] = a11 * b12 + a12 * b22 + a13 * b32;
  4608. te[ 6 ] = a11 * b13 + a12 * b23 + a13 * b33;
  4609. te[ 1 ] = a21 * b11 + a22 * b21 + a23 * b31;
  4610. te[ 4 ] = a21 * b12 + a22 * b22 + a23 * b32;
  4611. te[ 7 ] = a21 * b13 + a22 * b23 + a23 * b33;
  4612. te[ 2 ] = a31 * b11 + a32 * b21 + a33 * b31;
  4613. te[ 5 ] = a31 * b12 + a32 * b22 + a33 * b32;
  4614. te[ 8 ] = a31 * b13 + a32 * b23 + a33 * b33;
  4615. return this;
  4616. }
  4617. /**
  4618. * Multiplies every component of the matrix by the given scalar.
  4619. *
  4620. * @param {number} s - The scalar.
  4621. * @return {Matrix3} A reference to this matrix.
  4622. */
  4623. multiplyScalar( s ) {
  4624. const te = this.elements;
  4625. te[ 0 ] *= s; te[ 3 ] *= s; te[ 6 ] *= s;
  4626. te[ 1 ] *= s; te[ 4 ] *= s; te[ 7 ] *= s;
  4627. te[ 2 ] *= s; te[ 5 ] *= s; te[ 8 ] *= s;
  4628. return this;
  4629. }
  4630. /**
  4631. * Computes and returns the determinant of this matrix.
  4632. *
  4633. * @return {number} The determinant.
  4634. */
  4635. determinant() {
  4636. const te = this.elements;
  4637. const a = te[ 0 ], b = te[ 1 ], c = te[ 2 ],
  4638. d = te[ 3 ], e = te[ 4 ], f = te[ 5 ],
  4639. g = te[ 6 ], h = te[ 7 ], i = te[ 8 ];
  4640. return a * e * i - a * f * h - b * d * i + b * f * g + c * d * h - c * e * g;
  4641. }
  4642. /**
  4643. * Inverts this matrix, using the [analytic method]{@link https://en.wikipedia.org/wiki/Invertible_matrix#Analytic_solution}.
  4644. * You can not invert with a determinant of zero. If you attempt this, the method produces
  4645. * a zero matrix instead.
  4646. *
  4647. * @return {Matrix3} A reference to this matrix.
  4648. */
  4649. invert() {
  4650. const te = this.elements,
  4651. n11 = te[ 0 ], n21 = te[ 1 ], n31 = te[ 2 ],
  4652. n12 = te[ 3 ], n22 = te[ 4 ], n32 = te[ 5 ],
  4653. n13 = te[ 6 ], n23 = te[ 7 ], n33 = te[ 8 ],
  4654. t11 = n33 * n22 - n32 * n23,
  4655. t12 = n32 * n13 - n33 * n12,
  4656. t13 = n23 * n12 - n22 * n13,
  4657. det = n11 * t11 + n21 * t12 + n31 * t13;
  4658. if ( det === 0 ) return this.set( 0, 0, 0, 0, 0, 0, 0, 0, 0 );
  4659. const detInv = 1 / det;
  4660. te[ 0 ] = t11 * detInv;
  4661. te[ 1 ] = ( n31 * n23 - n33 * n21 ) * detInv;
  4662. te[ 2 ] = ( n32 * n21 - n31 * n22 ) * detInv;
  4663. te[ 3 ] = t12 * detInv;
  4664. te[ 4 ] = ( n33 * n11 - n31 * n13 ) * detInv;
  4665. te[ 5 ] = ( n31 * n12 - n32 * n11 ) * detInv;
  4666. te[ 6 ] = t13 * detInv;
  4667. te[ 7 ] = ( n21 * n13 - n23 * n11 ) * detInv;
  4668. te[ 8 ] = ( n22 * n11 - n21 * n12 ) * detInv;
  4669. return this;
  4670. }
  4671. /**
  4672. * Transposes this matrix in place.
  4673. *
  4674. * @return {Matrix3} A reference to this matrix.
  4675. */
  4676. transpose() {
  4677. let tmp;
  4678. const m = this.elements;
  4679. tmp = m[ 1 ]; m[ 1 ] = m[ 3 ]; m[ 3 ] = tmp;
  4680. tmp = m[ 2 ]; m[ 2 ] = m[ 6 ]; m[ 6 ] = tmp;
  4681. tmp = m[ 5 ]; m[ 5 ] = m[ 7 ]; m[ 7 ] = tmp;
  4682. return this;
  4683. }
  4684. /**
  4685. * Computes the normal matrix which is the inverse transpose of the upper
  4686. * left 3x3 portion of the given 4x4 matrix.
  4687. *
  4688. * @param {Matrix4} matrix4 - The 4x4 matrix.
  4689. * @return {Matrix3} A reference to this matrix.
  4690. */
  4691. getNormalMatrix( matrix4 ) {
  4692. return this.setFromMatrix4( matrix4 ).invert().transpose();
  4693. }
  4694. /**
  4695. * Transposes this matrix into the supplied array, and returns itself unchanged.
  4696. *
  4697. * @param {Array<number>} r - An array to store the transposed matrix elements.
  4698. * @return {Matrix3} A reference to this matrix.
  4699. */
  4700. transposeIntoArray( r ) {
  4701. const m = this.elements;
  4702. r[ 0 ] = m[ 0 ];
  4703. r[ 1 ] = m[ 3 ];
  4704. r[ 2 ] = m[ 6 ];
  4705. r[ 3 ] = m[ 1 ];
  4706. r[ 4 ] = m[ 4 ];
  4707. r[ 5 ] = m[ 7 ];
  4708. r[ 6 ] = m[ 2 ];
  4709. r[ 7 ] = m[ 5 ];
  4710. r[ 8 ] = m[ 8 ];
  4711. return this;
  4712. }
  4713. /**
  4714. * Sets the UV transform matrix from offset, repeat, rotation, and center.
  4715. *
  4716. * @param {number} tx - Offset x.
  4717. * @param {number} ty - Offset y.
  4718. * @param {number} sx - Repeat x.
  4719. * @param {number} sy - Repeat y.
  4720. * @param {number} rotation - Rotation, in radians. Positive values rotate counterclockwise.
  4721. * @param {number} cx - Center x of rotation.
  4722. * @param {number} cy - Center y of rotation
  4723. * @return {Matrix3} A reference to this matrix.
  4724. */
  4725. setUvTransform( tx, ty, sx, sy, rotation, cx, cy ) {
  4726. const c = Math.cos( rotation );
  4727. const s = Math.sin( rotation );
  4728. this.set(
  4729. sx * c, sx * s, - sx * ( c * cx + s * cy ) + cx + tx,
  4730. - sy * s, sy * c, - sy * ( - s * cx + c * cy ) + cy + ty,
  4731. 0, 0, 1
  4732. );
  4733. return this;
  4734. }
  4735. /**
  4736. * Scales this matrix with the given scalar values.
  4737. *
  4738. * @param {number} sx - The amount to scale in the X axis.
  4739. * @param {number} sy - The amount to scale in the Y axis.
  4740. * @return {Matrix3} A reference to this matrix.
  4741. */
  4742. scale( sx, sy ) {
  4743. this.premultiply( _m3.makeScale( sx, sy ) );
  4744. return this;
  4745. }
  4746. /**
  4747. * Rotates this matrix by the given angle.
  4748. *
  4749. * @param {number} theta - The rotation in radians.
  4750. * @return {Matrix3} A reference to this matrix.
  4751. */
  4752. rotate( theta ) {
  4753. this.premultiply( _m3.makeRotation( - theta ) );
  4754. return this;
  4755. }
  4756. /**
  4757. * Translates this matrix by the given scalar values.
  4758. *
  4759. * @param {number} tx - The amount to translate in the X axis.
  4760. * @param {number} ty - The amount to translate in the Y axis.
  4761. * @return {Matrix3} A reference to this matrix.
  4762. */
  4763. translate( tx, ty ) {
  4764. this.premultiply( _m3.makeTranslation( tx, ty ) );
  4765. return this;
  4766. }
  4767. // for 2D Transforms
  4768. /**
  4769. * Sets this matrix as a 2D translation transform.
  4770. *
  4771. * @param {number|Vector2} x - The amount to translate in the X axis or alternatively a translation vector.
  4772. * @param {number} y - The amount to translate in the Y axis.
  4773. * @return {Matrix3} A reference to this matrix.
  4774. */
  4775. makeTranslation( x, y ) {
  4776. if ( x.isVector2 ) {
  4777. this.set(
  4778. 1, 0, x.x,
  4779. 0, 1, x.y,
  4780. 0, 0, 1
  4781. );
  4782. } else {
  4783. this.set(
  4784. 1, 0, x,
  4785. 0, 1, y,
  4786. 0, 0, 1
  4787. );
  4788. }
  4789. return this;
  4790. }
  4791. /**
  4792. * Sets this matrix as a 2D rotational transformation.
  4793. *
  4794. * @param {number} theta - The rotation in radians.
  4795. * @return {Matrix3} A reference to this matrix.
  4796. */
  4797. makeRotation( theta ) {
  4798. // counterclockwise
  4799. const c = Math.cos( theta );
  4800. const s = Math.sin( theta );
  4801. this.set(
  4802. c, - s, 0,
  4803. s, c, 0,
  4804. 0, 0, 1
  4805. );
  4806. return this;
  4807. }
  4808. /**
  4809. * Sets this matrix as a 2D scale transform.
  4810. *
  4811. * @param {number} x - The amount to scale in the X axis.
  4812. * @param {number} y - The amount to scale in the Y axis.
  4813. * @return {Matrix3} A reference to this matrix.
  4814. */
  4815. makeScale( x, y ) {
  4816. this.set(
  4817. x, 0, 0,
  4818. 0, y, 0,
  4819. 0, 0, 1
  4820. );
  4821. return this;
  4822. }
  4823. /**
  4824. * Returns `true` if this matrix is equal with the given one.
  4825. *
  4826. * @param {Matrix3} matrix - The matrix to test for equality.
  4827. * @return {boolean} Whether this matrix is equal with the given one.
  4828. */
  4829. equals( matrix ) {
  4830. const te = this.elements;
  4831. const me = matrix.elements;
  4832. for ( let i = 0; i < 9; i ++ ) {
  4833. if ( te[ i ] !== me[ i ] ) return false;
  4834. }
  4835. return true;
  4836. }
  4837. /**
  4838. * Sets the elements of the matrix from the given array.
  4839. *
  4840. * @param {Array<number>} array - The matrix elements in column-major order.
  4841. * @param {number} [offset=0] - Index of the first element in the array.
  4842. * @return {Matrix3} A reference to this matrix.
  4843. */
  4844. fromArray( array, offset = 0 ) {
  4845. for ( let i = 0; i < 9; i ++ ) {
  4846. this.elements[ i ] = array[ i + offset ];
  4847. }
  4848. return this;
  4849. }
  4850. /**
  4851. * Writes the elements of this matrix to the given array. If no array is provided,
  4852. * the method returns a new instance.
  4853. *
  4854. * @param {Array<number>} [array=[]] - The target array holding the matrix elements in column-major order.
  4855. * @param {number} [offset=0] - Index of the first element in the array.
  4856. * @return {Array<number>} The matrix elements in column-major order.
  4857. */
  4858. toArray( array = [], offset = 0 ) {
  4859. const te = this.elements;
  4860. array[ offset ] = te[ 0 ];
  4861. array[ offset + 1 ] = te[ 1 ];
  4862. array[ offset + 2 ] = te[ 2 ];
  4863. array[ offset + 3 ] = te[ 3 ];
  4864. array[ offset + 4 ] = te[ 4 ];
  4865. array[ offset + 5 ] = te[ 5 ];
  4866. array[ offset + 6 ] = te[ 6 ];
  4867. array[ offset + 7 ] = te[ 7 ];
  4868. array[ offset + 8 ] = te[ 8 ];
  4869. return array;
  4870. }
  4871. /**
  4872. * Returns a matrix with copied values from this instance.
  4873. *
  4874. * @return {Matrix3} A clone of this instance.
  4875. */
  4876. clone() {
  4877. return new this.constructor().fromArray( this.elements );
  4878. }
  4879. }
  4880. const _m3 = /*@__PURE__*/ new Matrix3();
  4881. function arrayNeedsUint32( array ) {
  4882. // assumes larger values usually on last
  4883. for ( let i = array.length - 1; i >= 0; -- i ) {
  4884. if ( array[ i ] >= 65535 ) return true; // account for PRIMITIVE_RESTART_FIXED_INDEX, #24565
  4885. }
  4886. return false;
  4887. }
  4888. const TYPED_ARRAYS = {
  4889. Int8Array: Int8Array,
  4890. Uint8Array: Uint8Array,
  4891. Uint8ClampedArray: Uint8ClampedArray,
  4892. Int16Array: Int16Array,
  4893. Uint16Array: Uint16Array,
  4894. Int32Array: Int32Array,
  4895. Uint32Array: Uint32Array,
  4896. Float32Array: Float32Array,
  4897. Float64Array: Float64Array
  4898. };
  4899. function getTypedArray( type, buffer ) {
  4900. return new TYPED_ARRAYS[ type ]( buffer );
  4901. }
  4902. function createElementNS( name ) {
  4903. return document.createElementNS( 'http://www.w3.org/1999/xhtml', name );
  4904. }
  4905. function createCanvasElement() {
  4906. const canvas = createElementNS( 'canvas' );
  4907. canvas.style.display = 'block';
  4908. return canvas;
  4909. }
  4910. const _cache = {};
  4911. function warnOnce( message ) {
  4912. if ( message in _cache ) return;
  4913. _cache[ message ] = true;
  4914. console.warn( message );
  4915. }
  4916. function probeAsync( gl, sync, interval ) {
  4917. return new Promise( function ( resolve, reject ) {
  4918. function probe() {
  4919. switch ( gl.clientWaitSync( sync, gl.SYNC_FLUSH_COMMANDS_BIT, 0 ) ) {
  4920. case gl.WAIT_FAILED:
  4921. reject();
  4922. break;
  4923. case gl.TIMEOUT_EXPIRED:
  4924. setTimeout( probe, interval );
  4925. break;
  4926. default:
  4927. resolve();
  4928. }
  4929. }
  4930. setTimeout( probe, interval );
  4931. } );
  4932. }
  4933. function toNormalizedProjectionMatrix( projectionMatrix ) {
  4934. const m = projectionMatrix.elements;
  4935. // Convert [-1, 1] to [0, 1] projection matrix
  4936. m[ 2 ] = 0.5 * m[ 2 ] + 0.5 * m[ 3 ];
  4937. m[ 6 ] = 0.5 * m[ 6 ] + 0.5 * m[ 7 ];
  4938. m[ 10 ] = 0.5 * m[ 10 ] + 0.5 * m[ 11 ];
  4939. m[ 14 ] = 0.5 * m[ 14 ] + 0.5 * m[ 15 ];
  4940. }
  4941. function toReversedProjectionMatrix( projectionMatrix ) {
  4942. const m = projectionMatrix.elements;
  4943. const isPerspectiveMatrix = m[ 11 ] === -1;
  4944. // Reverse [0, 1] projection matrix
  4945. if ( isPerspectiveMatrix ) {
  4946. m[ 10 ] = - m[ 10 ] - 1;
  4947. m[ 14 ] = - m[ 14 ];
  4948. } else {
  4949. m[ 10 ] = - m[ 10 ];
  4950. m[ 14 ] = - m[ 14 ] + 1;
  4951. }
  4952. }
  4953. const LINEAR_REC709_TO_XYZ = /*@__PURE__*/ new Matrix3().set(
  4954. 0.4123908, 0.3575843, 0.1804808,
  4955. 0.2126390, 0.7151687, 0.0721923,
  4956. 0.0193308, 0.1191948, 0.9505322
  4957. );
  4958. const XYZ_TO_LINEAR_REC709 = /*@__PURE__*/ new Matrix3().set(
  4959. 3.2409699, -1.5373832, -0.4986108,
  4960. -0.9692436, 1.8759675, 0.0415551,
  4961. 0.0556301, -0.203977, 1.0569715
  4962. );
  4963. function createColorManagement() {
  4964. const ColorManagement = {
  4965. enabled: true,
  4966. workingColorSpace: LinearSRGBColorSpace,
  4967. /**
  4968. * Implementations of supported color spaces.
  4969. *
  4970. * Required:
  4971. * - primaries: chromaticity coordinates [ rx ry gx gy bx by ]
  4972. * - whitePoint: reference white [ x y ]
  4973. * - transfer: transfer function (pre-defined)
  4974. * - toXYZ: Matrix3 RGB to XYZ transform
  4975. * - fromXYZ: Matrix3 XYZ to RGB transform
  4976. * - luminanceCoefficients: RGB luminance coefficients
  4977. *
  4978. * Optional:
  4979. * - outputColorSpaceConfig: { drawingBufferColorSpace: ColorSpace }
  4980. * - workingColorSpaceConfig: { unpackColorSpace: ColorSpace }
  4981. *
  4982. * Reference:
  4983. * - https://www.russellcottrell.com/photo/matrixCalculator.htm
  4984. */
  4985. spaces: {},
  4986. convert: function ( color, sourceColorSpace, targetColorSpace ) {
  4987. if ( this.enabled === false || sourceColorSpace === targetColorSpace || ! sourceColorSpace || ! targetColorSpace ) {
  4988. return color;
  4989. }
  4990. if ( this.spaces[ sourceColorSpace ].transfer === SRGBTransfer ) {
  4991. color.r = SRGBToLinear( color.r );
  4992. color.g = SRGBToLinear( color.g );
  4993. color.b = SRGBToLinear( color.b );
  4994. }
  4995. if ( this.spaces[ sourceColorSpace ].primaries !== this.spaces[ targetColorSpace ].primaries ) {
  4996. color.applyMatrix3( this.spaces[ sourceColorSpace ].toXYZ );
  4997. color.applyMatrix3( this.spaces[ targetColorSpace ].fromXYZ );
  4998. }
  4999. if ( this.spaces[ targetColorSpace ].transfer === SRGBTransfer ) {
  5000. color.r = LinearToSRGB( color.r );
  5001. color.g = LinearToSRGB( color.g );
  5002. color.b = LinearToSRGB( color.b );
  5003. }
  5004. return color;
  5005. },
  5006. fromWorkingColorSpace: function ( color, targetColorSpace ) {
  5007. return this.convert( color, this.workingColorSpace, targetColorSpace );
  5008. },
  5009. toWorkingColorSpace: function ( color, sourceColorSpace ) {
  5010. return this.convert( color, sourceColorSpace, this.workingColorSpace );
  5011. },
  5012. getPrimaries: function ( colorSpace ) {
  5013. return this.spaces[ colorSpace ].primaries;
  5014. },
  5015. getTransfer: function ( colorSpace ) {
  5016. if ( colorSpace === NoColorSpace ) return LinearTransfer;
  5017. return this.spaces[ colorSpace ].transfer;
  5018. },
  5019. getLuminanceCoefficients: function ( target, colorSpace = this.workingColorSpace ) {
  5020. return target.fromArray( this.spaces[ colorSpace ].luminanceCoefficients );
  5021. },
  5022. define: function ( colorSpaces ) {
  5023. Object.assign( this.spaces, colorSpaces );
  5024. },
  5025. // Internal APIs
  5026. _getMatrix: function ( targetMatrix, sourceColorSpace, targetColorSpace ) {
  5027. return targetMatrix
  5028. .copy( this.spaces[ sourceColorSpace ].toXYZ )
  5029. .multiply( this.spaces[ targetColorSpace ].fromXYZ );
  5030. },
  5031. _getDrawingBufferColorSpace: function ( colorSpace ) {
  5032. return this.spaces[ colorSpace ].outputColorSpaceConfig.drawingBufferColorSpace;
  5033. },
  5034. _getUnpackColorSpace: function ( colorSpace = this.workingColorSpace ) {
  5035. return this.spaces[ colorSpace ].workingColorSpaceConfig.unpackColorSpace;
  5036. }
  5037. };
  5038. /******************************************************************************
  5039. * sRGB definitions
  5040. */
  5041. const REC709_PRIMARIES = [ 0.640, 0.330, 0.300, 0.600, 0.150, 0.060 ];
  5042. const REC709_LUMINANCE_COEFFICIENTS = [ 0.2126, 0.7152, 0.0722 ];
  5043. const D65 = [ 0.3127, 0.3290 ];
  5044. ColorManagement.define( {
  5045. [ LinearSRGBColorSpace ]: {
  5046. primaries: REC709_PRIMARIES,
  5047. whitePoint: D65,
  5048. transfer: LinearTransfer,
  5049. toXYZ: LINEAR_REC709_TO_XYZ,
  5050. fromXYZ: XYZ_TO_LINEAR_REC709,
  5051. luminanceCoefficients: REC709_LUMINANCE_COEFFICIENTS,
  5052. workingColorSpaceConfig: { unpackColorSpace: SRGBColorSpace },
  5053. outputColorSpaceConfig: { drawingBufferColorSpace: SRGBColorSpace }
  5054. },
  5055. [ SRGBColorSpace ]: {
  5056. primaries: REC709_PRIMARIES,
  5057. whitePoint: D65,
  5058. transfer: SRGBTransfer,
  5059. toXYZ: LINEAR_REC709_TO_XYZ,
  5060. fromXYZ: XYZ_TO_LINEAR_REC709,
  5061. luminanceCoefficients: REC709_LUMINANCE_COEFFICIENTS,
  5062. outputColorSpaceConfig: { drawingBufferColorSpace: SRGBColorSpace }
  5063. },
  5064. } );
  5065. return ColorManagement;
  5066. }
  5067. const ColorManagement = /*@__PURE__*/ createColorManagement();
  5068. function SRGBToLinear( c ) {
  5069. return ( c < 0.04045 ) ? c * 0.0773993808 : Math.pow( c * 0.9478672986 + 0.0521327014, 2.4 );
  5070. }
  5071. function LinearToSRGB( c ) {
  5072. return ( c < 0.0031308 ) ? c * 12.92 : 1.055 * ( Math.pow( c, 0.41666 ) ) - 0.055;
  5073. }
  5074. let _canvas;
  5075. /**
  5076. * A class containing utility functions for images.
  5077. *
  5078. * @hideconstructor
  5079. */
  5080. class ImageUtils {
  5081. /**
  5082. * Returns a data URI containing a representation of the given image.
  5083. *
  5084. * @param {(HTMLImageElement|HTMLCanvasElement)} image - The image object.
  5085. * @param {string} [type='image/png'] - Indicates the image format.
  5086. * @return {string} The data URI.
  5087. */
  5088. static getDataURL( image, type = 'image/png' ) {
  5089. if ( /^data:/i.test( image.src ) ) {
  5090. return image.src;
  5091. }
  5092. if ( typeof HTMLCanvasElement === 'undefined' ) {
  5093. return image.src;
  5094. }
  5095. let canvas;
  5096. if ( image instanceof HTMLCanvasElement ) {
  5097. canvas = image;
  5098. } else {
  5099. if ( _canvas === undefined ) _canvas = createElementNS( 'canvas' );
  5100. _canvas.width = image.width;
  5101. _canvas.height = image.height;
  5102. const context = _canvas.getContext( '2d' );
  5103. if ( image instanceof ImageData ) {
  5104. context.putImageData( image, 0, 0 );
  5105. } else {
  5106. context.drawImage( image, 0, 0, image.width, image.height );
  5107. }
  5108. canvas = _canvas;
  5109. }
  5110. return canvas.toDataURL( type );
  5111. }
  5112. /**
  5113. * Converts the given sRGB image data to linear color space.
  5114. *
  5115. * @param {(HTMLImageElement|HTMLCanvasElement|ImageBitmap|Object)} image - The image object.
  5116. * @return {HTMLCanvasElement|Object} The converted image.
  5117. */
  5118. static sRGBToLinear( image ) {
  5119. if ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) ||
  5120. ( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) ||
  5121. ( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) ) {
  5122. const canvas = createElementNS( 'canvas' );
  5123. canvas.width = image.width;
  5124. canvas.height = image.height;
  5125. const context = canvas.getContext( '2d' );
  5126. context.drawImage( image, 0, 0, image.width, image.height );
  5127. const imageData = context.getImageData( 0, 0, image.width, image.height );
  5128. const data = imageData.data;
  5129. for ( let i = 0; i < data.length; i ++ ) {
  5130. data[ i ] = SRGBToLinear( data[ i ] / 255 ) * 255;
  5131. }
  5132. context.putImageData( imageData, 0, 0 );
  5133. return canvas;
  5134. } else if ( image.data ) {
  5135. const data = image.data.slice( 0 );
  5136. for ( let i = 0; i < data.length; i ++ ) {
  5137. if ( data instanceof Uint8Array || data instanceof Uint8ClampedArray ) {
  5138. data[ i ] = Math.floor( SRGBToLinear( data[ i ] / 255 ) * 255 );
  5139. } else {
  5140. // assuming float
  5141. data[ i ] = SRGBToLinear( data[ i ] );
  5142. }
  5143. }
  5144. return {
  5145. data: data,
  5146. width: image.width,
  5147. height: image.height
  5148. };
  5149. } else {
  5150. console.warn( 'THREE.ImageUtils.sRGBToLinear(): Unsupported image type. No color space conversion applied.' );
  5151. return image;
  5152. }
  5153. }
  5154. }
  5155. let _sourceId = 0;
  5156. /**
  5157. * Represents the data source of a texture.
  5158. *
  5159. * The main purpose of this class is to decouple the data definition from the texture
  5160. * definition so the same data can be used with multiple texture instances.
  5161. */
  5162. class Source {
  5163. /**
  5164. * Constructs a new video texture.
  5165. *
  5166. * @param {any} [data=null] - The data definition of a texture.
  5167. */
  5168. constructor( data = null ) {
  5169. /**
  5170. * This flag can be used for type testing.
  5171. *
  5172. * @type {boolean}
  5173. * @readonly
  5174. * @default true
  5175. */
  5176. this.isSource = true;
  5177. /**
  5178. * The ID of the source.
  5179. *
  5180. * @name Source#id
  5181. * @type {number}
  5182. * @readonly
  5183. */
  5184. Object.defineProperty( this, 'id', { value: _sourceId ++ } );
  5185. /**
  5186. * The UUID of the source.
  5187. *
  5188. * @type {string}
  5189. * @readonly
  5190. */
  5191. this.uuid = generateUUID();
  5192. /**
  5193. * The data definition of a texture.
  5194. *
  5195. * @type {any}
  5196. */
  5197. this.data = data;
  5198. /**
  5199. * This property is only relevant when {@link Source#needsUpdate} is set to `true` and
  5200. * provides more control on how texture data should be processed. When `dataReady` is set
  5201. * to `false`, the engine performs the memory allocation (if necessary) but does not transfer
  5202. * the data into the GPU memory.
  5203. *
  5204. * @type {boolean}
  5205. * @default true
  5206. */
  5207. this.dataReady = true;
  5208. /**
  5209. * This starts at `0` and counts how many times {@link Source#needsUpdate} is set to `true`.
  5210. *
  5211. * @type {number}
  5212. * @readonly
  5213. * @default 0
  5214. */
  5215. this.version = 0;
  5216. }
  5217. getSize( target ) {
  5218. const data = this.data;
  5219. if ( data instanceof HTMLVideoElement ) {
  5220. target.set( data.videoWidth, data.videoHeight );
  5221. } else if ( data !== null ) {
  5222. target.set( data.width, data.height, data.depth || 0 );
  5223. } else {
  5224. target.set( 0, 0, 0 );
  5225. }
  5226. return target;
  5227. }
  5228. /**
  5229. * When the property is set to `true`, the engine allocates the memory
  5230. * for the texture (if necessary) and triggers the actual texture upload
  5231. * to the GPU next time the source is used.
  5232. *
  5233. * @type {boolean}
  5234. * @default false
  5235. * @param {boolean} value
  5236. */
  5237. set needsUpdate( value ) {
  5238. if ( value === true ) this.version ++;
  5239. }
  5240. /**
  5241. * Serializes the source into JSON.
  5242. *
  5243. * @param {?(Object|string)} meta - An optional value holding meta information about the serialization.
  5244. * @return {Object} A JSON object representing the serialized source.
  5245. * @see {@link ObjectLoader#parse}
  5246. */
  5247. toJSON( meta ) {
  5248. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  5249. if ( ! isRootObject && meta.images[ this.uuid ] !== undefined ) {
  5250. return meta.images[ this.uuid ];
  5251. }
  5252. const output = {
  5253. uuid: this.uuid,
  5254. url: ''
  5255. };
  5256. const data = this.data;
  5257. if ( data !== null ) {
  5258. let url;
  5259. if ( Array.isArray( data ) ) {
  5260. // cube texture
  5261. url = [];
  5262. for ( let i = 0, l = data.length; i < l; i ++ ) {
  5263. if ( data[ i ].isDataTexture ) {
  5264. url.push( serializeImage( data[ i ].image ) );
  5265. } else {
  5266. url.push( serializeImage( data[ i ] ) );
  5267. }
  5268. }
  5269. } else {
  5270. // texture
  5271. url = serializeImage( data );
  5272. }
  5273. output.url = url;
  5274. }
  5275. if ( ! isRootObject ) {
  5276. meta.images[ this.uuid ] = output;
  5277. }
  5278. return output;
  5279. }
  5280. }
  5281. function serializeImage( image ) {
  5282. if ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) ||
  5283. ( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) ||
  5284. ( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) ) {
  5285. // default images
  5286. return ImageUtils.getDataURL( image );
  5287. } else {
  5288. if ( image.data ) {
  5289. // images of DataTexture
  5290. return {
  5291. data: Array.from( image.data ),
  5292. width: image.width,
  5293. height: image.height,
  5294. type: image.data.constructor.name
  5295. };
  5296. } else {
  5297. console.warn( 'THREE.Texture: Unable to serialize Texture.' );
  5298. return {};
  5299. }
  5300. }
  5301. }
  5302. let _textureId = 0;
  5303. const _tempVec3 = /*@__PURE__*/ new Vector3();
  5304. /**
  5305. * Base class for all textures.
  5306. *
  5307. * Note: After the initial use of a texture, its dimensions, format, and type
  5308. * cannot be changed. Instead, call {@link Texture#dispose} on the texture and instantiate a new one.
  5309. *
  5310. * @augments EventDispatcher
  5311. */
  5312. class Texture extends EventDispatcher {
  5313. /**
  5314. * Constructs a new texture.
  5315. *
  5316. * @param {?Object} [image=Texture.DEFAULT_IMAGE] - The image holding the texture data.
  5317. * @param {number} [mapping=Texture.DEFAULT_MAPPING] - The texture mapping.
  5318. * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value.
  5319. * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value.
  5320. * @param {number} [magFilter=LinearFilter] - The mag filter value.
  5321. * @param {number} [minFilter=LinearMipmapLinearFilter] - The min filter value.
  5322. * @param {number} [format=RGBAFormat] - The texture format.
  5323. * @param {number} [type=UnsignedByteType] - The texture type.
  5324. * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value.
  5325. * @param {string} [colorSpace=NoColorSpace] - The color space.
  5326. */
  5327. 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 ) {
  5328. super();
  5329. /**
  5330. * This flag can be used for type testing.
  5331. *
  5332. * @type {boolean}
  5333. * @readonly
  5334. * @default true
  5335. */
  5336. this.isTexture = true;
  5337. /**
  5338. * The ID of the texture.
  5339. *
  5340. * @name Texture#id
  5341. * @type {number}
  5342. * @readonly
  5343. */
  5344. Object.defineProperty( this, 'id', { value: _textureId ++ } );
  5345. /**
  5346. * The UUID of the material.
  5347. *
  5348. * @type {string}
  5349. * @readonly
  5350. */
  5351. this.uuid = generateUUID();
  5352. /**
  5353. * The name of the material.
  5354. *
  5355. * @type {string}
  5356. */
  5357. this.name = '';
  5358. /**
  5359. * The data definition of a texture. A reference to the data source can be
  5360. * shared across textures. This is often useful in context of spritesheets
  5361. * where multiple textures render the same data but with different texture
  5362. * transformations.
  5363. *
  5364. * @type {Source}
  5365. */
  5366. this.source = new Source( image );
  5367. /**
  5368. * An array holding user-defined mipmaps.
  5369. *
  5370. * @type {Array<Object>}
  5371. */
  5372. this.mipmaps = [];
  5373. /**
  5374. * How the texture is applied to the object. The value `UVMapping`
  5375. * is the default, where texture or uv coordinates are used to apply the map.
  5376. *
  5377. * @type {(UVMapping|CubeReflectionMapping|CubeRefractionMapping|EquirectangularReflectionMapping|EquirectangularRefractionMapping|CubeUVReflectionMapping)}
  5378. * @default UVMapping
  5379. */
  5380. this.mapping = mapping;
  5381. /**
  5382. * Lets you select the uv attribute to map the texture to. `0` for `uv`,
  5383. * `1` for `uv1`, `2` for `uv2` and `3` for `uv3`.
  5384. *
  5385. * @type {number}
  5386. * @default 0
  5387. */
  5388. this.channel = 0;
  5389. /**
  5390. * This defines how the texture is wrapped horizontally and corresponds to
  5391. * *U* in UV mapping.
  5392. *
  5393. * @type {(RepeatWrapping|ClampToEdgeWrapping|MirroredRepeatWrapping)}
  5394. * @default ClampToEdgeWrapping
  5395. */
  5396. this.wrapS = wrapS;
  5397. /**
  5398. * This defines how the texture is wrapped horizontally and corresponds to
  5399. * *V* in UV mapping.
  5400. *
  5401. * @type {(RepeatWrapping|ClampToEdgeWrapping|MirroredRepeatWrapping)}
  5402. * @default ClampToEdgeWrapping
  5403. */
  5404. this.wrapT = wrapT;
  5405. /**
  5406. * How the texture is sampled when a texel covers more than one pixel.
  5407. *
  5408. * @type {(NearestFilter|NearestMipmapNearestFilter|NearestMipmapLinearFilter|LinearFilter|LinearMipmapNearestFilter|LinearMipmapLinearFilter)}
  5409. * @default LinearFilter
  5410. */
  5411. this.magFilter = magFilter;
  5412. /**
  5413. * How the texture is sampled when a texel covers less than one pixel.
  5414. *
  5415. * @type {(NearestFilter|NearestMipmapNearestFilter|NearestMipmapLinearFilter|LinearFilter|LinearMipmapNearestFilter|LinearMipmapLinearFilter)}
  5416. * @default LinearMipmapLinearFilter
  5417. */
  5418. this.minFilter = minFilter;
  5419. /**
  5420. * The number of samples taken along the axis through the pixel that has the
  5421. * highest density of texels. By default, this value is `1`. A higher value
  5422. * gives a less blurry result than a basic mipmap, at the cost of more
  5423. * texture samples being used.
  5424. *
  5425. * @type {number}
  5426. * @default 0
  5427. */
  5428. this.anisotropy = anisotropy;
  5429. /**
  5430. * The format of the texture.
  5431. *
  5432. * @type {number}
  5433. * @default RGBAFormat
  5434. */
  5435. this.format = format;
  5436. /**
  5437. * The default internal format is derived from {@link Texture#format} and {@link Texture#type} and
  5438. * defines how the texture data is going to be stored on the GPU.
  5439. *
  5440. * This property allows to overwrite the default format.
  5441. *
  5442. * @type {?string}
  5443. * @default null
  5444. */
  5445. this.internalFormat = null;
  5446. /**
  5447. * The data type of the texture.
  5448. *
  5449. * @type {number}
  5450. * @default UnsignedByteType
  5451. */
  5452. this.type = type;
  5453. /**
  5454. * How much a single repetition of the texture is offset from the beginning,
  5455. * in each direction U and V. Typical range is `0.0` to `1.0`.
  5456. *
  5457. * @type {Vector2}
  5458. * @default (0,0)
  5459. */
  5460. this.offset = new Vector2( 0, 0 );
  5461. /**
  5462. * How many times the texture is repeated across the surface, in each
  5463. * direction U and V. If repeat is set greater than `1` in either direction,
  5464. * the corresponding wrap parameter should also be set to `RepeatWrapping`
  5465. * or `MirroredRepeatWrapping` to achieve the desired tiling effect.
  5466. *
  5467. * @type {Vector2}
  5468. * @default (1,1)
  5469. */
  5470. this.repeat = new Vector2( 1, 1 );
  5471. /**
  5472. * The point around which rotation occurs. A value of `(0.5, 0.5)` corresponds
  5473. * to the center of the texture. Default is `(0, 0)`, the lower left.
  5474. *
  5475. * @type {Vector2}
  5476. * @default (0,0)
  5477. */
  5478. this.center = new Vector2( 0, 0 );
  5479. /**
  5480. * How much the texture is rotated around the center point, in radians.
  5481. * Positive values are counter-clockwise.
  5482. *
  5483. * @type {number}
  5484. * @default 0
  5485. */
  5486. this.rotation = 0;
  5487. /**
  5488. * Whether to update the texture's uv-transformation {@link Texture#matrix}
  5489. * from the properties {@link Texture#offset}, {@link Texture#repeat},
  5490. * {@link Texture#rotation}, and {@link Texture#center}.
  5491. *
  5492. * Set this to `false` if you are specifying the uv-transform matrix directly.
  5493. *
  5494. * @type {boolean}
  5495. * @default true
  5496. */
  5497. this.matrixAutoUpdate = true;
  5498. /**
  5499. * The uv-transformation matrix of the texture.
  5500. *
  5501. * @type {Matrix3}
  5502. */
  5503. this.matrix = new Matrix3();
  5504. /**
  5505. * Whether to generate mipmaps (if possible) for a texture.
  5506. *
  5507. * Set this to `false` if you are creating mipmaps manually.
  5508. *
  5509. * @type {boolean}
  5510. * @default true
  5511. */
  5512. this.generateMipmaps = true;
  5513. /**
  5514. * If set to `true`, the alpha channel, if present, is multiplied into the
  5515. * color channels when the texture is uploaded to the GPU.
  5516. *
  5517. * Note that this property has no effect when using `ImageBitmap`. You need to
  5518. * configure premultiply alpha on bitmap creation instead.
  5519. *
  5520. * @type {boolean}
  5521. * @default false
  5522. */
  5523. this.premultiplyAlpha = false;
  5524. /**
  5525. * If set to `true`, the texture is flipped along the vertical axis when
  5526. * uploaded to the GPU.
  5527. *
  5528. * Note that this property has no effect when using `ImageBitmap`. You need to
  5529. * configure the flip on bitmap creation instead.
  5530. *
  5531. * @type {boolean}
  5532. * @default true
  5533. */
  5534. this.flipY = true;
  5535. /**
  5536. * Specifies the alignment requirements for the start of each pixel row in memory.
  5537. * The allowable values are `1` (byte-alignment), `2` (rows aligned to even-numbered bytes),
  5538. * `4` (word-alignment), and `8` (rows start on double-word boundaries).
  5539. *
  5540. * @type {number}
  5541. * @default 4
  5542. */
  5543. this.unpackAlignment = 4; // valid values: 1, 2, 4, 8 (see http://www.khronos.org/opengles/sdk/docs/man/xhtml/glPixelStorei.xml)
  5544. /**
  5545. * Textures containing color data should be annotated with `SRGBColorSpace` or `LinearSRGBColorSpace`.
  5546. *
  5547. * @type {string}
  5548. * @default NoColorSpace
  5549. */
  5550. this.colorSpace = colorSpace;
  5551. /**
  5552. * An object that can be used to store custom data about the texture. It
  5553. * should not hold references to functions as these will not be cloned.
  5554. *
  5555. * @type {Object}
  5556. */
  5557. this.userData = {};
  5558. /**
  5559. * This can be used to only update a subregion or specific rows of the texture (for example, just the
  5560. * first 3 rows). Use the `addUpdateRange()` function to add ranges to this array.
  5561. *
  5562. * @type {Array<Object>}
  5563. */
  5564. this.updateRanges = [];
  5565. /**
  5566. * This starts at `0` and counts how many times {@link Texture#needsUpdate} is set to `true`.
  5567. *
  5568. * @type {number}
  5569. * @readonly
  5570. * @default 0
  5571. */
  5572. this.version = 0;
  5573. /**
  5574. * A callback function, called when the texture is updated (e.g., when
  5575. * {@link Texture#needsUpdate} has been set to true and then the texture is used).
  5576. *
  5577. * @type {?Function}
  5578. * @default null
  5579. */
  5580. this.onUpdate = null;
  5581. /**
  5582. * An optional back reference to the textures render target.
  5583. *
  5584. * @type {?(RenderTarget|WebGLRenderTarget)}
  5585. * @default null
  5586. */
  5587. this.renderTarget = null;
  5588. /**
  5589. * Indicates whether a texture belongs to a render target or not.
  5590. *
  5591. * @type {boolean}
  5592. * @readonly
  5593. * @default false
  5594. */
  5595. this.isRenderTargetTexture = false;
  5596. /**
  5597. * Indicates if a texture should be handled like a texture array.
  5598. *
  5599. * @type {boolean}
  5600. * @readonly
  5601. * @default false
  5602. */
  5603. this.isArrayTexture = image && image.depth && image.depth > 1 ? true : false;
  5604. /**
  5605. * Indicates whether this texture should be processed by `PMREMGenerator` or not
  5606. * (only relevant for render target textures).
  5607. *
  5608. * @type {number}
  5609. * @readonly
  5610. * @default 0
  5611. */
  5612. this.pmremVersion = 0;
  5613. }
  5614. /**
  5615. * The width of the texture in pixels.
  5616. */
  5617. get width() {
  5618. return this.source.getSize( _tempVec3 ).x;
  5619. }
  5620. /**
  5621. * The height of the texture in pixels.
  5622. */
  5623. get height() {
  5624. return this.source.getSize( _tempVec3 ).y;
  5625. }
  5626. /**
  5627. * The depth of the texture in pixels.
  5628. */
  5629. get depth() {
  5630. return this.source.getSize( _tempVec3 ).z;
  5631. }
  5632. /**
  5633. * The image object holding the texture data.
  5634. *
  5635. * @type {?Object}
  5636. */
  5637. get image() {
  5638. return this.source.data;
  5639. }
  5640. set image( value = null ) {
  5641. this.source.data = value;
  5642. }
  5643. /**
  5644. * Updates the texture transformation matrix from the from the properties {@link Texture#offset},
  5645. * {@link Texture#repeat}, {@link Texture#rotation}, and {@link Texture#center}.
  5646. */
  5647. updateMatrix() {
  5648. this.matrix.setUvTransform( this.offset.x, this.offset.y, this.repeat.x, this.repeat.y, this.rotation, this.center.x, this.center.y );
  5649. }
  5650. /**
  5651. * Adds a range of data in the data texture to be updated on the GPU.
  5652. *
  5653. * @param {number} start - Position at which to start update.
  5654. * @param {number} count - The number of components to update.
  5655. */
  5656. addUpdateRange( start, count ) {
  5657. this.updateRanges.push( { start, count } );
  5658. }
  5659. /**
  5660. * Clears the update ranges.
  5661. */
  5662. clearUpdateRanges() {
  5663. this.updateRanges.length = 0;
  5664. }
  5665. /**
  5666. * Returns a new texture with copied values from this instance.
  5667. *
  5668. * @return {Texture} A clone of this instance.
  5669. */
  5670. clone() {
  5671. return new this.constructor().copy( this );
  5672. }
  5673. /**
  5674. * Copies the values of the given texture to this instance.
  5675. *
  5676. * @param {Texture} source - The texture to copy.
  5677. * @return {Texture} A reference to this instance.
  5678. */
  5679. copy( source ) {
  5680. this.name = source.name;
  5681. this.source = source.source;
  5682. this.mipmaps = source.mipmaps.slice( 0 );
  5683. this.mapping = source.mapping;
  5684. this.channel = source.channel;
  5685. this.wrapS = source.wrapS;
  5686. this.wrapT = source.wrapT;
  5687. this.magFilter = source.magFilter;
  5688. this.minFilter = source.minFilter;
  5689. this.anisotropy = source.anisotropy;
  5690. this.format = source.format;
  5691. this.internalFormat = source.internalFormat;
  5692. this.type = source.type;
  5693. this.offset.copy( source.offset );
  5694. this.repeat.copy( source.repeat );
  5695. this.center.copy( source.center );
  5696. this.rotation = source.rotation;
  5697. this.matrixAutoUpdate = source.matrixAutoUpdate;
  5698. this.matrix.copy( source.matrix );
  5699. this.generateMipmaps = source.generateMipmaps;
  5700. this.premultiplyAlpha = source.premultiplyAlpha;
  5701. this.flipY = source.flipY;
  5702. this.unpackAlignment = source.unpackAlignment;
  5703. this.colorSpace = source.colorSpace;
  5704. this.renderTarget = source.renderTarget;
  5705. this.isRenderTargetTexture = source.isRenderTargetTexture;
  5706. this.isArrayTexture = source.isArrayTexture;
  5707. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  5708. this.needsUpdate = true;
  5709. return this;
  5710. }
  5711. /**
  5712. * Sets this texture's properties based on `values`.
  5713. * @param {Object} values - A container with texture parameters.
  5714. */
  5715. setValues( values ) {
  5716. for ( const key in values ) {
  5717. const newValue = values[ key ];
  5718. if ( newValue === undefined ) {
  5719. console.warn( `THREE.Texture.setValues(): parameter '${ key }' has value of undefined.` );
  5720. continue;
  5721. }
  5722. const currentValue = this[ key ];
  5723. if ( currentValue === undefined ) {
  5724. console.warn( `THREE.Texture.setValues(): property '${ key }' does not exist.` );
  5725. continue;
  5726. }
  5727. if ( ( currentValue && newValue ) && ( currentValue.isVector2 && newValue.isVector2 ) ) {
  5728. currentValue.copy( newValue );
  5729. } else if ( ( currentValue && newValue ) && ( currentValue.isVector3 && newValue.isVector3 ) ) {
  5730. currentValue.copy( newValue );
  5731. } else if ( ( currentValue && newValue ) && ( currentValue.isMatrix3 && newValue.isMatrix3 ) ) {
  5732. currentValue.copy( newValue );
  5733. } else {
  5734. this[ key ] = newValue;
  5735. }
  5736. }
  5737. }
  5738. /**
  5739. * Serializes the texture into JSON.
  5740. *
  5741. * @param {?(Object|string)} meta - An optional value holding meta information about the serialization.
  5742. * @return {Object} A JSON object representing the serialized texture.
  5743. * @see {@link ObjectLoader#parse}
  5744. */
  5745. toJSON( meta ) {
  5746. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  5747. if ( ! isRootObject && meta.textures[ this.uuid ] !== undefined ) {
  5748. return meta.textures[ this.uuid ];
  5749. }
  5750. const output = {
  5751. metadata: {
  5752. version: 4.6,
  5753. type: 'Texture',
  5754. generator: 'Texture.toJSON'
  5755. },
  5756. uuid: this.uuid,
  5757. name: this.name,
  5758. image: this.source.toJSON( meta ).uuid,
  5759. mapping: this.mapping,
  5760. channel: this.channel,
  5761. repeat: [ this.repeat.x, this.repeat.y ],
  5762. offset: [ this.offset.x, this.offset.y ],
  5763. center: [ this.center.x, this.center.y ],
  5764. rotation: this.rotation,
  5765. wrap: [ this.wrapS, this.wrapT ],
  5766. format: this.format,
  5767. internalFormat: this.internalFormat,
  5768. type: this.type,
  5769. colorSpace: this.colorSpace,
  5770. minFilter: this.minFilter,
  5771. magFilter: this.magFilter,
  5772. anisotropy: this.anisotropy,
  5773. flipY: this.flipY,
  5774. generateMipmaps: this.generateMipmaps,
  5775. premultiplyAlpha: this.premultiplyAlpha,
  5776. unpackAlignment: this.unpackAlignment
  5777. };
  5778. if ( Object.keys( this.userData ).length > 0 ) output.userData = this.userData;
  5779. if ( ! isRootObject ) {
  5780. meta.textures[ this.uuid ] = output;
  5781. }
  5782. return output;
  5783. }
  5784. /**
  5785. * Frees the GPU-related resources allocated by this instance. Call this
  5786. * method whenever this instance is no longer used in your app.
  5787. *
  5788. * @fires Texture#dispose
  5789. */
  5790. dispose() {
  5791. /**
  5792. * Fires when the texture has been disposed of.
  5793. *
  5794. * @event Texture#dispose
  5795. * @type {Object}
  5796. */
  5797. this.dispatchEvent( { type: 'dispose' } );
  5798. }
  5799. /**
  5800. * Transforms the given uv vector with the textures uv transformation matrix.
  5801. *
  5802. * @param {Vector2} uv - The uv vector.
  5803. * @return {Vector2} The transformed uv vector.
  5804. */
  5805. transformUv( uv ) {
  5806. if ( this.mapping !== UVMapping ) return uv;
  5807. uv.applyMatrix3( this.matrix );
  5808. if ( uv.x < 0 || uv.x > 1 ) {
  5809. switch ( this.wrapS ) {
  5810. case RepeatWrapping:
  5811. uv.x = uv.x - Math.floor( uv.x );
  5812. break;
  5813. case ClampToEdgeWrapping:
  5814. uv.x = uv.x < 0 ? 0 : 1;
  5815. break;
  5816. case MirroredRepeatWrapping:
  5817. if ( Math.abs( Math.floor( uv.x ) % 2 ) === 1 ) {
  5818. uv.x = Math.ceil( uv.x ) - uv.x;
  5819. } else {
  5820. uv.x = uv.x - Math.floor( uv.x );
  5821. }
  5822. break;
  5823. }
  5824. }
  5825. if ( uv.y < 0 || uv.y > 1 ) {
  5826. switch ( this.wrapT ) {
  5827. case RepeatWrapping:
  5828. uv.y = uv.y - Math.floor( uv.y );
  5829. break;
  5830. case ClampToEdgeWrapping:
  5831. uv.y = uv.y < 0 ? 0 : 1;
  5832. break;
  5833. case MirroredRepeatWrapping:
  5834. if ( Math.abs( Math.floor( uv.y ) % 2 ) === 1 ) {
  5835. uv.y = Math.ceil( uv.y ) - uv.y;
  5836. } else {
  5837. uv.y = uv.y - Math.floor( uv.y );
  5838. }
  5839. break;
  5840. }
  5841. }
  5842. if ( this.flipY ) {
  5843. uv.y = 1 - uv.y;
  5844. }
  5845. return uv;
  5846. }
  5847. /**
  5848. * Setting this property to `true` indicates the engine the texture
  5849. * must be updated in the next render. This triggers a texture upload
  5850. * to the GPU and ensures correct texture parameter configuration.
  5851. *
  5852. * @type {boolean}
  5853. * @default false
  5854. * @param {boolean} value
  5855. */
  5856. set needsUpdate( value ) {
  5857. if ( value === true ) {
  5858. this.version ++;
  5859. this.source.needsUpdate = true;
  5860. }
  5861. }
  5862. /**
  5863. * Setting this property to `true` indicates the engine the PMREM
  5864. * must be regenerated.
  5865. *
  5866. * @type {boolean}
  5867. * @default false
  5868. * @param {boolean} value
  5869. */
  5870. set needsPMREMUpdate( value ) {
  5871. if ( value === true ) {
  5872. this.pmremVersion ++;
  5873. }
  5874. }
  5875. }
  5876. /**
  5877. * The default image for all textures.
  5878. *
  5879. * @static
  5880. * @type {?Image}
  5881. * @default null
  5882. */
  5883. Texture.DEFAULT_IMAGE = null;
  5884. /**
  5885. * The default mapping for all textures.
  5886. *
  5887. * @static
  5888. * @type {number}
  5889. * @default UVMapping
  5890. */
  5891. Texture.DEFAULT_MAPPING = UVMapping;
  5892. /**
  5893. * The default anisotropy value for all textures.
  5894. *
  5895. * @static
  5896. * @type {number}
  5897. * @default 1
  5898. */
  5899. Texture.DEFAULT_ANISOTROPY = 1;
  5900. /**
  5901. * Class representing a 4D vector. A 4D vector is an ordered quadruplet of numbers
  5902. * (labeled x, y, z and w), which can be used to represent a number of things, such as:
  5903. *
  5904. * - A point in 4D space.
  5905. * - A direction and length in 4D space. In three.js the length will
  5906. * always be the Euclidean distance(straight-line distance) from `(0, 0, 0, 0)` to `(x, y, z, w)`
  5907. * and the direction is also measured from `(0, 0, 0, 0)` towards `(x, y, z, w)`.
  5908. * - Any arbitrary ordered quadruplet of numbers.
  5909. *
  5910. * There are other things a 4D vector can be used to represent, however these
  5911. * are the most common uses in *three.js*.
  5912. *
  5913. * Iterating through a vector instance will yield its components `(x, y, z, w)` in
  5914. * the corresponding order.
  5915. * ```js
  5916. * const a = new THREE.Vector4( 0, 1, 0, 0 );
  5917. *
  5918. * //no arguments; will be initialised to (0, 0, 0, 1)
  5919. * const b = new THREE.Vector4( );
  5920. *
  5921. * const d = a.dot( b );
  5922. * ```
  5923. */
  5924. class Vector4 {
  5925. /**
  5926. * Constructs a new 4D vector.
  5927. *
  5928. * @param {number} [x=0] - The x value of this vector.
  5929. * @param {number} [y=0] - The y value of this vector.
  5930. * @param {number} [z=0] - The z value of this vector.
  5931. * @param {number} [w=1] - The w value of this vector.
  5932. */
  5933. constructor( x = 0, y = 0, z = 0, w = 1 ) {
  5934. /**
  5935. * This flag can be used for type testing.
  5936. *
  5937. * @type {boolean}
  5938. * @readonly
  5939. * @default true
  5940. */
  5941. Vector4.prototype.isVector4 = true;
  5942. /**
  5943. * The x value of this vector.
  5944. *
  5945. * @type {number}
  5946. */
  5947. this.x = x;
  5948. /**
  5949. * The y value of this vector.
  5950. *
  5951. * @type {number}
  5952. */
  5953. this.y = y;
  5954. /**
  5955. * The z value of this vector.
  5956. *
  5957. * @type {number}
  5958. */
  5959. this.z = z;
  5960. /**
  5961. * The w value of this vector.
  5962. *
  5963. * @type {number}
  5964. */
  5965. this.w = w;
  5966. }
  5967. /**
  5968. * Alias for {@link Vector4#z}.
  5969. *
  5970. * @type {number}
  5971. */
  5972. get width() {
  5973. return this.z;
  5974. }
  5975. set width( value ) {
  5976. this.z = value;
  5977. }
  5978. /**
  5979. * Alias for {@link Vector4#w}.
  5980. *
  5981. * @type {number}
  5982. */
  5983. get height() {
  5984. return this.w;
  5985. }
  5986. set height( value ) {
  5987. this.w = value;
  5988. }
  5989. /**
  5990. * Sets the vector components.
  5991. *
  5992. * @param {number} x - The value of the x component.
  5993. * @param {number} y - The value of the y component.
  5994. * @param {number} z - The value of the z component.
  5995. * @param {number} w - The value of the w component.
  5996. * @return {Vector4} A reference to this vector.
  5997. */
  5998. set( x, y, z, w ) {
  5999. this.x = x;
  6000. this.y = y;
  6001. this.z = z;
  6002. this.w = w;
  6003. return this;
  6004. }
  6005. /**
  6006. * Sets the vector components to the same value.
  6007. *
  6008. * @param {number} scalar - The value to set for all vector components.
  6009. * @return {Vector4} A reference to this vector.
  6010. */
  6011. setScalar( scalar ) {
  6012. this.x = scalar;
  6013. this.y = scalar;
  6014. this.z = scalar;
  6015. this.w = scalar;
  6016. return this;
  6017. }
  6018. /**
  6019. * Sets the vector's x component to the given value
  6020. *
  6021. * @param {number} x - The value to set.
  6022. * @return {Vector4} A reference to this vector.
  6023. */
  6024. setX( x ) {
  6025. this.x = x;
  6026. return this;
  6027. }
  6028. /**
  6029. * Sets the vector's y component to the given value
  6030. *
  6031. * @param {number} y - The value to set.
  6032. * @return {Vector4} A reference to this vector.
  6033. */
  6034. setY( y ) {
  6035. this.y = y;
  6036. return this;
  6037. }
  6038. /**
  6039. * Sets the vector's z component to the given value
  6040. *
  6041. * @param {number} z - The value to set.
  6042. * @return {Vector4} A reference to this vector.
  6043. */
  6044. setZ( z ) {
  6045. this.z = z;
  6046. return this;
  6047. }
  6048. /**
  6049. * Sets the vector's w component to the given value
  6050. *
  6051. * @param {number} w - The value to set.
  6052. * @return {Vector4} A reference to this vector.
  6053. */
  6054. setW( w ) {
  6055. this.w = w;
  6056. return this;
  6057. }
  6058. /**
  6059. * Allows to set a vector component with an index.
  6060. *
  6061. * @param {number} index - The component index. `0` equals to x, `1` equals to y,
  6062. * `2` equals to z, `3` equals to w.
  6063. * @param {number} value - The value to set.
  6064. * @return {Vector4} A reference to this vector.
  6065. */
  6066. setComponent( index, value ) {
  6067. switch ( index ) {
  6068. case 0: this.x = value; break;
  6069. case 1: this.y = value; break;
  6070. case 2: this.z = value; break;
  6071. case 3: this.w = value; break;
  6072. default: throw new Error( 'index is out of range: ' + index );
  6073. }
  6074. return this;
  6075. }
  6076. /**
  6077. * Returns the value of the vector component which matches the given index.
  6078. *
  6079. * @param {number} index - The component index. `0` equals to x, `1` equals to y,
  6080. * `2` equals to z, `3` equals to w.
  6081. * @return {number} A vector component value.
  6082. */
  6083. getComponent( index ) {
  6084. switch ( index ) {
  6085. case 0: return this.x;
  6086. case 1: return this.y;
  6087. case 2: return this.z;
  6088. case 3: return this.w;
  6089. default: throw new Error( 'index is out of range: ' + index );
  6090. }
  6091. }
  6092. /**
  6093. * Returns a new vector with copied values from this instance.
  6094. *
  6095. * @return {Vector4} A clone of this instance.
  6096. */
  6097. clone() {
  6098. return new this.constructor( this.x, this.y, this.z, this.w );
  6099. }
  6100. /**
  6101. * Copies the values of the given vector to this instance.
  6102. *
  6103. * @param {Vector3|Vector4} v - The vector to copy.
  6104. * @return {Vector4} A reference to this vector.
  6105. */
  6106. copy( v ) {
  6107. this.x = v.x;
  6108. this.y = v.y;
  6109. this.z = v.z;
  6110. this.w = ( v.w !== undefined ) ? v.w : 1;
  6111. return this;
  6112. }
  6113. /**
  6114. * Adds the given vector to this instance.
  6115. *
  6116. * @param {Vector4} v - The vector to add.
  6117. * @return {Vector4} A reference to this vector.
  6118. */
  6119. add( v ) {
  6120. this.x += v.x;
  6121. this.y += v.y;
  6122. this.z += v.z;
  6123. this.w += v.w;
  6124. return this;
  6125. }
  6126. /**
  6127. * Adds the given scalar value to all components of this instance.
  6128. *
  6129. * @param {number} s - The scalar to add.
  6130. * @return {Vector4} A reference to this vector.
  6131. */
  6132. addScalar( s ) {
  6133. this.x += s;
  6134. this.y += s;
  6135. this.z += s;
  6136. this.w += s;
  6137. return this;
  6138. }
  6139. /**
  6140. * Adds the given vectors and stores the result in this instance.
  6141. *
  6142. * @param {Vector4} a - The first vector.
  6143. * @param {Vector4} b - The second vector.
  6144. * @return {Vector4} A reference to this vector.
  6145. */
  6146. addVectors( a, b ) {
  6147. this.x = a.x + b.x;
  6148. this.y = a.y + b.y;
  6149. this.z = a.z + b.z;
  6150. this.w = a.w + b.w;
  6151. return this;
  6152. }
  6153. /**
  6154. * Adds the given vector scaled by the given factor to this instance.
  6155. *
  6156. * @param {Vector4} v - The vector.
  6157. * @param {number} s - The factor that scales `v`.
  6158. * @return {Vector4} A reference to this vector.
  6159. */
  6160. addScaledVector( v, s ) {
  6161. this.x += v.x * s;
  6162. this.y += v.y * s;
  6163. this.z += v.z * s;
  6164. this.w += v.w * s;
  6165. return this;
  6166. }
  6167. /**
  6168. * Subtracts the given vector from this instance.
  6169. *
  6170. * @param {Vector4} v - The vector to subtract.
  6171. * @return {Vector4} A reference to this vector.
  6172. */
  6173. sub( v ) {
  6174. this.x -= v.x;
  6175. this.y -= v.y;
  6176. this.z -= v.z;
  6177. this.w -= v.w;
  6178. return this;
  6179. }
  6180. /**
  6181. * Subtracts the given scalar value from all components of this instance.
  6182. *
  6183. * @param {number} s - The scalar to subtract.
  6184. * @return {Vector4} A reference to this vector.
  6185. */
  6186. subScalar( s ) {
  6187. this.x -= s;
  6188. this.y -= s;
  6189. this.z -= s;
  6190. this.w -= s;
  6191. return this;
  6192. }
  6193. /**
  6194. * Subtracts the given vectors and stores the result in this instance.
  6195. *
  6196. * @param {Vector4} a - The first vector.
  6197. * @param {Vector4} b - The second vector.
  6198. * @return {Vector4} A reference to this vector.
  6199. */
  6200. subVectors( a, b ) {
  6201. this.x = a.x - b.x;
  6202. this.y = a.y - b.y;
  6203. this.z = a.z - b.z;
  6204. this.w = a.w - b.w;
  6205. return this;
  6206. }
  6207. /**
  6208. * Multiplies the given vector with this instance.
  6209. *
  6210. * @param {Vector4} v - The vector to multiply.
  6211. * @return {Vector4} A reference to this vector.
  6212. */
  6213. multiply( v ) {
  6214. this.x *= v.x;
  6215. this.y *= v.y;
  6216. this.z *= v.z;
  6217. this.w *= v.w;
  6218. return this;
  6219. }
  6220. /**
  6221. * Multiplies the given scalar value with all components of this instance.
  6222. *
  6223. * @param {number} scalar - The scalar to multiply.
  6224. * @return {Vector4} A reference to this vector.
  6225. */
  6226. multiplyScalar( scalar ) {
  6227. this.x *= scalar;
  6228. this.y *= scalar;
  6229. this.z *= scalar;
  6230. this.w *= scalar;
  6231. return this;
  6232. }
  6233. /**
  6234. * Multiplies this vector with the given 4x4 matrix.
  6235. *
  6236. * @param {Matrix4} m - The 4x4 matrix.
  6237. * @return {Vector4} A reference to this vector.
  6238. */
  6239. applyMatrix4( m ) {
  6240. const x = this.x, y = this.y, z = this.z, w = this.w;
  6241. const e = m.elements;
  6242. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] * w;
  6243. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] * w;
  6244. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] * w;
  6245. this.w = e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] * w;
  6246. return this;
  6247. }
  6248. /**
  6249. * Divides this instance by the given vector.
  6250. *
  6251. * @param {Vector4} v - The vector to divide.
  6252. * @return {Vector4} A reference to this vector.
  6253. */
  6254. divide( v ) {
  6255. this.x /= v.x;
  6256. this.y /= v.y;
  6257. this.z /= v.z;
  6258. this.w /= v.w;
  6259. return this;
  6260. }
  6261. /**
  6262. * Divides this vector by the given scalar.
  6263. *
  6264. * @param {number} scalar - The scalar to divide.
  6265. * @return {Vector4} A reference to this vector.
  6266. */
  6267. divideScalar( scalar ) {
  6268. return this.multiplyScalar( 1 / scalar );
  6269. }
  6270. /**
  6271. * Sets the x, y and z components of this
  6272. * vector to the quaternion's axis and w to the angle.
  6273. *
  6274. * @param {Quaternion} q - The Quaternion to set.
  6275. * @return {Vector4} A reference to this vector.
  6276. */
  6277. setAxisAngleFromQuaternion( q ) {
  6278. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToAngle/index.htm
  6279. // q is assumed to be normalized
  6280. this.w = 2 * Math.acos( q.w );
  6281. const s = Math.sqrt( 1 - q.w * q.w );
  6282. if ( s < 0.0001 ) {
  6283. this.x = 1;
  6284. this.y = 0;
  6285. this.z = 0;
  6286. } else {
  6287. this.x = q.x / s;
  6288. this.y = q.y / s;
  6289. this.z = q.z / s;
  6290. }
  6291. return this;
  6292. }
  6293. /**
  6294. * Sets the x, y and z components of this
  6295. * vector to the axis of rotation and w to the angle.
  6296. *
  6297. * @param {Matrix4} m - A 4x4 matrix of which the upper left 3x3 matrix is a pure rotation matrix.
  6298. * @return {Vector4} A reference to this vector.
  6299. */
  6300. setAxisAngleFromRotationMatrix( m ) {
  6301. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToAngle/index.htm
  6302. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  6303. let angle, x, y, z; // variables for result
  6304. const epsilon = 0.01, // margin to allow for rounding errors
  6305. epsilon2 = 0.1, // margin to distinguish between 0 and 180 degrees
  6306. te = m.elements,
  6307. m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ],
  6308. m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ],
  6309. m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];
  6310. if ( ( Math.abs( m12 - m21 ) < epsilon ) &&
  6311. ( Math.abs( m13 - m31 ) < epsilon ) &&
  6312. ( Math.abs( m23 - m32 ) < epsilon ) ) {
  6313. // singularity found
  6314. // first check for identity matrix which must have +1 for all terms
  6315. // in leading diagonal and zero in other terms
  6316. if ( ( Math.abs( m12 + m21 ) < epsilon2 ) &&
  6317. ( Math.abs( m13 + m31 ) < epsilon2 ) &&
  6318. ( Math.abs( m23 + m32 ) < epsilon2 ) &&
  6319. ( Math.abs( m11 + m22 + m33 - 3 ) < epsilon2 ) ) {
  6320. // this singularity is identity matrix so angle = 0
  6321. this.set( 1, 0, 0, 0 );
  6322. return this; // zero angle, arbitrary axis
  6323. }
  6324. // otherwise this singularity is angle = 180
  6325. angle = Math.PI;
  6326. const xx = ( m11 + 1 ) / 2;
  6327. const yy = ( m22 + 1 ) / 2;
  6328. const zz = ( m33 + 1 ) / 2;
  6329. const xy = ( m12 + m21 ) / 4;
  6330. const xz = ( m13 + m31 ) / 4;
  6331. const yz = ( m23 + m32 ) / 4;
  6332. if ( ( xx > yy ) && ( xx > zz ) ) {
  6333. // m11 is the largest diagonal term
  6334. if ( xx < epsilon ) {
  6335. x = 0;
  6336. y = 0.707106781;
  6337. z = 0.707106781;
  6338. } else {
  6339. x = Math.sqrt( xx );
  6340. y = xy / x;
  6341. z = xz / x;
  6342. }
  6343. } else if ( yy > zz ) {
  6344. // m22 is the largest diagonal term
  6345. if ( yy < epsilon ) {
  6346. x = 0.707106781;
  6347. y = 0;
  6348. z = 0.707106781;
  6349. } else {
  6350. y = Math.sqrt( yy );
  6351. x = xy / y;
  6352. z = yz / y;
  6353. }
  6354. } else {
  6355. // m33 is the largest diagonal term so base result on this
  6356. if ( zz < epsilon ) {
  6357. x = 0.707106781;
  6358. y = 0.707106781;
  6359. z = 0;
  6360. } else {
  6361. z = Math.sqrt( zz );
  6362. x = xz / z;
  6363. y = yz / z;
  6364. }
  6365. }
  6366. this.set( x, y, z, angle );
  6367. return this; // return 180 deg rotation
  6368. }
  6369. // as we have reached here there are no singularities so we can handle normally
  6370. let s = Math.sqrt( ( m32 - m23 ) * ( m32 - m23 ) +
  6371. ( m13 - m31 ) * ( m13 - m31 ) +
  6372. ( m21 - m12 ) * ( m21 - m12 ) ); // used to normalize
  6373. if ( Math.abs( s ) < 0.001 ) s = 1;
  6374. // prevent divide by zero, should not happen if matrix is orthogonal and should be
  6375. // caught by singularity test above, but I've left it in just in case
  6376. this.x = ( m32 - m23 ) / s;
  6377. this.y = ( m13 - m31 ) / s;
  6378. this.z = ( m21 - m12 ) / s;
  6379. this.w = Math.acos( ( m11 + m22 + m33 - 1 ) / 2 );
  6380. return this;
  6381. }
  6382. /**
  6383. * Sets the vector components to the position elements of the
  6384. * given transformation matrix.
  6385. *
  6386. * @param {Matrix4} m - The 4x4 matrix.
  6387. * @return {Vector4} A reference to this vector.
  6388. */
  6389. setFromMatrixPosition( m ) {
  6390. const e = m.elements;
  6391. this.x = e[ 12 ];
  6392. this.y = e[ 13 ];
  6393. this.z = e[ 14 ];
  6394. this.w = e[ 15 ];
  6395. return this;
  6396. }
  6397. /**
  6398. * If this vector's x, y, z or w value is greater than the given vector's x, y, z or w
  6399. * value, replace that value with the corresponding min value.
  6400. *
  6401. * @param {Vector4} v - The vector.
  6402. * @return {Vector4} A reference to this vector.
  6403. */
  6404. min( v ) {
  6405. this.x = Math.min( this.x, v.x );
  6406. this.y = Math.min( this.y, v.y );
  6407. this.z = Math.min( this.z, v.z );
  6408. this.w = Math.min( this.w, v.w );
  6409. return this;
  6410. }
  6411. /**
  6412. * If this vector's x, y, z or w value is less than the given vector's x, y, z or w
  6413. * value, replace that value with the corresponding max value.
  6414. *
  6415. * @param {Vector4} v - The vector.
  6416. * @return {Vector4} A reference to this vector.
  6417. */
  6418. max( v ) {
  6419. this.x = Math.max( this.x, v.x );
  6420. this.y = Math.max( this.y, v.y );
  6421. this.z = Math.max( this.z, v.z );
  6422. this.w = Math.max( this.w, v.w );
  6423. return this;
  6424. }
  6425. /**
  6426. * If this vector's x, y, z or w value is greater than the max vector's x, y, z or w
  6427. * value, it is replaced by the corresponding value.
  6428. * If this vector's x, y, z or w value is less than the min vector's x, y, z or w value,
  6429. * it is replaced by the corresponding value.
  6430. *
  6431. * @param {Vector4} min - The minimum x, y and z values.
  6432. * @param {Vector4} max - The maximum x, y and z values in the desired range.
  6433. * @return {Vector4} A reference to this vector.
  6434. */
  6435. clamp( min, max ) {
  6436. // assumes min < max, componentwise
  6437. this.x = clamp( this.x, min.x, max.x );
  6438. this.y = clamp( this.y, min.y, max.y );
  6439. this.z = clamp( this.z, min.z, max.z );
  6440. this.w = clamp( this.w, min.w, max.w );
  6441. return this;
  6442. }
  6443. /**
  6444. * If this vector's x, y, z or w values are greater than the max value, they are
  6445. * replaced by the max value.
  6446. * If this vector's x, y, z or w values are less than the min value, they are
  6447. * replaced by the min value.
  6448. *
  6449. * @param {number} minVal - The minimum value the components will be clamped to.
  6450. * @param {number} maxVal - The maximum value the components will be clamped to.
  6451. * @return {Vector4} A reference to this vector.
  6452. */
  6453. clampScalar( minVal, maxVal ) {
  6454. this.x = clamp( this.x, minVal, maxVal );
  6455. this.y = clamp( this.y, minVal, maxVal );
  6456. this.z = clamp( this.z, minVal, maxVal );
  6457. this.w = clamp( this.w, minVal, maxVal );
  6458. return this;
  6459. }
  6460. /**
  6461. * If this vector's length is greater than the max value, it is replaced by
  6462. * the max value.
  6463. * If this vector's length is less than the min value, it is replaced by the
  6464. * min value.
  6465. *
  6466. * @param {number} min - The minimum value the vector length will be clamped to.
  6467. * @param {number} max - The maximum value the vector length will be clamped to.
  6468. * @return {Vector4} A reference to this vector.
  6469. */
  6470. clampLength( min, max ) {
  6471. const length = this.length();
  6472. return this.divideScalar( length || 1 ).multiplyScalar( clamp( length, min, max ) );
  6473. }
  6474. /**
  6475. * The components of this vector are rounded down to the nearest integer value.
  6476. *
  6477. * @return {Vector4} A reference to this vector.
  6478. */
  6479. floor() {
  6480. this.x = Math.floor( this.x );
  6481. this.y = Math.floor( this.y );
  6482. this.z = Math.floor( this.z );
  6483. this.w = Math.floor( this.w );
  6484. return this;
  6485. }
  6486. /**
  6487. * The components of this vector are rounded up to the nearest integer value.
  6488. *
  6489. * @return {Vector4} A reference to this vector.
  6490. */
  6491. ceil() {
  6492. this.x = Math.ceil( this.x );
  6493. this.y = Math.ceil( this.y );
  6494. this.z = Math.ceil( this.z );
  6495. this.w = Math.ceil( this.w );
  6496. return this;
  6497. }
  6498. /**
  6499. * The components of this vector are rounded to the nearest integer value
  6500. *
  6501. * @return {Vector4} A reference to this vector.
  6502. */
  6503. round() {
  6504. this.x = Math.round( this.x );
  6505. this.y = Math.round( this.y );
  6506. this.z = Math.round( this.z );
  6507. this.w = Math.round( this.w );
  6508. return this;
  6509. }
  6510. /**
  6511. * The components of this vector are rounded towards zero (up if negative,
  6512. * down if positive) to an integer value.
  6513. *
  6514. * @return {Vector4} A reference to this vector.
  6515. */
  6516. roundToZero() {
  6517. this.x = Math.trunc( this.x );
  6518. this.y = Math.trunc( this.y );
  6519. this.z = Math.trunc( this.z );
  6520. this.w = Math.trunc( this.w );
  6521. return this;
  6522. }
  6523. /**
  6524. * Inverts this vector - i.e. sets x = -x, y = -y, z = -z, w = -w.
  6525. *
  6526. * @return {Vector4} A reference to this vector.
  6527. */
  6528. negate() {
  6529. this.x = - this.x;
  6530. this.y = - this.y;
  6531. this.z = - this.z;
  6532. this.w = - this.w;
  6533. return this;
  6534. }
  6535. /**
  6536. * Calculates the dot product of the given vector with this instance.
  6537. *
  6538. * @param {Vector4} v - The vector to compute the dot product with.
  6539. * @return {number} The result of the dot product.
  6540. */
  6541. dot( v ) {
  6542. return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w;
  6543. }
  6544. /**
  6545. * Computes the square of the Euclidean length (straight-line length) from
  6546. * (0, 0, 0, 0) to (x, y, z, w). If you are comparing the lengths of vectors, you should
  6547. * compare the length squared instead as it is slightly more efficient to calculate.
  6548. *
  6549. * @return {number} The square length of this vector.
  6550. */
  6551. lengthSq() {
  6552. return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w;
  6553. }
  6554. /**
  6555. * Computes the Euclidean length (straight-line length) from (0, 0, 0, 0) to (x, y, z, w).
  6556. *
  6557. * @return {number} The length of this vector.
  6558. */
  6559. length() {
  6560. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w );
  6561. }
  6562. /**
  6563. * Computes the Manhattan length of this vector.
  6564. *
  6565. * @return {number} The length of this vector.
  6566. */
  6567. manhattanLength() {
  6568. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z ) + Math.abs( this.w );
  6569. }
  6570. /**
  6571. * Converts this vector to a unit vector - that is, sets it equal to a vector
  6572. * with the same direction as this one, but with a vector length of `1`.
  6573. *
  6574. * @return {Vector4} A reference to this vector.
  6575. */
  6576. normalize() {
  6577. return this.divideScalar( this.length() || 1 );
  6578. }
  6579. /**
  6580. * Sets this vector to a vector with the same direction as this one, but
  6581. * with the specified length.
  6582. *
  6583. * @param {number} length - The new length of this vector.
  6584. * @return {Vector4} A reference to this vector.
  6585. */
  6586. setLength( length ) {
  6587. return this.normalize().multiplyScalar( length );
  6588. }
  6589. /**
  6590. * Linearly interpolates between the given vector and this instance, where
  6591. * alpha is the percent distance along the line - alpha = 0 will be this
  6592. * vector, and alpha = 1 will be the given one.
  6593. *
  6594. * @param {Vector4} v - The vector to interpolate towards.
  6595. * @param {number} alpha - The interpolation factor, typically in the closed interval `[0, 1]`.
  6596. * @return {Vector4} A reference to this vector.
  6597. */
  6598. lerp( v, alpha ) {
  6599. this.x += ( v.x - this.x ) * alpha;
  6600. this.y += ( v.y - this.y ) * alpha;
  6601. this.z += ( v.z - this.z ) * alpha;
  6602. this.w += ( v.w - this.w ) * alpha;
  6603. return this;
  6604. }
  6605. /**
  6606. * Linearly interpolates between the given vectors, where alpha is the percent
  6607. * distance along the line - alpha = 0 will be first vector, and alpha = 1 will
  6608. * be the second one. The result is stored in this instance.
  6609. *
  6610. * @param {Vector4} v1 - The first vector.
  6611. * @param {Vector4} v2 - The second vector.
  6612. * @param {number} alpha - The interpolation factor, typically in the closed interval `[0, 1]`.
  6613. * @return {Vector4} A reference to this vector.
  6614. */
  6615. lerpVectors( v1, v2, alpha ) {
  6616. this.x = v1.x + ( v2.x - v1.x ) * alpha;
  6617. this.y = v1.y + ( v2.y - v1.y ) * alpha;
  6618. this.z = v1.z + ( v2.z - v1.z ) * alpha;
  6619. this.w = v1.w + ( v2.w - v1.w ) * alpha;
  6620. return this;
  6621. }
  6622. /**
  6623. * Returns `true` if this vector is equal with the given one.
  6624. *
  6625. * @param {Vector4} v - The vector to test for equality.
  6626. * @return {boolean} Whether this vector is equal with the given one.
  6627. */
  6628. equals( v ) {
  6629. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) && ( v.w === this.w ) );
  6630. }
  6631. /**
  6632. * Sets this vector's x value to be `array[ offset ]`, y value to be `array[ offset + 1 ]`,
  6633. * z value to be `array[ offset + 2 ]`, w value to be `array[ offset + 3 ]`.
  6634. *
  6635. * @param {Array<number>} array - An array holding the vector component values.
  6636. * @param {number} [offset=0] - The offset into the array.
  6637. * @return {Vector4} A reference to this vector.
  6638. */
  6639. fromArray( array, offset = 0 ) {
  6640. this.x = array[ offset ];
  6641. this.y = array[ offset + 1 ];
  6642. this.z = array[ offset + 2 ];
  6643. this.w = array[ offset + 3 ];
  6644. return this;
  6645. }
  6646. /**
  6647. * Writes the components of this vector to the given array. If no array is provided,
  6648. * the method returns a new instance.
  6649. *
  6650. * @param {Array<number>} [array=[]] - The target array holding the vector components.
  6651. * @param {number} [offset=0] - Index of the first element in the array.
  6652. * @return {Array<number>} The vector components.
  6653. */
  6654. toArray( array = [], offset = 0 ) {
  6655. array[ offset ] = this.x;
  6656. array[ offset + 1 ] = this.y;
  6657. array[ offset + 2 ] = this.z;
  6658. array[ offset + 3 ] = this.w;
  6659. return array;
  6660. }
  6661. /**
  6662. * Sets the components of this vector from the given buffer attribute.
  6663. *
  6664. * @param {BufferAttribute} attribute - The buffer attribute holding vector data.
  6665. * @param {number} index - The index into the attribute.
  6666. * @return {Vector4} A reference to this vector.
  6667. */
  6668. fromBufferAttribute( attribute, index ) {
  6669. this.x = attribute.getX( index );
  6670. this.y = attribute.getY( index );
  6671. this.z = attribute.getZ( index );
  6672. this.w = attribute.getW( index );
  6673. return this;
  6674. }
  6675. /**
  6676. * Sets each component of this vector to a pseudo-random value between `0` and
  6677. * `1`, excluding `1`.
  6678. *
  6679. * @return {Vector4} A reference to this vector.
  6680. */
  6681. random() {
  6682. this.x = Math.random();
  6683. this.y = Math.random();
  6684. this.z = Math.random();
  6685. this.w = Math.random();
  6686. return this;
  6687. }
  6688. *[ Symbol.iterator ]() {
  6689. yield this.x;
  6690. yield this.y;
  6691. yield this.z;
  6692. yield this.w;
  6693. }
  6694. }
  6695. /**
  6696. * A render target is a buffer where the video card draws pixels for a scene
  6697. * that is being rendered in the background. It is used in different effects,
  6698. * such as applying postprocessing to a rendered image before displaying it
  6699. * on the screen.
  6700. *
  6701. * @augments EventDispatcher
  6702. */
  6703. class RenderTarget extends EventDispatcher {
  6704. /**
  6705. * Render target options.
  6706. *
  6707. * @typedef {Object} RenderTarget~Options
  6708. * @property {boolean} [generateMipmaps=false] - Whether to generate mipmaps or not.
  6709. * @property {number} [magFilter=LinearFilter] - The mag filter.
  6710. * @property {number} [minFilter=LinearFilter] - The min filter.
  6711. * @property {number} [format=RGBAFormat] - The texture format.
  6712. * @property {number} [type=UnsignedByteType] - The texture type.
  6713. * @property {?string} [internalFormat=null] - The texture's internal format.
  6714. * @property {number} [wrapS=ClampToEdgeWrapping] - The texture's uv wrapping mode.
  6715. * @property {number} [wrapT=ClampToEdgeWrapping] - The texture's uv wrapping mode.
  6716. * @property {number} [anisotropy=1] - The texture's anisotropy value.
  6717. * @property {string} [colorSpace=NoColorSpace] - The texture's color space.
  6718. * @property {boolean} [depthBuffer=true] - Whether to allocate a depth buffer or not.
  6719. * @property {boolean} [stencilBuffer=false] - Whether to allocate a stencil buffer or not.
  6720. * @property {boolean} [resolveDepthBuffer=true] - Whether to resolve the depth buffer or not.
  6721. * @property {boolean} [resolveStencilBuffer=true] - Whether to resolve the stencil buffer or not.
  6722. * @property {?Texture} [depthTexture=null] - Reference to a depth texture.
  6723. * @property {number} [samples=0] - The MSAA samples count.
  6724. * @property {number} [count=1] - Defines the number of color attachments . Must be at least `1`.
  6725. * @property {number} [depth=1] - The texture depth.
  6726. * @property {boolean} [multiview=false] - Whether this target is used for multiview rendering.
  6727. */
  6728. /**
  6729. * Constructs a new render target.
  6730. *
  6731. * @param {number} [width=1] - The width of the render target.
  6732. * @param {number} [height=1] - The height of the render target.
  6733. * @param {RenderTarget~Options} [options] - The configuration object.
  6734. */
  6735. constructor( width = 1, height = 1, options = {} ) {
  6736. super();
  6737. options = Object.assign( {
  6738. generateMipmaps: false,
  6739. internalFormat: null,
  6740. minFilter: LinearFilter,
  6741. depthBuffer: true,
  6742. stencilBuffer: false,
  6743. resolveDepthBuffer: true,
  6744. resolveStencilBuffer: true,
  6745. depthTexture: null,
  6746. samples: 0,
  6747. count: 1,
  6748. depth: 1,
  6749. multiview: false
  6750. }, options );
  6751. /**
  6752. * This flag can be used for type testing.
  6753. *
  6754. * @type {boolean}
  6755. * @readonly
  6756. * @default true
  6757. */
  6758. this.isRenderTarget = true;
  6759. /**
  6760. * The width of the render target.
  6761. *
  6762. * @type {number}
  6763. * @default 1
  6764. */
  6765. this.width = width;
  6766. /**
  6767. * The height of the render target.
  6768. *
  6769. * @type {number}
  6770. * @default 1
  6771. */
  6772. this.height = height;
  6773. /**
  6774. * The depth of the render target.
  6775. *
  6776. * @type {number}
  6777. * @default 1
  6778. */
  6779. this.depth = options.depth;
  6780. /**
  6781. * A rectangular area inside the render target's viewport. Fragments that are
  6782. * outside the area will be discarded.
  6783. *
  6784. * @type {Vector4}
  6785. * @default (0,0,width,height)
  6786. */
  6787. this.scissor = new Vector4( 0, 0, width, height );
  6788. /**
  6789. * Indicates whether the scissor test should be enabled when rendering into
  6790. * this render target or not.
  6791. *
  6792. * @type {boolean}
  6793. * @default false
  6794. */
  6795. this.scissorTest = false;
  6796. /**
  6797. * A rectangular area representing the render target's viewport.
  6798. *
  6799. * @type {Vector4}
  6800. * @default (0,0,width,height)
  6801. */
  6802. this.viewport = new Vector4( 0, 0, width, height );
  6803. const image = { width: width, height: height, depth: options.depth };
  6804. const texture = new Texture( image );
  6805. /**
  6806. * An array of textures. Each color attachment is represented as a separate texture.
  6807. * Has at least a single entry for the default color attachment.
  6808. *
  6809. * @type {Array<Texture>}
  6810. */
  6811. this.textures = [];
  6812. const count = options.count;
  6813. for ( let i = 0; i < count; i ++ ) {
  6814. this.textures[ i ] = texture.clone();
  6815. this.textures[ i ].isRenderTargetTexture = true;
  6816. this.textures[ i ].renderTarget = this;
  6817. }
  6818. this._setTextureOptions( options );
  6819. /**
  6820. * Whether to allocate a depth buffer or not.
  6821. *
  6822. * @type {boolean}
  6823. * @default true
  6824. */
  6825. this.depthBuffer = options.depthBuffer;
  6826. /**
  6827. * Whether to allocate a stencil buffer or not.
  6828. *
  6829. * @type {boolean}
  6830. * @default false
  6831. */
  6832. this.stencilBuffer = options.stencilBuffer;
  6833. /**
  6834. * Whether to resolve the depth buffer or not.
  6835. *
  6836. * @type {boolean}
  6837. * @default true
  6838. */
  6839. this.resolveDepthBuffer = options.resolveDepthBuffer;
  6840. /**
  6841. * Whether to resolve the stencil buffer or not.
  6842. *
  6843. * @type {boolean}
  6844. * @default true
  6845. */
  6846. this.resolveStencilBuffer = options.resolveStencilBuffer;
  6847. this._depthTexture = null;
  6848. this.depthTexture = options.depthTexture;
  6849. /**
  6850. * The number of MSAA samples.
  6851. *
  6852. * A value of `0` disables MSAA.
  6853. *
  6854. * @type {number}
  6855. * @default 0
  6856. */
  6857. this.samples = options.samples;
  6858. /**
  6859. * Whether to this target is used in multiview rendering.
  6860. *
  6861. * @type {boolean}
  6862. * @default false
  6863. */
  6864. this.multiview = options.multiview;
  6865. }
  6866. _setTextureOptions( options = {} ) {
  6867. const values = {
  6868. minFilter: LinearFilter,
  6869. generateMipmaps: false,
  6870. flipY: false,
  6871. internalFormat: null
  6872. };
  6873. if ( options.mapping !== undefined ) values.mapping = options.mapping;
  6874. if ( options.wrapS !== undefined ) values.wrapS = options.wrapS;
  6875. if ( options.wrapT !== undefined ) values.wrapT = options.wrapT;
  6876. if ( options.wrapR !== undefined ) values.wrapR = options.wrapR;
  6877. if ( options.magFilter !== undefined ) values.magFilter = options.magFilter;
  6878. if ( options.minFilter !== undefined ) values.minFilter = options.minFilter;
  6879. if ( options.format !== undefined ) values.format = options.format;
  6880. if ( options.type !== undefined ) values.type = options.type;
  6881. if ( options.anisotropy !== undefined ) values.anisotropy = options.anisotropy;
  6882. if ( options.colorSpace !== undefined ) values.colorSpace = options.colorSpace;
  6883. if ( options.flipY !== undefined ) values.flipY = options.flipY;
  6884. if ( options.generateMipmaps !== undefined ) values.generateMipmaps = options.generateMipmaps;
  6885. if ( options.internalFormat !== undefined ) values.internalFormat = options.internalFormat;
  6886. for ( let i = 0; i < this.textures.length; i ++ ) {
  6887. const texture = this.textures[ i ];
  6888. texture.setValues( values );
  6889. }
  6890. }
  6891. /**
  6892. * The texture representing the default color attachment.
  6893. *
  6894. * @type {Texture}
  6895. */
  6896. get texture() {
  6897. return this.textures[ 0 ];
  6898. }
  6899. set texture( value ) {
  6900. this.textures[ 0 ] = value;
  6901. }
  6902. set depthTexture( current ) {
  6903. if ( this._depthTexture !== null ) this._depthTexture.renderTarget = null;
  6904. if ( current !== null ) current.renderTarget = this;
  6905. this._depthTexture = current;
  6906. }
  6907. /**
  6908. * Instead of saving the depth in a renderbuffer, a texture
  6909. * can be used instead which is useful for further processing
  6910. * e.g. in context of post-processing.
  6911. *
  6912. * @type {?DepthTexture}
  6913. * @default null
  6914. */
  6915. get depthTexture() {
  6916. return this._depthTexture;
  6917. }
  6918. /**
  6919. * Sets the size of this render target.
  6920. *
  6921. * @param {number} width - The width.
  6922. * @param {number} height - The height.
  6923. * @param {number} [depth=1] - The depth.
  6924. */
  6925. setSize( width, height, depth = 1 ) {
  6926. if ( this.width !== width || this.height !== height || this.depth !== depth ) {
  6927. this.width = width;
  6928. this.height = height;
  6929. this.depth = depth;
  6930. for ( let i = 0, il = this.textures.length; i < il; i ++ ) {
  6931. this.textures[ i ].image.width = width;
  6932. this.textures[ i ].image.height = height;
  6933. this.textures[ i ].image.depth = depth;
  6934. this.textures[ i ].isArrayTexture = this.textures[ i ].image.depth > 1;
  6935. }
  6936. this.dispose();
  6937. }
  6938. this.viewport.set( 0, 0, width, height );
  6939. this.scissor.set( 0, 0, width, height );
  6940. }
  6941. /**
  6942. * Returns a new render target with copied values from this instance.
  6943. *
  6944. * @return {RenderTarget} A clone of this instance.
  6945. */
  6946. clone() {
  6947. return new this.constructor().copy( this );
  6948. }
  6949. /**
  6950. * Copies the settings of the given render target. This is a structural copy so
  6951. * no resources are shared between render targets after the copy. That includes
  6952. * all MRT textures and the depth texture.
  6953. *
  6954. * @param {RenderTarget} source - The render target to copy.
  6955. * @return {RenderTarget} A reference to this instance.
  6956. */
  6957. copy( source ) {
  6958. this.width = source.width;
  6959. this.height = source.height;
  6960. this.depth = source.depth;
  6961. this.scissor.copy( source.scissor );
  6962. this.scissorTest = source.scissorTest;
  6963. this.viewport.copy( source.viewport );
  6964. this.textures.length = 0;
  6965. for ( let i = 0, il = source.textures.length; i < il; i ++ ) {
  6966. this.textures[ i ] = source.textures[ i ].clone();
  6967. this.textures[ i ].isRenderTargetTexture = true;
  6968. this.textures[ i ].renderTarget = this;
  6969. // ensure image object is not shared, see #20328
  6970. const image = Object.assign( {}, source.textures[ i ].image );
  6971. this.textures[ i ].source = new Source( image );
  6972. }
  6973. this.depthBuffer = source.depthBuffer;
  6974. this.stencilBuffer = source.stencilBuffer;
  6975. this.resolveDepthBuffer = source.resolveDepthBuffer;
  6976. this.resolveStencilBuffer = source.resolveStencilBuffer;
  6977. if ( source.depthTexture !== null ) this.depthTexture = source.depthTexture.clone();
  6978. this.samples = source.samples;
  6979. return this;
  6980. }
  6981. /**
  6982. * Frees the GPU-related resources allocated by this instance. Call this
  6983. * method whenever this instance is no longer used in your app.
  6984. *
  6985. * @fires RenderTarget#dispose
  6986. */
  6987. dispose() {
  6988. this.dispatchEvent( { type: 'dispose' } );
  6989. }
  6990. }
  6991. /**
  6992. * A render target used in context of {@link WebGLRenderer}.
  6993. *
  6994. * @augments RenderTarget
  6995. */
  6996. class WebGLRenderTarget extends RenderTarget {
  6997. /**
  6998. * Constructs a new 3D render target.
  6999. *
  7000. * @param {number} [width=1] - The width of the render target.
  7001. * @param {number} [height=1] - The height of the render target.
  7002. * @param {RenderTarget~Options} [options] - The configuration object.
  7003. */
  7004. constructor( width = 1, height = 1, options = {} ) {
  7005. super( width, height, options );
  7006. /**
  7007. * This flag can be used for type testing.
  7008. *
  7009. * @type {boolean}
  7010. * @readonly
  7011. * @default true
  7012. */
  7013. this.isWebGLRenderTarget = true;
  7014. }
  7015. }
  7016. /**
  7017. * Creates an array of textures directly from raw buffer data.
  7018. *
  7019. * @augments Texture
  7020. */
  7021. class DataArrayTexture extends Texture {
  7022. /**
  7023. * Constructs a new data array texture.
  7024. *
  7025. * @param {?TypedArray} [data=null] - The buffer data.
  7026. * @param {number} [width=1] - The width of the texture.
  7027. * @param {number} [height=1] - The height of the texture.
  7028. * @param {number} [depth=1] - The depth of the texture.
  7029. */
  7030. constructor( data = null, width = 1, height = 1, depth = 1 ) {
  7031. super( null );
  7032. /**
  7033. * This flag can be used for type testing.
  7034. *
  7035. * @type {boolean}
  7036. * @readonly
  7037. * @default true
  7038. */
  7039. this.isDataArrayTexture = true;
  7040. /**
  7041. * The image definition of a data texture.
  7042. *
  7043. * @type {{data:TypedArray,width:number,height:number,depth:number}}
  7044. */
  7045. this.image = { data, width, height, depth };
  7046. /**
  7047. * How the texture is sampled when a texel covers more than one pixel.
  7048. *
  7049. * Overwritten and set to `NearestFilter` by default.
  7050. *
  7051. * @type {(NearestFilter|NearestMipmapNearestFilter|NearestMipmapLinearFilter|LinearFilter|LinearMipmapNearestFilter|LinearMipmapLinearFilter)}
  7052. * @default NearestFilter
  7053. */
  7054. this.magFilter = NearestFilter;
  7055. /**
  7056. * How the texture is sampled when a texel covers less than one pixel.
  7057. *
  7058. * Overwritten and set to `NearestFilter` by default.
  7059. *
  7060. * @type {(NearestFilter|NearestMipmapNearestFilter|NearestMipmapLinearFilter|LinearFilter|LinearMipmapNearestFilter|LinearMipmapLinearFilter)}
  7061. * @default NearestFilter
  7062. */
  7063. this.minFilter = NearestFilter;
  7064. /**
  7065. * This defines how the texture is wrapped in the depth and corresponds to
  7066. * *W* in UVW mapping.
  7067. *
  7068. * @type {(RepeatWrapping|ClampToEdgeWrapping|MirroredRepeatWrapping)}
  7069. * @default ClampToEdgeWrapping
  7070. */
  7071. this.wrapR = ClampToEdgeWrapping;
  7072. /**
  7073. * Whether to generate mipmaps (if possible) for a texture.
  7074. *
  7075. * Overwritten and set to `false` by default.
  7076. *
  7077. * @type {boolean}
  7078. * @default false
  7079. */
  7080. this.generateMipmaps = false;
  7081. /**
  7082. * If set to `true`, the texture is flipped along the vertical axis when
  7083. * uploaded to the GPU.
  7084. *
  7085. * Overwritten and set to `false` by default.
  7086. *
  7087. * @type {boolean}
  7088. * @default false
  7089. */
  7090. this.flipY = false;
  7091. /**
  7092. * Specifies the alignment requirements for the start of each pixel row in memory.
  7093. *
  7094. * Overwritten and set to `1` by default.
  7095. *
  7096. * @type {boolean}
  7097. * @default 1
  7098. */
  7099. this.unpackAlignment = 1;
  7100. /**
  7101. * A set of all layers which need to be updated in the texture.
  7102. *
  7103. * @type {Set<number>}
  7104. */
  7105. this.layerUpdates = new Set();
  7106. }
  7107. /**
  7108. * Describes that a specific layer of the texture needs to be updated.
  7109. * Normally when {@link Texture#needsUpdate} is set to `true`, the
  7110. * entire data texture array is sent to the GPU. Marking specific
  7111. * layers will only transmit subsets of all mipmaps associated with a
  7112. * specific depth in the array which is often much more performant.
  7113. *
  7114. * @param {number} layerIndex - The layer index that should be updated.
  7115. */
  7116. addLayerUpdate( layerIndex ) {
  7117. this.layerUpdates.add( layerIndex );
  7118. }
  7119. /**
  7120. * Resets the layer updates registry.
  7121. */
  7122. clearLayerUpdates() {
  7123. this.layerUpdates.clear();
  7124. }
  7125. }
  7126. /**
  7127. * An array render target used in context of {@link WebGLRenderer}.
  7128. *
  7129. * @augments WebGLRenderTarget
  7130. */
  7131. class WebGLArrayRenderTarget extends WebGLRenderTarget {
  7132. /**
  7133. * Constructs a new array render target.
  7134. *
  7135. * @param {number} [width=1] - The width of the render target.
  7136. * @param {number} [height=1] - The height of the render target.
  7137. * @param {number} [depth=1] - The height of the render target.
  7138. * @param {RenderTarget~Options} [options] - The configuration object.
  7139. */
  7140. constructor( width = 1, height = 1, depth = 1, options = {} ) {
  7141. super( width, height, options );
  7142. /**
  7143. * This flag can be used for type testing.
  7144. *
  7145. * @type {boolean}
  7146. * @readonly
  7147. * @default true
  7148. */
  7149. this.isWebGLArrayRenderTarget = true;
  7150. this.depth = depth;
  7151. /**
  7152. * Overwritten with a different texture type.
  7153. *
  7154. * @type {DataArrayTexture}
  7155. */
  7156. this.texture = new DataArrayTexture( null, width, height, depth );
  7157. this._setTextureOptions( options );
  7158. this.texture.isRenderTargetTexture = true;
  7159. }
  7160. }
  7161. /**
  7162. * Creates a three-dimensional texture from raw data, with parameters to
  7163. * divide it into width, height, and depth.
  7164. *
  7165. * @augments Texture
  7166. */
  7167. class Data3DTexture extends Texture {
  7168. /**
  7169. * Constructs a new data array texture.
  7170. *
  7171. * @param {?TypedArray} [data=null] - The buffer data.
  7172. * @param {number} [width=1] - The width of the texture.
  7173. * @param {number} [height=1] - The height of the texture.
  7174. * @param {number} [depth=1] - The depth of the texture.
  7175. */
  7176. constructor( data = null, width = 1, height = 1, depth = 1 ) {
  7177. // We're going to add .setXXX() methods for setting properties later.
  7178. // Users can still set in Data3DTexture directly.
  7179. //
  7180. // const texture = new THREE.Data3DTexture( data, width, height, depth );
  7181. // texture.anisotropy = 16;
  7182. //
  7183. // See #14839
  7184. super( null );
  7185. /**
  7186. * This flag can be used for type testing.
  7187. *
  7188. * @type {boolean}
  7189. * @readonly
  7190. * @default true
  7191. */
  7192. this.isData3DTexture = true;
  7193. /**
  7194. * The image definition of a data texture.
  7195. *
  7196. * @type {{data:TypedArray,width:number,height:number,depth:number}}
  7197. */
  7198. this.image = { data, width, height, depth };
  7199. /**
  7200. * How the texture is sampled when a texel covers more than one pixel.
  7201. *
  7202. * Overwritten and set to `NearestFilter` by default.
  7203. *
  7204. * @type {(NearestFilter|NearestMipmapNearestFilter|NearestMipmapLinearFilter|LinearFilter|LinearMipmapNearestFilter|LinearMipmapLinearFilter)}
  7205. * @default NearestFilter
  7206. */
  7207. this.magFilter = NearestFilter;
  7208. /**
  7209. * How the texture is sampled when a texel covers less than one pixel.
  7210. *
  7211. * Overwritten and set to `NearestFilter` by default.
  7212. *
  7213. * @type {(NearestFilter|NearestMipmapNearestFilter|NearestMipmapLinearFilter|LinearFilter|LinearMipmapNearestFilter|LinearMipmapLinearFilter)}
  7214. * @default NearestFilter
  7215. */
  7216. this.minFilter = NearestFilter;
  7217. /**
  7218. * This defines how the texture is wrapped in the depth and corresponds to
  7219. * *W* in UVW mapping.
  7220. *
  7221. * @type {(RepeatWrapping|ClampToEdgeWrapping|MirroredRepeatWrapping)}
  7222. * @default ClampToEdgeWrapping
  7223. */
  7224. this.wrapR = ClampToEdgeWrapping;
  7225. /**
  7226. * Whether to generate mipmaps (if possible) for a texture.
  7227. *
  7228. * Overwritten and set to `false` by default.
  7229. *
  7230. * @type {boolean}
  7231. * @default false
  7232. */
  7233. this.generateMipmaps = false;
  7234. /**
  7235. * If set to `true`, the texture is flipped along the vertical axis when
  7236. * uploaded to the GPU.
  7237. *
  7238. * Overwritten and set to `false` by default.
  7239. *
  7240. * @type {boolean}
  7241. * @default false
  7242. */
  7243. this.flipY = false;
  7244. /**
  7245. * Specifies the alignment requirements for the start of each pixel row in memory.
  7246. *
  7247. * Overwritten and set to `1` by default.
  7248. *
  7249. * @type {boolean}
  7250. * @default 1
  7251. */
  7252. this.unpackAlignment = 1;
  7253. }
  7254. }
  7255. /**
  7256. * A 3D render target used in context of {@link WebGLRenderer}.
  7257. *
  7258. * @augments WebGLRenderTarget
  7259. */
  7260. class WebGL3DRenderTarget extends WebGLRenderTarget {
  7261. /**
  7262. * Constructs a new 3D render target.
  7263. *
  7264. * @param {number} [width=1] - The width of the render target.
  7265. * @param {number} [height=1] - The height of the render target.
  7266. * @param {number} [depth=1] - The height of the render target.
  7267. * @param {RenderTarget~Options} [options] - The configuration object.
  7268. */
  7269. constructor( width = 1, height = 1, depth = 1, options = {} ) {
  7270. super( width, height, options );
  7271. /**
  7272. * This flag can be used for type testing.
  7273. *
  7274. * @type {boolean}
  7275. * @readonly
  7276. * @default true
  7277. */
  7278. this.isWebGL3DRenderTarget = true;
  7279. this.depth = depth;
  7280. /**
  7281. * Overwritten with a different texture type.
  7282. *
  7283. * @type {Data3DTexture}
  7284. */
  7285. this.texture = new Data3DTexture( null, width, height, depth );
  7286. this._setTextureOptions( options );
  7287. this.texture.isRenderTargetTexture = true;
  7288. }
  7289. }
  7290. /**
  7291. * Represents an axis-aligned bounding box (AABB) in 3D space.
  7292. */
  7293. class Box3 {
  7294. /**
  7295. * Constructs a new bounding box.
  7296. *
  7297. * @param {Vector3} [min=(Infinity,Infinity,Infinity)] - A vector representing the lower boundary of the box.
  7298. * @param {Vector3} [max=(-Infinity,-Infinity,-Infinity)] - A vector representing the upper boundary of the box.
  7299. */
  7300. constructor( min = new Vector3( + Infinity, + Infinity, + Infinity ), max = new Vector3( - Infinity, - Infinity, - Infinity ) ) {
  7301. /**
  7302. * This flag can be used for type testing.
  7303. *
  7304. * @type {boolean}
  7305. * @readonly
  7306. * @default true
  7307. */
  7308. this.isBox3 = true;
  7309. /**
  7310. * The lower boundary of the box.
  7311. *
  7312. * @type {Vector3}
  7313. */
  7314. this.min = min;
  7315. /**
  7316. * The upper boundary of the box.
  7317. *
  7318. * @type {Vector3}
  7319. */
  7320. this.max = max;
  7321. }
  7322. /**
  7323. * Sets the lower and upper boundaries of this box.
  7324. * Please note that this method only copies the values from the given objects.
  7325. *
  7326. * @param {Vector3} min - The lower boundary of the box.
  7327. * @param {Vector3} max - The upper boundary of the box.
  7328. * @return {Box3} A reference to this bounding box.
  7329. */
  7330. set( min, max ) {
  7331. this.min.copy( min );
  7332. this.max.copy( max );
  7333. return this;
  7334. }
  7335. /**
  7336. * Sets the upper and lower bounds of this box so it encloses the position data
  7337. * in the given array.
  7338. *
  7339. * @param {Array<number>} array - An array holding 3D position data.
  7340. * @return {Box3} A reference to this bounding box.
  7341. */
  7342. setFromArray( array ) {
  7343. this.makeEmpty();
  7344. for ( let i = 0, il = array.length; i < il; i += 3 ) {
  7345. this.expandByPoint( _vector$b.fromArray( array, i ) );
  7346. }
  7347. return this;
  7348. }
  7349. /**
  7350. * Sets the upper and lower bounds of this box so it encloses the position data
  7351. * in the given buffer attribute.
  7352. *
  7353. * @param {BufferAttribute} attribute - A buffer attribute holding 3D position data.
  7354. * @return {Box3} A reference to this bounding box.
  7355. */
  7356. setFromBufferAttribute( attribute ) {
  7357. this.makeEmpty();
  7358. for ( let i = 0, il = attribute.count; i < il; i ++ ) {
  7359. this.expandByPoint( _vector$b.fromBufferAttribute( attribute, i ) );
  7360. }
  7361. return this;
  7362. }
  7363. /**
  7364. * Sets the upper and lower bounds of this box so it encloses the position data
  7365. * in the given array.
  7366. *
  7367. * @param {Array<Vector3>} points - An array holding 3D position data as instances of {@link Vector3}.
  7368. * @return {Box3} A reference to this bounding box.
  7369. */
  7370. setFromPoints( points ) {
  7371. this.makeEmpty();
  7372. for ( let i = 0, il = points.length; i < il; i ++ ) {
  7373. this.expandByPoint( points[ i ] );
  7374. }
  7375. return this;
  7376. }
  7377. /**
  7378. * Centers this box on the given center vector and sets this box's width, height and
  7379. * depth to the given size values.
  7380. *
  7381. * @param {Vector3} center - The center of the box.
  7382. * @param {Vector3} size - The x, y and z dimensions of the box.
  7383. * @return {Box3} A reference to this bounding box.
  7384. */
  7385. setFromCenterAndSize( center, size ) {
  7386. const halfSize = _vector$b.copy( size ).multiplyScalar( 0.5 );
  7387. this.min.copy( center ).sub( halfSize );
  7388. this.max.copy( center ).add( halfSize );
  7389. return this;
  7390. }
  7391. /**
  7392. * Computes the world-axis-aligned bounding box for the given 3D object
  7393. * (including its children), accounting for the object's, and children's,
  7394. * world transforms. The function may result in a larger box than strictly necessary.
  7395. *
  7396. * @param {Object3D} object - The 3D object to compute the bounding box for.
  7397. * @param {boolean} [precise=false] - If set to `true`, the method computes the smallest
  7398. * world-axis-aligned bounding box at the expense of more computation.
  7399. * @return {Box3} A reference to this bounding box.
  7400. */
  7401. setFromObject( object, precise = false ) {
  7402. this.makeEmpty();
  7403. return this.expandByObject( object, precise );
  7404. }
  7405. /**
  7406. * Returns a new box with copied values from this instance.
  7407. *
  7408. * @return {Box3} A clone of this instance.
  7409. */
  7410. clone() {
  7411. return new this.constructor().copy( this );
  7412. }
  7413. /**
  7414. * Copies the values of the given box to this instance.
  7415. *
  7416. * @param {Box3} box - The box to copy.
  7417. * @return {Box3} A reference to this bounding box.
  7418. */
  7419. copy( box ) {
  7420. this.min.copy( box.min );
  7421. this.max.copy( box.max );
  7422. return this;
  7423. }
  7424. /**
  7425. * Makes this box empty which means in encloses a zero space in 3D.
  7426. *
  7427. * @return {Box3} A reference to this bounding box.
  7428. */
  7429. makeEmpty() {
  7430. this.min.x = this.min.y = this.min.z = + Infinity;
  7431. this.max.x = this.max.y = this.max.z = - Infinity;
  7432. return this;
  7433. }
  7434. /**
  7435. * Returns true if this box includes zero points within its bounds.
  7436. * Note that a box with equal lower and upper bounds still includes one
  7437. * point, the one both bounds share.
  7438. *
  7439. * @return {boolean} Whether this box is empty or not.
  7440. */
  7441. isEmpty() {
  7442. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  7443. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y ) || ( this.max.z < this.min.z );
  7444. }
  7445. /**
  7446. * Returns the center point of this box.
  7447. *
  7448. * @param {Vector3} target - The target vector that is used to store the method's result.
  7449. * @return {Vector3} The center point.
  7450. */
  7451. getCenter( target ) {
  7452. return this.isEmpty() ? target.set( 0, 0, 0 ) : target.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  7453. }
  7454. /**
  7455. * Returns the dimensions of this box.
  7456. *
  7457. * @param {Vector3} target - The target vector that is used to store the method's result.
  7458. * @return {Vector3} The size.
  7459. */
  7460. getSize( target ) {
  7461. return this.isEmpty() ? target.set( 0, 0, 0 ) : target.subVectors( this.max, this.min );
  7462. }
  7463. /**
  7464. * Expands the boundaries of this box to include the given point.
  7465. *
  7466. * @param {Vector3} point - The point that should be included by the bounding box.
  7467. * @return {Box3} A reference to this bounding box.
  7468. */
  7469. expandByPoint( point ) {
  7470. this.min.min( point );
  7471. this.max.max( point );
  7472. return this;
  7473. }
  7474. /**
  7475. * Expands this box equilaterally by the given vector. The width of this
  7476. * box will be expanded by the x component of the vector in both
  7477. * directions. The height of this box will be expanded by the y component of
  7478. * the vector in both directions. The depth of this box will be
  7479. * expanded by the z component of the vector in both directions.
  7480. *
  7481. * @param {Vector3} vector - The vector that should expand the bounding box.
  7482. * @return {Box3} A reference to this bounding box.
  7483. */
  7484. expandByVector( vector ) {
  7485. this.min.sub( vector );
  7486. this.max.add( vector );
  7487. return this;
  7488. }
  7489. /**
  7490. * Expands each dimension of the box by the given scalar. If negative, the
  7491. * dimensions of the box will be contracted.
  7492. *
  7493. * @param {number} scalar - The scalar value that should expand the bounding box.
  7494. * @return {Box3} A reference to this bounding box.
  7495. */
  7496. expandByScalar( scalar ) {
  7497. this.min.addScalar( - scalar );
  7498. this.max.addScalar( scalar );
  7499. return this;
  7500. }
  7501. /**
  7502. * Expands the boundaries of this box to include the given 3D object and
  7503. * its children, accounting for the object's, and children's, world
  7504. * transforms. The function may result in a larger box than strictly
  7505. * necessary (unless the precise parameter is set to true).
  7506. *
  7507. * @param {Object3D} object - The 3D object that should expand the bounding box.
  7508. * @param {boolean} precise - If set to `true`, the method expands the bounding box
  7509. * as little as necessary at the expense of more computation.
  7510. * @return {Box3} A reference to this bounding box.
  7511. */
  7512. expandByObject( object, precise = false ) {
  7513. // Computes the world-axis-aligned bounding box of an object (including its children),
  7514. // accounting for both the object's, and children's, world transforms
  7515. object.updateWorldMatrix( false, false );
  7516. const geometry = object.geometry;
  7517. if ( geometry !== undefined ) {
  7518. const positionAttribute = geometry.getAttribute( 'position' );
  7519. // precise AABB computation based on vertex data requires at least a position attribute.
  7520. // instancing isn't supported so far and uses the normal (conservative) code path.
  7521. if ( precise === true && positionAttribute !== undefined && object.isInstancedMesh !== true ) {
  7522. for ( let i = 0, l = positionAttribute.count; i < l; i ++ ) {
  7523. if ( object.isMesh === true ) {
  7524. object.getVertexPosition( i, _vector$b );
  7525. } else {
  7526. _vector$b.fromBufferAttribute( positionAttribute, i );
  7527. }
  7528. _vector$b.applyMatrix4( object.matrixWorld );
  7529. this.expandByPoint( _vector$b );
  7530. }
  7531. } else {
  7532. if ( object.boundingBox !== undefined ) {
  7533. // object-level bounding box
  7534. if ( object.boundingBox === null ) {
  7535. object.computeBoundingBox();
  7536. }
  7537. _box$4.copy( object.boundingBox );
  7538. } else {
  7539. // geometry-level bounding box
  7540. if ( geometry.boundingBox === null ) {
  7541. geometry.computeBoundingBox();
  7542. }
  7543. _box$4.copy( geometry.boundingBox );
  7544. }
  7545. _box$4.applyMatrix4( object.matrixWorld );
  7546. this.union( _box$4 );
  7547. }
  7548. }
  7549. const children = object.children;
  7550. for ( let i = 0, l = children.length; i < l; i ++ ) {
  7551. this.expandByObject( children[ i ], precise );
  7552. }
  7553. return this;
  7554. }
  7555. /**
  7556. * Returns `true` if the given point lies within or on the boundaries of this box.
  7557. *
  7558. * @param {Vector3} point - The point to test.
  7559. * @return {boolean} Whether the bounding box contains the given point or not.
  7560. */
  7561. containsPoint( point ) {
  7562. return point.x >= this.min.x && point.x <= this.max.x &&
  7563. point.y >= this.min.y && point.y <= this.max.y &&
  7564. point.z >= this.min.z && point.z <= this.max.z;
  7565. }
  7566. /**
  7567. * Returns `true` if this bounding box includes the entirety of the given bounding box.
  7568. * If this box and the given one are identical, this function also returns `true`.
  7569. *
  7570. * @param {Box3} box - The bounding box to test.
  7571. * @return {boolean} Whether the bounding box contains the given bounding box or not.
  7572. */
  7573. containsBox( box ) {
  7574. return this.min.x <= box.min.x && box.max.x <= this.max.x &&
  7575. this.min.y <= box.min.y && box.max.y <= this.max.y &&
  7576. this.min.z <= box.min.z && box.max.z <= this.max.z;
  7577. }
  7578. /**
  7579. * Returns a point as a proportion of this box's width, height and depth.
  7580. *
  7581. * @param {Vector3} point - A point in 3D space.
  7582. * @param {Vector3} target - The target vector that is used to store the method's result.
  7583. * @return {Vector3} A point as a proportion of this box's width, height and depth.
  7584. */
  7585. getParameter( point, target ) {
  7586. // This can potentially have a divide by zero if the box
  7587. // has a size dimension of 0.
  7588. return target.set(
  7589. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  7590. ( point.y - this.min.y ) / ( this.max.y - this.min.y ),
  7591. ( point.z - this.min.z ) / ( this.max.z - this.min.z )
  7592. );
  7593. }
  7594. /**
  7595. * Returns `true` if the given bounding box intersects with this bounding box.
  7596. *
  7597. * @param {Box3} box - The bounding box to test.
  7598. * @return {boolean} Whether the given bounding box intersects with this bounding box.
  7599. */
  7600. intersectsBox( box ) {
  7601. // using 6 splitting planes to rule out intersections.
  7602. return box.max.x >= this.min.x && box.min.x <= this.max.x &&
  7603. box.max.y >= this.min.y && box.min.y <= this.max.y &&
  7604. box.max.z >= this.min.z && box.min.z <= this.max.z;
  7605. }
  7606. /**
  7607. * Returns `true` if the given bounding sphere intersects with this bounding box.
  7608. *
  7609. * @param {Sphere} sphere - The bounding sphere to test.
  7610. * @return {boolean} Whether the given bounding sphere intersects with this bounding box.
  7611. */
  7612. intersectsSphere( sphere ) {
  7613. // Find the point on the AABB closest to the sphere center.
  7614. this.clampPoint( sphere.center, _vector$b );
  7615. // If that point is inside the sphere, the AABB and sphere intersect.
  7616. return _vector$b.distanceToSquared( sphere.center ) <= ( sphere.radius * sphere.radius );
  7617. }
  7618. /**
  7619. * Returns `true` if the given plane intersects with this bounding box.
  7620. *
  7621. * @param {Plane} plane - The plane to test.
  7622. * @return {boolean} Whether the given plane intersects with this bounding box.
  7623. */
  7624. intersectsPlane( plane ) {
  7625. // We compute the minimum and maximum dot product values. If those values
  7626. // are on the same side (back or front) of the plane, then there is no intersection.
  7627. let min, max;
  7628. if ( plane.normal.x > 0 ) {
  7629. min = plane.normal.x * this.min.x;
  7630. max = plane.normal.x * this.max.x;
  7631. } else {
  7632. min = plane.normal.x * this.max.x;
  7633. max = plane.normal.x * this.min.x;
  7634. }
  7635. if ( plane.normal.y > 0 ) {
  7636. min += plane.normal.y * this.min.y;
  7637. max += plane.normal.y * this.max.y;
  7638. } else {
  7639. min += plane.normal.y * this.max.y;
  7640. max += plane.normal.y * this.min.y;
  7641. }
  7642. if ( plane.normal.z > 0 ) {
  7643. min += plane.normal.z * this.min.z;
  7644. max += plane.normal.z * this.max.z;
  7645. } else {
  7646. min += plane.normal.z * this.max.z;
  7647. max += plane.normal.z * this.min.z;
  7648. }
  7649. return ( min <= - plane.constant && max >= - plane.constant );
  7650. }
  7651. /**
  7652. * Returns `true` if the given triangle intersects with this bounding box.
  7653. *
  7654. * @param {Triangle} triangle - The triangle to test.
  7655. * @return {boolean} Whether the given triangle intersects with this bounding box.
  7656. */
  7657. intersectsTriangle( triangle ) {
  7658. if ( this.isEmpty() ) {
  7659. return false;
  7660. }
  7661. // compute box center and extents
  7662. this.getCenter( _center );
  7663. _extents.subVectors( this.max, _center );
  7664. // translate triangle to aabb origin
  7665. _v0$2.subVectors( triangle.a, _center );
  7666. _v1$7.subVectors( triangle.b, _center );
  7667. _v2$4.subVectors( triangle.c, _center );
  7668. // compute edge vectors for triangle
  7669. _f0.subVectors( _v1$7, _v0$2 );
  7670. _f1.subVectors( _v2$4, _v1$7 );
  7671. _f2.subVectors( _v0$2, _v2$4 );
  7672. // test against axes that are given by cross product combinations of the edges of the triangle and the edges of the aabb
  7673. // 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
  7674. // axis_ij = u_i x f_j (u0, u1, u2 = face normals of aabb = x,y,z axes vectors since aabb is axis aligned)
  7675. let axes = [
  7676. 0, - _f0.z, _f0.y, 0, - _f1.z, _f1.y, 0, - _f2.z, _f2.y,
  7677. _f0.z, 0, - _f0.x, _f1.z, 0, - _f1.x, _f2.z, 0, - _f2.x,
  7678. - _f0.y, _f0.x, 0, - _f1.y, _f1.x, 0, - _f2.y, _f2.x, 0
  7679. ];
  7680. if ( ! satForAxes( axes, _v0$2, _v1$7, _v2$4, _extents ) ) {
  7681. return false;
  7682. }
  7683. // test 3 face normals from the aabb
  7684. axes = [ 1, 0, 0, 0, 1, 0, 0, 0, 1 ];
  7685. if ( ! satForAxes( axes, _v0$2, _v1$7, _v2$4, _extents ) ) {
  7686. return false;
  7687. }
  7688. // finally testing the face normal of the triangle
  7689. // use already existing triangle edge vectors here
  7690. _triangleNormal.crossVectors( _f0, _f1 );
  7691. axes = [ _triangleNormal.x, _triangleNormal.y, _triangleNormal.z ];
  7692. return satForAxes( axes, _v0$2, _v1$7, _v2$4, _extents );
  7693. }
  7694. /**
  7695. * Clamps the given point within the bounds of this box.
  7696. *
  7697. * @param {Vector3} point - The point to clamp.
  7698. * @param {Vector3} target - The target vector that is used to store the method's result.
  7699. * @return {Vector3} The clamped point.
  7700. */
  7701. clampPoint( point, target ) {
  7702. return target.copy( point ).clamp( this.min, this.max );
  7703. }
  7704. /**
  7705. * Returns the euclidean distance from any edge of this box to the specified point. If
  7706. * the given point lies inside of this box, the distance will be `0`.
  7707. *
  7708. * @param {Vector3} point - The point to compute the distance to.
  7709. * @return {number} The euclidean distance.
  7710. */
  7711. distanceToPoint( point ) {
  7712. return this.clampPoint( point, _vector$b ).distanceTo( point );
  7713. }
  7714. /**
  7715. * Returns a bounding sphere that encloses this bounding box.
  7716. *
  7717. * @param {Sphere} target - The target sphere that is used to store the method's result.
  7718. * @return {Sphere} The bounding sphere that encloses this bounding box.
  7719. */
  7720. getBoundingSphere( target ) {
  7721. if ( this.isEmpty() ) {
  7722. target.makeEmpty();
  7723. } else {
  7724. this.getCenter( target.center );
  7725. target.radius = this.getSize( _vector$b ).length() * 0.5;
  7726. }
  7727. return target;
  7728. }
  7729. /**
  7730. * Computes the intersection of this bounding box and the given one, setting the upper
  7731. * bound of this box to the lesser of the two boxes' upper bounds and the
  7732. * lower bound of this box to the greater of the two boxes' lower bounds. If
  7733. * there's no overlap, makes this box empty.
  7734. *
  7735. * @param {Box3} box - The bounding box to intersect with.
  7736. * @return {Box3} A reference to this bounding box.
  7737. */
  7738. intersect( box ) {
  7739. this.min.max( box.min );
  7740. this.max.min( box.max );
  7741. // 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.
  7742. if ( this.isEmpty() ) this.makeEmpty();
  7743. return this;
  7744. }
  7745. /**
  7746. * Computes the union of this box and another and the given one, setting the upper
  7747. * bound of this box to the greater of the two boxes' upper bounds and the
  7748. * lower bound of this box to the lesser of the two boxes' lower bounds.
  7749. *
  7750. * @param {Box3} box - The bounding box that will be unioned with this instance.
  7751. * @return {Box3} A reference to this bounding box.
  7752. */
  7753. union( box ) {
  7754. this.min.min( box.min );
  7755. this.max.max( box.max );
  7756. return this;
  7757. }
  7758. /**
  7759. * Transforms this bounding box by the given 4x4 transformation matrix.
  7760. *
  7761. * @param {Matrix4} matrix - The transformation matrix.
  7762. * @return {Box3} A reference to this bounding box.
  7763. */
  7764. applyMatrix4( matrix ) {
  7765. // transform of empty box is an empty box.
  7766. if ( this.isEmpty() ) return this;
  7767. // NOTE: I am using a binary pattern to specify all 2^3 combinations below
  7768. _points[ 0 ].set( this.min.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 000
  7769. _points[ 1 ].set( this.min.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 001
  7770. _points[ 2 ].set( this.min.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 010
  7771. _points[ 3 ].set( this.min.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 011
  7772. _points[ 4 ].set( this.max.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 100
  7773. _points[ 5 ].set( this.max.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 101
  7774. _points[ 6 ].set( this.max.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 110
  7775. _points[ 7 ].set( this.max.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 111
  7776. this.setFromPoints( _points );
  7777. return this;
  7778. }
  7779. /**
  7780. * Adds the given offset to both the upper and lower bounds of this bounding box,
  7781. * effectively moving it in 3D space.
  7782. *
  7783. * @param {Vector3} offset - The offset that should be used to translate the bounding box.
  7784. * @return {Box3} A reference to this bounding box.
  7785. */
  7786. translate( offset ) {
  7787. this.min.add( offset );
  7788. this.max.add( offset );
  7789. return this;
  7790. }
  7791. /**
  7792. * Returns `true` if this bounding box is equal with the given one.
  7793. *
  7794. * @param {Box3} box - The box to test for equality.
  7795. * @return {boolean} Whether this bounding box is equal with the given one.
  7796. */
  7797. equals( box ) {
  7798. return box.min.equals( this.min ) && box.max.equals( this.max );
  7799. }
  7800. /**
  7801. * Returns a serialized structure of the bounding box.
  7802. *
  7803. * @return {Object} Serialized structure with fields representing the object state.
  7804. */
  7805. toJSON() {
  7806. return {
  7807. min: this.min.toArray(),
  7808. max: this.max.toArray()
  7809. };
  7810. }
  7811. /**
  7812. * Returns a serialized structure of the bounding box.
  7813. *
  7814. * @param {Object} json - The serialized json to set the box from.
  7815. * @return {Box3} A reference to this bounding box.
  7816. */
  7817. fromJSON( json ) {
  7818. this.min.fromArray( json.min );
  7819. this.max.fromArray( json.max );
  7820. return this;
  7821. }
  7822. }
  7823. const _points = [
  7824. /*@__PURE__*/ new Vector3(),
  7825. /*@__PURE__*/ new Vector3(),
  7826. /*@__PURE__*/ new Vector3(),
  7827. /*@__PURE__*/ new Vector3(),
  7828. /*@__PURE__*/ new Vector3(),
  7829. /*@__PURE__*/ new Vector3(),
  7830. /*@__PURE__*/ new Vector3(),
  7831. /*@__PURE__*/ new Vector3()
  7832. ];
  7833. const _vector$b = /*@__PURE__*/ new Vector3();
  7834. const _box$4 = /*@__PURE__*/ new Box3();
  7835. // triangle centered vertices
  7836. const _v0$2 = /*@__PURE__*/ new Vector3();
  7837. const _v1$7 = /*@__PURE__*/ new Vector3();
  7838. const _v2$4 = /*@__PURE__*/ new Vector3();
  7839. // triangle edge vectors
  7840. const _f0 = /*@__PURE__*/ new Vector3();
  7841. const _f1 = /*@__PURE__*/ new Vector3();
  7842. const _f2 = /*@__PURE__*/ new Vector3();
  7843. const _center = /*@__PURE__*/ new Vector3();
  7844. const _extents = /*@__PURE__*/ new Vector3();
  7845. const _triangleNormal = /*@__PURE__*/ new Vector3();
  7846. const _testAxis = /*@__PURE__*/ new Vector3();
  7847. function satForAxes( axes, v0, v1, v2, extents ) {
  7848. for ( let i = 0, j = axes.length - 3; i <= j; i += 3 ) {
  7849. _testAxis.fromArray( axes, i );
  7850. // project the aabb onto the separating axis
  7851. const r = extents.x * Math.abs( _testAxis.x ) + extents.y * Math.abs( _testAxis.y ) + extents.z * Math.abs( _testAxis.z );
  7852. // project all 3 vertices of the triangle onto the separating axis
  7853. const p0 = v0.dot( _testAxis );
  7854. const p1 = v1.dot( _testAxis );
  7855. const p2 = v2.dot( _testAxis );
  7856. // actual test, basically see if either of the most extreme of the triangle points intersects r
  7857. if ( Math.max( - Math.max( p0, p1, p2 ), Math.min( p0, p1, p2 ) ) > r ) {
  7858. // points of the projected triangle are outside the projected half-length of the aabb
  7859. // the axis is separating and we can exit
  7860. return false;
  7861. }
  7862. }
  7863. return true;
  7864. }
  7865. const _box$3 = /*@__PURE__*/ new Box3();
  7866. const _v1$6 = /*@__PURE__*/ new Vector3();
  7867. const _v2$3 = /*@__PURE__*/ new Vector3();
  7868. /**
  7869. * An analytical 3D sphere defined by a center and radius. This class is mainly
  7870. * used as a Bounding Sphere for 3D objects.
  7871. */
  7872. class Sphere {
  7873. /**
  7874. * Constructs a new sphere.
  7875. *
  7876. * @param {Vector3} [center=(0,0,0)] - The center of the sphere
  7877. * @param {number} [radius=-1] - The radius of the sphere.
  7878. */
  7879. constructor( center = new Vector3(), radius = -1 ) {
  7880. /**
  7881. * This flag can be used for type testing.
  7882. *
  7883. * @type {boolean}
  7884. * @readonly
  7885. * @default true
  7886. */
  7887. this.isSphere = true;
  7888. /**
  7889. * The center of the sphere
  7890. *
  7891. * @type {Vector3}
  7892. */
  7893. this.center = center;
  7894. /**
  7895. * The radius of the sphere.
  7896. *
  7897. * @type {number}
  7898. */
  7899. this.radius = radius;
  7900. }
  7901. /**
  7902. * Sets the sphere's components by copying the given values.
  7903. *
  7904. * @param {Vector3} center - The center.
  7905. * @param {number} radius - The radius.
  7906. * @return {Sphere} A reference to this sphere.
  7907. */
  7908. set( center, radius ) {
  7909. this.center.copy( center );
  7910. this.radius = radius;
  7911. return this;
  7912. }
  7913. /**
  7914. * Computes the minimum bounding sphere for list of points.
  7915. * If the optional center point is given, it is used as the sphere's
  7916. * center. Otherwise, the center of the axis-aligned bounding box
  7917. * encompassing the points is calculated.
  7918. *
  7919. * @param {Array<Vector3>} points - A list of points in 3D space.
  7920. * @param {Vector3} [optionalCenter] - The center of the sphere.
  7921. * @return {Sphere} A reference to this sphere.
  7922. */
  7923. setFromPoints( points, optionalCenter ) {
  7924. const center = this.center;
  7925. if ( optionalCenter !== undefined ) {
  7926. center.copy( optionalCenter );
  7927. } else {
  7928. _box$3.setFromPoints( points ).getCenter( center );
  7929. }
  7930. let maxRadiusSq = 0;
  7931. for ( let i = 0, il = points.length; i < il; i ++ ) {
  7932. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( points[ i ] ) );
  7933. }
  7934. this.radius = Math.sqrt( maxRadiusSq );
  7935. return this;
  7936. }
  7937. /**
  7938. * Copies the values of the given sphere to this instance.
  7939. *
  7940. * @param {Sphere} sphere - The sphere to copy.
  7941. * @return {Sphere} A reference to this sphere.
  7942. */
  7943. copy( sphere ) {
  7944. this.center.copy( sphere.center );
  7945. this.radius = sphere.radius;
  7946. return this;
  7947. }
  7948. /**
  7949. * Returns `true` if the sphere is empty (the radius set to a negative number).
  7950. *
  7951. * Spheres with a radius of `0` contain only their center point and are not
  7952. * considered to be empty.
  7953. *
  7954. * @return {boolean} Whether this sphere is empty or not.
  7955. */
  7956. isEmpty() {
  7957. return ( this.radius < 0 );
  7958. }
  7959. /**
  7960. * Makes this sphere empty which means in encloses a zero space in 3D.
  7961. *
  7962. * @return {Sphere} A reference to this sphere.
  7963. */
  7964. makeEmpty() {
  7965. this.center.set( 0, 0, 0 );
  7966. this.radius = -1;
  7967. return this;
  7968. }
  7969. /**
  7970. * Returns `true` if this sphere contains the given point inclusive of
  7971. * the surface of the sphere.
  7972. *
  7973. * @param {Vector3} point - The point to check.
  7974. * @return {boolean} Whether this sphere contains the given point or not.
  7975. */
  7976. containsPoint( point ) {
  7977. return ( point.distanceToSquared( this.center ) <= ( this.radius * this.radius ) );
  7978. }
  7979. /**
  7980. * Returns the closest distance from the boundary of the sphere to the
  7981. * given point. If the sphere contains the point, the distance will
  7982. * be negative.
  7983. *
  7984. * @param {Vector3} point - The point to compute the distance to.
  7985. * @return {number} The distance to the point.
  7986. */
  7987. distanceToPoint( point ) {
  7988. return ( point.distanceTo( this.center ) - this.radius );
  7989. }
  7990. /**
  7991. * Returns `true` if this sphere intersects with the given one.
  7992. *
  7993. * @param {Sphere} sphere - The sphere to test.
  7994. * @return {boolean} Whether this sphere intersects with the given one or not.
  7995. */
  7996. intersectsSphere( sphere ) {
  7997. const radiusSum = this.radius + sphere.radius;
  7998. return sphere.center.distanceToSquared( this.center ) <= ( radiusSum * radiusSum );
  7999. }
  8000. /**
  8001. * Returns `true` if this sphere intersects with the given box.
  8002. *
  8003. * @param {Box3} box - The box to test.
  8004. * @return {boolean} Whether this sphere intersects with the given box or not.
  8005. */
  8006. intersectsBox( box ) {
  8007. return box.intersectsSphere( this );
  8008. }
  8009. /**
  8010. * Returns `true` if this sphere intersects with the given plane.
  8011. *
  8012. * @param {Plane} plane - The plane to test.
  8013. * @return {boolean} Whether this sphere intersects with the given plane or not.
  8014. */
  8015. intersectsPlane( plane ) {
  8016. return Math.abs( plane.distanceToPoint( this.center ) ) <= this.radius;
  8017. }
  8018. /**
  8019. * Clamps a point within the sphere. If the point is outside the sphere, it
  8020. * will clamp it to the closest point on the edge of the sphere. Points
  8021. * already inside the sphere will not be affected.
  8022. *
  8023. * @param {Vector3} point - The plane to clamp.
  8024. * @param {Vector3} target - The target vector that is used to store the method's result.
  8025. * @return {Vector3} The clamped point.
  8026. */
  8027. clampPoint( point, target ) {
  8028. const deltaLengthSq = this.center.distanceToSquared( point );
  8029. target.copy( point );
  8030. if ( deltaLengthSq > ( this.radius * this.radius ) ) {
  8031. target.sub( this.center ).normalize();
  8032. target.multiplyScalar( this.radius ).add( this.center );
  8033. }
  8034. return target;
  8035. }
  8036. /**
  8037. * Returns a bounding box that encloses this sphere.
  8038. *
  8039. * @param {Box3} target - The target box that is used to store the method's result.
  8040. * @return {Box3} The bounding box that encloses this sphere.
  8041. */
  8042. getBoundingBox( target ) {
  8043. if ( this.isEmpty() ) {
  8044. // Empty sphere produces empty bounding box
  8045. target.makeEmpty();
  8046. return target;
  8047. }
  8048. target.set( this.center, this.center );
  8049. target.expandByScalar( this.radius );
  8050. return target;
  8051. }
  8052. /**
  8053. * Transforms this sphere with the given 4x4 transformation matrix.
  8054. *
  8055. * @param {Matrix4} matrix - The transformation matrix.
  8056. * @return {Sphere} A reference to this sphere.
  8057. */
  8058. applyMatrix4( matrix ) {
  8059. this.center.applyMatrix4( matrix );
  8060. this.radius = this.radius * matrix.getMaxScaleOnAxis();
  8061. return this;
  8062. }
  8063. /**
  8064. * Translates the sphere's center by the given offset.
  8065. *
  8066. * @param {Vector3} offset - The offset.
  8067. * @return {Sphere} A reference to this sphere.
  8068. */
  8069. translate( offset ) {
  8070. this.center.add( offset );
  8071. return this;
  8072. }
  8073. /**
  8074. * Expands the boundaries of this sphere to include the given point.
  8075. *
  8076. * @param {Vector3} point - The point to include.
  8077. * @return {Sphere} A reference to this sphere.
  8078. */
  8079. expandByPoint( point ) {
  8080. if ( this.isEmpty() ) {
  8081. this.center.copy( point );
  8082. this.radius = 0;
  8083. return this;
  8084. }
  8085. _v1$6.subVectors( point, this.center );
  8086. const lengthSq = _v1$6.lengthSq();
  8087. if ( lengthSq > ( this.radius * this.radius ) ) {
  8088. // calculate the minimal sphere
  8089. const length = Math.sqrt( lengthSq );
  8090. const delta = ( length - this.radius ) * 0.5;
  8091. this.center.addScaledVector( _v1$6, delta / length );
  8092. this.radius += delta;
  8093. }
  8094. return this;
  8095. }
  8096. /**
  8097. * Expands this sphere to enclose both the original sphere and the given sphere.
  8098. *
  8099. * @param {Sphere} sphere - The sphere to include.
  8100. * @return {Sphere} A reference to this sphere.
  8101. */
  8102. union( sphere ) {
  8103. if ( sphere.isEmpty() ) {
  8104. return this;
  8105. }
  8106. if ( this.isEmpty() ) {
  8107. this.copy( sphere );
  8108. return this;
  8109. }
  8110. if ( this.center.equals( sphere.center ) === true ) {
  8111. this.radius = Math.max( this.radius, sphere.radius );
  8112. } else {
  8113. _v2$3.subVectors( sphere.center, this.center ).setLength( sphere.radius );
  8114. this.expandByPoint( _v1$6.copy( sphere.center ).add( _v2$3 ) );
  8115. this.expandByPoint( _v1$6.copy( sphere.center ).sub( _v2$3 ) );
  8116. }
  8117. return this;
  8118. }
  8119. /**
  8120. * Returns `true` if this sphere is equal with the given one.
  8121. *
  8122. * @param {Sphere} sphere - The sphere to test for equality.
  8123. * @return {boolean} Whether this bounding sphere is equal with the given one.
  8124. */
  8125. equals( sphere ) {
  8126. return sphere.center.equals( this.center ) && ( sphere.radius === this.radius );
  8127. }
  8128. /**
  8129. * Returns a new sphere with copied values from this instance.
  8130. *
  8131. * @return {Sphere} A clone of this instance.
  8132. */
  8133. clone() {
  8134. return new this.constructor().copy( this );
  8135. }
  8136. /**
  8137. * Returns a serialized structure of the bounding sphere.
  8138. *
  8139. * @return {Object} Serialized structure with fields representing the object state.
  8140. */
  8141. toJSON() {
  8142. return {
  8143. radius: this.radius,
  8144. center: this.center.toArray()
  8145. };
  8146. }
  8147. /**
  8148. * Returns a serialized structure of the bounding sphere.
  8149. *
  8150. * @param {Object} json - The serialized json to set the sphere from.
  8151. * @return {Box3} A reference to this bounding sphere.
  8152. */
  8153. fromJSON( json ) {
  8154. this.radius = json.radius;
  8155. this.center.fromArray( json.center );
  8156. return this;
  8157. }
  8158. }
  8159. const _vector$a = /*@__PURE__*/ new Vector3();
  8160. const _segCenter = /*@__PURE__*/ new Vector3();
  8161. const _segDir = /*@__PURE__*/ new Vector3();
  8162. const _diff = /*@__PURE__*/ new Vector3();
  8163. const _edge1 = /*@__PURE__*/ new Vector3();
  8164. const _edge2 = /*@__PURE__*/ new Vector3();
  8165. const _normal$1 = /*@__PURE__*/ new Vector3();
  8166. /**
  8167. * A ray that emits from an origin in a certain direction. The class is used by
  8168. * {@link Raycaster} to assist with raycasting. Raycasting is used for
  8169. * mouse picking (working out what objects in the 3D space the mouse is over)
  8170. * amongst other things.
  8171. */
  8172. class Ray {
  8173. /**
  8174. * Constructs a new ray.
  8175. *
  8176. * @param {Vector3} [origin=(0,0,0)] - The origin of the ray.
  8177. * @param {Vector3} [direction=(0,0,-1)] - The (normalized) direction of the ray.
  8178. */
  8179. constructor( origin = new Vector3(), direction = new Vector3( 0, 0, -1 ) ) {
  8180. /**
  8181. * The origin of the ray.
  8182. *
  8183. * @type {Vector3}
  8184. */
  8185. this.origin = origin;
  8186. /**
  8187. * The (normalized) direction of the ray.
  8188. *
  8189. * @type {Vector3}
  8190. */
  8191. this.direction = direction;
  8192. }
  8193. /**
  8194. * Sets the ray's components by copying the given values.
  8195. *
  8196. * @param {Vector3} origin - The origin.
  8197. * @param {Vector3} direction - The direction.
  8198. * @return {Ray} A reference to this ray.
  8199. */
  8200. set( origin, direction ) {
  8201. this.origin.copy( origin );
  8202. this.direction.copy( direction );
  8203. return this;
  8204. }
  8205. /**
  8206. * Copies the values of the given ray to this instance.
  8207. *
  8208. * @param {Ray} ray - The ray to copy.
  8209. * @return {Ray} A reference to this ray.
  8210. */
  8211. copy( ray ) {
  8212. this.origin.copy( ray.origin );
  8213. this.direction.copy( ray.direction );
  8214. return this;
  8215. }
  8216. /**
  8217. * Returns a vector that is located at a given distance along this ray.
  8218. *
  8219. * @param {number} t - The distance along the ray to retrieve a position for.
  8220. * @param {Vector3} target - The target vector that is used to store the method's result.
  8221. * @return {Vector3} A position on the ray.
  8222. */
  8223. at( t, target ) {
  8224. return target.copy( this.origin ).addScaledVector( this.direction, t );
  8225. }
  8226. /**
  8227. * Adjusts the direction of the ray to point at the given vector in world space.
  8228. *
  8229. * @param {Vector3} v - The target position.
  8230. * @return {Ray} A reference to this ray.
  8231. */
  8232. lookAt( v ) {
  8233. this.direction.copy( v ).sub( this.origin ).normalize();
  8234. return this;
  8235. }
  8236. /**
  8237. * Shift the origin of this ray along its direction by the given distance.
  8238. *
  8239. * @param {number} t - The distance along the ray to interpolate.
  8240. * @return {Ray} A reference to this ray.
  8241. */
  8242. recast( t ) {
  8243. this.origin.copy( this.at( t, _vector$a ) );
  8244. return this;
  8245. }
  8246. /**
  8247. * Returns the point along this ray that is closest to the given point.
  8248. *
  8249. * @param {Vector3} point - A point in 3D space to get the closet location on the ray for.
  8250. * @param {Vector3} target - The target vector that is used to store the method's result.
  8251. * @return {Vector3} The closest point on this ray.
  8252. */
  8253. closestPointToPoint( point, target ) {
  8254. target.subVectors( point, this.origin );
  8255. const directionDistance = target.dot( this.direction );
  8256. if ( directionDistance < 0 ) {
  8257. return target.copy( this.origin );
  8258. }
  8259. return target.copy( this.origin ).addScaledVector( this.direction, directionDistance );
  8260. }
  8261. /**
  8262. * Returns the distance of the closest approach between this ray and the given point.
  8263. *
  8264. * @param {Vector3} point - A point in 3D space to compute the distance to.
  8265. * @return {number} The distance.
  8266. */
  8267. distanceToPoint( point ) {
  8268. return Math.sqrt( this.distanceSqToPoint( point ) );
  8269. }
  8270. /**
  8271. * Returns the squared distance of the closest approach between this ray and the given point.
  8272. *
  8273. * @param {Vector3} point - A point in 3D space to compute the distance to.
  8274. * @return {number} The squared distance.
  8275. */
  8276. distanceSqToPoint( point ) {
  8277. const directionDistance = _vector$a.subVectors( point, this.origin ).dot( this.direction );
  8278. // point behind the ray
  8279. if ( directionDistance < 0 ) {
  8280. return this.origin.distanceToSquared( point );
  8281. }
  8282. _vector$a.copy( this.origin ).addScaledVector( this.direction, directionDistance );
  8283. return _vector$a.distanceToSquared( point );
  8284. }
  8285. /**
  8286. * Returns the squared distance between this ray and the given line segment.
  8287. *
  8288. * @param {Vector3} v0 - The start point of the line segment.
  8289. * @param {Vector3} v1 - The end point of the line segment.
  8290. * @param {Vector3} [optionalPointOnRay] - When provided, it receives the point on this ray that is closest to the segment.
  8291. * @param {Vector3} [optionalPointOnSegment] - When provided, it receives the point on the line segment that is closest to this ray.
  8292. * @return {number} The squared distance.
  8293. */
  8294. distanceSqToSegment( v0, v1, optionalPointOnRay, optionalPointOnSegment ) {
  8295. // from https://github.com/pmjoniak/GeometricTools/blob/master/GTEngine/Include/Mathematics/GteDistRaySegment.h
  8296. // It returns the min distance between the ray and the segment
  8297. // defined by v0 and v1
  8298. // It can also set two optional targets :
  8299. // - The closest point on the ray
  8300. // - The closest point on the segment
  8301. _segCenter.copy( v0 ).add( v1 ).multiplyScalar( 0.5 );
  8302. _segDir.copy( v1 ).sub( v0 ).normalize();
  8303. _diff.copy( this.origin ).sub( _segCenter );
  8304. const segExtent = v0.distanceTo( v1 ) * 0.5;
  8305. const a01 = - this.direction.dot( _segDir );
  8306. const b0 = _diff.dot( this.direction );
  8307. const b1 = - _diff.dot( _segDir );
  8308. const c = _diff.lengthSq();
  8309. const det = Math.abs( 1 - a01 * a01 );
  8310. let s0, s1, sqrDist, extDet;
  8311. if ( det > 0 ) {
  8312. // The ray and segment are not parallel.
  8313. s0 = a01 * b1 - b0;
  8314. s1 = a01 * b0 - b1;
  8315. extDet = segExtent * det;
  8316. if ( s0 >= 0 ) {
  8317. if ( s1 >= - extDet ) {
  8318. if ( s1 <= extDet ) {
  8319. // region 0
  8320. // Minimum at interior points of ray and segment.
  8321. const invDet = 1 / det;
  8322. s0 *= invDet;
  8323. s1 *= invDet;
  8324. sqrDist = s0 * ( s0 + a01 * s1 + 2 * b0 ) + s1 * ( a01 * s0 + s1 + 2 * b1 ) + c;
  8325. } else {
  8326. // region 1
  8327. s1 = segExtent;
  8328. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  8329. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  8330. }
  8331. } else {
  8332. // region 5
  8333. s1 = - segExtent;
  8334. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  8335. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  8336. }
  8337. } else {
  8338. if ( s1 <= - extDet ) {
  8339. // region 4
  8340. s0 = Math.max( 0, - ( - a01 * segExtent + b0 ) );
  8341. s1 = ( s0 > 0 ) ? - segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  8342. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  8343. } else if ( s1 <= extDet ) {
  8344. // region 3
  8345. s0 = 0;
  8346. s1 = Math.min( Math.max( - segExtent, - b1 ), segExtent );
  8347. sqrDist = s1 * ( s1 + 2 * b1 ) + c;
  8348. } else {
  8349. // region 2
  8350. s0 = Math.max( 0, - ( a01 * segExtent + b0 ) );
  8351. s1 = ( s0 > 0 ) ? segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  8352. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  8353. }
  8354. }
  8355. } else {
  8356. // Ray and segment are parallel.
  8357. s1 = ( a01 > 0 ) ? - segExtent : segExtent;
  8358. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  8359. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  8360. }
  8361. if ( optionalPointOnRay ) {
  8362. optionalPointOnRay.copy( this.origin ).addScaledVector( this.direction, s0 );
  8363. }
  8364. if ( optionalPointOnSegment ) {
  8365. optionalPointOnSegment.copy( _segCenter ).addScaledVector( _segDir, s1 );
  8366. }
  8367. return sqrDist;
  8368. }
  8369. /**
  8370. * Intersects this ray with the given sphere, returning the intersection
  8371. * point or `null` if there is no intersection.
  8372. *
  8373. * @param {Sphere} sphere - The sphere to intersect.
  8374. * @param {Vector3} target - The target vector that is used to store the method's result.
  8375. * @return {?Vector3} The intersection point.
  8376. */
  8377. intersectSphere( sphere, target ) {
  8378. _vector$a.subVectors( sphere.center, this.origin );
  8379. const tca = _vector$a.dot( this.direction );
  8380. const d2 = _vector$a.dot( _vector$a ) - tca * tca;
  8381. const radius2 = sphere.radius * sphere.radius;
  8382. if ( d2 > radius2 ) return null;
  8383. const thc = Math.sqrt( radius2 - d2 );
  8384. // t0 = first intersect point - entrance on front of sphere
  8385. const t0 = tca - thc;
  8386. // t1 = second intersect point - exit point on back of sphere
  8387. const t1 = tca + thc;
  8388. // test to see if t1 is behind the ray - if so, return null
  8389. if ( t1 < 0 ) return null;
  8390. // test to see if t0 is behind the ray:
  8391. // if it is, the ray is inside the sphere, so return the second exit point scaled by t1,
  8392. // in order to always return an intersect point that is in front of the ray.
  8393. if ( t0 < 0 ) return this.at( t1, target );
  8394. // else t0 is in front of the ray, so return the first collision point scaled by t0
  8395. return this.at( t0, target );
  8396. }
  8397. /**
  8398. * Returns `true` if this ray intersects with the given sphere.
  8399. *
  8400. * @param {Sphere} sphere - The sphere to intersect.
  8401. * @return {boolean} Whether this ray intersects with the given sphere or not.
  8402. */
  8403. intersectsSphere( sphere ) {
  8404. return this.distanceSqToPoint( sphere.center ) <= ( sphere.radius * sphere.radius );
  8405. }
  8406. /**
  8407. * Computes the distance from the ray's origin to the given plane. Returns `null` if the ray
  8408. * does not intersect with the plane.
  8409. *
  8410. * @param {Plane} plane - The plane to compute the distance to.
  8411. * @return {?number} Whether this ray intersects with the given sphere or not.
  8412. */
  8413. distanceToPlane( plane ) {
  8414. const denominator = plane.normal.dot( this.direction );
  8415. if ( denominator === 0 ) {
  8416. // line is coplanar, return origin
  8417. if ( plane.distanceToPoint( this.origin ) === 0 ) {
  8418. return 0;
  8419. }
  8420. // Null is preferable to undefined since undefined means.... it is undefined
  8421. return null;
  8422. }
  8423. const t = - ( this.origin.dot( plane.normal ) + plane.constant ) / denominator;
  8424. // Return if the ray never intersects the plane
  8425. return t >= 0 ? t : null;
  8426. }
  8427. /**
  8428. * Intersects this ray with the given plane, returning the intersection
  8429. * point or `null` if there is no intersection.
  8430. *
  8431. * @param {Plane} plane - The plane to intersect.
  8432. * @param {Vector3} target - The target vector that is used to store the method's result.
  8433. * @return {?Vector3} The intersection point.
  8434. */
  8435. intersectPlane( plane, target ) {
  8436. const t = this.distanceToPlane( plane );
  8437. if ( t === null ) {
  8438. return null;
  8439. }
  8440. return this.at( t, target );
  8441. }
  8442. /**
  8443. * Returns `true` if this ray intersects with the given plane.
  8444. *
  8445. * @param {Plane} plane - The plane to intersect.
  8446. * @return {boolean} Whether this ray intersects with the given plane or not.
  8447. */
  8448. intersectsPlane( plane ) {
  8449. // check if the ray lies on the plane first
  8450. const distToPoint = plane.distanceToPoint( this.origin );
  8451. if ( distToPoint === 0 ) {
  8452. return true;
  8453. }
  8454. const denominator = plane.normal.dot( this.direction );
  8455. if ( denominator * distToPoint < 0 ) {
  8456. return true;
  8457. }
  8458. // ray origin is behind the plane (and is pointing behind it)
  8459. return false;
  8460. }
  8461. /**
  8462. * Intersects this ray with the given bounding box, returning the intersection
  8463. * point or `null` if there is no intersection.
  8464. *
  8465. * @param {Box3} box - The box to intersect.
  8466. * @param {Vector3} target - The target vector that is used to store the method's result.
  8467. * @return {?Vector3} The intersection point.
  8468. */
  8469. intersectBox( box, target ) {
  8470. let tmin, tmax, tymin, tymax, tzmin, tzmax;
  8471. const invdirx = 1 / this.direction.x,
  8472. invdiry = 1 / this.direction.y,
  8473. invdirz = 1 / this.direction.z;
  8474. const origin = this.origin;
  8475. if ( invdirx >= 0 ) {
  8476. tmin = ( box.min.x - origin.x ) * invdirx;
  8477. tmax = ( box.max.x - origin.x ) * invdirx;
  8478. } else {
  8479. tmin = ( box.max.x - origin.x ) * invdirx;
  8480. tmax = ( box.min.x - origin.x ) * invdirx;
  8481. }
  8482. if ( invdiry >= 0 ) {
  8483. tymin = ( box.min.y - origin.y ) * invdiry;
  8484. tymax = ( box.max.y - origin.y ) * invdiry;
  8485. } else {
  8486. tymin = ( box.max.y - origin.y ) * invdiry;
  8487. tymax = ( box.min.y - origin.y ) * invdiry;
  8488. }
  8489. if ( ( tmin > tymax ) || ( tymin > tmax ) ) return null;
  8490. if ( tymin > tmin || isNaN( tmin ) ) tmin = tymin;
  8491. if ( tymax < tmax || isNaN( tmax ) ) tmax = tymax;
  8492. if ( invdirz >= 0 ) {
  8493. tzmin = ( box.min.z - origin.z ) * invdirz;
  8494. tzmax = ( box.max.z - origin.z ) * invdirz;
  8495. } else {
  8496. tzmin = ( box.max.z - origin.z ) * invdirz;
  8497. tzmax = ( box.min.z - origin.z ) * invdirz;
  8498. }
  8499. if ( ( tmin > tzmax ) || ( tzmin > tmax ) ) return null;
  8500. if ( tzmin > tmin || tmin !== tmin ) tmin = tzmin;
  8501. if ( tzmax < tmax || tmax !== tmax ) tmax = tzmax;
  8502. //return point closest to the ray (positive side)
  8503. if ( tmax < 0 ) return null;
  8504. return this.at( tmin >= 0 ? tmin : tmax, target );
  8505. }
  8506. /**
  8507. * Returns `true` if this ray intersects with the given box.
  8508. *
  8509. * @param {Box3} box - The box to intersect.
  8510. * @return {boolean} Whether this ray intersects with the given box or not.
  8511. */
  8512. intersectsBox( box ) {
  8513. return this.intersectBox( box, _vector$a ) !== null;
  8514. }
  8515. /**
  8516. * Intersects this ray with the given triangle, returning the intersection
  8517. * point or `null` if there is no intersection.
  8518. *
  8519. * @param {Vector3} a - The first vertex of the triangle.
  8520. * @param {Vector3} b - The second vertex of the triangle.
  8521. * @param {Vector3} c - The third vertex of the triangle.
  8522. * @param {boolean} backfaceCulling - Whether to use backface culling or not.
  8523. * @param {Vector3} target - The target vector that is used to store the method's result.
  8524. * @return {?Vector3} The intersection point.
  8525. */
  8526. intersectTriangle( a, b, c, backfaceCulling, target ) {
  8527. // Compute the offset origin, edges, and normal.
  8528. // from https://github.com/pmjoniak/GeometricTools/blob/master/GTEngine/Include/Mathematics/GteIntrRay3Triangle3.h
  8529. _edge1.subVectors( b, a );
  8530. _edge2.subVectors( c, a );
  8531. _normal$1.crossVectors( _edge1, _edge2 );
  8532. // Solve Q + t*D = b1*E1 + b2*E2 (Q = kDiff, D = ray direction,
  8533. // E1 = kEdge1, E2 = kEdge2, N = Cross(E1,E2)) by
  8534. // |Dot(D,N)|*b1 = sign(Dot(D,N))*Dot(D,Cross(Q,E2))
  8535. // |Dot(D,N)|*b2 = sign(Dot(D,N))*Dot(D,Cross(E1,Q))
  8536. // |Dot(D,N)|*t = -sign(Dot(D,N))*Dot(Q,N)
  8537. let DdN = this.direction.dot( _normal$1 );
  8538. let sign;
  8539. if ( DdN > 0 ) {
  8540. if ( backfaceCulling ) return null;
  8541. sign = 1;
  8542. } else if ( DdN < 0 ) {
  8543. sign = -1;
  8544. DdN = - DdN;
  8545. } else {
  8546. return null;
  8547. }
  8548. _diff.subVectors( this.origin, a );
  8549. const DdQxE2 = sign * this.direction.dot( _edge2.crossVectors( _diff, _edge2 ) );
  8550. // b1 < 0, no intersection
  8551. if ( DdQxE2 < 0 ) {
  8552. return null;
  8553. }
  8554. const DdE1xQ = sign * this.direction.dot( _edge1.cross( _diff ) );
  8555. // b2 < 0, no intersection
  8556. if ( DdE1xQ < 0 ) {
  8557. return null;
  8558. }
  8559. // b1+b2 > 1, no intersection
  8560. if ( DdQxE2 + DdE1xQ > DdN ) {
  8561. return null;
  8562. }
  8563. // Line intersects triangle, check if ray does.
  8564. const QdN = - sign * _diff.dot( _normal$1 );
  8565. // t < 0, no intersection
  8566. if ( QdN < 0 ) {
  8567. return null;
  8568. }
  8569. // Ray intersects triangle.
  8570. return this.at( QdN / DdN, target );
  8571. }
  8572. /**
  8573. * Transforms this ray with the given 4x4 transformation matrix.
  8574. *
  8575. * @param {Matrix4} matrix4 - The transformation matrix.
  8576. * @return {Ray} A reference to this ray.
  8577. */
  8578. applyMatrix4( matrix4 ) {
  8579. this.origin.applyMatrix4( matrix4 );
  8580. this.direction.transformDirection( matrix4 );
  8581. return this;
  8582. }
  8583. /**
  8584. * Returns `true` if this ray is equal with the given one.
  8585. *
  8586. * @param {Ray} ray - The ray to test for equality.
  8587. * @return {boolean} Whether this ray is equal with the given one.
  8588. */
  8589. equals( ray ) {
  8590. return ray.origin.equals( this.origin ) && ray.direction.equals( this.direction );
  8591. }
  8592. /**
  8593. * Returns a new ray with copied values from this instance.
  8594. *
  8595. * @return {Ray} A clone of this instance.
  8596. */
  8597. clone() {
  8598. return new this.constructor().copy( this );
  8599. }
  8600. }
  8601. /**
  8602. * Represents a 4x4 matrix.
  8603. *
  8604. * The most common use of a 4x4 matrix in 3D computer graphics is as a transformation matrix.
  8605. * 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}
  8606. *
  8607. * This allows a 3D vector representing a point in 3D space to undergo
  8608. * transformations such as translation, rotation, shear, scale, reflection,
  8609. * orthogonal or perspective projection and so on, by being multiplied by the
  8610. * matrix. This is known as `applying` the matrix to the vector.
  8611. *
  8612. * A Note on Row-Major and Column-Major Ordering:
  8613. *
  8614. * The constructor and {@link Matrix3#set} method take arguments in
  8615. * [row-major]{@link https://en.wikipedia.org/wiki/Row-_and_column-major_order#Column-major_order}
  8616. * order, while internally they are stored in the {@link Matrix3#elements} array in column-major order.
  8617. * This means that calling:
  8618. * ```js
  8619. * const m = new THREE.Matrix4();
  8620. * m.set( 11, 12, 13, 14,
  8621. * 21, 22, 23, 24,
  8622. * 31, 32, 33, 34,
  8623. * 41, 42, 43, 44 );
  8624. * ```
  8625. * will result in the elements array containing:
  8626. * ```js
  8627. * m.elements = [ 11, 21, 31, 41,
  8628. * 12, 22, 32, 42,
  8629. * 13, 23, 33, 43,
  8630. * 14, 24, 34, 44 ];
  8631. * ```
  8632. * and internally all calculations are performed using column-major ordering.
  8633. * However, as the actual ordering makes no difference mathematically and
  8634. * most people are used to thinking about matrices in row-major order, the
  8635. * three.js documentation shows matrices in row-major order. Just bear in
  8636. * mind that if you are reading the source code, you'll have to take the
  8637. * transpose of any matrices outlined here to make sense of the calculations.
  8638. */
  8639. class Matrix4 {
  8640. /**
  8641. * Constructs a new 4x4 matrix. The arguments are supposed to be
  8642. * in row-major order. If no arguments are provided, the constructor
  8643. * initializes the matrix as an identity matrix.
  8644. *
  8645. * @param {number} [n11] - 1-1 matrix element.
  8646. * @param {number} [n12] - 1-2 matrix element.
  8647. * @param {number} [n13] - 1-3 matrix element.
  8648. * @param {number} [n14] - 1-4 matrix element.
  8649. * @param {number} [n21] - 2-1 matrix element.
  8650. * @param {number} [n22] - 2-2 matrix element.
  8651. * @param {number} [n23] - 2-3 matrix element.
  8652. * @param {number} [n24] - 2-4 matrix element.
  8653. * @param {number} [n31] - 3-1 matrix element.
  8654. * @param {number} [n32] - 3-2 matrix element.
  8655. * @param {number} [n33] - 3-3 matrix element.
  8656. * @param {number} [n34] - 3-4 matrix element.
  8657. * @param {number} [n41] - 4-1 matrix element.
  8658. * @param {number} [n42] - 4-2 matrix element.
  8659. * @param {number} [n43] - 4-3 matrix element.
  8660. * @param {number} [n44] - 4-4 matrix element.
  8661. */
  8662. constructor( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  8663. /**
  8664. * This flag can be used for type testing.
  8665. *
  8666. * @type {boolean}
  8667. * @readonly
  8668. * @default true
  8669. */
  8670. Matrix4.prototype.isMatrix4 = true;
  8671. /**
  8672. * A column-major list of matrix values.
  8673. *
  8674. * @type {Array<number>}
  8675. */
  8676. this.elements = [
  8677. 1, 0, 0, 0,
  8678. 0, 1, 0, 0,
  8679. 0, 0, 1, 0,
  8680. 0, 0, 0, 1
  8681. ];
  8682. if ( n11 !== undefined ) {
  8683. this.set( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 );
  8684. }
  8685. }
  8686. /**
  8687. * Sets the elements of the matrix.The arguments are supposed to be
  8688. * in row-major order.
  8689. *
  8690. * @param {number} [n11] - 1-1 matrix element.
  8691. * @param {number} [n12] - 1-2 matrix element.
  8692. * @param {number} [n13] - 1-3 matrix element.
  8693. * @param {number} [n14] - 1-4 matrix element.
  8694. * @param {number} [n21] - 2-1 matrix element.
  8695. * @param {number} [n22] - 2-2 matrix element.
  8696. * @param {number} [n23] - 2-3 matrix element.
  8697. * @param {number} [n24] - 2-4 matrix element.
  8698. * @param {number} [n31] - 3-1 matrix element.
  8699. * @param {number} [n32] - 3-2 matrix element.
  8700. * @param {number} [n33] - 3-3 matrix element.
  8701. * @param {number} [n34] - 3-4 matrix element.
  8702. * @param {number} [n41] - 4-1 matrix element.
  8703. * @param {number} [n42] - 4-2 matrix element.
  8704. * @param {number} [n43] - 4-3 matrix element.
  8705. * @param {number} [n44] - 4-4 matrix element.
  8706. * @return {Matrix4} A reference to this matrix.
  8707. */
  8708. set( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  8709. const te = this.elements;
  8710. te[ 0 ] = n11; te[ 4 ] = n12; te[ 8 ] = n13; te[ 12 ] = n14;
  8711. te[ 1 ] = n21; te[ 5 ] = n22; te[ 9 ] = n23; te[ 13 ] = n24;
  8712. te[ 2 ] = n31; te[ 6 ] = n32; te[ 10 ] = n33; te[ 14 ] = n34;
  8713. te[ 3 ] = n41; te[ 7 ] = n42; te[ 11 ] = n43; te[ 15 ] = n44;
  8714. return this;
  8715. }
  8716. /**
  8717. * Sets this matrix to the 4x4 identity matrix.
  8718. *
  8719. * @return {Matrix4} A reference to this matrix.
  8720. */
  8721. identity() {
  8722. this.set(
  8723. 1, 0, 0, 0,
  8724. 0, 1, 0, 0,
  8725. 0, 0, 1, 0,
  8726. 0, 0, 0, 1
  8727. );
  8728. return this;
  8729. }
  8730. /**
  8731. * Returns a matrix with copied values from this instance.
  8732. *
  8733. * @return {Matrix4} A clone of this instance.
  8734. */
  8735. clone() {
  8736. return new Matrix4().fromArray( this.elements );
  8737. }
  8738. /**
  8739. * Copies the values of the given matrix to this instance.
  8740. *
  8741. * @param {Matrix4} m - The matrix to copy.
  8742. * @return {Matrix4} A reference to this matrix.
  8743. */
  8744. copy( m ) {
  8745. const te = this.elements;
  8746. const me = m.elements;
  8747. te[ 0 ] = me[ 0 ]; te[ 1 ] = me[ 1 ]; te[ 2 ] = me[ 2 ]; te[ 3 ] = me[ 3 ];
  8748. te[ 4 ] = me[ 4 ]; te[ 5 ] = me[ 5 ]; te[ 6 ] = me[ 6 ]; te[ 7 ] = me[ 7 ];
  8749. te[ 8 ] = me[ 8 ]; te[ 9 ] = me[ 9 ]; te[ 10 ] = me[ 10 ]; te[ 11 ] = me[ 11 ];
  8750. te[ 12 ] = me[ 12 ]; te[ 13 ] = me[ 13 ]; te[ 14 ] = me[ 14 ]; te[ 15 ] = me[ 15 ];
  8751. return this;
  8752. }
  8753. /**
  8754. * Copies the translation component of the given matrix
  8755. * into this matrix's translation component.
  8756. *
  8757. * @param {Matrix4} m - The matrix to copy the translation component.
  8758. * @return {Matrix4} A reference to this matrix.
  8759. */
  8760. copyPosition( m ) {
  8761. const te = this.elements, me = m.elements;
  8762. te[ 12 ] = me[ 12 ];
  8763. te[ 13 ] = me[ 13 ];
  8764. te[ 14 ] = me[ 14 ];
  8765. return this;
  8766. }
  8767. /**
  8768. * Set the upper 3x3 elements of this matrix to the values of given 3x3 matrix.
  8769. *
  8770. * @param {Matrix3} m - The 3x3 matrix.
  8771. * @return {Matrix4} A reference to this matrix.
  8772. */
  8773. setFromMatrix3( m ) {
  8774. const me = m.elements;
  8775. this.set(
  8776. me[ 0 ], me[ 3 ], me[ 6 ], 0,
  8777. me[ 1 ], me[ 4 ], me[ 7 ], 0,
  8778. me[ 2 ], me[ 5 ], me[ 8 ], 0,
  8779. 0, 0, 0, 1
  8780. );
  8781. return this;
  8782. }
  8783. /**
  8784. * Extracts the basis of this matrix into the three axis vectors provided.
  8785. *
  8786. * @param {Vector3} xAxis - The basis's x axis.
  8787. * @param {Vector3} yAxis - The basis's y axis.
  8788. * @param {Vector3} zAxis - The basis's z axis.
  8789. * @return {Matrix4} A reference to this matrix.
  8790. */
  8791. extractBasis( xAxis, yAxis, zAxis ) {
  8792. xAxis.setFromMatrixColumn( this, 0 );
  8793. yAxis.setFromMatrixColumn( this, 1 );
  8794. zAxis.setFromMatrixColumn( this, 2 );
  8795. return this;
  8796. }
  8797. /**
  8798. * Sets the given basis vectors to this matrix.
  8799. *
  8800. * @param {Vector3} xAxis - The basis's x axis.
  8801. * @param {Vector3} yAxis - The basis's y axis.
  8802. * @param {Vector3} zAxis - The basis's z axis.
  8803. * @return {Matrix4} A reference to this matrix.
  8804. */
  8805. makeBasis( xAxis, yAxis, zAxis ) {
  8806. this.set(
  8807. xAxis.x, yAxis.x, zAxis.x, 0,
  8808. xAxis.y, yAxis.y, zAxis.y, 0,
  8809. xAxis.z, yAxis.z, zAxis.z, 0,
  8810. 0, 0, 0, 1
  8811. );
  8812. return this;
  8813. }
  8814. /**
  8815. * Extracts the rotation component of the given matrix
  8816. * into this matrix's rotation component.
  8817. *
  8818. * Note: This method does not support reflection matrices.
  8819. *
  8820. * @param {Matrix4} m - The matrix.
  8821. * @return {Matrix4} A reference to this matrix.
  8822. */
  8823. extractRotation( m ) {
  8824. const te = this.elements;
  8825. const me = m.elements;
  8826. const scaleX = 1 / _v1$5.setFromMatrixColumn( m, 0 ).length();
  8827. const scaleY = 1 / _v1$5.setFromMatrixColumn( m, 1 ).length();
  8828. const scaleZ = 1 / _v1$5.setFromMatrixColumn( m, 2 ).length();
  8829. te[ 0 ] = me[ 0 ] * scaleX;
  8830. te[ 1 ] = me[ 1 ] * scaleX;
  8831. te[ 2 ] = me[ 2 ] * scaleX;
  8832. te[ 3 ] = 0;
  8833. te[ 4 ] = me[ 4 ] * scaleY;
  8834. te[ 5 ] = me[ 5 ] * scaleY;
  8835. te[ 6 ] = me[ 6 ] * scaleY;
  8836. te[ 7 ] = 0;
  8837. te[ 8 ] = me[ 8 ] * scaleZ;
  8838. te[ 9 ] = me[ 9 ] * scaleZ;
  8839. te[ 10 ] = me[ 10 ] * scaleZ;
  8840. te[ 11 ] = 0;
  8841. te[ 12 ] = 0;
  8842. te[ 13 ] = 0;
  8843. te[ 14 ] = 0;
  8844. te[ 15 ] = 1;
  8845. return this;
  8846. }
  8847. /**
  8848. * Sets the rotation component (the upper left 3x3 matrix) of this matrix to
  8849. * the rotation specified by the given Euler angles. The rest of
  8850. * the matrix is set to the identity. Depending on the {@link Euler#order},
  8851. * there are six possible outcomes. See [this page]{@link https://en.wikipedia.org/wiki/Euler_angles#Rotation_matrix}
  8852. * for a complete list.
  8853. *
  8854. * @param {Euler} euler - The Euler angles.
  8855. * @return {Matrix4} A reference to this matrix.
  8856. */
  8857. makeRotationFromEuler( euler ) {
  8858. const te = this.elements;
  8859. const x = euler.x, y = euler.y, z = euler.z;
  8860. const a = Math.cos( x ), b = Math.sin( x );
  8861. const c = Math.cos( y ), d = Math.sin( y );
  8862. const e = Math.cos( z ), f = Math.sin( z );
  8863. if ( euler.order === 'XYZ' ) {
  8864. const ae = a * e, af = a * f, be = b * e, bf = b * f;
  8865. te[ 0 ] = c * e;
  8866. te[ 4 ] = - c * f;
  8867. te[ 8 ] = d;
  8868. te[ 1 ] = af + be * d;
  8869. te[ 5 ] = ae - bf * d;
  8870. te[ 9 ] = - b * c;
  8871. te[ 2 ] = bf - ae * d;
  8872. te[ 6 ] = be + af * d;
  8873. te[ 10 ] = a * c;
  8874. } else if ( euler.order === 'YXZ' ) {
  8875. const ce = c * e, cf = c * f, de = d * e, df = d * f;
  8876. te[ 0 ] = ce + df * b;
  8877. te[ 4 ] = de * b - cf;
  8878. te[ 8 ] = a * d;
  8879. te[ 1 ] = a * f;
  8880. te[ 5 ] = a * e;
  8881. te[ 9 ] = - b;
  8882. te[ 2 ] = cf * b - de;
  8883. te[ 6 ] = df + ce * b;
  8884. te[ 10 ] = a * c;
  8885. } else if ( euler.order === 'ZXY' ) {
  8886. const ce = c * e, cf = c * f, de = d * e, df = d * f;
  8887. te[ 0 ] = ce - df * b;
  8888. te[ 4 ] = - a * f;
  8889. te[ 8 ] = de + cf * b;
  8890. te[ 1 ] = cf + de * b;
  8891. te[ 5 ] = a * e;
  8892. te[ 9 ] = df - ce * b;
  8893. te[ 2 ] = - a * d;
  8894. te[ 6 ] = b;
  8895. te[ 10 ] = a * c;
  8896. } else if ( euler.order === 'ZYX' ) {
  8897. const ae = a * e, af = a * f, be = b * e, bf = b * f;
  8898. te[ 0 ] = c * e;
  8899. te[ 4 ] = be * d - af;
  8900. te[ 8 ] = ae * d + bf;
  8901. te[ 1 ] = c * f;
  8902. te[ 5 ] = bf * d + ae;
  8903. te[ 9 ] = af * d - be;
  8904. te[ 2 ] = - d;
  8905. te[ 6 ] = b * c;
  8906. te[ 10 ] = a * c;
  8907. } else if ( euler.order === 'YZX' ) {
  8908. const ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  8909. te[ 0 ] = c * e;
  8910. te[ 4 ] = bd - ac * f;
  8911. te[ 8 ] = bc * f + ad;
  8912. te[ 1 ] = f;
  8913. te[ 5 ] = a * e;
  8914. te[ 9 ] = - b * e;
  8915. te[ 2 ] = - d * e;
  8916. te[ 6 ] = ad * f + bc;
  8917. te[ 10 ] = ac - bd * f;
  8918. } else if ( euler.order === 'XZY' ) {
  8919. const ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  8920. te[ 0 ] = c * e;
  8921. te[ 4 ] = - f;
  8922. te[ 8 ] = d * e;
  8923. te[ 1 ] = ac * f + bd;
  8924. te[ 5 ] = a * e;
  8925. te[ 9 ] = ad * f - bc;
  8926. te[ 2 ] = bc * f - ad;
  8927. te[ 6 ] = b * e;
  8928. te[ 10 ] = bd * f + ac;
  8929. }
  8930. // bottom row
  8931. te[ 3 ] = 0;
  8932. te[ 7 ] = 0;
  8933. te[ 11 ] = 0;
  8934. // last column
  8935. te[ 12 ] = 0;
  8936. te[ 13 ] = 0;
  8937. te[ 14 ] = 0;
  8938. te[ 15 ] = 1;
  8939. return this;
  8940. }
  8941. /**
  8942. * Sets the rotation component of this matrix to the rotation specified by
  8943. * the given Quaternion as outlined [here]{@link https://en.wikipedia.org/wiki/Rotation_matrix#Quaternion}
  8944. * The rest of the matrix is set to the identity.
  8945. *
  8946. * @param {Quaternion} q - The Quaternion.
  8947. * @return {Matrix4} A reference to this matrix.
  8948. */
  8949. makeRotationFromQuaternion( q ) {
  8950. return this.compose( _zero, q, _one );
  8951. }
  8952. /**
  8953. * Sets the rotation component of the transformation matrix, looking from `eye` towards
  8954. * `target`, and oriented by the up-direction.
  8955. *
  8956. * @param {Vector3} eye - The eye vector.
  8957. * @param {Vector3} target - The target vector.
  8958. * @param {Vector3} up - The up vector.
  8959. * @return {Matrix4} A reference to this matrix.
  8960. */
  8961. lookAt( eye, target, up ) {
  8962. const te = this.elements;
  8963. _z.subVectors( eye, target );
  8964. if ( _z.lengthSq() === 0 ) {
  8965. // eye and target are in the same position
  8966. _z.z = 1;
  8967. }
  8968. _z.normalize();
  8969. _x.crossVectors( up, _z );
  8970. if ( _x.lengthSq() === 0 ) {
  8971. // up and z are parallel
  8972. if ( Math.abs( up.z ) === 1 ) {
  8973. _z.x += 0.0001;
  8974. } else {
  8975. _z.z += 0.0001;
  8976. }
  8977. _z.normalize();
  8978. _x.crossVectors( up, _z );
  8979. }
  8980. _x.normalize();
  8981. _y.crossVectors( _z, _x );
  8982. te[ 0 ] = _x.x; te[ 4 ] = _y.x; te[ 8 ] = _z.x;
  8983. te[ 1 ] = _x.y; te[ 5 ] = _y.y; te[ 9 ] = _z.y;
  8984. te[ 2 ] = _x.z; te[ 6 ] = _y.z; te[ 10 ] = _z.z;
  8985. return this;
  8986. }
  8987. /**
  8988. * Post-multiplies this matrix by the given 4x4 matrix.
  8989. *
  8990. * @param {Matrix4} m - The matrix to multiply with.
  8991. * @return {Matrix4} A reference to this matrix.
  8992. */
  8993. multiply( m ) {
  8994. return this.multiplyMatrices( this, m );
  8995. }
  8996. /**
  8997. * Pre-multiplies this matrix by the given 4x4 matrix.
  8998. *
  8999. * @param {Matrix4} m - The matrix to multiply with.
  9000. * @return {Matrix4} A reference to this matrix.
  9001. */
  9002. premultiply( m ) {
  9003. return this.multiplyMatrices( m, this );
  9004. }
  9005. /**
  9006. * Multiples the given 4x4 matrices and stores the result
  9007. * in this matrix.
  9008. *
  9009. * @param {Matrix4} a - The first matrix.
  9010. * @param {Matrix4} b - The second matrix.
  9011. * @return {Matrix4} A reference to this matrix.
  9012. */
  9013. multiplyMatrices( a, b ) {
  9014. const ae = a.elements;
  9015. const be = b.elements;
  9016. const te = this.elements;
  9017. const a11 = ae[ 0 ], a12 = ae[ 4 ], a13 = ae[ 8 ], a14 = ae[ 12 ];
  9018. const a21 = ae[ 1 ], a22 = ae[ 5 ], a23 = ae[ 9 ], a24 = ae[ 13 ];
  9019. const a31 = ae[ 2 ], a32 = ae[ 6 ], a33 = ae[ 10 ], a34 = ae[ 14 ];
  9020. const a41 = ae[ 3 ], a42 = ae[ 7 ], a43 = ae[ 11 ], a44 = ae[ 15 ];
  9021. const b11 = be[ 0 ], b12 = be[ 4 ], b13 = be[ 8 ], b14 = be[ 12 ];
  9022. const b21 = be[ 1 ], b22 = be[ 5 ], b23 = be[ 9 ], b24 = be[ 13 ];
  9023. const b31 = be[ 2 ], b32 = be[ 6 ], b33 = be[ 10 ], b34 = be[ 14 ];
  9024. const b41 = be[ 3 ], b42 = be[ 7 ], b43 = be[ 11 ], b44 = be[ 15 ];
  9025. te[ 0 ] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41;
  9026. te[ 4 ] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42;
  9027. te[ 8 ] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43;
  9028. te[ 12 ] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44;
  9029. te[ 1 ] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41;
  9030. te[ 5 ] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42;
  9031. te[ 9 ] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43;
  9032. te[ 13 ] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44;
  9033. te[ 2 ] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41;
  9034. te[ 6 ] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42;
  9035. te[ 10 ] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43;
  9036. te[ 14 ] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44;
  9037. te[ 3 ] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41;
  9038. te[ 7 ] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42;
  9039. te[ 11 ] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43;
  9040. te[ 15 ] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44;
  9041. return this;
  9042. }
  9043. /**
  9044. * Multiplies every component of the matrix by the given scalar.
  9045. *
  9046. * @param {number} s - The scalar.
  9047. * @return {Matrix4} A reference to this matrix.
  9048. */
  9049. multiplyScalar( s ) {
  9050. const te = this.elements;
  9051. te[ 0 ] *= s; te[ 4 ] *= s; te[ 8 ] *= s; te[ 12 ] *= s;
  9052. te[ 1 ] *= s; te[ 5 ] *= s; te[ 9 ] *= s; te[ 13 ] *= s;
  9053. te[ 2 ] *= s; te[ 6 ] *= s; te[ 10 ] *= s; te[ 14 ] *= s;
  9054. te[ 3 ] *= s; te[ 7 ] *= s; te[ 11 ] *= s; te[ 15 ] *= s;
  9055. return this;
  9056. }
  9057. /**
  9058. * Computes and returns the determinant of this matrix.
  9059. *
  9060. * Based on the method outlined [here]{@link http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.html}.
  9061. *
  9062. * @return {number} The determinant.
  9063. */
  9064. determinant() {
  9065. const te = this.elements;
  9066. const n11 = te[ 0 ], n12 = te[ 4 ], n13 = te[ 8 ], n14 = te[ 12 ];
  9067. const n21 = te[ 1 ], n22 = te[ 5 ], n23 = te[ 9 ], n24 = te[ 13 ];
  9068. const n31 = te[ 2 ], n32 = te[ 6 ], n33 = te[ 10 ], n34 = te[ 14 ];
  9069. const n41 = te[ 3 ], n42 = te[ 7 ], n43 = te[ 11 ], n44 = te[ 15 ];
  9070. //TODO: make this more efficient
  9071. return (
  9072. n41 * (
  9073. + n14 * n23 * n32
  9074. - n13 * n24 * n32
  9075. - n14 * n22 * n33
  9076. + n12 * n24 * n33
  9077. + n13 * n22 * n34
  9078. - n12 * n23 * n34
  9079. ) +
  9080. n42 * (
  9081. + n11 * n23 * n34
  9082. - n11 * n24 * n33
  9083. + n14 * n21 * n33
  9084. - n13 * n21 * n34
  9085. + n13 * n24 * n31
  9086. - n14 * n23 * n31
  9087. ) +
  9088. n43 * (
  9089. + n11 * n24 * n32
  9090. - n11 * n22 * n34
  9091. - n14 * n21 * n32
  9092. + n12 * n21 * n34
  9093. + n14 * n22 * n31
  9094. - n12 * n24 * n31
  9095. ) +
  9096. n44 * (
  9097. - n13 * n22 * n31
  9098. - n11 * n23 * n32
  9099. + n11 * n22 * n33
  9100. + n13 * n21 * n32
  9101. - n12 * n21 * n33
  9102. + n12 * n23 * n31
  9103. )
  9104. );
  9105. }
  9106. /**
  9107. * Transposes this matrix in place.
  9108. *
  9109. * @return {Matrix4} A reference to this matrix.
  9110. */
  9111. transpose() {
  9112. const te = this.elements;
  9113. let tmp;
  9114. tmp = te[ 1 ]; te[ 1 ] = te[ 4 ]; te[ 4 ] = tmp;
  9115. tmp = te[ 2 ]; te[ 2 ] = te[ 8 ]; te[ 8 ] = tmp;
  9116. tmp = te[ 6 ]; te[ 6 ] = te[ 9 ]; te[ 9 ] = tmp;
  9117. tmp = te[ 3 ]; te[ 3 ] = te[ 12 ]; te[ 12 ] = tmp;
  9118. tmp = te[ 7 ]; te[ 7 ] = te[ 13 ]; te[ 13 ] = tmp;
  9119. tmp = te[ 11 ]; te[ 11 ] = te[ 14 ]; te[ 14 ] = tmp;
  9120. return this;
  9121. }
  9122. /**
  9123. * Sets the position component for this matrix from the given vector,
  9124. * without affecting the rest of the matrix.
  9125. *
  9126. * @param {number|Vector3} x - The x component of the vector or alternatively the vector object.
  9127. * @param {number} y - The y component of the vector.
  9128. * @param {number} z - The z component of the vector.
  9129. * @return {Matrix4} A reference to this matrix.
  9130. */
  9131. setPosition( x, y, z ) {
  9132. const te = this.elements;
  9133. if ( x.isVector3 ) {
  9134. te[ 12 ] = x.x;
  9135. te[ 13 ] = x.y;
  9136. te[ 14 ] = x.z;
  9137. } else {
  9138. te[ 12 ] = x;
  9139. te[ 13 ] = y;
  9140. te[ 14 ] = z;
  9141. }
  9142. return this;
  9143. }
  9144. /**
  9145. * Inverts this matrix, using the [analytic method]{@link https://en.wikipedia.org/wiki/Invertible_matrix#Analytic_solution}.
  9146. * You can not invert with a determinant of zero. If you attempt this, the method produces
  9147. * a zero matrix instead.
  9148. *
  9149. * @return {Matrix4} A reference to this matrix.
  9150. */
  9151. invert() {
  9152. // based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm
  9153. const te = this.elements,
  9154. n11 = te[ 0 ], n21 = te[ 1 ], n31 = te[ 2 ], n41 = te[ 3 ],
  9155. n12 = te[ 4 ], n22 = te[ 5 ], n32 = te[ 6 ], n42 = te[ 7 ],
  9156. n13 = te[ 8 ], n23 = te[ 9 ], n33 = te[ 10 ], n43 = te[ 11 ],
  9157. n14 = te[ 12 ], n24 = te[ 13 ], n34 = te[ 14 ], n44 = te[ 15 ],
  9158. t11 = n23 * n34 * n42 - n24 * n33 * n42 + n24 * n32 * n43 - n22 * n34 * n43 - n23 * n32 * n44 + n22 * n33 * n44,
  9159. t12 = n14 * n33 * n42 - n13 * n34 * n42 - n14 * n32 * n43 + n12 * n34 * n43 + n13 * n32 * n44 - n12 * n33 * n44,
  9160. t13 = n13 * n24 * n42 - n14 * n23 * n42 + n14 * n22 * n43 - n12 * n24 * n43 - n13 * n22 * n44 + n12 * n23 * n44,
  9161. t14 = n14 * n23 * n32 - n13 * n24 * n32 - n14 * n22 * n33 + n12 * n24 * n33 + n13 * n22 * n34 - n12 * n23 * n34;
  9162. const det = n11 * t11 + n21 * t12 + n31 * t13 + n41 * t14;
  9163. if ( det === 0 ) return this.set( 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 );
  9164. const detInv = 1 / det;
  9165. te[ 0 ] = t11 * detInv;
  9166. te[ 1 ] = ( n24 * n33 * n41 - n23 * n34 * n41 - n24 * n31 * n43 + n21 * n34 * n43 + n23 * n31 * n44 - n21 * n33 * n44 ) * detInv;
  9167. te[ 2 ] = ( n22 * n34 * n41 - n24 * n32 * n41 + n24 * n31 * n42 - n21 * n34 * n42 - n22 * n31 * n44 + n21 * n32 * n44 ) * detInv;
  9168. te[ 3 ] = ( n23 * n32 * n41 - n22 * n33 * n41 - n23 * n31 * n42 + n21 * n33 * n42 + n22 * n31 * n43 - n21 * n32 * n43 ) * detInv;
  9169. te[ 4 ] = t12 * detInv;
  9170. te[ 5 ] = ( n13 * n34 * n41 - n14 * n33 * n41 + n14 * n31 * n43 - n11 * n34 * n43 - n13 * n31 * n44 + n11 * n33 * n44 ) * detInv;
  9171. te[ 6 ] = ( n14 * n32 * n41 - n12 * n34 * n41 - n14 * n31 * n42 + n11 * n34 * n42 + n12 * n31 * n44 - n11 * n32 * n44 ) * detInv;
  9172. te[ 7 ] = ( n12 * n33 * n41 - n13 * n32 * n41 + n13 * n31 * n42 - n11 * n33 * n42 - n12 * n31 * n43 + n11 * n32 * n43 ) * detInv;
  9173. te[ 8 ] = t13 * detInv;
  9174. te[ 9 ] = ( n14 * n23 * n41 - n13 * n24 * n41 - n14 * n21 * n43 + n11 * n24 * n43 + n13 * n21 * n44 - n11 * n23 * n44 ) * detInv;
  9175. te[ 10 ] = ( n12 * n24 * n41 - n14 * n22 * n41 + n14 * n21 * n42 - n11 * n24 * n42 - n12 * n21 * n44 + n11 * n22 * n44 ) * detInv;
  9176. te[ 11 ] = ( n13 * n22 * n41 - n12 * n23 * n41 - n13 * n21 * n42 + n11 * n23 * n42 + n12 * n21 * n43 - n11 * n22 * n43 ) * detInv;
  9177. te[ 12 ] = t14 * detInv;
  9178. te[ 13 ] = ( n13 * n24 * n31 - n14 * n23 * n31 + n14 * n21 * n33 - n11 * n24 * n33 - n13 * n21 * n34 + n11 * n23 * n34 ) * detInv;
  9179. te[ 14 ] = ( n14 * n22 * n31 - n12 * n24 * n31 - n14 * n21 * n32 + n11 * n24 * n32 + n12 * n21 * n34 - n11 * n22 * n34 ) * detInv;
  9180. te[ 15 ] = ( n12 * n23 * n31 - n13 * n22 * n31 + n13 * n21 * n32 - n11 * n23 * n32 - n12 * n21 * n33 + n11 * n22 * n33 ) * detInv;
  9181. return this;
  9182. }
  9183. /**
  9184. * Multiplies the columns of this matrix by the given vector.
  9185. *
  9186. * @param {Vector3} v - The scale vector.
  9187. * @return {Matrix4} A reference to this matrix.
  9188. */
  9189. scale( v ) {
  9190. const te = this.elements;
  9191. const x = v.x, y = v.y, z = v.z;
  9192. te[ 0 ] *= x; te[ 4 ] *= y; te[ 8 ] *= z;
  9193. te[ 1 ] *= x; te[ 5 ] *= y; te[ 9 ] *= z;
  9194. te[ 2 ] *= x; te[ 6 ] *= y; te[ 10 ] *= z;
  9195. te[ 3 ] *= x; te[ 7 ] *= y; te[ 11 ] *= z;
  9196. return this;
  9197. }
  9198. /**
  9199. * Gets the maximum scale value of the three axes.
  9200. *
  9201. * @return {number} The maximum scale.
  9202. */
  9203. getMaxScaleOnAxis() {
  9204. const te = this.elements;
  9205. const scaleXSq = te[ 0 ] * te[ 0 ] + te[ 1 ] * te[ 1 ] + te[ 2 ] * te[ 2 ];
  9206. const scaleYSq = te[ 4 ] * te[ 4 ] + te[ 5 ] * te[ 5 ] + te[ 6 ] * te[ 6 ];
  9207. const scaleZSq = te[ 8 ] * te[ 8 ] + te[ 9 ] * te[ 9 ] + te[ 10 ] * te[ 10 ];
  9208. return Math.sqrt( Math.max( scaleXSq, scaleYSq, scaleZSq ) );
  9209. }
  9210. /**
  9211. * Sets this matrix as a translation transform from the given vector.
  9212. *
  9213. * @param {number|Vector3} x - The amount to translate in the X axis or alternatively a translation vector.
  9214. * @param {number} y - The amount to translate in the Y axis.
  9215. * @param {number} z - The amount to translate in the z axis.
  9216. * @return {Matrix4} A reference to this matrix.
  9217. */
  9218. makeTranslation( x, y, z ) {
  9219. if ( x.isVector3 ) {
  9220. this.set(
  9221. 1, 0, 0, x.x,
  9222. 0, 1, 0, x.y,
  9223. 0, 0, 1, x.z,
  9224. 0, 0, 0, 1
  9225. );
  9226. } else {
  9227. this.set(
  9228. 1, 0, 0, x,
  9229. 0, 1, 0, y,
  9230. 0, 0, 1, z,
  9231. 0, 0, 0, 1
  9232. );
  9233. }
  9234. return this;
  9235. }
  9236. /**
  9237. * Sets this matrix as a rotational transformation around the X axis by
  9238. * the given angle.
  9239. *
  9240. * @param {number} theta - The rotation in radians.
  9241. * @return {Matrix4} A reference to this matrix.
  9242. */
  9243. makeRotationX( theta ) {
  9244. const c = Math.cos( theta ), s = Math.sin( theta );
  9245. this.set(
  9246. 1, 0, 0, 0,
  9247. 0, c, - s, 0,
  9248. 0, s, c, 0,
  9249. 0, 0, 0, 1
  9250. );
  9251. return this;
  9252. }
  9253. /**
  9254. * Sets this matrix as a rotational transformation around the Y axis by
  9255. * the given angle.
  9256. *
  9257. * @param {number} theta - The rotation in radians.
  9258. * @return {Matrix4} A reference to this matrix.
  9259. */
  9260. makeRotationY( theta ) {
  9261. const c = Math.cos( theta ), s = Math.sin( theta );
  9262. this.set(
  9263. c, 0, s, 0,
  9264. 0, 1, 0, 0,
  9265. - s, 0, c, 0,
  9266. 0, 0, 0, 1
  9267. );
  9268. return this;
  9269. }
  9270. /**
  9271. * Sets this matrix as a rotational transformation around the Z axis by
  9272. * the given angle.
  9273. *
  9274. * @param {number} theta - The rotation in radians.
  9275. * @return {Matrix4} A reference to this matrix.
  9276. */
  9277. makeRotationZ( theta ) {
  9278. const c = Math.cos( theta ), s = Math.sin( theta );
  9279. this.set(
  9280. c, - s, 0, 0,
  9281. s, c, 0, 0,
  9282. 0, 0, 1, 0,
  9283. 0, 0, 0, 1
  9284. );
  9285. return this;
  9286. }
  9287. /**
  9288. * Sets this matrix as a rotational transformation around the given axis by
  9289. * the given angle.
  9290. *
  9291. * This is a somewhat controversial but mathematically sound alternative to
  9292. * rotating via Quaternions. See the discussion [here]{@link https://www.gamedev.net/articles/programming/math-and-physics/do-we-really-need-quaternions-r1199}.
  9293. *
  9294. * @param {Vector3} axis - The normalized rotation axis.
  9295. * @param {number} angle - The rotation in radians.
  9296. * @return {Matrix4} A reference to this matrix.
  9297. */
  9298. makeRotationAxis( axis, angle ) {
  9299. // Based on http://www.gamedev.net/reference/articles/article1199.asp
  9300. const c = Math.cos( angle );
  9301. const s = Math.sin( angle );
  9302. const t = 1 - c;
  9303. const x = axis.x, y = axis.y, z = axis.z;
  9304. const tx = t * x, ty = t * y;
  9305. this.set(
  9306. tx * x + c, tx * y - s * z, tx * z + s * y, 0,
  9307. tx * y + s * z, ty * y + c, ty * z - s * x, 0,
  9308. tx * z - s * y, ty * z + s * x, t * z * z + c, 0,
  9309. 0, 0, 0, 1
  9310. );
  9311. return this;
  9312. }
  9313. /**
  9314. * Sets this matrix as a scale transformation.
  9315. *
  9316. * @param {number} x - The amount to scale in the X axis.
  9317. * @param {number} y - The amount to scale in the Y axis.
  9318. * @param {number} z - The amount to scale in the Z axis.
  9319. * @return {Matrix4} A reference to this matrix.
  9320. */
  9321. makeScale( x, y, z ) {
  9322. this.set(
  9323. x, 0, 0, 0,
  9324. 0, y, 0, 0,
  9325. 0, 0, z, 0,
  9326. 0, 0, 0, 1
  9327. );
  9328. return this;
  9329. }
  9330. /**
  9331. * Sets this matrix as a shear transformation.
  9332. *
  9333. * @param {number} xy - The amount to shear X by Y.
  9334. * @param {number} xz - The amount to shear X by Z.
  9335. * @param {number} yx - The amount to shear Y by X.
  9336. * @param {number} yz - The amount to shear Y by Z.
  9337. * @param {number} zx - The amount to shear Z by X.
  9338. * @param {number} zy - The amount to shear Z by Y.
  9339. * @return {Matrix4} A reference to this matrix.
  9340. */
  9341. makeShear( xy, xz, yx, yz, zx, zy ) {
  9342. this.set(
  9343. 1, yx, zx, 0,
  9344. xy, 1, zy, 0,
  9345. xz, yz, 1, 0,
  9346. 0, 0, 0, 1
  9347. );
  9348. return this;
  9349. }
  9350. /**
  9351. * Sets this matrix to the transformation composed of the given position,
  9352. * rotation (Quaternion) and scale.
  9353. *
  9354. * @param {Vector3} position - The position vector.
  9355. * @param {Quaternion} quaternion - The rotation as a Quaternion.
  9356. * @param {Vector3} scale - The scale vector.
  9357. * @return {Matrix4} A reference to this matrix.
  9358. */
  9359. compose( position, quaternion, scale ) {
  9360. const te = this.elements;
  9361. const x = quaternion._x, y = quaternion._y, z = quaternion._z, w = quaternion._w;
  9362. const x2 = x + x, y2 = y + y, z2 = z + z;
  9363. const xx = x * x2, xy = x * y2, xz = x * z2;
  9364. const yy = y * y2, yz = y * z2, zz = z * z2;
  9365. const wx = w * x2, wy = w * y2, wz = w * z2;
  9366. const sx = scale.x, sy = scale.y, sz = scale.z;
  9367. te[ 0 ] = ( 1 - ( yy + zz ) ) * sx;
  9368. te[ 1 ] = ( xy + wz ) * sx;
  9369. te[ 2 ] = ( xz - wy ) * sx;
  9370. te[ 3 ] = 0;
  9371. te[ 4 ] = ( xy - wz ) * sy;
  9372. te[ 5 ] = ( 1 - ( xx + zz ) ) * sy;
  9373. te[ 6 ] = ( yz + wx ) * sy;
  9374. te[ 7 ] = 0;
  9375. te[ 8 ] = ( xz + wy ) * sz;
  9376. te[ 9 ] = ( yz - wx ) * sz;
  9377. te[ 10 ] = ( 1 - ( xx + yy ) ) * sz;
  9378. te[ 11 ] = 0;
  9379. te[ 12 ] = position.x;
  9380. te[ 13 ] = position.y;
  9381. te[ 14 ] = position.z;
  9382. te[ 15 ] = 1;
  9383. return this;
  9384. }
  9385. /**
  9386. * Decomposes this matrix into its position, rotation and scale components
  9387. * and provides the result in the given objects.
  9388. *
  9389. * Note: Not all matrices are decomposable in this way. For example, if an
  9390. * object has a non-uniformly scaled parent, then the object's world matrix
  9391. * may not be decomposable, and this method may not be appropriate.
  9392. *
  9393. * @param {Vector3} position - The position vector.
  9394. * @param {Quaternion} quaternion - The rotation as a Quaternion.
  9395. * @param {Vector3} scale - The scale vector.
  9396. * @return {Matrix4} A reference to this matrix.
  9397. */
  9398. decompose( position, quaternion, scale ) {
  9399. const te = this.elements;
  9400. let sx = _v1$5.set( te[ 0 ], te[ 1 ], te[ 2 ] ).length();
  9401. const sy = _v1$5.set( te[ 4 ], te[ 5 ], te[ 6 ] ).length();
  9402. const sz = _v1$5.set( te[ 8 ], te[ 9 ], te[ 10 ] ).length();
  9403. // if determine is negative, we need to invert one scale
  9404. const det = this.determinant();
  9405. if ( det < 0 ) sx = - sx;
  9406. position.x = te[ 12 ];
  9407. position.y = te[ 13 ];
  9408. position.z = te[ 14 ];
  9409. // scale the rotation part
  9410. _m1$2.copy( this );
  9411. const invSX = 1 / sx;
  9412. const invSY = 1 / sy;
  9413. const invSZ = 1 / sz;
  9414. _m1$2.elements[ 0 ] *= invSX;
  9415. _m1$2.elements[ 1 ] *= invSX;
  9416. _m1$2.elements[ 2 ] *= invSX;
  9417. _m1$2.elements[ 4 ] *= invSY;
  9418. _m1$2.elements[ 5 ] *= invSY;
  9419. _m1$2.elements[ 6 ] *= invSY;
  9420. _m1$2.elements[ 8 ] *= invSZ;
  9421. _m1$2.elements[ 9 ] *= invSZ;
  9422. _m1$2.elements[ 10 ] *= invSZ;
  9423. quaternion.setFromRotationMatrix( _m1$2 );
  9424. scale.x = sx;
  9425. scale.y = sy;
  9426. scale.z = sz;
  9427. return this;
  9428. }
  9429. /**
  9430. * Creates a perspective projection matrix. This is used internally by
  9431. * {@link PerspectiveCamera#updateProjectionMatrix}.
  9432. * @param {number} left - Left boundary of the viewing frustum at the near plane.
  9433. * @param {number} right - Right boundary of the viewing frustum at the near plane.
  9434. * @param {number} top - Top boundary of the viewing frustum at the near plane.
  9435. * @param {number} bottom - Bottom boundary of the viewing frustum at the near plane.
  9436. * @param {number} near - The distance from the camera to the near plane.
  9437. * @param {number} far - The distance from the camera to the far plane.
  9438. * @param {(WebGLCoordinateSystem|WebGPUCoordinateSystem)} [coordinateSystem=WebGLCoordinateSystem] - The coordinate system.
  9439. * @return {Matrix4} A reference to this matrix.
  9440. */
  9441. makePerspective( left, right, top, bottom, near, far, coordinateSystem = WebGLCoordinateSystem ) {
  9442. const te = this.elements;
  9443. const x = 2 * near / ( right - left );
  9444. const y = 2 * near / ( top - bottom );
  9445. const a = ( right + left ) / ( right - left );
  9446. const b = ( top + bottom ) / ( top - bottom );
  9447. let c, d;
  9448. if ( coordinateSystem === WebGLCoordinateSystem ) {
  9449. c = - ( far + near ) / ( far - near );
  9450. d = ( -2 * far * near ) / ( far - near );
  9451. } else if ( coordinateSystem === WebGPUCoordinateSystem ) {
  9452. c = - far / ( far - near );
  9453. d = ( - far * near ) / ( far - near );
  9454. } else {
  9455. throw new Error( 'THREE.Matrix4.makePerspective(): Invalid coordinate system: ' + coordinateSystem );
  9456. }
  9457. te[ 0 ] = x; te[ 4 ] = 0; te[ 8 ] = a; te[ 12 ] = 0;
  9458. te[ 1 ] = 0; te[ 5 ] = y; te[ 9 ] = b; te[ 13 ] = 0;
  9459. te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = c; te[ 14 ] = d;
  9460. te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = -1; te[ 15 ] = 0;
  9461. return this;
  9462. }
  9463. /**
  9464. * Creates a orthographic projection matrix. This is used internally by
  9465. * {@link OrthographicCamera#updateProjectionMatrix}.
  9466. * @param {number} left - Left boundary of the viewing frustum at the near plane.
  9467. * @param {number} right - Right boundary of the viewing frustum at the near plane.
  9468. * @param {number} top - Top boundary of the viewing frustum at the near plane.
  9469. * @param {number} bottom - Bottom boundary of the viewing frustum at the near plane.
  9470. * @param {number} near - The distance from the camera to the near plane.
  9471. * @param {number} far - The distance from the camera to the far plane.
  9472. * @param {(WebGLCoordinateSystem|WebGPUCoordinateSystem)} [coordinateSystem=WebGLCoordinateSystem] - The coordinate system.
  9473. * @return {Matrix4} A reference to this matrix.
  9474. */
  9475. makeOrthographic( left, right, top, bottom, near, far, coordinateSystem = WebGLCoordinateSystem ) {
  9476. const te = this.elements;
  9477. const w = 1.0 / ( right - left );
  9478. const h = 1.0 / ( top - bottom );
  9479. const p = 1.0 / ( far - near );
  9480. const x = ( right + left ) * w;
  9481. const y = ( top + bottom ) * h;
  9482. let z, zInv;
  9483. if ( coordinateSystem === WebGLCoordinateSystem ) {
  9484. z = ( far + near ) * p;
  9485. zInv = -2 * p;
  9486. } else if ( coordinateSystem === WebGPUCoordinateSystem ) {
  9487. z = near * p;
  9488. zInv = -1 * p;
  9489. } else {
  9490. throw new Error( 'THREE.Matrix4.makeOrthographic(): Invalid coordinate system: ' + coordinateSystem );
  9491. }
  9492. te[ 0 ] = 2 * w; te[ 4 ] = 0; te[ 8 ] = 0; te[ 12 ] = - x;
  9493. te[ 1 ] = 0; te[ 5 ] = 2 * h; te[ 9 ] = 0; te[ 13 ] = - y;
  9494. te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = zInv; te[ 14 ] = - z;
  9495. te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = 0; te[ 15 ] = 1;
  9496. return this;
  9497. }
  9498. /**
  9499. * Returns `true` if this matrix is equal with the given one.
  9500. *
  9501. * @param {Matrix4} matrix - The matrix to test for equality.
  9502. * @return {boolean} Whether this matrix is equal with the given one.
  9503. */
  9504. equals( matrix ) {
  9505. const te = this.elements;
  9506. const me = matrix.elements;
  9507. for ( let i = 0; i < 16; i ++ ) {
  9508. if ( te[ i ] !== me[ i ] ) return false;
  9509. }
  9510. return true;
  9511. }
  9512. /**
  9513. * Sets the elements of the matrix from the given array.
  9514. *
  9515. * @param {Array<number>} array - The matrix elements in column-major order.
  9516. * @param {number} [offset=0] - Index of the first element in the array.
  9517. * @return {Matrix4} A reference to this matrix.
  9518. */
  9519. fromArray( array, offset = 0 ) {
  9520. for ( let i = 0; i < 16; i ++ ) {
  9521. this.elements[ i ] = array[ i + offset ];
  9522. }
  9523. return this;
  9524. }
  9525. /**
  9526. * Writes the elements of this matrix to the given array. If no array is provided,
  9527. * the method returns a new instance.
  9528. *
  9529. * @param {Array<number>} [array=[]] - The target array holding the matrix elements in column-major order.
  9530. * @param {number} [offset=0] - Index of the first element in the array.
  9531. * @return {Array<number>} The matrix elements in column-major order.
  9532. */
  9533. toArray( array = [], offset = 0 ) {
  9534. const te = this.elements;
  9535. array[ offset ] = te[ 0 ];
  9536. array[ offset + 1 ] = te[ 1 ];
  9537. array[ offset + 2 ] = te[ 2 ];
  9538. array[ offset + 3 ] = te[ 3 ];
  9539. array[ offset + 4 ] = te[ 4 ];
  9540. array[ offset + 5 ] = te[ 5 ];
  9541. array[ offset + 6 ] = te[ 6 ];
  9542. array[ offset + 7 ] = te[ 7 ];
  9543. array[ offset + 8 ] = te[ 8 ];
  9544. array[ offset + 9 ] = te[ 9 ];
  9545. array[ offset + 10 ] = te[ 10 ];
  9546. array[ offset + 11 ] = te[ 11 ];
  9547. array[ offset + 12 ] = te[ 12 ];
  9548. array[ offset + 13 ] = te[ 13 ];
  9549. array[ offset + 14 ] = te[ 14 ];
  9550. array[ offset + 15 ] = te[ 15 ];
  9551. return array;
  9552. }
  9553. }
  9554. const _v1$5 = /*@__PURE__*/ new Vector3();
  9555. const _m1$2 = /*@__PURE__*/ new Matrix4();
  9556. const _zero = /*@__PURE__*/ new Vector3( 0, 0, 0 );
  9557. const _one = /*@__PURE__*/ new Vector3( 1, 1, 1 );
  9558. const _x = /*@__PURE__*/ new Vector3();
  9559. const _y = /*@__PURE__*/ new Vector3();
  9560. const _z = /*@__PURE__*/ new Vector3();
  9561. const _matrix$2 = /*@__PURE__*/ new Matrix4();
  9562. const _quaternion$3 = /*@__PURE__*/ new Quaternion();
  9563. /**
  9564. * A class representing Euler angles.
  9565. *
  9566. * Euler angles describe a rotational transformation by rotating an object on
  9567. * its various axes in specified amounts per axis, and a specified axis
  9568. * order.
  9569. *
  9570. * Iterating through an instance will yield its components (x, y, z,
  9571. * order) in the corresponding order.
  9572. *
  9573. * ```js
  9574. * const a = new THREE.Euler( 0, 1, 1.57, 'XYZ' );
  9575. * const b = new THREE.Vector3( 1, 0, 1 );
  9576. * b.applyEuler(a);
  9577. * ```
  9578. */
  9579. class Euler {
  9580. /**
  9581. * Constructs a new euler instance.
  9582. *
  9583. * @param {number} [x=0] - The angle of the x axis in radians.
  9584. * @param {number} [y=0] - The angle of the y axis in radians.
  9585. * @param {number} [z=0] - The angle of the z axis in radians.
  9586. * @param {string} [order=Euler.DEFAULT_ORDER] - A string representing the order that the rotations are applied.
  9587. */
  9588. constructor( x = 0, y = 0, z = 0, order = Euler.DEFAULT_ORDER ) {
  9589. /**
  9590. * This flag can be used for type testing.
  9591. *
  9592. * @type {boolean}
  9593. * @readonly
  9594. * @default true
  9595. */
  9596. this.isEuler = true;
  9597. this._x = x;
  9598. this._y = y;
  9599. this._z = z;
  9600. this._order = order;
  9601. }
  9602. /**
  9603. * The angle of the x axis in radians.
  9604. *
  9605. * @type {number}
  9606. * @default 0
  9607. */
  9608. get x() {
  9609. return this._x;
  9610. }
  9611. set x( value ) {
  9612. this._x = value;
  9613. this._onChangeCallback();
  9614. }
  9615. /**
  9616. * The angle of the y axis in radians.
  9617. *
  9618. * @type {number}
  9619. * @default 0
  9620. */
  9621. get y() {
  9622. return this._y;
  9623. }
  9624. set y( value ) {
  9625. this._y = value;
  9626. this._onChangeCallback();
  9627. }
  9628. /**
  9629. * The angle of the z axis in radians.
  9630. *
  9631. * @type {number}
  9632. * @default 0
  9633. */
  9634. get z() {
  9635. return this._z;
  9636. }
  9637. set z( value ) {
  9638. this._z = value;
  9639. this._onChangeCallback();
  9640. }
  9641. /**
  9642. * A string representing the order that the rotations are applied.
  9643. *
  9644. * @type {string}
  9645. * @default 'XYZ'
  9646. */
  9647. get order() {
  9648. return this._order;
  9649. }
  9650. set order( value ) {
  9651. this._order = value;
  9652. this._onChangeCallback();
  9653. }
  9654. /**
  9655. * Sets the Euler components.
  9656. *
  9657. * @param {number} x - The angle of the x axis in radians.
  9658. * @param {number} y - The angle of the y axis in radians.
  9659. * @param {number} z - The angle of the z axis in radians.
  9660. * @param {string} [order] - A string representing the order that the rotations are applied.
  9661. * @return {Euler} A reference to this Euler instance.
  9662. */
  9663. set( x, y, z, order = this._order ) {
  9664. this._x = x;
  9665. this._y = y;
  9666. this._z = z;
  9667. this._order = order;
  9668. this._onChangeCallback();
  9669. return this;
  9670. }
  9671. /**
  9672. * Returns a new Euler instance with copied values from this instance.
  9673. *
  9674. * @return {Euler} A clone of this instance.
  9675. */
  9676. clone() {
  9677. return new this.constructor( this._x, this._y, this._z, this._order );
  9678. }
  9679. /**
  9680. * Copies the values of the given Euler instance to this instance.
  9681. *
  9682. * @param {Euler} euler - The Euler instance to copy.
  9683. * @return {Euler} A reference to this Euler instance.
  9684. */
  9685. copy( euler ) {
  9686. this._x = euler._x;
  9687. this._y = euler._y;
  9688. this._z = euler._z;
  9689. this._order = euler._order;
  9690. this._onChangeCallback();
  9691. return this;
  9692. }
  9693. /**
  9694. * Sets the angles of this Euler instance from a pure rotation matrix.
  9695. *
  9696. * @param {Matrix4} m - A 4x4 matrix of which the upper 3x3 of matrix is a pure rotation matrix (i.e. unscaled).
  9697. * @param {string} [order] - A string representing the order that the rotations are applied.
  9698. * @param {boolean} [update=true] - Whether the internal `onChange` callback should be executed or not.
  9699. * @return {Euler} A reference to this Euler instance.
  9700. */
  9701. setFromRotationMatrix( m, order = this._order, update = true ) {
  9702. const te = m.elements;
  9703. const m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ];
  9704. const m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ];
  9705. const m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];
  9706. switch ( order ) {
  9707. case 'XYZ':
  9708. this._y = Math.asin( clamp( m13, -1, 1 ) );
  9709. if ( Math.abs( m13 ) < 0.9999999 ) {
  9710. this._x = Math.atan2( - m23, m33 );
  9711. this._z = Math.atan2( - m12, m11 );
  9712. } else {
  9713. this._x = Math.atan2( m32, m22 );
  9714. this._z = 0;
  9715. }
  9716. break;
  9717. case 'YXZ':
  9718. this._x = Math.asin( - clamp( m23, -1, 1 ) );
  9719. if ( Math.abs( m23 ) < 0.9999999 ) {
  9720. this._y = Math.atan2( m13, m33 );
  9721. this._z = Math.atan2( m21, m22 );
  9722. } else {
  9723. this._y = Math.atan2( - m31, m11 );
  9724. this._z = 0;
  9725. }
  9726. break;
  9727. case 'ZXY':
  9728. this._x = Math.asin( clamp( m32, -1, 1 ) );
  9729. if ( Math.abs( m32 ) < 0.9999999 ) {
  9730. this._y = Math.atan2( - m31, m33 );
  9731. this._z = Math.atan2( - m12, m22 );
  9732. } else {
  9733. this._y = 0;
  9734. this._z = Math.atan2( m21, m11 );
  9735. }
  9736. break;
  9737. case 'ZYX':
  9738. this._y = Math.asin( - clamp( m31, -1, 1 ) );
  9739. if ( Math.abs( m31 ) < 0.9999999 ) {
  9740. this._x = Math.atan2( m32, m33 );
  9741. this._z = Math.atan2( m21, m11 );
  9742. } else {
  9743. this._x = 0;
  9744. this._z = Math.atan2( - m12, m22 );
  9745. }
  9746. break;
  9747. case 'YZX':
  9748. this._z = Math.asin( clamp( m21, -1, 1 ) );
  9749. if ( Math.abs( m21 ) < 0.9999999 ) {
  9750. this._x = Math.atan2( - m23, m22 );
  9751. this._y = Math.atan2( - m31, m11 );
  9752. } else {
  9753. this._x = 0;
  9754. this._y = Math.atan2( m13, m33 );
  9755. }
  9756. break;
  9757. case 'XZY':
  9758. this._z = Math.asin( - clamp( m12, -1, 1 ) );
  9759. if ( Math.abs( m12 ) < 0.9999999 ) {
  9760. this._x = Math.atan2( m32, m22 );
  9761. this._y = Math.atan2( m13, m11 );
  9762. } else {
  9763. this._x = Math.atan2( - m23, m33 );
  9764. this._y = 0;
  9765. }
  9766. break;
  9767. default:
  9768. console.warn( 'THREE.Euler: .setFromRotationMatrix() encountered an unknown order: ' + order );
  9769. }
  9770. this._order = order;
  9771. if ( update === true ) this._onChangeCallback();
  9772. return this;
  9773. }
  9774. /**
  9775. * Sets the angles of this Euler instance from a normalized quaternion.
  9776. *
  9777. * @param {Quaternion} q - A normalized Quaternion.
  9778. * @param {string} [order] - A string representing the order that the rotations are applied.
  9779. * @param {boolean} [update=true] - Whether the internal `onChange` callback should be executed or not.
  9780. * @return {Euler} A reference to this Euler instance.
  9781. */
  9782. setFromQuaternion( q, order, update ) {
  9783. _matrix$2.makeRotationFromQuaternion( q );
  9784. return this.setFromRotationMatrix( _matrix$2, order, update );
  9785. }
  9786. /**
  9787. * Sets the angles of this Euler instance from the given vector.
  9788. *
  9789. * @param {Vector3} v - The vector.
  9790. * @param {string} [order] - A string representing the order that the rotations are applied.
  9791. * @return {Euler} A reference to this Euler instance.
  9792. */
  9793. setFromVector3( v, order = this._order ) {
  9794. return this.set( v.x, v.y, v.z, order );
  9795. }
  9796. /**
  9797. * Resets the euler angle with a new order by creating a quaternion from this
  9798. * euler angle and then setting this euler angle with the quaternion and the
  9799. * new order.
  9800. *
  9801. * Warning: This discards revolution information.
  9802. *
  9803. * @param {string} [newOrder] - A string representing the new order that the rotations are applied.
  9804. * @return {Euler} A reference to this Euler instance.
  9805. */
  9806. reorder( newOrder ) {
  9807. _quaternion$3.setFromEuler( this );
  9808. return this.setFromQuaternion( _quaternion$3, newOrder );
  9809. }
  9810. /**
  9811. * Returns `true` if this Euler instance is equal with the given one.
  9812. *
  9813. * @param {Euler} euler - The Euler instance to test for equality.
  9814. * @return {boolean} Whether this Euler instance is equal with the given one.
  9815. */
  9816. equals( euler ) {
  9817. return ( euler._x === this._x ) && ( euler._y === this._y ) && ( euler._z === this._z ) && ( euler._order === this._order );
  9818. }
  9819. /**
  9820. * Sets this Euler instance's components to values from the given array. The first three
  9821. * entries of the array are assign to the x,y and z components. An optional fourth entry
  9822. * defines the Euler order.
  9823. *
  9824. * @param {Array<number,number,number,?string>} array - An array holding the Euler component values.
  9825. * @return {Euler} A reference to this Euler instance.
  9826. */
  9827. fromArray( array ) {
  9828. this._x = array[ 0 ];
  9829. this._y = array[ 1 ];
  9830. this._z = array[ 2 ];
  9831. if ( array[ 3 ] !== undefined ) this._order = array[ 3 ];
  9832. this._onChangeCallback();
  9833. return this;
  9834. }
  9835. /**
  9836. * Writes the components of this Euler instance to the given array. If no array is provided,
  9837. * the method returns a new instance.
  9838. *
  9839. * @param {Array<number,number,number,string>} [array=[]] - The target array holding the Euler components.
  9840. * @param {number} [offset=0] - Index of the first element in the array.
  9841. * @return {Array<number,number,number,string>} The Euler components.
  9842. */
  9843. toArray( array = [], offset = 0 ) {
  9844. array[ offset ] = this._x;
  9845. array[ offset + 1 ] = this._y;
  9846. array[ offset + 2 ] = this._z;
  9847. array[ offset + 3 ] = this._order;
  9848. return array;
  9849. }
  9850. _onChange( callback ) {
  9851. this._onChangeCallback = callback;
  9852. return this;
  9853. }
  9854. _onChangeCallback() {}
  9855. *[ Symbol.iterator ]() {
  9856. yield this._x;
  9857. yield this._y;
  9858. yield this._z;
  9859. yield this._order;
  9860. }
  9861. }
  9862. /**
  9863. * The default Euler angle order.
  9864. *
  9865. * @static
  9866. * @type {string}
  9867. * @default 'XYZ'
  9868. */
  9869. Euler.DEFAULT_ORDER = 'XYZ';
  9870. /**
  9871. * A layers object assigns an 3D object to 1 or more of 32
  9872. * layers numbered `0` to `31` - internally the layers are stored as a
  9873. * bit mask], and by default all 3D objects are a member of layer `0`.
  9874. *
  9875. * This can be used to control visibility - an object must share a layer with
  9876. * a camera to be visible when that camera's view is
  9877. * rendered.
  9878. *
  9879. * All classes that inherit from {@link Object3D} have an `layers` property which
  9880. * is an instance of this class.
  9881. */
  9882. class Layers {
  9883. /**
  9884. * Constructs a new layers instance, with membership
  9885. * initially set to layer `0`.
  9886. */
  9887. constructor() {
  9888. /**
  9889. * A bit mask storing which of the 32 layers this layers object is currently
  9890. * a member of.
  9891. *
  9892. * @type {number}
  9893. */
  9894. this.mask = 1 | 0;
  9895. }
  9896. /**
  9897. * Sets membership to the given layer, and remove membership all other layers.
  9898. *
  9899. * @param {number} layer - The layer to set.
  9900. */
  9901. set( layer ) {
  9902. this.mask = ( 1 << layer | 0 ) >>> 0;
  9903. }
  9904. /**
  9905. * Adds membership of the given layer.
  9906. *
  9907. * @param {number} layer - The layer to enable.
  9908. */
  9909. enable( layer ) {
  9910. this.mask |= 1 << layer | 0;
  9911. }
  9912. /**
  9913. * Adds membership to all layers.
  9914. */
  9915. enableAll() {
  9916. this.mask = 0xffffffff | 0;
  9917. }
  9918. /**
  9919. * Toggles the membership of the given layer.
  9920. *
  9921. * @param {number} layer - The layer to toggle.
  9922. */
  9923. toggle( layer ) {
  9924. this.mask ^= 1 << layer | 0;
  9925. }
  9926. /**
  9927. * Removes membership of the given layer.
  9928. *
  9929. * @param {number} layer - The layer to enable.
  9930. */
  9931. disable( layer ) {
  9932. this.mask &= ~ ( 1 << layer | 0 );
  9933. }
  9934. /**
  9935. * Removes the membership from all layers.
  9936. */
  9937. disableAll() {
  9938. this.mask = 0;
  9939. }
  9940. /**
  9941. * Returns `true` if this and the given layers object have at least one
  9942. * layer in common.
  9943. *
  9944. * @param {Layers} layers - The layers to test.
  9945. * @return {boolean } Whether this and the given layers object have at least one layer in common or not.
  9946. */
  9947. test( layers ) {
  9948. return ( this.mask & layers.mask ) !== 0;
  9949. }
  9950. /**
  9951. * Returns `true` if the given layer is enabled.
  9952. *
  9953. * @param {number} layer - The layer to test.
  9954. * @return {boolean } Whether the given layer is enabled or not.
  9955. */
  9956. isEnabled( layer ) {
  9957. return ( this.mask & ( 1 << layer | 0 ) ) !== 0;
  9958. }
  9959. }
  9960. let _object3DId = 0;
  9961. const _v1$4 = /*@__PURE__*/ new Vector3();
  9962. const _q1 = /*@__PURE__*/ new Quaternion();
  9963. const _m1$1 = /*@__PURE__*/ new Matrix4();
  9964. const _target = /*@__PURE__*/ new Vector3();
  9965. const _position$3 = /*@__PURE__*/ new Vector3();
  9966. const _scale$2 = /*@__PURE__*/ new Vector3();
  9967. const _quaternion$2 = /*@__PURE__*/ new Quaternion();
  9968. const _xAxis = /*@__PURE__*/ new Vector3( 1, 0, 0 );
  9969. const _yAxis = /*@__PURE__*/ new Vector3( 0, 1, 0 );
  9970. const _zAxis = /*@__PURE__*/ new Vector3( 0, 0, 1 );
  9971. /**
  9972. * Fires when the object has been added to its parent object.
  9973. *
  9974. * @event Object3D#added
  9975. * @type {Object}
  9976. */
  9977. const _addedEvent = { type: 'added' };
  9978. /**
  9979. * Fires when the object has been removed from its parent object.
  9980. *
  9981. * @event Object3D#removed
  9982. * @type {Object}
  9983. */
  9984. const _removedEvent = { type: 'removed' };
  9985. /**
  9986. * Fires when a new child object has been added.
  9987. *
  9988. * @event Object3D#childadded
  9989. * @type {Object}
  9990. */
  9991. const _childaddedEvent = { type: 'childadded', child: null };
  9992. /**
  9993. * Fires when a new child object has been added.
  9994. *
  9995. * @event Object3D#childremoved
  9996. * @type {Object}
  9997. */
  9998. const _childremovedEvent = { type: 'childremoved', child: null };
  9999. /**
  10000. * This is the base class for most objects in three.js and provides a set of
  10001. * properties and methods for manipulating objects in 3D space.
  10002. *
  10003. * @augments EventDispatcher
  10004. */
  10005. class Object3D extends EventDispatcher {
  10006. /**
  10007. * Constructs a new 3D object.
  10008. */
  10009. constructor() {
  10010. super();
  10011. /**
  10012. * This flag can be used for type testing.
  10013. *
  10014. * @type {boolean}
  10015. * @readonly
  10016. * @default true
  10017. */
  10018. this.isObject3D = true;
  10019. /**
  10020. * The ID of the 3D object.
  10021. *
  10022. * @name Object3D#id
  10023. * @type {number}
  10024. * @readonly
  10025. */
  10026. Object.defineProperty( this, 'id', { value: _object3DId ++ } );
  10027. /**
  10028. * The UUID of the 3D object.
  10029. *
  10030. * @type {string}
  10031. * @readonly
  10032. */
  10033. this.uuid = generateUUID();
  10034. /**
  10035. * The name of the 3D object.
  10036. *
  10037. * @type {string}
  10038. */
  10039. this.name = '';
  10040. /**
  10041. * The type property is used for detecting the object type
  10042. * in context of serialization/deserialization.
  10043. *
  10044. * @type {string}
  10045. * @readonly
  10046. */
  10047. this.type = 'Object3D';
  10048. /**
  10049. * A reference to the parent object.
  10050. *
  10051. * @type {?Object3D}
  10052. * @default null
  10053. */
  10054. this.parent = null;
  10055. /**
  10056. * An array holding the child 3D objects of this instance.
  10057. *
  10058. * @type {Array<Object3D>}
  10059. */
  10060. this.children = [];
  10061. /**
  10062. * Defines the `up` direction of the 3D object which influences
  10063. * the orientation via methods like {@link Object3D#lookAt}.
  10064. *
  10065. * The default values for all 3D objects is defined by `Object3D.DEFAULT_UP`.
  10066. *
  10067. * @type {Vector3}
  10068. */
  10069. this.up = Object3D.DEFAULT_UP.clone();
  10070. const position = new Vector3();
  10071. const rotation = new Euler();
  10072. const quaternion = new Quaternion();
  10073. const scale = new Vector3( 1, 1, 1 );
  10074. function onRotationChange() {
  10075. quaternion.setFromEuler( rotation, false );
  10076. }
  10077. function onQuaternionChange() {
  10078. rotation.setFromQuaternion( quaternion, undefined, false );
  10079. }
  10080. rotation._onChange( onRotationChange );
  10081. quaternion._onChange( onQuaternionChange );
  10082. Object.defineProperties( this, {
  10083. /**
  10084. * Represents the object's local position.
  10085. *
  10086. * @name Object3D#position
  10087. * @type {Vector3}
  10088. * @default (0,0,0)
  10089. */
  10090. position: {
  10091. configurable: true,
  10092. enumerable: true,
  10093. value: position
  10094. },
  10095. /**
  10096. * Represents the object's local rotation as Euler angles, in radians.
  10097. *
  10098. * @name Object3D#rotation
  10099. * @type {Euler}
  10100. * @default (0,0,0)
  10101. */
  10102. rotation: {
  10103. configurable: true,
  10104. enumerable: true,
  10105. value: rotation
  10106. },
  10107. /**
  10108. * Represents the object's local rotation as Quaternions.
  10109. *
  10110. * @name Object3D#quaternion
  10111. * @type {Quaternion}
  10112. */
  10113. quaternion: {
  10114. configurable: true,
  10115. enumerable: true,
  10116. value: quaternion
  10117. },
  10118. /**
  10119. * Represents the object's local scale.
  10120. *
  10121. * @name Object3D#scale
  10122. * @type {Vector3}
  10123. * @default (1,1,1)
  10124. */
  10125. scale: {
  10126. configurable: true,
  10127. enumerable: true,
  10128. value: scale
  10129. },
  10130. /**
  10131. * Represents the object's model-view matrix.
  10132. *
  10133. * @name Object3D#modelViewMatrix
  10134. * @type {Matrix4}
  10135. */
  10136. modelViewMatrix: {
  10137. value: new Matrix4()
  10138. },
  10139. /**
  10140. * Represents the object's normal matrix.
  10141. *
  10142. * @name Object3D#normalMatrix
  10143. * @type {Matrix3}
  10144. */
  10145. normalMatrix: {
  10146. value: new Matrix3()
  10147. }
  10148. } );
  10149. /**
  10150. * Represents the object's transformation matrix in local space.
  10151. *
  10152. * @type {Matrix4}
  10153. */
  10154. this.matrix = new Matrix4();
  10155. /**
  10156. * Represents the object's transformation matrix in world space.
  10157. * If the 3D object has no parent, then it's identical to the local transformation matrix
  10158. *
  10159. * @type {Matrix4}
  10160. */
  10161. this.matrixWorld = new Matrix4();
  10162. /**
  10163. * When set to `true`, the engine automatically computes the local matrix from position,
  10164. * rotation and scale every frame.
  10165. *
  10166. * The default values for all 3D objects is defined by `Object3D.DEFAULT_MATRIX_AUTO_UPDATE`.
  10167. *
  10168. * @type {boolean}
  10169. * @default true
  10170. */
  10171. this.matrixAutoUpdate = Object3D.DEFAULT_MATRIX_AUTO_UPDATE;
  10172. /**
  10173. * When set to `true`, the engine automatically computes the world matrix from the current local
  10174. * matrix and the object's transformation hierarchy.
  10175. *
  10176. * The default values for all 3D objects is defined by `Object3D.DEFAULT_MATRIX_WORLD_AUTO_UPDATE`.
  10177. *
  10178. * @type {boolean}
  10179. * @default true
  10180. */
  10181. this.matrixWorldAutoUpdate = Object3D.DEFAULT_MATRIX_WORLD_AUTO_UPDATE; // checked by the renderer
  10182. /**
  10183. * When set to `true`, it calculates the world matrix in that frame and resets this property
  10184. * to `false`.
  10185. *
  10186. * @type {boolean}
  10187. * @default false
  10188. */
  10189. this.matrixWorldNeedsUpdate = false;
  10190. /**
  10191. * The layer membership of the 3D object. The 3D object is only visible if it has
  10192. * at least one layer in common with the camera in use. This property can also be
  10193. * used to filter out unwanted objects in ray-intersection tests when using {@link Raycaster}.
  10194. *
  10195. * @type {Layers}
  10196. */
  10197. this.layers = new Layers();
  10198. /**
  10199. * When set to `true`, the 3D object gets rendered.
  10200. *
  10201. * @type {boolean}
  10202. * @default true
  10203. */
  10204. this.visible = true;
  10205. /**
  10206. * When set to `true`, the 3D object gets rendered into shadow maps.
  10207. *
  10208. * @type {boolean}
  10209. * @default false
  10210. */
  10211. this.castShadow = false;
  10212. /**
  10213. * When set to `true`, the 3D object is affected by shadows in the scene.
  10214. *
  10215. * @type {boolean}
  10216. * @default false
  10217. */
  10218. this.receiveShadow = false;
  10219. /**
  10220. * When set to `true`, the 3D object is honored by view frustum culling.
  10221. *
  10222. * @type {boolean}
  10223. * @default true
  10224. */
  10225. this.frustumCulled = true;
  10226. /**
  10227. * This value allows the default rendering order of scene graph objects to be
  10228. * overridden although opaque and transparent objects remain sorted independently.
  10229. * When this property is set for an instance of {@link Group},all descendants
  10230. * objects will be sorted and rendered together. Sorting is from lowest to highest
  10231. * render order.
  10232. *
  10233. * @type {number}
  10234. * @default 0
  10235. */
  10236. this.renderOrder = 0;
  10237. /**
  10238. * An array holding the animation clips of the 3D object.
  10239. *
  10240. * @type {Array<AnimationClip>}
  10241. */
  10242. this.animations = [];
  10243. /**
  10244. * Custom depth material to be used when rendering to the depth map. Can only be used
  10245. * in context of meshes. When shadow-casting with a {@link DirectionalLight} or {@link SpotLight},
  10246. * if you are modifying vertex positions in the vertex shader you must specify a custom depth
  10247. * material for proper shadows.
  10248. *
  10249. * Only relevant in context of {@link WebGLRenderer}.
  10250. *
  10251. * @type {(Material|undefined)}
  10252. * @default undefined
  10253. */
  10254. this.customDepthMaterial = undefined;
  10255. /**
  10256. * Same as {@link Object3D#customDepthMaterial}, but used with {@link PointLight}.
  10257. *
  10258. * Only relevant in context of {@link WebGLRenderer}.
  10259. *
  10260. * @type {(Material|undefined)}
  10261. * @default undefined
  10262. */
  10263. this.customDistanceMaterial = undefined;
  10264. /**
  10265. * An object that can be used to store custom data about the 3D object. It
  10266. * should not hold references to functions as these will not be cloned.
  10267. *
  10268. * @type {Object}
  10269. */
  10270. this.userData = {};
  10271. }
  10272. /**
  10273. * A callback that is executed immediately before a 3D object is rendered to a shadow map.
  10274. *
  10275. * @param {Renderer|WebGLRenderer} renderer - The renderer.
  10276. * @param {Object3D} object - The 3D object.
  10277. * @param {Camera} camera - The camera that is used to render the scene.
  10278. * @param {Camera} shadowCamera - The shadow camera.
  10279. * @param {BufferGeometry} geometry - The 3D object's geometry.
  10280. * @param {Material} depthMaterial - The depth material.
  10281. * @param {Object} group - The geometry group data.
  10282. */
  10283. onBeforeShadow( /* renderer, object, camera, shadowCamera, geometry, depthMaterial, group */ ) {}
  10284. /**
  10285. * A callback that is executed immediately after a 3D object is rendered to a shadow map.
  10286. *
  10287. * @param {Renderer|WebGLRenderer} renderer - The renderer.
  10288. * @param {Object3D} object - The 3D object.
  10289. * @param {Camera} camera - The camera that is used to render the scene.
  10290. * @param {Camera} shadowCamera - The shadow camera.
  10291. * @param {BufferGeometry} geometry - The 3D object's geometry.
  10292. * @param {Material} depthMaterial - The depth material.
  10293. * @param {Object} group - The geometry group data.
  10294. */
  10295. onAfterShadow( /* renderer, object, camera, shadowCamera, geometry, depthMaterial, group */ ) {}
  10296. /**
  10297. * A callback that is executed immediately before a 3D object is rendered.
  10298. *
  10299. * @param {Renderer|WebGLRenderer} renderer - The renderer.
  10300. * @param {Object3D} object - The 3D object.
  10301. * @param {Camera} camera - The camera that is used to render the scene.
  10302. * @param {BufferGeometry} geometry - The 3D object's geometry.
  10303. * @param {Material} material - The 3D object's material.
  10304. * @param {Object} group - The geometry group data.
  10305. */
  10306. onBeforeRender( /* renderer, scene, camera, geometry, material, group */ ) {}
  10307. /**
  10308. * A callback that is executed immediately after a 3D object is rendered.
  10309. *
  10310. * @param {Renderer|WebGLRenderer} renderer - The renderer.
  10311. * @param {Object3D} object - The 3D object.
  10312. * @param {Camera} camera - The camera that is used to render the scene.
  10313. * @param {BufferGeometry} geometry - The 3D object's geometry.
  10314. * @param {Material} material - The 3D object's material.
  10315. * @param {Object} group - The geometry group data.
  10316. */
  10317. onAfterRender( /* renderer, scene, camera, geometry, material, group */ ) {}
  10318. /**
  10319. * Applies the given transformation matrix to the object and updates the object's position,
  10320. * rotation and scale.
  10321. *
  10322. * @param {Matrix4} matrix - The transformation matrix.
  10323. */
  10324. applyMatrix4( matrix ) {
  10325. if ( this.matrixAutoUpdate ) this.updateMatrix();
  10326. this.matrix.premultiply( matrix );
  10327. this.matrix.decompose( this.position, this.quaternion, this.scale );
  10328. }
  10329. /**
  10330. * Applies a rotation represented by given the quaternion to the 3D object.
  10331. *
  10332. * @param {Quaternion} q - The quaternion.
  10333. * @return {Object3D} A reference to this instance.
  10334. */
  10335. applyQuaternion( q ) {
  10336. this.quaternion.premultiply( q );
  10337. return this;
  10338. }
  10339. /**
  10340. * Sets the given rotation represented as an axis/angle couple to the 3D object.
  10341. *
  10342. * @param {Vector3} axis - The (normalized) axis vector.
  10343. * @param {number} angle - The angle in radians.
  10344. */
  10345. setRotationFromAxisAngle( axis, angle ) {
  10346. // assumes axis is normalized
  10347. this.quaternion.setFromAxisAngle( axis, angle );
  10348. }
  10349. /**
  10350. * Sets the given rotation represented as Euler angles to the 3D object.
  10351. *
  10352. * @param {Euler} euler - The Euler angles.
  10353. */
  10354. setRotationFromEuler( euler ) {
  10355. this.quaternion.setFromEuler( euler, true );
  10356. }
  10357. /**
  10358. * Sets the given rotation represented as rotation matrix to the 3D object.
  10359. *
  10360. * @param {Matrix4} m - Although a 4x4 matrix is expected, the upper 3x3 portion must be
  10361. * a pure rotation matrix (i.e, unscaled).
  10362. */
  10363. setRotationFromMatrix( m ) {
  10364. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  10365. this.quaternion.setFromRotationMatrix( m );
  10366. }
  10367. /**
  10368. * Sets the given rotation represented as a Quaternion to the 3D object.
  10369. *
  10370. * @param {Quaternion} q - The Quaternion
  10371. */
  10372. setRotationFromQuaternion( q ) {
  10373. // assumes q is normalized
  10374. this.quaternion.copy( q );
  10375. }
  10376. /**
  10377. * Rotates the 3D object along an axis in local space.
  10378. *
  10379. * @param {Vector3} axis - The (normalized) axis vector.
  10380. * @param {number} angle - The angle in radians.
  10381. * @return {Object3D} A reference to this instance.
  10382. */
  10383. rotateOnAxis( axis, angle ) {
  10384. // rotate object on axis in object space
  10385. // axis is assumed to be normalized
  10386. _q1.setFromAxisAngle( axis, angle );
  10387. this.quaternion.multiply( _q1 );
  10388. return this;
  10389. }
  10390. /**
  10391. * Rotates the 3D object along an axis in world space.
  10392. *
  10393. * @param {Vector3} axis - The (normalized) axis vector.
  10394. * @param {number} angle - The angle in radians.
  10395. * @return {Object3D} A reference to this instance.
  10396. */
  10397. rotateOnWorldAxis( axis, angle ) {
  10398. // rotate object on axis in world space
  10399. // axis is assumed to be normalized
  10400. // method assumes no rotated parent
  10401. _q1.setFromAxisAngle( axis, angle );
  10402. this.quaternion.premultiply( _q1 );
  10403. return this;
  10404. }
  10405. /**
  10406. * Rotates the 3D object around its X axis in local space.
  10407. *
  10408. * @param {number} angle - The angle in radians.
  10409. * @return {Object3D} A reference to this instance.
  10410. */
  10411. rotateX( angle ) {
  10412. return this.rotateOnAxis( _xAxis, angle );
  10413. }
  10414. /**
  10415. * Rotates the 3D object around its Y axis in local space.
  10416. *
  10417. * @param {number} angle - The angle in radians.
  10418. * @return {Object3D} A reference to this instance.
  10419. */
  10420. rotateY( angle ) {
  10421. return this.rotateOnAxis( _yAxis, angle );
  10422. }
  10423. /**
  10424. * Rotates the 3D object around its Z axis in local space.
  10425. *
  10426. * @param {number} angle - The angle in radians.
  10427. * @return {Object3D} A reference to this instance.
  10428. */
  10429. rotateZ( angle ) {
  10430. return this.rotateOnAxis( _zAxis, angle );
  10431. }
  10432. /**
  10433. * Translate the 3D object by a distance along the given axis in local space.
  10434. *
  10435. * @param {Vector3} axis - The (normalized) axis vector.
  10436. * @param {number} distance - The distance in world units.
  10437. * @return {Object3D} A reference to this instance.
  10438. */
  10439. translateOnAxis( axis, distance ) {
  10440. // translate object by distance along axis in object space
  10441. // axis is assumed to be normalized
  10442. _v1$4.copy( axis ).applyQuaternion( this.quaternion );
  10443. this.position.add( _v1$4.multiplyScalar( distance ) );
  10444. return this;
  10445. }
  10446. /**
  10447. * Translate the 3D object by a distance along its X-axis in local space.
  10448. *
  10449. * @param {number} distance - The distance in world units.
  10450. * @return {Object3D} A reference to this instance.
  10451. */
  10452. translateX( distance ) {
  10453. return this.translateOnAxis( _xAxis, distance );
  10454. }
  10455. /**
  10456. * Translate the 3D object by a distance along its Y-axis in local space.
  10457. *
  10458. * @param {number} distance - The distance in world units.
  10459. * @return {Object3D} A reference to this instance.
  10460. */
  10461. translateY( distance ) {
  10462. return this.translateOnAxis( _yAxis, distance );
  10463. }
  10464. /**
  10465. * Translate the 3D object by a distance along its Z-axis in local space.
  10466. *
  10467. * @param {number} distance - The distance in world units.
  10468. * @return {Object3D} A reference to this instance.
  10469. */
  10470. translateZ( distance ) {
  10471. return this.translateOnAxis( _zAxis, distance );
  10472. }
  10473. /**
  10474. * Converts the given vector from this 3D object's local space to world space.
  10475. *
  10476. * @param {Vector3} vector - The vector to convert.
  10477. * @return {Vector3} The converted vector.
  10478. */
  10479. localToWorld( vector ) {
  10480. this.updateWorldMatrix( true, false );
  10481. return vector.applyMatrix4( this.matrixWorld );
  10482. }
  10483. /**
  10484. * Converts the given vector from this 3D object's word space to local space.
  10485. *
  10486. * @param {Vector3} vector - The vector to convert.
  10487. * @return {Vector3} The converted vector.
  10488. */
  10489. worldToLocal( vector ) {
  10490. this.updateWorldMatrix( true, false );
  10491. return vector.applyMatrix4( _m1$1.copy( this.matrixWorld ).invert() );
  10492. }
  10493. /**
  10494. * Rotates the object to face a point in world space.
  10495. *
  10496. * This method does not support objects having non-uniformly-scaled parent(s).
  10497. *
  10498. * @param {number|Vector3} x - The x coordinate in world space. Alternatively, a vector representing a position in world space
  10499. * @param {number} [y] - The y coordinate in world space.
  10500. * @param {number} [z] - The z coordinate in world space.
  10501. */
  10502. lookAt( x, y, z ) {
  10503. // This method does not support objects having non-uniformly-scaled parent(s)
  10504. if ( x.isVector3 ) {
  10505. _target.copy( x );
  10506. } else {
  10507. _target.set( x, y, z );
  10508. }
  10509. const parent = this.parent;
  10510. this.updateWorldMatrix( true, false );
  10511. _position$3.setFromMatrixPosition( this.matrixWorld );
  10512. if ( this.isCamera || this.isLight ) {
  10513. _m1$1.lookAt( _position$3, _target, this.up );
  10514. } else {
  10515. _m1$1.lookAt( _target, _position$3, this.up );
  10516. }
  10517. this.quaternion.setFromRotationMatrix( _m1$1 );
  10518. if ( parent ) {
  10519. _m1$1.extractRotation( parent.matrixWorld );
  10520. _q1.setFromRotationMatrix( _m1$1 );
  10521. this.quaternion.premultiply( _q1.invert() );
  10522. }
  10523. }
  10524. /**
  10525. * Adds the given 3D object as a child to this 3D object. An arbitrary number of
  10526. * objects may be added. Any current parent on an object passed in here will be
  10527. * removed, since an object can have at most one parent.
  10528. *
  10529. * @fires Object3D#added
  10530. * @fires Object3D#childadded
  10531. * @param {Object3D} object - The 3D object to add.
  10532. * @return {Object3D} A reference to this instance.
  10533. */
  10534. add( object ) {
  10535. if ( arguments.length > 1 ) {
  10536. for ( let i = 0; i < arguments.length; i ++ ) {
  10537. this.add( arguments[ i ] );
  10538. }
  10539. return this;
  10540. }
  10541. if ( object === this ) {
  10542. console.error( 'THREE.Object3D.add: object can\'t be added as a child of itself.', object );
  10543. return this;
  10544. }
  10545. if ( object && object.isObject3D ) {
  10546. object.removeFromParent();
  10547. object.parent = this;
  10548. this.children.push( object );
  10549. object.dispatchEvent( _addedEvent );
  10550. _childaddedEvent.child = object;
  10551. this.dispatchEvent( _childaddedEvent );
  10552. _childaddedEvent.child = null;
  10553. } else {
  10554. console.error( 'THREE.Object3D.add: object not an instance of THREE.Object3D.', object );
  10555. }
  10556. return this;
  10557. }
  10558. /**
  10559. * Removes the given 3D object as child from this 3D object.
  10560. * An arbitrary number of objects may be removed.
  10561. *
  10562. * @fires Object3D#removed
  10563. * @fires Object3D#childremoved
  10564. * @param {Object3D} object - The 3D object to remove.
  10565. * @return {Object3D} A reference to this instance.
  10566. */
  10567. remove( object ) {
  10568. if ( arguments.length > 1 ) {
  10569. for ( let i = 0; i < arguments.length; i ++ ) {
  10570. this.remove( arguments[ i ] );
  10571. }
  10572. return this;
  10573. }
  10574. const index = this.children.indexOf( object );
  10575. if ( index !== -1 ) {
  10576. object.parent = null;
  10577. this.children.splice( index, 1 );
  10578. object.dispatchEvent( _removedEvent );
  10579. _childremovedEvent.child = object;
  10580. this.dispatchEvent( _childremovedEvent );
  10581. _childremovedEvent.child = null;
  10582. }
  10583. return this;
  10584. }
  10585. /**
  10586. * Removes this 3D object from its current parent.
  10587. *
  10588. * @fires Object3D#removed
  10589. * @fires Object3D#childremoved
  10590. * @return {Object3D} A reference to this instance.
  10591. */
  10592. removeFromParent() {
  10593. const parent = this.parent;
  10594. if ( parent !== null ) {
  10595. parent.remove( this );
  10596. }
  10597. return this;
  10598. }
  10599. /**
  10600. * Removes all child objects.
  10601. *
  10602. * @fires Object3D#removed
  10603. * @fires Object3D#childremoved
  10604. * @return {Object3D} A reference to this instance.
  10605. */
  10606. clear() {
  10607. return this.remove( ... this.children );
  10608. }
  10609. /**
  10610. * Adds the given 3D object as a child of this 3D object, while maintaining the object's world
  10611. * transform. This method does not support scene graphs having non-uniformly-scaled nodes(s).
  10612. *
  10613. * @fires Object3D#added
  10614. * @fires Object3D#childadded
  10615. * @param {Object3D} object - The 3D object to attach.
  10616. * @return {Object3D} A reference to this instance.
  10617. */
  10618. attach( object ) {
  10619. // adds object as a child of this, while maintaining the object's world transform
  10620. // Note: This method does not support scene graphs having non-uniformly-scaled nodes(s)
  10621. this.updateWorldMatrix( true, false );
  10622. _m1$1.copy( this.matrixWorld ).invert();
  10623. if ( object.parent !== null ) {
  10624. object.parent.updateWorldMatrix( true, false );
  10625. _m1$1.multiply( object.parent.matrixWorld );
  10626. }
  10627. object.applyMatrix4( _m1$1 );
  10628. object.removeFromParent();
  10629. object.parent = this;
  10630. this.children.push( object );
  10631. object.updateWorldMatrix( false, true );
  10632. object.dispatchEvent( _addedEvent );
  10633. _childaddedEvent.child = object;
  10634. this.dispatchEvent( _childaddedEvent );
  10635. _childaddedEvent.child = null;
  10636. return this;
  10637. }
  10638. /**
  10639. * Searches through the 3D object and its children, starting with the 3D object
  10640. * itself, and returns the first with a matching ID.
  10641. *
  10642. * @param {number} id - The id.
  10643. * @return {Object3D|undefined} The found 3D object. Returns `undefined` if no 3D object has been found.
  10644. */
  10645. getObjectById( id ) {
  10646. return this.getObjectByProperty( 'id', id );
  10647. }
  10648. /**
  10649. * Searches through the 3D object and its children, starting with the 3D object
  10650. * itself, and returns the first with a matching name.
  10651. *
  10652. * @param {string} name - The name.
  10653. * @return {Object3D|undefined} The found 3D object. Returns `undefined` if no 3D object has been found.
  10654. */
  10655. getObjectByName( name ) {
  10656. return this.getObjectByProperty( 'name', name );
  10657. }
  10658. /**
  10659. * Searches through the 3D object and its children, starting with the 3D object
  10660. * itself, and returns the first with a matching property value.
  10661. *
  10662. * @param {string} name - The name of the property.
  10663. * @param {any} value - The value.
  10664. * @return {Object3D|undefined} The found 3D object. Returns `undefined` if no 3D object has been found.
  10665. */
  10666. getObjectByProperty( name, value ) {
  10667. if ( this[ name ] === value ) return this;
  10668. for ( let i = 0, l = this.children.length; i < l; i ++ ) {
  10669. const child = this.children[ i ];
  10670. const object = child.getObjectByProperty( name, value );
  10671. if ( object !== undefined ) {
  10672. return object;
  10673. }
  10674. }
  10675. return undefined;
  10676. }
  10677. /**
  10678. * Searches through the 3D object and its children, starting with the 3D object
  10679. * itself, and returns all 3D objects with a matching property value.
  10680. *
  10681. * @param {string} name - The name of the property.
  10682. * @param {any} value - The value.
  10683. * @param {Array<Object3D>} result - The method stores the result in this array.
  10684. * @return {Array<Object3D>} The found 3D objects.
  10685. */
  10686. getObjectsByProperty( name, value, result = [] ) {
  10687. if ( this[ name ] === value ) result.push( this );
  10688. const children = this.children;
  10689. for ( let i = 0, l = children.length; i < l; i ++ ) {
  10690. children[ i ].getObjectsByProperty( name, value, result );
  10691. }
  10692. return result;
  10693. }
  10694. /**
  10695. * Returns a vector representing the position of the 3D object in world space.
  10696. *
  10697. * @param {Vector3} target - The target vector the result is stored to.
  10698. * @return {Vector3} The 3D object's position in world space.
  10699. */
  10700. getWorldPosition( target ) {
  10701. this.updateWorldMatrix( true, false );
  10702. return target.setFromMatrixPosition( this.matrixWorld );
  10703. }
  10704. /**
  10705. * Returns a Quaternion representing the position of the 3D object in world space.
  10706. *
  10707. * @param {Quaternion} target - The target Quaternion the result is stored to.
  10708. * @return {Quaternion} The 3D object's rotation in world space.
  10709. */
  10710. getWorldQuaternion( target ) {
  10711. this.updateWorldMatrix( true, false );
  10712. this.matrixWorld.decompose( _position$3, target, _scale$2 );
  10713. return target;
  10714. }
  10715. /**
  10716. * Returns a vector representing the scale of the 3D object in world space.
  10717. *
  10718. * @param {Vector3} target - The target vector the result is stored to.
  10719. * @return {Vector3} The 3D object's scale in world space.
  10720. */
  10721. getWorldScale( target ) {
  10722. this.updateWorldMatrix( true, false );
  10723. this.matrixWorld.decompose( _position$3, _quaternion$2, target );
  10724. return target;
  10725. }
  10726. /**
  10727. * Returns a vector representing the ("look") direction of the 3D object in world space.
  10728. *
  10729. * @param {Vector3} target - The target vector the result is stored to.
  10730. * @return {Vector3} The 3D object's direction in world space.
  10731. */
  10732. getWorldDirection( target ) {
  10733. this.updateWorldMatrix( true, false );
  10734. const e = this.matrixWorld.elements;
  10735. return target.set( e[ 8 ], e[ 9 ], e[ 10 ] ).normalize();
  10736. }
  10737. /**
  10738. * Abstract method to get intersections between a casted ray and this
  10739. * 3D object. Renderable 3D objects such as {@link Mesh}, {@link Line} or {@link Points}
  10740. * implement this method in order to use raycasting.
  10741. *
  10742. * @abstract
  10743. * @param {Raycaster} raycaster - The raycaster.
  10744. * @param {Array<Object>} intersects - An array holding the result of the method.
  10745. */
  10746. raycast( /* raycaster, intersects */ ) {}
  10747. /**
  10748. * Executes the callback on this 3D object and all descendants.
  10749. *
  10750. * Note: Modifying the scene graph inside the callback is discouraged.
  10751. *
  10752. * @param {Function} callback - A callback function that allows to process the current 3D object.
  10753. */
  10754. traverse( callback ) {
  10755. callback( this );
  10756. const children = this.children;
  10757. for ( let i = 0, l = children.length; i < l; i ++ ) {
  10758. children[ i ].traverse( callback );
  10759. }
  10760. }
  10761. /**
  10762. * Like {@link Object3D#traverse}, but the callback will only be executed for visible 3D objects.
  10763. * Descendants of invisible 3D objects are not traversed.
  10764. *
  10765. * Note: Modifying the scene graph inside the callback is discouraged.
  10766. *
  10767. * @param {Function} callback - A callback function that allows to process the current 3D object.
  10768. */
  10769. traverseVisible( callback ) {
  10770. if ( this.visible === false ) return;
  10771. callback( this );
  10772. const children = this.children;
  10773. for ( let i = 0, l = children.length; i < l; i ++ ) {
  10774. children[ i ].traverseVisible( callback );
  10775. }
  10776. }
  10777. /**
  10778. * Like {@link Object3D#traverse}, but the callback will only be executed for all ancestors.
  10779. *
  10780. * Note: Modifying the scene graph inside the callback is discouraged.
  10781. *
  10782. * @param {Function} callback - A callback function that allows to process the current 3D object.
  10783. */
  10784. traverseAncestors( callback ) {
  10785. const parent = this.parent;
  10786. if ( parent !== null ) {
  10787. callback( parent );
  10788. parent.traverseAncestors( callback );
  10789. }
  10790. }
  10791. /**
  10792. * Updates the transformation matrix in local space by computing it from the current
  10793. * position, rotation and scale values.
  10794. */
  10795. updateMatrix() {
  10796. this.matrix.compose( this.position, this.quaternion, this.scale );
  10797. this.matrixWorldNeedsUpdate = true;
  10798. }
  10799. /**
  10800. * Updates the transformation matrix in world space of this 3D objects and its descendants.
  10801. *
  10802. * To ensure correct results, this method also recomputes the 3D object's transformation matrix in
  10803. * local space. The computation of the local and world matrix can be controlled with the
  10804. * {@link Object3D#matrixAutoUpdate} and {@link Object3D#matrixWorldAutoUpdate} flags which are both
  10805. * `true` by default. Set these flags to `false` if you need more control over the update matrix process.
  10806. *
  10807. * @param {boolean} [force=false] - When set to `true`, a recomputation of world matrices is forced even
  10808. * when {@link Object3D#matrixWorldAutoUpdate} is set to `false`.
  10809. */
  10810. updateMatrixWorld( force ) {
  10811. if ( this.matrixAutoUpdate ) this.updateMatrix();
  10812. if ( this.matrixWorldNeedsUpdate || force ) {
  10813. if ( this.matrixWorldAutoUpdate === true ) {
  10814. if ( this.parent === null ) {
  10815. this.matrixWorld.copy( this.matrix );
  10816. } else {
  10817. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  10818. }
  10819. }
  10820. this.matrixWorldNeedsUpdate = false;
  10821. force = true;
  10822. }
  10823. // make sure descendants are updated if required
  10824. const children = this.children;
  10825. for ( let i = 0, l = children.length; i < l; i ++ ) {
  10826. const child = children[ i ];
  10827. child.updateMatrixWorld( force );
  10828. }
  10829. }
  10830. /**
  10831. * An alternative version of {@link Object3D#updateMatrixWorld} with more control over the
  10832. * update of ancestor and descendant nodes.
  10833. *
  10834. * @param {boolean} [updateParents=false] Whether ancestor nodes should be updated or not.
  10835. * @param {boolean} [updateChildren=false] Whether descendant nodes should be updated or not.
  10836. */
  10837. updateWorldMatrix( updateParents, updateChildren ) {
  10838. const parent = this.parent;
  10839. if ( updateParents === true && parent !== null ) {
  10840. parent.updateWorldMatrix( true, false );
  10841. }
  10842. if ( this.matrixAutoUpdate ) this.updateMatrix();
  10843. if ( this.matrixWorldAutoUpdate === true ) {
  10844. if ( this.parent === null ) {
  10845. this.matrixWorld.copy( this.matrix );
  10846. } else {
  10847. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  10848. }
  10849. }
  10850. // make sure descendants are updated
  10851. if ( updateChildren === true ) {
  10852. const children = this.children;
  10853. for ( let i = 0, l = children.length; i < l; i ++ ) {
  10854. const child = children[ i ];
  10855. child.updateWorldMatrix( false, true );
  10856. }
  10857. }
  10858. }
  10859. /**
  10860. * Serializes the 3D object into JSON.
  10861. *
  10862. * @param {?(Object|string)} meta - An optional value holding meta information about the serialization.
  10863. * @return {Object} A JSON object representing the serialized 3D object.
  10864. * @see {@link ObjectLoader#parse}
  10865. */
  10866. toJSON( meta ) {
  10867. // meta is a string when called from JSON.stringify
  10868. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  10869. const output = {};
  10870. // meta is a hash used to collect geometries, materials.
  10871. // not providing it implies that this is the root object
  10872. // being serialized.
  10873. if ( isRootObject ) {
  10874. // initialize meta obj
  10875. meta = {
  10876. geometries: {},
  10877. materials: {},
  10878. textures: {},
  10879. images: {},
  10880. shapes: {},
  10881. skeletons: {},
  10882. animations: {},
  10883. nodes: {}
  10884. };
  10885. output.metadata = {
  10886. version: 4.6,
  10887. type: 'Object',
  10888. generator: 'Object3D.toJSON'
  10889. };
  10890. }
  10891. // standard Object3D serialization
  10892. const object = {};
  10893. object.uuid = this.uuid;
  10894. object.type = this.type;
  10895. if ( this.name !== '' ) object.name = this.name;
  10896. if ( this.castShadow === true ) object.castShadow = true;
  10897. if ( this.receiveShadow === true ) object.receiveShadow = true;
  10898. if ( this.visible === false ) object.visible = false;
  10899. if ( this.frustumCulled === false ) object.frustumCulled = false;
  10900. if ( this.renderOrder !== 0 ) object.renderOrder = this.renderOrder;
  10901. if ( Object.keys( this.userData ).length > 0 ) object.userData = this.userData;
  10902. object.layers = this.layers.mask;
  10903. object.matrix = this.matrix.toArray();
  10904. object.up = this.up.toArray();
  10905. if ( this.matrixAutoUpdate === false ) object.matrixAutoUpdate = false;
  10906. // object specific properties
  10907. if ( this.isInstancedMesh ) {
  10908. object.type = 'InstancedMesh';
  10909. object.count = this.count;
  10910. object.instanceMatrix = this.instanceMatrix.toJSON();
  10911. if ( this.instanceColor !== null ) object.instanceColor = this.instanceColor.toJSON();
  10912. }
  10913. if ( this.isBatchedMesh ) {
  10914. object.type = 'BatchedMesh';
  10915. object.perObjectFrustumCulled = this.perObjectFrustumCulled;
  10916. object.sortObjects = this.sortObjects;
  10917. object.drawRanges = this._drawRanges;
  10918. object.reservedRanges = this._reservedRanges;
  10919. object.geometryInfo = this._geometryInfo.map( info => ( {
  10920. ...info,
  10921. boundingBox: info.boundingBox ? info.boundingBox.toJSON() : undefined,
  10922. boundingSphere: info.boundingSphere ? info.boundingSphere.toJSON() : undefined
  10923. } ) );
  10924. object.instanceInfo = this._instanceInfo.map( info => ( { ...info } ) );
  10925. object.availableInstanceIds = this._availableInstanceIds.slice();
  10926. object.availableGeometryIds = this._availableGeometryIds.slice();
  10927. object.nextIndexStart = this._nextIndexStart;
  10928. object.nextVertexStart = this._nextVertexStart;
  10929. object.geometryCount = this._geometryCount;
  10930. object.maxInstanceCount = this._maxInstanceCount;
  10931. object.maxVertexCount = this._maxVertexCount;
  10932. object.maxIndexCount = this._maxIndexCount;
  10933. object.geometryInitialized = this._geometryInitialized;
  10934. object.matricesTexture = this._matricesTexture.toJSON( meta );
  10935. object.indirectTexture = this._indirectTexture.toJSON( meta );
  10936. if ( this._colorsTexture !== null ) {
  10937. object.colorsTexture = this._colorsTexture.toJSON( meta );
  10938. }
  10939. if ( this.boundingSphere !== null ) {
  10940. object.boundingSphere = this.boundingSphere.toJSON();
  10941. }
  10942. if ( this.boundingBox !== null ) {
  10943. object.boundingBox = this.boundingBox.toJSON();
  10944. }
  10945. }
  10946. //
  10947. function serialize( library, element ) {
  10948. if ( library[ element.uuid ] === undefined ) {
  10949. library[ element.uuid ] = element.toJSON( meta );
  10950. }
  10951. return element.uuid;
  10952. }
  10953. if ( this.isScene ) {
  10954. if ( this.background ) {
  10955. if ( this.background.isColor ) {
  10956. object.background = this.background.toJSON();
  10957. } else if ( this.background.isTexture ) {
  10958. object.background = this.background.toJSON( meta ).uuid;
  10959. }
  10960. }
  10961. if ( this.environment && this.environment.isTexture && this.environment.isRenderTargetTexture !== true ) {
  10962. object.environment = this.environment.toJSON( meta ).uuid;
  10963. }
  10964. } else if ( this.isMesh || this.isLine || this.isPoints ) {
  10965. object.geometry = serialize( meta.geometries, this.geometry );
  10966. const parameters = this.geometry.parameters;
  10967. if ( parameters !== undefined && parameters.shapes !== undefined ) {
  10968. const shapes = parameters.shapes;
  10969. if ( Array.isArray( shapes ) ) {
  10970. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  10971. const shape = shapes[ i ];
  10972. serialize( meta.shapes, shape );
  10973. }
  10974. } else {
  10975. serialize( meta.shapes, shapes );
  10976. }
  10977. }
  10978. }
  10979. if ( this.isSkinnedMesh ) {
  10980. object.bindMode = this.bindMode;
  10981. object.bindMatrix = this.bindMatrix.toArray();
  10982. if ( this.skeleton !== undefined ) {
  10983. serialize( meta.skeletons, this.skeleton );
  10984. object.skeleton = this.skeleton.uuid;
  10985. }
  10986. }
  10987. if ( this.material !== undefined ) {
  10988. if ( Array.isArray( this.material ) ) {
  10989. const uuids = [];
  10990. for ( let i = 0, l = this.material.length; i < l; i ++ ) {
  10991. uuids.push( serialize( meta.materials, this.material[ i ] ) );
  10992. }
  10993. object.material = uuids;
  10994. } else {
  10995. object.material = serialize( meta.materials, this.material );
  10996. }
  10997. }
  10998. //
  10999. if ( this.children.length > 0 ) {
  11000. object.children = [];
  11001. for ( let i = 0; i < this.children.length; i ++ ) {
  11002. object.children.push( this.children[ i ].toJSON( meta ).object );
  11003. }
  11004. }
  11005. //
  11006. if ( this.animations.length > 0 ) {
  11007. object.animations = [];
  11008. for ( let i = 0; i < this.animations.length; i ++ ) {
  11009. const animation = this.animations[ i ];
  11010. object.animations.push( serialize( meta.animations, animation ) );
  11011. }
  11012. }
  11013. if ( isRootObject ) {
  11014. const geometries = extractFromCache( meta.geometries );
  11015. const materials = extractFromCache( meta.materials );
  11016. const textures = extractFromCache( meta.textures );
  11017. const images = extractFromCache( meta.images );
  11018. const shapes = extractFromCache( meta.shapes );
  11019. const skeletons = extractFromCache( meta.skeletons );
  11020. const animations = extractFromCache( meta.animations );
  11021. const nodes = extractFromCache( meta.nodes );
  11022. if ( geometries.length > 0 ) output.geometries = geometries;
  11023. if ( materials.length > 0 ) output.materials = materials;
  11024. if ( textures.length > 0 ) output.textures = textures;
  11025. if ( images.length > 0 ) output.images = images;
  11026. if ( shapes.length > 0 ) output.shapes = shapes;
  11027. if ( skeletons.length > 0 ) output.skeletons = skeletons;
  11028. if ( animations.length > 0 ) output.animations = animations;
  11029. if ( nodes.length > 0 ) output.nodes = nodes;
  11030. }
  11031. output.object = object;
  11032. return output;
  11033. // extract data from the cache hash
  11034. // remove metadata on each item
  11035. // and return as array
  11036. function extractFromCache( cache ) {
  11037. const values = [];
  11038. for ( const key in cache ) {
  11039. const data = cache[ key ];
  11040. delete data.metadata;
  11041. values.push( data );
  11042. }
  11043. return values;
  11044. }
  11045. }
  11046. /**
  11047. * Returns a new 3D object with copied values from this instance.
  11048. *
  11049. * @param {boolean} [recursive=true] - When set to `true`, descendants of the 3D object are also cloned.
  11050. * @return {Object3D} A clone of this instance.
  11051. */
  11052. clone( recursive ) {
  11053. return new this.constructor().copy( this, recursive );
  11054. }
  11055. /**
  11056. * Copies the values of the given 3D object to this instance.
  11057. *
  11058. * @param {Object3D} source - The 3D object to copy.
  11059. * @param {boolean} [recursive=true] - When set to `true`, descendants of the 3D object are cloned.
  11060. * @return {Object3D} A reference to this instance.
  11061. */
  11062. copy( source, recursive = true ) {
  11063. this.name = source.name;
  11064. this.up.copy( source.up );
  11065. this.position.copy( source.position );
  11066. this.rotation.order = source.rotation.order;
  11067. this.quaternion.copy( source.quaternion );
  11068. this.scale.copy( source.scale );
  11069. this.matrix.copy( source.matrix );
  11070. this.matrixWorld.copy( source.matrixWorld );
  11071. this.matrixAutoUpdate = source.matrixAutoUpdate;
  11072. this.matrixWorldAutoUpdate = source.matrixWorldAutoUpdate;
  11073. this.matrixWorldNeedsUpdate = source.matrixWorldNeedsUpdate;
  11074. this.layers.mask = source.layers.mask;
  11075. this.visible = source.visible;
  11076. this.castShadow = source.castShadow;
  11077. this.receiveShadow = source.receiveShadow;
  11078. this.frustumCulled = source.frustumCulled;
  11079. this.renderOrder = source.renderOrder;
  11080. this.animations = source.animations.slice();
  11081. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  11082. if ( recursive === true ) {
  11083. for ( let i = 0; i < source.children.length; i ++ ) {
  11084. const child = source.children[ i ];
  11085. this.add( child.clone() );
  11086. }
  11087. }
  11088. return this;
  11089. }
  11090. }
  11091. /**
  11092. * The default up direction for objects, also used as the default
  11093. * position for {@link DirectionalLight} and {@link HemisphereLight}.
  11094. *
  11095. * @static
  11096. * @type {Vector3}
  11097. * @default (0,1,0)
  11098. */
  11099. Object3D.DEFAULT_UP = /*@__PURE__*/ new Vector3( 0, 1, 0 );
  11100. /**
  11101. * The default setting for {@link Object3D#matrixAutoUpdate} for
  11102. * newly created 3D objects.
  11103. *
  11104. * @static
  11105. * @type {boolean}
  11106. * @default true
  11107. */
  11108. Object3D.DEFAULT_MATRIX_AUTO_UPDATE = true;
  11109. /**
  11110. * The default setting for {@link Object3D#matrixWorldAutoUpdate} for
  11111. * newly created 3D objects.
  11112. *
  11113. * @static
  11114. * @type {boolean}
  11115. * @default true
  11116. */
  11117. Object3D.DEFAULT_MATRIX_WORLD_AUTO_UPDATE = true;
  11118. const _v0$1 = /*@__PURE__*/ new Vector3();
  11119. const _v1$3 = /*@__PURE__*/ new Vector3();
  11120. const _v2$2 = /*@__PURE__*/ new Vector3();
  11121. const _v3$2 = /*@__PURE__*/ new Vector3();
  11122. const _vab = /*@__PURE__*/ new Vector3();
  11123. const _vac = /*@__PURE__*/ new Vector3();
  11124. const _vbc = /*@__PURE__*/ new Vector3();
  11125. const _vap = /*@__PURE__*/ new Vector3();
  11126. const _vbp = /*@__PURE__*/ new Vector3();
  11127. const _vcp = /*@__PURE__*/ new Vector3();
  11128. const _v40 = /*@__PURE__*/ new Vector4();
  11129. const _v41 = /*@__PURE__*/ new Vector4();
  11130. const _v42 = /*@__PURE__*/ new Vector4();
  11131. /**
  11132. * A geometric triangle as defined by three vectors representing its three corners.
  11133. */
  11134. class Triangle {
  11135. /**
  11136. * Constructs a new triangle.
  11137. *
  11138. * @param {Vector3} [a=(0,0,0)] - The first corner of the triangle.
  11139. * @param {Vector3} [b=(0,0,0)] - The second corner of the triangle.
  11140. * @param {Vector3} [c=(0,0,0)] - The third corner of the triangle.
  11141. */
  11142. constructor( a = new Vector3(), b = new Vector3(), c = new Vector3() ) {
  11143. /**
  11144. * The first corner of the triangle.
  11145. *
  11146. * @type {Vector3}
  11147. */
  11148. this.a = a;
  11149. /**
  11150. * The second corner of the triangle.
  11151. *
  11152. * @type {Vector3}
  11153. */
  11154. this.b = b;
  11155. /**
  11156. * The third corner of the triangle.
  11157. *
  11158. * @type {Vector3}
  11159. */
  11160. this.c = c;
  11161. }
  11162. /**
  11163. * Computes the normal vector of a triangle.
  11164. *
  11165. * @param {Vector3} a - The first corner of the triangle.
  11166. * @param {Vector3} b - The second corner of the triangle.
  11167. * @param {Vector3} c - The third corner of the triangle.
  11168. * @param {Vector3} target - The target vector that is used to store the method's result.
  11169. * @return {Vector3} The triangle's normal.
  11170. */
  11171. static getNormal( a, b, c, target ) {
  11172. target.subVectors( c, b );
  11173. _v0$1.subVectors( a, b );
  11174. target.cross( _v0$1 );
  11175. const targetLengthSq = target.lengthSq();
  11176. if ( targetLengthSq > 0 ) {
  11177. return target.multiplyScalar( 1 / Math.sqrt( targetLengthSq ) );
  11178. }
  11179. return target.set( 0, 0, 0 );
  11180. }
  11181. /**
  11182. * Computes a barycentric coordinates from the given vector.
  11183. * Returns `null` if the triangle is degenerate.
  11184. *
  11185. * @param {Vector3} point - A point in 3D space.
  11186. * @param {Vector3} a - The first corner of the triangle.
  11187. * @param {Vector3} b - The second corner of the triangle.
  11188. * @param {Vector3} c - The third corner of the triangle.
  11189. * @param {Vector3} target - The target vector that is used to store the method's result.
  11190. * @return {?Vector3} The barycentric coordinates for the given point
  11191. */
  11192. static getBarycoord( point, a, b, c, target ) {
  11193. // based on: http://www.blackpawn.com/texts/pointinpoly/default.html
  11194. _v0$1.subVectors( c, a );
  11195. _v1$3.subVectors( b, a );
  11196. _v2$2.subVectors( point, a );
  11197. const dot00 = _v0$1.dot( _v0$1 );
  11198. const dot01 = _v0$1.dot( _v1$3 );
  11199. const dot02 = _v0$1.dot( _v2$2 );
  11200. const dot11 = _v1$3.dot( _v1$3 );
  11201. const dot12 = _v1$3.dot( _v2$2 );
  11202. const denom = ( dot00 * dot11 - dot01 * dot01 );
  11203. // collinear or singular triangle
  11204. if ( denom === 0 ) {
  11205. target.set( 0, 0, 0 );
  11206. return null;
  11207. }
  11208. const invDenom = 1 / denom;
  11209. const u = ( dot11 * dot02 - dot01 * dot12 ) * invDenom;
  11210. const v = ( dot00 * dot12 - dot01 * dot02 ) * invDenom;
  11211. // barycentric coordinates must always sum to 1
  11212. return target.set( 1 - u - v, v, u );
  11213. }
  11214. /**
  11215. * Returns `true` if the given point, when projected onto the plane of the
  11216. * triangle, lies within the triangle.
  11217. *
  11218. * @param {Vector3} point - The point in 3D space to test.
  11219. * @param {Vector3} a - The first corner of the triangle.
  11220. * @param {Vector3} b - The second corner of the triangle.
  11221. * @param {Vector3} c - The third corner of the triangle.
  11222. * @return {boolean} Whether the given point, when projected onto the plane of the
  11223. * triangle, lies within the triangle or not.
  11224. */
  11225. static containsPoint( point, a, b, c ) {
  11226. // if the triangle is degenerate then we can't contain a point
  11227. if ( this.getBarycoord( point, a, b, c, _v3$2 ) === null ) {
  11228. return false;
  11229. }
  11230. return ( _v3$2.x >= 0 ) && ( _v3$2.y >= 0 ) && ( ( _v3$2.x + _v3$2.y ) <= 1 );
  11231. }
  11232. /**
  11233. * Computes the value barycentrically interpolated for the given point on the
  11234. * triangle. Returns `null` if the triangle is degenerate.
  11235. *
  11236. * @param {Vector3} point - Position of interpolated point.
  11237. * @param {Vector3} p1 - The first corner of the triangle.
  11238. * @param {Vector3} p2 - The second corner of the triangle.
  11239. * @param {Vector3} p3 - The third corner of the triangle.
  11240. * @param {Vector3} v1 - Value to interpolate of first vertex.
  11241. * @param {Vector3} v2 - Value to interpolate of second vertex.
  11242. * @param {Vector3} v3 - Value to interpolate of third vertex.
  11243. * @param {Vector3} target - The target vector that is used to store the method's result.
  11244. * @return {?Vector3} The interpolated value.
  11245. */
  11246. static getInterpolation( point, p1, p2, p3, v1, v2, v3, target ) {
  11247. if ( this.getBarycoord( point, p1, p2, p3, _v3$2 ) === null ) {
  11248. target.x = 0;
  11249. target.y = 0;
  11250. if ( 'z' in target ) target.z = 0;
  11251. if ( 'w' in target ) target.w = 0;
  11252. return null;
  11253. }
  11254. target.setScalar( 0 );
  11255. target.addScaledVector( v1, _v3$2.x );
  11256. target.addScaledVector( v2, _v3$2.y );
  11257. target.addScaledVector( v3, _v3$2.z );
  11258. return target;
  11259. }
  11260. /**
  11261. * Computes the value barycentrically interpolated for the given attribute and indices.
  11262. *
  11263. * @param {BufferAttribute} attr - The attribute to interpolate.
  11264. * @param {number} i1 - Index of first vertex.
  11265. * @param {number} i2 - Index of second vertex.
  11266. * @param {number} i3 - Index of third vertex.
  11267. * @param {Vector3} barycoord - The barycoordinate value to use to interpolate.
  11268. * @param {Vector3} target - The target vector that is used to store the method's result.
  11269. * @return {Vector3} The interpolated attribute value.
  11270. */
  11271. static getInterpolatedAttribute( attr, i1, i2, i3, barycoord, target ) {
  11272. _v40.setScalar( 0 );
  11273. _v41.setScalar( 0 );
  11274. _v42.setScalar( 0 );
  11275. _v40.fromBufferAttribute( attr, i1 );
  11276. _v41.fromBufferAttribute( attr, i2 );
  11277. _v42.fromBufferAttribute( attr, i3 );
  11278. target.setScalar( 0 );
  11279. target.addScaledVector( _v40, barycoord.x );
  11280. target.addScaledVector( _v41, barycoord.y );
  11281. target.addScaledVector( _v42, barycoord.z );
  11282. return target;
  11283. }
  11284. /**
  11285. * Returns `true` if the triangle is oriented towards the given direction.
  11286. *
  11287. * @param {Vector3} a - The first corner of the triangle.
  11288. * @param {Vector3} b - The second corner of the triangle.
  11289. * @param {Vector3} c - The third corner of the triangle.
  11290. * @param {Vector3} direction - The (normalized) direction vector.
  11291. * @return {boolean} Whether the triangle is oriented towards the given direction or not.
  11292. */
  11293. static isFrontFacing( a, b, c, direction ) {
  11294. _v0$1.subVectors( c, b );
  11295. _v1$3.subVectors( a, b );
  11296. // strictly front facing
  11297. return ( _v0$1.cross( _v1$3 ).dot( direction ) < 0 ) ? true : false;
  11298. }
  11299. /**
  11300. * Sets the triangle's vertices by copying the given values.
  11301. *
  11302. * @param {Vector3} a - The first corner of the triangle.
  11303. * @param {Vector3} b - The second corner of the triangle.
  11304. * @param {Vector3} c - The third corner of the triangle.
  11305. * @return {Triangle} A reference to this triangle.
  11306. */
  11307. set( a, b, c ) {
  11308. this.a.copy( a );
  11309. this.b.copy( b );
  11310. this.c.copy( c );
  11311. return this;
  11312. }
  11313. /**
  11314. * Sets the triangle's vertices by copying the given array values.
  11315. *
  11316. * @param {Array<Vector3>} points - An array with 3D points.
  11317. * @param {number} i0 - The array index representing the first corner of the triangle.
  11318. * @param {number} i1 - The array index representing the second corner of the triangle.
  11319. * @param {number} i2 - The array index representing the third corner of the triangle.
  11320. * @return {Triangle} A reference to this triangle.
  11321. */
  11322. setFromPointsAndIndices( points, i0, i1, i2 ) {
  11323. this.a.copy( points[ i0 ] );
  11324. this.b.copy( points[ i1 ] );
  11325. this.c.copy( points[ i2 ] );
  11326. return this;
  11327. }
  11328. /**
  11329. * Sets the triangle's vertices by copying the given attribute values.
  11330. *
  11331. * @param {BufferAttribute} attribute - A buffer attribute with 3D points data.
  11332. * @param {number} i0 - The attribute index representing the first corner of the triangle.
  11333. * @param {number} i1 - The attribute index representing the second corner of the triangle.
  11334. * @param {number} i2 - The attribute index representing the third corner of the triangle.
  11335. * @return {Triangle} A reference to this triangle.
  11336. */
  11337. setFromAttributeAndIndices( attribute, i0, i1, i2 ) {
  11338. this.a.fromBufferAttribute( attribute, i0 );
  11339. this.b.fromBufferAttribute( attribute, i1 );
  11340. this.c.fromBufferAttribute( attribute, i2 );
  11341. return this;
  11342. }
  11343. /**
  11344. * Returns a new triangle with copied values from this instance.
  11345. *
  11346. * @return {Triangle} A clone of this instance.
  11347. */
  11348. clone() {
  11349. return new this.constructor().copy( this );
  11350. }
  11351. /**
  11352. * Copies the values of the given triangle to this instance.
  11353. *
  11354. * @param {Triangle} triangle - The triangle to copy.
  11355. * @return {Triangle} A reference to this triangle.
  11356. */
  11357. copy( triangle ) {
  11358. this.a.copy( triangle.a );
  11359. this.b.copy( triangle.b );
  11360. this.c.copy( triangle.c );
  11361. return this;
  11362. }
  11363. /**
  11364. * Computes the area of the triangle.
  11365. *
  11366. * @return {number} The triangle's area.
  11367. */
  11368. getArea() {
  11369. _v0$1.subVectors( this.c, this.b );
  11370. _v1$3.subVectors( this.a, this.b );
  11371. return _v0$1.cross( _v1$3 ).length() * 0.5;
  11372. }
  11373. /**
  11374. * Computes the midpoint of the triangle.
  11375. *
  11376. * @param {Vector3} target - The target vector that is used to store the method's result.
  11377. * @return {Vector3} The triangle's midpoint.
  11378. */
  11379. getMidpoint( target ) {
  11380. return target.addVectors( this.a, this.b ).add( this.c ).multiplyScalar( 1 / 3 );
  11381. }
  11382. /**
  11383. * Computes the normal of the triangle.
  11384. *
  11385. * @param {Vector3} target - The target vector that is used to store the method's result.
  11386. * @return {Vector3} The triangle's normal.
  11387. */
  11388. getNormal( target ) {
  11389. return Triangle.getNormal( this.a, this.b, this.c, target );
  11390. }
  11391. /**
  11392. * Computes a plane the triangle lies within.
  11393. *
  11394. * @param {Plane} target - The target vector that is used to store the method's result.
  11395. * @return {Plane} The plane the triangle lies within.
  11396. */
  11397. getPlane( target ) {
  11398. return target.setFromCoplanarPoints( this.a, this.b, this.c );
  11399. }
  11400. /**
  11401. * Computes a barycentric coordinates from the given vector.
  11402. * Returns `null` if the triangle is degenerate.
  11403. *
  11404. * @param {Vector3} point - A point in 3D space.
  11405. * @param {Vector3} target - The target vector that is used to store the method's result.
  11406. * @return {?Vector3} The barycentric coordinates for the given point
  11407. */
  11408. getBarycoord( point, target ) {
  11409. return Triangle.getBarycoord( point, this.a, this.b, this.c, target );
  11410. }
  11411. /**
  11412. * Computes the value barycentrically interpolated for the given point on the
  11413. * triangle. Returns `null` if the triangle is degenerate.
  11414. *
  11415. * @param {Vector3} point - Position of interpolated point.
  11416. * @param {Vector3} v1 - Value to interpolate of first vertex.
  11417. * @param {Vector3} v2 - Value to interpolate of second vertex.
  11418. * @param {Vector3} v3 - Value to interpolate of third vertex.
  11419. * @param {Vector3} target - The target vector that is used to store the method's result.
  11420. * @return {?Vector3} The interpolated value.
  11421. */
  11422. getInterpolation( point, v1, v2, v3, target ) {
  11423. return Triangle.getInterpolation( point, this.a, this.b, this.c, v1, v2, v3, target );
  11424. }
  11425. /**
  11426. * Returns `true` if the given point, when projected onto the plane of the
  11427. * triangle, lies within the triangle.
  11428. *
  11429. * @param {Vector3} point - The point in 3D space to test.
  11430. * @return {boolean} Whether the given point, when projected onto the plane of the
  11431. * triangle, lies within the triangle or not.
  11432. */
  11433. containsPoint( point ) {
  11434. return Triangle.containsPoint( point, this.a, this.b, this.c );
  11435. }
  11436. /**
  11437. * Returns `true` if the triangle is oriented towards the given direction.
  11438. *
  11439. * @param {Vector3} direction - The (normalized) direction vector.
  11440. * @return {boolean} Whether the triangle is oriented towards the given direction or not.
  11441. */
  11442. isFrontFacing( direction ) {
  11443. return Triangle.isFrontFacing( this.a, this.b, this.c, direction );
  11444. }
  11445. /**
  11446. * Returns `true` if this triangle intersects with the given box.
  11447. *
  11448. * @param {Box3} box - The box to intersect.
  11449. * @return {boolean} Whether this triangle intersects with the given box or not.
  11450. */
  11451. intersectsBox( box ) {
  11452. return box.intersectsTriangle( this );
  11453. }
  11454. /**
  11455. * Returns the closest point on the triangle to the given point.
  11456. *
  11457. * @param {Vector3} p - The point to compute the closest point for.
  11458. * @param {Vector3} target - The target vector that is used to store the method's result.
  11459. * @return {Vector3} The closest point on the triangle.
  11460. */
  11461. closestPointToPoint( p, target ) {
  11462. const a = this.a, b = this.b, c = this.c;
  11463. let v, w;
  11464. // algorithm thanks to Real-Time Collision Detection by Christer Ericson,
  11465. // published by Morgan Kaufmann Publishers, (c) 2005 Elsevier Inc.,
  11466. // under the accompanying license; see chapter 5.1.5 for detailed explanation.
  11467. // basically, we're distinguishing which of the voronoi regions of the triangle
  11468. // the point lies in with the minimum amount of redundant computation.
  11469. _vab.subVectors( b, a );
  11470. _vac.subVectors( c, a );
  11471. _vap.subVectors( p, a );
  11472. const d1 = _vab.dot( _vap );
  11473. const d2 = _vac.dot( _vap );
  11474. if ( d1 <= 0 && d2 <= 0 ) {
  11475. // vertex region of A; barycentric coords (1, 0, 0)
  11476. return target.copy( a );
  11477. }
  11478. _vbp.subVectors( p, b );
  11479. const d3 = _vab.dot( _vbp );
  11480. const d4 = _vac.dot( _vbp );
  11481. if ( d3 >= 0 && d4 <= d3 ) {
  11482. // vertex region of B; barycentric coords (0, 1, 0)
  11483. return target.copy( b );
  11484. }
  11485. const vc = d1 * d4 - d3 * d2;
  11486. if ( vc <= 0 && d1 >= 0 && d3 <= 0 ) {
  11487. v = d1 / ( d1 - d3 );
  11488. // edge region of AB; barycentric coords (1-v, v, 0)
  11489. return target.copy( a ).addScaledVector( _vab, v );
  11490. }
  11491. _vcp.subVectors( p, c );
  11492. const d5 = _vab.dot( _vcp );
  11493. const d6 = _vac.dot( _vcp );
  11494. if ( d6 >= 0 && d5 <= d6 ) {
  11495. // vertex region of C; barycentric coords (0, 0, 1)
  11496. return target.copy( c );
  11497. }
  11498. const vb = d5 * d2 - d1 * d6;
  11499. if ( vb <= 0 && d2 >= 0 && d6 <= 0 ) {
  11500. w = d2 / ( d2 - d6 );
  11501. // edge region of AC; barycentric coords (1-w, 0, w)
  11502. return target.copy( a ).addScaledVector( _vac, w );
  11503. }
  11504. const va = d3 * d6 - d5 * d4;
  11505. if ( va <= 0 && ( d4 - d3 ) >= 0 && ( d5 - d6 ) >= 0 ) {
  11506. _vbc.subVectors( c, b );
  11507. w = ( d4 - d3 ) / ( ( d4 - d3 ) + ( d5 - d6 ) );
  11508. // edge region of BC; barycentric coords (0, 1-w, w)
  11509. return target.copy( b ).addScaledVector( _vbc, w ); // edge region of BC
  11510. }
  11511. // face region
  11512. const denom = 1 / ( va + vb + vc );
  11513. // u = va * denom
  11514. v = vb * denom;
  11515. w = vc * denom;
  11516. return target.copy( a ).addScaledVector( _vab, v ).addScaledVector( _vac, w );
  11517. }
  11518. /**
  11519. * Returns `true` if this triangle is equal with the given one.
  11520. *
  11521. * @param {Triangle} triangle - The triangle to test for equality.
  11522. * @return {boolean} Whether this triangle is equal with the given one.
  11523. */
  11524. equals( triangle ) {
  11525. return triangle.a.equals( this.a ) && triangle.b.equals( this.b ) && triangle.c.equals( this.c );
  11526. }
  11527. }
  11528. const _colorKeywords = { 'aliceblue': 0xF0F8FF, 'antiquewhite': 0xFAEBD7, 'aqua': 0x00FFFF, 'aquamarine': 0x7FFFD4, 'azure': 0xF0FFFF,
  11529. 'beige': 0xF5F5DC, 'bisque': 0xFFE4C4, 'black': 0x000000, 'blanchedalmond': 0xFFEBCD, 'blue': 0x0000FF, 'blueviolet': 0x8A2BE2,
  11530. 'brown': 0xA52A2A, 'burlywood': 0xDEB887, 'cadetblue': 0x5F9EA0, 'chartreuse': 0x7FFF00, 'chocolate': 0xD2691E, 'coral': 0xFF7F50,
  11531. 'cornflowerblue': 0x6495ED, 'cornsilk': 0xFFF8DC, 'crimson': 0xDC143C, 'cyan': 0x00FFFF, 'darkblue': 0x00008B, 'darkcyan': 0x008B8B,
  11532. 'darkgoldenrod': 0xB8860B, 'darkgray': 0xA9A9A9, 'darkgreen': 0x006400, 'darkgrey': 0xA9A9A9, 'darkkhaki': 0xBDB76B, 'darkmagenta': 0x8B008B,
  11533. 'darkolivegreen': 0x556B2F, 'darkorange': 0xFF8C00, 'darkorchid': 0x9932CC, 'darkred': 0x8B0000, 'darksalmon': 0xE9967A, 'darkseagreen': 0x8FBC8F,
  11534. 'darkslateblue': 0x483D8B, 'darkslategray': 0x2F4F4F, 'darkslategrey': 0x2F4F4F, 'darkturquoise': 0x00CED1, 'darkviolet': 0x9400D3,
  11535. 'deeppink': 0xFF1493, 'deepskyblue': 0x00BFFF, 'dimgray': 0x696969, 'dimgrey': 0x696969, 'dodgerblue': 0x1E90FF, 'firebrick': 0xB22222,
  11536. 'floralwhite': 0xFFFAF0, 'forestgreen': 0x228B22, 'fuchsia': 0xFF00FF, 'gainsboro': 0xDCDCDC, 'ghostwhite': 0xF8F8FF, 'gold': 0xFFD700,
  11537. 'goldenrod': 0xDAA520, 'gray': 0x808080, 'green': 0x008000, 'greenyellow': 0xADFF2F, 'grey': 0x808080, 'honeydew': 0xF0FFF0, 'hotpink': 0xFF69B4,
  11538. 'indianred': 0xCD5C5C, 'indigo': 0x4B0082, 'ivory': 0xFFFFF0, 'khaki': 0xF0E68C, 'lavender': 0xE6E6FA, 'lavenderblush': 0xFFF0F5, 'lawngreen': 0x7CFC00,
  11539. 'lemonchiffon': 0xFFFACD, 'lightblue': 0xADD8E6, 'lightcoral': 0xF08080, 'lightcyan': 0xE0FFFF, 'lightgoldenrodyellow': 0xFAFAD2, 'lightgray': 0xD3D3D3,
  11540. 'lightgreen': 0x90EE90, 'lightgrey': 0xD3D3D3, 'lightpink': 0xFFB6C1, 'lightsalmon': 0xFFA07A, 'lightseagreen': 0x20B2AA, 'lightskyblue': 0x87CEFA,
  11541. 'lightslategray': 0x778899, 'lightslategrey': 0x778899, 'lightsteelblue': 0xB0C4DE, 'lightyellow': 0xFFFFE0, 'lime': 0x00FF00, 'limegreen': 0x32CD32,
  11542. 'linen': 0xFAF0E6, 'magenta': 0xFF00FF, 'maroon': 0x800000, 'mediumaquamarine': 0x66CDAA, 'mediumblue': 0x0000CD, 'mediumorchid': 0xBA55D3,
  11543. 'mediumpurple': 0x9370DB, 'mediumseagreen': 0x3CB371, 'mediumslateblue': 0x7B68EE, 'mediumspringgreen': 0x00FA9A, 'mediumturquoise': 0x48D1CC,
  11544. 'mediumvioletred': 0xC71585, 'midnightblue': 0x191970, 'mintcream': 0xF5FFFA, 'mistyrose': 0xFFE4E1, 'moccasin': 0xFFE4B5, 'navajowhite': 0xFFDEAD,
  11545. 'navy': 0x000080, 'oldlace': 0xFDF5E6, 'olive': 0x808000, 'olivedrab': 0x6B8E23, 'orange': 0xFFA500, 'orangered': 0xFF4500, 'orchid': 0xDA70D6,
  11546. 'palegoldenrod': 0xEEE8AA, 'palegreen': 0x98FB98, 'paleturquoise': 0xAFEEEE, 'palevioletred': 0xDB7093, 'papayawhip': 0xFFEFD5, 'peachpuff': 0xFFDAB9,
  11547. 'peru': 0xCD853F, 'pink': 0xFFC0CB, 'plum': 0xDDA0DD, 'powderblue': 0xB0E0E6, 'purple': 0x800080, 'rebeccapurple': 0x663399, 'red': 0xFF0000, 'rosybrown': 0xBC8F8F,
  11548. 'royalblue': 0x4169E1, 'saddlebrown': 0x8B4513, 'salmon': 0xFA8072, 'sandybrown': 0xF4A460, 'seagreen': 0x2E8B57, 'seashell': 0xFFF5EE,
  11549. 'sienna': 0xA0522D, 'silver': 0xC0C0C0, 'skyblue': 0x87CEEB, 'slateblue': 0x6A5ACD, 'slategray': 0x708090, 'slategrey': 0x708090, 'snow': 0xFFFAFA,
  11550. 'springgreen': 0x00FF7F, 'steelblue': 0x4682B4, 'tan': 0xD2B48C, 'teal': 0x008080, 'thistle': 0xD8BFD8, 'tomato': 0xFF6347, 'turquoise': 0x40E0D0,
  11551. 'violet': 0xEE82EE, 'wheat': 0xF5DEB3, 'white': 0xFFFFFF, 'whitesmoke': 0xF5F5F5, 'yellow': 0xFFFF00, 'yellowgreen': 0x9ACD32 };
  11552. const _hslA = { h: 0, s: 0, l: 0 };
  11553. const _hslB = { h: 0, s: 0, l: 0 };
  11554. function hue2rgb( p, q, t ) {
  11555. if ( t < 0 ) t += 1;
  11556. if ( t > 1 ) t -= 1;
  11557. if ( t < 1 / 6 ) return p + ( q - p ) * 6 * t;
  11558. if ( t < 1 / 2 ) return q;
  11559. if ( t < 2 / 3 ) return p + ( q - p ) * 6 * ( 2 / 3 - t );
  11560. return p;
  11561. }
  11562. /**
  11563. * A Color instance is represented by RGB components in the linear <i>working
  11564. * color space</i>, which defaults to `LinearSRGBColorSpace`. Inputs
  11565. * conventionally using `SRGBColorSpace` (such as hexadecimals and CSS
  11566. * strings) are converted to the working color space automatically.
  11567. *
  11568. * ```js
  11569. * // converted automatically from SRGBColorSpace to LinearSRGBColorSpace
  11570. * const color = new THREE.Color().setHex( 0x112233 );
  11571. * ```
  11572. * Source color spaces may be specified explicitly, to ensure correct conversions.
  11573. * ```js
  11574. * // assumed already LinearSRGBColorSpace; no conversion
  11575. * const color = new THREE.Color().setRGB( 0.5, 0.5, 0.5 );
  11576. *
  11577. * // converted explicitly from SRGBColorSpace to LinearSRGBColorSpace
  11578. * const color = new THREE.Color().setRGB( 0.5, 0.5, 0.5, SRGBColorSpace );
  11579. * ```
  11580. * If THREE.ColorManagement is disabled, no conversions occur. For details,
  11581. * see <i>Color management</i>. Iterating through a Color instance will yield
  11582. * its components (r, g, b) in the corresponding order. A Color can be initialised
  11583. * in any of the following ways:
  11584. * ```js
  11585. * //empty constructor - will default white
  11586. * const color1 = new THREE.Color();
  11587. *
  11588. * //Hexadecimal color (recommended)
  11589. * const color2 = new THREE.Color( 0xff0000 );
  11590. *
  11591. * //RGB string
  11592. * const color3 = new THREE.Color("rgb(255, 0, 0)");
  11593. * const color4 = new THREE.Color("rgb(100%, 0%, 0%)");
  11594. *
  11595. * //X11 color name - all 140 color names are supported.
  11596. * //Note the lack of CamelCase in the name
  11597. * const color5 = new THREE.Color( 'skyblue' );
  11598. * //HSL string
  11599. * const color6 = new THREE.Color("hsl(0, 100%, 50%)");
  11600. *
  11601. * //Separate RGB values between 0 and 1
  11602. * const color7 = new THREE.Color( 1, 0, 0 );
  11603. * ```
  11604. */
  11605. class Color {
  11606. /**
  11607. * Constructs a new color.
  11608. *
  11609. * Note that standard method of specifying color in three.js is with a hexadecimal triplet,
  11610. * and that method is used throughout the rest of the documentation.
  11611. *
  11612. * @param {(number|string|Color)} [r] - The red component of the color. If `g` and `b` are
  11613. * not provided, it can be hexadecimal triplet, a CSS-style string or another `Color` instance.
  11614. * @param {number} [g] - The green component.
  11615. * @param {number} [b] - The blue component.
  11616. */
  11617. constructor( r, g, b ) {
  11618. /**
  11619. * This flag can be used for type testing.
  11620. *
  11621. * @type {boolean}
  11622. * @readonly
  11623. * @default true
  11624. */
  11625. this.isColor = true;
  11626. /**
  11627. * The red component.
  11628. *
  11629. * @type {number}
  11630. * @default 1
  11631. */
  11632. this.r = 1;
  11633. /**
  11634. * The green component.
  11635. *
  11636. * @type {number}
  11637. * @default 1
  11638. */
  11639. this.g = 1;
  11640. /**
  11641. * The blue component.
  11642. *
  11643. * @type {number}
  11644. * @default 1
  11645. */
  11646. this.b = 1;
  11647. return this.set( r, g, b );
  11648. }
  11649. /**
  11650. * Sets the colors's components from the given values.
  11651. *
  11652. * @param {(number|string|Color)} [r] - The red component of the color. If `g` and `b` are
  11653. * not provided, it can be hexadecimal triplet, a CSS-style string or another `Color` instance.
  11654. * @param {number} [g] - The green component.
  11655. * @param {number} [b] - The blue component.
  11656. * @return {Color} A reference to this color.
  11657. */
  11658. set( r, g, b ) {
  11659. if ( g === undefined && b === undefined ) {
  11660. // r is THREE.Color, hex or string
  11661. const value = r;
  11662. if ( value && value.isColor ) {
  11663. this.copy( value );
  11664. } else if ( typeof value === 'number' ) {
  11665. this.setHex( value );
  11666. } else if ( typeof value === 'string' ) {
  11667. this.setStyle( value );
  11668. }
  11669. } else {
  11670. this.setRGB( r, g, b );
  11671. }
  11672. return this;
  11673. }
  11674. /**
  11675. * Sets the colors's components to the given scalar value.
  11676. *
  11677. * @param {number} scalar - The scalar value.
  11678. * @return {Color} A reference to this color.
  11679. */
  11680. setScalar( scalar ) {
  11681. this.r = scalar;
  11682. this.g = scalar;
  11683. this.b = scalar;
  11684. return this;
  11685. }
  11686. /**
  11687. * Sets this color from a hexadecimal value.
  11688. *
  11689. * @param {number} hex - The hexadecimal value.
  11690. * @param {string} [colorSpace=SRGBColorSpace] - The color space.
  11691. * @return {Color} A reference to this color.
  11692. */
  11693. setHex( hex, colorSpace = SRGBColorSpace ) {
  11694. hex = Math.floor( hex );
  11695. this.r = ( hex >> 16 & 255 ) / 255;
  11696. this.g = ( hex >> 8 & 255 ) / 255;
  11697. this.b = ( hex & 255 ) / 255;
  11698. ColorManagement.toWorkingColorSpace( this, colorSpace );
  11699. return this;
  11700. }
  11701. /**
  11702. * Sets this color from RGB values.
  11703. *
  11704. * @param {number} r - Red channel value between `0.0` and `1.0`.
  11705. * @param {number} g - Green channel value between `0.0` and `1.0`.
  11706. * @param {number} b - Blue channel value between `0.0` and `1.0`.
  11707. * @param {string} [colorSpace=ColorManagement.workingColorSpace] - The color space.
  11708. * @return {Color} A reference to this color.
  11709. */
  11710. setRGB( r, g, b, colorSpace = ColorManagement.workingColorSpace ) {
  11711. this.r = r;
  11712. this.g = g;
  11713. this.b = b;
  11714. ColorManagement.toWorkingColorSpace( this, colorSpace );
  11715. return this;
  11716. }
  11717. /**
  11718. * Sets this color from RGB values.
  11719. *
  11720. * @param {number} h - Hue value between `0.0` and `1.0`.
  11721. * @param {number} s - Saturation value between `0.0` and `1.0`.
  11722. * @param {number} l - Lightness value between `0.0` and `1.0`.
  11723. * @param {string} [colorSpace=ColorManagement.workingColorSpace] - The color space.
  11724. * @return {Color} A reference to this color.
  11725. */
  11726. setHSL( h, s, l, colorSpace = ColorManagement.workingColorSpace ) {
  11727. // h,s,l ranges are in 0.0 - 1.0
  11728. h = euclideanModulo( h, 1 );
  11729. s = clamp( s, 0, 1 );
  11730. l = clamp( l, 0, 1 );
  11731. if ( s === 0 ) {
  11732. this.r = this.g = this.b = l;
  11733. } else {
  11734. const p = l <= 0.5 ? l * ( 1 + s ) : l + s - ( l * s );
  11735. const q = ( 2 * l ) - p;
  11736. this.r = hue2rgb( q, p, h + 1 / 3 );
  11737. this.g = hue2rgb( q, p, h );
  11738. this.b = hue2rgb( q, p, h - 1 / 3 );
  11739. }
  11740. ColorManagement.toWorkingColorSpace( this, colorSpace );
  11741. return this;
  11742. }
  11743. /**
  11744. * Sets this color from a CSS-style string. For example, `rgb(250, 0,0)`,
  11745. * `rgb(100%, 0%, 0%)`, `hsl(0, 100%, 50%)`, `#ff0000`, `#f00`, or `red` ( or
  11746. * any [X11 color name]{@link https://en.wikipedia.org/wiki/X11_color_names#Color_name_chart} -
  11747. * all 140 color names are supported).
  11748. *
  11749. * @param {string} style - Color as a CSS-style string.
  11750. * @param {string} [colorSpace=SRGBColorSpace] - The color space.
  11751. * @return {Color} A reference to this color.
  11752. */
  11753. setStyle( style, colorSpace = SRGBColorSpace ) {
  11754. function handleAlpha( string ) {
  11755. if ( string === undefined ) return;
  11756. if ( parseFloat( string ) < 1 ) {
  11757. console.warn( 'THREE.Color: Alpha component of ' + style + ' will be ignored.' );
  11758. }
  11759. }
  11760. let m;
  11761. if ( m = /^(\w+)\(([^\)]*)\)/.exec( style ) ) {
  11762. // rgb / hsl
  11763. let color;
  11764. const name = m[ 1 ];
  11765. const components = m[ 2 ];
  11766. switch ( name ) {
  11767. case 'rgb':
  11768. case 'rgba':
  11769. if ( color = /^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) {
  11770. // rgb(255,0,0) rgba(255,0,0,0.5)
  11771. handleAlpha( color[ 4 ] );
  11772. return this.setRGB(
  11773. Math.min( 255, parseInt( color[ 1 ], 10 ) ) / 255,
  11774. Math.min( 255, parseInt( color[ 2 ], 10 ) ) / 255,
  11775. Math.min( 255, parseInt( color[ 3 ], 10 ) ) / 255,
  11776. colorSpace
  11777. );
  11778. }
  11779. if ( color = /^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) {
  11780. // rgb(100%,0%,0%) rgba(100%,0%,0%,0.5)
  11781. handleAlpha( color[ 4 ] );
  11782. return this.setRGB(
  11783. Math.min( 100, parseInt( color[ 1 ], 10 ) ) / 100,
  11784. Math.min( 100, parseInt( color[ 2 ], 10 ) ) / 100,
  11785. Math.min( 100, parseInt( color[ 3 ], 10 ) ) / 100,
  11786. colorSpace
  11787. );
  11788. }
  11789. break;
  11790. case 'hsl':
  11791. case 'hsla':
  11792. if ( color = /^\s*(\d*\.?\d+)\s*,\s*(\d*\.?\d+)\%\s*,\s*(\d*\.?\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) {
  11793. // hsl(120,50%,50%) hsla(120,50%,50%,0.5)
  11794. handleAlpha( color[ 4 ] );
  11795. return this.setHSL(
  11796. parseFloat( color[ 1 ] ) / 360,
  11797. parseFloat( color[ 2 ] ) / 100,
  11798. parseFloat( color[ 3 ] ) / 100,
  11799. colorSpace
  11800. );
  11801. }
  11802. break;
  11803. default:
  11804. console.warn( 'THREE.Color: Unknown color model ' + style );
  11805. }
  11806. } else if ( m = /^\#([A-Fa-f\d]+)$/.exec( style ) ) {
  11807. // hex color
  11808. const hex = m[ 1 ];
  11809. const size = hex.length;
  11810. if ( size === 3 ) {
  11811. // #ff0
  11812. return this.setRGB(
  11813. parseInt( hex.charAt( 0 ), 16 ) / 15,
  11814. parseInt( hex.charAt( 1 ), 16 ) / 15,
  11815. parseInt( hex.charAt( 2 ), 16 ) / 15,
  11816. colorSpace
  11817. );
  11818. } else if ( size === 6 ) {
  11819. // #ff0000
  11820. return this.setHex( parseInt( hex, 16 ), colorSpace );
  11821. } else {
  11822. console.warn( 'THREE.Color: Invalid hex color ' + style );
  11823. }
  11824. } else if ( style && style.length > 0 ) {
  11825. return this.setColorName( style, colorSpace );
  11826. }
  11827. return this;
  11828. }
  11829. /**
  11830. * Sets this color from a color name. Faster than {@link Color#setStyle} if
  11831. * you don't need the other CSS-style formats.
  11832. *
  11833. * For convenience, the list of names is exposed in `Color.NAMES` as a hash.
  11834. * ```js
  11835. * Color.NAMES.aliceblue // returns 0xF0F8FF
  11836. * ```
  11837. *
  11838. * @param {string} style - The color name.
  11839. * @param {string} [colorSpace=SRGBColorSpace] - The color space.
  11840. * @return {Color} A reference to this color.
  11841. */
  11842. setColorName( style, colorSpace = SRGBColorSpace ) {
  11843. // color keywords
  11844. const hex = _colorKeywords[ style.toLowerCase() ];
  11845. if ( hex !== undefined ) {
  11846. // red
  11847. this.setHex( hex, colorSpace );
  11848. } else {
  11849. // unknown color
  11850. console.warn( 'THREE.Color: Unknown color ' + style );
  11851. }
  11852. return this;
  11853. }
  11854. /**
  11855. * Returns a new color with copied values from this instance.
  11856. *
  11857. * @return {Color} A clone of this instance.
  11858. */
  11859. clone() {
  11860. return new this.constructor( this.r, this.g, this.b );
  11861. }
  11862. /**
  11863. * Copies the values of the given color to this instance.
  11864. *
  11865. * @param {Color} color - The color to copy.
  11866. * @return {Color} A reference to this color.
  11867. */
  11868. copy( color ) {
  11869. this.r = color.r;
  11870. this.g = color.g;
  11871. this.b = color.b;
  11872. return this;
  11873. }
  11874. /**
  11875. * Copies the given color into this color, and then converts this color from
  11876. * `SRGBColorSpace` to `LinearSRGBColorSpace`.
  11877. *
  11878. * @param {Color} color - The color to copy/convert.
  11879. * @return {Color} A reference to this color.
  11880. */
  11881. copySRGBToLinear( color ) {
  11882. this.r = SRGBToLinear( color.r );
  11883. this.g = SRGBToLinear( color.g );
  11884. this.b = SRGBToLinear( color.b );
  11885. return this;
  11886. }
  11887. /**
  11888. * Copies the given color into this color, and then converts this color from
  11889. * `LinearSRGBColorSpace` to `SRGBColorSpace`.
  11890. *
  11891. * @param {Color} color - The color to copy/convert.
  11892. * @return {Color} A reference to this color.
  11893. */
  11894. copyLinearToSRGB( color ) {
  11895. this.r = LinearToSRGB( color.r );
  11896. this.g = LinearToSRGB( color.g );
  11897. this.b = LinearToSRGB( color.b );
  11898. return this;
  11899. }
  11900. /**
  11901. * Converts this color from `SRGBColorSpace` to `LinearSRGBColorSpace`.
  11902. *
  11903. * @return {Color} A reference to this color.
  11904. */
  11905. convertSRGBToLinear() {
  11906. this.copySRGBToLinear( this );
  11907. return this;
  11908. }
  11909. /**
  11910. * Converts this color from `LinearSRGBColorSpace` to `SRGBColorSpace`.
  11911. *
  11912. * @return {Color} A reference to this color.
  11913. */
  11914. convertLinearToSRGB() {
  11915. this.copyLinearToSRGB( this );
  11916. return this;
  11917. }
  11918. /**
  11919. * Returns the hexadecimal value of this color.
  11920. *
  11921. * @param {string} [colorSpace=SRGBColorSpace] - The color space.
  11922. * @return {number} The hexadecimal value.
  11923. */
  11924. getHex( colorSpace = SRGBColorSpace ) {
  11925. ColorManagement.fromWorkingColorSpace( _color.copy( this ), colorSpace );
  11926. 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 ) );
  11927. }
  11928. /**
  11929. * Returns the hexadecimal value of this color as a string (for example, 'FFFFFF').
  11930. *
  11931. * @param {string} [colorSpace=SRGBColorSpace] - The color space.
  11932. * @return {string} The hexadecimal value as a string.
  11933. */
  11934. getHexString( colorSpace = SRGBColorSpace ) {
  11935. return ( '000000' + this.getHex( colorSpace ).toString( 16 ) ).slice( -6 );
  11936. }
  11937. /**
  11938. * Converts the colors RGB values into the HSL format and stores them into the
  11939. * given target object.
  11940. *
  11941. * @param {{h:number,s:number,l:number}} target - The target object that is used to store the method's result.
  11942. * @param {string} [colorSpace=ColorManagement.workingColorSpace] - The color space.
  11943. * @return {{h:number,s:number,l:number}} The HSL representation of this color.
  11944. */
  11945. getHSL( target, colorSpace = ColorManagement.workingColorSpace ) {
  11946. // h,s,l ranges are in 0.0 - 1.0
  11947. ColorManagement.fromWorkingColorSpace( _color.copy( this ), colorSpace );
  11948. const r = _color.r, g = _color.g, b = _color.b;
  11949. const max = Math.max( r, g, b );
  11950. const min = Math.min( r, g, b );
  11951. let hue, saturation;
  11952. const lightness = ( min + max ) / 2.0;
  11953. if ( min === max ) {
  11954. hue = 0;
  11955. saturation = 0;
  11956. } else {
  11957. const delta = max - min;
  11958. saturation = lightness <= 0.5 ? delta / ( max + min ) : delta / ( 2 - max - min );
  11959. switch ( max ) {
  11960. case r: hue = ( g - b ) / delta + ( g < b ? 6 : 0 ); break;
  11961. case g: hue = ( b - r ) / delta + 2; break;
  11962. case b: hue = ( r - g ) / delta + 4; break;
  11963. }
  11964. hue /= 6;
  11965. }
  11966. target.h = hue;
  11967. target.s = saturation;
  11968. target.l = lightness;
  11969. return target;
  11970. }
  11971. /**
  11972. * Returns the RGB values of this color and stores them into the given target object.
  11973. *
  11974. * @param {Color} target - The target color that is used to store the method's result.
  11975. * @param {string} [colorSpace=ColorManagement.workingColorSpace] - The color space.
  11976. * @return {Color} The RGB representation of this color.
  11977. */
  11978. getRGB( target, colorSpace = ColorManagement.workingColorSpace ) {
  11979. ColorManagement.fromWorkingColorSpace( _color.copy( this ), colorSpace );
  11980. target.r = _color.r;
  11981. target.g = _color.g;
  11982. target.b = _color.b;
  11983. return target;
  11984. }
  11985. /**
  11986. * Returns the value of this color as a CSS style string. Example: `rgb(255,0,0)`.
  11987. *
  11988. * @param {string} [colorSpace=SRGBColorSpace] - The color space.
  11989. * @return {string} The CSS representation of this color.
  11990. */
  11991. getStyle( colorSpace = SRGBColorSpace ) {
  11992. ColorManagement.fromWorkingColorSpace( _color.copy( this ), colorSpace );
  11993. const r = _color.r, g = _color.g, b = _color.b;
  11994. if ( colorSpace !== SRGBColorSpace ) {
  11995. // Requires CSS Color Module Level 4 (https://www.w3.org/TR/css-color-4/).
  11996. return `color(${ colorSpace } ${ r.toFixed( 3 ) } ${ g.toFixed( 3 ) } ${ b.toFixed( 3 ) })`;
  11997. }
  11998. return `rgb(${ Math.round( r * 255 ) },${ Math.round( g * 255 ) },${ Math.round( b * 255 ) })`;
  11999. }
  12000. /**
  12001. * Adds the given HSL values to this color's values.
  12002. * Internally, this converts the color's RGB values to HSL, adds HSL
  12003. * and then converts the color back to RGB.
  12004. *
  12005. * @param {number} h - Hue value between `0.0` and `1.0`.
  12006. * @param {number} s - Saturation value between `0.0` and `1.0`.
  12007. * @param {number} l - Lightness value between `0.0` and `1.0`.
  12008. * @return {Color} A reference to this color.
  12009. */
  12010. offsetHSL( h, s, l ) {
  12011. this.getHSL( _hslA );
  12012. return this.setHSL( _hslA.h + h, _hslA.s + s, _hslA.l + l );
  12013. }
  12014. /**
  12015. * Adds the RGB values of the given color to the RGB values of this color.
  12016. *
  12017. * @param {Color} color - The color to add.
  12018. * @return {Color} A reference to this color.
  12019. */
  12020. add( color ) {
  12021. this.r += color.r;
  12022. this.g += color.g;
  12023. this.b += color.b;
  12024. return this;
  12025. }
  12026. /**
  12027. * Adds the RGB values of the given colors and stores the result in this instance.
  12028. *
  12029. * @param {Color} color1 - The first color.
  12030. * @param {Color} color2 - The second color.
  12031. * @return {Color} A reference to this color.
  12032. */
  12033. addColors( color1, color2 ) {
  12034. this.r = color1.r + color2.r;
  12035. this.g = color1.g + color2.g;
  12036. this.b = color1.b + color2.b;
  12037. return this;
  12038. }
  12039. /**
  12040. * Adds the given scalar value to the RGB values of this color.
  12041. *
  12042. * @param {number} s - The scalar to add.
  12043. * @return {Color} A reference to this color.
  12044. */
  12045. addScalar( s ) {
  12046. this.r += s;
  12047. this.g += s;
  12048. this.b += s;
  12049. return this;
  12050. }
  12051. /**
  12052. * Subtracts the RGB values of the given color from the RGB values of this color.
  12053. *
  12054. * @param {Color} color - The color to subtract.
  12055. * @return {Color} A reference to this color.
  12056. */
  12057. sub( color ) {
  12058. this.r = Math.max( 0, this.r - color.r );
  12059. this.g = Math.max( 0, this.g - color.g );
  12060. this.b = Math.max( 0, this.b - color.b );
  12061. return this;
  12062. }
  12063. /**
  12064. * Multiplies the RGB values of the given color with the RGB values of this color.
  12065. *
  12066. * @param {Color} color - The color to multiply.
  12067. * @return {Color} A reference to this color.
  12068. */
  12069. multiply( color ) {
  12070. this.r *= color.r;
  12071. this.g *= color.g;
  12072. this.b *= color.b;
  12073. return this;
  12074. }
  12075. /**
  12076. * Multiplies the given scalar value with the RGB values of this color.
  12077. *
  12078. * @param {number} s - The scalar to multiply.
  12079. * @return {Color} A reference to this color.
  12080. */
  12081. multiplyScalar( s ) {
  12082. this.r *= s;
  12083. this.g *= s;
  12084. this.b *= s;
  12085. return this;
  12086. }
  12087. /**
  12088. * Linearly interpolates this color's RGB values toward the RGB values of the
  12089. * given color. The alpha argument can be thought of as the ratio between
  12090. * the two colors, where `0.0` is this color and `1.0` is the first argument.
  12091. *
  12092. * @param {Color} color - The color to converge on.
  12093. * @param {number} alpha - The interpolation factor in the closed interval `[0,1]`.
  12094. * @return {Color} A reference to this color.
  12095. */
  12096. lerp( color, alpha ) {
  12097. this.r += ( color.r - this.r ) * alpha;
  12098. this.g += ( color.g - this.g ) * alpha;
  12099. this.b += ( color.b - this.b ) * alpha;
  12100. return this;
  12101. }
  12102. /**
  12103. * Linearly interpolates between the given colors and stores the result in this instance.
  12104. * The alpha argument can be thought of as the ratio between the two colors, where `0.0`
  12105. * is the first and `1.0` is the second color.
  12106. *
  12107. * @param {Color} color1 - The first color.
  12108. * @param {Color} color2 - The second color.
  12109. * @param {number} alpha - The interpolation factor in the closed interval `[0,1]`.
  12110. * @return {Color} A reference to this color.
  12111. */
  12112. lerpColors( color1, color2, alpha ) {
  12113. this.r = color1.r + ( color2.r - color1.r ) * alpha;
  12114. this.g = color1.g + ( color2.g - color1.g ) * alpha;
  12115. this.b = color1.b + ( color2.b - color1.b ) * alpha;
  12116. return this;
  12117. }
  12118. /**
  12119. * Linearly interpolates this color's HSL values toward the HSL values of the
  12120. * given color. It differs from {@link Color#lerp} by not interpolating straight
  12121. * from one color to the other, but instead going through all the hues in between
  12122. * those two colors. The alpha argument can be thought of as the ratio between
  12123. * the two colors, where 0.0 is this color and 1.0 is the first argument.
  12124. *
  12125. * @param {Color} color - The color to converge on.
  12126. * @param {number} alpha - The interpolation factor in the closed interval `[0,1]`.
  12127. * @return {Color} A reference to this color.
  12128. */
  12129. lerpHSL( color, alpha ) {
  12130. this.getHSL( _hslA );
  12131. color.getHSL( _hslB );
  12132. const h = lerp( _hslA.h, _hslB.h, alpha );
  12133. const s = lerp( _hslA.s, _hslB.s, alpha );
  12134. const l = lerp( _hslA.l, _hslB.l, alpha );
  12135. this.setHSL( h, s, l );
  12136. return this;
  12137. }
  12138. /**
  12139. * Sets the color's RGB components from the given 3D vector.
  12140. *
  12141. * @param {Vector3} v - The vector to set.
  12142. * @return {Color} A reference to this color.
  12143. */
  12144. setFromVector3( v ) {
  12145. this.r = v.x;
  12146. this.g = v.y;
  12147. this.b = v.z;
  12148. return this;
  12149. }
  12150. /**
  12151. * Transforms this color with the given 3x3 matrix.
  12152. *
  12153. * @param {Matrix3} m - The matrix.
  12154. * @return {Color} A reference to this color.
  12155. */
  12156. applyMatrix3( m ) {
  12157. const r = this.r, g = this.g, b = this.b;
  12158. const e = m.elements;
  12159. this.r = e[ 0 ] * r + e[ 3 ] * g + e[ 6 ] * b;
  12160. this.g = e[ 1 ] * r + e[ 4 ] * g + e[ 7 ] * b;
  12161. this.b = e[ 2 ] * r + e[ 5 ] * g + e[ 8 ] * b;
  12162. return this;
  12163. }
  12164. /**
  12165. * Returns `true` if this color is equal with the given one.
  12166. *
  12167. * @param {Color} c - The color to test for equality.
  12168. * @return {boolean} Whether this bounding color is equal with the given one.
  12169. */
  12170. equals( c ) {
  12171. return ( c.r === this.r ) && ( c.g === this.g ) && ( c.b === this.b );
  12172. }
  12173. /**
  12174. * Sets this color's RGB components from the given array.
  12175. *
  12176. * @param {Array<number>} array - An array holding the RGB values.
  12177. * @param {number} [offset=0] - The offset into the array.
  12178. * @return {Color} A reference to this color.
  12179. */
  12180. fromArray( array, offset = 0 ) {
  12181. this.r = array[ offset ];
  12182. this.g = array[ offset + 1 ];
  12183. this.b = array[ offset + 2 ];
  12184. return this;
  12185. }
  12186. /**
  12187. * Writes the RGB components of this color to the given array. If no array is provided,
  12188. * the method returns a new instance.
  12189. *
  12190. * @param {Array<number>} [array=[]] - The target array holding the color components.
  12191. * @param {number} [offset=0] - Index of the first element in the array.
  12192. * @return {Array<number>} The color components.
  12193. */
  12194. toArray( array = [], offset = 0 ) {
  12195. array[ offset ] = this.r;
  12196. array[ offset + 1 ] = this.g;
  12197. array[ offset + 2 ] = this.b;
  12198. return array;
  12199. }
  12200. /**
  12201. * Sets the components of this color from the given buffer attribute.
  12202. *
  12203. * @param {BufferAttribute} attribute - The buffer attribute holding color data.
  12204. * @param {number} index - The index into the attribute.
  12205. * @return {Color} A reference to this color.
  12206. */
  12207. fromBufferAttribute( attribute, index ) {
  12208. this.r = attribute.getX( index );
  12209. this.g = attribute.getY( index );
  12210. this.b = attribute.getZ( index );
  12211. return this;
  12212. }
  12213. /**
  12214. * This methods defines the serialization result of this class. Returns the color
  12215. * as a hexadecimal value.
  12216. *
  12217. * @return {number} The hexadecimal value.
  12218. */
  12219. toJSON() {
  12220. return this.getHex();
  12221. }
  12222. *[ Symbol.iterator ]() {
  12223. yield this.r;
  12224. yield this.g;
  12225. yield this.b;
  12226. }
  12227. }
  12228. const _color = /*@__PURE__*/ new Color();
  12229. /**
  12230. * A dictionary with X11 color names.
  12231. *
  12232. * Note that multiple words such as Dark Orange become the string 'darkorange'.
  12233. *
  12234. * @static
  12235. * @type {Object}
  12236. */
  12237. Color.NAMES = _colorKeywords;
  12238. let _materialId = 0;
  12239. /**
  12240. * Abstract base class for materials.
  12241. *
  12242. * Materials define the appearance of renderable 3D objects.
  12243. *
  12244. * @abstract
  12245. * @augments EventDispatcher
  12246. */
  12247. class Material extends EventDispatcher {
  12248. /**
  12249. * Constructs a new material.
  12250. */
  12251. constructor() {
  12252. super();
  12253. /**
  12254. * This flag can be used for type testing.
  12255. *
  12256. * @type {boolean}
  12257. * @readonly
  12258. * @default true
  12259. */
  12260. this.isMaterial = true;
  12261. /**
  12262. * The ID of the material.
  12263. *
  12264. * @name Material#id
  12265. * @type {number}
  12266. * @readonly
  12267. */
  12268. Object.defineProperty( this, 'id', { value: _materialId ++ } );
  12269. /**
  12270. * The UUID of the material.
  12271. *
  12272. * @type {string}
  12273. * @readonly
  12274. */
  12275. this.uuid = generateUUID();
  12276. /**
  12277. * The name of the material.
  12278. *
  12279. * @type {string}
  12280. */
  12281. this.name = '';
  12282. /**
  12283. * The type property is used for detecting the object type
  12284. * in context of serialization/deserialization.
  12285. *
  12286. * @type {string}
  12287. * @readonly
  12288. */
  12289. this.type = 'Material';
  12290. /**
  12291. * Defines the blending type of the material.
  12292. *
  12293. * It must be set to `CustomBlending` if custom blending properties like
  12294. * {@link Material#blendSrc}, {@link Material#blendDst} or {@link Material#blendEquation}
  12295. * should have any effect.
  12296. *
  12297. * @type {(NoBlending|NormalBlending|AdditiveBlending|SubtractiveBlending|MultiplyBlending|CustomBlending)}
  12298. * @default NormalBlending
  12299. */
  12300. this.blending = NormalBlending;
  12301. /**
  12302. * Defines which side of faces will be rendered - front, back or both.
  12303. *
  12304. * @type {(FrontSide|BackSide|DoubleSide)}
  12305. * @default FrontSide
  12306. */
  12307. this.side = FrontSide;
  12308. /**
  12309. * If set to `true`, vertex colors should be used.
  12310. *
  12311. * The engine supports RGB and RGBA vertex colors depending on whether a three (RGB) or
  12312. * four (RGBA) component color buffer attribute is used.
  12313. *
  12314. * @type {boolean}
  12315. * @default false
  12316. */
  12317. this.vertexColors = false;
  12318. /**
  12319. * Defines how transparent the material is.
  12320. * A value of `0.0` indicates fully transparent, `1.0` is fully opaque.
  12321. *
  12322. * If the {@link Material#transparent} is not set to `true`,
  12323. * the material will remain fully opaque and this value will only affect its color.
  12324. *
  12325. * @type {number}
  12326. * @default 1
  12327. */
  12328. this.opacity = 1;
  12329. /**
  12330. * Defines whether this material is transparent. This has an effect on
  12331. * rendering as transparent objects need special treatment and are rendered
  12332. * after non-transparent objects.
  12333. *
  12334. * When set to true, the extent to which the material is transparent is
  12335. * controlled by {@link Material#opacity}.
  12336. *
  12337. * @type {boolean}
  12338. * @default false
  12339. */
  12340. this.transparent = false;
  12341. /**
  12342. * Enables alpha hashed transparency, an alternative to {@link Material#transparent} or
  12343. * {@link Material#alphaTest}. The material will not be rendered if opacity is lower than
  12344. * a random threshold. Randomization introduces some grain or noise, but approximates alpha
  12345. * blending without the associated problems of sorting. Using TAA can reduce the resulting noise.
  12346. *
  12347. * @type {boolean}
  12348. * @default false
  12349. */
  12350. this.alphaHash = false;
  12351. /**
  12352. * Defines the blending source factor.
  12353. *
  12354. * @type {(ZeroFactor|OneFactor|SrcColorFactor|OneMinusSrcColorFactor|SrcAlphaFactor|OneMinusSrcAlphaFactor|DstAlphaFactor|OneMinusDstAlphaFactor|DstColorFactor|OneMinusDstColorFactor|SrcAlphaSaturateFactor|ConstantColorFactor|OneMinusConstantColorFactor|ConstantAlphaFactor|OneMinusConstantAlphaFactor)}
  12355. * @default SrcAlphaFactor
  12356. */
  12357. this.blendSrc = SrcAlphaFactor;
  12358. /**
  12359. * Defines the blending destination factor.
  12360. *
  12361. * @type {(ZeroFactor|OneFactor|SrcColorFactor|OneMinusSrcColorFactor|SrcAlphaFactor|OneMinusSrcAlphaFactor|DstAlphaFactor|OneMinusDstAlphaFactor|DstColorFactor|OneMinusDstColorFactor|SrcAlphaSaturateFactor|ConstantColorFactor|OneMinusConstantColorFactor|ConstantAlphaFactor|OneMinusConstantAlphaFactor)}
  12362. * @default OneMinusSrcAlphaFactor
  12363. */
  12364. this.blendDst = OneMinusSrcAlphaFactor;
  12365. /**
  12366. * Defines the blending equation.
  12367. *
  12368. * @type {(AddEquation|SubtractEquation|ReverseSubtractEquation|MinEquation|MaxEquation)}
  12369. * @default AddEquation
  12370. */
  12371. this.blendEquation = AddEquation;
  12372. /**
  12373. * Defines the blending source alpha factor.
  12374. *
  12375. * @type {?(ZeroFactor|OneFactor|SrcColorFactor|OneMinusSrcColorFactor|SrcAlphaFactor|OneMinusSrcAlphaFactor|DstAlphaFactor|OneMinusDstAlphaFactor|DstColorFactor|OneMinusDstColorFactor|SrcAlphaSaturateFactor|ConstantColorFactor|OneMinusConstantColorFactor|ConstantAlphaFactor|OneMinusConstantAlphaFactor)}
  12376. * @default null
  12377. */
  12378. this.blendSrcAlpha = null;
  12379. /**
  12380. * Defines the blending destination alpha factor.
  12381. *
  12382. * @type {?(ZeroFactor|OneFactor|SrcColorFactor|OneMinusSrcColorFactor|SrcAlphaFactor|OneMinusSrcAlphaFactor|DstAlphaFactor|OneMinusDstAlphaFactor|DstColorFactor|OneMinusDstColorFactor|SrcAlphaSaturateFactor|ConstantColorFactor|OneMinusConstantColorFactor|ConstantAlphaFactor|OneMinusConstantAlphaFactor)}
  12383. * @default null
  12384. */
  12385. this.blendDstAlpha = null;
  12386. /**
  12387. * Defines the blending equation of the alpha channel.
  12388. *
  12389. * @type {?(AddEquation|SubtractEquation|ReverseSubtractEquation|MinEquation|MaxEquation)}
  12390. * @default null
  12391. */
  12392. this.blendEquationAlpha = null;
  12393. /**
  12394. * Represents the RGB values of the constant blend color.
  12395. *
  12396. * This property has only an effect when using custom blending with `ConstantColor` or `OneMinusConstantColor`.
  12397. *
  12398. * @type {Color}
  12399. * @default (0,0,0)
  12400. */
  12401. this.blendColor = new Color( 0, 0, 0 );
  12402. /**
  12403. * Represents the alpha value of the constant blend color.
  12404. *
  12405. * This property has only an effect when using custom blending with `ConstantAlpha` or `OneMinusConstantAlpha`.
  12406. *
  12407. * @type {number}
  12408. * @default 0
  12409. */
  12410. this.blendAlpha = 0;
  12411. /**
  12412. * Defines the depth function.
  12413. *
  12414. * @type {(NeverDepth|AlwaysDepth|LessDepth|LessEqualDepth|EqualDepth|GreaterEqualDepth|GreaterDepth|NotEqualDepth)}
  12415. * @default LessEqualDepth
  12416. */
  12417. this.depthFunc = LessEqualDepth;
  12418. /**
  12419. * Whether to have depth test enabled when rendering this material.
  12420. * When the depth test is disabled, the depth write will also be implicitly disabled.
  12421. *
  12422. * @type {boolean}
  12423. * @default true
  12424. */
  12425. this.depthTest = true;
  12426. /**
  12427. * Whether rendering this material has any effect on the depth buffer.
  12428. *
  12429. * When drawing 2D overlays it can be useful to disable the depth writing in
  12430. * order to layer several things together without creating z-index artifacts.
  12431. *
  12432. * @type {boolean}
  12433. * @default true
  12434. */
  12435. this.depthWrite = true;
  12436. /**
  12437. * The bit mask to use when writing to the stencil buffer.
  12438. *
  12439. * @type {number}
  12440. * @default 0xff
  12441. */
  12442. this.stencilWriteMask = 0xff;
  12443. /**
  12444. * The stencil comparison function to use.
  12445. *
  12446. * @type {NeverStencilFunc|LessStencilFunc|EqualStencilFunc|LessEqualStencilFunc|GreaterStencilFunc|NotEqualStencilFunc|GreaterEqualStencilFunc|AlwaysStencilFunc}
  12447. * @default AlwaysStencilFunc
  12448. */
  12449. this.stencilFunc = AlwaysStencilFunc;
  12450. /**
  12451. * The value to use when performing stencil comparisons or stencil operations.
  12452. *
  12453. * @type {number}
  12454. * @default 0
  12455. */
  12456. this.stencilRef = 0;
  12457. /**
  12458. * The bit mask to use when comparing against the stencil buffer.
  12459. *
  12460. * @type {number}
  12461. * @default 0xff
  12462. */
  12463. this.stencilFuncMask = 0xff;
  12464. /**
  12465. * Which stencil operation to perform when the comparison function returns `false`.
  12466. *
  12467. * @type {ZeroStencilOp|KeepStencilOp|ReplaceStencilOp|IncrementStencilOp|DecrementStencilOp|IncrementWrapStencilOp|DecrementWrapStencilOp|InvertStencilOp}
  12468. * @default KeepStencilOp
  12469. */
  12470. this.stencilFail = KeepStencilOp;
  12471. /**
  12472. * Which stencil operation to perform when the comparison function returns
  12473. * `true` but the depth test fails.
  12474. *
  12475. * @type {ZeroStencilOp|KeepStencilOp|ReplaceStencilOp|IncrementStencilOp|DecrementStencilOp|IncrementWrapStencilOp|DecrementWrapStencilOp|InvertStencilOp}
  12476. * @default KeepStencilOp
  12477. */
  12478. this.stencilZFail = KeepStencilOp;
  12479. /**
  12480. * Which stencil operation to perform when the comparison function returns
  12481. * `true` and the depth test passes.
  12482. *
  12483. * @type {ZeroStencilOp|KeepStencilOp|ReplaceStencilOp|IncrementStencilOp|DecrementStencilOp|IncrementWrapStencilOp|DecrementWrapStencilOp|InvertStencilOp}
  12484. * @default KeepStencilOp
  12485. */
  12486. this.stencilZPass = KeepStencilOp;
  12487. /**
  12488. * Whether stencil operations are performed against the stencil buffer. In
  12489. * order to perform writes or comparisons against the stencil buffer this
  12490. * value must be `true`.
  12491. *
  12492. * @type {boolean}
  12493. * @default false
  12494. */
  12495. this.stencilWrite = false;
  12496. /**
  12497. * User-defined clipping planes specified as THREE.Plane objects in world
  12498. * space. These planes apply to the objects this material is attached to.
  12499. * Points in space whose signed distance to the plane is negative are clipped
  12500. * (not rendered). This requires {@link WebGLRenderer#localClippingEnabled} to
  12501. * be `true`.
  12502. *
  12503. * @type {?Array<Plane>}
  12504. * @default null
  12505. */
  12506. this.clippingPlanes = null;
  12507. /**
  12508. * Changes the behavior of clipping planes so that only their intersection is
  12509. * clipped, rather than their union.
  12510. *
  12511. * @type {boolean}
  12512. * @default false
  12513. */
  12514. this.clipIntersection = false;
  12515. /**
  12516. * Defines whether to clip shadows according to the clipping planes specified
  12517. * on this material.
  12518. *
  12519. * @type {boolean}
  12520. * @default false
  12521. */
  12522. this.clipShadows = false;
  12523. /**
  12524. * Defines which side of faces cast shadows. If `null`, the side casting shadows
  12525. * is determined as follows:
  12526. *
  12527. * - When {@link Material#side} is set to `FrontSide`, the back side cast shadows.
  12528. * - When {@link Material#side} is set to `BackSide`, the front side cast shadows.
  12529. * - When {@link Material#side} is set to `DoubleSide`, both sides cast shadows.
  12530. *
  12531. * @type {?(FrontSide|BackSide|DoubleSide)}
  12532. * @default null
  12533. */
  12534. this.shadowSide = null;
  12535. /**
  12536. * Whether to render the material's color.
  12537. *
  12538. * This can be used in conjunction with {@link Object3D#renderOder} to create invisible
  12539. * objects that occlude other objects.
  12540. *
  12541. * @type {boolean}
  12542. * @default true
  12543. */
  12544. this.colorWrite = true;
  12545. /**
  12546. * Override the renderer's default precision for this material.
  12547. *
  12548. * @type {?('highp'|'mediump'|'lowp')}
  12549. * @default null
  12550. */
  12551. this.precision = null;
  12552. /**
  12553. * Whether to use polygon offset or not. When enabled, each fragment's depth value will
  12554. * be offset after it is interpolated from the depth values of the appropriate vertices.
  12555. * The offset is added before the depth test is performed and before the value is written
  12556. * into the depth buffer.
  12557. *
  12558. * Can be useful for rendering hidden-line images, for applying decals to surfaces, and for
  12559. * rendering solids with highlighted edges.
  12560. *
  12561. * @type {boolean}
  12562. * @default false
  12563. */
  12564. this.polygonOffset = false;
  12565. /**
  12566. * Specifies a scale factor that is used to create a variable depth offset for each polygon.
  12567. *
  12568. * @type {number}
  12569. * @default 0
  12570. */
  12571. this.polygonOffsetFactor = 0;
  12572. /**
  12573. * Is multiplied by an implementation-specific value to create a constant depth offset.
  12574. *
  12575. * @type {number}
  12576. * @default 0
  12577. */
  12578. this.polygonOffsetUnits = 0;
  12579. /**
  12580. * Whether to apply dithering to the color to remove the appearance of banding.
  12581. *
  12582. * @type {boolean}
  12583. * @default false
  12584. */
  12585. this.dithering = false;
  12586. /**
  12587. * Whether alpha to coverage should be enabled or not. Can only be used with MSAA-enabled contexts
  12588. * (meaning when the renderer was created with *antialias* parameter set to `true`). Enabling this
  12589. * will smooth aliasing on clip plane edges and alphaTest-clipped edges.
  12590. *
  12591. * @type {boolean}
  12592. * @default false
  12593. */
  12594. this.alphaToCoverage = false;
  12595. /**
  12596. * Whether to premultiply the alpha (transparency) value.
  12597. *
  12598. * @type {boolean}
  12599. * @default false
  12600. */
  12601. this.premultipliedAlpha = false;
  12602. /**
  12603. * Whether double-sided, transparent objects should be rendered with a single pass or not.
  12604. *
  12605. * The engine renders double-sided, transparent objects with two draw calls (back faces first,
  12606. * then front faces) to mitigate transparency artifacts. There are scenarios however where this
  12607. * approach produces no quality gains but still doubles draw calls e.g. when rendering flat
  12608. * vegetation like grass sprites. In these cases, set the `forceSinglePass` flag to `true` to
  12609. * disable the two pass rendering to avoid performance issues.
  12610. *
  12611. * @type {boolean}
  12612. * @default false
  12613. */
  12614. this.forceSinglePass = false;
  12615. /**
  12616. * Whether it's possible to override the material with {@link Scene#overrideMaterial} or not.
  12617. *
  12618. * @type {boolean}
  12619. * @default true
  12620. */
  12621. this.allowOverride = true;
  12622. /**
  12623. * Defines whether 3D objects using this material are visible.
  12624. *
  12625. * @type {boolean}
  12626. * @default true
  12627. */
  12628. this.visible = true;
  12629. /**
  12630. * Defines whether this material is tone mapped according to the renderer's tone mapping setting.
  12631. *
  12632. * It is ignored when rendering to a render target or using post processing or when using
  12633. * `WebGPURenderer`. In all these cases, all materials are honored by tone mapping.
  12634. *
  12635. * @type {boolean}
  12636. * @default true
  12637. */
  12638. this.toneMapped = true;
  12639. /**
  12640. * An object that can be used to store custom data about the Material. It
  12641. * should not hold references to functions as these will not be cloned.
  12642. *
  12643. * @type {Object}
  12644. */
  12645. this.userData = {};
  12646. /**
  12647. * This starts at `0` and counts how many times {@link Material#needsUpdate} is set to `true`.
  12648. *
  12649. * @type {number}
  12650. * @readonly
  12651. * @default 0
  12652. */
  12653. this.version = 0;
  12654. this._alphaTest = 0;
  12655. }
  12656. /**
  12657. * Sets the alpha value to be used when running an alpha test. The material
  12658. * will not be rendered if the opacity is lower than this value.
  12659. *
  12660. * @type {number}
  12661. * @readonly
  12662. * @default 0
  12663. */
  12664. get alphaTest() {
  12665. return this._alphaTest;
  12666. }
  12667. set alphaTest( value ) {
  12668. if ( this._alphaTest > 0 !== value > 0 ) {
  12669. this.version ++;
  12670. }
  12671. this._alphaTest = value;
  12672. }
  12673. /**
  12674. * An optional callback that is executed immediately before the material is used to render a 3D object.
  12675. *
  12676. * This method can only be used when rendering with {@link WebGLRenderer}.
  12677. *
  12678. * @param {WebGLRenderer} renderer - The renderer.
  12679. * @param {Scene} scene - The scene.
  12680. * @param {Camera} camera - The camera that is used to render the scene.
  12681. * @param {BufferGeometry} geometry - The 3D object's geometry.
  12682. * @param {Object3D} object - The 3D object.
  12683. * @param {Object} group - The geometry group data.
  12684. */
  12685. onBeforeRender( /* renderer, scene, camera, geometry, object, group */ ) {}
  12686. /**
  12687. * An optional callback that is executed immediately before the shader
  12688. * program is compiled. This function is called with the shader source code
  12689. * as a parameter. Useful for the modification of built-in materials.
  12690. *
  12691. * This method can only be used when rendering with {@link WebGLRenderer}. The
  12692. * recommended approach when customizing materials is to use `WebGPURenderer` with the new
  12693. * Node Material system and [TSL]{@link https://github.com/mrdoob/three.js/wiki/Three.js-Shading-Language}.
  12694. *
  12695. * @param {{vertexShader:string,fragmentShader:string,uniforms:Object}} shaderobject - The object holds the uniforms and the vertex and fragment shader source.
  12696. * @param {WebGLRenderer} renderer - A reference to the renderer.
  12697. */
  12698. onBeforeCompile( /* shaderobject, renderer */ ) {}
  12699. /**
  12700. * In case {@link Material#onBeforeCompile} is used, this callback can be used to identify
  12701. * values of settings used in `onBeforeCompile()`, so three.js can reuse a cached
  12702. * shader or recompile the shader for this material as needed.
  12703. *
  12704. * This method can only be used when rendering with {@link WebGLRenderer}.
  12705. *
  12706. * @return {string} The custom program cache key.
  12707. */
  12708. customProgramCacheKey() {
  12709. return this.onBeforeCompile.toString();
  12710. }
  12711. /**
  12712. * This method can be used to set default values from parameter objects.
  12713. * It is a generic implementation so it can be used with different types
  12714. * of materials.
  12715. *
  12716. * @param {Object} [values] - The material values to set.
  12717. */
  12718. setValues( values ) {
  12719. if ( values === undefined ) return;
  12720. for ( const key in values ) {
  12721. const newValue = values[ key ];
  12722. if ( newValue === undefined ) {
  12723. console.warn( `THREE.Material: parameter '${ key }' has value of undefined.` );
  12724. continue;
  12725. }
  12726. const currentValue = this[ key ];
  12727. if ( currentValue === undefined ) {
  12728. console.warn( `THREE.Material: '${ key }' is not a property of THREE.${ this.type }.` );
  12729. continue;
  12730. }
  12731. if ( currentValue && currentValue.isColor ) {
  12732. currentValue.set( newValue );
  12733. } else if ( ( currentValue && currentValue.isVector3 ) && ( newValue && newValue.isVector3 ) ) {
  12734. currentValue.copy( newValue );
  12735. } else {
  12736. this[ key ] = newValue;
  12737. }
  12738. }
  12739. }
  12740. /**
  12741. * Serializes the material into JSON.
  12742. *
  12743. * @param {?(Object|string)} meta - An optional value holding meta information about the serialization.
  12744. * @return {Object} A JSON object representing the serialized material.
  12745. * @see {@link ObjectLoader#parse}
  12746. */
  12747. toJSON( meta ) {
  12748. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  12749. if ( isRootObject ) {
  12750. meta = {
  12751. textures: {},
  12752. images: {}
  12753. };
  12754. }
  12755. const data = {
  12756. metadata: {
  12757. version: 4.6,
  12758. type: 'Material',
  12759. generator: 'Material.toJSON'
  12760. }
  12761. };
  12762. // standard Material serialization
  12763. data.uuid = this.uuid;
  12764. data.type = this.type;
  12765. if ( this.name !== '' ) data.name = this.name;
  12766. if ( this.color && this.color.isColor ) data.color = this.color.getHex();
  12767. if ( this.roughness !== undefined ) data.roughness = this.roughness;
  12768. if ( this.metalness !== undefined ) data.metalness = this.metalness;
  12769. if ( this.sheen !== undefined ) data.sheen = this.sheen;
  12770. if ( this.sheenColor && this.sheenColor.isColor ) data.sheenColor = this.sheenColor.getHex();
  12771. if ( this.sheenRoughness !== undefined ) data.sheenRoughness = this.sheenRoughness;
  12772. if ( this.emissive && this.emissive.isColor ) data.emissive = this.emissive.getHex();
  12773. if ( this.emissiveIntensity !== undefined && this.emissiveIntensity !== 1 ) data.emissiveIntensity = this.emissiveIntensity;
  12774. if ( this.specular && this.specular.isColor ) data.specular = this.specular.getHex();
  12775. if ( this.specularIntensity !== undefined ) data.specularIntensity = this.specularIntensity;
  12776. if ( this.specularColor && this.specularColor.isColor ) data.specularColor = this.specularColor.getHex();
  12777. if ( this.shininess !== undefined ) data.shininess = this.shininess;
  12778. if ( this.clearcoat !== undefined ) data.clearcoat = this.clearcoat;
  12779. if ( this.clearcoatRoughness !== undefined ) data.clearcoatRoughness = this.clearcoatRoughness;
  12780. if ( this.clearcoatMap && this.clearcoatMap.isTexture ) {
  12781. data.clearcoatMap = this.clearcoatMap.toJSON( meta ).uuid;
  12782. }
  12783. if ( this.clearcoatRoughnessMap && this.clearcoatRoughnessMap.isTexture ) {
  12784. data.clearcoatRoughnessMap = this.clearcoatRoughnessMap.toJSON( meta ).uuid;
  12785. }
  12786. if ( this.clearcoatNormalMap && this.clearcoatNormalMap.isTexture ) {
  12787. data.clearcoatNormalMap = this.clearcoatNormalMap.toJSON( meta ).uuid;
  12788. data.clearcoatNormalScale = this.clearcoatNormalScale.toArray();
  12789. }
  12790. if ( this.dispersion !== undefined ) data.dispersion = this.dispersion;
  12791. if ( this.iridescence !== undefined ) data.iridescence = this.iridescence;
  12792. if ( this.iridescenceIOR !== undefined ) data.iridescenceIOR = this.iridescenceIOR;
  12793. if ( this.iridescenceThicknessRange !== undefined ) data.iridescenceThicknessRange = this.iridescenceThicknessRange;
  12794. if ( this.iridescenceMap && this.iridescenceMap.isTexture ) {
  12795. data.iridescenceMap = this.iridescenceMap.toJSON( meta ).uuid;
  12796. }
  12797. if ( this.iridescenceThicknessMap && this.iridescenceThicknessMap.isTexture ) {
  12798. data.iridescenceThicknessMap = this.iridescenceThicknessMap.toJSON( meta ).uuid;
  12799. }
  12800. if ( this.anisotropy !== undefined ) data.anisotropy = this.anisotropy;
  12801. if ( this.anisotropyRotation !== undefined ) data.anisotropyRotation = this.anisotropyRotation;
  12802. if ( this.anisotropyMap && this.anisotropyMap.isTexture ) {
  12803. data.anisotropyMap = this.anisotropyMap.toJSON( meta ).uuid;
  12804. }
  12805. if ( this.map && this.map.isTexture ) data.map = this.map.toJSON( meta ).uuid;
  12806. if ( this.matcap && this.matcap.isTexture ) data.matcap = this.matcap.toJSON( meta ).uuid;
  12807. if ( this.alphaMap && this.alphaMap.isTexture ) data.alphaMap = this.alphaMap.toJSON( meta ).uuid;
  12808. if ( this.lightMap && this.lightMap.isTexture ) {
  12809. data.lightMap = this.lightMap.toJSON( meta ).uuid;
  12810. data.lightMapIntensity = this.lightMapIntensity;
  12811. }
  12812. if ( this.aoMap && this.aoMap.isTexture ) {
  12813. data.aoMap = this.aoMap.toJSON( meta ).uuid;
  12814. data.aoMapIntensity = this.aoMapIntensity;
  12815. }
  12816. if ( this.bumpMap && this.bumpMap.isTexture ) {
  12817. data.bumpMap = this.bumpMap.toJSON( meta ).uuid;
  12818. data.bumpScale = this.bumpScale;
  12819. }
  12820. if ( this.normalMap && this.normalMap.isTexture ) {
  12821. data.normalMap = this.normalMap.toJSON( meta ).uuid;
  12822. data.normalMapType = this.normalMapType;
  12823. data.normalScale = this.normalScale.toArray();
  12824. }
  12825. if ( this.displacementMap && this.displacementMap.isTexture ) {
  12826. data.displacementMap = this.displacementMap.toJSON( meta ).uuid;
  12827. data.displacementScale = this.displacementScale;
  12828. data.displacementBias = this.displacementBias;
  12829. }
  12830. if ( this.roughnessMap && this.roughnessMap.isTexture ) data.roughnessMap = this.roughnessMap.toJSON( meta ).uuid;
  12831. if ( this.metalnessMap && this.metalnessMap.isTexture ) data.metalnessMap = this.metalnessMap.toJSON( meta ).uuid;
  12832. if ( this.emissiveMap && this.emissiveMap.isTexture ) data.emissiveMap = this.emissiveMap.toJSON( meta ).uuid;
  12833. if ( this.specularMap && this.specularMap.isTexture ) data.specularMap = this.specularMap.toJSON( meta ).uuid;
  12834. if ( this.specularIntensityMap && this.specularIntensityMap.isTexture ) data.specularIntensityMap = this.specularIntensityMap.toJSON( meta ).uuid;
  12835. if ( this.specularColorMap && this.specularColorMap.isTexture ) data.specularColorMap = this.specularColorMap.toJSON( meta ).uuid;
  12836. if ( this.envMap && this.envMap.isTexture ) {
  12837. data.envMap = this.envMap.toJSON( meta ).uuid;
  12838. if ( this.combine !== undefined ) data.combine = this.combine;
  12839. }
  12840. if ( this.envMapRotation !== undefined ) data.envMapRotation = this.envMapRotation.toArray();
  12841. if ( this.envMapIntensity !== undefined ) data.envMapIntensity = this.envMapIntensity;
  12842. if ( this.reflectivity !== undefined ) data.reflectivity = this.reflectivity;
  12843. if ( this.refractionRatio !== undefined ) data.refractionRatio = this.refractionRatio;
  12844. if ( this.gradientMap && this.gradientMap.isTexture ) {
  12845. data.gradientMap = this.gradientMap.toJSON( meta ).uuid;
  12846. }
  12847. if ( this.transmission !== undefined ) data.transmission = this.transmission;
  12848. if ( this.transmissionMap && this.transmissionMap.isTexture ) data.transmissionMap = this.transmissionMap.toJSON( meta ).uuid;
  12849. if ( this.thickness !== undefined ) data.thickness = this.thickness;
  12850. if ( this.thicknessMap && this.thicknessMap.isTexture ) data.thicknessMap = this.thicknessMap.toJSON( meta ).uuid;
  12851. if ( this.attenuationDistance !== undefined && this.attenuationDistance !== Infinity ) data.attenuationDistance = this.attenuationDistance;
  12852. if ( this.attenuationColor !== undefined ) data.attenuationColor = this.attenuationColor.getHex();
  12853. if ( this.size !== undefined ) data.size = this.size;
  12854. if ( this.shadowSide !== null ) data.shadowSide = this.shadowSide;
  12855. if ( this.sizeAttenuation !== undefined ) data.sizeAttenuation = this.sizeAttenuation;
  12856. if ( this.blending !== NormalBlending ) data.blending = this.blending;
  12857. if ( this.side !== FrontSide ) data.side = this.side;
  12858. if ( this.vertexColors === true ) data.vertexColors = true;
  12859. if ( this.opacity < 1 ) data.opacity = this.opacity;
  12860. if ( this.transparent === true ) data.transparent = true;
  12861. if ( this.blendSrc !== SrcAlphaFactor ) data.blendSrc = this.blendSrc;
  12862. if ( this.blendDst !== OneMinusSrcAlphaFactor ) data.blendDst = this.blendDst;
  12863. if ( this.blendEquation !== AddEquation ) data.blendEquation = this.blendEquation;
  12864. if ( this.blendSrcAlpha !== null ) data.blendSrcAlpha = this.blendSrcAlpha;
  12865. if ( this.blendDstAlpha !== null ) data.blendDstAlpha = this.blendDstAlpha;
  12866. if ( this.blendEquationAlpha !== null ) data.blendEquationAlpha = this.blendEquationAlpha;
  12867. if ( this.blendColor && this.blendColor.isColor ) data.blendColor = this.blendColor.getHex();
  12868. if ( this.blendAlpha !== 0 ) data.blendAlpha = this.blendAlpha;
  12869. if ( this.depthFunc !== LessEqualDepth ) data.depthFunc = this.depthFunc;
  12870. if ( this.depthTest === false ) data.depthTest = this.depthTest;
  12871. if ( this.depthWrite === false ) data.depthWrite = this.depthWrite;
  12872. if ( this.colorWrite === false ) data.colorWrite = this.colorWrite;
  12873. if ( this.stencilWriteMask !== 0xff ) data.stencilWriteMask = this.stencilWriteMask;
  12874. if ( this.stencilFunc !== AlwaysStencilFunc ) data.stencilFunc = this.stencilFunc;
  12875. if ( this.stencilRef !== 0 ) data.stencilRef = this.stencilRef;
  12876. if ( this.stencilFuncMask !== 0xff ) data.stencilFuncMask = this.stencilFuncMask;
  12877. if ( this.stencilFail !== KeepStencilOp ) data.stencilFail = this.stencilFail;
  12878. if ( this.stencilZFail !== KeepStencilOp ) data.stencilZFail = this.stencilZFail;
  12879. if ( this.stencilZPass !== KeepStencilOp ) data.stencilZPass = this.stencilZPass;
  12880. if ( this.stencilWrite === true ) data.stencilWrite = this.stencilWrite;
  12881. // rotation (SpriteMaterial)
  12882. if ( this.rotation !== undefined && this.rotation !== 0 ) data.rotation = this.rotation;
  12883. if ( this.polygonOffset === true ) data.polygonOffset = true;
  12884. if ( this.polygonOffsetFactor !== 0 ) data.polygonOffsetFactor = this.polygonOffsetFactor;
  12885. if ( this.polygonOffsetUnits !== 0 ) data.polygonOffsetUnits = this.polygonOffsetUnits;
  12886. if ( this.linewidth !== undefined && this.linewidth !== 1 ) data.linewidth = this.linewidth;
  12887. if ( this.dashSize !== undefined ) data.dashSize = this.dashSize;
  12888. if ( this.gapSize !== undefined ) data.gapSize = this.gapSize;
  12889. if ( this.scale !== undefined ) data.scale = this.scale;
  12890. if ( this.dithering === true ) data.dithering = true;
  12891. if ( this.alphaTest > 0 ) data.alphaTest = this.alphaTest;
  12892. if ( this.alphaHash === true ) data.alphaHash = true;
  12893. if ( this.alphaToCoverage === true ) data.alphaToCoverage = true;
  12894. if ( this.premultipliedAlpha === true ) data.premultipliedAlpha = true;
  12895. if ( this.forceSinglePass === true ) data.forceSinglePass = true;
  12896. if ( this.wireframe === true ) data.wireframe = true;
  12897. if ( this.wireframeLinewidth > 1 ) data.wireframeLinewidth = this.wireframeLinewidth;
  12898. if ( this.wireframeLinecap !== 'round' ) data.wireframeLinecap = this.wireframeLinecap;
  12899. if ( this.wireframeLinejoin !== 'round' ) data.wireframeLinejoin = this.wireframeLinejoin;
  12900. if ( this.flatShading === true ) data.flatShading = true;
  12901. if ( this.visible === false ) data.visible = false;
  12902. if ( this.toneMapped === false ) data.toneMapped = false;
  12903. if ( this.fog === false ) data.fog = false;
  12904. if ( Object.keys( this.userData ).length > 0 ) data.userData = this.userData;
  12905. // TODO: Copied from Object3D.toJSON
  12906. function extractFromCache( cache ) {
  12907. const values = [];
  12908. for ( const key in cache ) {
  12909. const data = cache[ key ];
  12910. delete data.metadata;
  12911. values.push( data );
  12912. }
  12913. return values;
  12914. }
  12915. if ( isRootObject ) {
  12916. const textures = extractFromCache( meta.textures );
  12917. const images = extractFromCache( meta.images );
  12918. if ( textures.length > 0 ) data.textures = textures;
  12919. if ( images.length > 0 ) data.images = images;
  12920. }
  12921. return data;
  12922. }
  12923. /**
  12924. * Returns a new material with copied values from this instance.
  12925. *
  12926. * @return {Material} A clone of this instance.
  12927. */
  12928. clone() {
  12929. return new this.constructor().copy( this );
  12930. }
  12931. /**
  12932. * Copies the values of the given material to this instance.
  12933. *
  12934. * @param {Material} source - The material to copy.
  12935. * @return {Material} A reference to this instance.
  12936. */
  12937. copy( source ) {
  12938. this.name = source.name;
  12939. this.blending = source.blending;
  12940. this.side = source.side;
  12941. this.vertexColors = source.vertexColors;
  12942. this.opacity = source.opacity;
  12943. this.transparent = source.transparent;
  12944. this.blendSrc = source.blendSrc;
  12945. this.blendDst = source.blendDst;
  12946. this.blendEquation = source.blendEquation;
  12947. this.blendSrcAlpha = source.blendSrcAlpha;
  12948. this.blendDstAlpha = source.blendDstAlpha;
  12949. this.blendEquationAlpha = source.blendEquationAlpha;
  12950. this.blendColor.copy( source.blendColor );
  12951. this.blendAlpha = source.blendAlpha;
  12952. this.depthFunc = source.depthFunc;
  12953. this.depthTest = source.depthTest;
  12954. this.depthWrite = source.depthWrite;
  12955. this.stencilWriteMask = source.stencilWriteMask;
  12956. this.stencilFunc = source.stencilFunc;
  12957. this.stencilRef = source.stencilRef;
  12958. this.stencilFuncMask = source.stencilFuncMask;
  12959. this.stencilFail = source.stencilFail;
  12960. this.stencilZFail = source.stencilZFail;
  12961. this.stencilZPass = source.stencilZPass;
  12962. this.stencilWrite = source.stencilWrite;
  12963. const srcPlanes = source.clippingPlanes;
  12964. let dstPlanes = null;
  12965. if ( srcPlanes !== null ) {
  12966. const n = srcPlanes.length;
  12967. dstPlanes = new Array( n );
  12968. for ( let i = 0; i !== n; ++ i ) {
  12969. dstPlanes[ i ] = srcPlanes[ i ].clone();
  12970. }
  12971. }
  12972. this.clippingPlanes = dstPlanes;
  12973. this.clipIntersection = source.clipIntersection;
  12974. this.clipShadows = source.clipShadows;
  12975. this.shadowSide = source.shadowSide;
  12976. this.colorWrite = source.colorWrite;
  12977. this.precision = source.precision;
  12978. this.polygonOffset = source.polygonOffset;
  12979. this.polygonOffsetFactor = source.polygonOffsetFactor;
  12980. this.polygonOffsetUnits = source.polygonOffsetUnits;
  12981. this.dithering = source.dithering;
  12982. this.alphaTest = source.alphaTest;
  12983. this.alphaHash = source.alphaHash;
  12984. this.alphaToCoverage = source.alphaToCoverage;
  12985. this.premultipliedAlpha = source.premultipliedAlpha;
  12986. this.forceSinglePass = source.forceSinglePass;
  12987. this.visible = source.visible;
  12988. this.toneMapped = source.toneMapped;
  12989. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  12990. return this;
  12991. }
  12992. /**
  12993. * Frees the GPU-related resources allocated by this instance. Call this
  12994. * method whenever this instance is no longer used in your app.
  12995. *
  12996. * @fires Material#dispose
  12997. */
  12998. dispose() {
  12999. /**
  13000. * Fires when the material has been disposed of.
  13001. *
  13002. * @event Material#dispose
  13003. * @type {Object}
  13004. */
  13005. this.dispatchEvent( { type: 'dispose' } );
  13006. }
  13007. /**
  13008. * Setting this property to `true` indicates the engine the material
  13009. * needs to be recompiled.
  13010. *
  13011. * @type {boolean}
  13012. * @default false
  13013. * @param {boolean} value
  13014. */
  13015. set needsUpdate( value ) {
  13016. if ( value === true ) this.version ++;
  13017. }
  13018. }
  13019. /**
  13020. * A material for drawing geometries in a simple shaded (flat or wireframe) way.
  13021. *
  13022. * This material is not affected by lights.
  13023. *
  13024. * @augments Material
  13025. */
  13026. class MeshBasicMaterial extends Material {
  13027. /**
  13028. * Constructs a new mesh basic material.
  13029. *
  13030. * @param {Object} [parameters] - An object with one or more properties
  13031. * defining the material's appearance. Any property of the material
  13032. * (including any property from inherited materials) can be passed
  13033. * in here. Color values can be passed any type of value accepted
  13034. * by {@link Color#set}.
  13035. */
  13036. constructor( parameters ) {
  13037. super();
  13038. /**
  13039. * This flag can be used for type testing.
  13040. *
  13041. * @type {boolean}
  13042. * @readonly
  13043. * @default true
  13044. */
  13045. this.isMeshBasicMaterial = true;
  13046. this.type = 'MeshBasicMaterial';
  13047. /**
  13048. * Color of the material.
  13049. *
  13050. * @type {Color}
  13051. * @default (1,1,1)
  13052. */
  13053. this.color = new Color( 0xffffff ); // emissive
  13054. /**
  13055. * The color map. May optionally include an alpha channel, typically combined
  13056. * with {@link Material#transparent} or {@link Material#alphaTest}. The texture map
  13057. * color is modulated by the diffuse `color`.
  13058. *
  13059. * @type {?Texture}
  13060. * @default null
  13061. */
  13062. this.map = null;
  13063. /**
  13064. * The light map. Requires a second set of UVs.
  13065. *
  13066. * @type {?Texture}
  13067. * @default null
  13068. */
  13069. this.lightMap = null;
  13070. /**
  13071. * Intensity of the baked light.
  13072. *
  13073. * @type {number}
  13074. * @default 1
  13075. */
  13076. this.lightMapIntensity = 1.0;
  13077. /**
  13078. * The red channel of this texture is used as the ambient occlusion map.
  13079. * Requires a second set of UVs.
  13080. *
  13081. * @type {?Texture}
  13082. * @default null
  13083. */
  13084. this.aoMap = null;
  13085. /**
  13086. * Intensity of the ambient occlusion effect. Range is `[0,1]`, where `0`
  13087. * disables ambient occlusion. Where intensity is `1` and the AO map's
  13088. * red channel is also `1`, ambient light is fully occluded on a surface.
  13089. *
  13090. * @type {number}
  13091. * @default 1
  13092. */
  13093. this.aoMapIntensity = 1.0;
  13094. /**
  13095. * Specular map used by the material.
  13096. *
  13097. * @type {?Texture}
  13098. * @default null
  13099. */
  13100. this.specularMap = null;
  13101. /**
  13102. * The alpha map is a grayscale texture that controls the opacity across the
  13103. * surface (black: fully transparent; white: fully opaque).
  13104. *
  13105. * Only the color of the texture is used, ignoring the alpha channel if one
  13106. * exists. For RGB and RGBA textures, the renderer will use the green channel
  13107. * when sampling this texture due to the extra bit of precision provided for
  13108. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  13109. * luminance/alpha textures will also still work as expected.
  13110. *
  13111. * @type {?Texture}
  13112. * @default null
  13113. */
  13114. this.alphaMap = null;
  13115. /**
  13116. * The environment map.
  13117. *
  13118. * @type {?Texture}
  13119. * @default null
  13120. */
  13121. this.envMap = null;
  13122. /**
  13123. * The rotation of the environment map in radians.
  13124. *
  13125. * @type {Euler}
  13126. * @default (0,0,0)
  13127. */
  13128. this.envMapRotation = new Euler();
  13129. /**
  13130. * How to combine the result of the surface's color with the environment map, if any.
  13131. *
  13132. * When set to `MixOperation`, the {@link MeshBasicMaterial#reflectivity} is used to
  13133. * blend between the two colors.
  13134. *
  13135. * @type {(MultiplyOperation|MixOperation|AddOperation)}
  13136. * @default MultiplyOperation
  13137. */
  13138. this.combine = MultiplyOperation;
  13139. /**
  13140. * How much the environment map affects the surface.
  13141. * The valid range is between `0` (no reflections) and `1` (full reflections).
  13142. *
  13143. * @type {number}
  13144. * @default 1
  13145. */
  13146. this.reflectivity = 1;
  13147. /**
  13148. * The index of refraction (IOR) of air (approximately 1) divided by the
  13149. * index of refraction of the material. It is used with environment mapping
  13150. * modes {@link CubeRefractionMapping} and {@link EquirectangularRefractionMapping}.
  13151. * The refraction ratio should not exceed `1`.
  13152. *
  13153. * @type {number}
  13154. * @default 0.98
  13155. */
  13156. this.refractionRatio = 0.98;
  13157. /**
  13158. * Renders the geometry as a wireframe.
  13159. *
  13160. * @type {boolean}
  13161. * @default false
  13162. */
  13163. this.wireframe = false;
  13164. /**
  13165. * Controls the thickness of the wireframe.
  13166. *
  13167. * Can only be used with {@link SVGRenderer}.
  13168. *
  13169. * @type {number}
  13170. * @default 1
  13171. */
  13172. this.wireframeLinewidth = 1;
  13173. /**
  13174. * Defines appearance of wireframe ends.
  13175. *
  13176. * Can only be used with {@link SVGRenderer}.
  13177. *
  13178. * @type {('round'|'bevel'|'miter')}
  13179. * @default 'round'
  13180. */
  13181. this.wireframeLinecap = 'round';
  13182. /**
  13183. * Defines appearance of wireframe joints.
  13184. *
  13185. * Can only be used with {@link SVGRenderer}.
  13186. *
  13187. * @type {('round'|'bevel'|'miter')}
  13188. * @default 'round'
  13189. */
  13190. this.wireframeLinejoin = 'round';
  13191. /**
  13192. * Whether the material is affected by fog or not.
  13193. *
  13194. * @type {boolean}
  13195. * @default true
  13196. */
  13197. this.fog = true;
  13198. this.setValues( parameters );
  13199. }
  13200. copy( source ) {
  13201. super.copy( source );
  13202. this.color.copy( source.color );
  13203. this.map = source.map;
  13204. this.lightMap = source.lightMap;
  13205. this.lightMapIntensity = source.lightMapIntensity;
  13206. this.aoMap = source.aoMap;
  13207. this.aoMapIntensity = source.aoMapIntensity;
  13208. this.specularMap = source.specularMap;
  13209. this.alphaMap = source.alphaMap;
  13210. this.envMap = source.envMap;
  13211. this.envMapRotation.copy( source.envMapRotation );
  13212. this.combine = source.combine;
  13213. this.reflectivity = source.reflectivity;
  13214. this.refractionRatio = source.refractionRatio;
  13215. this.wireframe = source.wireframe;
  13216. this.wireframeLinewidth = source.wireframeLinewidth;
  13217. this.wireframeLinecap = source.wireframeLinecap;
  13218. this.wireframeLinejoin = source.wireframeLinejoin;
  13219. this.fog = source.fog;
  13220. return this;
  13221. }
  13222. }
  13223. // Fast Half Float Conversions, http://www.fox-toolkit.org/ftp/fasthalffloatconversion.pdf
  13224. const _tables = /*@__PURE__*/ _generateTables();
  13225. function _generateTables() {
  13226. // float32 to float16 helpers
  13227. const buffer = new ArrayBuffer( 4 );
  13228. const floatView = new Float32Array( buffer );
  13229. const uint32View = new Uint32Array( buffer );
  13230. const baseTable = new Uint32Array( 512 );
  13231. const shiftTable = new Uint32Array( 512 );
  13232. for ( let i = 0; i < 256; ++ i ) {
  13233. const e = i - 127;
  13234. // very small number (0, -0)
  13235. if ( e < -27 ) {
  13236. baseTable[ i ] = 0x0000;
  13237. baseTable[ i | 0x100 ] = 0x8000;
  13238. shiftTable[ i ] = 24;
  13239. shiftTable[ i | 0x100 ] = 24;
  13240. // small number (denorm)
  13241. } else if ( e < -14 ) {
  13242. baseTable[ i ] = 0x0400 >> ( - e - 14 );
  13243. baseTable[ i | 0x100 ] = ( 0x0400 >> ( - e - 14 ) ) | 0x8000;
  13244. shiftTable[ i ] = - e - 1;
  13245. shiftTable[ i | 0x100 ] = - e - 1;
  13246. // normal number
  13247. } else if ( e <= 15 ) {
  13248. baseTable[ i ] = ( e + 15 ) << 10;
  13249. baseTable[ i | 0x100 ] = ( ( e + 15 ) << 10 ) | 0x8000;
  13250. shiftTable[ i ] = 13;
  13251. shiftTable[ i | 0x100 ] = 13;
  13252. // large number (Infinity, -Infinity)
  13253. } else if ( e < 128 ) {
  13254. baseTable[ i ] = 0x7c00;
  13255. baseTable[ i | 0x100 ] = 0xfc00;
  13256. shiftTable[ i ] = 24;
  13257. shiftTable[ i | 0x100 ] = 24;
  13258. // stay (NaN, Infinity, -Infinity)
  13259. } else {
  13260. baseTable[ i ] = 0x7c00;
  13261. baseTable[ i | 0x100 ] = 0xfc00;
  13262. shiftTable[ i ] = 13;
  13263. shiftTable[ i | 0x100 ] = 13;
  13264. }
  13265. }
  13266. // float16 to float32 helpers
  13267. const mantissaTable = new Uint32Array( 2048 );
  13268. const exponentTable = new Uint32Array( 64 );
  13269. const offsetTable = new Uint32Array( 64 );
  13270. for ( let i = 1; i < 1024; ++ i ) {
  13271. let m = i << 13; // zero pad mantissa bits
  13272. let e = 0; // zero exponent
  13273. // normalized
  13274. while ( ( m & 0x00800000 ) === 0 ) {
  13275. m <<= 1;
  13276. e -= 0x00800000; // decrement exponent
  13277. }
  13278. m &= -8388609; // clear leading 1 bit
  13279. e += 0x38800000; // adjust bias
  13280. mantissaTable[ i ] = m | e;
  13281. }
  13282. for ( let i = 1024; i < 2048; ++ i ) {
  13283. mantissaTable[ i ] = 0x38000000 + ( ( i - 1024 ) << 13 );
  13284. }
  13285. for ( let i = 1; i < 31; ++ i ) {
  13286. exponentTable[ i ] = i << 23;
  13287. }
  13288. exponentTable[ 31 ] = 0x47800000;
  13289. exponentTable[ 32 ] = 0x80000000;
  13290. for ( let i = 33; i < 63; ++ i ) {
  13291. exponentTable[ i ] = 0x80000000 + ( ( i - 32 ) << 23 );
  13292. }
  13293. exponentTable[ 63 ] = 0xc7800000;
  13294. for ( let i = 1; i < 64; ++ i ) {
  13295. if ( i !== 32 ) {
  13296. offsetTable[ i ] = 1024;
  13297. }
  13298. }
  13299. return {
  13300. floatView: floatView,
  13301. uint32View: uint32View,
  13302. baseTable: baseTable,
  13303. shiftTable: shiftTable,
  13304. mantissaTable: mantissaTable,
  13305. exponentTable: exponentTable,
  13306. offsetTable: offsetTable
  13307. };
  13308. }
  13309. /**
  13310. * Returns a half precision floating point value (FP16) from the given single
  13311. * precision floating point value (FP32).
  13312. *
  13313. * @param {number} val - A single precision floating point value.
  13314. * @return {number} The FP16 value.
  13315. */
  13316. function toHalfFloat( val ) {
  13317. if ( Math.abs( val ) > 65504 ) console.warn( 'THREE.DataUtils.toHalfFloat(): Value out of range.' );
  13318. val = clamp( val, -65504, 65504 );
  13319. _tables.floatView[ 0 ] = val;
  13320. const f = _tables.uint32View[ 0 ];
  13321. const e = ( f >> 23 ) & 0x1ff;
  13322. return _tables.baseTable[ e ] + ( ( f & 0x007fffff ) >> _tables.shiftTable[ e ] );
  13323. }
  13324. /**
  13325. * Returns a single precision floating point value (FP32) from the given half
  13326. * precision floating point value (FP16).
  13327. *
  13328. * @param {number} val - A half precision floating point value.
  13329. * @return {number} The FP32 value.
  13330. */
  13331. function fromHalfFloat( val ) {
  13332. const m = val >> 10;
  13333. _tables.uint32View[ 0 ] = _tables.mantissaTable[ _tables.offsetTable[ m ] + ( val & 0x3ff ) ] + _tables.exponentTable[ m ];
  13334. return _tables.floatView[ 0 ];
  13335. }
  13336. /**
  13337. * A class containing utility functions for data.
  13338. *
  13339. * @hideconstructor
  13340. */
  13341. class DataUtils {
  13342. /**
  13343. * Returns a half precision floating point value (FP16) from the given single
  13344. * precision floating point value (FP32).
  13345. *
  13346. * @param {number} val - A single precision floating point value.
  13347. * @return {number} The FP16 value.
  13348. */
  13349. static toHalfFloat( val ) {
  13350. return toHalfFloat( val );
  13351. }
  13352. /**
  13353. * Returns a single precision floating point value (FP32) from the given half
  13354. * precision floating point value (FP16).
  13355. *
  13356. * @param {number} val - A half precision floating point value.
  13357. * @return {number} The FP32 value.
  13358. */
  13359. static fromHalfFloat( val ) {
  13360. return fromHalfFloat( val );
  13361. }
  13362. }
  13363. const _vector$9 = /*@__PURE__*/ new Vector3();
  13364. const _vector2$1 = /*@__PURE__*/ new Vector2();
  13365. let _id$2 = 0;
  13366. /**
  13367. * This class stores data for an attribute (such as vertex positions, face
  13368. * indices, normals, colors, UVs, and any custom attributes ) associated with
  13369. * a geometry, which allows for more efficient passing of data to the GPU.
  13370. *
  13371. * When working with vector-like data, the `fromBufferAttribute( attribute, index )`
  13372. * helper methods on vector and color class might be helpful. E.g. {@link Vector3#fromBufferAttribute}.
  13373. */
  13374. class BufferAttribute {
  13375. /**
  13376. * Constructs a new buffer attribute.
  13377. *
  13378. * @param {TypedArray} array - The array holding the attribute data.
  13379. * @param {number} itemSize - The item size.
  13380. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  13381. */
  13382. constructor( array, itemSize, normalized = false ) {
  13383. if ( Array.isArray( array ) ) {
  13384. throw new TypeError( 'THREE.BufferAttribute: array should be a Typed Array.' );
  13385. }
  13386. /**
  13387. * This flag can be used for type testing.
  13388. *
  13389. * @type {boolean}
  13390. * @readonly
  13391. * @default true
  13392. */
  13393. this.isBufferAttribute = true;
  13394. /**
  13395. * The ID of the buffer attribute.
  13396. *
  13397. * @name BufferAttribute#id
  13398. * @type {number}
  13399. * @readonly
  13400. */
  13401. Object.defineProperty( this, 'id', { value: _id$2 ++ } );
  13402. /**
  13403. * The name of the buffer attribute.
  13404. *
  13405. * @type {string}
  13406. */
  13407. this.name = '';
  13408. /**
  13409. * The array holding the attribute data. It should have `itemSize * numVertices`
  13410. * elements, where `numVertices` is the number of vertices in the associated geometry.
  13411. *
  13412. * @type {TypedArray}
  13413. */
  13414. this.array = array;
  13415. /**
  13416. * The number of values of the array that should be associated with a particular vertex.
  13417. * For instance, if this attribute is storing a 3-component vector (such as a position,
  13418. * normal, or color), then the value should be `3`.
  13419. *
  13420. * @type {number}
  13421. */
  13422. this.itemSize = itemSize;
  13423. /**
  13424. * Represents the number of items this buffer attribute stores. It is internally computed
  13425. * by dividing the `array` length by the `itemSize`.
  13426. *
  13427. * @type {number}
  13428. * @readonly
  13429. */
  13430. this.count = array !== undefined ? array.length / itemSize : 0;
  13431. /**
  13432. * Applies to integer data only. Indicates how the underlying data in the buffer maps to
  13433. * the values in the GLSL code. For instance, if `array` is an instance of `UInt16Array`,
  13434. * and `normalized` is `true`, the values `0 -+65535` in the array data will be mapped to
  13435. * `0.0f - +1.0f` in the GLSL attribute. If `normalized` is `false`, the values will be converted
  13436. * to floats unmodified, i.e. `65535` becomes `65535.0f`.
  13437. *
  13438. * @type {boolean}
  13439. */
  13440. this.normalized = normalized;
  13441. /**
  13442. * Defines the intended usage pattern of the data store for optimization purposes.
  13443. *
  13444. * Note: After the initial use of a buffer, its usage cannot be changed. Instead,
  13445. * instantiate a new one and set the desired usage before the next render.
  13446. *
  13447. * @type {(StaticDrawUsage|DynamicDrawUsage|StreamDrawUsage|StaticReadUsage|DynamicReadUsage|StreamReadUsage|StaticCopyUsage|DynamicCopyUsage|StreamCopyUsage)}
  13448. * @default StaticDrawUsage
  13449. */
  13450. this.usage = StaticDrawUsage;
  13451. /**
  13452. * This can be used to only update some components of stored vectors (for example, just the
  13453. * component related to color). Use the `addUpdateRange()` function to add ranges to this array.
  13454. *
  13455. * @type {Array<Object>}
  13456. */
  13457. this.updateRanges = [];
  13458. /**
  13459. * Configures the bound GPU type for use in shaders.
  13460. *
  13461. * Note: this only has an effect for integer arrays and is not configurable for float arrays.
  13462. * For lower precision float types, use `Float16BufferAttribute`.
  13463. *
  13464. * @type {(FloatType|IntType)}
  13465. * @default FloatType
  13466. */
  13467. this.gpuType = FloatType;
  13468. /**
  13469. * A version number, incremented every time the `needsUpdate` is set to `true`.
  13470. *
  13471. * @type {number}
  13472. */
  13473. this.version = 0;
  13474. }
  13475. /**
  13476. * A callback function that is executed after the renderer has transferred the attribute
  13477. * array data to the GPU.
  13478. */
  13479. onUploadCallback() {}
  13480. /**
  13481. * Flag to indicate that this attribute has changed and should be re-sent to
  13482. * the GPU. Set this to `true` when you modify the value of the array.
  13483. *
  13484. * @type {number}
  13485. * @default false
  13486. * @param {boolean} value
  13487. */
  13488. set needsUpdate( value ) {
  13489. if ( value === true ) this.version ++;
  13490. }
  13491. /**
  13492. * Sets the usage of this buffer attribute.
  13493. *
  13494. * @param {(StaticDrawUsage|DynamicDrawUsage|StreamDrawUsage|StaticReadUsage|DynamicReadUsage|StreamReadUsage|StaticCopyUsage|DynamicCopyUsage|StreamCopyUsage)} value - The usage to set.
  13495. * @return {BufferAttribute} A reference to this buffer attribute.
  13496. */
  13497. setUsage( value ) {
  13498. this.usage = value;
  13499. return this;
  13500. }
  13501. /**
  13502. * Adds a range of data in the data array to be updated on the GPU.
  13503. *
  13504. * @param {number} start - Position at which to start update.
  13505. * @param {number} count - The number of components to update.
  13506. */
  13507. addUpdateRange( start, count ) {
  13508. this.updateRanges.push( { start, count } );
  13509. }
  13510. /**
  13511. * Clears the update ranges.
  13512. */
  13513. clearUpdateRanges() {
  13514. this.updateRanges.length = 0;
  13515. }
  13516. /**
  13517. * Copies the values of the given buffer attribute to this instance.
  13518. *
  13519. * @param {BufferAttribute} source - The buffer attribute to copy.
  13520. * @return {BufferAttribute} A reference to this instance.
  13521. */
  13522. copy( source ) {
  13523. this.name = source.name;
  13524. this.array = new source.array.constructor( source.array );
  13525. this.itemSize = source.itemSize;
  13526. this.count = source.count;
  13527. this.normalized = source.normalized;
  13528. this.usage = source.usage;
  13529. this.gpuType = source.gpuType;
  13530. return this;
  13531. }
  13532. /**
  13533. * Copies a vector from the given buffer attribute to this one. The start
  13534. * and destination position in the attribute buffers are represented by the
  13535. * given indices.
  13536. *
  13537. * @param {number} index1 - The destination index into this buffer attribute.
  13538. * @param {BufferAttribute} attribute - The buffer attribute to copy from.
  13539. * @param {number} index2 - The source index into the given buffer attribute.
  13540. * @return {BufferAttribute} A reference to this instance.
  13541. */
  13542. copyAt( index1, attribute, index2 ) {
  13543. index1 *= this.itemSize;
  13544. index2 *= attribute.itemSize;
  13545. for ( let i = 0, l = this.itemSize; i < l; i ++ ) {
  13546. this.array[ index1 + i ] = attribute.array[ index2 + i ];
  13547. }
  13548. return this;
  13549. }
  13550. /**
  13551. * Copies the given array data into this buffer attribute.
  13552. *
  13553. * @param {(TypedArray|Array)} array - The array to copy.
  13554. * @return {BufferAttribute} A reference to this instance.
  13555. */
  13556. copyArray( array ) {
  13557. this.array.set( array );
  13558. return this;
  13559. }
  13560. /**
  13561. * Applies the given 3x3 matrix to the given attribute. Works with
  13562. * item size `2` and `3`.
  13563. *
  13564. * @param {Matrix3} m - The matrix to apply.
  13565. * @return {BufferAttribute} A reference to this instance.
  13566. */
  13567. applyMatrix3( m ) {
  13568. if ( this.itemSize === 2 ) {
  13569. for ( let i = 0, l = this.count; i < l; i ++ ) {
  13570. _vector2$1.fromBufferAttribute( this, i );
  13571. _vector2$1.applyMatrix3( m );
  13572. this.setXY( i, _vector2$1.x, _vector2$1.y );
  13573. }
  13574. } else if ( this.itemSize === 3 ) {
  13575. for ( let i = 0, l = this.count; i < l; i ++ ) {
  13576. _vector$9.fromBufferAttribute( this, i );
  13577. _vector$9.applyMatrix3( m );
  13578. this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  13579. }
  13580. }
  13581. return this;
  13582. }
  13583. /**
  13584. * Applies the given 4x4 matrix to the given attribute. Only works with
  13585. * item size `3`.
  13586. *
  13587. * @param {Matrix4} m - The matrix to apply.
  13588. * @return {BufferAttribute} A reference to this instance.
  13589. */
  13590. applyMatrix4( m ) {
  13591. for ( let i = 0, l = this.count; i < l; i ++ ) {
  13592. _vector$9.fromBufferAttribute( this, i );
  13593. _vector$9.applyMatrix4( m );
  13594. this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  13595. }
  13596. return this;
  13597. }
  13598. /**
  13599. * Applies the given 3x3 normal matrix to the given attribute. Only works with
  13600. * item size `3`.
  13601. *
  13602. * @param {Matrix3} m - The normal matrix to apply.
  13603. * @return {BufferAttribute} A reference to this instance.
  13604. */
  13605. applyNormalMatrix( m ) {
  13606. for ( let i = 0, l = this.count; i < l; i ++ ) {
  13607. _vector$9.fromBufferAttribute( this, i );
  13608. _vector$9.applyNormalMatrix( m );
  13609. this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  13610. }
  13611. return this;
  13612. }
  13613. /**
  13614. * Applies the given 4x4 matrix to the given attribute. Only works with
  13615. * item size `3` and with direction vectors.
  13616. *
  13617. * @param {Matrix4} m - The matrix to apply.
  13618. * @return {BufferAttribute} A reference to this instance.
  13619. */
  13620. transformDirection( m ) {
  13621. for ( let i = 0, l = this.count; i < l; i ++ ) {
  13622. _vector$9.fromBufferAttribute( this, i );
  13623. _vector$9.transformDirection( m );
  13624. this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  13625. }
  13626. return this;
  13627. }
  13628. /**
  13629. * Sets the given array data in the buffer attribute.
  13630. *
  13631. * @param {(TypedArray|Array)} value - The array data to set.
  13632. * @param {number} [offset=0] - The offset in this buffer attribute's array.
  13633. * @return {BufferAttribute} A reference to this instance.
  13634. */
  13635. set( value, offset = 0 ) {
  13636. // Matching BufferAttribute constructor, do not normalize the array.
  13637. this.array.set( value, offset );
  13638. return this;
  13639. }
  13640. /**
  13641. * Returns the given component of the vector at the given index.
  13642. *
  13643. * @param {number} index - The index into the buffer attribute.
  13644. * @param {number} component - The component index.
  13645. * @return {number} The returned value.
  13646. */
  13647. getComponent( index, component ) {
  13648. let value = this.array[ index * this.itemSize + component ];
  13649. if ( this.normalized ) value = denormalize( value, this.array );
  13650. return value;
  13651. }
  13652. /**
  13653. * Sets the given value to the given component of the vector at the given index.
  13654. *
  13655. * @param {number} index - The index into the buffer attribute.
  13656. * @param {number} component - The component index.
  13657. * @param {number} value - The value to set.
  13658. * @return {BufferAttribute} A reference to this instance.
  13659. */
  13660. setComponent( index, component, value ) {
  13661. if ( this.normalized ) value = normalize( value, this.array );
  13662. this.array[ index * this.itemSize + component ] = value;
  13663. return this;
  13664. }
  13665. /**
  13666. * Returns the x component of the vector at the given index.
  13667. *
  13668. * @param {number} index - The index into the buffer attribute.
  13669. * @return {number} The x component.
  13670. */
  13671. getX( index ) {
  13672. let x = this.array[ index * this.itemSize ];
  13673. if ( this.normalized ) x = denormalize( x, this.array );
  13674. return x;
  13675. }
  13676. /**
  13677. * Sets the x component of the vector at the given index.
  13678. *
  13679. * @param {number} index - The index into the buffer attribute.
  13680. * @param {number} x - The value to set.
  13681. * @return {BufferAttribute} A reference to this instance.
  13682. */
  13683. setX( index, x ) {
  13684. if ( this.normalized ) x = normalize( x, this.array );
  13685. this.array[ index * this.itemSize ] = x;
  13686. return this;
  13687. }
  13688. /**
  13689. * Returns the y component of the vector at the given index.
  13690. *
  13691. * @param {number} index - The index into the buffer attribute.
  13692. * @return {number} The y component.
  13693. */
  13694. getY( index ) {
  13695. let y = this.array[ index * this.itemSize + 1 ];
  13696. if ( this.normalized ) y = denormalize( y, this.array );
  13697. return y;
  13698. }
  13699. /**
  13700. * Sets the y component of the vector at the given index.
  13701. *
  13702. * @param {number} index - The index into the buffer attribute.
  13703. * @param {number} y - The value to set.
  13704. * @return {BufferAttribute} A reference to this instance.
  13705. */
  13706. setY( index, y ) {
  13707. if ( this.normalized ) y = normalize( y, this.array );
  13708. this.array[ index * this.itemSize + 1 ] = y;
  13709. return this;
  13710. }
  13711. /**
  13712. * Returns the z component of the vector at the given index.
  13713. *
  13714. * @param {number} index - The index into the buffer attribute.
  13715. * @return {number} The z component.
  13716. */
  13717. getZ( index ) {
  13718. let z = this.array[ index * this.itemSize + 2 ];
  13719. if ( this.normalized ) z = denormalize( z, this.array );
  13720. return z;
  13721. }
  13722. /**
  13723. * Sets the z component of the vector at the given index.
  13724. *
  13725. * @param {number} index - The index into the buffer attribute.
  13726. * @param {number} z - The value to set.
  13727. * @return {BufferAttribute} A reference to this instance.
  13728. */
  13729. setZ( index, z ) {
  13730. if ( this.normalized ) z = normalize( z, this.array );
  13731. this.array[ index * this.itemSize + 2 ] = z;
  13732. return this;
  13733. }
  13734. /**
  13735. * Returns the w component of the vector at the given index.
  13736. *
  13737. * @param {number} index - The index into the buffer attribute.
  13738. * @return {number} The w component.
  13739. */
  13740. getW( index ) {
  13741. let w = this.array[ index * this.itemSize + 3 ];
  13742. if ( this.normalized ) w = denormalize( w, this.array );
  13743. return w;
  13744. }
  13745. /**
  13746. * Sets the w component of the vector at the given index.
  13747. *
  13748. * @param {number} index - The index into the buffer attribute.
  13749. * @param {number} w - The value to set.
  13750. * @return {BufferAttribute} A reference to this instance.
  13751. */
  13752. setW( index, w ) {
  13753. if ( this.normalized ) w = normalize( w, this.array );
  13754. this.array[ index * this.itemSize + 3 ] = w;
  13755. return this;
  13756. }
  13757. /**
  13758. * Sets the x and y component of the vector at the given index.
  13759. *
  13760. * @param {number} index - The index into the buffer attribute.
  13761. * @param {number} x - The value for the x component to set.
  13762. * @param {number} y - The value for the y component to set.
  13763. * @return {BufferAttribute} A reference to this instance.
  13764. */
  13765. setXY( index, x, y ) {
  13766. index *= this.itemSize;
  13767. if ( this.normalized ) {
  13768. x = normalize( x, this.array );
  13769. y = normalize( y, this.array );
  13770. }
  13771. this.array[ index + 0 ] = x;
  13772. this.array[ index + 1 ] = y;
  13773. return this;
  13774. }
  13775. /**
  13776. * Sets the x, y and z component of the vector at the given index.
  13777. *
  13778. * @param {number} index - The index into the buffer attribute.
  13779. * @param {number} x - The value for the x component to set.
  13780. * @param {number} y - The value for the y component to set.
  13781. * @param {number} z - The value for the z component to set.
  13782. * @return {BufferAttribute} A reference to this instance.
  13783. */
  13784. setXYZ( index, x, y, z ) {
  13785. index *= this.itemSize;
  13786. if ( this.normalized ) {
  13787. x = normalize( x, this.array );
  13788. y = normalize( y, this.array );
  13789. z = normalize( z, this.array );
  13790. }
  13791. this.array[ index + 0 ] = x;
  13792. this.array[ index + 1 ] = y;
  13793. this.array[ index + 2 ] = z;
  13794. return this;
  13795. }
  13796. /**
  13797. * Sets the x, y, z and w component of the vector at the given index.
  13798. *
  13799. * @param {number} index - The index into the buffer attribute.
  13800. * @param {number} x - The value for the x component to set.
  13801. * @param {number} y - The value for the y component to set.
  13802. * @param {number} z - The value for the z component to set.
  13803. * @param {number} w - The value for the w component to set.
  13804. * @return {BufferAttribute} A reference to this instance.
  13805. */
  13806. setXYZW( index, x, y, z, w ) {
  13807. index *= this.itemSize;
  13808. if ( this.normalized ) {
  13809. x = normalize( x, this.array );
  13810. y = normalize( y, this.array );
  13811. z = normalize( z, this.array );
  13812. w = normalize( w, this.array );
  13813. }
  13814. this.array[ index + 0 ] = x;
  13815. this.array[ index + 1 ] = y;
  13816. this.array[ index + 2 ] = z;
  13817. this.array[ index + 3 ] = w;
  13818. return this;
  13819. }
  13820. /**
  13821. * Sets the given callback function that is executed after the Renderer has transferred
  13822. * the attribute array data to the GPU. Can be used to perform clean-up operations after
  13823. * the upload when attribute data are not needed anymore on the CPU side.
  13824. *
  13825. * @param {Function} callback - The `onUpload()` callback.
  13826. * @return {BufferAttribute} A reference to this instance.
  13827. */
  13828. onUpload( callback ) {
  13829. this.onUploadCallback = callback;
  13830. return this;
  13831. }
  13832. /**
  13833. * Returns a new buffer attribute with copied values from this instance.
  13834. *
  13835. * @return {BufferAttribute} A clone of this instance.
  13836. */
  13837. clone() {
  13838. return new this.constructor( this.array, this.itemSize ).copy( this );
  13839. }
  13840. /**
  13841. * Serializes the buffer attribute into JSON.
  13842. *
  13843. * @return {Object} A JSON object representing the serialized buffer attribute.
  13844. */
  13845. toJSON() {
  13846. const data = {
  13847. itemSize: this.itemSize,
  13848. type: this.array.constructor.name,
  13849. array: Array.from( this.array ),
  13850. normalized: this.normalized
  13851. };
  13852. if ( this.name !== '' ) data.name = this.name;
  13853. if ( this.usage !== StaticDrawUsage ) data.usage = this.usage;
  13854. return data;
  13855. }
  13856. }
  13857. /**
  13858. * Convenient class that can be used when creating a `Int8` buffer attribute with
  13859. * a plain `Array` instance.
  13860. *
  13861. * @augments BufferAttribute
  13862. */
  13863. class Int8BufferAttribute extends BufferAttribute {
  13864. /**
  13865. * Constructs a new buffer attribute.
  13866. *
  13867. * @param {(Array<number>|Int8Array)} array - The array holding the attribute data.
  13868. * @param {number} itemSize - The item size.
  13869. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  13870. */
  13871. constructor( array, itemSize, normalized ) {
  13872. super( new Int8Array( array ), itemSize, normalized );
  13873. }
  13874. }
  13875. /**
  13876. * Convenient class that can be used when creating a `UInt8` buffer attribute with
  13877. * a plain `Array` instance.
  13878. *
  13879. * @augments BufferAttribute
  13880. */
  13881. class Uint8BufferAttribute extends BufferAttribute {
  13882. /**
  13883. * Constructs a new buffer attribute.
  13884. *
  13885. * @param {(Array<number>|Uint8Array)} array - The array holding the attribute data.
  13886. * @param {number} itemSize - The item size.
  13887. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  13888. */
  13889. constructor( array, itemSize, normalized ) {
  13890. super( new Uint8Array( array ), itemSize, normalized );
  13891. }
  13892. }
  13893. /**
  13894. * Convenient class that can be used when creating a `UInt8Clamped` buffer attribute with
  13895. * a plain `Array` instance.
  13896. *
  13897. * @augments BufferAttribute
  13898. */
  13899. class Uint8ClampedBufferAttribute extends BufferAttribute {
  13900. /**
  13901. * Constructs a new buffer attribute.
  13902. *
  13903. * @param {(Array<number>|Uint8ClampedArray)} array - The array holding the attribute data.
  13904. * @param {number} itemSize - The item size.
  13905. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  13906. */
  13907. constructor( array, itemSize, normalized ) {
  13908. super( new Uint8ClampedArray( array ), itemSize, normalized );
  13909. }
  13910. }
  13911. /**
  13912. * Convenient class that can be used when creating a `Int16` buffer attribute with
  13913. * a plain `Array` instance.
  13914. *
  13915. * @augments BufferAttribute
  13916. */
  13917. class Int16BufferAttribute extends BufferAttribute {
  13918. /**
  13919. * Constructs a new buffer attribute.
  13920. *
  13921. * @param {(Array<number>|Int16Array)} array - The array holding the attribute data.
  13922. * @param {number} itemSize - The item size.
  13923. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  13924. */
  13925. constructor( array, itemSize, normalized ) {
  13926. super( new Int16Array( array ), itemSize, normalized );
  13927. }
  13928. }
  13929. /**
  13930. * Convenient class that can be used when creating a `UInt16` buffer attribute with
  13931. * a plain `Array` instance.
  13932. *
  13933. * @augments BufferAttribute
  13934. */
  13935. class Uint16BufferAttribute extends BufferAttribute {
  13936. /**
  13937. * Constructs a new buffer attribute.
  13938. *
  13939. * @param {(Array<number>|Uint16Array)} array - The array holding the attribute data.
  13940. * @param {number} itemSize - The item size.
  13941. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  13942. */
  13943. constructor( array, itemSize, normalized ) {
  13944. super( new Uint16Array( array ), itemSize, normalized );
  13945. }
  13946. }
  13947. /**
  13948. * Convenient class that can be used when creating a `Int32` buffer attribute with
  13949. * a plain `Array` instance.
  13950. *
  13951. * @augments BufferAttribute
  13952. */
  13953. class Int32BufferAttribute extends BufferAttribute {
  13954. /**
  13955. * Constructs a new buffer attribute.
  13956. *
  13957. * @param {(Array<number>|Int32Array)} array - The array holding the attribute data.
  13958. * @param {number} itemSize - The item size.
  13959. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  13960. */
  13961. constructor( array, itemSize, normalized ) {
  13962. super( new Int32Array( array ), itemSize, normalized );
  13963. }
  13964. }
  13965. /**
  13966. * Convenient class that can be used when creating a `UInt32` buffer attribute with
  13967. * a plain `Array` instance.
  13968. *
  13969. * @augments BufferAttribute
  13970. */
  13971. class Uint32BufferAttribute extends BufferAttribute {
  13972. /**
  13973. * Constructs a new buffer attribute.
  13974. *
  13975. * @param {(Array<number>|Uint32Array)} array - The array holding the attribute data.
  13976. * @param {number} itemSize - The item size.
  13977. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  13978. */
  13979. constructor( array, itemSize, normalized ) {
  13980. super( new Uint32Array( array ), itemSize, normalized );
  13981. }
  13982. }
  13983. /**
  13984. * Convenient class that can be used when creating a `Float16` buffer attribute with
  13985. * a plain `Array` instance.
  13986. *
  13987. * This class automatically converts to and from FP16 since `Float16Array` is not
  13988. * natively supported in JavaScript.
  13989. *
  13990. * @augments BufferAttribute
  13991. */
  13992. class Float16BufferAttribute extends BufferAttribute {
  13993. /**
  13994. * Constructs a new buffer attribute.
  13995. *
  13996. * @param {(Array<number>|Uint16Array)} array - The array holding the attribute data.
  13997. * @param {number} itemSize - The item size.
  13998. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  13999. */
  14000. constructor( array, itemSize, normalized ) {
  14001. super( new Uint16Array( array ), itemSize, normalized );
  14002. this.isFloat16BufferAttribute = true;
  14003. }
  14004. getX( index ) {
  14005. let x = fromHalfFloat( this.array[ index * this.itemSize ] );
  14006. if ( this.normalized ) x = denormalize( x, this.array );
  14007. return x;
  14008. }
  14009. setX( index, x ) {
  14010. if ( this.normalized ) x = normalize( x, this.array );
  14011. this.array[ index * this.itemSize ] = toHalfFloat( x );
  14012. return this;
  14013. }
  14014. getY( index ) {
  14015. let y = fromHalfFloat( this.array[ index * this.itemSize + 1 ] );
  14016. if ( this.normalized ) y = denormalize( y, this.array );
  14017. return y;
  14018. }
  14019. setY( index, y ) {
  14020. if ( this.normalized ) y = normalize( y, this.array );
  14021. this.array[ index * this.itemSize + 1 ] = toHalfFloat( y );
  14022. return this;
  14023. }
  14024. getZ( index ) {
  14025. let z = fromHalfFloat( this.array[ index * this.itemSize + 2 ] );
  14026. if ( this.normalized ) z = denormalize( z, this.array );
  14027. return z;
  14028. }
  14029. setZ( index, z ) {
  14030. if ( this.normalized ) z = normalize( z, this.array );
  14031. this.array[ index * this.itemSize + 2 ] = toHalfFloat( z );
  14032. return this;
  14033. }
  14034. getW( index ) {
  14035. let w = fromHalfFloat( this.array[ index * this.itemSize + 3 ] );
  14036. if ( this.normalized ) w = denormalize( w, this.array );
  14037. return w;
  14038. }
  14039. setW( index, w ) {
  14040. if ( this.normalized ) w = normalize( w, this.array );
  14041. this.array[ index * this.itemSize + 3 ] = toHalfFloat( w );
  14042. return this;
  14043. }
  14044. setXY( index, x, y ) {
  14045. index *= this.itemSize;
  14046. if ( this.normalized ) {
  14047. x = normalize( x, this.array );
  14048. y = normalize( y, this.array );
  14049. }
  14050. this.array[ index + 0 ] = toHalfFloat( x );
  14051. this.array[ index + 1 ] = toHalfFloat( y );
  14052. return this;
  14053. }
  14054. setXYZ( index, x, y, z ) {
  14055. index *= this.itemSize;
  14056. if ( this.normalized ) {
  14057. x = normalize( x, this.array );
  14058. y = normalize( y, this.array );
  14059. z = normalize( z, this.array );
  14060. }
  14061. this.array[ index + 0 ] = toHalfFloat( x );
  14062. this.array[ index + 1 ] = toHalfFloat( y );
  14063. this.array[ index + 2 ] = toHalfFloat( z );
  14064. return this;
  14065. }
  14066. setXYZW( index, x, y, z, w ) {
  14067. index *= this.itemSize;
  14068. if ( this.normalized ) {
  14069. x = normalize( x, this.array );
  14070. y = normalize( y, this.array );
  14071. z = normalize( z, this.array );
  14072. w = normalize( w, this.array );
  14073. }
  14074. this.array[ index + 0 ] = toHalfFloat( x );
  14075. this.array[ index + 1 ] = toHalfFloat( y );
  14076. this.array[ index + 2 ] = toHalfFloat( z );
  14077. this.array[ index + 3 ] = toHalfFloat( w );
  14078. return this;
  14079. }
  14080. }
  14081. /**
  14082. * Convenient class that can be used when creating a `Float32` buffer attribute with
  14083. * a plain `Array` instance.
  14084. *
  14085. * @augments BufferAttribute
  14086. */
  14087. class Float32BufferAttribute extends BufferAttribute {
  14088. /**
  14089. * Constructs a new buffer attribute.
  14090. *
  14091. * @param {(Array<number>|Float32Array)} array - The array holding the attribute data.
  14092. * @param {number} itemSize - The item size.
  14093. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  14094. */
  14095. constructor( array, itemSize, normalized ) {
  14096. super( new Float32Array( array ), itemSize, normalized );
  14097. }
  14098. }
  14099. let _id$1 = 0;
  14100. const _m1 = /*@__PURE__*/ new Matrix4();
  14101. const _obj = /*@__PURE__*/ new Object3D();
  14102. const _offset = /*@__PURE__*/ new Vector3();
  14103. const _box$2 = /*@__PURE__*/ new Box3();
  14104. const _boxMorphTargets = /*@__PURE__*/ new Box3();
  14105. const _vector$8 = /*@__PURE__*/ new Vector3();
  14106. /**
  14107. * A representation of mesh, line, or point geometry. Includes vertex
  14108. * positions, face indices, normals, colors, UVs, and custom attributes
  14109. * within buffers, reducing the cost of passing all this data to the GPU.
  14110. *
  14111. * ```js
  14112. * const geometry = new THREE.BufferGeometry();
  14113. * // create a simple square shape. We duplicate the top left and bottom right
  14114. * // vertices because each vertex needs to appear once per triangle.
  14115. * const vertices = new Float32Array( [
  14116. * -1.0, -1.0, 1.0, // v0
  14117. * 1.0, -1.0, 1.0, // v1
  14118. * 1.0, 1.0, 1.0, // v2
  14119. *
  14120. * 1.0, 1.0, 1.0, // v3
  14121. * -1.0, 1.0, 1.0, // v4
  14122. * -1.0, -1.0, 1.0 // v5
  14123. * ] );
  14124. * // itemSize = 3 because there are 3 values (components) per vertex
  14125. * geometry.setAttribute( 'position', new THREE.BufferAttribute( vertices, 3 ) );
  14126. * const material = new THREE.MeshBasicMaterial( { color: 0xff0000 } );
  14127. * const mesh = new THREE.Mesh( geometry, material );
  14128. * ```
  14129. *
  14130. * @augments EventDispatcher
  14131. */
  14132. class BufferGeometry extends EventDispatcher {
  14133. /**
  14134. * Constructs a new geometry.
  14135. */
  14136. constructor() {
  14137. super();
  14138. /**
  14139. * This flag can be used for type testing.
  14140. *
  14141. * @type {boolean}
  14142. * @readonly
  14143. * @default true
  14144. */
  14145. this.isBufferGeometry = true;
  14146. /**
  14147. * The ID of the geometry.
  14148. *
  14149. * @name BufferGeometry#id
  14150. * @type {number}
  14151. * @readonly
  14152. */
  14153. Object.defineProperty( this, 'id', { value: _id$1 ++ } );
  14154. /**
  14155. * The UUID of the geometry.
  14156. *
  14157. * @type {string}
  14158. * @readonly
  14159. */
  14160. this.uuid = generateUUID();
  14161. /**
  14162. * The name of the geometry.
  14163. *
  14164. * @type {string}
  14165. */
  14166. this.name = '';
  14167. this.type = 'BufferGeometry';
  14168. /**
  14169. * Allows for vertices to be re-used across multiple triangles; this is
  14170. * called using "indexed triangles". Each triangle is associated with the
  14171. * indices of three vertices. This attribute therefore stores the index of
  14172. * each vertex for each triangular face. If this attribute is not set, the
  14173. * renderer assumes that each three contiguous positions represent a single triangle.
  14174. *
  14175. * @type {?BufferAttribute}
  14176. * @default null
  14177. */
  14178. this.index = null;
  14179. /**
  14180. * A (storage) buffer attribute which was generated with a compute shader and
  14181. * now defines indirect draw calls.
  14182. *
  14183. * Can only be used with {@link WebGPURenderer} and a WebGPU backend.
  14184. *
  14185. * @type {?BufferAttribute}
  14186. * @default null
  14187. */
  14188. this.indirect = null;
  14189. /**
  14190. * This dictionary has as id the name of the attribute to be set and as value
  14191. * the buffer attribute to set it to. Rather than accessing this property directly,
  14192. * use `setAttribute()` and `getAttribute()` to access attributes of this geometry.
  14193. *
  14194. * @type {Object<string,(BufferAttribute|InterleavedBufferAttribute)>}
  14195. */
  14196. this.attributes = {};
  14197. /**
  14198. * This dictionary holds the morph targets of the geometry.
  14199. *
  14200. * Note: Once the geometry has been rendered, the morph attribute data cannot
  14201. * be changed. You will have to call `dispose()?, and create a new geometry instance.
  14202. *
  14203. * @type {Object}
  14204. */
  14205. this.morphAttributes = {};
  14206. /**
  14207. * Used to control the morph target behavior; when set to `true`, the morph
  14208. * target data is treated as relative offsets, rather than as absolute
  14209. * positions/normals.
  14210. *
  14211. * @type {boolean}
  14212. * @default false
  14213. */
  14214. this.morphTargetsRelative = false;
  14215. /**
  14216. * Split the geometry into groups, each of which will be rendered in a
  14217. * separate draw call. This allows an array of materials to be used with the geometry.
  14218. *
  14219. * Use `addGroup()` and `clearGroups()` to edit groups, rather than modifying this array directly.
  14220. *
  14221. * Every vertex and index must belong to exactly one group — groups must not share vertices or
  14222. * indices, and must not leave vertices or indices unused.
  14223. *
  14224. * @type {Array<Object>}
  14225. */
  14226. this.groups = [];
  14227. /**
  14228. * Bounding box for the geometry which can be calculated with `computeBoundingBox()`.
  14229. *
  14230. * @type {Box3}
  14231. * @default null
  14232. */
  14233. this.boundingBox = null;
  14234. /**
  14235. * Bounding sphere for the geometry which can be calculated with `computeBoundingSphere()`.
  14236. *
  14237. * @type {Sphere}
  14238. * @default null
  14239. */
  14240. this.boundingSphere = null;
  14241. /**
  14242. * Determines the part of the geometry to render. This should not be set directly,
  14243. * instead use `setDrawRange()`.
  14244. *
  14245. * @type {{start:number,count:number}}
  14246. */
  14247. this.drawRange = { start: 0, count: Infinity };
  14248. /**
  14249. * An object that can be used to store custom data about the geometry.
  14250. * It should not hold references to functions as these will not be cloned.
  14251. *
  14252. * @type {Object}
  14253. */
  14254. this.userData = {};
  14255. }
  14256. /**
  14257. * Returns the index of this geometry.
  14258. *
  14259. * @return {?BufferAttribute} The index. Returns `null` if no index is defined.
  14260. */
  14261. getIndex() {
  14262. return this.index;
  14263. }
  14264. /**
  14265. * Sets the given index to this geometry.
  14266. *
  14267. * @param {Array<number>|BufferAttribute} index - The index to set.
  14268. * @return {BufferGeometry} A reference to this instance.
  14269. */
  14270. setIndex( index ) {
  14271. if ( Array.isArray( index ) ) {
  14272. this.index = new ( arrayNeedsUint32( index ) ? Uint32BufferAttribute : Uint16BufferAttribute )( index, 1 );
  14273. } else {
  14274. this.index = index;
  14275. }
  14276. return this;
  14277. }
  14278. /**
  14279. * Sets the given indirect attribute to this geometry.
  14280. *
  14281. * @param {BufferAttribute} indirect - The attribute holding indirect draw calls.
  14282. * @return {BufferGeometry} A reference to this instance.
  14283. */
  14284. setIndirect( indirect ) {
  14285. this.indirect = indirect;
  14286. return this;
  14287. }
  14288. /**
  14289. * Returns the indirect attribute of this geometry.
  14290. *
  14291. * @return {?BufferAttribute} The indirect attribute. Returns `null` if no indirect attribute is defined.
  14292. */
  14293. getIndirect() {
  14294. return this.indirect;
  14295. }
  14296. /**
  14297. * Returns the buffer attribute for the given name.
  14298. *
  14299. * @param {string} name - The attribute name.
  14300. * @return {BufferAttribute|InterleavedBufferAttribute|undefined} The buffer attribute.
  14301. * Returns `undefined` if not attribute has been found.
  14302. */
  14303. getAttribute( name ) {
  14304. return this.attributes[ name ];
  14305. }
  14306. /**
  14307. * Sets the given attribute for the given name.
  14308. *
  14309. * @param {string} name - The attribute name.
  14310. * @param {BufferAttribute|InterleavedBufferAttribute} attribute - The attribute to set.
  14311. * @return {BufferGeometry} A reference to this instance.
  14312. */
  14313. setAttribute( name, attribute ) {
  14314. this.attributes[ name ] = attribute;
  14315. return this;
  14316. }
  14317. /**
  14318. * Deletes the attribute for the given name.
  14319. *
  14320. * @param {string} name - The attribute name to delete.
  14321. * @return {BufferGeometry} A reference to this instance.
  14322. */
  14323. deleteAttribute( name ) {
  14324. delete this.attributes[ name ];
  14325. return this;
  14326. }
  14327. /**
  14328. * Returns `true` if this geometry has an attribute for the given name.
  14329. *
  14330. * @param {string} name - The attribute name.
  14331. * @return {boolean} Whether this geometry has an attribute for the given name or not.
  14332. */
  14333. hasAttribute( name ) {
  14334. return this.attributes[ name ] !== undefined;
  14335. }
  14336. /**
  14337. * Adds a group to this geometry.
  14338. *
  14339. * @param {number} start - The first element in this draw call. That is the first
  14340. * vertex for non-indexed geometry, otherwise the first triangle index.
  14341. * @param {number} count - Specifies how many vertices (or indices) are part of this group.
  14342. * @param {number} [materialIndex=0] - The material array index to use.
  14343. */
  14344. addGroup( start, count, materialIndex = 0 ) {
  14345. this.groups.push( {
  14346. start: start,
  14347. count: count,
  14348. materialIndex: materialIndex
  14349. } );
  14350. }
  14351. /**
  14352. * Clears all groups.
  14353. */
  14354. clearGroups() {
  14355. this.groups = [];
  14356. }
  14357. /**
  14358. * Sets the draw range for this geometry.
  14359. *
  14360. * @param {number} start - The first vertex for non-indexed geometry, otherwise the first triangle index.
  14361. * @param {number} count - For non-indexed BufferGeometry, `count` is the number of vertices to render.
  14362. * For indexed BufferGeometry, `count` is the number of indices to render.
  14363. */
  14364. setDrawRange( start, count ) {
  14365. this.drawRange.start = start;
  14366. this.drawRange.count = count;
  14367. }
  14368. /**
  14369. * Applies the given 4x4 transformation matrix to the geometry.
  14370. *
  14371. * @param {Matrix4} matrix - The matrix to apply.
  14372. * @return {BufferGeometry} A reference to this instance.
  14373. */
  14374. applyMatrix4( matrix ) {
  14375. const position = this.attributes.position;
  14376. if ( position !== undefined ) {
  14377. position.applyMatrix4( matrix );
  14378. position.needsUpdate = true;
  14379. }
  14380. const normal = this.attributes.normal;
  14381. if ( normal !== undefined ) {
  14382. const normalMatrix = new Matrix3().getNormalMatrix( matrix );
  14383. normal.applyNormalMatrix( normalMatrix );
  14384. normal.needsUpdate = true;
  14385. }
  14386. const tangent = this.attributes.tangent;
  14387. if ( tangent !== undefined ) {
  14388. tangent.transformDirection( matrix );
  14389. tangent.needsUpdate = true;
  14390. }
  14391. if ( this.boundingBox !== null ) {
  14392. this.computeBoundingBox();
  14393. }
  14394. if ( this.boundingSphere !== null ) {
  14395. this.computeBoundingSphere();
  14396. }
  14397. return this;
  14398. }
  14399. /**
  14400. * Applies the rotation represented by the Quaternion to the geometry.
  14401. *
  14402. * @param {Quaternion} q - The Quaternion to apply.
  14403. * @return {BufferGeometry} A reference to this instance.
  14404. */
  14405. applyQuaternion( q ) {
  14406. _m1.makeRotationFromQuaternion( q );
  14407. this.applyMatrix4( _m1 );
  14408. return this;
  14409. }
  14410. /**
  14411. * Rotates the geometry about the X axis. This is typically done as a one time
  14412. * operation, and not during a loop. Use {@link Object3D#rotation} for typical
  14413. * real-time mesh rotation.
  14414. *
  14415. * @param {number} angle - The angle in radians.
  14416. * @return {BufferGeometry} A reference to this instance.
  14417. */
  14418. rotateX( angle ) {
  14419. // rotate geometry around world x-axis
  14420. _m1.makeRotationX( angle );
  14421. this.applyMatrix4( _m1 );
  14422. return this;
  14423. }
  14424. /**
  14425. * Rotates the geometry about the Y axis. This is typically done as a one time
  14426. * operation, and not during a loop. Use {@link Object3D#rotation} for typical
  14427. * real-time mesh rotation.
  14428. *
  14429. * @param {number} angle - The angle in radians.
  14430. * @return {BufferGeometry} A reference to this instance.
  14431. */
  14432. rotateY( angle ) {
  14433. // rotate geometry around world y-axis
  14434. _m1.makeRotationY( angle );
  14435. this.applyMatrix4( _m1 );
  14436. return this;
  14437. }
  14438. /**
  14439. * Rotates the geometry about the Z axis. This is typically done as a one time
  14440. * operation, and not during a loop. Use {@link Object3D#rotation} for typical
  14441. * real-time mesh rotation.
  14442. *
  14443. * @param {number} angle - The angle in radians.
  14444. * @return {BufferGeometry} A reference to this instance.
  14445. */
  14446. rotateZ( angle ) {
  14447. // rotate geometry around world z-axis
  14448. _m1.makeRotationZ( angle );
  14449. this.applyMatrix4( _m1 );
  14450. return this;
  14451. }
  14452. /**
  14453. * Translates the geometry. This is typically done as a one time
  14454. * operation, and not during a loop. Use {@link Object3D#position} for typical
  14455. * real-time mesh rotation.
  14456. *
  14457. * @param {number} x - The x offset.
  14458. * @param {number} y - The y offset.
  14459. * @param {number} z - The z offset.
  14460. * @return {BufferGeometry} A reference to this instance.
  14461. */
  14462. translate( x, y, z ) {
  14463. // translate geometry
  14464. _m1.makeTranslation( x, y, z );
  14465. this.applyMatrix4( _m1 );
  14466. return this;
  14467. }
  14468. /**
  14469. * Scales the geometry. This is typically done as a one time
  14470. * operation, and not during a loop. Use {@link Object3D#scale} for typical
  14471. * real-time mesh rotation.
  14472. *
  14473. * @param {number} x - The x scale.
  14474. * @param {number} y - The y scale.
  14475. * @param {number} z - The z scale.
  14476. * @return {BufferGeometry} A reference to this instance.
  14477. */
  14478. scale( x, y, z ) {
  14479. // scale geometry
  14480. _m1.makeScale( x, y, z );
  14481. this.applyMatrix4( _m1 );
  14482. return this;
  14483. }
  14484. /**
  14485. * Rotates the geometry to face a point in 3D space. This is typically done as a one time
  14486. * operation, and not during a loop. Use {@link Object3D#lookAt} for typical
  14487. * real-time mesh rotation.
  14488. *
  14489. * @param {Vector3} vector - The target point.
  14490. * @return {BufferGeometry} A reference to this instance.
  14491. */
  14492. lookAt( vector ) {
  14493. _obj.lookAt( vector );
  14494. _obj.updateMatrix();
  14495. this.applyMatrix4( _obj.matrix );
  14496. return this;
  14497. }
  14498. /**
  14499. * Center the geometry based on its bounding box.
  14500. *
  14501. * @return {BufferGeometry} A reference to this instance.
  14502. */
  14503. center() {
  14504. this.computeBoundingBox();
  14505. this.boundingBox.getCenter( _offset ).negate();
  14506. this.translate( _offset.x, _offset.y, _offset.z );
  14507. return this;
  14508. }
  14509. /**
  14510. * Defines a geometry by creating a `position` attribute based on the given array of points. The array
  14511. * can hold 2D or 3D vectors. When using two-dimensional data, the `z` coordinate for all vertices is
  14512. * set to `0`.
  14513. *
  14514. * If the method is used with an existing `position` attribute, the vertex data are overwritten with the
  14515. * data from the array. The length of the array must match the vertex count.
  14516. *
  14517. * @param {Array<Vector2>|Array<Vector3>} points - The points.
  14518. * @return {BufferGeometry} A reference to this instance.
  14519. */
  14520. setFromPoints( points ) {
  14521. const positionAttribute = this.getAttribute( 'position' );
  14522. if ( positionAttribute === undefined ) {
  14523. const position = [];
  14524. for ( let i = 0, l = points.length; i < l; i ++ ) {
  14525. const point = points[ i ];
  14526. position.push( point.x, point.y, point.z || 0 );
  14527. }
  14528. this.setAttribute( 'position', new Float32BufferAttribute( position, 3 ) );
  14529. } else {
  14530. const l = Math.min( points.length, positionAttribute.count ); // make sure data do not exceed buffer size
  14531. for ( let i = 0; i < l; i ++ ) {
  14532. const point = points[ i ];
  14533. positionAttribute.setXYZ( i, point.x, point.y, point.z || 0 );
  14534. }
  14535. if ( points.length > positionAttribute.count ) {
  14536. console.warn( 'THREE.BufferGeometry: Buffer size too small for points data. Use .dispose() and create a new geometry.' );
  14537. }
  14538. positionAttribute.needsUpdate = true;
  14539. }
  14540. return this;
  14541. }
  14542. /**
  14543. * Computes the bounding box of the geometry, and updates the `boundingBox` member.
  14544. * The bounding box is not computed by the engine; it must be computed by your app.
  14545. * You may need to recompute the bounding box if the geometry vertices are modified.
  14546. */
  14547. computeBoundingBox() {
  14548. if ( this.boundingBox === null ) {
  14549. this.boundingBox = new Box3();
  14550. }
  14551. const position = this.attributes.position;
  14552. const morphAttributesPosition = this.morphAttributes.position;
  14553. if ( position && position.isGLBufferAttribute ) {
  14554. console.error( 'THREE.BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box.', this );
  14555. this.boundingBox.set(
  14556. new Vector3( - Infinity, - Infinity, - Infinity ),
  14557. new Vector3( + Infinity, + Infinity, + Infinity )
  14558. );
  14559. return;
  14560. }
  14561. if ( position !== undefined ) {
  14562. this.boundingBox.setFromBufferAttribute( position );
  14563. // process morph attributes if present
  14564. if ( morphAttributesPosition ) {
  14565. for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  14566. const morphAttribute = morphAttributesPosition[ i ];
  14567. _box$2.setFromBufferAttribute( morphAttribute );
  14568. if ( this.morphTargetsRelative ) {
  14569. _vector$8.addVectors( this.boundingBox.min, _box$2.min );
  14570. this.boundingBox.expandByPoint( _vector$8 );
  14571. _vector$8.addVectors( this.boundingBox.max, _box$2.max );
  14572. this.boundingBox.expandByPoint( _vector$8 );
  14573. } else {
  14574. this.boundingBox.expandByPoint( _box$2.min );
  14575. this.boundingBox.expandByPoint( _box$2.max );
  14576. }
  14577. }
  14578. }
  14579. } else {
  14580. this.boundingBox.makeEmpty();
  14581. }
  14582. if ( isNaN( this.boundingBox.min.x ) || isNaN( this.boundingBox.min.y ) || isNaN( this.boundingBox.min.z ) ) {
  14583. console.error( 'THREE.BufferGeometry.computeBoundingBox(): Computed min/max have NaN values. The "position" attribute is likely to have NaN values.', this );
  14584. }
  14585. }
  14586. /**
  14587. * Computes the bounding sphere of the geometry, and updates the `boundingSphere` member.
  14588. * The engine automatically computes the bounding sphere when it is needed, e.g., for ray casting or view frustum culling.
  14589. * You may need to recompute the bounding sphere if the geometry vertices are modified.
  14590. */
  14591. computeBoundingSphere() {
  14592. if ( this.boundingSphere === null ) {
  14593. this.boundingSphere = new Sphere();
  14594. }
  14595. const position = this.attributes.position;
  14596. const morphAttributesPosition = this.morphAttributes.position;
  14597. if ( position && position.isGLBufferAttribute ) {
  14598. console.error( 'THREE.BufferGeometry.computeBoundingSphere(): GLBufferAttribute requires a manual bounding sphere.', this );
  14599. this.boundingSphere.set( new Vector3(), Infinity );
  14600. return;
  14601. }
  14602. if ( position ) {
  14603. // first, find the center of the bounding sphere
  14604. const center = this.boundingSphere.center;
  14605. _box$2.setFromBufferAttribute( position );
  14606. // process morph attributes if present
  14607. if ( morphAttributesPosition ) {
  14608. for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  14609. const morphAttribute = morphAttributesPosition[ i ];
  14610. _boxMorphTargets.setFromBufferAttribute( morphAttribute );
  14611. if ( this.morphTargetsRelative ) {
  14612. _vector$8.addVectors( _box$2.min, _boxMorphTargets.min );
  14613. _box$2.expandByPoint( _vector$8 );
  14614. _vector$8.addVectors( _box$2.max, _boxMorphTargets.max );
  14615. _box$2.expandByPoint( _vector$8 );
  14616. } else {
  14617. _box$2.expandByPoint( _boxMorphTargets.min );
  14618. _box$2.expandByPoint( _boxMorphTargets.max );
  14619. }
  14620. }
  14621. }
  14622. _box$2.getCenter( center );
  14623. // second, try to find a boundingSphere with a radius smaller than the
  14624. // boundingSphere of the boundingBox: sqrt(3) smaller in the best case
  14625. let maxRadiusSq = 0;
  14626. for ( let i = 0, il = position.count; i < il; i ++ ) {
  14627. _vector$8.fromBufferAttribute( position, i );
  14628. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( _vector$8 ) );
  14629. }
  14630. // process morph attributes if present
  14631. if ( morphAttributesPosition ) {
  14632. for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  14633. const morphAttribute = morphAttributesPosition[ i ];
  14634. const morphTargetsRelative = this.morphTargetsRelative;
  14635. for ( let j = 0, jl = morphAttribute.count; j < jl; j ++ ) {
  14636. _vector$8.fromBufferAttribute( morphAttribute, j );
  14637. if ( morphTargetsRelative ) {
  14638. _offset.fromBufferAttribute( position, j );
  14639. _vector$8.add( _offset );
  14640. }
  14641. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( _vector$8 ) );
  14642. }
  14643. }
  14644. }
  14645. this.boundingSphere.radius = Math.sqrt( maxRadiusSq );
  14646. if ( isNaN( this.boundingSphere.radius ) ) {
  14647. console.error( 'THREE.BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.', this );
  14648. }
  14649. }
  14650. }
  14651. /**
  14652. * Calculates and adds a tangent attribute to this geometry.
  14653. *
  14654. * The computation is only supported for indexed geometries and if position, normal, and uv attributes
  14655. * are defined. When using a tangent space normal map, prefer the MikkTSpace algorithm provided by
  14656. * {@link BufferGeometryUtils#computeMikkTSpaceTangents} instead.
  14657. */
  14658. computeTangents() {
  14659. const index = this.index;
  14660. const attributes = this.attributes;
  14661. // based on http://www.terathon.com/code/tangent.html
  14662. // (per vertex tangents)
  14663. if ( index === null ||
  14664. attributes.position === undefined ||
  14665. attributes.normal === undefined ||
  14666. attributes.uv === undefined ) {
  14667. console.error( 'THREE.BufferGeometry: .computeTangents() failed. Missing required attributes (index, position, normal or uv)' );
  14668. return;
  14669. }
  14670. const positionAttribute = attributes.position;
  14671. const normalAttribute = attributes.normal;
  14672. const uvAttribute = attributes.uv;
  14673. if ( this.hasAttribute( 'tangent' ) === false ) {
  14674. this.setAttribute( 'tangent', new BufferAttribute( new Float32Array( 4 * positionAttribute.count ), 4 ) );
  14675. }
  14676. const tangentAttribute = this.getAttribute( 'tangent' );
  14677. const tan1 = [], tan2 = [];
  14678. for ( let i = 0; i < positionAttribute.count; i ++ ) {
  14679. tan1[ i ] = new Vector3();
  14680. tan2[ i ] = new Vector3();
  14681. }
  14682. const vA = new Vector3(),
  14683. vB = new Vector3(),
  14684. vC = new Vector3(),
  14685. uvA = new Vector2(),
  14686. uvB = new Vector2(),
  14687. uvC = new Vector2(),
  14688. sdir = new Vector3(),
  14689. tdir = new Vector3();
  14690. function handleTriangle( a, b, c ) {
  14691. vA.fromBufferAttribute( positionAttribute, a );
  14692. vB.fromBufferAttribute( positionAttribute, b );
  14693. vC.fromBufferAttribute( positionAttribute, c );
  14694. uvA.fromBufferAttribute( uvAttribute, a );
  14695. uvB.fromBufferAttribute( uvAttribute, b );
  14696. uvC.fromBufferAttribute( uvAttribute, c );
  14697. vB.sub( vA );
  14698. vC.sub( vA );
  14699. uvB.sub( uvA );
  14700. uvC.sub( uvA );
  14701. const r = 1.0 / ( uvB.x * uvC.y - uvC.x * uvB.y );
  14702. // silently ignore degenerate uv triangles having coincident or colinear vertices
  14703. if ( ! isFinite( r ) ) return;
  14704. sdir.copy( vB ).multiplyScalar( uvC.y ).addScaledVector( vC, - uvB.y ).multiplyScalar( r );
  14705. tdir.copy( vC ).multiplyScalar( uvB.x ).addScaledVector( vB, - uvC.x ).multiplyScalar( r );
  14706. tan1[ a ].add( sdir );
  14707. tan1[ b ].add( sdir );
  14708. tan1[ c ].add( sdir );
  14709. tan2[ a ].add( tdir );
  14710. tan2[ b ].add( tdir );
  14711. tan2[ c ].add( tdir );
  14712. }
  14713. let groups = this.groups;
  14714. if ( groups.length === 0 ) {
  14715. groups = [ {
  14716. start: 0,
  14717. count: index.count
  14718. } ];
  14719. }
  14720. for ( let i = 0, il = groups.length; i < il; ++ i ) {
  14721. const group = groups[ i ];
  14722. const start = group.start;
  14723. const count = group.count;
  14724. for ( let j = start, jl = start + count; j < jl; j += 3 ) {
  14725. handleTriangle(
  14726. index.getX( j + 0 ),
  14727. index.getX( j + 1 ),
  14728. index.getX( j + 2 )
  14729. );
  14730. }
  14731. }
  14732. const tmp = new Vector3(), tmp2 = new Vector3();
  14733. const n = new Vector3(), n2 = new Vector3();
  14734. function handleVertex( v ) {
  14735. n.fromBufferAttribute( normalAttribute, v );
  14736. n2.copy( n );
  14737. const t = tan1[ v ];
  14738. // Gram-Schmidt orthogonalize
  14739. tmp.copy( t );
  14740. tmp.sub( n.multiplyScalar( n.dot( t ) ) ).normalize();
  14741. // Calculate handedness
  14742. tmp2.crossVectors( n2, t );
  14743. const test = tmp2.dot( tan2[ v ] );
  14744. const w = ( test < 0.0 ) ? -1 : 1.0;
  14745. tangentAttribute.setXYZW( v, tmp.x, tmp.y, tmp.z, w );
  14746. }
  14747. for ( let i = 0, il = groups.length; i < il; ++ i ) {
  14748. const group = groups[ i ];
  14749. const start = group.start;
  14750. const count = group.count;
  14751. for ( let j = start, jl = start + count; j < jl; j += 3 ) {
  14752. handleVertex( index.getX( j + 0 ) );
  14753. handleVertex( index.getX( j + 1 ) );
  14754. handleVertex( index.getX( j + 2 ) );
  14755. }
  14756. }
  14757. }
  14758. /**
  14759. * Computes vertex normals for the given vertex data. For indexed geometries, the method sets
  14760. * each vertex normal to be the average of the face normals of the faces that share that vertex.
  14761. * For non-indexed geometries, vertices are not shared, and the method sets each vertex normal
  14762. * to be the same as the face normal.
  14763. */
  14764. computeVertexNormals() {
  14765. const index = this.index;
  14766. const positionAttribute = this.getAttribute( 'position' );
  14767. if ( positionAttribute !== undefined ) {
  14768. let normalAttribute = this.getAttribute( 'normal' );
  14769. if ( normalAttribute === undefined ) {
  14770. normalAttribute = new BufferAttribute( new Float32Array( positionAttribute.count * 3 ), 3 );
  14771. this.setAttribute( 'normal', normalAttribute );
  14772. } else {
  14773. // reset existing normals to zero
  14774. for ( let i = 0, il = normalAttribute.count; i < il; i ++ ) {
  14775. normalAttribute.setXYZ( i, 0, 0, 0 );
  14776. }
  14777. }
  14778. const pA = new Vector3(), pB = new Vector3(), pC = new Vector3();
  14779. const nA = new Vector3(), nB = new Vector3(), nC = new Vector3();
  14780. const cb = new Vector3(), ab = new Vector3();
  14781. // indexed elements
  14782. if ( index ) {
  14783. for ( let i = 0, il = index.count; i < il; i += 3 ) {
  14784. const vA = index.getX( i + 0 );
  14785. const vB = index.getX( i + 1 );
  14786. const vC = index.getX( i + 2 );
  14787. pA.fromBufferAttribute( positionAttribute, vA );
  14788. pB.fromBufferAttribute( positionAttribute, vB );
  14789. pC.fromBufferAttribute( positionAttribute, vC );
  14790. cb.subVectors( pC, pB );
  14791. ab.subVectors( pA, pB );
  14792. cb.cross( ab );
  14793. nA.fromBufferAttribute( normalAttribute, vA );
  14794. nB.fromBufferAttribute( normalAttribute, vB );
  14795. nC.fromBufferAttribute( normalAttribute, vC );
  14796. nA.add( cb );
  14797. nB.add( cb );
  14798. nC.add( cb );
  14799. normalAttribute.setXYZ( vA, nA.x, nA.y, nA.z );
  14800. normalAttribute.setXYZ( vB, nB.x, nB.y, nB.z );
  14801. normalAttribute.setXYZ( vC, nC.x, nC.y, nC.z );
  14802. }
  14803. } else {
  14804. // non-indexed elements (unconnected triangle soup)
  14805. for ( let i = 0, il = positionAttribute.count; i < il; i += 3 ) {
  14806. pA.fromBufferAttribute( positionAttribute, i + 0 );
  14807. pB.fromBufferAttribute( positionAttribute, i + 1 );
  14808. pC.fromBufferAttribute( positionAttribute, i + 2 );
  14809. cb.subVectors( pC, pB );
  14810. ab.subVectors( pA, pB );
  14811. cb.cross( ab );
  14812. normalAttribute.setXYZ( i + 0, cb.x, cb.y, cb.z );
  14813. normalAttribute.setXYZ( i + 1, cb.x, cb.y, cb.z );
  14814. normalAttribute.setXYZ( i + 2, cb.x, cb.y, cb.z );
  14815. }
  14816. }
  14817. this.normalizeNormals();
  14818. normalAttribute.needsUpdate = true;
  14819. }
  14820. }
  14821. /**
  14822. * Ensures every normal vector in a geometry will have a magnitude of `1`. This will
  14823. * correct lighting on the geometry surfaces.
  14824. */
  14825. normalizeNormals() {
  14826. const normals = this.attributes.normal;
  14827. for ( let i = 0, il = normals.count; i < il; i ++ ) {
  14828. _vector$8.fromBufferAttribute( normals, i );
  14829. _vector$8.normalize();
  14830. normals.setXYZ( i, _vector$8.x, _vector$8.y, _vector$8.z );
  14831. }
  14832. }
  14833. /**
  14834. * Return a new non-index version of this indexed geometry. If the geometry
  14835. * is already non-indexed, the method is a NOOP.
  14836. *
  14837. * @return {BufferGeometry} The non-indexed version of this indexed geometry.
  14838. */
  14839. toNonIndexed() {
  14840. function convertBufferAttribute( attribute, indices ) {
  14841. const array = attribute.array;
  14842. const itemSize = attribute.itemSize;
  14843. const normalized = attribute.normalized;
  14844. const array2 = new array.constructor( indices.length * itemSize );
  14845. let index = 0, index2 = 0;
  14846. for ( let i = 0, l = indices.length; i < l; i ++ ) {
  14847. if ( attribute.isInterleavedBufferAttribute ) {
  14848. index = indices[ i ] * attribute.data.stride + attribute.offset;
  14849. } else {
  14850. index = indices[ i ] * itemSize;
  14851. }
  14852. for ( let j = 0; j < itemSize; j ++ ) {
  14853. array2[ index2 ++ ] = array[ index ++ ];
  14854. }
  14855. }
  14856. return new BufferAttribute( array2, itemSize, normalized );
  14857. }
  14858. //
  14859. if ( this.index === null ) {
  14860. console.warn( 'THREE.BufferGeometry.toNonIndexed(): BufferGeometry is already non-indexed.' );
  14861. return this;
  14862. }
  14863. const geometry2 = new BufferGeometry();
  14864. const indices = this.index.array;
  14865. const attributes = this.attributes;
  14866. // attributes
  14867. for ( const name in attributes ) {
  14868. const attribute = attributes[ name ];
  14869. const newAttribute = convertBufferAttribute( attribute, indices );
  14870. geometry2.setAttribute( name, newAttribute );
  14871. }
  14872. // morph attributes
  14873. const morphAttributes = this.morphAttributes;
  14874. for ( const name in morphAttributes ) {
  14875. const morphArray = [];
  14876. const morphAttribute = morphAttributes[ name ]; // morphAttribute: array of Float32BufferAttributes
  14877. for ( let i = 0, il = morphAttribute.length; i < il; i ++ ) {
  14878. const attribute = morphAttribute[ i ];
  14879. const newAttribute = convertBufferAttribute( attribute, indices );
  14880. morphArray.push( newAttribute );
  14881. }
  14882. geometry2.morphAttributes[ name ] = morphArray;
  14883. }
  14884. geometry2.morphTargetsRelative = this.morphTargetsRelative;
  14885. // groups
  14886. const groups = this.groups;
  14887. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  14888. const group = groups[ i ];
  14889. geometry2.addGroup( group.start, group.count, group.materialIndex );
  14890. }
  14891. return geometry2;
  14892. }
  14893. /**
  14894. * Serializes the geometry into JSON.
  14895. *
  14896. * @return {Object} A JSON object representing the serialized geometry.
  14897. */
  14898. toJSON() {
  14899. const data = {
  14900. metadata: {
  14901. version: 4.6,
  14902. type: 'BufferGeometry',
  14903. generator: 'BufferGeometry.toJSON'
  14904. }
  14905. };
  14906. // standard BufferGeometry serialization
  14907. data.uuid = this.uuid;
  14908. data.type = this.type;
  14909. if ( this.name !== '' ) data.name = this.name;
  14910. if ( Object.keys( this.userData ).length > 0 ) data.userData = this.userData;
  14911. if ( this.parameters !== undefined ) {
  14912. const parameters = this.parameters;
  14913. for ( const key in parameters ) {
  14914. if ( parameters[ key ] !== undefined ) data[ key ] = parameters[ key ];
  14915. }
  14916. return data;
  14917. }
  14918. // for simplicity the code assumes attributes are not shared across geometries, see #15811
  14919. data.data = { attributes: {} };
  14920. const index = this.index;
  14921. if ( index !== null ) {
  14922. data.data.index = {
  14923. type: index.array.constructor.name,
  14924. array: Array.prototype.slice.call( index.array )
  14925. };
  14926. }
  14927. const attributes = this.attributes;
  14928. for ( const key in attributes ) {
  14929. const attribute = attributes[ key ];
  14930. data.data.attributes[ key ] = attribute.toJSON( data.data );
  14931. }
  14932. const morphAttributes = {};
  14933. let hasMorphAttributes = false;
  14934. for ( const key in this.morphAttributes ) {
  14935. const attributeArray = this.morphAttributes[ key ];
  14936. const array = [];
  14937. for ( let i = 0, il = attributeArray.length; i < il; i ++ ) {
  14938. const attribute = attributeArray[ i ];
  14939. array.push( attribute.toJSON( data.data ) );
  14940. }
  14941. if ( array.length > 0 ) {
  14942. morphAttributes[ key ] = array;
  14943. hasMorphAttributes = true;
  14944. }
  14945. }
  14946. if ( hasMorphAttributes ) {
  14947. data.data.morphAttributes = morphAttributes;
  14948. data.data.morphTargetsRelative = this.morphTargetsRelative;
  14949. }
  14950. const groups = this.groups;
  14951. if ( groups.length > 0 ) {
  14952. data.data.groups = JSON.parse( JSON.stringify( groups ) );
  14953. }
  14954. const boundingSphere = this.boundingSphere;
  14955. if ( boundingSphere !== null ) {
  14956. data.data.boundingSphere = boundingSphere.toJSON();
  14957. }
  14958. return data;
  14959. }
  14960. /**
  14961. * Returns a new geometry with copied values from this instance.
  14962. *
  14963. * @return {BufferGeometry} A clone of this instance.
  14964. */
  14965. clone() {
  14966. return new this.constructor().copy( this );
  14967. }
  14968. /**
  14969. * Copies the values of the given geometry to this instance.
  14970. *
  14971. * @param {BufferGeometry} source - The geometry to copy.
  14972. * @return {BufferGeometry} A reference to this instance.
  14973. */
  14974. copy( source ) {
  14975. // reset
  14976. this.index = null;
  14977. this.attributes = {};
  14978. this.morphAttributes = {};
  14979. this.groups = [];
  14980. this.boundingBox = null;
  14981. this.boundingSphere = null;
  14982. // used for storing cloned, shared data
  14983. const data = {};
  14984. // name
  14985. this.name = source.name;
  14986. // index
  14987. const index = source.index;
  14988. if ( index !== null ) {
  14989. this.setIndex( index.clone() );
  14990. }
  14991. // attributes
  14992. const attributes = source.attributes;
  14993. for ( const name in attributes ) {
  14994. const attribute = attributes[ name ];
  14995. this.setAttribute( name, attribute.clone( data ) );
  14996. }
  14997. // morph attributes
  14998. const morphAttributes = source.morphAttributes;
  14999. for ( const name in morphAttributes ) {
  15000. const array = [];
  15001. const morphAttribute = morphAttributes[ name ]; // morphAttribute: array of Float32BufferAttributes
  15002. for ( let i = 0, l = morphAttribute.length; i < l; i ++ ) {
  15003. array.push( morphAttribute[ i ].clone( data ) );
  15004. }
  15005. this.morphAttributes[ name ] = array;
  15006. }
  15007. this.morphTargetsRelative = source.morphTargetsRelative;
  15008. // groups
  15009. const groups = source.groups;
  15010. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  15011. const group = groups[ i ];
  15012. this.addGroup( group.start, group.count, group.materialIndex );
  15013. }
  15014. // bounding box
  15015. const boundingBox = source.boundingBox;
  15016. if ( boundingBox !== null ) {
  15017. this.boundingBox = boundingBox.clone();
  15018. }
  15019. // bounding sphere
  15020. const boundingSphere = source.boundingSphere;
  15021. if ( boundingSphere !== null ) {
  15022. this.boundingSphere = boundingSphere.clone();
  15023. }
  15024. // draw range
  15025. this.drawRange.start = source.drawRange.start;
  15026. this.drawRange.count = source.drawRange.count;
  15027. // user data
  15028. this.userData = source.userData;
  15029. return this;
  15030. }
  15031. /**
  15032. * Frees the GPU-related resources allocated by this instance. Call this
  15033. * method whenever this instance is no longer used in your app.
  15034. *
  15035. * @fires BufferGeometry#dispose
  15036. */
  15037. dispose() {
  15038. this.dispatchEvent( { type: 'dispose' } );
  15039. }
  15040. }
  15041. const _inverseMatrix$3 = /*@__PURE__*/ new Matrix4();
  15042. const _ray$3 = /*@__PURE__*/ new Ray();
  15043. const _sphere$6 = /*@__PURE__*/ new Sphere();
  15044. const _sphereHitAt = /*@__PURE__*/ new Vector3();
  15045. const _vA$1 = /*@__PURE__*/ new Vector3();
  15046. const _vB$1 = /*@__PURE__*/ new Vector3();
  15047. const _vC$1 = /*@__PURE__*/ new Vector3();
  15048. const _tempA = /*@__PURE__*/ new Vector3();
  15049. const _morphA = /*@__PURE__*/ new Vector3();
  15050. const _intersectionPoint = /*@__PURE__*/ new Vector3();
  15051. const _intersectionPointWorld = /*@__PURE__*/ new Vector3();
  15052. /**
  15053. * Class representing triangular polygon mesh based objects.
  15054. *
  15055. * ```js
  15056. * const geometry = new THREE.BoxGeometry( 1, 1, 1 );
  15057. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  15058. * const mesh = new THREE.Mesh( geometry, material );
  15059. * scene.add( mesh );
  15060. * ```
  15061. *
  15062. * @augments Object3D
  15063. */
  15064. class Mesh extends Object3D {
  15065. /**
  15066. * Constructs a new mesh.
  15067. *
  15068. * @param {BufferGeometry} [geometry] - The mesh geometry.
  15069. * @param {Material|Array<Material>} [material] - The mesh material.
  15070. */
  15071. constructor( geometry = new BufferGeometry(), material = new MeshBasicMaterial() ) {
  15072. super();
  15073. /**
  15074. * This flag can be used for type testing.
  15075. *
  15076. * @type {boolean}
  15077. * @readonly
  15078. * @default true
  15079. */
  15080. this.isMesh = true;
  15081. this.type = 'Mesh';
  15082. /**
  15083. * The mesh geometry.
  15084. *
  15085. * @type {BufferGeometry}
  15086. */
  15087. this.geometry = geometry;
  15088. /**
  15089. * The mesh material.
  15090. *
  15091. * @type {Material|Array<Material>}
  15092. * @default MeshBasicMaterial
  15093. */
  15094. this.material = material;
  15095. /**
  15096. * A dictionary representing the morph targets in the geometry. The key is the
  15097. * morph targets name, the value its attribute index. This member is `undefined`
  15098. * by default and only set when morph targets are detected in the geometry.
  15099. *
  15100. * @type {Object<String,number>|undefined}
  15101. * @default undefined
  15102. */
  15103. this.morphTargetDictionary = undefined;
  15104. /**
  15105. * An array of weights typically in the range `[0,1]` that specify how much of the morph
  15106. * is applied. This member is `undefined` by default and only set when morph targets are
  15107. * detected in the geometry.
  15108. *
  15109. * @type {Array<number>|undefined}
  15110. * @default undefined
  15111. */
  15112. this.morphTargetInfluences = undefined;
  15113. /**
  15114. * The number of instances of this mesh.
  15115. * Can only be used with {@link WebGPURenderer}.
  15116. *
  15117. * @type {number}
  15118. * @default 1
  15119. */
  15120. this.count = 1;
  15121. this.updateMorphTargets();
  15122. }
  15123. copy( source, recursive ) {
  15124. super.copy( source, recursive );
  15125. if ( source.morphTargetInfluences !== undefined ) {
  15126. this.morphTargetInfluences = source.morphTargetInfluences.slice();
  15127. }
  15128. if ( source.morphTargetDictionary !== undefined ) {
  15129. this.morphTargetDictionary = Object.assign( {}, source.morphTargetDictionary );
  15130. }
  15131. this.material = Array.isArray( source.material ) ? source.material.slice() : source.material;
  15132. this.geometry = source.geometry;
  15133. return this;
  15134. }
  15135. /**
  15136. * Sets the values of {@link Mesh#morphTargetDictionary} and {@link Mesh#morphTargetInfluences}
  15137. * to make sure existing morph targets can influence this 3D object.
  15138. */
  15139. updateMorphTargets() {
  15140. const geometry = this.geometry;
  15141. const morphAttributes = geometry.morphAttributes;
  15142. const keys = Object.keys( morphAttributes );
  15143. if ( keys.length > 0 ) {
  15144. const morphAttribute = morphAttributes[ keys[ 0 ] ];
  15145. if ( morphAttribute !== undefined ) {
  15146. this.morphTargetInfluences = [];
  15147. this.morphTargetDictionary = {};
  15148. for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  15149. const name = morphAttribute[ m ].name || String( m );
  15150. this.morphTargetInfluences.push( 0 );
  15151. this.morphTargetDictionary[ name ] = m;
  15152. }
  15153. }
  15154. }
  15155. }
  15156. /**
  15157. * Returns the local-space position of the vertex at the given index, taking into
  15158. * account the current animation state of both morph targets and skinning.
  15159. *
  15160. * @param {number} index - The vertex index.
  15161. * @param {Vector3} target - The target object that is used to store the method's result.
  15162. * @return {Vector3} The vertex position in local space.
  15163. */
  15164. getVertexPosition( index, target ) {
  15165. const geometry = this.geometry;
  15166. const position = geometry.attributes.position;
  15167. const morphPosition = geometry.morphAttributes.position;
  15168. const morphTargetsRelative = geometry.morphTargetsRelative;
  15169. target.fromBufferAttribute( position, index );
  15170. const morphInfluences = this.morphTargetInfluences;
  15171. if ( morphPosition && morphInfluences ) {
  15172. _morphA.set( 0, 0, 0 );
  15173. for ( let i = 0, il = morphPosition.length; i < il; i ++ ) {
  15174. const influence = morphInfluences[ i ];
  15175. const morphAttribute = morphPosition[ i ];
  15176. if ( influence === 0 ) continue;
  15177. _tempA.fromBufferAttribute( morphAttribute, index );
  15178. if ( morphTargetsRelative ) {
  15179. _morphA.addScaledVector( _tempA, influence );
  15180. } else {
  15181. _morphA.addScaledVector( _tempA.sub( target ), influence );
  15182. }
  15183. }
  15184. target.add( _morphA );
  15185. }
  15186. return target;
  15187. }
  15188. /**
  15189. * Computes intersection points between a casted ray and this line.
  15190. *
  15191. * @param {Raycaster} raycaster - The raycaster.
  15192. * @param {Array<Object>} intersects - The target array that holds the intersection points.
  15193. */
  15194. raycast( raycaster, intersects ) {
  15195. const geometry = this.geometry;
  15196. const material = this.material;
  15197. const matrixWorld = this.matrixWorld;
  15198. if ( material === undefined ) return;
  15199. // test with bounding sphere in world space
  15200. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  15201. _sphere$6.copy( geometry.boundingSphere );
  15202. _sphere$6.applyMatrix4( matrixWorld );
  15203. // check distance from ray origin to bounding sphere
  15204. _ray$3.copy( raycaster.ray ).recast( raycaster.near );
  15205. if ( _sphere$6.containsPoint( _ray$3.origin ) === false ) {
  15206. if ( _ray$3.intersectSphere( _sphere$6, _sphereHitAt ) === null ) return;
  15207. if ( _ray$3.origin.distanceToSquared( _sphereHitAt ) > ( raycaster.far - raycaster.near ) ** 2 ) return;
  15208. }
  15209. // convert ray to local space of mesh
  15210. _inverseMatrix$3.copy( matrixWorld ).invert();
  15211. _ray$3.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$3 );
  15212. // test with bounding box in local space
  15213. if ( geometry.boundingBox !== null ) {
  15214. if ( _ray$3.intersectsBox( geometry.boundingBox ) === false ) return;
  15215. }
  15216. // test for intersections with geometry
  15217. this._computeIntersections( raycaster, intersects, _ray$3 );
  15218. }
  15219. _computeIntersections( raycaster, intersects, rayLocalSpace ) {
  15220. let intersection;
  15221. const geometry = this.geometry;
  15222. const material = this.material;
  15223. const index = geometry.index;
  15224. const position = geometry.attributes.position;
  15225. const uv = geometry.attributes.uv;
  15226. const uv1 = geometry.attributes.uv1;
  15227. const normal = geometry.attributes.normal;
  15228. const groups = geometry.groups;
  15229. const drawRange = geometry.drawRange;
  15230. if ( index !== null ) {
  15231. // indexed buffer geometry
  15232. if ( Array.isArray( material ) ) {
  15233. for ( let i = 0, il = groups.length; i < il; i ++ ) {
  15234. const group = groups[ i ];
  15235. const groupMaterial = material[ group.materialIndex ];
  15236. const start = Math.max( group.start, drawRange.start );
  15237. const end = Math.min( index.count, Math.min( ( group.start + group.count ), ( drawRange.start + drawRange.count ) ) );
  15238. for ( let j = start, jl = end; j < jl; j += 3 ) {
  15239. const a = index.getX( j );
  15240. const b = index.getX( j + 1 );
  15241. const c = index.getX( j + 2 );
  15242. intersection = checkGeometryIntersection( this, groupMaterial, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c );
  15243. if ( intersection ) {
  15244. intersection.faceIndex = Math.floor( j / 3 ); // triangle number in indexed buffer semantics
  15245. intersection.face.materialIndex = group.materialIndex;
  15246. intersects.push( intersection );
  15247. }
  15248. }
  15249. }
  15250. } else {
  15251. const start = Math.max( 0, drawRange.start );
  15252. const end = Math.min( index.count, ( drawRange.start + drawRange.count ) );
  15253. for ( let i = start, il = end; i < il; i += 3 ) {
  15254. const a = index.getX( i );
  15255. const b = index.getX( i + 1 );
  15256. const c = index.getX( i + 2 );
  15257. intersection = checkGeometryIntersection( this, material, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c );
  15258. if ( intersection ) {
  15259. intersection.faceIndex = Math.floor( i / 3 ); // triangle number in indexed buffer semantics
  15260. intersects.push( intersection );
  15261. }
  15262. }
  15263. }
  15264. } else if ( position !== undefined ) {
  15265. // non-indexed buffer geometry
  15266. if ( Array.isArray( material ) ) {
  15267. for ( let i = 0, il = groups.length; i < il; i ++ ) {
  15268. const group = groups[ i ];
  15269. const groupMaterial = material[ group.materialIndex ];
  15270. const start = Math.max( group.start, drawRange.start );
  15271. const end = Math.min( position.count, Math.min( ( group.start + group.count ), ( drawRange.start + drawRange.count ) ) );
  15272. for ( let j = start, jl = end; j < jl; j += 3 ) {
  15273. const a = j;
  15274. const b = j + 1;
  15275. const c = j + 2;
  15276. intersection = checkGeometryIntersection( this, groupMaterial, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c );
  15277. if ( intersection ) {
  15278. intersection.faceIndex = Math.floor( j / 3 ); // triangle number in non-indexed buffer semantics
  15279. intersection.face.materialIndex = group.materialIndex;
  15280. intersects.push( intersection );
  15281. }
  15282. }
  15283. }
  15284. } else {
  15285. const start = Math.max( 0, drawRange.start );
  15286. const end = Math.min( position.count, ( drawRange.start + drawRange.count ) );
  15287. for ( let i = start, il = end; i < il; i += 3 ) {
  15288. const a = i;
  15289. const b = i + 1;
  15290. const c = i + 2;
  15291. intersection = checkGeometryIntersection( this, material, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c );
  15292. if ( intersection ) {
  15293. intersection.faceIndex = Math.floor( i / 3 ); // triangle number in non-indexed buffer semantics
  15294. intersects.push( intersection );
  15295. }
  15296. }
  15297. }
  15298. }
  15299. }
  15300. }
  15301. function checkIntersection$1( object, material, raycaster, ray, pA, pB, pC, point ) {
  15302. let intersect;
  15303. if ( material.side === BackSide ) {
  15304. intersect = ray.intersectTriangle( pC, pB, pA, true, point );
  15305. } else {
  15306. intersect = ray.intersectTriangle( pA, pB, pC, ( material.side === FrontSide ), point );
  15307. }
  15308. if ( intersect === null ) return null;
  15309. _intersectionPointWorld.copy( point );
  15310. _intersectionPointWorld.applyMatrix4( object.matrixWorld );
  15311. const distance = raycaster.ray.origin.distanceTo( _intersectionPointWorld );
  15312. if ( distance < raycaster.near || distance > raycaster.far ) return null;
  15313. return {
  15314. distance: distance,
  15315. point: _intersectionPointWorld.clone(),
  15316. object: object
  15317. };
  15318. }
  15319. function checkGeometryIntersection( object, material, raycaster, ray, uv, uv1, normal, a, b, c ) {
  15320. object.getVertexPosition( a, _vA$1 );
  15321. object.getVertexPosition( b, _vB$1 );
  15322. object.getVertexPosition( c, _vC$1 );
  15323. const intersection = checkIntersection$1( object, material, raycaster, ray, _vA$1, _vB$1, _vC$1, _intersectionPoint );
  15324. if ( intersection ) {
  15325. const barycoord = new Vector3();
  15326. Triangle.getBarycoord( _intersectionPoint, _vA$1, _vB$1, _vC$1, barycoord );
  15327. if ( uv ) {
  15328. intersection.uv = Triangle.getInterpolatedAttribute( uv, a, b, c, barycoord, new Vector2() );
  15329. }
  15330. if ( uv1 ) {
  15331. intersection.uv1 = Triangle.getInterpolatedAttribute( uv1, a, b, c, barycoord, new Vector2() );
  15332. }
  15333. if ( normal ) {
  15334. intersection.normal = Triangle.getInterpolatedAttribute( normal, a, b, c, barycoord, new Vector3() );
  15335. if ( intersection.normal.dot( ray.direction ) > 0 ) {
  15336. intersection.normal.multiplyScalar( -1 );
  15337. }
  15338. }
  15339. const face = {
  15340. a: a,
  15341. b: b,
  15342. c: c,
  15343. normal: new Vector3(),
  15344. materialIndex: 0
  15345. };
  15346. Triangle.getNormal( _vA$1, _vB$1, _vC$1, face.normal );
  15347. intersection.face = face;
  15348. intersection.barycoord = barycoord;
  15349. }
  15350. return intersection;
  15351. }
  15352. /**
  15353. * A geometry class for a rectangular cuboid with a given width, height, and depth.
  15354. * On creation, the cuboid is centred on the origin, with each edge parallel to one
  15355. * of the axes.
  15356. *
  15357. * ```js
  15358. * const geometry = new THREE.BoxGeometry( 1, 1, 1 );
  15359. * const material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } );
  15360. * const cube = new THREE.Mesh( geometry, material );
  15361. * scene.add( cube );
  15362. * ```
  15363. *
  15364. * @augments BufferGeometry
  15365. */
  15366. class BoxGeometry extends BufferGeometry {
  15367. /**
  15368. * Constructs a new box geometry.
  15369. *
  15370. * @param {number} [width=1] - The width. That is, the length of the edges parallel to the X axis.
  15371. * @param {number} [height=1] - The height. That is, the length of the edges parallel to the Y axis.
  15372. * @param {number} [depth=1] - The depth. That is, the length of the edges parallel to the Z axis.
  15373. * @param {number} [widthSegments=1] - Number of segmented rectangular faces along the width of the sides.
  15374. * @param {number} [heightSegments=1] - Number of segmented rectangular faces along the height of the sides.
  15375. * @param {number} [depthSegments=1] - Number of segmented rectangular faces along the depth of the sides.
  15376. */
  15377. constructor( width = 1, height = 1, depth = 1, widthSegments = 1, heightSegments = 1, depthSegments = 1 ) {
  15378. super();
  15379. this.type = 'BoxGeometry';
  15380. /**
  15381. * Holds the constructor parameters that have been
  15382. * used to generate the geometry. Any modification
  15383. * after instantiation does not change the geometry.
  15384. *
  15385. * @type {Object}
  15386. */
  15387. this.parameters = {
  15388. width: width,
  15389. height: height,
  15390. depth: depth,
  15391. widthSegments: widthSegments,
  15392. heightSegments: heightSegments,
  15393. depthSegments: depthSegments
  15394. };
  15395. const scope = this;
  15396. // segments
  15397. widthSegments = Math.floor( widthSegments );
  15398. heightSegments = Math.floor( heightSegments );
  15399. depthSegments = Math.floor( depthSegments );
  15400. // buffers
  15401. const indices = [];
  15402. const vertices = [];
  15403. const normals = [];
  15404. const uvs = [];
  15405. // helper variables
  15406. let numberOfVertices = 0;
  15407. let groupStart = 0;
  15408. // build each side of the box geometry
  15409. buildPlane( 'z', 'y', 'x', -1, -1, depth, height, width, depthSegments, heightSegments, 0 ); // px
  15410. buildPlane( 'z', 'y', 'x', 1, -1, depth, height, - width, depthSegments, heightSegments, 1 ); // nx
  15411. buildPlane( 'x', 'z', 'y', 1, 1, width, depth, height, widthSegments, depthSegments, 2 ); // py
  15412. buildPlane( 'x', 'z', 'y', 1, -1, width, depth, - height, widthSegments, depthSegments, 3 ); // ny
  15413. buildPlane( 'x', 'y', 'z', 1, -1, width, height, depth, widthSegments, heightSegments, 4 ); // pz
  15414. buildPlane( 'x', 'y', 'z', -1, -1, width, height, - depth, widthSegments, heightSegments, 5 ); // nz
  15415. // build geometry
  15416. this.setIndex( indices );
  15417. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  15418. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  15419. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  15420. function buildPlane( u, v, w, udir, vdir, width, height, depth, gridX, gridY, materialIndex ) {
  15421. const segmentWidth = width / gridX;
  15422. const segmentHeight = height / gridY;
  15423. const widthHalf = width / 2;
  15424. const heightHalf = height / 2;
  15425. const depthHalf = depth / 2;
  15426. const gridX1 = gridX + 1;
  15427. const gridY1 = gridY + 1;
  15428. let vertexCounter = 0;
  15429. let groupCount = 0;
  15430. const vector = new Vector3();
  15431. // generate vertices, normals and uvs
  15432. for ( let iy = 0; iy < gridY1; iy ++ ) {
  15433. const y = iy * segmentHeight - heightHalf;
  15434. for ( let ix = 0; ix < gridX1; ix ++ ) {
  15435. const x = ix * segmentWidth - widthHalf;
  15436. // set values to correct vector component
  15437. vector[ u ] = x * udir;
  15438. vector[ v ] = y * vdir;
  15439. vector[ w ] = depthHalf;
  15440. // now apply vector to vertex buffer
  15441. vertices.push( vector.x, vector.y, vector.z );
  15442. // set values to correct vector component
  15443. vector[ u ] = 0;
  15444. vector[ v ] = 0;
  15445. vector[ w ] = depth > 0 ? 1 : -1;
  15446. // now apply vector to normal buffer
  15447. normals.push( vector.x, vector.y, vector.z );
  15448. // uvs
  15449. uvs.push( ix / gridX );
  15450. uvs.push( 1 - ( iy / gridY ) );
  15451. // counters
  15452. vertexCounter += 1;
  15453. }
  15454. }
  15455. // indices
  15456. // 1. you need three indices to draw a single face
  15457. // 2. a single segment consists of two faces
  15458. // 3. so we need to generate six (2*3) indices per segment
  15459. for ( let iy = 0; iy < gridY; iy ++ ) {
  15460. for ( let ix = 0; ix < gridX; ix ++ ) {
  15461. const a = numberOfVertices + ix + gridX1 * iy;
  15462. const b = numberOfVertices + ix + gridX1 * ( iy + 1 );
  15463. const c = numberOfVertices + ( ix + 1 ) + gridX1 * ( iy + 1 );
  15464. const d = numberOfVertices + ( ix + 1 ) + gridX1 * iy;
  15465. // faces
  15466. indices.push( a, b, d );
  15467. indices.push( b, c, d );
  15468. // increase counter
  15469. groupCount += 6;
  15470. }
  15471. }
  15472. // add a group to the geometry. this will ensure multi material support
  15473. scope.addGroup( groupStart, groupCount, materialIndex );
  15474. // calculate new start value for groups
  15475. groupStart += groupCount;
  15476. // update total number of vertices
  15477. numberOfVertices += vertexCounter;
  15478. }
  15479. }
  15480. copy( source ) {
  15481. super.copy( source );
  15482. this.parameters = Object.assign( {}, source.parameters );
  15483. return this;
  15484. }
  15485. /**
  15486. * Factory method for creating an instance of this class from the given
  15487. * JSON object.
  15488. *
  15489. * @param {Object} data - A JSON object representing the serialized geometry.
  15490. * @return {BoxGeometry} A new instance.
  15491. */
  15492. static fromJSON( data ) {
  15493. return new BoxGeometry( data.width, data.height, data.depth, data.widthSegments, data.heightSegments, data.depthSegments );
  15494. }
  15495. }
  15496. // Uniform Utilities
  15497. function cloneUniforms( src ) {
  15498. const dst = {};
  15499. for ( const u in src ) {
  15500. dst[ u ] = {};
  15501. for ( const p in src[ u ] ) {
  15502. const property = src[ u ][ p ];
  15503. if ( property && ( property.isColor ||
  15504. property.isMatrix3 || property.isMatrix4 ||
  15505. property.isVector2 || property.isVector3 || property.isVector4 ||
  15506. property.isTexture || property.isQuaternion ) ) {
  15507. if ( property.isRenderTargetTexture ) {
  15508. console.warn( 'UniformsUtils: Textures of render targets cannot be cloned via cloneUniforms() or mergeUniforms().' );
  15509. dst[ u ][ p ] = null;
  15510. } else {
  15511. dst[ u ][ p ] = property.clone();
  15512. }
  15513. } else if ( Array.isArray( property ) ) {
  15514. dst[ u ][ p ] = property.slice();
  15515. } else {
  15516. dst[ u ][ p ] = property;
  15517. }
  15518. }
  15519. }
  15520. return dst;
  15521. }
  15522. function mergeUniforms( uniforms ) {
  15523. const merged = {};
  15524. for ( let u = 0; u < uniforms.length; u ++ ) {
  15525. const tmp = cloneUniforms( uniforms[ u ] );
  15526. for ( const p in tmp ) {
  15527. merged[ p ] = tmp[ p ];
  15528. }
  15529. }
  15530. return merged;
  15531. }
  15532. function cloneUniformsGroups( src ) {
  15533. const dst = [];
  15534. for ( let u = 0; u < src.length; u ++ ) {
  15535. dst.push( src[ u ].clone() );
  15536. }
  15537. return dst;
  15538. }
  15539. function getUnlitUniformColorSpace( renderer ) {
  15540. const currentRenderTarget = renderer.getRenderTarget();
  15541. if ( currentRenderTarget === null ) {
  15542. // https://github.com/mrdoob/three.js/pull/23937#issuecomment-1111067398
  15543. return renderer.outputColorSpace;
  15544. }
  15545. // https://github.com/mrdoob/three.js/issues/27868
  15546. if ( currentRenderTarget.isXRRenderTarget === true ) {
  15547. return currentRenderTarget.texture.colorSpace;
  15548. }
  15549. return ColorManagement.workingColorSpace;
  15550. }
  15551. // Legacy
  15552. const UniformsUtils = { clone: cloneUniforms, merge: mergeUniforms };
  15553. var default_vertex = "void main() {\n\tgl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n}";
  15554. var default_fragment = "void main() {\n\tgl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );\n}";
  15555. /**
  15556. * A material rendered with custom shaders. A shader is a small program written in GLSL.
  15557. * that runs on the GPU. You may want to use a custom shader if you need to implement an
  15558. * effect not included with any of the built-in materials.
  15559. *
  15560. * There are the following notes to bear in mind when using a `ShaderMaterial`:
  15561. *
  15562. * - `ShaderMaterial` can only be used with {@link WebGLRenderer}.
  15563. * - Built in attributes and uniforms are passed to the shaders along with your code. If
  15564. * you don't want that, use {@link RawShaderMaterial} instead.
  15565. * - You can use the directive `#pragma unroll_loop_start` and `#pragma unroll_loop_end`
  15566. * in order to unroll a `for` loop in GLSL by the shader preprocessor. The directive has
  15567. * to be placed right above the loop. The loop formatting has to correspond to a defined standard.
  15568. * - The loop has to be [normalized]{@link https://en.wikipedia.org/wiki/Normalized_loop}.
  15569. * - The loop variable has to be *i*.
  15570. * - The value `UNROLLED_LOOP_INDEX` will be replaced with the explicitly
  15571. * value of *i* for the given iteration and can be used in preprocessor
  15572. * statements.
  15573. *
  15574. * ```js
  15575. * const material = new THREE.ShaderMaterial( {
  15576. * uniforms: {
  15577. * time: { value: 1.0 },
  15578. * resolution: { value: new THREE.Vector2() }
  15579. * },
  15580. * vertexShader: document.getElementById( 'vertexShader' ).textContent,
  15581. * fragmentShader: document.getElementById( 'fragmentShader' ).textContent
  15582. * } );
  15583. * ```
  15584. *
  15585. * @augments Material
  15586. */
  15587. class ShaderMaterial extends Material {
  15588. /**
  15589. * Constructs a new shader material.
  15590. *
  15591. * @param {Object} [parameters] - An object with one or more properties
  15592. * defining the material's appearance. Any property of the material
  15593. * (including any property from inherited materials) can be passed
  15594. * in here. Color values can be passed any type of value accepted
  15595. * by {@link Color#set}.
  15596. */
  15597. constructor( parameters ) {
  15598. super();
  15599. /**
  15600. * This flag can be used for type testing.
  15601. *
  15602. * @type {boolean}
  15603. * @readonly
  15604. * @default true
  15605. */
  15606. this.isShaderMaterial = true;
  15607. this.type = 'ShaderMaterial';
  15608. /**
  15609. * Defines custom constants using `#define` directives within the GLSL code
  15610. * for both the vertex shader and the fragment shader; each key/value pair
  15611. * yields another directive.
  15612. * ```js
  15613. * defines: {
  15614. * FOO: 15,
  15615. * BAR: true
  15616. * }
  15617. * ```
  15618. * Yields the lines:
  15619. * ```
  15620. * #define FOO 15
  15621. * #define BAR true
  15622. * ```
  15623. *
  15624. * @type {Object}
  15625. */
  15626. this.defines = {};
  15627. /**
  15628. * An object of the form:
  15629. * ```js
  15630. * {
  15631. * "uniform1": { value: 1.0 },
  15632. * "uniform2": { value: 2 }
  15633. * }
  15634. * ```
  15635. * specifying the uniforms to be passed to the shader code; keys are uniform
  15636. * names, values are definitions of the form
  15637. * ```
  15638. * {
  15639. * value: 1.0
  15640. * }
  15641. * ```
  15642. * where `value` is the value of the uniform. Names must match the name of
  15643. * the uniform, as defined in the GLSL code. Note that uniforms are refreshed
  15644. * on every frame, so updating the value of the uniform will immediately
  15645. * update the value available to the GLSL code.
  15646. *
  15647. * @type {Object}
  15648. */
  15649. this.uniforms = {};
  15650. /**
  15651. * An array holding uniforms groups for configuring UBOs.
  15652. *
  15653. * @type {Array<UniformsGroup>}
  15654. */
  15655. this.uniformsGroups = [];
  15656. /**
  15657. * Vertex shader GLSL code. This is the actual code for the shader.
  15658. *
  15659. * @type {string}
  15660. */
  15661. this.vertexShader = default_vertex;
  15662. /**
  15663. * Fragment shader GLSL code. This is the actual code for the shader.
  15664. *
  15665. * @type {string}
  15666. */
  15667. this.fragmentShader = default_fragment;
  15668. /**
  15669. * Controls line thickness or lines.
  15670. *
  15671. * WebGL and WebGPU ignore this setting and always render line primitives with a
  15672. * width of one pixel.
  15673. *
  15674. * @type {number}
  15675. * @default 1
  15676. */
  15677. this.linewidth = 1;
  15678. /**
  15679. * Renders the geometry as a wireframe.
  15680. *
  15681. * @type {boolean}
  15682. * @default false
  15683. */
  15684. this.wireframe = false;
  15685. /**
  15686. * Controls the thickness of the wireframe.
  15687. *
  15688. * WebGL and WebGPU ignore this property and always render
  15689. * 1 pixel wide lines.
  15690. *
  15691. * @type {number}
  15692. * @default 1
  15693. */
  15694. this.wireframeLinewidth = 1;
  15695. /**
  15696. * Define whether the material color is affected by global fog settings; `true`
  15697. * to pass fog uniforms to the shader.
  15698. *
  15699. * @type {boolean}
  15700. * @default false
  15701. */
  15702. this.fog = false;
  15703. /**
  15704. * Defines whether this material uses lighting; `true` to pass uniform data
  15705. * related to lighting to this shader.
  15706. *
  15707. * @type {boolean}
  15708. * @default false
  15709. */
  15710. this.lights = false;
  15711. /**
  15712. * Defines whether this material supports clipping; `true` to let the renderer
  15713. * pass the clippingPlanes uniform.
  15714. *
  15715. * @type {boolean}
  15716. * @default false
  15717. */
  15718. this.clipping = false;
  15719. /**
  15720. * Overwritten and set to `true` by default.
  15721. *
  15722. * @type {boolean}
  15723. * @default true
  15724. */
  15725. this.forceSinglePass = true;
  15726. /**
  15727. * This object allows to enable certain WebGL 2 extensions.
  15728. *
  15729. * - clipCullDistance: set to `true` to use vertex shader clipping
  15730. * - multiDraw: set to `true` to use vertex shader multi_draw / enable gl_DrawID
  15731. *
  15732. * @type {{clipCullDistance:false,multiDraw:false}}
  15733. */
  15734. this.extensions = {
  15735. clipCullDistance: false, // set to use vertex shader clipping
  15736. multiDraw: false // set to use vertex shader multi_draw / enable gl_DrawID
  15737. };
  15738. /**
  15739. * When the rendered geometry doesn't include these attributes but the
  15740. * material does, these default values will be passed to the shaders. This
  15741. * avoids errors when buffer data is missing.
  15742. *
  15743. * - color: [ 1, 1, 1 ]
  15744. * - uv: [ 0, 0 ]
  15745. * - uv1: [ 0, 0 ]
  15746. *
  15747. * @type {Object}
  15748. */
  15749. this.defaultAttributeValues = {
  15750. 'color': [ 1, 1, 1 ],
  15751. 'uv': [ 0, 0 ],
  15752. 'uv1': [ 0, 0 ]
  15753. };
  15754. /**
  15755. * If set, this calls [gl.bindAttribLocation]{@link https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/bindAttribLocation}
  15756. * to bind a generic vertex index to an attribute variable.
  15757. *
  15758. * @type {string|undefined}
  15759. * @default undefined
  15760. */
  15761. this.index0AttributeName = undefined;
  15762. /**
  15763. * Can be used to force a uniform update while changing uniforms in
  15764. * {@link Object3D#onBeforeRender}.
  15765. *
  15766. * @type {boolean}
  15767. * @default false
  15768. */
  15769. this.uniformsNeedUpdate = false;
  15770. /**
  15771. * Defines the GLSL version of custom shader code.
  15772. *
  15773. * @type {?(GLSL1|GLSL3)}
  15774. * @default null
  15775. */
  15776. this.glslVersion = null;
  15777. if ( parameters !== undefined ) {
  15778. this.setValues( parameters );
  15779. }
  15780. }
  15781. copy( source ) {
  15782. super.copy( source );
  15783. this.fragmentShader = source.fragmentShader;
  15784. this.vertexShader = source.vertexShader;
  15785. this.uniforms = cloneUniforms( source.uniforms );
  15786. this.uniformsGroups = cloneUniformsGroups( source.uniformsGroups );
  15787. this.defines = Object.assign( {}, source.defines );
  15788. this.wireframe = source.wireframe;
  15789. this.wireframeLinewidth = source.wireframeLinewidth;
  15790. this.fog = source.fog;
  15791. this.lights = source.lights;
  15792. this.clipping = source.clipping;
  15793. this.extensions = Object.assign( {}, source.extensions );
  15794. this.glslVersion = source.glslVersion;
  15795. return this;
  15796. }
  15797. toJSON( meta ) {
  15798. const data = super.toJSON( meta );
  15799. data.glslVersion = this.glslVersion;
  15800. data.uniforms = {};
  15801. for ( const name in this.uniforms ) {
  15802. const uniform = this.uniforms[ name ];
  15803. const value = uniform.value;
  15804. if ( value && value.isTexture ) {
  15805. data.uniforms[ name ] = {
  15806. type: 't',
  15807. value: value.toJSON( meta ).uuid
  15808. };
  15809. } else if ( value && value.isColor ) {
  15810. data.uniforms[ name ] = {
  15811. type: 'c',
  15812. value: value.getHex()
  15813. };
  15814. } else if ( value && value.isVector2 ) {
  15815. data.uniforms[ name ] = {
  15816. type: 'v2',
  15817. value: value.toArray()
  15818. };
  15819. } else if ( value && value.isVector3 ) {
  15820. data.uniforms[ name ] = {
  15821. type: 'v3',
  15822. value: value.toArray()
  15823. };
  15824. } else if ( value && value.isVector4 ) {
  15825. data.uniforms[ name ] = {
  15826. type: 'v4',
  15827. value: value.toArray()
  15828. };
  15829. } else if ( value && value.isMatrix3 ) {
  15830. data.uniforms[ name ] = {
  15831. type: 'm3',
  15832. value: value.toArray()
  15833. };
  15834. } else if ( value && value.isMatrix4 ) {
  15835. data.uniforms[ name ] = {
  15836. type: 'm4',
  15837. value: value.toArray()
  15838. };
  15839. } else {
  15840. data.uniforms[ name ] = {
  15841. value: value
  15842. };
  15843. // note: the array variants v2v, v3v, v4v, m4v and tv are not supported so far
  15844. }
  15845. }
  15846. if ( Object.keys( this.defines ).length > 0 ) data.defines = this.defines;
  15847. data.vertexShader = this.vertexShader;
  15848. data.fragmentShader = this.fragmentShader;
  15849. data.lights = this.lights;
  15850. data.clipping = this.clipping;
  15851. const extensions = {};
  15852. for ( const key in this.extensions ) {
  15853. if ( this.extensions[ key ] === true ) extensions[ key ] = true;
  15854. }
  15855. if ( Object.keys( extensions ).length > 0 ) data.extensions = extensions;
  15856. return data;
  15857. }
  15858. }
  15859. /**
  15860. * Abstract base class for cameras. This class should always be inherited
  15861. * when you build a new camera.
  15862. *
  15863. * @abstract
  15864. * @augments Object3D
  15865. */
  15866. class Camera extends Object3D {
  15867. /**
  15868. * Constructs a new camera.
  15869. */
  15870. constructor() {
  15871. super();
  15872. /**
  15873. * This flag can be used for type testing.
  15874. *
  15875. * @type {boolean}
  15876. * @readonly
  15877. * @default true
  15878. */
  15879. this.isCamera = true;
  15880. this.type = 'Camera';
  15881. /**
  15882. * The inverse of the camera's world matrix.
  15883. *
  15884. * @type {Matrix4}
  15885. */
  15886. this.matrixWorldInverse = new Matrix4();
  15887. /**
  15888. * The camera's projection matrix.
  15889. *
  15890. * @type {Matrix4}
  15891. */
  15892. this.projectionMatrix = new Matrix4();
  15893. /**
  15894. * The inverse of the camera's projection matrix.
  15895. *
  15896. * @type {Matrix4}
  15897. */
  15898. this.projectionMatrixInverse = new Matrix4();
  15899. /**
  15900. * The coordinate system in which the camera is used.
  15901. *
  15902. * @type {(WebGLCoordinateSystem|WebGPUCoordinateSystem)}
  15903. */
  15904. this.coordinateSystem = WebGLCoordinateSystem;
  15905. }
  15906. copy( source, recursive ) {
  15907. super.copy( source, recursive );
  15908. this.matrixWorldInverse.copy( source.matrixWorldInverse );
  15909. this.projectionMatrix.copy( source.projectionMatrix );
  15910. this.projectionMatrixInverse.copy( source.projectionMatrixInverse );
  15911. this.coordinateSystem = source.coordinateSystem;
  15912. return this;
  15913. }
  15914. /**
  15915. * Returns a vector representing the ("look") direction of the 3D object in world space.
  15916. *
  15917. * This method is overwritten since cameras have a different forward vector compared to other
  15918. * 3D objects. A camera looks down its local, negative z-axis by default.
  15919. *
  15920. * @param {Vector3} target - The target vector the result is stored to.
  15921. * @return {Vector3} The 3D object's direction in world space.
  15922. */
  15923. getWorldDirection( target ) {
  15924. return super.getWorldDirection( target ).negate();
  15925. }
  15926. updateMatrixWorld( force ) {
  15927. super.updateMatrixWorld( force );
  15928. this.matrixWorldInverse.copy( this.matrixWorld ).invert();
  15929. }
  15930. updateWorldMatrix( updateParents, updateChildren ) {
  15931. super.updateWorldMatrix( updateParents, updateChildren );
  15932. this.matrixWorldInverse.copy( this.matrixWorld ).invert();
  15933. }
  15934. clone() {
  15935. return new this.constructor().copy( this );
  15936. }
  15937. }
  15938. const _v3$1 = /*@__PURE__*/ new Vector3();
  15939. const _minTarget = /*@__PURE__*/ new Vector2();
  15940. const _maxTarget = /*@__PURE__*/ new Vector2();
  15941. /**
  15942. * Camera that uses [perspective projection]{@link https://en.wikipedia.org/wiki/Perspective_(graphical)}.
  15943. *
  15944. * This projection mode is designed to mimic the way the human eye sees. It
  15945. * is the most common projection mode used for rendering a 3D scene.
  15946. *
  15947. * ```js
  15948. * const camera = new THREE.PerspectiveCamera( 45, width / height, 1, 1000 );
  15949. * scene.add( camera );
  15950. * ```
  15951. *
  15952. * @augments Camera
  15953. */
  15954. class PerspectiveCamera extends Camera {
  15955. /**
  15956. * Constructs a new perspective camera.
  15957. *
  15958. * @param {number} [fov=50] - The vertical field of view.
  15959. * @param {number} [aspect=1] - The aspect ratio.
  15960. * @param {number} [near=0.1] - The camera's near plane.
  15961. * @param {number} [far=2000] - The camera's far plane.
  15962. */
  15963. constructor( fov = 50, aspect = 1, near = 0.1, far = 2000 ) {
  15964. super();
  15965. /**
  15966. * This flag can be used for type testing.
  15967. *
  15968. * @type {boolean}
  15969. * @readonly
  15970. * @default true
  15971. */
  15972. this.isPerspectiveCamera = true;
  15973. this.type = 'PerspectiveCamera';
  15974. /**
  15975. * The vertical field of view, from bottom to top of view,
  15976. * in degrees.
  15977. *
  15978. * @type {number}
  15979. * @default 50
  15980. */
  15981. this.fov = fov;
  15982. /**
  15983. * The zoom factor of the camera.
  15984. *
  15985. * @type {number}
  15986. * @default 1
  15987. */
  15988. this.zoom = 1;
  15989. /**
  15990. * The camera's near plane. The valid range is greater than `0`
  15991. * and less than the current value of {@link PerspectiveCamera#far}.
  15992. *
  15993. * Note that, unlike for the {@link OrthographicCamera}, `0` is <em>not</em> a
  15994. * valid value for a perspective camera's near plane.
  15995. *
  15996. * @type {number}
  15997. * @default 0.1
  15998. */
  15999. this.near = near;
  16000. /**
  16001. * The camera's far plane. Must be greater than the
  16002. * current value of {@link PerspectiveCamera#near}.
  16003. *
  16004. * @type {number}
  16005. * @default 2000
  16006. */
  16007. this.far = far;
  16008. /**
  16009. * Object distance used for stereoscopy and depth-of-field effects. This
  16010. * parameter does not influence the projection matrix unless a
  16011. * {@link StereoCamera} is being used.
  16012. *
  16013. * @type {number}
  16014. * @default 10
  16015. */
  16016. this.focus = 10;
  16017. /**
  16018. * The aspect ratio, usually the canvas width / canvas height.
  16019. *
  16020. * @type {number}
  16021. * @default 1
  16022. */
  16023. this.aspect = aspect;
  16024. /**
  16025. * Represents the frustum window specification. This property should not be edited
  16026. * directly but via {@link PerspectiveCamera#setViewOffset} and {@link PerspectiveCamera#clearViewOffset}.
  16027. *
  16028. * @type {?Object}
  16029. * @default null
  16030. */
  16031. this.view = null;
  16032. /**
  16033. * Film size used for the larger axis. Default is `35` (millimeters). This
  16034. * parameter does not influence the projection matrix unless {@link PerspectiveCamera#filmOffset}
  16035. * is set to a nonzero value.
  16036. *
  16037. * @type {number}
  16038. * @default 35
  16039. */
  16040. this.filmGauge = 35;
  16041. /**
  16042. * Horizontal off-center offset in the same unit as {@link PerspectiveCamera#filmGauge}.
  16043. *
  16044. * @type {number}
  16045. * @default 0
  16046. */
  16047. this.filmOffset = 0;
  16048. this.updateProjectionMatrix();
  16049. }
  16050. copy( source, recursive ) {
  16051. super.copy( source, recursive );
  16052. this.fov = source.fov;
  16053. this.zoom = source.zoom;
  16054. this.near = source.near;
  16055. this.far = source.far;
  16056. this.focus = source.focus;
  16057. this.aspect = source.aspect;
  16058. this.view = source.view === null ? null : Object.assign( {}, source.view );
  16059. this.filmGauge = source.filmGauge;
  16060. this.filmOffset = source.filmOffset;
  16061. return this;
  16062. }
  16063. /**
  16064. * Sets the FOV by focal length in respect to the current {@link PerspectiveCamera#filmGauge}.
  16065. *
  16066. * The default film gauge is 35, so that the focal length can be specified for
  16067. * a 35mm (full frame) camera.
  16068. *
  16069. * @param {number} focalLength - Values for focal length and film gauge must have the same unit.
  16070. */
  16071. setFocalLength( focalLength ) {
  16072. /** see {@link http://www.bobatkins.com/photography/technical/field_of_view.html} */
  16073. const vExtentSlope = 0.5 * this.getFilmHeight() / focalLength;
  16074. this.fov = RAD2DEG * 2 * Math.atan( vExtentSlope );
  16075. this.updateProjectionMatrix();
  16076. }
  16077. /**
  16078. * Returns the focal length from the current {@link PerspectiveCamera#fov} and
  16079. * {@link PerspectiveCamera#filmGauge}.
  16080. *
  16081. * @return {number} The computed focal length.
  16082. */
  16083. getFocalLength() {
  16084. const vExtentSlope = Math.tan( DEG2RAD * 0.5 * this.fov );
  16085. return 0.5 * this.getFilmHeight() / vExtentSlope;
  16086. }
  16087. /**
  16088. * Returns the current vertical field of view angle in degrees considering {@link PerspectiveCamera#zoom}.
  16089. *
  16090. * @return {number} The effective FOV.
  16091. */
  16092. getEffectiveFOV() {
  16093. return RAD2DEG * 2 * Math.atan(
  16094. Math.tan( DEG2RAD * 0.5 * this.fov ) / this.zoom );
  16095. }
  16096. /**
  16097. * Returns the width of the image on the film. If {@link PerspectiveCamera#aspect} is greater than or
  16098. * equal to one (landscape format), the result equals {@link PerspectiveCamera#filmGauge}.
  16099. *
  16100. * @return {number} The film width.
  16101. */
  16102. getFilmWidth() {
  16103. // film not completely covered in portrait format (aspect < 1)
  16104. return this.filmGauge * Math.min( this.aspect, 1 );
  16105. }
  16106. /**
  16107. * Returns the height of the image on the film. If {@link PerspectiveCamera#aspect} is greater than or
  16108. * equal to one (landscape format), the result equals {@link PerspectiveCamera#filmGauge}.
  16109. *
  16110. * @return {number} The film width.
  16111. */
  16112. getFilmHeight() {
  16113. // film not completely covered in landscape format (aspect > 1)
  16114. return this.filmGauge / Math.max( this.aspect, 1 );
  16115. }
  16116. /**
  16117. * Computes the 2D bounds of the camera's viewable rectangle at a given distance along the viewing direction.
  16118. * Sets `minTarget` and `maxTarget` to the coordinates of the lower-left and upper-right corners of the view rectangle.
  16119. *
  16120. * @param {number} distance - The viewing distance.
  16121. * @param {Vector2} minTarget - The lower-left corner of the view rectangle is written into this vector.
  16122. * @param {Vector2} maxTarget - The upper-right corner of the view rectangle is written into this vector.
  16123. */
  16124. getViewBounds( distance, minTarget, maxTarget ) {
  16125. _v3$1.set( -1, -1, 0.5 ).applyMatrix4( this.projectionMatrixInverse );
  16126. minTarget.set( _v3$1.x, _v3$1.y ).multiplyScalar( - distance / _v3$1.z );
  16127. _v3$1.set( 1, 1, 0.5 ).applyMatrix4( this.projectionMatrixInverse );
  16128. maxTarget.set( _v3$1.x, _v3$1.y ).multiplyScalar( - distance / _v3$1.z );
  16129. }
  16130. /**
  16131. * Computes the width and height of the camera's viewable rectangle at a given distance along the viewing direction.
  16132. *
  16133. * @param {number} distance - The viewing distance.
  16134. * @param {Vector2} target - The target vector that is used to store result where x is width and y is height.
  16135. * @returns {Vector2} The view size.
  16136. */
  16137. getViewSize( distance, target ) {
  16138. this.getViewBounds( distance, _minTarget, _maxTarget );
  16139. return target.subVectors( _maxTarget, _minTarget );
  16140. }
  16141. /**
  16142. * Sets an offset in a larger frustum. This is useful for multi-window or
  16143. * multi-monitor/multi-machine setups.
  16144. *
  16145. * For example, if you have 3x2 monitors and each monitor is 1920x1080 and
  16146. * the monitors are in grid like this
  16147. *```
  16148. * +---+---+---+
  16149. * | A | B | C |
  16150. * +---+---+---+
  16151. * | D | E | F |
  16152. * +---+---+---+
  16153. *```
  16154. * then for each monitor you would call it like this:
  16155. *```js
  16156. * const w = 1920;
  16157. * const h = 1080;
  16158. * const fullWidth = w * 3;
  16159. * const fullHeight = h * 2;
  16160. *
  16161. * // --A--
  16162. * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 0, w, h );
  16163. * // --B--
  16164. * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 0, w, h );
  16165. * // --C--
  16166. * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 0, w, h );
  16167. * // --D--
  16168. * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 1, w, h );
  16169. * // --E--
  16170. * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 1, w, h );
  16171. * // --F--
  16172. * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 1, w, h );
  16173. * ```
  16174. *
  16175. * Note there is no reason monitors have to be the same size or in a grid.
  16176. *
  16177. * @param {number} fullWidth - The full width of multiview setup.
  16178. * @param {number} fullHeight - The full height of multiview setup.
  16179. * @param {number} x - The horizontal offset of the subcamera.
  16180. * @param {number} y - The vertical offset of the subcamera.
  16181. * @param {number} width - The width of subcamera.
  16182. * @param {number} height - The height of subcamera.
  16183. */
  16184. setViewOffset( fullWidth, fullHeight, x, y, width, height ) {
  16185. this.aspect = fullWidth / fullHeight;
  16186. if ( this.view === null ) {
  16187. this.view = {
  16188. enabled: true,
  16189. fullWidth: 1,
  16190. fullHeight: 1,
  16191. offsetX: 0,
  16192. offsetY: 0,
  16193. width: 1,
  16194. height: 1
  16195. };
  16196. }
  16197. this.view.enabled = true;
  16198. this.view.fullWidth = fullWidth;
  16199. this.view.fullHeight = fullHeight;
  16200. this.view.offsetX = x;
  16201. this.view.offsetY = y;
  16202. this.view.width = width;
  16203. this.view.height = height;
  16204. this.updateProjectionMatrix();
  16205. }
  16206. /**
  16207. * Removes the view offset from the projection matrix.
  16208. */
  16209. clearViewOffset() {
  16210. if ( this.view !== null ) {
  16211. this.view.enabled = false;
  16212. }
  16213. this.updateProjectionMatrix();
  16214. }
  16215. /**
  16216. * Updates the camera's projection matrix. Must be called after any change of
  16217. * camera properties.
  16218. */
  16219. updateProjectionMatrix() {
  16220. const near = this.near;
  16221. let top = near * Math.tan( DEG2RAD * 0.5 * this.fov ) / this.zoom;
  16222. let height = 2 * top;
  16223. let width = this.aspect * height;
  16224. let left = -0.5 * width;
  16225. const view = this.view;
  16226. if ( this.view !== null && this.view.enabled ) {
  16227. const fullWidth = view.fullWidth,
  16228. fullHeight = view.fullHeight;
  16229. left += view.offsetX * width / fullWidth;
  16230. top -= view.offsetY * height / fullHeight;
  16231. width *= view.width / fullWidth;
  16232. height *= view.height / fullHeight;
  16233. }
  16234. const skew = this.filmOffset;
  16235. if ( skew !== 0 ) left += near * skew / this.getFilmWidth();
  16236. this.projectionMatrix.makePerspective( left, left + width, top, top - height, near, this.far, this.coordinateSystem );
  16237. this.projectionMatrixInverse.copy( this.projectionMatrix ).invert();
  16238. }
  16239. toJSON( meta ) {
  16240. const data = super.toJSON( meta );
  16241. data.object.fov = this.fov;
  16242. data.object.zoom = this.zoom;
  16243. data.object.near = this.near;
  16244. data.object.far = this.far;
  16245. data.object.focus = this.focus;
  16246. data.object.aspect = this.aspect;
  16247. if ( this.view !== null ) data.object.view = Object.assign( {}, this.view );
  16248. data.object.filmGauge = this.filmGauge;
  16249. data.object.filmOffset = this.filmOffset;
  16250. return data;
  16251. }
  16252. }
  16253. const fov = -90; // negative fov is not an error
  16254. const aspect = 1;
  16255. /**
  16256. * A special type of camera that is positioned in 3D space to render its surroundings into a
  16257. * cube render target. The render target can then be used as an environment map for rendering
  16258. * realtime reflections in your scene.
  16259. *
  16260. * ```js
  16261. * // Create cube render target
  16262. * const cubeRenderTarget = new THREE.WebGLCubeRenderTarget( 256, { generateMipmaps: true, minFilter: THREE.LinearMipmapLinearFilter } );
  16263. *
  16264. * // Create cube camera
  16265. * const cubeCamera = new THREE.CubeCamera( 1, 100000, cubeRenderTarget );
  16266. * scene.add( cubeCamera );
  16267. *
  16268. * // Create car
  16269. * const chromeMaterial = new THREE.MeshLambertMaterial( { color: 0xffffff, envMap: cubeRenderTarget.texture } );
  16270. * const car = new THREE.Mesh( carGeometry, chromeMaterial );
  16271. * scene.add( car );
  16272. *
  16273. * // Update the render target cube
  16274. * car.visible = false;
  16275. * cubeCamera.position.copy( car.position );
  16276. * cubeCamera.update( renderer, scene );
  16277. *
  16278. * // Render the scene
  16279. * car.visible = true;
  16280. * renderer.render( scene, camera );
  16281. * ```
  16282. *
  16283. * @augments Object3D
  16284. */
  16285. class CubeCamera extends Object3D {
  16286. /**
  16287. * Constructs a new cube camera.
  16288. *
  16289. * @param {number} near - The camera's near plane.
  16290. * @param {number} far - The camera's far plane.
  16291. * @param {WebGLCubeRenderTarget} renderTarget - The cube render target.
  16292. */
  16293. constructor( near, far, renderTarget ) {
  16294. super();
  16295. this.type = 'CubeCamera';
  16296. /**
  16297. * A reference to the cube render target.
  16298. *
  16299. * @type {WebGLCubeRenderTarget}
  16300. */
  16301. this.renderTarget = renderTarget;
  16302. /**
  16303. * The current active coordinate system.
  16304. *
  16305. * @type {?(WebGLCoordinateSystem|WebGPUCoordinateSystem)}
  16306. * @default null
  16307. */
  16308. this.coordinateSystem = null;
  16309. /**
  16310. * The current active mipmap level
  16311. *
  16312. * @type {number}
  16313. * @default 0
  16314. */
  16315. this.activeMipmapLevel = 0;
  16316. const cameraPX = new PerspectiveCamera( fov, aspect, near, far );
  16317. cameraPX.layers = this.layers;
  16318. this.add( cameraPX );
  16319. const cameraNX = new PerspectiveCamera( fov, aspect, near, far );
  16320. cameraNX.layers = this.layers;
  16321. this.add( cameraNX );
  16322. const cameraPY = new PerspectiveCamera( fov, aspect, near, far );
  16323. cameraPY.layers = this.layers;
  16324. this.add( cameraPY );
  16325. const cameraNY = new PerspectiveCamera( fov, aspect, near, far );
  16326. cameraNY.layers = this.layers;
  16327. this.add( cameraNY );
  16328. const cameraPZ = new PerspectiveCamera( fov, aspect, near, far );
  16329. cameraPZ.layers = this.layers;
  16330. this.add( cameraPZ );
  16331. const cameraNZ = new PerspectiveCamera( fov, aspect, near, far );
  16332. cameraNZ.layers = this.layers;
  16333. this.add( cameraNZ );
  16334. }
  16335. /**
  16336. * Must be called when the coordinate system of the cube camera is changed.
  16337. */
  16338. updateCoordinateSystem() {
  16339. const coordinateSystem = this.coordinateSystem;
  16340. const cameras = this.children.concat();
  16341. const [ cameraPX, cameraNX, cameraPY, cameraNY, cameraPZ, cameraNZ ] = cameras;
  16342. for ( const camera of cameras ) this.remove( camera );
  16343. if ( coordinateSystem === WebGLCoordinateSystem ) {
  16344. cameraPX.up.set( 0, 1, 0 );
  16345. cameraPX.lookAt( 1, 0, 0 );
  16346. cameraNX.up.set( 0, 1, 0 );
  16347. cameraNX.lookAt( -1, 0, 0 );
  16348. cameraPY.up.set( 0, 0, -1 );
  16349. cameraPY.lookAt( 0, 1, 0 );
  16350. cameraNY.up.set( 0, 0, 1 );
  16351. cameraNY.lookAt( 0, -1, 0 );
  16352. cameraPZ.up.set( 0, 1, 0 );
  16353. cameraPZ.lookAt( 0, 0, 1 );
  16354. cameraNZ.up.set( 0, 1, 0 );
  16355. cameraNZ.lookAt( 0, 0, -1 );
  16356. } else if ( coordinateSystem === WebGPUCoordinateSystem ) {
  16357. cameraPX.up.set( 0, -1, 0 );
  16358. cameraPX.lookAt( -1, 0, 0 );
  16359. cameraNX.up.set( 0, -1, 0 );
  16360. cameraNX.lookAt( 1, 0, 0 );
  16361. cameraPY.up.set( 0, 0, 1 );
  16362. cameraPY.lookAt( 0, 1, 0 );
  16363. cameraNY.up.set( 0, 0, -1 );
  16364. cameraNY.lookAt( 0, -1, 0 );
  16365. cameraPZ.up.set( 0, -1, 0 );
  16366. cameraPZ.lookAt( 0, 0, 1 );
  16367. cameraNZ.up.set( 0, -1, 0 );
  16368. cameraNZ.lookAt( 0, 0, -1 );
  16369. } else {
  16370. throw new Error( 'THREE.CubeCamera.updateCoordinateSystem(): Invalid coordinate system: ' + coordinateSystem );
  16371. }
  16372. for ( const camera of cameras ) {
  16373. this.add( camera );
  16374. camera.updateMatrixWorld();
  16375. }
  16376. }
  16377. /**
  16378. * Calling this method will render the given scene with the given renderer
  16379. * into the cube render target of the camera.
  16380. *
  16381. * @param {(Renderer|WebGLRenderer)} renderer - The renderer.
  16382. * @param {Scene} scene - The scene to render.
  16383. */
  16384. update( renderer, scene ) {
  16385. if ( this.parent === null ) this.updateMatrixWorld();
  16386. const { renderTarget, activeMipmapLevel } = this;
  16387. if ( this.coordinateSystem !== renderer.coordinateSystem ) {
  16388. this.coordinateSystem = renderer.coordinateSystem;
  16389. this.updateCoordinateSystem();
  16390. }
  16391. const [ cameraPX, cameraNX, cameraPY, cameraNY, cameraPZ, cameraNZ ] = this.children;
  16392. const currentRenderTarget = renderer.getRenderTarget();
  16393. const currentActiveCubeFace = renderer.getActiveCubeFace();
  16394. const currentActiveMipmapLevel = renderer.getActiveMipmapLevel();
  16395. const currentXrEnabled = renderer.xr.enabled;
  16396. renderer.xr.enabled = false;
  16397. const generateMipmaps = renderTarget.texture.generateMipmaps;
  16398. renderTarget.texture.generateMipmaps = false;
  16399. renderer.setRenderTarget( renderTarget, 0, activeMipmapLevel );
  16400. renderer.render( scene, cameraPX );
  16401. renderer.setRenderTarget( renderTarget, 1, activeMipmapLevel );
  16402. renderer.render( scene, cameraNX );
  16403. renderer.setRenderTarget( renderTarget, 2, activeMipmapLevel );
  16404. renderer.render( scene, cameraPY );
  16405. renderer.setRenderTarget( renderTarget, 3, activeMipmapLevel );
  16406. renderer.render( scene, cameraNY );
  16407. renderer.setRenderTarget( renderTarget, 4, activeMipmapLevel );
  16408. renderer.render( scene, cameraPZ );
  16409. // mipmaps are generated during the last call of render()
  16410. // at this point, all sides of the cube render target are defined
  16411. renderTarget.texture.generateMipmaps = generateMipmaps;
  16412. renderer.setRenderTarget( renderTarget, 5, activeMipmapLevel );
  16413. renderer.render( scene, cameraNZ );
  16414. renderer.setRenderTarget( currentRenderTarget, currentActiveCubeFace, currentActiveMipmapLevel );
  16415. renderer.xr.enabled = currentXrEnabled;
  16416. renderTarget.texture.needsPMREMUpdate = true;
  16417. }
  16418. }
  16419. /**
  16420. * Creates a cube texture made up of six images.
  16421. *
  16422. * ```js
  16423. * const loader = new THREE.CubeTextureLoader();
  16424. * loader.setPath( 'textures/cube/pisa/' );
  16425. *
  16426. * const textureCube = loader.load( [
  16427. * 'px.png', 'nx.png', 'py.png', 'ny.png', 'pz.png', 'nz.png'
  16428. * ] );
  16429. *
  16430. * const material = new THREE.MeshBasicMaterial( { color: 0xffffff, envMap: textureCube } );
  16431. * ```
  16432. *
  16433. * @augments Texture
  16434. */
  16435. class CubeTexture extends Texture {
  16436. /**
  16437. * Constructs a new cube texture.
  16438. *
  16439. * @param {Array<Image>} [images=[]] - An array holding a image for each side of a cube.
  16440. * @param {number} [mapping=CubeReflectionMapping] - The texture mapping.
  16441. * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value.
  16442. * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value.
  16443. * @param {number} [magFilter=LinearFilter] - The mag filter value.
  16444. * @param {number} [minFilter=LinearMipmapLinearFilter] - The min filter value.
  16445. * @param {number} [format=RGBAFormat] - The texture format.
  16446. * @param {number} [type=UnsignedByteType] - The texture type.
  16447. * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value.
  16448. * @param {string} [colorSpace=NoColorSpace] - The color space value.
  16449. */
  16450. constructor( images = [], mapping = CubeReflectionMapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace ) {
  16451. super( images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace );
  16452. /**
  16453. * This flag can be used for type testing.
  16454. *
  16455. * @type {boolean}
  16456. * @readonly
  16457. * @default true
  16458. */
  16459. this.isCubeTexture = true;
  16460. /**
  16461. * If set to `true`, the texture is flipped along the vertical axis when
  16462. * uploaded to the GPU.
  16463. *
  16464. * Overwritten and set to `false` by default.
  16465. *
  16466. * @type {boolean}
  16467. * @default false
  16468. */
  16469. this.flipY = false;
  16470. }
  16471. /**
  16472. * Alias for {@link CubeTexture#image}.
  16473. *
  16474. * @type {Array<Image>}
  16475. */
  16476. get images() {
  16477. return this.image;
  16478. }
  16479. set images( value ) {
  16480. this.image = value;
  16481. }
  16482. }
  16483. /**
  16484. * A cube render target used in context of {@link WebGLRenderer}.
  16485. *
  16486. * @augments WebGLRenderTarget
  16487. */
  16488. class WebGLCubeRenderTarget extends WebGLRenderTarget {
  16489. /**
  16490. * Constructs a new cube render target.
  16491. *
  16492. * @param {number} [size=1] - The size of the render target.
  16493. * @param {RenderTarget~Options} [options] - The configuration object.
  16494. */
  16495. constructor( size = 1, options = {} ) {
  16496. super( size, size, options );
  16497. /**
  16498. * This flag can be used for type testing.
  16499. *
  16500. * @type {boolean}
  16501. * @readonly
  16502. * @default true
  16503. */
  16504. this.isWebGLCubeRenderTarget = true;
  16505. const image = { width: size, height: size, depth: 1 };
  16506. const images = [ image, image, image, image, image, image ];
  16507. /**
  16508. * Overwritten with a different texture type.
  16509. *
  16510. * @type {DataArrayTexture}
  16511. */
  16512. this.texture = new CubeTexture( images );
  16513. this._setTextureOptions( options );
  16514. // By convention -- likely based on the RenderMan spec from the 1990's -- cube maps are specified by WebGL (and three.js)
  16515. // in a coordinate system in which positive-x is to the right when looking up the positive-z axis -- in other words,
  16516. // in a left-handed coordinate system. By continuing this convention, preexisting cube maps continued to render correctly.
  16517. // three.js uses a right-handed coordinate system. So environment maps used in three.js appear to have px and nx swapped
  16518. // and the flag isRenderTargetTexture controls this conversion. The flip is not required when using WebGLCubeRenderTarget.texture
  16519. // as a cube texture (this is detected when isRenderTargetTexture is set to true for cube textures).
  16520. this.texture.isRenderTargetTexture = true;
  16521. }
  16522. /**
  16523. * Converts the given equirectangular texture to a cube map.
  16524. *
  16525. * @param {WebGLRenderer} renderer - The renderer.
  16526. * @param {Texture} texture - The equirectangular texture.
  16527. * @return {WebGLCubeRenderTarget} A reference to this cube render target.
  16528. */
  16529. fromEquirectangularTexture( renderer, texture ) {
  16530. this.texture.type = texture.type;
  16531. this.texture.colorSpace = texture.colorSpace;
  16532. this.texture.generateMipmaps = texture.generateMipmaps;
  16533. this.texture.minFilter = texture.minFilter;
  16534. this.texture.magFilter = texture.magFilter;
  16535. const shader = {
  16536. uniforms: {
  16537. tEquirect: { value: null },
  16538. },
  16539. vertexShader: /* glsl */`
  16540. varying vec3 vWorldDirection;
  16541. vec3 transformDirection( in vec3 dir, in mat4 matrix ) {
  16542. return normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );
  16543. }
  16544. void main() {
  16545. vWorldDirection = transformDirection( position, modelMatrix );
  16546. #include <begin_vertex>
  16547. #include <project_vertex>
  16548. }
  16549. `,
  16550. fragmentShader: /* glsl */`
  16551. uniform sampler2D tEquirect;
  16552. varying vec3 vWorldDirection;
  16553. #include <common>
  16554. void main() {
  16555. vec3 direction = normalize( vWorldDirection );
  16556. vec2 sampleUV = equirectUv( direction );
  16557. gl_FragColor = texture2D( tEquirect, sampleUV );
  16558. }
  16559. `
  16560. };
  16561. const geometry = new BoxGeometry( 5, 5, 5 );
  16562. const material = new ShaderMaterial( {
  16563. name: 'CubemapFromEquirect',
  16564. uniforms: cloneUniforms( shader.uniforms ),
  16565. vertexShader: shader.vertexShader,
  16566. fragmentShader: shader.fragmentShader,
  16567. side: BackSide,
  16568. blending: NoBlending
  16569. } );
  16570. material.uniforms.tEquirect.value = texture;
  16571. const mesh = new Mesh( geometry, material );
  16572. const currentMinFilter = texture.minFilter;
  16573. // Avoid blurred poles
  16574. if ( texture.minFilter === LinearMipmapLinearFilter ) texture.minFilter = LinearFilter;
  16575. const camera = new CubeCamera( 1, 10, this );
  16576. camera.update( renderer, mesh );
  16577. texture.minFilter = currentMinFilter;
  16578. mesh.geometry.dispose();
  16579. mesh.material.dispose();
  16580. return this;
  16581. }
  16582. /**
  16583. * Clears this cube render target.
  16584. *
  16585. * @param {WebGLRenderer} renderer - The renderer.
  16586. * @param {boolean} [color=true] - Whether the color buffer should be cleared or not.
  16587. * @param {boolean} [depth=true] - Whether the depth buffer should be cleared or not.
  16588. * @param {boolean} [stencil=true] - Whether the stencil buffer should be cleared or not.
  16589. */
  16590. clear( renderer, color = true, depth = true, stencil = true ) {
  16591. const currentRenderTarget = renderer.getRenderTarget();
  16592. for ( let i = 0; i < 6; i ++ ) {
  16593. renderer.setRenderTarget( this, i );
  16594. renderer.clear( color, depth, stencil );
  16595. }
  16596. renderer.setRenderTarget( currentRenderTarget );
  16597. }
  16598. }
  16599. /**
  16600. * This is almost identical to an {@link Object3D}. Its purpose is to
  16601. * make working with groups of objects syntactically clearer.
  16602. *
  16603. * ```js
  16604. * // Create a group and add the two cubes.
  16605. * // These cubes can now be rotated / scaled etc as a group.
  16606. * const group = new THREE.Group();
  16607. *
  16608. * group.add( meshA );
  16609. * group.add( meshB );
  16610. *
  16611. * scene.add( group );
  16612. * ```
  16613. *
  16614. * @augments Object3D
  16615. */
  16616. class Group extends Object3D {
  16617. constructor() {
  16618. super();
  16619. /**
  16620. * This flag can be used for type testing.
  16621. *
  16622. * @type {boolean}
  16623. * @readonly
  16624. * @default true
  16625. */
  16626. this.isGroup = true;
  16627. this.type = 'Group';
  16628. }
  16629. }
  16630. const _moveEvent = { type: 'move' };
  16631. /**
  16632. * Class for representing a XR controller with its
  16633. * different coordinate systems.
  16634. *
  16635. * @private
  16636. */
  16637. class WebXRController {
  16638. /**
  16639. * Constructs a new XR controller.
  16640. */
  16641. constructor() {
  16642. /**
  16643. * A group representing the target ray space
  16644. * of the XR controller.
  16645. *
  16646. * @private
  16647. * @type {?Group}
  16648. * @default null
  16649. */
  16650. this._targetRay = null;
  16651. /**
  16652. * A group representing the grip space
  16653. * of the XR controller.
  16654. *
  16655. * @private
  16656. * @type {?Group}
  16657. * @default null
  16658. */
  16659. this._grip = null;
  16660. /**
  16661. * A group representing the hand space
  16662. * of the XR controller.
  16663. *
  16664. * @private
  16665. * @type {?Group}
  16666. * @default null
  16667. */
  16668. this._hand = null;
  16669. }
  16670. /**
  16671. * Returns a group representing the hand space of the XR controller.
  16672. *
  16673. * @return {Group} A group representing the hand space of the XR controller.
  16674. */
  16675. getHandSpace() {
  16676. if ( this._hand === null ) {
  16677. this._hand = new Group();
  16678. this._hand.matrixAutoUpdate = false;
  16679. this._hand.visible = false;
  16680. this._hand.joints = {};
  16681. this._hand.inputState = { pinching: false };
  16682. }
  16683. return this._hand;
  16684. }
  16685. /**
  16686. * Returns a group representing the target ray space of the XR controller.
  16687. *
  16688. * @return {Group} A group representing the target ray space of the XR controller.
  16689. */
  16690. getTargetRaySpace() {
  16691. if ( this._targetRay === null ) {
  16692. this._targetRay = new Group();
  16693. this._targetRay.matrixAutoUpdate = false;
  16694. this._targetRay.visible = false;
  16695. this._targetRay.hasLinearVelocity = false;
  16696. this._targetRay.linearVelocity = new Vector3();
  16697. this._targetRay.hasAngularVelocity = false;
  16698. this._targetRay.angularVelocity = new Vector3();
  16699. }
  16700. return this._targetRay;
  16701. }
  16702. /**
  16703. * Returns a group representing the grip space of the XR controller.
  16704. *
  16705. * @return {Group} A group representing the grip space of the XR controller.
  16706. */
  16707. getGripSpace() {
  16708. if ( this._grip === null ) {
  16709. this._grip = new Group();
  16710. this._grip.matrixAutoUpdate = false;
  16711. this._grip.visible = false;
  16712. this._grip.hasLinearVelocity = false;
  16713. this._grip.linearVelocity = new Vector3();
  16714. this._grip.hasAngularVelocity = false;
  16715. this._grip.angularVelocity = new Vector3();
  16716. }
  16717. return this._grip;
  16718. }
  16719. /**
  16720. * Dispatches the given event to the groups representing
  16721. * the different coordinate spaces of the XR controller.
  16722. *
  16723. * @param {Object} event - The event to dispatch.
  16724. * @return {WebXRController} A reference to this instance.
  16725. */
  16726. dispatchEvent( event ) {
  16727. if ( this._targetRay !== null ) {
  16728. this._targetRay.dispatchEvent( event );
  16729. }
  16730. if ( this._grip !== null ) {
  16731. this._grip.dispatchEvent( event );
  16732. }
  16733. if ( this._hand !== null ) {
  16734. this._hand.dispatchEvent( event );
  16735. }
  16736. return this;
  16737. }
  16738. /**
  16739. * Connects the controller with the given XR input source.
  16740. *
  16741. * @param {XRInputSource} inputSource - The input source.
  16742. * @return {WebXRController} A reference to this instance.
  16743. */
  16744. connect( inputSource ) {
  16745. if ( inputSource && inputSource.hand ) {
  16746. const hand = this._hand;
  16747. if ( hand ) {
  16748. for ( const inputjoint of inputSource.hand.values() ) {
  16749. // Initialize hand with joints when connected
  16750. this._getHandJoint( hand, inputjoint );
  16751. }
  16752. }
  16753. }
  16754. this.dispatchEvent( { type: 'connected', data: inputSource } );
  16755. return this;
  16756. }
  16757. /**
  16758. * Disconnects the controller from the given XR input source.
  16759. *
  16760. * @param {XRInputSource} inputSource - The input source.
  16761. * @return {WebXRController} A reference to this instance.
  16762. */
  16763. disconnect( inputSource ) {
  16764. this.dispatchEvent( { type: 'disconnected', data: inputSource } );
  16765. if ( this._targetRay !== null ) {
  16766. this._targetRay.visible = false;
  16767. }
  16768. if ( this._grip !== null ) {
  16769. this._grip.visible = false;
  16770. }
  16771. if ( this._hand !== null ) {
  16772. this._hand.visible = false;
  16773. }
  16774. return this;
  16775. }
  16776. /**
  16777. * Updates the controller with the given input source, XR frame and reference space.
  16778. * This updates the transformations of the groups that represent the different
  16779. * coordinate systems of the controller.
  16780. *
  16781. * @param {XRInputSource} inputSource - The input source.
  16782. * @param {XRFrame} frame - The XR frame.
  16783. * @param {XRReferenceSpace} referenceSpace - The reference space.
  16784. * @return {WebXRController} A reference to this instance.
  16785. */
  16786. update( inputSource, frame, referenceSpace ) {
  16787. let inputPose = null;
  16788. let gripPose = null;
  16789. let handPose = null;
  16790. const targetRay = this._targetRay;
  16791. const grip = this._grip;
  16792. const hand = this._hand;
  16793. if ( inputSource && frame.session.visibilityState !== 'visible-blurred' ) {
  16794. if ( hand && inputSource.hand ) {
  16795. handPose = true;
  16796. for ( const inputjoint of inputSource.hand.values() ) {
  16797. // Update the joints groups with the XRJoint poses
  16798. const jointPose = frame.getJointPose( inputjoint, referenceSpace );
  16799. // The transform of this joint will be updated with the joint pose on each frame
  16800. const joint = this._getHandJoint( hand, inputjoint );
  16801. if ( jointPose !== null ) {
  16802. joint.matrix.fromArray( jointPose.transform.matrix );
  16803. joint.matrix.decompose( joint.position, joint.rotation, joint.scale );
  16804. joint.matrixWorldNeedsUpdate = true;
  16805. joint.jointRadius = jointPose.radius;
  16806. }
  16807. joint.visible = jointPose !== null;
  16808. }
  16809. // Custom events
  16810. // Check pinchz
  16811. const indexTip = hand.joints[ 'index-finger-tip' ];
  16812. const thumbTip = hand.joints[ 'thumb-tip' ];
  16813. const distance = indexTip.position.distanceTo( thumbTip.position );
  16814. const distanceToPinch = 0.02;
  16815. const threshold = 0.005;
  16816. if ( hand.inputState.pinching && distance > distanceToPinch + threshold ) {
  16817. hand.inputState.pinching = false;
  16818. this.dispatchEvent( {
  16819. type: 'pinchend',
  16820. handedness: inputSource.handedness,
  16821. target: this
  16822. } );
  16823. } else if ( ! hand.inputState.pinching && distance <= distanceToPinch - threshold ) {
  16824. hand.inputState.pinching = true;
  16825. this.dispatchEvent( {
  16826. type: 'pinchstart',
  16827. handedness: inputSource.handedness,
  16828. target: this
  16829. } );
  16830. }
  16831. } else {
  16832. if ( grip !== null && inputSource.gripSpace ) {
  16833. gripPose = frame.getPose( inputSource.gripSpace, referenceSpace );
  16834. if ( gripPose !== null ) {
  16835. grip.matrix.fromArray( gripPose.transform.matrix );
  16836. grip.matrix.decompose( grip.position, grip.rotation, grip.scale );
  16837. grip.matrixWorldNeedsUpdate = true;
  16838. if ( gripPose.linearVelocity ) {
  16839. grip.hasLinearVelocity = true;
  16840. grip.linearVelocity.copy( gripPose.linearVelocity );
  16841. } else {
  16842. grip.hasLinearVelocity = false;
  16843. }
  16844. if ( gripPose.angularVelocity ) {
  16845. grip.hasAngularVelocity = true;
  16846. grip.angularVelocity.copy( gripPose.angularVelocity );
  16847. } else {
  16848. grip.hasAngularVelocity = false;
  16849. }
  16850. }
  16851. }
  16852. }
  16853. if ( targetRay !== null ) {
  16854. inputPose = frame.getPose( inputSource.targetRaySpace, referenceSpace );
  16855. // Some runtimes (namely Vive Cosmos with Vive OpenXR Runtime) have only grip space and ray space is equal to it
  16856. if ( inputPose === null && gripPose !== null ) {
  16857. inputPose = gripPose;
  16858. }
  16859. if ( inputPose !== null ) {
  16860. targetRay.matrix.fromArray( inputPose.transform.matrix );
  16861. targetRay.matrix.decompose( targetRay.position, targetRay.rotation, targetRay.scale );
  16862. targetRay.matrixWorldNeedsUpdate = true;
  16863. if ( inputPose.linearVelocity ) {
  16864. targetRay.hasLinearVelocity = true;
  16865. targetRay.linearVelocity.copy( inputPose.linearVelocity );
  16866. } else {
  16867. targetRay.hasLinearVelocity = false;
  16868. }
  16869. if ( inputPose.angularVelocity ) {
  16870. targetRay.hasAngularVelocity = true;
  16871. targetRay.angularVelocity.copy( inputPose.angularVelocity );
  16872. } else {
  16873. targetRay.hasAngularVelocity = false;
  16874. }
  16875. this.dispatchEvent( _moveEvent );
  16876. }
  16877. }
  16878. }
  16879. if ( targetRay !== null ) {
  16880. targetRay.visible = ( inputPose !== null );
  16881. }
  16882. if ( grip !== null ) {
  16883. grip.visible = ( gripPose !== null );
  16884. }
  16885. if ( hand !== null ) {
  16886. hand.visible = ( handPose !== null );
  16887. }
  16888. return this;
  16889. }
  16890. /**
  16891. * Returns a group representing the hand joint for the given input joint.
  16892. *
  16893. * @private
  16894. * @param {Group} hand - The group representing the hand space.
  16895. * @param {XRJointSpace} inputjoint - The hand joint data.
  16896. * @return {Group} A group representing the hand joint for the given input joint.
  16897. */
  16898. _getHandJoint( hand, inputjoint ) {
  16899. if ( hand.joints[ inputjoint.jointName ] === undefined ) {
  16900. const joint = new Group();
  16901. joint.matrixAutoUpdate = false;
  16902. joint.visible = false;
  16903. hand.joints[ inputjoint.jointName ] = joint;
  16904. hand.add( joint );
  16905. }
  16906. return hand.joints[ inputjoint.jointName ];
  16907. }
  16908. }
  16909. /**
  16910. * This class can be used to define an exponential squared fog,
  16911. * which gives a clear view near the camera and a faster than exponentially
  16912. * densening fog farther from the camera.
  16913. *
  16914. * ```js
  16915. * const scene = new THREE.Scene();
  16916. * scene.fog = new THREE.FogExp2( 0xcccccc, 0.002 );
  16917. * ```
  16918. */
  16919. class FogExp2 {
  16920. /**
  16921. * Constructs a new fog.
  16922. *
  16923. * @param {number|Color} color - The fog's color.
  16924. * @param {number} [density=0.00025] - Defines how fast the fog will grow dense.
  16925. */
  16926. constructor( color, density = 0.00025 ) {
  16927. /**
  16928. * This flag can be used for type testing.
  16929. *
  16930. * @type {boolean}
  16931. * @readonly
  16932. * @default true
  16933. */
  16934. this.isFogExp2 = true;
  16935. /**
  16936. * The name of the fog.
  16937. *
  16938. * @type {string}
  16939. */
  16940. this.name = '';
  16941. /**
  16942. * The fog's color.
  16943. *
  16944. * @type {Color}
  16945. */
  16946. this.color = new Color( color );
  16947. /**
  16948. * Defines how fast the fog will grow dense.
  16949. *
  16950. * @type {number}
  16951. * @default 0.00025
  16952. */
  16953. this.density = density;
  16954. }
  16955. /**
  16956. * Returns a new fog with copied values from this instance.
  16957. *
  16958. * @return {FogExp2} A clone of this instance.
  16959. */
  16960. clone() {
  16961. return new FogExp2( this.color, this.density );
  16962. }
  16963. /**
  16964. * Serializes the fog into JSON.
  16965. *
  16966. * @param {?(Object|string)} meta - An optional value holding meta information about the serialization.
  16967. * @return {Object} A JSON object representing the serialized fog
  16968. */
  16969. toJSON( /* meta */ ) {
  16970. return {
  16971. type: 'FogExp2',
  16972. name: this.name,
  16973. color: this.color.getHex(),
  16974. density: this.density
  16975. };
  16976. }
  16977. }
  16978. /**
  16979. * This class can be used to define a linear fog that grows linearly denser
  16980. * with the distance.
  16981. *
  16982. * ```js
  16983. * const scene = new THREE.Scene();
  16984. * scene.fog = new THREE.Fog( 0xcccccc, 10, 15 );
  16985. * ```
  16986. */
  16987. class Fog {
  16988. /**
  16989. * Constructs a new fog.
  16990. *
  16991. * @param {number|Color} color - The fog's color.
  16992. * @param {number} [near=1] - The minimum distance to start applying fog.
  16993. * @param {number} [far=1000] - The maximum distance at which fog stops being calculated and applied.
  16994. */
  16995. constructor( color, near = 1, far = 1000 ) {
  16996. /**
  16997. * This flag can be used for type testing.
  16998. *
  16999. * @type {boolean}
  17000. * @readonly
  17001. * @default true
  17002. */
  17003. this.isFog = true;
  17004. /**
  17005. * The name of the fog.
  17006. *
  17007. * @type {string}
  17008. */
  17009. this.name = '';
  17010. /**
  17011. * The fog's color.
  17012. *
  17013. * @type {Color}
  17014. */
  17015. this.color = new Color( color );
  17016. /**
  17017. * The minimum distance to start applying fog. Objects that are less than
  17018. * `near` units from the active camera won't be affected by fog.
  17019. *
  17020. * @type {number}
  17021. * @default 1
  17022. */
  17023. this.near = near;
  17024. /**
  17025. * The maximum distance at which fog stops being calculated and applied.
  17026. * Objects that are more than `far` units away from the active camera won't
  17027. * be affected by fog.
  17028. *
  17029. * @type {number}
  17030. * @default 1000
  17031. */
  17032. this.far = far;
  17033. }
  17034. /**
  17035. * Returns a new fog with copied values from this instance.
  17036. *
  17037. * @return {Fog} A clone of this instance.
  17038. */
  17039. clone() {
  17040. return new Fog( this.color, this.near, this.far );
  17041. }
  17042. /**
  17043. * Serializes the fog into JSON.
  17044. *
  17045. * @param {?(Object|string)} meta - An optional value holding meta information about the serialization.
  17046. * @return {Object} A JSON object representing the serialized fog
  17047. */
  17048. toJSON( /* meta */ ) {
  17049. return {
  17050. type: 'Fog',
  17051. name: this.name,
  17052. color: this.color.getHex(),
  17053. near: this.near,
  17054. far: this.far
  17055. };
  17056. }
  17057. }
  17058. /**
  17059. * Scenes allow you to set up what is to be rendered and where by three.js.
  17060. * This is where you place 3D objects like meshes, lines or lights.
  17061. *
  17062. * @augments Object3D
  17063. */
  17064. class Scene extends Object3D {
  17065. /**
  17066. * Constructs a new scene.
  17067. */
  17068. constructor() {
  17069. super();
  17070. /**
  17071. * This flag can be used for type testing.
  17072. *
  17073. * @type {boolean}
  17074. * @readonly
  17075. * @default true
  17076. */
  17077. this.isScene = true;
  17078. this.type = 'Scene';
  17079. /**
  17080. * Defines the background of the scene. Valid inputs are:
  17081. *
  17082. * - A color for defining a uniform colored background.
  17083. * - A texture for defining a (flat) textured background.
  17084. * - Cube textures or equirectangular textures for defining a skybox.
  17085. *
  17086. * @type {?(Color|Texture)}
  17087. * @default null
  17088. */
  17089. this.background = null;
  17090. /**
  17091. * Sets the environment map for all physical materials in the scene. However,
  17092. * it's not possible to overwrite an existing texture assigned to the `envMap`
  17093. * material property.
  17094. *
  17095. * @type {?Texture}
  17096. * @default null
  17097. */
  17098. this.environment = null;
  17099. /**
  17100. * A fog instance defining the type of fog that affects everything
  17101. * rendered in the scene.
  17102. *
  17103. * @type {?(Fog|FogExp2)}
  17104. * @default null
  17105. */
  17106. this.fog = null;
  17107. /**
  17108. * Sets the blurriness of the background. Only influences environment maps
  17109. * assigned to {@link Scene#background}. Valid input is a float between `0`
  17110. * and `1`.
  17111. *
  17112. * @type {number}
  17113. * @default 0
  17114. */
  17115. this.backgroundBlurriness = 0;
  17116. /**
  17117. * Attenuates the color of the background. Only applies to background textures.
  17118. *
  17119. * @type {number}
  17120. * @default 1
  17121. */
  17122. this.backgroundIntensity = 1;
  17123. /**
  17124. * The rotation of the background in radians. Only influences environment maps
  17125. * assigned to {@link Scene#background}.
  17126. *
  17127. * @type {Euler}
  17128. * @default (0,0,0)
  17129. */
  17130. this.backgroundRotation = new Euler();
  17131. /**
  17132. * Attenuates the color of the environment. Only influences environment maps
  17133. * assigned to {@link Scene#environment}.
  17134. *
  17135. * @type {number}
  17136. * @default 1
  17137. */
  17138. this.environmentIntensity = 1;
  17139. /**
  17140. * The rotation of the environment map in radians. Only influences physical materials
  17141. * in the scene when {@link Scene#environment} is used.
  17142. *
  17143. * @type {Euler}
  17144. * @default (0,0,0)
  17145. */
  17146. this.environmentRotation = new Euler();
  17147. /**
  17148. * Forces everything in the scene to be rendered with the defined material. It is possible
  17149. * to exclude materials from override by setting {@link Material#allowOverride} to `false`.
  17150. *
  17151. * @type {?Material}
  17152. * @default null
  17153. */
  17154. this.overrideMaterial = null;
  17155. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  17156. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'observe', { detail: this } ) );
  17157. }
  17158. }
  17159. copy( source, recursive ) {
  17160. super.copy( source, recursive );
  17161. if ( source.background !== null ) this.background = source.background.clone();
  17162. if ( source.environment !== null ) this.environment = source.environment.clone();
  17163. if ( source.fog !== null ) this.fog = source.fog.clone();
  17164. this.backgroundBlurriness = source.backgroundBlurriness;
  17165. this.backgroundIntensity = source.backgroundIntensity;
  17166. this.backgroundRotation.copy( source.backgroundRotation );
  17167. this.environmentIntensity = source.environmentIntensity;
  17168. this.environmentRotation.copy( source.environmentRotation );
  17169. if ( source.overrideMaterial !== null ) this.overrideMaterial = source.overrideMaterial.clone();
  17170. this.matrixAutoUpdate = source.matrixAutoUpdate;
  17171. return this;
  17172. }
  17173. toJSON( meta ) {
  17174. const data = super.toJSON( meta );
  17175. if ( this.fog !== null ) data.object.fog = this.fog.toJSON();
  17176. if ( this.backgroundBlurriness > 0 ) data.object.backgroundBlurriness = this.backgroundBlurriness;
  17177. if ( this.backgroundIntensity !== 1 ) data.object.backgroundIntensity = this.backgroundIntensity;
  17178. data.object.backgroundRotation = this.backgroundRotation.toArray();
  17179. if ( this.environmentIntensity !== 1 ) data.object.environmentIntensity = this.environmentIntensity;
  17180. data.object.environmentRotation = this.environmentRotation.toArray();
  17181. return data;
  17182. }
  17183. }
  17184. /**
  17185. * "Interleaved" means that multiple attributes, possibly of different types,
  17186. * (e.g., position, normal, uv, color) are packed into a single array buffer.
  17187. *
  17188. * An introduction into interleaved arrays can be found here: [Interleaved array basics]{@link https://blog.tojicode.com/2011/05/interleaved-array-basics.html}
  17189. */
  17190. class InterleavedBuffer {
  17191. /**
  17192. * Constructs a new interleaved buffer.
  17193. *
  17194. * @param {TypedArray} array - A typed array with a shared buffer storing attribute data.
  17195. * @param {number} stride - The number of typed-array elements per vertex.
  17196. */
  17197. constructor( array, stride ) {
  17198. /**
  17199. * This flag can be used for type testing.
  17200. *
  17201. * @type {boolean}
  17202. * @readonly
  17203. * @default true
  17204. */
  17205. this.isInterleavedBuffer = true;
  17206. /**
  17207. * A typed array with a shared buffer storing attribute data.
  17208. *
  17209. * @type {TypedArray}
  17210. */
  17211. this.array = array;
  17212. /**
  17213. * The number of typed-array elements per vertex.
  17214. *
  17215. * @type {number}
  17216. */
  17217. this.stride = stride;
  17218. /**
  17219. * The total number of elements in the array
  17220. *
  17221. * @type {number}
  17222. * @readonly
  17223. */
  17224. this.count = array !== undefined ? array.length / stride : 0;
  17225. /**
  17226. * Defines the intended usage pattern of the data store for optimization purposes.
  17227. *
  17228. * Note: After the initial use of a buffer, its usage cannot be changed. Instead,
  17229. * instantiate a new one and set the desired usage before the next render.
  17230. *
  17231. * @type {(StaticDrawUsage|DynamicDrawUsage|StreamDrawUsage|StaticReadUsage|DynamicReadUsage|StreamReadUsage|StaticCopyUsage|DynamicCopyUsage|StreamCopyUsage)}
  17232. * @default StaticDrawUsage
  17233. */
  17234. this.usage = StaticDrawUsage;
  17235. /**
  17236. * This can be used to only update some components of stored vectors (for example, just the
  17237. * component related to color). Use the `addUpdateRange()` function to add ranges to this array.
  17238. *
  17239. * @type {Array<Object>}
  17240. */
  17241. this.updateRanges = [];
  17242. /**
  17243. * A version number, incremented every time the `needsUpdate` is set to `true`.
  17244. *
  17245. * @type {number}
  17246. */
  17247. this.version = 0;
  17248. /**
  17249. * The UUID of the interleaved buffer.
  17250. *
  17251. * @type {string}
  17252. * @readonly
  17253. */
  17254. this.uuid = generateUUID();
  17255. }
  17256. /**
  17257. * A callback function that is executed after the renderer has transferred the attribute array
  17258. * data to the GPU.
  17259. */
  17260. onUploadCallback() {}
  17261. /**
  17262. * Flag to indicate that this attribute has changed and should be re-sent to
  17263. * the GPU. Set this to `true` when you modify the value of the array.
  17264. *
  17265. * @type {number}
  17266. * @default false
  17267. * @param {boolean} value
  17268. */
  17269. set needsUpdate( value ) {
  17270. if ( value === true ) this.version ++;
  17271. }
  17272. /**
  17273. * Sets the usage of this interleaved buffer.
  17274. *
  17275. * @param {(StaticDrawUsage|DynamicDrawUsage|StreamDrawUsage|StaticReadUsage|DynamicReadUsage|StreamReadUsage|StaticCopyUsage|DynamicCopyUsage|StreamCopyUsage)} value - The usage to set.
  17276. * @return {InterleavedBuffer} A reference to this interleaved buffer.
  17277. */
  17278. setUsage( value ) {
  17279. this.usage = value;
  17280. return this;
  17281. }
  17282. /**
  17283. * Adds a range of data in the data array to be updated on the GPU.
  17284. *
  17285. * @param {number} start - Position at which to start update.
  17286. * @param {number} count - The number of components to update.
  17287. */
  17288. addUpdateRange( start, count ) {
  17289. this.updateRanges.push( { start, count } );
  17290. }
  17291. /**
  17292. * Clears the update ranges.
  17293. */
  17294. clearUpdateRanges() {
  17295. this.updateRanges.length = 0;
  17296. }
  17297. /**
  17298. * Copies the values of the given interleaved buffer to this instance.
  17299. *
  17300. * @param {InterleavedBuffer} source - The interleaved buffer to copy.
  17301. * @return {InterleavedBuffer} A reference to this instance.
  17302. */
  17303. copy( source ) {
  17304. this.array = new source.array.constructor( source.array );
  17305. this.count = source.count;
  17306. this.stride = source.stride;
  17307. this.usage = source.usage;
  17308. return this;
  17309. }
  17310. /**
  17311. * Copies a vector from the given interleaved buffer to this one. The start
  17312. * and destination position in the attribute buffers are represented by the
  17313. * given indices.
  17314. *
  17315. * @param {number} index1 - The destination index into this interleaved buffer.
  17316. * @param {InterleavedBuffer} interleavedBuffer - The interleaved buffer to copy from.
  17317. * @param {number} index2 - The source index into the given interleaved buffer.
  17318. * @return {InterleavedBuffer} A reference to this instance.
  17319. */
  17320. copyAt( index1, interleavedBuffer, index2 ) {
  17321. index1 *= this.stride;
  17322. index2 *= interleavedBuffer.stride;
  17323. for ( let i = 0, l = this.stride; i < l; i ++ ) {
  17324. this.array[ index1 + i ] = interleavedBuffer.array[ index2 + i ];
  17325. }
  17326. return this;
  17327. }
  17328. /**
  17329. * Sets the given array data in the interleaved buffer.
  17330. *
  17331. * @param {(TypedArray|Array)} value - The array data to set.
  17332. * @param {number} [offset=0] - The offset in this interleaved buffer's array.
  17333. * @return {InterleavedBuffer} A reference to this instance.
  17334. */
  17335. set( value, offset = 0 ) {
  17336. this.array.set( value, offset );
  17337. return this;
  17338. }
  17339. /**
  17340. * Returns a new interleaved buffer with copied values from this instance.
  17341. *
  17342. * @param {Object} [data] - An object with shared array buffers that allows to retain shared structures.
  17343. * @return {InterleavedBuffer} A clone of this instance.
  17344. */
  17345. clone( data ) {
  17346. if ( data.arrayBuffers === undefined ) {
  17347. data.arrayBuffers = {};
  17348. }
  17349. if ( this.array.buffer._uuid === undefined ) {
  17350. this.array.buffer._uuid = generateUUID();
  17351. }
  17352. if ( data.arrayBuffers[ this.array.buffer._uuid ] === undefined ) {
  17353. data.arrayBuffers[ this.array.buffer._uuid ] = this.array.slice( 0 ).buffer;
  17354. }
  17355. const array = new this.array.constructor( data.arrayBuffers[ this.array.buffer._uuid ] );
  17356. const ib = new this.constructor( array, this.stride );
  17357. ib.setUsage( this.usage );
  17358. return ib;
  17359. }
  17360. /**
  17361. * Sets the given callback function that is executed after the Renderer has transferred
  17362. * the array data to the GPU. Can be used to perform clean-up operations after
  17363. * the upload when data are not needed anymore on the CPU side.
  17364. *
  17365. * @param {Function} callback - The `onUpload()` callback.
  17366. * @return {InterleavedBuffer} A reference to this instance.
  17367. */
  17368. onUpload( callback ) {
  17369. this.onUploadCallback = callback;
  17370. return this;
  17371. }
  17372. /**
  17373. * Serializes the interleaved buffer into JSON.
  17374. *
  17375. * @param {Object} [data] - An optional value holding meta information about the serialization.
  17376. * @return {Object} A JSON object representing the serialized interleaved buffer.
  17377. */
  17378. toJSON( data ) {
  17379. if ( data.arrayBuffers === undefined ) {
  17380. data.arrayBuffers = {};
  17381. }
  17382. // generate UUID for array buffer if necessary
  17383. if ( this.array.buffer._uuid === undefined ) {
  17384. this.array.buffer._uuid = generateUUID();
  17385. }
  17386. if ( data.arrayBuffers[ this.array.buffer._uuid ] === undefined ) {
  17387. data.arrayBuffers[ this.array.buffer._uuid ] = Array.from( new Uint32Array( this.array.buffer ) );
  17388. }
  17389. //
  17390. return {
  17391. uuid: this.uuid,
  17392. buffer: this.array.buffer._uuid,
  17393. type: this.array.constructor.name,
  17394. stride: this.stride
  17395. };
  17396. }
  17397. }
  17398. const _vector$7 = /*@__PURE__*/ new Vector3();
  17399. /**
  17400. * An alternative version of a buffer attribute with interleaved data. Interleaved
  17401. * attributes share a common interleaved data storage ({@link InterleavedBuffer}) and refer with
  17402. * different offsets into the buffer.
  17403. */
  17404. class InterleavedBufferAttribute {
  17405. /**
  17406. * Constructs a new interleaved buffer attribute.
  17407. *
  17408. * @param {InterleavedBuffer} interleavedBuffer - The buffer holding the interleaved data.
  17409. * @param {number} itemSize - The item size.
  17410. * @param {number} offset - The attribute offset into the buffer.
  17411. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  17412. */
  17413. constructor( interleavedBuffer, itemSize, offset, normalized = false ) {
  17414. /**
  17415. * This flag can be used for type testing.
  17416. *
  17417. * @type {boolean}
  17418. * @readonly
  17419. * @default true
  17420. */
  17421. this.isInterleavedBufferAttribute = true;
  17422. /**
  17423. * The name of the buffer attribute.
  17424. *
  17425. * @type {string}
  17426. */
  17427. this.name = '';
  17428. /**
  17429. * The buffer holding the interleaved data.
  17430. *
  17431. * @type {InterleavedBuffer}
  17432. */
  17433. this.data = interleavedBuffer;
  17434. /**
  17435. * The item size, see {@link BufferAttribute#itemSize}.
  17436. *
  17437. * @type {number}
  17438. */
  17439. this.itemSize = itemSize;
  17440. /**
  17441. * The attribute offset into the buffer.
  17442. *
  17443. * @type {number}
  17444. */
  17445. this.offset = offset;
  17446. /**
  17447. * Whether the data are normalized or not, see {@link BufferAttribute#normalized}
  17448. *
  17449. * @type {InterleavedBuffer}
  17450. */
  17451. this.normalized = normalized;
  17452. }
  17453. /**
  17454. * The item count of this buffer attribute.
  17455. *
  17456. * @type {number}
  17457. * @readonly
  17458. */
  17459. get count() {
  17460. return this.data.count;
  17461. }
  17462. /**
  17463. * The array holding the interleaved buffer attribute data.
  17464. *
  17465. * @type {TypedArray}
  17466. */
  17467. get array() {
  17468. return this.data.array;
  17469. }
  17470. /**
  17471. * Flag to indicate that this attribute has changed and should be re-sent to
  17472. * the GPU. Set this to `true` when you modify the value of the array.
  17473. *
  17474. * @type {number}
  17475. * @default false
  17476. * @param {boolean} value
  17477. */
  17478. set needsUpdate( value ) {
  17479. this.data.needsUpdate = value;
  17480. }
  17481. /**
  17482. * Applies the given 4x4 matrix to the given attribute. Only works with
  17483. * item size `3`.
  17484. *
  17485. * @param {Matrix4} m - The matrix to apply.
  17486. * @return {InterleavedBufferAttribute} A reference to this instance.
  17487. */
  17488. applyMatrix4( m ) {
  17489. for ( let i = 0, l = this.data.count; i < l; i ++ ) {
  17490. _vector$7.fromBufferAttribute( this, i );
  17491. _vector$7.applyMatrix4( m );
  17492. this.setXYZ( i, _vector$7.x, _vector$7.y, _vector$7.z );
  17493. }
  17494. return this;
  17495. }
  17496. /**
  17497. * Applies the given 3x3 normal matrix to the given attribute. Only works with
  17498. * item size `3`.
  17499. *
  17500. * @param {Matrix3} m - The normal matrix to apply.
  17501. * @return {InterleavedBufferAttribute} A reference to this instance.
  17502. */
  17503. applyNormalMatrix( m ) {
  17504. for ( let i = 0, l = this.count; i < l; i ++ ) {
  17505. _vector$7.fromBufferAttribute( this, i );
  17506. _vector$7.applyNormalMatrix( m );
  17507. this.setXYZ( i, _vector$7.x, _vector$7.y, _vector$7.z );
  17508. }
  17509. return this;
  17510. }
  17511. /**
  17512. * Applies the given 4x4 matrix to the given attribute. Only works with
  17513. * item size `3` and with direction vectors.
  17514. *
  17515. * @param {Matrix4} m - The matrix to apply.
  17516. * @return {InterleavedBufferAttribute} A reference to this instance.
  17517. */
  17518. transformDirection( m ) {
  17519. for ( let i = 0, l = this.count; i < l; i ++ ) {
  17520. _vector$7.fromBufferAttribute( this, i );
  17521. _vector$7.transformDirection( m );
  17522. this.setXYZ( i, _vector$7.x, _vector$7.y, _vector$7.z );
  17523. }
  17524. return this;
  17525. }
  17526. /**
  17527. * Returns the given component of the vector at the given index.
  17528. *
  17529. * @param {number} index - The index into the buffer attribute.
  17530. * @param {number} component - The component index.
  17531. * @return {number} The returned value.
  17532. */
  17533. getComponent( index, component ) {
  17534. let value = this.array[ index * this.data.stride + this.offset + component ];
  17535. if ( this.normalized ) value = denormalize( value, this.array );
  17536. return value;
  17537. }
  17538. /**
  17539. * Sets the given value to the given component of the vector at the given index.
  17540. *
  17541. * @param {number} index - The index into the buffer attribute.
  17542. * @param {number} component - The component index.
  17543. * @param {number} value - The value to set.
  17544. * @return {InterleavedBufferAttribute} A reference to this instance.
  17545. */
  17546. setComponent( index, component, value ) {
  17547. if ( this.normalized ) value = normalize( value, this.array );
  17548. this.data.array[ index * this.data.stride + this.offset + component ] = value;
  17549. return this;
  17550. }
  17551. /**
  17552. * Sets the x component of the vector at the given index.
  17553. *
  17554. * @param {number} index - The index into the buffer attribute.
  17555. * @param {number} x - The value to set.
  17556. * @return {InterleavedBufferAttribute} A reference to this instance.
  17557. */
  17558. setX( index, x ) {
  17559. if ( this.normalized ) x = normalize( x, this.array );
  17560. this.data.array[ index * this.data.stride + this.offset ] = x;
  17561. return this;
  17562. }
  17563. /**
  17564. * Sets the y component of the vector at the given index.
  17565. *
  17566. * @param {number} index - The index into the buffer attribute.
  17567. * @param {number} y - The value to set.
  17568. * @return {InterleavedBufferAttribute} A reference to this instance.
  17569. */
  17570. setY( index, y ) {
  17571. if ( this.normalized ) y = normalize( y, this.array );
  17572. this.data.array[ index * this.data.stride + this.offset + 1 ] = y;
  17573. return this;
  17574. }
  17575. /**
  17576. * Sets the z component of the vector at the given index.
  17577. *
  17578. * @param {number} index - The index into the buffer attribute.
  17579. * @param {number} z - The value to set.
  17580. * @return {InterleavedBufferAttribute} A reference to this instance.
  17581. */
  17582. setZ( index, z ) {
  17583. if ( this.normalized ) z = normalize( z, this.array );
  17584. this.data.array[ index * this.data.stride + this.offset + 2 ] = z;
  17585. return this;
  17586. }
  17587. /**
  17588. * Sets the w component of the vector at the given index.
  17589. *
  17590. * @param {number} index - The index into the buffer attribute.
  17591. * @param {number} w - The value to set.
  17592. * @return {InterleavedBufferAttribute} A reference to this instance.
  17593. */
  17594. setW( index, w ) {
  17595. if ( this.normalized ) w = normalize( w, this.array );
  17596. this.data.array[ index * this.data.stride + this.offset + 3 ] = w;
  17597. return this;
  17598. }
  17599. /**
  17600. * Returns the x component of the vector at the given index.
  17601. *
  17602. * @param {number} index - The index into the buffer attribute.
  17603. * @return {number} The x component.
  17604. */
  17605. getX( index ) {
  17606. let x = this.data.array[ index * this.data.stride + this.offset ];
  17607. if ( this.normalized ) x = denormalize( x, this.array );
  17608. return x;
  17609. }
  17610. /**
  17611. * Returns the y component of the vector at the given index.
  17612. *
  17613. * @param {number} index - The index into the buffer attribute.
  17614. * @return {number} The y component.
  17615. */
  17616. getY( index ) {
  17617. let y = this.data.array[ index * this.data.stride + this.offset + 1 ];
  17618. if ( this.normalized ) y = denormalize( y, this.array );
  17619. return y;
  17620. }
  17621. /**
  17622. * Returns the z component of the vector at the given index.
  17623. *
  17624. * @param {number} index - The index into the buffer attribute.
  17625. * @return {number} The z component.
  17626. */
  17627. getZ( index ) {
  17628. let z = this.data.array[ index * this.data.stride + this.offset + 2 ];
  17629. if ( this.normalized ) z = denormalize( z, this.array );
  17630. return z;
  17631. }
  17632. /**
  17633. * Returns the w component of the vector at the given index.
  17634. *
  17635. * @param {number} index - The index into the buffer attribute.
  17636. * @return {number} The w component.
  17637. */
  17638. getW( index ) {
  17639. let w = this.data.array[ index * this.data.stride + this.offset + 3 ];
  17640. if ( this.normalized ) w = denormalize( w, this.array );
  17641. return w;
  17642. }
  17643. /**
  17644. * Sets the x and y component of the vector at the given index.
  17645. *
  17646. * @param {number} index - The index into the buffer attribute.
  17647. * @param {number} x - The value for the x component to set.
  17648. * @param {number} y - The value for the y component to set.
  17649. * @return {InterleavedBufferAttribute} A reference to this instance.
  17650. */
  17651. setXY( index, x, y ) {
  17652. index = index * this.data.stride + this.offset;
  17653. if ( this.normalized ) {
  17654. x = normalize( x, this.array );
  17655. y = normalize( y, this.array );
  17656. }
  17657. this.data.array[ index + 0 ] = x;
  17658. this.data.array[ index + 1 ] = y;
  17659. return this;
  17660. }
  17661. /**
  17662. * Sets the x, y and z component of the vector at the given index.
  17663. *
  17664. * @param {number} index - The index into the buffer attribute.
  17665. * @param {number} x - The value for the x component to set.
  17666. * @param {number} y - The value for the y component to set.
  17667. * @param {number} z - The value for the z component to set.
  17668. * @return {InterleavedBufferAttribute} A reference to this instance.
  17669. */
  17670. setXYZ( index, x, y, z ) {
  17671. index = index * this.data.stride + this.offset;
  17672. if ( this.normalized ) {
  17673. x = normalize( x, this.array );
  17674. y = normalize( y, this.array );
  17675. z = normalize( z, this.array );
  17676. }
  17677. this.data.array[ index + 0 ] = x;
  17678. this.data.array[ index + 1 ] = y;
  17679. this.data.array[ index + 2 ] = z;
  17680. return this;
  17681. }
  17682. /**
  17683. * Sets the x, y, z and w component of the vector at the given index.
  17684. *
  17685. * @param {number} index - The index into the buffer attribute.
  17686. * @param {number} x - The value for the x component to set.
  17687. * @param {number} y - The value for the y component to set.
  17688. * @param {number} z - The value for the z component to set.
  17689. * @param {number} w - The value for the w component to set.
  17690. * @return {InterleavedBufferAttribute} A reference to this instance.
  17691. */
  17692. setXYZW( index, x, y, z, w ) {
  17693. index = index * this.data.stride + this.offset;
  17694. if ( this.normalized ) {
  17695. x = normalize( x, this.array );
  17696. y = normalize( y, this.array );
  17697. z = normalize( z, this.array );
  17698. w = normalize( w, this.array );
  17699. }
  17700. this.data.array[ index + 0 ] = x;
  17701. this.data.array[ index + 1 ] = y;
  17702. this.data.array[ index + 2 ] = z;
  17703. this.data.array[ index + 3 ] = w;
  17704. return this;
  17705. }
  17706. /**
  17707. * Returns a new buffer attribute with copied values from this instance.
  17708. *
  17709. * If no parameter is provided, cloning an interleaved buffer attribute will de-interleave buffer data.
  17710. *
  17711. * @param {Object} [data] - An object with interleaved buffers that allows to retain the interleaved property.
  17712. * @return {BufferAttribute|InterleavedBufferAttribute} A clone of this instance.
  17713. */
  17714. clone( data ) {
  17715. if ( data === undefined ) {
  17716. console.log( 'THREE.InterleavedBufferAttribute.clone(): Cloning an interleaved buffer attribute will de-interleave buffer data.' );
  17717. const array = [];
  17718. for ( let i = 0; i < this.count; i ++ ) {
  17719. const index = i * this.data.stride + this.offset;
  17720. for ( let j = 0; j < this.itemSize; j ++ ) {
  17721. array.push( this.data.array[ index + j ] );
  17722. }
  17723. }
  17724. return new BufferAttribute( new this.array.constructor( array ), this.itemSize, this.normalized );
  17725. } else {
  17726. if ( data.interleavedBuffers === undefined ) {
  17727. data.interleavedBuffers = {};
  17728. }
  17729. if ( data.interleavedBuffers[ this.data.uuid ] === undefined ) {
  17730. data.interleavedBuffers[ this.data.uuid ] = this.data.clone( data );
  17731. }
  17732. return new InterleavedBufferAttribute( data.interleavedBuffers[ this.data.uuid ], this.itemSize, this.offset, this.normalized );
  17733. }
  17734. }
  17735. /**
  17736. * Serializes the buffer attribute into JSON.
  17737. *
  17738. * If no parameter is provided, cloning an interleaved buffer attribute will de-interleave buffer data.
  17739. *
  17740. * @param {Object} [data] - An optional value holding meta information about the serialization.
  17741. * @return {Object} A JSON object representing the serialized buffer attribute.
  17742. */
  17743. toJSON( data ) {
  17744. if ( data === undefined ) {
  17745. console.log( 'THREE.InterleavedBufferAttribute.toJSON(): Serializing an interleaved buffer attribute will de-interleave buffer data.' );
  17746. const array = [];
  17747. for ( let i = 0; i < this.count; i ++ ) {
  17748. const index = i * this.data.stride + this.offset;
  17749. for ( let j = 0; j < this.itemSize; j ++ ) {
  17750. array.push( this.data.array[ index + j ] );
  17751. }
  17752. }
  17753. // de-interleave data and save it as an ordinary buffer attribute for now
  17754. return {
  17755. itemSize: this.itemSize,
  17756. type: this.array.constructor.name,
  17757. array: array,
  17758. normalized: this.normalized
  17759. };
  17760. } else {
  17761. // save as true interleaved attribute
  17762. if ( data.interleavedBuffers === undefined ) {
  17763. data.interleavedBuffers = {};
  17764. }
  17765. if ( data.interleavedBuffers[ this.data.uuid ] === undefined ) {
  17766. data.interleavedBuffers[ this.data.uuid ] = this.data.toJSON( data );
  17767. }
  17768. return {
  17769. isInterleavedBufferAttribute: true,
  17770. itemSize: this.itemSize,
  17771. data: this.data.uuid,
  17772. offset: this.offset,
  17773. normalized: this.normalized
  17774. };
  17775. }
  17776. }
  17777. }
  17778. /**
  17779. * A material for rendering instances of {@link Sprite}.
  17780. *
  17781. * ```js
  17782. * const map = new THREE.TextureLoader().load( 'textures/sprite.png' );
  17783. * const material = new THREE.SpriteMaterial( { map: map, color: 0xffffff } );
  17784. *
  17785. * const sprite = new THREE.Sprite( material );
  17786. * sprite.scale.set(200, 200, 1)
  17787. * scene.add( sprite );
  17788. * ```
  17789. *
  17790. * @augments Material
  17791. */
  17792. class SpriteMaterial extends Material {
  17793. /**
  17794. * Constructs a new sprite material.
  17795. *
  17796. * @param {Object} [parameters] - An object with one or more properties
  17797. * defining the material's appearance. Any property of the material
  17798. * (including any property from inherited materials) can be passed
  17799. * in here. Color values can be passed any type of value accepted
  17800. * by {@link Color#set}.
  17801. */
  17802. constructor( parameters ) {
  17803. super();
  17804. /**
  17805. * This flag can be used for type testing.
  17806. *
  17807. * @type {boolean}
  17808. * @readonly
  17809. * @default true
  17810. */
  17811. this.isSpriteMaterial = true;
  17812. this.type = 'SpriteMaterial';
  17813. /**
  17814. * Color of the material.
  17815. *
  17816. * @type {Color}
  17817. * @default (1,1,1)
  17818. */
  17819. this.color = new Color( 0xffffff );
  17820. /**
  17821. * The color map. May optionally include an alpha channel, typically combined
  17822. * with {@link Material#transparent} or {@link Material#alphaTest}. The texture map
  17823. * color is modulated by the diffuse `color`.
  17824. *
  17825. * @type {?Texture}
  17826. * @default null
  17827. */
  17828. this.map = null;
  17829. /**
  17830. * The alpha map is a grayscale texture that controls the opacity across the
  17831. * surface (black: fully transparent; white: fully opaque).
  17832. *
  17833. * Only the color of the texture is used, ignoring the alpha channel if one
  17834. * exists. For RGB and RGBA textures, the renderer will use the green channel
  17835. * when sampling this texture due to the extra bit of precision provided for
  17836. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  17837. * luminance/alpha textures will also still work as expected.
  17838. *
  17839. * @type {?Texture}
  17840. * @default null
  17841. */
  17842. this.alphaMap = null;
  17843. /**
  17844. * The rotation of the sprite in radians.
  17845. *
  17846. * @type {number}
  17847. * @default 0
  17848. */
  17849. this.rotation = 0;
  17850. /**
  17851. * Specifies whether size of the sprite is attenuated by the camera depth (perspective camera only).
  17852. *
  17853. * @type {boolean}
  17854. * @default true
  17855. */
  17856. this.sizeAttenuation = true;
  17857. /**
  17858. * Overwritten since sprite materials are transparent
  17859. * by default.
  17860. *
  17861. * @type {boolean}
  17862. * @default true
  17863. */
  17864. this.transparent = true;
  17865. /**
  17866. * Whether the material is affected by fog or not.
  17867. *
  17868. * @type {boolean}
  17869. * @default true
  17870. */
  17871. this.fog = true;
  17872. this.setValues( parameters );
  17873. }
  17874. copy( source ) {
  17875. super.copy( source );
  17876. this.color.copy( source.color );
  17877. this.map = source.map;
  17878. this.alphaMap = source.alphaMap;
  17879. this.rotation = source.rotation;
  17880. this.sizeAttenuation = source.sizeAttenuation;
  17881. this.fog = source.fog;
  17882. return this;
  17883. }
  17884. }
  17885. let _geometry;
  17886. const _intersectPoint = /*@__PURE__*/ new Vector3();
  17887. const _worldScale = /*@__PURE__*/ new Vector3();
  17888. const _mvPosition = /*@__PURE__*/ new Vector3();
  17889. const _alignedPosition = /*@__PURE__*/ new Vector2();
  17890. const _rotatedPosition = /*@__PURE__*/ new Vector2();
  17891. const _viewWorldMatrix = /*@__PURE__*/ new Matrix4();
  17892. const _vA = /*@__PURE__*/ new Vector3();
  17893. const _vB = /*@__PURE__*/ new Vector3();
  17894. const _vC = /*@__PURE__*/ new Vector3();
  17895. const _uvA = /*@__PURE__*/ new Vector2();
  17896. const _uvB = /*@__PURE__*/ new Vector2();
  17897. const _uvC = /*@__PURE__*/ new Vector2();
  17898. /**
  17899. * A sprite is a plane that always faces towards the camera, generally with a
  17900. * partially transparent texture applied.
  17901. *
  17902. * Sprites do not cast shadows, setting {@link Object3D#castShadow} to `true` will
  17903. * have no effect.
  17904. *
  17905. * ```js
  17906. * const map = new THREE.TextureLoader().load( 'sprite.png' );
  17907. * const material = new THREE.SpriteMaterial( { map: map } );
  17908. *
  17909. * const sprite = new THREE.Sprite( material );
  17910. * scene.add( sprite );
  17911. * ```
  17912. *
  17913. * @augments Object3D
  17914. */
  17915. class Sprite extends Object3D {
  17916. /**
  17917. * Constructs a new sprite.
  17918. *
  17919. * @param {SpriteMaterial} [material] - The sprite material.
  17920. */
  17921. constructor( material = new SpriteMaterial() ) {
  17922. super();
  17923. /**
  17924. * This flag can be used for type testing.
  17925. *
  17926. * @type {boolean}
  17927. * @readonly
  17928. * @default true
  17929. */
  17930. this.isSprite = true;
  17931. this.type = 'Sprite';
  17932. if ( _geometry === undefined ) {
  17933. _geometry = new BufferGeometry();
  17934. const float32Array = new Float32Array( [
  17935. -0.5, -0.5, 0, 0, 0,
  17936. 0.5, -0.5, 0, 1, 0,
  17937. 0.5, 0.5, 0, 1, 1,
  17938. -0.5, 0.5, 0, 0, 1
  17939. ] );
  17940. const interleavedBuffer = new InterleavedBuffer( float32Array, 5 );
  17941. _geometry.setIndex( [ 0, 1, 2, 0, 2, 3 ] );
  17942. _geometry.setAttribute( 'position', new InterleavedBufferAttribute( interleavedBuffer, 3, 0, false ) );
  17943. _geometry.setAttribute( 'uv', new InterleavedBufferAttribute( interleavedBuffer, 2, 3, false ) );
  17944. }
  17945. /**
  17946. * The sprite geometry.
  17947. *
  17948. * @type {BufferGeometry}
  17949. */
  17950. this.geometry = _geometry;
  17951. /**
  17952. * The sprite material.
  17953. *
  17954. * @type {SpriteMaterial}
  17955. */
  17956. this.material = material;
  17957. /**
  17958. * The sprite's anchor point, and the point around which the sprite rotates.
  17959. * A value of `(0.5, 0.5)` corresponds to the midpoint of the sprite. A value
  17960. * of `(0, 0)` corresponds to the lower left corner of the sprite.
  17961. *
  17962. * @type {Vector2}
  17963. * @default (0.5,0.5)
  17964. */
  17965. this.center = new Vector2( 0.5, 0.5 );
  17966. /**
  17967. * The number of instances of this sprite.
  17968. * Can only be used with {@link WebGPURenderer}.
  17969. *
  17970. * @type {number}
  17971. * @default 1
  17972. */
  17973. this.count = 1;
  17974. }
  17975. /**
  17976. * Computes intersection points between a casted ray and this sprite.
  17977. *
  17978. * @param {Raycaster} raycaster - The raycaster.
  17979. * @param {Array<Object>} intersects - The target array that holds the intersection points.
  17980. */
  17981. raycast( raycaster, intersects ) {
  17982. if ( raycaster.camera === null ) {
  17983. console.error( 'THREE.Sprite: "Raycaster.camera" needs to be set in order to raycast against sprites.' );
  17984. }
  17985. _worldScale.setFromMatrixScale( this.matrixWorld );
  17986. _viewWorldMatrix.copy( raycaster.camera.matrixWorld );
  17987. this.modelViewMatrix.multiplyMatrices( raycaster.camera.matrixWorldInverse, this.matrixWorld );
  17988. _mvPosition.setFromMatrixPosition( this.modelViewMatrix );
  17989. if ( raycaster.camera.isPerspectiveCamera && this.material.sizeAttenuation === false ) {
  17990. _worldScale.multiplyScalar( - _mvPosition.z );
  17991. }
  17992. const rotation = this.material.rotation;
  17993. let sin, cos;
  17994. if ( rotation !== 0 ) {
  17995. cos = Math.cos( rotation );
  17996. sin = Math.sin( rotation );
  17997. }
  17998. const center = this.center;
  17999. transformVertex( _vA.set( -0.5, -0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  18000. transformVertex( _vB.set( 0.5, -0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  18001. transformVertex( _vC.set( 0.5, 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  18002. _uvA.set( 0, 0 );
  18003. _uvB.set( 1, 0 );
  18004. _uvC.set( 1, 1 );
  18005. // check first triangle
  18006. let intersect = raycaster.ray.intersectTriangle( _vA, _vB, _vC, false, _intersectPoint );
  18007. if ( intersect === null ) {
  18008. // check second triangle
  18009. transformVertex( _vB.set( -0.5, 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  18010. _uvB.set( 0, 1 );
  18011. intersect = raycaster.ray.intersectTriangle( _vA, _vC, _vB, false, _intersectPoint );
  18012. if ( intersect === null ) {
  18013. return;
  18014. }
  18015. }
  18016. const distance = raycaster.ray.origin.distanceTo( _intersectPoint );
  18017. if ( distance < raycaster.near || distance > raycaster.far ) return;
  18018. intersects.push( {
  18019. distance: distance,
  18020. point: _intersectPoint.clone(),
  18021. uv: Triangle.getInterpolation( _intersectPoint, _vA, _vB, _vC, _uvA, _uvB, _uvC, new Vector2() ),
  18022. face: null,
  18023. object: this
  18024. } );
  18025. }
  18026. copy( source, recursive ) {
  18027. super.copy( source, recursive );
  18028. if ( source.center !== undefined ) this.center.copy( source.center );
  18029. this.material = source.material;
  18030. return this;
  18031. }
  18032. }
  18033. function transformVertex( vertexPosition, mvPosition, center, scale, sin, cos ) {
  18034. // compute position in camera space
  18035. _alignedPosition.subVectors( vertexPosition, center ).addScalar( 0.5 ).multiply( scale );
  18036. // to check if rotation is not zero
  18037. if ( sin !== undefined ) {
  18038. _rotatedPosition.x = ( cos * _alignedPosition.x ) - ( sin * _alignedPosition.y );
  18039. _rotatedPosition.y = ( sin * _alignedPosition.x ) + ( cos * _alignedPosition.y );
  18040. } else {
  18041. _rotatedPosition.copy( _alignedPosition );
  18042. }
  18043. vertexPosition.copy( mvPosition );
  18044. vertexPosition.x += _rotatedPosition.x;
  18045. vertexPosition.y += _rotatedPosition.y;
  18046. // transform to world space
  18047. vertexPosition.applyMatrix4( _viewWorldMatrix );
  18048. }
  18049. const _v1$2 = /*@__PURE__*/ new Vector3();
  18050. const _v2$1 = /*@__PURE__*/ new Vector3();
  18051. /**
  18052. * A component for providing a basic Level of Detail (LOD) mechanism.
  18053. *
  18054. * Every LOD level is associated with an object, and rendering can be switched
  18055. * between them at the distances specified. Typically you would create, say,
  18056. * three meshes, one for far away (low detail), one for mid range (medium
  18057. * detail) and one for close up (high detail).
  18058. *
  18059. * ```js
  18060. * const lod = new THREE.LOD();
  18061. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  18062. *
  18063. * //Create spheres with 3 levels of detail and create new LOD levels for them
  18064. * for( let i = 0; i < 3; i++ ) {
  18065. *
  18066. * const geometry = new THREE.IcosahedronGeometry( 10, 3 - i );
  18067. * const mesh = new THREE.Mesh( geometry, material );
  18068. * lod.addLevel( mesh, i * 75 );
  18069. *
  18070. * }
  18071. *
  18072. * scene.add( lod );
  18073. * ```
  18074. *
  18075. * @augments Object3D
  18076. */
  18077. class LOD extends Object3D {
  18078. /**
  18079. * Constructs a new LOD.
  18080. */
  18081. constructor() {
  18082. super();
  18083. /**
  18084. * This flag can be used for type testing.
  18085. *
  18086. * @type {boolean}
  18087. * @readonly
  18088. * @default true
  18089. */
  18090. this.isLOD = true;
  18091. /**
  18092. * The current LOD index.
  18093. *
  18094. * @private
  18095. * @type {number}
  18096. * @default 0
  18097. */
  18098. this._currentLevel = 0;
  18099. this.type = 'LOD';
  18100. Object.defineProperties( this, {
  18101. /**
  18102. * This array holds the LOD levels.
  18103. *
  18104. * @name LOD#levels
  18105. * @type {Array<{object:Object3D,distance:number,hysteresis:number}>}
  18106. */
  18107. levels: {
  18108. enumerable: true,
  18109. value: []
  18110. }
  18111. } );
  18112. /**
  18113. * Whether the LOD object is updated automatically by the renderer per frame
  18114. * or not. If set to `false`, you have to call {@link LOD#update} in the
  18115. * render loop by yourself.
  18116. *
  18117. * @type {boolean}
  18118. * @default true
  18119. */
  18120. this.autoUpdate = true;
  18121. }
  18122. copy( source ) {
  18123. super.copy( source, false );
  18124. const levels = source.levels;
  18125. for ( let i = 0, l = levels.length; i < l; i ++ ) {
  18126. const level = levels[ i ];
  18127. this.addLevel( level.object.clone(), level.distance, level.hysteresis );
  18128. }
  18129. this.autoUpdate = source.autoUpdate;
  18130. return this;
  18131. }
  18132. /**
  18133. * Adds a mesh that will display at a certain distance and greater. Typically
  18134. * the further away the distance, the lower the detail on the mesh.
  18135. *
  18136. * @param {Object3D} object - The 3D object to display at this level.
  18137. * @param {number} [distance=0] - The distance at which to display this level of detail.
  18138. * @param {number} [hysteresis=0] - Threshold used to avoid flickering at LOD boundaries, as a fraction of distance.
  18139. * @return {LOD} A reference to this instance.
  18140. */
  18141. addLevel( object, distance = 0, hysteresis = 0 ) {
  18142. distance = Math.abs( distance );
  18143. const levels = this.levels;
  18144. let l;
  18145. for ( l = 0; l < levels.length; l ++ ) {
  18146. if ( distance < levels[ l ].distance ) {
  18147. break;
  18148. }
  18149. }
  18150. levels.splice( l, 0, { distance: distance, hysteresis: hysteresis, object: object } );
  18151. this.add( object );
  18152. return this;
  18153. }
  18154. /**
  18155. * Removes an existing level, based on the distance from the camera.
  18156. * Returns `true` when the level has been removed. Otherwise `false`.
  18157. *
  18158. * @param {number} distance - Distance of the level to remove.
  18159. * @return {boolean} Whether the level has been removed or not.
  18160. */
  18161. removeLevel( distance ) {
  18162. const levels = this.levels;
  18163. for ( let i = 0; i < levels.length; i ++ ) {
  18164. if ( levels[ i ].distance === distance ) {
  18165. const removedElements = levels.splice( i, 1 );
  18166. this.remove( removedElements[ 0 ].object );
  18167. return true;
  18168. }
  18169. }
  18170. return false;
  18171. }
  18172. /**
  18173. * Returns the currently active LOD level index.
  18174. *
  18175. * @return {number} The current active LOD level index.
  18176. */
  18177. getCurrentLevel() {
  18178. return this._currentLevel;
  18179. }
  18180. /**
  18181. * Returns a reference to the first 3D object that is greater than
  18182. * the given distance.
  18183. *
  18184. * @param {number} distance - The LOD distance.
  18185. * @return {Object3D|null} The found 3D object. `null` if no 3D object has been found.
  18186. */
  18187. getObjectForDistance( distance ) {
  18188. const levels = this.levels;
  18189. if ( levels.length > 0 ) {
  18190. let i, l;
  18191. for ( i = 1, l = levels.length; i < l; i ++ ) {
  18192. let levelDistance = levels[ i ].distance;
  18193. if ( levels[ i ].object.visible ) {
  18194. levelDistance -= levelDistance * levels[ i ].hysteresis;
  18195. }
  18196. if ( distance < levelDistance ) {
  18197. break;
  18198. }
  18199. }
  18200. return levels[ i - 1 ].object;
  18201. }
  18202. return null;
  18203. }
  18204. /**
  18205. * Computes intersection points between a casted ray and this LOD.
  18206. *
  18207. * @param {Raycaster} raycaster - The raycaster.
  18208. * @param {Array<Object>} intersects - The target array that holds the intersection points.
  18209. */
  18210. raycast( raycaster, intersects ) {
  18211. const levels = this.levels;
  18212. if ( levels.length > 0 ) {
  18213. _v1$2.setFromMatrixPosition( this.matrixWorld );
  18214. const distance = raycaster.ray.origin.distanceTo( _v1$2 );
  18215. this.getObjectForDistance( distance ).raycast( raycaster, intersects );
  18216. }
  18217. }
  18218. /**
  18219. * Updates the LOD by computing which LOD level should be visible according
  18220. * to the current distance of the given camera.
  18221. *
  18222. * @param {Camera} camera - The camera the scene is rendered with.
  18223. */
  18224. update( camera ) {
  18225. const levels = this.levels;
  18226. if ( levels.length > 1 ) {
  18227. _v1$2.setFromMatrixPosition( camera.matrixWorld );
  18228. _v2$1.setFromMatrixPosition( this.matrixWorld );
  18229. const distance = _v1$2.distanceTo( _v2$1 ) / camera.zoom;
  18230. levels[ 0 ].object.visible = true;
  18231. let i, l;
  18232. for ( i = 1, l = levels.length; i < l; i ++ ) {
  18233. let levelDistance = levels[ i ].distance;
  18234. if ( levels[ i ].object.visible ) {
  18235. levelDistance -= levelDistance * levels[ i ].hysteresis;
  18236. }
  18237. if ( distance >= levelDistance ) {
  18238. levels[ i - 1 ].object.visible = false;
  18239. levels[ i ].object.visible = true;
  18240. } else {
  18241. break;
  18242. }
  18243. }
  18244. this._currentLevel = i - 1;
  18245. for ( ; i < l; i ++ ) {
  18246. levels[ i ].object.visible = false;
  18247. }
  18248. }
  18249. }
  18250. toJSON( meta ) {
  18251. const data = super.toJSON( meta );
  18252. if ( this.autoUpdate === false ) data.object.autoUpdate = false;
  18253. data.object.levels = [];
  18254. const levels = this.levels;
  18255. for ( let i = 0, l = levels.length; i < l; i ++ ) {
  18256. const level = levels[ i ];
  18257. data.object.levels.push( {
  18258. object: level.object.uuid,
  18259. distance: level.distance,
  18260. hysteresis: level.hysteresis
  18261. } );
  18262. }
  18263. return data;
  18264. }
  18265. }
  18266. const _basePosition = /*@__PURE__*/ new Vector3();
  18267. const _skinIndex = /*@__PURE__*/ new Vector4();
  18268. const _skinWeight = /*@__PURE__*/ new Vector4();
  18269. const _vector3 = /*@__PURE__*/ new Vector3();
  18270. const _matrix4 = /*@__PURE__*/ new Matrix4();
  18271. const _vertex = /*@__PURE__*/ new Vector3();
  18272. const _sphere$5 = /*@__PURE__*/ new Sphere();
  18273. const _inverseMatrix$2 = /*@__PURE__*/ new Matrix4();
  18274. const _ray$2 = /*@__PURE__*/ new Ray();
  18275. /**
  18276. * A mesh that has a {@link Skeleton} that can then be used to animate the
  18277. * vertices of the geometry with skinning/skeleton animation.
  18278. *
  18279. * Next to a valid skeleton, the skinned mesh requires skin indices and weights
  18280. * as buffer attributes in its geometry. These attribute define which bones affect a single
  18281. * vertex to a certain extend.
  18282. *
  18283. * Typically skinned meshes are not created manually but loaders like {@link GLTFLoader}
  18284. * or {@link FBXLoader } import respective models.
  18285. *
  18286. * @augments Mesh
  18287. */
  18288. class SkinnedMesh extends Mesh {
  18289. /**
  18290. * Constructs a new skinned mesh.
  18291. *
  18292. * @param {BufferGeometry} [geometry] - The mesh geometry.
  18293. * @param {Material|Array<Material>} [material] - The mesh material.
  18294. */
  18295. constructor( geometry, material ) {
  18296. super( geometry, material );
  18297. /**
  18298. * This flag can be used for type testing.
  18299. *
  18300. * @type {boolean}
  18301. * @readonly
  18302. * @default true
  18303. */
  18304. this.isSkinnedMesh = true;
  18305. this.type = 'SkinnedMesh';
  18306. /**
  18307. * `AttachedBindMode` means the skinned mesh shares the same world space as the skeleton.
  18308. * This is not true when using `DetachedBindMode` which is useful when sharing a skeleton
  18309. * across multiple skinned meshes.
  18310. *
  18311. * @type {(AttachedBindMode|DetachedBindMode)}
  18312. * @default AttachedBindMode
  18313. */
  18314. this.bindMode = AttachedBindMode;
  18315. /**
  18316. * The base matrix that is used for the bound bone transforms.
  18317. *
  18318. * @type {Matrix4}
  18319. */
  18320. this.bindMatrix = new Matrix4();
  18321. /**
  18322. * The base matrix that is used for resetting the bound bone transforms.
  18323. *
  18324. * @type {Matrix4}
  18325. */
  18326. this.bindMatrixInverse = new Matrix4();
  18327. /**
  18328. * The bounding box of the skinned mesh. Can be computed via {@link SkinnedMesh#computeBoundingBox}.
  18329. *
  18330. * @type {?Box3}
  18331. * @default null
  18332. */
  18333. this.boundingBox = null;
  18334. /**
  18335. * The bounding sphere of the skinned mesh. Can be computed via {@link SkinnedMesh#computeBoundingSphere}.
  18336. *
  18337. * @type {?Sphere}
  18338. * @default null
  18339. */
  18340. this.boundingSphere = null;
  18341. }
  18342. /**
  18343. * Computes the bounding box of the skinned mesh, and updates {@link SkinnedMesh#boundingBox}.
  18344. * The bounding box is not automatically computed by the engine; this method must be called by your app.
  18345. * If the skinned mesh is animated, the bounding box should be recomputed per frame in order to reflect
  18346. * the current animation state.
  18347. */
  18348. computeBoundingBox() {
  18349. const geometry = this.geometry;
  18350. if ( this.boundingBox === null ) {
  18351. this.boundingBox = new Box3();
  18352. }
  18353. this.boundingBox.makeEmpty();
  18354. const positionAttribute = geometry.getAttribute( 'position' );
  18355. for ( let i = 0; i < positionAttribute.count; i ++ ) {
  18356. this.getVertexPosition( i, _vertex );
  18357. this.boundingBox.expandByPoint( _vertex );
  18358. }
  18359. }
  18360. /**
  18361. * Computes the bounding sphere of the skinned mesh, and updates {@link SkinnedMesh#boundingSphere}.
  18362. * The bounding sphere is automatically computed by the engine once when it is needed, e.g., for ray casting
  18363. * and view frustum culling. If the skinned mesh is animated, the bounding sphere should be recomputed
  18364. * per frame in order to reflect the current animation state.
  18365. */
  18366. computeBoundingSphere() {
  18367. const geometry = this.geometry;
  18368. if ( this.boundingSphere === null ) {
  18369. this.boundingSphere = new Sphere();
  18370. }
  18371. this.boundingSphere.makeEmpty();
  18372. const positionAttribute = geometry.getAttribute( 'position' );
  18373. for ( let i = 0; i < positionAttribute.count; i ++ ) {
  18374. this.getVertexPosition( i, _vertex );
  18375. this.boundingSphere.expandByPoint( _vertex );
  18376. }
  18377. }
  18378. copy( source, recursive ) {
  18379. super.copy( source, recursive );
  18380. this.bindMode = source.bindMode;
  18381. this.bindMatrix.copy( source.bindMatrix );
  18382. this.bindMatrixInverse.copy( source.bindMatrixInverse );
  18383. this.skeleton = source.skeleton;
  18384. if ( source.boundingBox !== null ) this.boundingBox = source.boundingBox.clone();
  18385. if ( source.boundingSphere !== null ) this.boundingSphere = source.boundingSphere.clone();
  18386. return this;
  18387. }
  18388. raycast( raycaster, intersects ) {
  18389. const material = this.material;
  18390. const matrixWorld = this.matrixWorld;
  18391. if ( material === undefined ) return;
  18392. // test with bounding sphere in world space
  18393. if ( this.boundingSphere === null ) this.computeBoundingSphere();
  18394. _sphere$5.copy( this.boundingSphere );
  18395. _sphere$5.applyMatrix4( matrixWorld );
  18396. if ( raycaster.ray.intersectsSphere( _sphere$5 ) === false ) return;
  18397. // convert ray to local space of skinned mesh
  18398. _inverseMatrix$2.copy( matrixWorld ).invert();
  18399. _ray$2.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$2 );
  18400. // test with bounding box in local space
  18401. if ( this.boundingBox !== null ) {
  18402. if ( _ray$2.intersectsBox( this.boundingBox ) === false ) return;
  18403. }
  18404. // test for intersections with geometry
  18405. this._computeIntersections( raycaster, intersects, _ray$2 );
  18406. }
  18407. getVertexPosition( index, target ) {
  18408. super.getVertexPosition( index, target );
  18409. this.applyBoneTransform( index, target );
  18410. return target;
  18411. }
  18412. /**
  18413. * Binds the given skeleton to the skinned mesh.
  18414. *
  18415. * @param {Skeleton} skeleton - The skeleton to bind.
  18416. * @param {Matrix4} [bindMatrix] - The bind matrix. If no bind matrix is provided,
  18417. * the skinned mesh's world matrix will be used instead.
  18418. */
  18419. bind( skeleton, bindMatrix ) {
  18420. this.skeleton = skeleton;
  18421. if ( bindMatrix === undefined ) {
  18422. this.updateMatrixWorld( true );
  18423. this.skeleton.calculateInverses();
  18424. bindMatrix = this.matrixWorld;
  18425. }
  18426. this.bindMatrix.copy( bindMatrix );
  18427. this.bindMatrixInverse.copy( bindMatrix ).invert();
  18428. }
  18429. /**
  18430. * This method sets the skinned mesh in the rest pose).
  18431. */
  18432. pose() {
  18433. this.skeleton.pose();
  18434. }
  18435. /**
  18436. * Normalizes the skin weights which are defined as a buffer attribute
  18437. * in the skinned mesh's geometry.
  18438. */
  18439. normalizeSkinWeights() {
  18440. const vector = new Vector4();
  18441. const skinWeight = this.geometry.attributes.skinWeight;
  18442. for ( let i = 0, l = skinWeight.count; i < l; i ++ ) {
  18443. vector.fromBufferAttribute( skinWeight, i );
  18444. const scale = 1.0 / vector.manhattanLength();
  18445. if ( scale !== Infinity ) {
  18446. vector.multiplyScalar( scale );
  18447. } else {
  18448. vector.set( 1, 0, 0, 0 ); // do something reasonable
  18449. }
  18450. skinWeight.setXYZW( i, vector.x, vector.y, vector.z, vector.w );
  18451. }
  18452. }
  18453. updateMatrixWorld( force ) {
  18454. super.updateMatrixWorld( force );
  18455. if ( this.bindMode === AttachedBindMode ) {
  18456. this.bindMatrixInverse.copy( this.matrixWorld ).invert();
  18457. } else if ( this.bindMode === DetachedBindMode ) {
  18458. this.bindMatrixInverse.copy( this.bindMatrix ).invert();
  18459. } else {
  18460. console.warn( 'THREE.SkinnedMesh: Unrecognized bindMode: ' + this.bindMode );
  18461. }
  18462. }
  18463. /**
  18464. * Applies the bone transform associated with the given index to the given
  18465. * vertex position. Returns the updated vector.
  18466. *
  18467. * @param {number} index - The vertex index.
  18468. * @param {Vector3} target - The target object that is used to store the method's result.
  18469. * the skinned mesh's world matrix will be used instead.
  18470. * @return {Vector3} The updated vertex position.
  18471. */
  18472. applyBoneTransform( index, target ) {
  18473. const skeleton = this.skeleton;
  18474. const geometry = this.geometry;
  18475. _skinIndex.fromBufferAttribute( geometry.attributes.skinIndex, index );
  18476. _skinWeight.fromBufferAttribute( geometry.attributes.skinWeight, index );
  18477. _basePosition.copy( target ).applyMatrix4( this.bindMatrix );
  18478. target.set( 0, 0, 0 );
  18479. for ( let i = 0; i < 4; i ++ ) {
  18480. const weight = _skinWeight.getComponent( i );
  18481. if ( weight !== 0 ) {
  18482. const boneIndex = _skinIndex.getComponent( i );
  18483. _matrix4.multiplyMatrices( skeleton.bones[ boneIndex ].matrixWorld, skeleton.boneInverses[ boneIndex ] );
  18484. target.addScaledVector( _vector3.copy( _basePosition ).applyMatrix4( _matrix4 ), weight );
  18485. }
  18486. }
  18487. return target.applyMatrix4( this.bindMatrixInverse );
  18488. }
  18489. }
  18490. /**
  18491. * A bone which is part of a {@link Skeleton}. The skeleton in turn is used by
  18492. * the {@link SkinnedMesh}.
  18493. *
  18494. * ```js
  18495. * const root = new THREE.Bone();
  18496. * const child = new THREE.Bone();
  18497. *
  18498. * root.add( child );
  18499. * child.position.y = 5;
  18500. * ```
  18501. *
  18502. * @augments Object3D
  18503. */
  18504. class Bone extends Object3D {
  18505. /**
  18506. * Constructs a new bone.
  18507. */
  18508. constructor() {
  18509. super();
  18510. /**
  18511. * This flag can be used for type testing.
  18512. *
  18513. * @type {boolean}
  18514. * @readonly
  18515. * @default true
  18516. */
  18517. this.isBone = true;
  18518. this.type = 'Bone';
  18519. }
  18520. }
  18521. /**
  18522. * Creates a texture directly from raw buffer data.
  18523. *
  18524. * The interpretation of the data depends on type and format: If the type is
  18525. * `UnsignedByteType`, a `Uint8Array` will be useful for addressing the
  18526. * texel data. If the format is `RGBAFormat`, data needs four values for
  18527. * one texel; Red, Green, Blue and Alpha (typically the opacity).
  18528. *
  18529. * @augments Texture
  18530. */
  18531. class DataTexture extends Texture {
  18532. /**
  18533. * Constructs a new data texture.
  18534. *
  18535. * @param {?TypedArray} [data=null] - The buffer data.
  18536. * @param {number} [width=1] - The width of the texture.
  18537. * @param {number} [height=1] - The height of the texture.
  18538. * @param {number} [format=RGBAFormat] - The texture format.
  18539. * @param {number} [type=UnsignedByteType] - The texture type.
  18540. * @param {number} [mapping=Texture.DEFAULT_MAPPING] - The texture mapping.
  18541. * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value.
  18542. * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value.
  18543. * @param {number} [magFilter=NearestFilter] - The mag filter value.
  18544. * @param {number} [minFilter=NearestFilter] - The min filter value.
  18545. * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value.
  18546. * @param {string} [colorSpace=NoColorSpace] - The color space.
  18547. */
  18548. constructor( data = null, width = 1, height = 1, format, type, mapping, wrapS, wrapT, magFilter = NearestFilter, minFilter = NearestFilter, anisotropy, colorSpace ) {
  18549. super( null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace );
  18550. /**
  18551. * This flag can be used for type testing.
  18552. *
  18553. * @type {boolean}
  18554. * @readonly
  18555. * @default true
  18556. */
  18557. this.isDataTexture = true;
  18558. /**
  18559. * The image definition of a data texture.
  18560. *
  18561. * @type {{data:TypedArray,width:number,height:number}}
  18562. */
  18563. this.image = { data: data, width: width, height: height };
  18564. /**
  18565. * Whether to generate mipmaps (if possible) for a texture.
  18566. *
  18567. * Overwritten and set to `false` by default.
  18568. *
  18569. * @type {boolean}
  18570. * @default false
  18571. */
  18572. this.generateMipmaps = false;
  18573. /**
  18574. * If set to `true`, the texture is flipped along the vertical axis when
  18575. * uploaded to the GPU.
  18576. *
  18577. * Overwritten and set to `false` by default.
  18578. *
  18579. * @type {boolean}
  18580. * @default false
  18581. */
  18582. this.flipY = false;
  18583. /**
  18584. * Specifies the alignment requirements for the start of each pixel row in memory.
  18585. *
  18586. * Overwritten and set to `1` by default.
  18587. *
  18588. * @type {boolean}
  18589. * @default 1
  18590. */
  18591. this.unpackAlignment = 1;
  18592. }
  18593. }
  18594. const _offsetMatrix = /*@__PURE__*/ new Matrix4();
  18595. const _identityMatrix = /*@__PURE__*/ new Matrix4();
  18596. /**
  18597. * Class for representing the armatures in `three.js`. The skeleton
  18598. * is defined by a hierarchy of bones.
  18599. *
  18600. * ```js
  18601. * const bones = [];
  18602. *
  18603. * const shoulder = new THREE.Bone();
  18604. * const elbow = new THREE.Bone();
  18605. * const hand = new THREE.Bone();
  18606. *
  18607. * shoulder.add( elbow );
  18608. * elbow.add( hand );
  18609. *
  18610. * bones.push( shoulder , elbow, hand);
  18611. *
  18612. * shoulder.position.y = -5;
  18613. * elbow.position.y = 0;
  18614. * hand.position.y = 5;
  18615. *
  18616. * const armSkeleton = new THREE.Skeleton( bones );
  18617. * ```
  18618. */
  18619. class Skeleton {
  18620. /**
  18621. * Constructs a new skeleton.
  18622. *
  18623. * @param {Array<Bone>} [bones] - An array of bones.
  18624. * @param {Array<Matrix4>} [boneInverses] - An array of bone inverse matrices.
  18625. * If not provided, these matrices will be computed automatically via {@link Skeleton#calculateInverses}.
  18626. */
  18627. constructor( bones = [], boneInverses = [] ) {
  18628. this.uuid = generateUUID();
  18629. /**
  18630. * An array of bones defining the skeleton.
  18631. *
  18632. * @type {Array<Bone>}
  18633. */
  18634. this.bones = bones.slice( 0 );
  18635. /**
  18636. * An array of bone inverse matrices.
  18637. *
  18638. * @type {Array<Matrix4>}
  18639. */
  18640. this.boneInverses = boneInverses;
  18641. /**
  18642. * An array buffer holding the bone data.
  18643. * Input data for {@link Skeleton#boneTexture}.
  18644. *
  18645. * @type {?Float32Array}
  18646. * @default null
  18647. */
  18648. this.boneMatrices = null;
  18649. /**
  18650. * A texture holding the bone data for use
  18651. * in the vertex shader.
  18652. *
  18653. * @type {?DataTexture}
  18654. * @default null
  18655. */
  18656. this.boneTexture = null;
  18657. this.init();
  18658. }
  18659. /**
  18660. * Initializes the skeleton. This method gets automatically called by the constructor
  18661. * but depending on how the skeleton is created it might be necessary to call this method
  18662. * manually.
  18663. */
  18664. init() {
  18665. const bones = this.bones;
  18666. const boneInverses = this.boneInverses;
  18667. this.boneMatrices = new Float32Array( bones.length * 16 );
  18668. // calculate inverse bone matrices if necessary
  18669. if ( boneInverses.length === 0 ) {
  18670. this.calculateInverses();
  18671. } else {
  18672. // handle special case
  18673. if ( bones.length !== boneInverses.length ) {
  18674. console.warn( 'THREE.Skeleton: Number of inverse bone matrices does not match amount of bones.' );
  18675. this.boneInverses = [];
  18676. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  18677. this.boneInverses.push( new Matrix4() );
  18678. }
  18679. }
  18680. }
  18681. }
  18682. /**
  18683. * Computes the bone inverse matrices. This method resets {@link Skeleton#boneInverses}
  18684. * and fills it with new matrices.
  18685. */
  18686. calculateInverses() {
  18687. this.boneInverses.length = 0;
  18688. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  18689. const inverse = new Matrix4();
  18690. if ( this.bones[ i ] ) {
  18691. inverse.copy( this.bones[ i ].matrixWorld ).invert();
  18692. }
  18693. this.boneInverses.push( inverse );
  18694. }
  18695. }
  18696. /**
  18697. * Resets the skeleton to the base pose.
  18698. */
  18699. pose() {
  18700. // recover the bind-time world matrices
  18701. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  18702. const bone = this.bones[ i ];
  18703. if ( bone ) {
  18704. bone.matrixWorld.copy( this.boneInverses[ i ] ).invert();
  18705. }
  18706. }
  18707. // compute the local matrices, positions, rotations and scales
  18708. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  18709. const bone = this.bones[ i ];
  18710. if ( bone ) {
  18711. if ( bone.parent && bone.parent.isBone ) {
  18712. bone.matrix.copy( bone.parent.matrixWorld ).invert();
  18713. bone.matrix.multiply( bone.matrixWorld );
  18714. } else {
  18715. bone.matrix.copy( bone.matrixWorld );
  18716. }
  18717. bone.matrix.decompose( bone.position, bone.quaternion, bone.scale );
  18718. }
  18719. }
  18720. }
  18721. /**
  18722. * Resets the skeleton to the base pose.
  18723. */
  18724. update() {
  18725. const bones = this.bones;
  18726. const boneInverses = this.boneInverses;
  18727. const boneMatrices = this.boneMatrices;
  18728. const boneTexture = this.boneTexture;
  18729. // flatten bone matrices to array
  18730. for ( let i = 0, il = bones.length; i < il; i ++ ) {
  18731. // compute the offset between the current and the original transform
  18732. const matrix = bones[ i ] ? bones[ i ].matrixWorld : _identityMatrix;
  18733. _offsetMatrix.multiplyMatrices( matrix, boneInverses[ i ] );
  18734. _offsetMatrix.toArray( boneMatrices, i * 16 );
  18735. }
  18736. if ( boneTexture !== null ) {
  18737. boneTexture.needsUpdate = true;
  18738. }
  18739. }
  18740. /**
  18741. * Returns a new skeleton with copied values from this instance.
  18742. *
  18743. * @return {Skeleton} A clone of this instance.
  18744. */
  18745. clone() {
  18746. return new Skeleton( this.bones, this.boneInverses );
  18747. }
  18748. /**
  18749. * Computes a data texture for passing bone data to the vertex shader.
  18750. *
  18751. * @return {Skeleton} A reference of this instance.
  18752. */
  18753. computeBoneTexture() {
  18754. // layout (1 matrix = 4 pixels)
  18755. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  18756. // with 8x8 pixel texture max 16 bones * 4 pixels = (8 * 8)
  18757. // 16x16 pixel texture max 64 bones * 4 pixels = (16 * 16)
  18758. // 32x32 pixel texture max 256 bones * 4 pixels = (32 * 32)
  18759. // 64x64 pixel texture max 1024 bones * 4 pixels = (64 * 64)
  18760. let size = Math.sqrt( this.bones.length * 4 ); // 4 pixels needed for 1 matrix
  18761. size = Math.ceil( size / 4 ) * 4;
  18762. size = Math.max( size, 4 );
  18763. const boneMatrices = new Float32Array( size * size * 4 ); // 4 floats per RGBA pixel
  18764. boneMatrices.set( this.boneMatrices ); // copy current values
  18765. const boneTexture = new DataTexture( boneMatrices, size, size, RGBAFormat, FloatType );
  18766. boneTexture.needsUpdate = true;
  18767. this.boneMatrices = boneMatrices;
  18768. this.boneTexture = boneTexture;
  18769. return this;
  18770. }
  18771. /**
  18772. * Searches through the skeleton's bone array and returns the first with a
  18773. * matching name.
  18774. *
  18775. * @param {string} name - The name of the bone.
  18776. * @return {Bone|undefined} The found bone. `undefined` if no bone has been found.
  18777. */
  18778. getBoneByName( name ) {
  18779. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  18780. const bone = this.bones[ i ];
  18781. if ( bone.name === name ) {
  18782. return bone;
  18783. }
  18784. }
  18785. return undefined;
  18786. }
  18787. /**
  18788. * Frees the GPU-related resources allocated by this instance. Call this
  18789. * method whenever this instance is no longer used in your app.
  18790. */
  18791. dispose( ) {
  18792. if ( this.boneTexture !== null ) {
  18793. this.boneTexture.dispose();
  18794. this.boneTexture = null;
  18795. }
  18796. }
  18797. /**
  18798. * Setups the skeleton by the given JSON and bones.
  18799. *
  18800. * @param {Object} json - The skeleton as serialized JSON.
  18801. * @param {Object<string, Bone>} bones - An array of bones.
  18802. * @return {Skeleton} A reference of this instance.
  18803. */
  18804. fromJSON( json, bones ) {
  18805. this.uuid = json.uuid;
  18806. for ( let i = 0, l = json.bones.length; i < l; i ++ ) {
  18807. const uuid = json.bones[ i ];
  18808. let bone = bones[ uuid ];
  18809. if ( bone === undefined ) {
  18810. console.warn( 'THREE.Skeleton: No bone found with UUID:', uuid );
  18811. bone = new Bone();
  18812. }
  18813. this.bones.push( bone );
  18814. this.boneInverses.push( new Matrix4().fromArray( json.boneInverses[ i ] ) );
  18815. }
  18816. this.init();
  18817. return this;
  18818. }
  18819. /**
  18820. * Serializes the skeleton into JSON.
  18821. *
  18822. * @return {Object} A JSON object representing the serialized skeleton.
  18823. * @see {@link ObjectLoader#parse}
  18824. */
  18825. toJSON() {
  18826. const data = {
  18827. metadata: {
  18828. version: 4.6,
  18829. type: 'Skeleton',
  18830. generator: 'Skeleton.toJSON'
  18831. },
  18832. bones: [],
  18833. boneInverses: []
  18834. };
  18835. data.uuid = this.uuid;
  18836. const bones = this.bones;
  18837. const boneInverses = this.boneInverses;
  18838. for ( let i = 0, l = bones.length; i < l; i ++ ) {
  18839. const bone = bones[ i ];
  18840. data.bones.push( bone.uuid );
  18841. const boneInverse = boneInverses[ i ];
  18842. data.boneInverses.push( boneInverse.toArray() );
  18843. }
  18844. return data;
  18845. }
  18846. }
  18847. /**
  18848. * An instanced version of a buffer attribute.
  18849. *
  18850. * @augments BufferAttribute
  18851. */
  18852. class InstancedBufferAttribute extends BufferAttribute {
  18853. /**
  18854. * Constructs a new instanced buffer attribute.
  18855. *
  18856. * @param {TypedArray} array - The array holding the attribute data.
  18857. * @param {number} itemSize - The item size.
  18858. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  18859. * @param {number} [meshPerAttribute=1] - How often a value of this buffer attribute should be repeated.
  18860. */
  18861. constructor( array, itemSize, normalized, meshPerAttribute = 1 ) {
  18862. super( array, itemSize, normalized );
  18863. /**
  18864. * This flag can be used for type testing.
  18865. *
  18866. * @type {boolean}
  18867. * @readonly
  18868. * @default true
  18869. */
  18870. this.isInstancedBufferAttribute = true;
  18871. /**
  18872. * Defines how often a value of this buffer attribute should be repeated. A
  18873. * value of one means that each value of the instanced attribute is used for
  18874. * a single instance. A value of two means that each value is used for two
  18875. * consecutive instances (and so on).
  18876. *
  18877. * @type {number}
  18878. * @default 1
  18879. */
  18880. this.meshPerAttribute = meshPerAttribute;
  18881. }
  18882. copy( source ) {
  18883. super.copy( source );
  18884. this.meshPerAttribute = source.meshPerAttribute;
  18885. return this;
  18886. }
  18887. toJSON() {
  18888. const data = super.toJSON();
  18889. data.meshPerAttribute = this.meshPerAttribute;
  18890. data.isInstancedBufferAttribute = true;
  18891. return data;
  18892. }
  18893. }
  18894. const _instanceLocalMatrix = /*@__PURE__*/ new Matrix4();
  18895. const _instanceWorldMatrix = /*@__PURE__*/ new Matrix4();
  18896. const _instanceIntersects = [];
  18897. const _box3 = /*@__PURE__*/ new Box3();
  18898. const _identity = /*@__PURE__*/ new Matrix4();
  18899. const _mesh$1 = /*@__PURE__*/ new Mesh();
  18900. const _sphere$4 = /*@__PURE__*/ new Sphere();
  18901. /**
  18902. * A special version of a mesh with instanced rendering support. Use
  18903. * this class if you have to render a large number of objects with the same
  18904. * geometry and material(s) but with different world transformations. The usage
  18905. * of 'InstancedMesh' will help you to reduce the number of draw calls and thus
  18906. * improve the overall rendering performance in your application.
  18907. *
  18908. * @augments Mesh
  18909. */
  18910. class InstancedMesh extends Mesh {
  18911. /**
  18912. * Constructs a new instanced mesh.
  18913. *
  18914. * @param {BufferGeometry} [geometry] - The mesh geometry.
  18915. * @param {Material|Array<Material>} [material] - The mesh material.
  18916. * @param {number} count - The number of instances.
  18917. */
  18918. constructor( geometry, material, count ) {
  18919. super( geometry, material );
  18920. /**
  18921. * This flag can be used for type testing.
  18922. *
  18923. * @type {boolean}
  18924. * @readonly
  18925. * @default true
  18926. */
  18927. this.isInstancedMesh = true;
  18928. /**
  18929. * Represents the local transformation of all instances. You have to set its
  18930. * {@link BufferAttribute#needsUpdate} flag to true if you modify instanced data
  18931. * via {@link InstancedMesh#setMatrixAt}.
  18932. *
  18933. * @type {InstancedBufferAttribute}
  18934. */
  18935. this.instanceMatrix = new InstancedBufferAttribute( new Float32Array( count * 16 ), 16 );
  18936. /**
  18937. * Represents the color of all instances. You have to set its
  18938. * {@link BufferAttribute#needsUpdate} flag to true if you modify instanced data
  18939. * via {@link InstancedMesh#setColorAt}.
  18940. *
  18941. * @type {?InstancedBufferAttribute}
  18942. * @default null
  18943. */
  18944. this.instanceColor = null;
  18945. /**
  18946. * Represents the morph target weights of all instances. You have to set its
  18947. * {@link Texture#needsUpdate} flag to true if you modify instanced data
  18948. * via {@link InstancedMesh#setMorphAt}.
  18949. *
  18950. * @type {?DataTexture}
  18951. * @default null
  18952. */
  18953. this.morphTexture = null;
  18954. /**
  18955. * The number of instances.
  18956. *
  18957. * @type {number}
  18958. */
  18959. this.count = count;
  18960. /**
  18961. * The bounding box of the instanced mesh. Can be computed via {@link InstancedMesh#computeBoundingBox}.
  18962. *
  18963. * @type {?Box3}
  18964. * @default null
  18965. */
  18966. this.boundingBox = null;
  18967. /**
  18968. * The bounding sphere of the instanced mesh. Can be computed via {@link InstancedMesh#computeBoundingSphere}.
  18969. *
  18970. * @type {?Sphere}
  18971. * @default null
  18972. */
  18973. this.boundingSphere = null;
  18974. for ( let i = 0; i < count; i ++ ) {
  18975. this.setMatrixAt( i, _identity );
  18976. }
  18977. }
  18978. /**
  18979. * Computes the bounding box of the instanced mesh, and updates {@link InstancedMesh#boundingBox}.
  18980. * The bounding box is not automatically computed by the engine; this method must be called by your app.
  18981. * You may need to recompute the bounding box if an instance is transformed via {@link InstancedMesh#setMatrixAt}.
  18982. */
  18983. computeBoundingBox() {
  18984. const geometry = this.geometry;
  18985. const count = this.count;
  18986. if ( this.boundingBox === null ) {
  18987. this.boundingBox = new Box3();
  18988. }
  18989. if ( geometry.boundingBox === null ) {
  18990. geometry.computeBoundingBox();
  18991. }
  18992. this.boundingBox.makeEmpty();
  18993. for ( let i = 0; i < count; i ++ ) {
  18994. this.getMatrixAt( i, _instanceLocalMatrix );
  18995. _box3.copy( geometry.boundingBox ).applyMatrix4( _instanceLocalMatrix );
  18996. this.boundingBox.union( _box3 );
  18997. }
  18998. }
  18999. /**
  19000. * Computes the bounding sphere of the instanced mesh, and updates {@link InstancedMesh#boundingSphere}
  19001. * The engine automatically computes the bounding sphere when it is needed, e.g., for ray casting or view frustum culling.
  19002. * You may need to recompute the bounding sphere if an instance is transformed via {@link InstancedMesh#setMatrixAt}.
  19003. */
  19004. computeBoundingSphere() {
  19005. const geometry = this.geometry;
  19006. const count = this.count;
  19007. if ( this.boundingSphere === null ) {
  19008. this.boundingSphere = new Sphere();
  19009. }
  19010. if ( geometry.boundingSphere === null ) {
  19011. geometry.computeBoundingSphere();
  19012. }
  19013. this.boundingSphere.makeEmpty();
  19014. for ( let i = 0; i < count; i ++ ) {
  19015. this.getMatrixAt( i, _instanceLocalMatrix );
  19016. _sphere$4.copy( geometry.boundingSphere ).applyMatrix4( _instanceLocalMatrix );
  19017. this.boundingSphere.union( _sphere$4 );
  19018. }
  19019. }
  19020. copy( source, recursive ) {
  19021. super.copy( source, recursive );
  19022. this.instanceMatrix.copy( source.instanceMatrix );
  19023. if ( source.morphTexture !== null ) this.morphTexture = source.morphTexture.clone();
  19024. if ( source.instanceColor !== null ) this.instanceColor = source.instanceColor.clone();
  19025. this.count = source.count;
  19026. if ( source.boundingBox !== null ) this.boundingBox = source.boundingBox.clone();
  19027. if ( source.boundingSphere !== null ) this.boundingSphere = source.boundingSphere.clone();
  19028. return this;
  19029. }
  19030. /**
  19031. * Gets the color of the defined instance.
  19032. *
  19033. * @param {number} index - The instance index.
  19034. * @param {Color} color - The target object that is used to store the method's result.
  19035. */
  19036. getColorAt( index, color ) {
  19037. color.fromArray( this.instanceColor.array, index * 3 );
  19038. }
  19039. /**
  19040. * Gets the local transformation matrix of the defined instance.
  19041. *
  19042. * @param {number} index - The instance index.
  19043. * @param {Matrix4} matrix - The target object that is used to store the method's result.
  19044. */
  19045. getMatrixAt( index, matrix ) {
  19046. matrix.fromArray( this.instanceMatrix.array, index * 16 );
  19047. }
  19048. /**
  19049. * Gets the morph target weights of the defined instance.
  19050. *
  19051. * @param {number} index - The instance index.
  19052. * @param {Mesh} object - The target object that is used to store the method's result.
  19053. */
  19054. getMorphAt( index, object ) {
  19055. const objectInfluences = object.morphTargetInfluences;
  19056. const array = this.morphTexture.source.data.data;
  19057. const len = objectInfluences.length + 1; // All influences + the baseInfluenceSum
  19058. const dataIndex = index * len + 1; // Skip the baseInfluenceSum at the beginning
  19059. for ( let i = 0; i < objectInfluences.length; i ++ ) {
  19060. objectInfluences[ i ] = array[ dataIndex + i ];
  19061. }
  19062. }
  19063. raycast( raycaster, intersects ) {
  19064. const matrixWorld = this.matrixWorld;
  19065. const raycastTimes = this.count;
  19066. _mesh$1.geometry = this.geometry;
  19067. _mesh$1.material = this.material;
  19068. if ( _mesh$1.material === undefined ) return;
  19069. // test with bounding sphere first
  19070. if ( this.boundingSphere === null ) this.computeBoundingSphere();
  19071. _sphere$4.copy( this.boundingSphere );
  19072. _sphere$4.applyMatrix4( matrixWorld );
  19073. if ( raycaster.ray.intersectsSphere( _sphere$4 ) === false ) return;
  19074. // now test each instance
  19075. for ( let instanceId = 0; instanceId < raycastTimes; instanceId ++ ) {
  19076. // calculate the world matrix for each instance
  19077. this.getMatrixAt( instanceId, _instanceLocalMatrix );
  19078. _instanceWorldMatrix.multiplyMatrices( matrixWorld, _instanceLocalMatrix );
  19079. // the mesh represents this single instance
  19080. _mesh$1.matrixWorld = _instanceWorldMatrix;
  19081. _mesh$1.raycast( raycaster, _instanceIntersects );
  19082. // process the result of raycast
  19083. for ( let i = 0, l = _instanceIntersects.length; i < l; i ++ ) {
  19084. const intersect = _instanceIntersects[ i ];
  19085. intersect.instanceId = instanceId;
  19086. intersect.object = this;
  19087. intersects.push( intersect );
  19088. }
  19089. _instanceIntersects.length = 0;
  19090. }
  19091. }
  19092. /**
  19093. * Sets the given color to the defined instance. Make sure you set the `needsUpdate` flag of
  19094. * {@link InstancedMesh#instanceColor} to `true` after updating all the colors.
  19095. *
  19096. * @param {number} index - The instance index.
  19097. * @param {Color} color - The instance color.
  19098. */
  19099. setColorAt( index, color ) {
  19100. if ( this.instanceColor === null ) {
  19101. this.instanceColor = new InstancedBufferAttribute( new Float32Array( this.instanceMatrix.count * 3 ).fill( 1 ), 3 );
  19102. }
  19103. color.toArray( this.instanceColor.array, index * 3 );
  19104. }
  19105. /**
  19106. * Sets the given local transformation matrix to the defined instance. Make sure you set the `needsUpdate` flag of
  19107. * {@link InstancedMesh#instanceMatrix} to `true` after updating all the colors.
  19108. *
  19109. * @param {number} index - The instance index.
  19110. * @param {Matrix4} matrix - The local transformation.
  19111. */
  19112. setMatrixAt( index, matrix ) {
  19113. matrix.toArray( this.instanceMatrix.array, index * 16 );
  19114. }
  19115. /**
  19116. * Sets the morph target weights to the defined instance. Make sure you set the `needsUpdate` flag of
  19117. * {@link InstancedMesh#morphTexture} to `true` after updating all the influences.
  19118. *
  19119. * @param {number} index - The instance index.
  19120. * @param {Mesh} object - A mesh which `morphTargetInfluences` property containing the morph target weights
  19121. * of a single instance.
  19122. */
  19123. setMorphAt( index, object ) {
  19124. const objectInfluences = object.morphTargetInfluences;
  19125. const len = objectInfluences.length + 1; // morphBaseInfluence + all influences
  19126. if ( this.morphTexture === null ) {
  19127. this.morphTexture = new DataTexture( new Float32Array( len * this.count ), len, this.count, RedFormat, FloatType );
  19128. }
  19129. const array = this.morphTexture.source.data.data;
  19130. let morphInfluencesSum = 0;
  19131. for ( let i = 0; i < objectInfluences.length; i ++ ) {
  19132. morphInfluencesSum += objectInfluences[ i ];
  19133. }
  19134. const morphBaseInfluence = this.geometry.morphTargetsRelative ? 1 : 1 - morphInfluencesSum;
  19135. const dataIndex = len * index;
  19136. array[ dataIndex ] = morphBaseInfluence;
  19137. array.set( objectInfluences, dataIndex + 1 );
  19138. }
  19139. updateMorphTargets() {
  19140. }
  19141. /**
  19142. * Frees the GPU-related resources allocated by this instance. Call this
  19143. * method whenever this instance is no longer used in your app.
  19144. */
  19145. dispose() {
  19146. this.dispatchEvent( { type: 'dispose' } );
  19147. if ( this.morphTexture !== null ) {
  19148. this.morphTexture.dispose();
  19149. this.morphTexture = null;
  19150. }
  19151. }
  19152. }
  19153. const _vector1 = /*@__PURE__*/ new Vector3();
  19154. const _vector2 = /*@__PURE__*/ new Vector3();
  19155. const _normalMatrix = /*@__PURE__*/ new Matrix3();
  19156. /**
  19157. * A two dimensional surface that extends infinitely in 3D space, represented
  19158. * in [Hessian normal form]{@link http://mathworld.wolfram.com/HessianNormalForm.html}
  19159. * by a unit length normal vector and a constant.
  19160. */
  19161. class Plane {
  19162. /**
  19163. * Constructs a new plane.
  19164. *
  19165. * @param {Vector3} [normal=(1,0,0)] - A unit length vector defining the normal of the plane.
  19166. * @param {number} [constant=0] - The signed distance from the origin to the plane.
  19167. */
  19168. constructor( normal = new Vector3( 1, 0, 0 ), constant = 0 ) {
  19169. /**
  19170. * This flag can be used for type testing.
  19171. *
  19172. * @type {boolean}
  19173. * @readonly
  19174. * @default true
  19175. */
  19176. this.isPlane = true;
  19177. /**
  19178. * A unit length vector defining the normal of the plane.
  19179. *
  19180. * @type {Vector3}
  19181. */
  19182. this.normal = normal;
  19183. /**
  19184. * The signed distance from the origin to the plane.
  19185. *
  19186. * @type {number}
  19187. * @default 0
  19188. */
  19189. this.constant = constant;
  19190. }
  19191. /**
  19192. * Sets the plane components by copying the given values.
  19193. *
  19194. * @param {Vector3} normal - The normal.
  19195. * @param {number} constant - The constant.
  19196. * @return {Plane} A reference to this plane.
  19197. */
  19198. set( normal, constant ) {
  19199. this.normal.copy( normal );
  19200. this.constant = constant;
  19201. return this;
  19202. }
  19203. /**
  19204. * Sets the plane components by defining `x`, `y`, `z` as the
  19205. * plane normal and `w` as the constant.
  19206. *
  19207. * @param {number} x - The value for the normal's x component.
  19208. * @param {number} y - The value for the normal's y component.
  19209. * @param {number} z - The value for the normal's z component.
  19210. * @param {number} w - The constant value.
  19211. * @return {Plane} A reference to this plane.
  19212. */
  19213. setComponents( x, y, z, w ) {
  19214. this.normal.set( x, y, z );
  19215. this.constant = w;
  19216. return this;
  19217. }
  19218. /**
  19219. * Sets the plane from the given normal and coplanar point (that is a point
  19220. * that lies onto the plane).
  19221. *
  19222. * @param {Vector3} normal - The normal.
  19223. * @param {Vector3} point - A coplanar point.
  19224. * @return {Plane} A reference to this plane.
  19225. */
  19226. setFromNormalAndCoplanarPoint( normal, point ) {
  19227. this.normal.copy( normal );
  19228. this.constant = - point.dot( this.normal );
  19229. return this;
  19230. }
  19231. /**
  19232. * Sets the plane from three coplanar points. The winding order is
  19233. * assumed to be counter-clockwise, and determines the direction of
  19234. * the plane normal.
  19235. *
  19236. * @param {Vector3} a - The first coplanar point.
  19237. * @param {Vector3} b - The second coplanar point.
  19238. * @param {Vector3} c - The third coplanar point.
  19239. * @return {Plane} A reference to this plane.
  19240. */
  19241. setFromCoplanarPoints( a, b, c ) {
  19242. const normal = _vector1.subVectors( c, b ).cross( _vector2.subVectors( a, b ) ).normalize();
  19243. // Q: should an error be thrown if normal is zero (e.g. degenerate plane)?
  19244. this.setFromNormalAndCoplanarPoint( normal, a );
  19245. return this;
  19246. }
  19247. /**
  19248. * Copies the values of the given plane to this instance.
  19249. *
  19250. * @param {Plane} plane - The plane to copy.
  19251. * @return {Plane} A reference to this plane.
  19252. */
  19253. copy( plane ) {
  19254. this.normal.copy( plane.normal );
  19255. this.constant = plane.constant;
  19256. return this;
  19257. }
  19258. /**
  19259. * Normalizes the plane normal and adjusts the constant accordingly.
  19260. *
  19261. * @return {Plane} A reference to this plane.
  19262. */
  19263. normalize() {
  19264. // Note: will lead to a divide by zero if the plane is invalid.
  19265. const inverseNormalLength = 1.0 / this.normal.length();
  19266. this.normal.multiplyScalar( inverseNormalLength );
  19267. this.constant *= inverseNormalLength;
  19268. return this;
  19269. }
  19270. /**
  19271. * Negates both the plane normal and the constant.
  19272. *
  19273. * @return {Plane} A reference to this plane.
  19274. */
  19275. negate() {
  19276. this.constant *= -1;
  19277. this.normal.negate();
  19278. return this;
  19279. }
  19280. /**
  19281. * Returns the signed distance from the given point to this plane.
  19282. *
  19283. * @param {Vector3} point - The point to compute the distance for.
  19284. * @return {number} The signed distance.
  19285. */
  19286. distanceToPoint( point ) {
  19287. return this.normal.dot( point ) + this.constant;
  19288. }
  19289. /**
  19290. * Returns the signed distance from the given sphere to this plane.
  19291. *
  19292. * @param {Sphere} sphere - The sphere to compute the distance for.
  19293. * @return {number} The signed distance.
  19294. */
  19295. distanceToSphere( sphere ) {
  19296. return this.distanceToPoint( sphere.center ) - sphere.radius;
  19297. }
  19298. /**
  19299. * Projects a the given point onto the plane.
  19300. *
  19301. * @param {Vector3} point - The point to project.
  19302. * @param {Vector3} target - The target vector that is used to store the method's result.
  19303. * @return {Vector3} The projected point on the plane.
  19304. */
  19305. projectPoint( point, target ) {
  19306. return target.copy( point ).addScaledVector( this.normal, - this.distanceToPoint( point ) );
  19307. }
  19308. /**
  19309. * Returns the intersection point of the passed line and the plane. Returns
  19310. * `null` if the line does not intersect. Returns the line's starting point if
  19311. * the line is coplanar with the plane.
  19312. *
  19313. * @param {Line3} line - The line to compute the intersection for.
  19314. * @param {Vector3} target - The target vector that is used to store the method's result.
  19315. * @return {?Vector3} The intersection point.
  19316. */
  19317. intersectLine( line, target ) {
  19318. const direction = line.delta( _vector1 );
  19319. const denominator = this.normal.dot( direction );
  19320. if ( denominator === 0 ) {
  19321. // line is coplanar, return origin
  19322. if ( this.distanceToPoint( line.start ) === 0 ) {
  19323. return target.copy( line.start );
  19324. }
  19325. // Unsure if this is the correct method to handle this case.
  19326. return null;
  19327. }
  19328. const t = - ( line.start.dot( this.normal ) + this.constant ) / denominator;
  19329. if ( t < 0 || t > 1 ) {
  19330. return null;
  19331. }
  19332. return target.copy( line.start ).addScaledVector( direction, t );
  19333. }
  19334. /**
  19335. * Returns `true` if the given line segment intersects with (passes through) the plane.
  19336. *
  19337. * @param {Line3} line - The line to test.
  19338. * @return {boolean} Whether the given line segment intersects with the plane or not.
  19339. */
  19340. intersectsLine( line ) {
  19341. // Note: this tests if a line intersects the plane, not whether it (or its end-points) are coplanar with it.
  19342. const startSign = this.distanceToPoint( line.start );
  19343. const endSign = this.distanceToPoint( line.end );
  19344. return ( startSign < 0 && endSign > 0 ) || ( endSign < 0 && startSign > 0 );
  19345. }
  19346. /**
  19347. * Returns `true` if the given bounding box intersects with the plane.
  19348. *
  19349. * @param {Box3} box - The bounding box to test.
  19350. * @return {boolean} Whether the given bounding box intersects with the plane or not.
  19351. */
  19352. intersectsBox( box ) {
  19353. return box.intersectsPlane( this );
  19354. }
  19355. /**
  19356. * Returns `true` if the given bounding sphere intersects with the plane.
  19357. *
  19358. * @param {Sphere} sphere - The bounding sphere to test.
  19359. * @return {boolean} Whether the given bounding sphere intersects with the plane or not.
  19360. */
  19361. intersectsSphere( sphere ) {
  19362. return sphere.intersectsPlane( this );
  19363. }
  19364. /**
  19365. * Returns a coplanar vector to the plane, by calculating the
  19366. * projection of the normal at the origin onto the plane.
  19367. *
  19368. * @param {Vector3} target - The target vector that is used to store the method's result.
  19369. * @return {Vector3} The coplanar point.
  19370. */
  19371. coplanarPoint( target ) {
  19372. return target.copy( this.normal ).multiplyScalar( - this.constant );
  19373. }
  19374. /**
  19375. * Apply a 4x4 matrix to the plane. The matrix must be an affine, homogeneous transform.
  19376. *
  19377. * The optional normal matrix can be pre-computed like so:
  19378. * ```js
  19379. * const optionalNormalMatrix = new THREE.Matrix3().getNormalMatrix( matrix );
  19380. * ```
  19381. *
  19382. * @param {Matrix4} matrix - The transformation matrix.
  19383. * @param {Matrix4} [optionalNormalMatrix] - A pre-computed normal matrix.
  19384. * @return {Plane} A reference to this plane.
  19385. */
  19386. applyMatrix4( matrix, optionalNormalMatrix ) {
  19387. const normalMatrix = optionalNormalMatrix || _normalMatrix.getNormalMatrix( matrix );
  19388. const referencePoint = this.coplanarPoint( _vector1 ).applyMatrix4( matrix );
  19389. const normal = this.normal.applyMatrix3( normalMatrix ).normalize();
  19390. this.constant = - referencePoint.dot( normal );
  19391. return this;
  19392. }
  19393. /**
  19394. * Translates the plane by the distance defined by the given offset vector.
  19395. * Note that this only affects the plane constant and will not affect the normal vector.
  19396. *
  19397. * @param {Vector3} offset - The offset vector.
  19398. * @return {Plane} A reference to this plane.
  19399. */
  19400. translate( offset ) {
  19401. this.constant -= offset.dot( this.normal );
  19402. return this;
  19403. }
  19404. /**
  19405. * Returns `true` if this plane is equal with the given one.
  19406. *
  19407. * @param {Plane} plane - The plane to test for equality.
  19408. * @return {boolean} Whether this plane is equal with the given one.
  19409. */
  19410. equals( plane ) {
  19411. return plane.normal.equals( this.normal ) && ( plane.constant === this.constant );
  19412. }
  19413. /**
  19414. * Returns a new plane with copied values from this instance.
  19415. *
  19416. * @return {Plane} A clone of this instance.
  19417. */
  19418. clone() {
  19419. return new this.constructor().copy( this );
  19420. }
  19421. }
  19422. const _sphere$3 = /*@__PURE__*/ new Sphere();
  19423. const _vector$6 = /*@__PURE__*/ new Vector3();
  19424. /**
  19425. * Frustums are used to determine what is inside the camera's field of view.
  19426. * They help speed up the rendering process - objects which lie outside a camera's
  19427. * frustum can safely be excluded from rendering.
  19428. *
  19429. * This class is mainly intended for use internally by a renderer.
  19430. */
  19431. class Frustum {
  19432. /**
  19433. * Constructs a new frustum.
  19434. *
  19435. * @param {Plane} [p0] - The first plane that encloses the frustum.
  19436. * @param {Plane} [p1] - The second plane that encloses the frustum.
  19437. * @param {Plane} [p2] - The third plane that encloses the frustum.
  19438. * @param {Plane} [p3] - The fourth plane that encloses the frustum.
  19439. * @param {Plane} [p4] - The fifth plane that encloses the frustum.
  19440. * @param {Plane} [p5] - The sixth plane that encloses the frustum.
  19441. */
  19442. constructor( p0 = new Plane(), p1 = new Plane(), p2 = new Plane(), p3 = new Plane(), p4 = new Plane(), p5 = new Plane() ) {
  19443. /**
  19444. * This array holds the planes that enclose the frustum.
  19445. *
  19446. * @type {Array<Plane>}
  19447. */
  19448. this.planes = [ p0, p1, p2, p3, p4, p5 ];
  19449. }
  19450. /**
  19451. * Sets the frustum planes by copying the given planes.
  19452. *
  19453. * @param {Plane} [p0] - The first plane that encloses the frustum.
  19454. * @param {Plane} [p1] - The second plane that encloses the frustum.
  19455. * @param {Plane} [p2] - The third plane that encloses the frustum.
  19456. * @param {Plane} [p3] - The fourth plane that encloses the frustum.
  19457. * @param {Plane} [p4] - The fifth plane that encloses the frustum.
  19458. * @param {Plane} [p5] - The sixth plane that encloses the frustum.
  19459. * @return {Frustum} A reference to this frustum.
  19460. */
  19461. set( p0, p1, p2, p3, p4, p5 ) {
  19462. const planes = this.planes;
  19463. planes[ 0 ].copy( p0 );
  19464. planes[ 1 ].copy( p1 );
  19465. planes[ 2 ].copy( p2 );
  19466. planes[ 3 ].copy( p3 );
  19467. planes[ 4 ].copy( p4 );
  19468. planes[ 5 ].copy( p5 );
  19469. return this;
  19470. }
  19471. /**
  19472. * Copies the values of the given frustum to this instance.
  19473. *
  19474. * @param {Frustum} frustum - The frustum to copy.
  19475. * @return {Frustum} A reference to this frustum.
  19476. */
  19477. copy( frustum ) {
  19478. const planes = this.planes;
  19479. for ( let i = 0; i < 6; i ++ ) {
  19480. planes[ i ].copy( frustum.planes[ i ] );
  19481. }
  19482. return this;
  19483. }
  19484. /**
  19485. * Sets the frustum planes from the given projection matrix.
  19486. *
  19487. * @param {Matrix4} m - The projection matrix.
  19488. * @param {(WebGLCoordinateSystem|WebGPUCoordinateSystem)} coordinateSystem - The coordinate system.
  19489. * @return {Frustum} A reference to this frustum.
  19490. */
  19491. setFromProjectionMatrix( m, coordinateSystem = WebGLCoordinateSystem ) {
  19492. const planes = this.planes;
  19493. const me = m.elements;
  19494. const me0 = me[ 0 ], me1 = me[ 1 ], me2 = me[ 2 ], me3 = me[ 3 ];
  19495. const me4 = me[ 4 ], me5 = me[ 5 ], me6 = me[ 6 ], me7 = me[ 7 ];
  19496. const me8 = me[ 8 ], me9 = me[ 9 ], me10 = me[ 10 ], me11 = me[ 11 ];
  19497. const me12 = me[ 12 ], me13 = me[ 13 ], me14 = me[ 14 ], me15 = me[ 15 ];
  19498. planes[ 0 ].setComponents( me3 - me0, me7 - me4, me11 - me8, me15 - me12 ).normalize();
  19499. planes[ 1 ].setComponents( me3 + me0, me7 + me4, me11 + me8, me15 + me12 ).normalize();
  19500. planes[ 2 ].setComponents( me3 + me1, me7 + me5, me11 + me9, me15 + me13 ).normalize();
  19501. planes[ 3 ].setComponents( me3 - me1, me7 - me5, me11 - me9, me15 - me13 ).normalize();
  19502. planes[ 4 ].setComponents( me3 - me2, me7 - me6, me11 - me10, me15 - me14 ).normalize();
  19503. if ( coordinateSystem === WebGLCoordinateSystem ) {
  19504. planes[ 5 ].setComponents( me3 + me2, me7 + me6, me11 + me10, me15 + me14 ).normalize();
  19505. } else if ( coordinateSystem === WebGPUCoordinateSystem ) {
  19506. planes[ 5 ].setComponents( me2, me6, me10, me14 ).normalize();
  19507. } else {
  19508. throw new Error( 'THREE.Frustum.setFromProjectionMatrix(): Invalid coordinate system: ' + coordinateSystem );
  19509. }
  19510. return this;
  19511. }
  19512. /**
  19513. * Returns `true` if the 3D object's bounding sphere is intersecting this frustum.
  19514. *
  19515. * Note that the 3D object must have a geometry so that the bounding sphere can be calculated.
  19516. *
  19517. * @param {Object3D} object - The 3D object to test.
  19518. * @return {boolean} Whether the 3D object's bounding sphere is intersecting this frustum or not.
  19519. */
  19520. intersectsObject( object ) {
  19521. if ( object.boundingSphere !== undefined ) {
  19522. if ( object.boundingSphere === null ) object.computeBoundingSphere();
  19523. _sphere$3.copy( object.boundingSphere ).applyMatrix4( object.matrixWorld );
  19524. } else {
  19525. const geometry = object.geometry;
  19526. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  19527. _sphere$3.copy( geometry.boundingSphere ).applyMatrix4( object.matrixWorld );
  19528. }
  19529. return this.intersectsSphere( _sphere$3 );
  19530. }
  19531. /**
  19532. * Returns `true` if the given sprite is intersecting this frustum.
  19533. *
  19534. * @param {Sprite} sprite - The sprite to test.
  19535. * @return {boolean} Whether the sprite is intersecting this frustum or not.
  19536. */
  19537. intersectsSprite( sprite ) {
  19538. _sphere$3.center.set( 0, 0, 0 );
  19539. _sphere$3.radius = 0.7071067811865476;
  19540. _sphere$3.applyMatrix4( sprite.matrixWorld );
  19541. return this.intersectsSphere( _sphere$3 );
  19542. }
  19543. /**
  19544. * Returns `true` if the given bounding sphere is intersecting this frustum.
  19545. *
  19546. * @param {Sphere} sphere - The bounding sphere to test.
  19547. * @return {boolean} Whether the bounding sphere is intersecting this frustum or not.
  19548. */
  19549. intersectsSphere( sphere ) {
  19550. const planes = this.planes;
  19551. const center = sphere.center;
  19552. const negRadius = - sphere.radius;
  19553. for ( let i = 0; i < 6; i ++ ) {
  19554. const distance = planes[ i ].distanceToPoint( center );
  19555. if ( distance < negRadius ) {
  19556. return false;
  19557. }
  19558. }
  19559. return true;
  19560. }
  19561. /**
  19562. * Returns `true` if the given bounding box is intersecting this frustum.
  19563. *
  19564. * @param {Box3} box - The bounding box to test.
  19565. * @return {boolean} Whether the bounding box is intersecting this frustum or not.
  19566. */
  19567. intersectsBox( box ) {
  19568. const planes = this.planes;
  19569. for ( let i = 0; i < 6; i ++ ) {
  19570. const plane = planes[ i ];
  19571. // corner at max distance
  19572. _vector$6.x = plane.normal.x > 0 ? box.max.x : box.min.x;
  19573. _vector$6.y = plane.normal.y > 0 ? box.max.y : box.min.y;
  19574. _vector$6.z = plane.normal.z > 0 ? box.max.z : box.min.z;
  19575. if ( plane.distanceToPoint( _vector$6 ) < 0 ) {
  19576. return false;
  19577. }
  19578. }
  19579. return true;
  19580. }
  19581. /**
  19582. * Returns `true` if the given point lies within the frustum.
  19583. *
  19584. * @param {Vector3} point - The point to test.
  19585. * @return {boolean} Whether the point lies within this frustum or not.
  19586. */
  19587. containsPoint( point ) {
  19588. const planes = this.planes;
  19589. for ( let i = 0; i < 6; i ++ ) {
  19590. if ( planes[ i ].distanceToPoint( point ) < 0 ) {
  19591. return false;
  19592. }
  19593. }
  19594. return true;
  19595. }
  19596. /**
  19597. * Returns a new frustum with copied values from this instance.
  19598. *
  19599. * @return {Frustum} A clone of this instance.
  19600. */
  19601. clone() {
  19602. return new this.constructor().copy( this );
  19603. }
  19604. }
  19605. const _projScreenMatrix$2 = /*@__PURE__*/ new Matrix4();
  19606. const _frustum$1 = /*@__PURE__*/ new Frustum();
  19607. /**
  19608. * FrustumArray is used to determine if an object is visible in at least one camera
  19609. * from an array of cameras. This is particularly useful for multi-view renderers.
  19610. */
  19611. class FrustumArray {
  19612. /**
  19613. * Constructs a new frustum array.
  19614. *
  19615. */
  19616. constructor() {
  19617. /**
  19618. * The coordinate system to use.
  19619. *
  19620. * @type {WebGLCoordinateSystem|WebGPUCoordinateSystem}
  19621. * @default WebGLCoordinateSystem
  19622. */
  19623. this.coordinateSystem = WebGLCoordinateSystem;
  19624. }
  19625. /**
  19626. * Returns `true` if the 3D object's bounding sphere is intersecting any frustum
  19627. * from the camera array.
  19628. *
  19629. * @param {Object3D} object - The 3D object to test.
  19630. * @param {Object} cameraArray - An object with a cameras property containing an array of cameras.
  19631. * @return {boolean} Whether the 3D object is visible in any camera.
  19632. */
  19633. intersectsObject( object, cameraArray ) {
  19634. if ( ! cameraArray.isArrayCamera || cameraArray.cameras.length === 0 ) {
  19635. return false;
  19636. }
  19637. for ( let i = 0; i < cameraArray.cameras.length; i ++ ) {
  19638. const camera = cameraArray.cameras[ i ];
  19639. _projScreenMatrix$2.multiplyMatrices(
  19640. camera.projectionMatrix,
  19641. camera.matrixWorldInverse
  19642. );
  19643. _frustum$1.setFromProjectionMatrix(
  19644. _projScreenMatrix$2,
  19645. this.coordinateSystem
  19646. );
  19647. if ( _frustum$1.intersectsObject( object ) ) {
  19648. return true; // Object is visible in at least one camera
  19649. }
  19650. }
  19651. return false; // Not visible in any camera
  19652. }
  19653. /**
  19654. * Returns `true` if the given sprite is intersecting any frustum
  19655. * from the camera array.
  19656. *
  19657. * @param {Sprite} sprite - The sprite to test.
  19658. * @param {Object} cameraArray - An object with a cameras property containing an array of cameras.
  19659. * @return {boolean} Whether the sprite is visible in any camera.
  19660. */
  19661. intersectsSprite( sprite, cameraArray ) {
  19662. if ( ! cameraArray || ! cameraArray.cameras || cameraArray.cameras.length === 0 ) {
  19663. return false;
  19664. }
  19665. for ( let i = 0; i < cameraArray.cameras.length; i ++ ) {
  19666. const camera = cameraArray.cameras[ i ];
  19667. _projScreenMatrix$2.multiplyMatrices(
  19668. camera.projectionMatrix,
  19669. camera.matrixWorldInverse
  19670. );
  19671. _frustum$1.setFromProjectionMatrix(
  19672. _projScreenMatrix$2,
  19673. this.coordinateSystem
  19674. );
  19675. if ( _frustum$1.intersectsSprite( sprite ) ) {
  19676. return true; // Sprite is visible in at least one camera
  19677. }
  19678. }
  19679. return false; // Not visible in any camera
  19680. }
  19681. /**
  19682. * Returns `true` if the given bounding sphere is intersecting any frustum
  19683. * from the camera array.
  19684. *
  19685. * @param {Sphere} sphere - The bounding sphere to test.
  19686. * @param {Object} cameraArray - An object with a cameras property containing an array of cameras.
  19687. * @return {boolean} Whether the sphere is visible in any camera.
  19688. */
  19689. intersectsSphere( sphere, cameraArray ) {
  19690. if ( ! cameraArray || ! cameraArray.cameras || cameraArray.cameras.length === 0 ) {
  19691. return false;
  19692. }
  19693. for ( let i = 0; i < cameraArray.cameras.length; i ++ ) {
  19694. const camera = cameraArray.cameras[ i ];
  19695. _projScreenMatrix$2.multiplyMatrices(
  19696. camera.projectionMatrix,
  19697. camera.matrixWorldInverse
  19698. );
  19699. _frustum$1.setFromProjectionMatrix(
  19700. _projScreenMatrix$2,
  19701. this.coordinateSystem
  19702. );
  19703. if ( _frustum$1.intersectsSphere( sphere ) ) {
  19704. return true; // Sphere is visible in at least one camera
  19705. }
  19706. }
  19707. return false; // Not visible in any camera
  19708. }
  19709. /**
  19710. * Returns `true` if the given bounding box is intersecting any frustum
  19711. * from the camera array.
  19712. *
  19713. * @param {Box3} box - The bounding box to test.
  19714. * @param {Object} cameraArray - An object with a cameras property containing an array of cameras.
  19715. * @return {boolean} Whether the box is visible in any camera.
  19716. */
  19717. intersectsBox( box, cameraArray ) {
  19718. if ( ! cameraArray || ! cameraArray.cameras || cameraArray.cameras.length === 0 ) {
  19719. return false;
  19720. }
  19721. for ( let i = 0; i < cameraArray.cameras.length; i ++ ) {
  19722. const camera = cameraArray.cameras[ i ];
  19723. _projScreenMatrix$2.multiplyMatrices(
  19724. camera.projectionMatrix,
  19725. camera.matrixWorldInverse
  19726. );
  19727. _frustum$1.setFromProjectionMatrix(
  19728. _projScreenMatrix$2,
  19729. this.coordinateSystem
  19730. );
  19731. if ( _frustum$1.intersectsBox( box ) ) {
  19732. return true; // Box is visible in at least one camera
  19733. }
  19734. }
  19735. return false; // Not visible in any camera
  19736. }
  19737. /**
  19738. * Returns `true` if the given point lies within any frustum
  19739. * from the camera array.
  19740. *
  19741. * @param {Vector3} point - The point to test.
  19742. * @param {Object} cameraArray - An object with a cameras property containing an array of cameras.
  19743. * @return {boolean} Whether the point is visible in any camera.
  19744. */
  19745. containsPoint( point, cameraArray ) {
  19746. if ( ! cameraArray || ! cameraArray.cameras || cameraArray.cameras.length === 0 ) {
  19747. return false;
  19748. }
  19749. for ( let i = 0; i < cameraArray.cameras.length; i ++ ) {
  19750. const camera = cameraArray.cameras[ i ];
  19751. _projScreenMatrix$2.multiplyMatrices(
  19752. camera.projectionMatrix,
  19753. camera.matrixWorldInverse
  19754. );
  19755. _frustum$1.setFromProjectionMatrix(
  19756. _projScreenMatrix$2,
  19757. this.coordinateSystem
  19758. );
  19759. if ( _frustum$1.containsPoint( point ) ) {
  19760. return true; // Point is visible in at least one camera
  19761. }
  19762. }
  19763. return false; // Not visible in any camera
  19764. }
  19765. /**
  19766. * Returns a new frustum array with copied values from this instance.
  19767. *
  19768. * @return {FrustumArray} A clone of this instance.
  19769. */
  19770. clone() {
  19771. return new FrustumArray();
  19772. }
  19773. }
  19774. function ascIdSort( a, b ) {
  19775. return a - b;
  19776. }
  19777. function sortOpaque( a, b ) {
  19778. return a.z - b.z;
  19779. }
  19780. function sortTransparent( a, b ) {
  19781. return b.z - a.z;
  19782. }
  19783. class MultiDrawRenderList {
  19784. constructor() {
  19785. this.index = 0;
  19786. this.pool = [];
  19787. this.list = [];
  19788. }
  19789. push( start, count, z, index ) {
  19790. const pool = this.pool;
  19791. const list = this.list;
  19792. if ( this.index >= pool.length ) {
  19793. pool.push( {
  19794. start: -1,
  19795. count: -1,
  19796. z: -1,
  19797. index: -1,
  19798. } );
  19799. }
  19800. const item = pool[ this.index ];
  19801. list.push( item );
  19802. this.index ++;
  19803. item.start = start;
  19804. item.count = count;
  19805. item.z = z;
  19806. item.index = index;
  19807. }
  19808. reset() {
  19809. this.list.length = 0;
  19810. this.index = 0;
  19811. }
  19812. }
  19813. const _matrix$1 = /*@__PURE__*/ new Matrix4();
  19814. const _whiteColor = /*@__PURE__*/ new Color( 1, 1, 1 );
  19815. const _frustum = /*@__PURE__*/ new Frustum();
  19816. const _frustumArray = /*@__PURE__*/ new FrustumArray();
  19817. const _box$1 = /*@__PURE__*/ new Box3();
  19818. const _sphere$2 = /*@__PURE__*/ new Sphere();
  19819. const _vector$5 = /*@__PURE__*/ new Vector3();
  19820. const _forward$1 = /*@__PURE__*/ new Vector3();
  19821. const _temp = /*@__PURE__*/ new Vector3();
  19822. const _renderList = /*@__PURE__*/ new MultiDrawRenderList();
  19823. const _mesh = /*@__PURE__*/ new Mesh();
  19824. const _batchIntersects = [];
  19825. // copies data from attribute "src" into "target" starting at "targetOffset"
  19826. function copyAttributeData( src, target, targetOffset = 0 ) {
  19827. const itemSize = target.itemSize;
  19828. if ( src.isInterleavedBufferAttribute || src.array.constructor !== target.array.constructor ) {
  19829. // use the component getters and setters if the array data cannot
  19830. // be copied directly
  19831. const vertexCount = src.count;
  19832. for ( let i = 0; i < vertexCount; i ++ ) {
  19833. for ( let c = 0; c < itemSize; c ++ ) {
  19834. target.setComponent( i + targetOffset, c, src.getComponent( i, c ) );
  19835. }
  19836. }
  19837. } else {
  19838. // faster copy approach using typed array set function
  19839. target.array.set( src.array, targetOffset * itemSize );
  19840. }
  19841. target.needsUpdate = true;
  19842. }
  19843. // safely copies array contents to a potentially smaller array
  19844. function copyArrayContents( src, target ) {
  19845. if ( src.constructor !== target.constructor ) {
  19846. // if arrays are of a different type (eg due to index size increasing) then data must be per-element copied
  19847. const len = Math.min( src.length, target.length );
  19848. for ( let i = 0; i < len; i ++ ) {
  19849. target[ i ] = src[ i ];
  19850. }
  19851. } else {
  19852. // if the arrays use the same data layout we can use a fast block copy
  19853. const len = Math.min( src.length, target.length );
  19854. target.set( new src.constructor( src.buffer, 0, len ) );
  19855. }
  19856. }
  19857. /**
  19858. * A special version of a mesh with multi draw batch rendering support. Use
  19859. * this class if you have to render a large number of objects with the same
  19860. * material but with different geometries or world transformations. The usage of
  19861. * `BatchedMesh` will help you to reduce the number of draw calls and thus improve the overall
  19862. * rendering performance in your application.
  19863. *
  19864. * ```js
  19865. * const box = new THREE.BoxGeometry( 1, 1, 1 );
  19866. * const sphere = new THREE.SphereGeometry( 1, 12, 12 );
  19867. * const material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } );
  19868. *
  19869. * // initialize and add geometries into the batched mesh
  19870. * const batchedMesh = new BatchedMesh( 10, 5000, 10000, material );
  19871. * const boxGeometryId = batchedMesh.addGeometry( box );
  19872. * const sphereGeometryId = batchedMesh.addGeometry( sphere );
  19873. *
  19874. * // create instances of those geometries
  19875. * const boxInstancedId1 = batchedMesh.addInstance( boxGeometryId );
  19876. * const boxInstancedId2 = batchedMesh.addInstance( boxGeometryId );
  19877. *
  19878. * const sphereInstancedId1 = batchedMesh.addInstance( sphereGeometryId );
  19879. * const sphereInstancedId2 = batchedMesh.addInstance( sphereGeometryId );
  19880. *
  19881. * // position the geometries
  19882. * batchedMesh.setMatrixAt( boxInstancedId1, boxMatrix1 );
  19883. * batchedMesh.setMatrixAt( boxInstancedId2, boxMatrix2 );
  19884. *
  19885. * batchedMesh.setMatrixAt( sphereInstancedId1, sphereMatrix1 );
  19886. * batchedMesh.setMatrixAt( sphereInstancedId2, sphereMatrix2 );
  19887. *
  19888. * scene.add( batchedMesh );
  19889. * ```
  19890. *
  19891. * @augments Mesh
  19892. */
  19893. class BatchedMesh extends Mesh {
  19894. /**
  19895. * Constructs a new batched mesh.
  19896. *
  19897. * @param {number} maxInstanceCount - The maximum number of individual instances planned to be added and rendered.
  19898. * @param {number} maxVertexCount - The maximum number of vertices to be used by all unique geometries.
  19899. * @param {number} [maxIndexCount=maxVertexCount*2] - The maximum number of indices to be used by all unique geometries
  19900. * @param {Material|Array<Material>} [material] - The mesh material.
  19901. */
  19902. constructor( maxInstanceCount, maxVertexCount, maxIndexCount = maxVertexCount * 2, material ) {
  19903. super( new BufferGeometry(), material );
  19904. /**
  19905. * This flag can be used for type testing.
  19906. *
  19907. * @type {boolean}
  19908. * @readonly
  19909. * @default true
  19910. */
  19911. this.isBatchedMesh = true;
  19912. /**
  19913. * When set ot `true`, the individual objects of a batch are frustum culled.
  19914. *
  19915. * @type {boolean}
  19916. * @default true
  19917. */
  19918. this.perObjectFrustumCulled = true;
  19919. /**
  19920. * When set to `true`, the individual objects of a batch are sorted to improve overdraw-related artifacts.
  19921. * If the material is marked as "transparent" objects are rendered back to front and if not then they are
  19922. * rendered front to back.
  19923. *
  19924. * @type {boolean}
  19925. * @default true
  19926. */
  19927. this.sortObjects = true;
  19928. /**
  19929. * The bounding box of the batched mesh. Can be computed via {@link BatchedMesh#computeBoundingBox}.
  19930. *
  19931. * @type {?Box3}
  19932. * @default null
  19933. */
  19934. this.boundingBox = null;
  19935. /**
  19936. * The bounding sphere of the batched mesh. Can be computed via {@link BatchedMesh#computeBoundingSphere}.
  19937. *
  19938. * @type {?Sphere}
  19939. * @default null
  19940. */
  19941. this.boundingSphere = null;
  19942. /**
  19943. * Takes a sort a function that is run before render. The function takes a list of instances to
  19944. * sort and a camera. The objects in the list include a "z" field to perform a depth-ordered
  19945. * sort with.
  19946. *
  19947. * @type {?Function}
  19948. * @default null
  19949. */
  19950. this.customSort = null;
  19951. // stores visible, active, and geometry id per instance and reserved buffer ranges for geometries
  19952. this._instanceInfo = [];
  19953. this._geometryInfo = [];
  19954. // instance, geometry ids that have been set as inactive, and are available to be overwritten
  19955. this._availableInstanceIds = [];
  19956. this._availableGeometryIds = [];
  19957. // used to track where the next point is that geometry should be inserted
  19958. this._nextIndexStart = 0;
  19959. this._nextVertexStart = 0;
  19960. this._geometryCount = 0;
  19961. // flags
  19962. this._visibilityChanged = true;
  19963. this._geometryInitialized = false;
  19964. // cached user options
  19965. this._maxInstanceCount = maxInstanceCount;
  19966. this._maxVertexCount = maxVertexCount;
  19967. this._maxIndexCount = maxIndexCount;
  19968. // buffers for multi draw
  19969. this._multiDrawCounts = new Int32Array( maxInstanceCount );
  19970. this._multiDrawStarts = new Int32Array( maxInstanceCount );
  19971. this._multiDrawCount = 0;
  19972. this._multiDrawInstances = null;
  19973. // Local matrix per geometry by using data texture
  19974. this._matricesTexture = null;
  19975. this._indirectTexture = null;
  19976. this._colorsTexture = null;
  19977. this._initMatricesTexture();
  19978. this._initIndirectTexture();
  19979. }
  19980. /**
  19981. * The maximum number of individual instances that can be stored in the batch.
  19982. *
  19983. * @type {number}
  19984. * @readonly
  19985. */
  19986. get maxInstanceCount() {
  19987. return this._maxInstanceCount;
  19988. }
  19989. /**
  19990. * The instance count.
  19991. *
  19992. * @type {number}
  19993. * @readonly
  19994. */
  19995. get instanceCount() {
  19996. return this._instanceInfo.length - this._availableInstanceIds.length;
  19997. }
  19998. /**
  19999. * The number of unused vertices.
  20000. *
  20001. * @type {number}
  20002. * @readonly
  20003. */
  20004. get unusedVertexCount() {
  20005. return this._maxVertexCount - this._nextVertexStart;
  20006. }
  20007. /**
  20008. * The number of unused indices.
  20009. *
  20010. * @type {number}
  20011. * @readonly
  20012. */
  20013. get unusedIndexCount() {
  20014. return this._maxIndexCount - this._nextIndexStart;
  20015. }
  20016. _initMatricesTexture() {
  20017. // layout (1 matrix = 4 pixels)
  20018. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  20019. // with 8x8 pixel texture max 16 matrices * 4 pixels = (8 * 8)
  20020. // 16x16 pixel texture max 64 matrices * 4 pixels = (16 * 16)
  20021. // 32x32 pixel texture max 256 matrices * 4 pixels = (32 * 32)
  20022. // 64x64 pixel texture max 1024 matrices * 4 pixels = (64 * 64)
  20023. let size = Math.sqrt( this._maxInstanceCount * 4 ); // 4 pixels needed for 1 matrix
  20024. size = Math.ceil( size / 4 ) * 4;
  20025. size = Math.max( size, 4 );
  20026. const matricesArray = new Float32Array( size * size * 4 ); // 4 floats per RGBA pixel
  20027. const matricesTexture = new DataTexture( matricesArray, size, size, RGBAFormat, FloatType );
  20028. this._matricesTexture = matricesTexture;
  20029. }
  20030. _initIndirectTexture() {
  20031. let size = Math.sqrt( this._maxInstanceCount );
  20032. size = Math.ceil( size );
  20033. const indirectArray = new Uint32Array( size * size );
  20034. const indirectTexture = new DataTexture( indirectArray, size, size, RedIntegerFormat, UnsignedIntType );
  20035. this._indirectTexture = indirectTexture;
  20036. }
  20037. _initColorsTexture() {
  20038. let size = Math.sqrt( this._maxInstanceCount );
  20039. size = Math.ceil( size );
  20040. // 4 floats per RGBA pixel initialized to white
  20041. const colorsArray = new Float32Array( size * size * 4 ).fill( 1 );
  20042. const colorsTexture = new DataTexture( colorsArray, size, size, RGBAFormat, FloatType );
  20043. colorsTexture.colorSpace = ColorManagement.workingColorSpace;
  20044. this._colorsTexture = colorsTexture;
  20045. }
  20046. _initializeGeometry( reference ) {
  20047. const geometry = this.geometry;
  20048. const maxVertexCount = this._maxVertexCount;
  20049. const maxIndexCount = this._maxIndexCount;
  20050. if ( this._geometryInitialized === false ) {
  20051. for ( const attributeName in reference.attributes ) {
  20052. const srcAttribute = reference.getAttribute( attributeName );
  20053. const { array, itemSize, normalized } = srcAttribute;
  20054. const dstArray = new array.constructor( maxVertexCount * itemSize );
  20055. const dstAttribute = new BufferAttribute( dstArray, itemSize, normalized );
  20056. geometry.setAttribute( attributeName, dstAttribute );
  20057. }
  20058. if ( reference.getIndex() !== null ) {
  20059. // Reserve last u16 index for primitive restart.
  20060. const indexArray = maxVertexCount > 65535
  20061. ? new Uint32Array( maxIndexCount )
  20062. : new Uint16Array( maxIndexCount );
  20063. geometry.setIndex( new BufferAttribute( indexArray, 1 ) );
  20064. }
  20065. this._geometryInitialized = true;
  20066. }
  20067. }
  20068. // Make sure the geometry is compatible with the existing combined geometry attributes
  20069. _validateGeometry( geometry ) {
  20070. // check to ensure the geometries are using consistent attributes and indices
  20071. const batchGeometry = this.geometry;
  20072. if ( Boolean( geometry.getIndex() ) !== Boolean( batchGeometry.getIndex() ) ) {
  20073. throw new Error( 'THREE.BatchedMesh: All geometries must consistently have "index".' );
  20074. }
  20075. for ( const attributeName in batchGeometry.attributes ) {
  20076. if ( ! geometry.hasAttribute( attributeName ) ) {
  20077. throw new Error( `THREE.BatchedMesh: Added geometry missing "${ attributeName }". All geometries must have consistent attributes.` );
  20078. }
  20079. const srcAttribute = geometry.getAttribute( attributeName );
  20080. const dstAttribute = batchGeometry.getAttribute( attributeName );
  20081. if ( srcAttribute.itemSize !== dstAttribute.itemSize || srcAttribute.normalized !== dstAttribute.normalized ) {
  20082. throw new Error( 'THREE.BatchedMesh: All attributes must have a consistent itemSize and normalized value.' );
  20083. }
  20084. }
  20085. }
  20086. /**
  20087. * Validates the instance defined by the given ID.
  20088. *
  20089. * @param {number} instanceId - The instance to validate.
  20090. */
  20091. validateInstanceId( instanceId ) {
  20092. const instanceInfo = this._instanceInfo;
  20093. if ( instanceId < 0 || instanceId >= instanceInfo.length || instanceInfo[ instanceId ].active === false ) {
  20094. throw new Error( `THREE.BatchedMesh: Invalid instanceId ${instanceId}. Instance is either out of range or has been deleted.` );
  20095. }
  20096. }
  20097. /**
  20098. * Validates the geometry defined by the given ID.
  20099. *
  20100. * @param {number} geometryId - The geometry to validate.
  20101. */
  20102. validateGeometryId( geometryId ) {
  20103. const geometryInfoList = this._geometryInfo;
  20104. if ( geometryId < 0 || geometryId >= geometryInfoList.length || geometryInfoList[ geometryId ].active === false ) {
  20105. throw new Error( `THREE.BatchedMesh: Invalid geometryId ${geometryId}. Geometry is either out of range or has been deleted.` );
  20106. }
  20107. }
  20108. /**
  20109. * Takes a sort a function that is run before render. The function takes a list of instances to
  20110. * sort and a camera. The objects in the list include a "z" field to perform a depth-ordered sort with.
  20111. *
  20112. * @param {Function} func - The custom sort function.
  20113. * @return {BatchedMesh} A reference to this batched mesh.
  20114. */
  20115. setCustomSort( func ) {
  20116. this.customSort = func;
  20117. return this;
  20118. }
  20119. /**
  20120. * Computes the bounding box, updating {@link BatchedMesh#boundingBox}.
  20121. * Bounding boxes aren't computed by default. They need to be explicitly computed,
  20122. * otherwise they are `null`.
  20123. */
  20124. computeBoundingBox() {
  20125. if ( this.boundingBox === null ) {
  20126. this.boundingBox = new Box3();
  20127. }
  20128. const boundingBox = this.boundingBox;
  20129. const instanceInfo = this._instanceInfo;
  20130. boundingBox.makeEmpty();
  20131. for ( let i = 0, l = instanceInfo.length; i < l; i ++ ) {
  20132. if ( instanceInfo[ i ].active === false ) continue;
  20133. const geometryId = instanceInfo[ i ].geometryIndex;
  20134. this.getMatrixAt( i, _matrix$1 );
  20135. this.getBoundingBoxAt( geometryId, _box$1 ).applyMatrix4( _matrix$1 );
  20136. boundingBox.union( _box$1 );
  20137. }
  20138. }
  20139. /**
  20140. * Computes the bounding sphere, updating {@link BatchedMesh#boundingSphere}.
  20141. * Bounding spheres aren't computed by default. They need to be explicitly computed,
  20142. * otherwise they are `null`.
  20143. */
  20144. computeBoundingSphere() {
  20145. if ( this.boundingSphere === null ) {
  20146. this.boundingSphere = new Sphere();
  20147. }
  20148. const boundingSphere = this.boundingSphere;
  20149. const instanceInfo = this._instanceInfo;
  20150. boundingSphere.makeEmpty();
  20151. for ( let i = 0, l = instanceInfo.length; i < l; i ++ ) {
  20152. if ( instanceInfo[ i ].active === false ) continue;
  20153. const geometryId = instanceInfo[ i ].geometryIndex;
  20154. this.getMatrixAt( i, _matrix$1 );
  20155. this.getBoundingSphereAt( geometryId, _sphere$2 ).applyMatrix4( _matrix$1 );
  20156. boundingSphere.union( _sphere$2 );
  20157. }
  20158. }
  20159. /**
  20160. * Adds a new instance to the batch using the geometry of the given ID and returns
  20161. * a new id referring to the new instance to be used by other functions.
  20162. *
  20163. * @param {number} geometryId - The ID of a previously added geometry via {@link BatchedMesh#addGeometry}.
  20164. * @return {number} The instance ID.
  20165. */
  20166. addInstance( geometryId ) {
  20167. const atCapacity = this._instanceInfo.length >= this.maxInstanceCount;
  20168. // ensure we're not over geometry
  20169. if ( atCapacity && this._availableInstanceIds.length === 0 ) {
  20170. throw new Error( 'THREE.BatchedMesh: Maximum item count reached.' );
  20171. }
  20172. const instanceInfo = {
  20173. visible: true,
  20174. active: true,
  20175. geometryIndex: geometryId,
  20176. };
  20177. let drawId = null;
  20178. // Prioritize using previously freed instance ids
  20179. if ( this._availableInstanceIds.length > 0 ) {
  20180. this._availableInstanceIds.sort( ascIdSort );
  20181. drawId = this._availableInstanceIds.shift();
  20182. this._instanceInfo[ drawId ] = instanceInfo;
  20183. } else {
  20184. drawId = this._instanceInfo.length;
  20185. this._instanceInfo.push( instanceInfo );
  20186. }
  20187. const matricesTexture = this._matricesTexture;
  20188. _matrix$1.identity().toArray( matricesTexture.image.data, drawId * 16 );
  20189. matricesTexture.needsUpdate = true;
  20190. const colorsTexture = this._colorsTexture;
  20191. if ( colorsTexture ) {
  20192. _whiteColor.toArray( colorsTexture.image.data, drawId * 4 );
  20193. colorsTexture.needsUpdate = true;
  20194. }
  20195. this._visibilityChanged = true;
  20196. return drawId;
  20197. }
  20198. /**
  20199. * Adds the given geometry to the batch and returns the associated
  20200. * geometry id referring to it to be used in other functions.
  20201. *
  20202. * @param {BufferGeometry} geometry - The geometry to add.
  20203. * @param {number} [reservedVertexCount=-1] - Optional parameter specifying the amount of
  20204. * vertex buffer space to reserve for the added geometry. This is necessary if it is planned
  20205. * to set a new geometry at this index at a later time that is larger than the original geometry.
  20206. * Defaults to the length of the given geometry vertex buffer.
  20207. * @param {number} [reservedIndexCount=-1] - Optional parameter specifying the amount of index
  20208. * buffer space to reserve for the added geometry. This is necessary if it is planned to set a
  20209. * new geometry at this index at a later time that is larger than the original geometry. Defaults to
  20210. * the length of the given geometry index buffer.
  20211. * @return {number} The geometry ID.
  20212. */
  20213. addGeometry( geometry, reservedVertexCount = -1, reservedIndexCount = -1 ) {
  20214. this._initializeGeometry( geometry );
  20215. this._validateGeometry( geometry );
  20216. const geometryInfo = {
  20217. // geometry information
  20218. vertexStart: -1,
  20219. vertexCount: -1,
  20220. reservedVertexCount: -1,
  20221. indexStart: -1,
  20222. indexCount: -1,
  20223. reservedIndexCount: -1,
  20224. // draw range information
  20225. start: -1,
  20226. count: -1,
  20227. // state
  20228. boundingBox: null,
  20229. boundingSphere: null,
  20230. active: true,
  20231. };
  20232. const geometryInfoList = this._geometryInfo;
  20233. geometryInfo.vertexStart = this._nextVertexStart;
  20234. geometryInfo.reservedVertexCount = reservedVertexCount === -1 ? geometry.getAttribute( 'position' ).count : reservedVertexCount;
  20235. const index = geometry.getIndex();
  20236. const hasIndex = index !== null;
  20237. if ( hasIndex ) {
  20238. geometryInfo.indexStart = this._nextIndexStart;
  20239. geometryInfo.reservedIndexCount = reservedIndexCount === -1 ? index.count : reservedIndexCount;
  20240. }
  20241. if (
  20242. geometryInfo.indexStart !== -1 &&
  20243. geometryInfo.indexStart + geometryInfo.reservedIndexCount > this._maxIndexCount ||
  20244. geometryInfo.vertexStart + geometryInfo.reservedVertexCount > this._maxVertexCount
  20245. ) {
  20246. throw new Error( 'THREE.BatchedMesh: Reserved space request exceeds the maximum buffer size.' );
  20247. }
  20248. // update id
  20249. let geometryId;
  20250. if ( this._availableGeometryIds.length > 0 ) {
  20251. this._availableGeometryIds.sort( ascIdSort );
  20252. geometryId = this._availableGeometryIds.shift();
  20253. geometryInfoList[ geometryId ] = geometryInfo;
  20254. } else {
  20255. geometryId = this._geometryCount;
  20256. this._geometryCount ++;
  20257. geometryInfoList.push( geometryInfo );
  20258. }
  20259. // update the geometry
  20260. this.setGeometryAt( geometryId, geometry );
  20261. // increment the next geometry position
  20262. this._nextIndexStart = geometryInfo.indexStart + geometryInfo.reservedIndexCount;
  20263. this._nextVertexStart = geometryInfo.vertexStart + geometryInfo.reservedVertexCount;
  20264. return geometryId;
  20265. }
  20266. /**
  20267. * Replaces the geometry at the given ID with the provided geometry. Throws an error if there
  20268. * is not enough space reserved for geometry. Calling this will change all instances that are
  20269. * rendering that geometry.
  20270. *
  20271. * @param {number} geometryId - The ID of the geometry that should be replaced with the given geometry.
  20272. * @param {BufferGeometry} geometry - The new geometry.
  20273. * @return {number} The geometry ID.
  20274. */
  20275. setGeometryAt( geometryId, geometry ) {
  20276. if ( geometryId >= this._geometryCount ) {
  20277. throw new Error( 'THREE.BatchedMesh: Maximum geometry count reached.' );
  20278. }
  20279. this._validateGeometry( geometry );
  20280. const batchGeometry = this.geometry;
  20281. const hasIndex = batchGeometry.getIndex() !== null;
  20282. const dstIndex = batchGeometry.getIndex();
  20283. const srcIndex = geometry.getIndex();
  20284. const geometryInfo = this._geometryInfo[ geometryId ];
  20285. if (
  20286. hasIndex &&
  20287. srcIndex.count > geometryInfo.reservedIndexCount ||
  20288. geometry.attributes.position.count > geometryInfo.reservedVertexCount
  20289. ) {
  20290. throw new Error( 'THREE.BatchedMesh: Reserved space not large enough for provided geometry.' );
  20291. }
  20292. // copy geometry buffer data over
  20293. const vertexStart = geometryInfo.vertexStart;
  20294. const reservedVertexCount = geometryInfo.reservedVertexCount;
  20295. geometryInfo.vertexCount = geometry.getAttribute( 'position' ).count;
  20296. for ( const attributeName in batchGeometry.attributes ) {
  20297. // copy attribute data
  20298. const srcAttribute = geometry.getAttribute( attributeName );
  20299. const dstAttribute = batchGeometry.getAttribute( attributeName );
  20300. copyAttributeData( srcAttribute, dstAttribute, vertexStart );
  20301. // fill the rest in with zeroes
  20302. const itemSize = srcAttribute.itemSize;
  20303. for ( let i = srcAttribute.count, l = reservedVertexCount; i < l; i ++ ) {
  20304. const index = vertexStart + i;
  20305. for ( let c = 0; c < itemSize; c ++ ) {
  20306. dstAttribute.setComponent( index, c, 0 );
  20307. }
  20308. }
  20309. dstAttribute.needsUpdate = true;
  20310. dstAttribute.addUpdateRange( vertexStart * itemSize, reservedVertexCount * itemSize );
  20311. }
  20312. // copy index
  20313. if ( hasIndex ) {
  20314. const indexStart = geometryInfo.indexStart;
  20315. const reservedIndexCount = geometryInfo.reservedIndexCount;
  20316. geometryInfo.indexCount = geometry.getIndex().count;
  20317. // copy index data over
  20318. for ( let i = 0; i < srcIndex.count; i ++ ) {
  20319. dstIndex.setX( indexStart + i, vertexStart + srcIndex.getX( i ) );
  20320. }
  20321. // fill the rest in with zeroes
  20322. for ( let i = srcIndex.count, l = reservedIndexCount; i < l; i ++ ) {
  20323. dstIndex.setX( indexStart + i, vertexStart );
  20324. }
  20325. dstIndex.needsUpdate = true;
  20326. dstIndex.addUpdateRange( indexStart, geometryInfo.reservedIndexCount );
  20327. }
  20328. // update the draw range
  20329. geometryInfo.start = hasIndex ? geometryInfo.indexStart : geometryInfo.vertexStart;
  20330. geometryInfo.count = hasIndex ? geometryInfo.indexCount : geometryInfo.vertexCount;
  20331. // store the bounding boxes
  20332. geometryInfo.boundingBox = null;
  20333. if ( geometry.boundingBox !== null ) {
  20334. geometryInfo.boundingBox = geometry.boundingBox.clone();
  20335. }
  20336. geometryInfo.boundingSphere = null;
  20337. if ( geometry.boundingSphere !== null ) {
  20338. geometryInfo.boundingSphere = geometry.boundingSphere.clone();
  20339. }
  20340. this._visibilityChanged = true;
  20341. return geometryId;
  20342. }
  20343. /**
  20344. * Deletes the geometry defined by the given ID from this batch. Any instances referencing
  20345. * this geometry will also be removed as a side effect.
  20346. *
  20347. * @param {number} geometryId - The ID of the geometry to remove from the batch.
  20348. * @return {BatchedMesh} A reference to this batched mesh.
  20349. */
  20350. deleteGeometry( geometryId ) {
  20351. const geometryInfoList = this._geometryInfo;
  20352. if ( geometryId >= geometryInfoList.length || geometryInfoList[ geometryId ].active === false ) {
  20353. return this;
  20354. }
  20355. // delete any instances associated with this geometry
  20356. const instanceInfo = this._instanceInfo;
  20357. for ( let i = 0, l = instanceInfo.length; i < l; i ++ ) {
  20358. if ( instanceInfo[ i ].active && instanceInfo[ i ].geometryIndex === geometryId ) {
  20359. this.deleteInstance( i );
  20360. }
  20361. }
  20362. geometryInfoList[ geometryId ].active = false;
  20363. this._availableGeometryIds.push( geometryId );
  20364. this._visibilityChanged = true;
  20365. return this;
  20366. }
  20367. /**
  20368. * Deletes an existing instance from the batch using the given ID.
  20369. *
  20370. * @param {number} instanceId - The ID of the instance to remove from the batch.
  20371. * @return {BatchedMesh} A reference to this batched mesh.
  20372. */
  20373. deleteInstance( instanceId ) {
  20374. this.validateInstanceId( instanceId );
  20375. this._instanceInfo[ instanceId ].active = false;
  20376. this._availableInstanceIds.push( instanceId );
  20377. this._visibilityChanged = true;
  20378. return this;
  20379. }
  20380. /**
  20381. * Repacks the sub geometries in [name] to remove any unused space remaining from
  20382. * previously deleted geometry, freeing up space to add new geometry.
  20383. *
  20384. * @param {number} instanceId - The ID of the instance to remove from the batch.
  20385. * @return {BatchedMesh} A reference to this batched mesh.
  20386. */
  20387. optimize() {
  20388. // track the next indices to copy data to
  20389. let nextVertexStart = 0;
  20390. let nextIndexStart = 0;
  20391. // Iterate over all geometry ranges in order sorted from earliest in the geometry buffer to latest
  20392. // in the geometry buffer. Because draw range objects can be reused there is no guarantee of their order.
  20393. const geometryInfoList = this._geometryInfo;
  20394. const indices = geometryInfoList
  20395. .map( ( e, i ) => i )
  20396. .sort( ( a, b ) => {
  20397. return geometryInfoList[ a ].vertexStart - geometryInfoList[ b ].vertexStart;
  20398. } );
  20399. const geometry = this.geometry;
  20400. for ( let i = 0, l = geometryInfoList.length; i < l; i ++ ) {
  20401. // if a geometry range is inactive then don't copy anything
  20402. const index = indices[ i ];
  20403. const geometryInfo = geometryInfoList[ index ];
  20404. if ( geometryInfo.active === false ) {
  20405. continue;
  20406. }
  20407. // if a geometry contains an index buffer then shift it, as well
  20408. if ( geometry.index !== null ) {
  20409. if ( geometryInfo.indexStart !== nextIndexStart ) {
  20410. const { indexStart, vertexStart, reservedIndexCount } = geometryInfo;
  20411. const index = geometry.index;
  20412. const array = index.array;
  20413. // shift the index pointers based on how the vertex data will shift
  20414. // adjusting the index must happen first so the original vertex start value is available
  20415. const elementDelta = nextVertexStart - vertexStart;
  20416. for ( let j = indexStart; j < indexStart + reservedIndexCount; j ++ ) {
  20417. array[ j ] = array[ j ] + elementDelta;
  20418. }
  20419. index.array.copyWithin( nextIndexStart, indexStart, indexStart + reservedIndexCount );
  20420. index.addUpdateRange( nextIndexStart, reservedIndexCount );
  20421. geometryInfo.indexStart = nextIndexStart;
  20422. }
  20423. nextIndexStart += geometryInfo.reservedIndexCount;
  20424. }
  20425. // if a geometry needs to be moved then copy attribute data to overwrite unused space
  20426. if ( geometryInfo.vertexStart !== nextVertexStart ) {
  20427. const { vertexStart, reservedVertexCount } = geometryInfo;
  20428. const attributes = geometry.attributes;
  20429. for ( const key in attributes ) {
  20430. const attribute = attributes[ key ];
  20431. const { array, itemSize } = attribute;
  20432. array.copyWithin( nextVertexStart * itemSize, vertexStart * itemSize, ( vertexStart + reservedVertexCount ) * itemSize );
  20433. attribute.addUpdateRange( nextVertexStart * itemSize, reservedVertexCount * itemSize );
  20434. }
  20435. geometryInfo.vertexStart = nextVertexStart;
  20436. }
  20437. nextVertexStart += geometryInfo.reservedVertexCount;
  20438. geometryInfo.start = geometry.index ? geometryInfo.indexStart : geometryInfo.vertexStart;
  20439. // step the next geometry points to the shifted position
  20440. this._nextIndexStart = geometry.index ? geometryInfo.indexStart + geometryInfo.reservedIndexCount : 0;
  20441. this._nextVertexStart = geometryInfo.vertexStart + geometryInfo.reservedVertexCount;
  20442. }
  20443. return this;
  20444. }
  20445. /**
  20446. * Returns the bounding box for the given geometry.
  20447. *
  20448. * @param {number} geometryId - The ID of the geometry to return the bounding box for.
  20449. * @param {Box3} target - The target object that is used to store the method's result.
  20450. * @return {Box3|null} The geometry's bounding box. Returns `null` if no geometry has been found for the given ID.
  20451. */
  20452. getBoundingBoxAt( geometryId, target ) {
  20453. if ( geometryId >= this._geometryCount ) {
  20454. return null;
  20455. }
  20456. // compute bounding box
  20457. const geometry = this.geometry;
  20458. const geometryInfo = this._geometryInfo[ geometryId ];
  20459. if ( geometryInfo.boundingBox === null ) {
  20460. const box = new Box3();
  20461. const index = geometry.index;
  20462. const position = geometry.attributes.position;
  20463. for ( let i = geometryInfo.start, l = geometryInfo.start + geometryInfo.count; i < l; i ++ ) {
  20464. let iv = i;
  20465. if ( index ) {
  20466. iv = index.getX( iv );
  20467. }
  20468. box.expandByPoint( _vector$5.fromBufferAttribute( position, iv ) );
  20469. }
  20470. geometryInfo.boundingBox = box;
  20471. }
  20472. target.copy( geometryInfo.boundingBox );
  20473. return target;
  20474. }
  20475. /**
  20476. * Returns the bounding sphere for the given geometry.
  20477. *
  20478. * @param {number} geometryId - The ID of the geometry to return the bounding sphere for.
  20479. * @param {Sphere} target - The target object that is used to store the method's result.
  20480. * @return {Sphere|null} The geometry's bounding sphere. Returns `null` if no geometry has been found for the given ID.
  20481. */
  20482. getBoundingSphereAt( geometryId, target ) {
  20483. if ( geometryId >= this._geometryCount ) {
  20484. return null;
  20485. }
  20486. // compute bounding sphere
  20487. const geometry = this.geometry;
  20488. const geometryInfo = this._geometryInfo[ geometryId ];
  20489. if ( geometryInfo.boundingSphere === null ) {
  20490. const sphere = new Sphere();
  20491. this.getBoundingBoxAt( geometryId, _box$1 );
  20492. _box$1.getCenter( sphere.center );
  20493. const index = geometry.index;
  20494. const position = geometry.attributes.position;
  20495. let maxRadiusSq = 0;
  20496. for ( let i = geometryInfo.start, l = geometryInfo.start + geometryInfo.count; i < l; i ++ ) {
  20497. let iv = i;
  20498. if ( index ) {
  20499. iv = index.getX( iv );
  20500. }
  20501. _vector$5.fromBufferAttribute( position, iv );
  20502. maxRadiusSq = Math.max( maxRadiusSq, sphere.center.distanceToSquared( _vector$5 ) );
  20503. }
  20504. sphere.radius = Math.sqrt( maxRadiusSq );
  20505. geometryInfo.boundingSphere = sphere;
  20506. }
  20507. target.copy( geometryInfo.boundingSphere );
  20508. return target;
  20509. }
  20510. /**
  20511. * Sets the given local transformation matrix to the defined instance.
  20512. * Negatively scaled matrices are not supported.
  20513. *
  20514. * @param {number} instanceId - The ID of an instance to set the matrix of.
  20515. * @param {Matrix4} matrix - A 4x4 matrix representing the local transformation of a single instance.
  20516. * @return {BatchedMesh} A reference to this batched mesh.
  20517. */
  20518. setMatrixAt( instanceId, matrix ) {
  20519. this.validateInstanceId( instanceId );
  20520. const matricesTexture = this._matricesTexture;
  20521. const matricesArray = this._matricesTexture.image.data;
  20522. matrix.toArray( matricesArray, instanceId * 16 );
  20523. matricesTexture.needsUpdate = true;
  20524. return this;
  20525. }
  20526. /**
  20527. * Returns the local transformation matrix of the defined instance.
  20528. *
  20529. * @param {number} instanceId - The ID of an instance to get the matrix of.
  20530. * @param {Matrix4} matrix - The target object that is used to store the method's result.
  20531. * @return {Matrix4} The instance's local transformation matrix.
  20532. */
  20533. getMatrixAt( instanceId, matrix ) {
  20534. this.validateInstanceId( instanceId );
  20535. return matrix.fromArray( this._matricesTexture.image.data, instanceId * 16 );
  20536. }
  20537. /**
  20538. * Sets the given color to the defined instance.
  20539. *
  20540. * @param {number} instanceId - The ID of an instance to set the color of.
  20541. * @param {Color} color - The color to set the instance to.
  20542. * @return {BatchedMesh} A reference to this batched mesh.
  20543. */
  20544. setColorAt( instanceId, color ) {
  20545. this.validateInstanceId( instanceId );
  20546. if ( this._colorsTexture === null ) {
  20547. this._initColorsTexture();
  20548. }
  20549. color.toArray( this._colorsTexture.image.data, instanceId * 4 );
  20550. this._colorsTexture.needsUpdate = true;
  20551. return this;
  20552. }
  20553. /**
  20554. * Returns the color of the defined instance.
  20555. *
  20556. * @param {number} instanceId - The ID of an instance to get the color of.
  20557. * @param {Color} color - The target object that is used to store the method's result.
  20558. * @return {Color} The instance's color.
  20559. */
  20560. getColorAt( instanceId, color ) {
  20561. this.validateInstanceId( instanceId );
  20562. return color.fromArray( this._colorsTexture.image.data, instanceId * 4 );
  20563. }
  20564. /**
  20565. * Sets the visibility of the instance.
  20566. *
  20567. * @param {number} instanceId - The id of the instance to set the visibility of.
  20568. * @param {boolean} visible - Whether the instance is visible or not.
  20569. * @return {BatchedMesh} A reference to this batched mesh.
  20570. */
  20571. setVisibleAt( instanceId, visible ) {
  20572. this.validateInstanceId( instanceId );
  20573. if ( this._instanceInfo[ instanceId ].visible === visible ) {
  20574. return this;
  20575. }
  20576. this._instanceInfo[ instanceId ].visible = visible;
  20577. this._visibilityChanged = true;
  20578. return this;
  20579. }
  20580. /**
  20581. * Returns the visibility state of the defined instance.
  20582. *
  20583. * @param {number} instanceId - The ID of an instance to get the visibility state of.
  20584. * @return {boolean} Whether the instance is visible or not.
  20585. */
  20586. getVisibleAt( instanceId ) {
  20587. this.validateInstanceId( instanceId );
  20588. return this._instanceInfo[ instanceId ].visible;
  20589. }
  20590. /**
  20591. * Sets the geometry ID of the instance at the given index.
  20592. *
  20593. * @param {number} instanceId - The ID of the instance to set the geometry ID of.
  20594. * @param {number} geometryId - The geometry ID to be use by the instance.
  20595. * @return {BatchedMesh} A reference to this batched mesh.
  20596. */
  20597. setGeometryIdAt( instanceId, geometryId ) {
  20598. this.validateInstanceId( instanceId );
  20599. this.validateGeometryId( geometryId );
  20600. this._instanceInfo[ instanceId ].geometryIndex = geometryId;
  20601. return this;
  20602. }
  20603. /**
  20604. * Returns the geometry ID of the defined instance.
  20605. *
  20606. * @param {number} instanceId - The ID of an instance to get the geometry ID of.
  20607. * @return {number} The instance's geometry ID.
  20608. */
  20609. getGeometryIdAt( instanceId ) {
  20610. this.validateInstanceId( instanceId );
  20611. return this._instanceInfo[ instanceId ].geometryIndex;
  20612. }
  20613. /**
  20614. * Get the range representing the subset of triangles related to the attached geometry,
  20615. * indicating the starting offset and count, or `null` if invalid.
  20616. *
  20617. * @param {number} geometryId - The id of the geometry to get the range of.
  20618. * @param {Object} [target] - The target object that is used to store the method's result.
  20619. * @return {{
  20620. * vertexStart:number,vertexCount:number,reservedVertexCount:number,
  20621. * indexStart:number,indexCount:number,reservedIndexCount:number,
  20622. * start:number,count:number
  20623. * }} The result object with range data.
  20624. */
  20625. getGeometryRangeAt( geometryId, target = {} ) {
  20626. this.validateGeometryId( geometryId );
  20627. const geometryInfo = this._geometryInfo[ geometryId ];
  20628. target.vertexStart = geometryInfo.vertexStart;
  20629. target.vertexCount = geometryInfo.vertexCount;
  20630. target.reservedVertexCount = geometryInfo.reservedVertexCount;
  20631. target.indexStart = geometryInfo.indexStart;
  20632. target.indexCount = geometryInfo.indexCount;
  20633. target.reservedIndexCount = geometryInfo.reservedIndexCount;
  20634. target.start = geometryInfo.start;
  20635. target.count = geometryInfo.count;
  20636. return target;
  20637. }
  20638. /**
  20639. * Resizes the necessary buffers to support the provided number of instances.
  20640. * If the provided arguments shrink the number of instances but there are not enough
  20641. * unused Ids at the end of the list then an error is thrown.
  20642. *
  20643. * @param {number} maxInstanceCount - The max number of individual instances that can be added and rendered by the batch.
  20644. */
  20645. setInstanceCount( maxInstanceCount ) {
  20646. // shrink the available instances as much as possible
  20647. const availableInstanceIds = this._availableInstanceIds;
  20648. const instanceInfo = this._instanceInfo;
  20649. availableInstanceIds.sort( ascIdSort );
  20650. while ( availableInstanceIds[ availableInstanceIds.length - 1 ] === instanceInfo.length ) {
  20651. instanceInfo.pop();
  20652. availableInstanceIds.pop();
  20653. }
  20654. // throw an error if it can't be shrunk to the desired size
  20655. if ( maxInstanceCount < instanceInfo.length ) {
  20656. throw new Error( `BatchedMesh: Instance ids outside the range ${ maxInstanceCount } are being used. Cannot shrink instance count.` );
  20657. }
  20658. // copy the multi draw counts
  20659. const multiDrawCounts = new Int32Array( maxInstanceCount );
  20660. const multiDrawStarts = new Int32Array( maxInstanceCount );
  20661. copyArrayContents( this._multiDrawCounts, multiDrawCounts );
  20662. copyArrayContents( this._multiDrawStarts, multiDrawStarts );
  20663. this._multiDrawCounts = multiDrawCounts;
  20664. this._multiDrawStarts = multiDrawStarts;
  20665. this._maxInstanceCount = maxInstanceCount;
  20666. // update texture data for instance sampling
  20667. const indirectTexture = this._indirectTexture;
  20668. const matricesTexture = this._matricesTexture;
  20669. const colorsTexture = this._colorsTexture;
  20670. indirectTexture.dispose();
  20671. this._initIndirectTexture();
  20672. copyArrayContents( indirectTexture.image.data, this._indirectTexture.image.data );
  20673. matricesTexture.dispose();
  20674. this._initMatricesTexture();
  20675. copyArrayContents( matricesTexture.image.data, this._matricesTexture.image.data );
  20676. if ( colorsTexture ) {
  20677. colorsTexture.dispose();
  20678. this._initColorsTexture();
  20679. copyArrayContents( colorsTexture.image.data, this._colorsTexture.image.data );
  20680. }
  20681. }
  20682. /**
  20683. * Resizes the available space in the batch's vertex and index buffer attributes to the provided sizes.
  20684. * If the provided arguments shrink the geometry buffers but there is not enough unused space at the
  20685. * end of the geometry attributes then an error is thrown.
  20686. *
  20687. * @param {number} maxVertexCount - The maximum number of vertices to be used by all unique geometries to resize to.
  20688. * @param {number} maxIndexCount - The maximum number of indices to be used by all unique geometries to resize to.
  20689. */
  20690. setGeometrySize( maxVertexCount, maxIndexCount ) {
  20691. // Check if we can shrink to the requested vertex attribute size
  20692. const validRanges = [ ...this._geometryInfo ].filter( info => info.active );
  20693. const requiredVertexLength = Math.max( ...validRanges.map( range => range.vertexStart + range.reservedVertexCount ) );
  20694. if ( requiredVertexLength > maxVertexCount ) {
  20695. throw new Error( `BatchedMesh: Geometry vertex values are being used outside the range ${ maxIndexCount }. Cannot shrink further.` );
  20696. }
  20697. // Check if we can shrink to the requested index attribute size
  20698. if ( this.geometry.index ) {
  20699. const requiredIndexLength = Math.max( ...validRanges.map( range => range.indexStart + range.reservedIndexCount ) );
  20700. if ( requiredIndexLength > maxIndexCount ) {
  20701. throw new Error( `BatchedMesh: Geometry index values are being used outside the range ${ maxIndexCount }. Cannot shrink further.` );
  20702. }
  20703. }
  20704. //
  20705. // dispose of the previous geometry
  20706. const oldGeometry = this.geometry;
  20707. oldGeometry.dispose();
  20708. // recreate the geometry needed based on the previous variant
  20709. this._maxVertexCount = maxVertexCount;
  20710. this._maxIndexCount = maxIndexCount;
  20711. if ( this._geometryInitialized ) {
  20712. this._geometryInitialized = false;
  20713. this.geometry = new BufferGeometry();
  20714. this._initializeGeometry( oldGeometry );
  20715. }
  20716. // copy data from the previous geometry
  20717. const geometry = this.geometry;
  20718. if ( oldGeometry.index ) {
  20719. copyArrayContents( oldGeometry.index.array, geometry.index.array );
  20720. }
  20721. for ( const key in oldGeometry.attributes ) {
  20722. copyArrayContents( oldGeometry.attributes[ key ].array, geometry.attributes[ key ].array );
  20723. }
  20724. }
  20725. raycast( raycaster, intersects ) {
  20726. const instanceInfo = this._instanceInfo;
  20727. const geometryInfoList = this._geometryInfo;
  20728. const matrixWorld = this.matrixWorld;
  20729. const batchGeometry = this.geometry;
  20730. // iterate over each geometry
  20731. _mesh.material = this.material;
  20732. _mesh.geometry.index = batchGeometry.index;
  20733. _mesh.geometry.attributes = batchGeometry.attributes;
  20734. if ( _mesh.geometry.boundingBox === null ) {
  20735. _mesh.geometry.boundingBox = new Box3();
  20736. }
  20737. if ( _mesh.geometry.boundingSphere === null ) {
  20738. _mesh.geometry.boundingSphere = new Sphere();
  20739. }
  20740. for ( let i = 0, l = instanceInfo.length; i < l; i ++ ) {
  20741. if ( ! instanceInfo[ i ].visible || ! instanceInfo[ i ].active ) {
  20742. continue;
  20743. }
  20744. const geometryId = instanceInfo[ i ].geometryIndex;
  20745. const geometryInfo = geometryInfoList[ geometryId ];
  20746. _mesh.geometry.setDrawRange( geometryInfo.start, geometryInfo.count );
  20747. // get the intersects
  20748. this.getMatrixAt( i, _mesh.matrixWorld ).premultiply( matrixWorld );
  20749. this.getBoundingBoxAt( geometryId, _mesh.geometry.boundingBox );
  20750. this.getBoundingSphereAt( geometryId, _mesh.geometry.boundingSphere );
  20751. _mesh.raycast( raycaster, _batchIntersects );
  20752. // add batch id to the intersects
  20753. for ( let j = 0, l = _batchIntersects.length; j < l; j ++ ) {
  20754. const intersect = _batchIntersects[ j ];
  20755. intersect.object = this;
  20756. intersect.batchId = i;
  20757. intersects.push( intersect );
  20758. }
  20759. _batchIntersects.length = 0;
  20760. }
  20761. _mesh.material = null;
  20762. _mesh.geometry.index = null;
  20763. _mesh.geometry.attributes = {};
  20764. _mesh.geometry.setDrawRange( 0, Infinity );
  20765. }
  20766. copy( source ) {
  20767. super.copy( source );
  20768. this.geometry = source.geometry.clone();
  20769. this.perObjectFrustumCulled = source.perObjectFrustumCulled;
  20770. this.sortObjects = source.sortObjects;
  20771. this.boundingBox = source.boundingBox !== null ? source.boundingBox.clone() : null;
  20772. this.boundingSphere = source.boundingSphere !== null ? source.boundingSphere.clone() : null;
  20773. this._geometryInfo = source._geometryInfo.map( info => ( {
  20774. ...info,
  20775. boundingBox: info.boundingBox !== null ? info.boundingBox.clone() : null,
  20776. boundingSphere: info.boundingSphere !== null ? info.boundingSphere.clone() : null,
  20777. } ) );
  20778. this._instanceInfo = source._instanceInfo.map( info => ( { ...info } ) );
  20779. this._availableInstanceIds = source._availableInstanceIds.slice();
  20780. this._availableGeometryIds = source._availableGeometryIds.slice();
  20781. this._nextIndexStart = source._nextIndexStart;
  20782. this._nextVertexStart = source._nextVertexStart;
  20783. this._geometryCount = source._geometryCount;
  20784. this._maxInstanceCount = source._maxInstanceCount;
  20785. this._maxVertexCount = source._maxVertexCount;
  20786. this._maxIndexCount = source._maxIndexCount;
  20787. this._geometryInitialized = source._geometryInitialized;
  20788. this._multiDrawCounts = source._multiDrawCounts.slice();
  20789. this._multiDrawStarts = source._multiDrawStarts.slice();
  20790. this._indirectTexture = source._indirectTexture.clone();
  20791. this._indirectTexture.image.data = this._indirectTexture.image.data.slice();
  20792. this._matricesTexture = source._matricesTexture.clone();
  20793. this._matricesTexture.image.data = this._matricesTexture.image.data.slice();
  20794. if ( this._colorsTexture !== null ) {
  20795. this._colorsTexture = source._colorsTexture.clone();
  20796. this._colorsTexture.image.data = this._colorsTexture.image.data.slice();
  20797. }
  20798. return this;
  20799. }
  20800. /**
  20801. * Frees the GPU-related resources allocated by this instance. Call this
  20802. * method whenever this instance is no longer used in your app.
  20803. */
  20804. dispose() {
  20805. // Assuming the geometry is not shared with other meshes
  20806. this.geometry.dispose();
  20807. this._matricesTexture.dispose();
  20808. this._matricesTexture = null;
  20809. this._indirectTexture.dispose();
  20810. this._indirectTexture = null;
  20811. if ( this._colorsTexture !== null ) {
  20812. this._colorsTexture.dispose();
  20813. this._colorsTexture = null;
  20814. }
  20815. }
  20816. onBeforeRender( renderer, scene, camera, geometry, material/*, _group*/ ) {
  20817. // if visibility has not changed and frustum culling and object sorting is not required
  20818. // then skip iterating over all items
  20819. if ( ! this._visibilityChanged && ! this.perObjectFrustumCulled && ! this.sortObjects ) {
  20820. return;
  20821. }
  20822. // the indexed version of the multi draw function requires specifying the start
  20823. // offset in bytes.
  20824. const index = geometry.getIndex();
  20825. const bytesPerElement = index === null ? 1 : index.array.BYTES_PER_ELEMENT;
  20826. const instanceInfo = this._instanceInfo;
  20827. const multiDrawStarts = this._multiDrawStarts;
  20828. const multiDrawCounts = this._multiDrawCounts;
  20829. const geometryInfoList = this._geometryInfo;
  20830. const perObjectFrustumCulled = this.perObjectFrustumCulled;
  20831. const indirectTexture = this._indirectTexture;
  20832. const indirectArray = indirectTexture.image.data;
  20833. const frustum = camera.isArrayCamera ? _frustumArray : _frustum;
  20834. // prepare the frustum in the local frame
  20835. if ( perObjectFrustumCulled && ! camera.isArrayCamera ) {
  20836. _matrix$1
  20837. .multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse )
  20838. .multiply( this.matrixWorld );
  20839. _frustum.setFromProjectionMatrix(
  20840. _matrix$1,
  20841. renderer.coordinateSystem
  20842. );
  20843. }
  20844. let multiDrawCount = 0;
  20845. if ( this.sortObjects ) {
  20846. // get the camera position in the local frame
  20847. _matrix$1.copy( this.matrixWorld ).invert();
  20848. _vector$5.setFromMatrixPosition( camera.matrixWorld ).applyMatrix4( _matrix$1 );
  20849. _forward$1.set( 0, 0, -1 ).transformDirection( camera.matrixWorld ).transformDirection( _matrix$1 );
  20850. for ( let i = 0, l = instanceInfo.length; i < l; i ++ ) {
  20851. if ( instanceInfo[ i ].visible && instanceInfo[ i ].active ) {
  20852. const geometryId = instanceInfo[ i ].geometryIndex;
  20853. // get the bounds in world space
  20854. this.getMatrixAt( i, _matrix$1 );
  20855. this.getBoundingSphereAt( geometryId, _sphere$2 ).applyMatrix4( _matrix$1 );
  20856. // determine whether the batched geometry is within the frustum
  20857. let culled = false;
  20858. if ( perObjectFrustumCulled ) {
  20859. culled = ! frustum.intersectsSphere( _sphere$2, camera );
  20860. }
  20861. if ( ! culled ) {
  20862. // get the distance from camera used for sorting
  20863. const geometryInfo = geometryInfoList[ geometryId ];
  20864. const z = _temp.subVectors( _sphere$2.center, _vector$5 ).dot( _forward$1 );
  20865. _renderList.push( geometryInfo.start, geometryInfo.count, z, i );
  20866. }
  20867. }
  20868. }
  20869. // Sort the draw ranges and prep for rendering
  20870. const list = _renderList.list;
  20871. const customSort = this.customSort;
  20872. if ( customSort === null ) {
  20873. list.sort( material.transparent ? sortTransparent : sortOpaque );
  20874. } else {
  20875. customSort.call( this, list, camera );
  20876. }
  20877. for ( let i = 0, l = list.length; i < l; i ++ ) {
  20878. const item = list[ i ];
  20879. multiDrawStarts[ multiDrawCount ] = item.start * bytesPerElement;
  20880. multiDrawCounts[ multiDrawCount ] = item.count;
  20881. indirectArray[ multiDrawCount ] = item.index;
  20882. multiDrawCount ++;
  20883. }
  20884. _renderList.reset();
  20885. } else {
  20886. for ( let i = 0, l = instanceInfo.length; i < l; i ++ ) {
  20887. if ( instanceInfo[ i ].visible && instanceInfo[ i ].active ) {
  20888. const geometryId = instanceInfo[ i ].geometryIndex;
  20889. // determine whether the batched geometry is within the frustum
  20890. let culled = false;
  20891. if ( perObjectFrustumCulled ) {
  20892. // get the bounds in world space
  20893. this.getMatrixAt( i, _matrix$1 );
  20894. this.getBoundingSphereAt( geometryId, _sphere$2 ).applyMatrix4( _matrix$1 );
  20895. culled = ! frustum.intersectsSphere( _sphere$2, camera );
  20896. }
  20897. if ( ! culled ) {
  20898. const geometryInfo = geometryInfoList[ geometryId ];
  20899. multiDrawStarts[ multiDrawCount ] = geometryInfo.start * bytesPerElement;
  20900. multiDrawCounts[ multiDrawCount ] = geometryInfo.count;
  20901. indirectArray[ multiDrawCount ] = i;
  20902. multiDrawCount ++;
  20903. }
  20904. }
  20905. }
  20906. }
  20907. indirectTexture.needsUpdate = true;
  20908. this._multiDrawCount = multiDrawCount;
  20909. this._visibilityChanged = false;
  20910. }
  20911. onBeforeShadow( renderer, object, camera, shadowCamera, geometry, depthMaterial/* , group */ ) {
  20912. this.onBeforeRender( renderer, null, shadowCamera, geometry, depthMaterial );
  20913. }
  20914. }
  20915. /**
  20916. * A material for rendering line primitives.
  20917. *
  20918. * Materials define the appearance of renderable 3D objects.
  20919. *
  20920. * ```js
  20921. * const material = new THREE.LineBasicMaterial( { color: 0xffffff } );
  20922. * ```
  20923. *
  20924. * @augments Material
  20925. */
  20926. class LineBasicMaterial extends Material {
  20927. /**
  20928. * Constructs a new line basic material.
  20929. *
  20930. * @param {Object} [parameters] - An object with one or more properties
  20931. * defining the material's appearance. Any property of the material
  20932. * (including any property from inherited materials) can be passed
  20933. * in here. Color values can be passed any type of value accepted
  20934. * by {@link Color#set}.
  20935. */
  20936. constructor( parameters ) {
  20937. super();
  20938. /**
  20939. * This flag can be used for type testing.
  20940. *
  20941. * @type {boolean}
  20942. * @readonly
  20943. * @default true
  20944. */
  20945. this.isLineBasicMaterial = true;
  20946. this.type = 'LineBasicMaterial';
  20947. /**
  20948. * Color of the material.
  20949. *
  20950. * @type {Color}
  20951. * @default (1,1,1)
  20952. */
  20953. this.color = new Color( 0xffffff );
  20954. /**
  20955. * Sets the color of the lines using data from a texture. The texture map
  20956. * color is modulated by the diffuse `color`.
  20957. *
  20958. * @type {?Texture}
  20959. * @default null
  20960. */
  20961. this.map = null;
  20962. /**
  20963. * Controls line thickness or lines.
  20964. *
  20965. * Can only be used with {@link SVGRenderer}. WebGL and WebGPU
  20966. * ignore this setting and always render line primitives with a
  20967. * width of one pixel.
  20968. *
  20969. * @type {number}
  20970. * @default 1
  20971. */
  20972. this.linewidth = 1;
  20973. /**
  20974. * Defines appearance of line ends.
  20975. *
  20976. * Can only be used with {@link SVGRenderer}.
  20977. *
  20978. * @type {('butt'|'round'|'square')}
  20979. * @default 'round'
  20980. */
  20981. this.linecap = 'round';
  20982. /**
  20983. * Defines appearance of line joints.
  20984. *
  20985. * Can only be used with {@link SVGRenderer}.
  20986. *
  20987. * @type {('round'|'bevel'|'miter')}
  20988. * @default 'round'
  20989. */
  20990. this.linejoin = 'round';
  20991. /**
  20992. * Whether the material is affected by fog or not.
  20993. *
  20994. * @type {boolean}
  20995. * @default true
  20996. */
  20997. this.fog = true;
  20998. this.setValues( parameters );
  20999. }
  21000. copy( source ) {
  21001. super.copy( source );
  21002. this.color.copy( source.color );
  21003. this.map = source.map;
  21004. this.linewidth = source.linewidth;
  21005. this.linecap = source.linecap;
  21006. this.linejoin = source.linejoin;
  21007. this.fog = source.fog;
  21008. return this;
  21009. }
  21010. }
  21011. const _vStart = /*@__PURE__*/ new Vector3();
  21012. const _vEnd = /*@__PURE__*/ new Vector3();
  21013. const _inverseMatrix$1 = /*@__PURE__*/ new Matrix4();
  21014. const _ray$1 = /*@__PURE__*/ new Ray();
  21015. const _sphere$1 = /*@__PURE__*/ new Sphere();
  21016. const _intersectPointOnRay = /*@__PURE__*/ new Vector3();
  21017. const _intersectPointOnSegment = /*@__PURE__*/ new Vector3();
  21018. /**
  21019. * A continuous line. The line are rendered by connecting consecutive
  21020. * vertices with straight lines.
  21021. *
  21022. * ```js
  21023. * const material = new THREE.LineBasicMaterial( { color: 0x0000ff } );
  21024. *
  21025. * const points = [];
  21026. * points.push( new THREE.Vector3( - 10, 0, 0 ) );
  21027. * points.push( new THREE.Vector3( 0, 10, 0 ) );
  21028. * points.push( new THREE.Vector3( 10, 0, 0 ) );
  21029. *
  21030. * const geometry = new THREE.BufferGeometry().setFromPoints( points );
  21031. *
  21032. * const line = new THREE.Line( geometry, material );
  21033. * scene.add( line );
  21034. * ```
  21035. *
  21036. * @augments Object3D
  21037. */
  21038. class Line extends Object3D {
  21039. /**
  21040. * Constructs a new line.
  21041. *
  21042. * @param {BufferGeometry} [geometry] - The line geometry.
  21043. * @param {Material|Array<Material>} [material] - The line material.
  21044. */
  21045. constructor( geometry = new BufferGeometry(), material = new LineBasicMaterial() ) {
  21046. super();
  21047. /**
  21048. * This flag can be used for type testing.
  21049. *
  21050. * @type {boolean}
  21051. * @readonly
  21052. * @default true
  21053. */
  21054. this.isLine = true;
  21055. this.type = 'Line';
  21056. /**
  21057. * The line geometry.
  21058. *
  21059. * @type {BufferGeometry}
  21060. */
  21061. this.geometry = geometry;
  21062. /**
  21063. * The line material.
  21064. *
  21065. * @type {Material|Array<Material>}
  21066. * @default LineBasicMaterial
  21067. */
  21068. this.material = material;
  21069. /**
  21070. * A dictionary representing the morph targets in the geometry. The key is the
  21071. * morph targets name, the value its attribute index. This member is `undefined`
  21072. * by default and only set when morph targets are detected in the geometry.
  21073. *
  21074. * @type {Object<String,number>|undefined}
  21075. * @default undefined
  21076. */
  21077. this.morphTargetDictionary = undefined;
  21078. /**
  21079. * An array of weights typically in the range `[0,1]` that specify how much of the morph
  21080. * is applied. This member is `undefined` by default and only set when morph targets are
  21081. * detected in the geometry.
  21082. *
  21083. * @type {Array<number>|undefined}
  21084. * @default undefined
  21085. */
  21086. this.morphTargetInfluences = undefined;
  21087. this.updateMorphTargets();
  21088. }
  21089. copy( source, recursive ) {
  21090. super.copy( source, recursive );
  21091. this.material = Array.isArray( source.material ) ? source.material.slice() : source.material;
  21092. this.geometry = source.geometry;
  21093. return this;
  21094. }
  21095. /**
  21096. * Computes an array of distance values which are necessary for rendering dashed lines.
  21097. * For each vertex in the geometry, the method calculates the cumulative length from the
  21098. * current point to the very beginning of the line.
  21099. *
  21100. * @return {Line} A reference to this line.
  21101. */
  21102. computeLineDistances() {
  21103. const geometry = this.geometry;
  21104. // we assume non-indexed geometry
  21105. if ( geometry.index === null ) {
  21106. const positionAttribute = geometry.attributes.position;
  21107. const lineDistances = [ 0 ];
  21108. for ( let i = 1, l = positionAttribute.count; i < l; i ++ ) {
  21109. _vStart.fromBufferAttribute( positionAttribute, i - 1 );
  21110. _vEnd.fromBufferAttribute( positionAttribute, i );
  21111. lineDistances[ i ] = lineDistances[ i - 1 ];
  21112. lineDistances[ i ] += _vStart.distanceTo( _vEnd );
  21113. }
  21114. geometry.setAttribute( 'lineDistance', new Float32BufferAttribute( lineDistances, 1 ) );
  21115. } else {
  21116. console.warn( 'THREE.Line.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.' );
  21117. }
  21118. return this;
  21119. }
  21120. /**
  21121. * Computes intersection points between a casted ray and this line.
  21122. *
  21123. * @param {Raycaster} raycaster - The raycaster.
  21124. * @param {Array<Object>} intersects - The target array that holds the intersection points.
  21125. */
  21126. raycast( raycaster, intersects ) {
  21127. const geometry = this.geometry;
  21128. const matrixWorld = this.matrixWorld;
  21129. const threshold = raycaster.params.Line.threshold;
  21130. const drawRange = geometry.drawRange;
  21131. // Checking boundingSphere distance to ray
  21132. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  21133. _sphere$1.copy( geometry.boundingSphere );
  21134. _sphere$1.applyMatrix4( matrixWorld );
  21135. _sphere$1.radius += threshold;
  21136. if ( raycaster.ray.intersectsSphere( _sphere$1 ) === false ) return;
  21137. //
  21138. _inverseMatrix$1.copy( matrixWorld ).invert();
  21139. _ray$1.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$1 );
  21140. const localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 );
  21141. const localThresholdSq = localThreshold * localThreshold;
  21142. const step = this.isLineSegments ? 2 : 1;
  21143. const index = geometry.index;
  21144. const attributes = geometry.attributes;
  21145. const positionAttribute = attributes.position;
  21146. if ( index !== null ) {
  21147. const start = Math.max( 0, drawRange.start );
  21148. const end = Math.min( index.count, ( drawRange.start + drawRange.count ) );
  21149. for ( let i = start, l = end - 1; i < l; i += step ) {
  21150. const a = index.getX( i );
  21151. const b = index.getX( i + 1 );
  21152. const intersect = checkIntersection( this, raycaster, _ray$1, localThresholdSq, a, b, i );
  21153. if ( intersect ) {
  21154. intersects.push( intersect );
  21155. }
  21156. }
  21157. if ( this.isLineLoop ) {
  21158. const a = index.getX( end - 1 );
  21159. const b = index.getX( start );
  21160. const intersect = checkIntersection( this, raycaster, _ray$1, localThresholdSq, a, b, end - 1 );
  21161. if ( intersect ) {
  21162. intersects.push( intersect );
  21163. }
  21164. }
  21165. } else {
  21166. const start = Math.max( 0, drawRange.start );
  21167. const end = Math.min( positionAttribute.count, ( drawRange.start + drawRange.count ) );
  21168. for ( let i = start, l = end - 1; i < l; i += step ) {
  21169. const intersect = checkIntersection( this, raycaster, _ray$1, localThresholdSq, i, i + 1, i );
  21170. if ( intersect ) {
  21171. intersects.push( intersect );
  21172. }
  21173. }
  21174. if ( this.isLineLoop ) {
  21175. const intersect = checkIntersection( this, raycaster, _ray$1, localThresholdSq, end - 1, start, end - 1 );
  21176. if ( intersect ) {
  21177. intersects.push( intersect );
  21178. }
  21179. }
  21180. }
  21181. }
  21182. /**
  21183. * Sets the values of {@link Line#morphTargetDictionary} and {@link Line#morphTargetInfluences}
  21184. * to make sure existing morph targets can influence this 3D object.
  21185. */
  21186. updateMorphTargets() {
  21187. const geometry = this.geometry;
  21188. const morphAttributes = geometry.morphAttributes;
  21189. const keys = Object.keys( morphAttributes );
  21190. if ( keys.length > 0 ) {
  21191. const morphAttribute = morphAttributes[ keys[ 0 ] ];
  21192. if ( morphAttribute !== undefined ) {
  21193. this.morphTargetInfluences = [];
  21194. this.morphTargetDictionary = {};
  21195. for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  21196. const name = morphAttribute[ m ].name || String( m );
  21197. this.morphTargetInfluences.push( 0 );
  21198. this.morphTargetDictionary[ name ] = m;
  21199. }
  21200. }
  21201. }
  21202. }
  21203. }
  21204. function checkIntersection( object, raycaster, ray, thresholdSq, a, b, i ) {
  21205. const positionAttribute = object.geometry.attributes.position;
  21206. _vStart.fromBufferAttribute( positionAttribute, a );
  21207. _vEnd.fromBufferAttribute( positionAttribute, b );
  21208. const distSq = ray.distanceSqToSegment( _vStart, _vEnd, _intersectPointOnRay, _intersectPointOnSegment );
  21209. if ( distSq > thresholdSq ) return;
  21210. _intersectPointOnRay.applyMatrix4( object.matrixWorld ); // Move back to world space for distance calculation
  21211. const distance = raycaster.ray.origin.distanceTo( _intersectPointOnRay );
  21212. if ( distance < raycaster.near || distance > raycaster.far ) return;
  21213. return {
  21214. distance: distance,
  21215. // What do we want? intersection point on the ray or on the segment??
  21216. // point: raycaster.ray.at( distance ),
  21217. point: _intersectPointOnSegment.clone().applyMatrix4( object.matrixWorld ),
  21218. index: i,
  21219. face: null,
  21220. faceIndex: null,
  21221. barycoord: null,
  21222. object: object
  21223. };
  21224. }
  21225. const _start = /*@__PURE__*/ new Vector3();
  21226. const _end = /*@__PURE__*/ new Vector3();
  21227. /**
  21228. * A series of lines drawn between pairs of vertices.
  21229. *
  21230. * @augments Line
  21231. */
  21232. class LineSegments extends Line {
  21233. /**
  21234. * Constructs a new line segments.
  21235. *
  21236. * @param {BufferGeometry} [geometry] - The line geometry.
  21237. * @param {Material|Array<Material>} [material] - The line material.
  21238. */
  21239. constructor( geometry, material ) {
  21240. super( geometry, material );
  21241. /**
  21242. * This flag can be used for type testing.
  21243. *
  21244. * @type {boolean}
  21245. * @readonly
  21246. * @default true
  21247. */
  21248. this.isLineSegments = true;
  21249. this.type = 'LineSegments';
  21250. }
  21251. computeLineDistances() {
  21252. const geometry = this.geometry;
  21253. // we assume non-indexed geometry
  21254. if ( geometry.index === null ) {
  21255. const positionAttribute = geometry.attributes.position;
  21256. const lineDistances = [];
  21257. for ( let i = 0, l = positionAttribute.count; i < l; i += 2 ) {
  21258. _start.fromBufferAttribute( positionAttribute, i );
  21259. _end.fromBufferAttribute( positionAttribute, i + 1 );
  21260. lineDistances[ i ] = ( i === 0 ) ? 0 : lineDistances[ i - 1 ];
  21261. lineDistances[ i + 1 ] = lineDistances[ i ] + _start.distanceTo( _end );
  21262. }
  21263. geometry.setAttribute( 'lineDistance', new Float32BufferAttribute( lineDistances, 1 ) );
  21264. } else {
  21265. console.warn( 'THREE.LineSegments.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.' );
  21266. }
  21267. return this;
  21268. }
  21269. }
  21270. /**
  21271. * A continuous line. This is nearly the same as {@link Line} the only difference
  21272. * is that the last vertex is connected with the first vertex in order to close
  21273. * the line to form a loop.
  21274. *
  21275. * @augments Line
  21276. */
  21277. class LineLoop extends Line {
  21278. /**
  21279. * Constructs a new line loop.
  21280. *
  21281. * @param {BufferGeometry} [geometry] - The line geometry.
  21282. * @param {Material|Array<Material>} [material] - The line material.
  21283. */
  21284. constructor( geometry, material ) {
  21285. super( geometry, material );
  21286. /**
  21287. * This flag can be used for type testing.
  21288. *
  21289. * @type {boolean}
  21290. * @readonly
  21291. * @default true
  21292. */
  21293. this.isLineLoop = true;
  21294. this.type = 'LineLoop';
  21295. }
  21296. }
  21297. /**
  21298. * A material for rendering point primitives.
  21299. *
  21300. * Materials define the appearance of renderable 3D objects.
  21301. *
  21302. * ```js
  21303. * const vertices = [];
  21304. *
  21305. * for ( let i = 0; i < 10000; i ++ ) {
  21306. * const x = THREE.MathUtils.randFloatSpread( 2000 );
  21307. * const y = THREE.MathUtils.randFloatSpread( 2000 );
  21308. * const z = THREE.MathUtils.randFloatSpread( 2000 );
  21309. *
  21310. * vertices.push( x, y, z );
  21311. * }
  21312. *
  21313. * const geometry = new THREE.BufferGeometry();
  21314. * geometry.setAttribute( 'position', new THREE.Float32BufferAttribute( vertices, 3 ) );
  21315. * const material = new THREE.PointsMaterial( { color: 0x888888 } );
  21316. * const points = new THREE.Points( geometry, material );
  21317. * scene.add( points );
  21318. * ```
  21319. *
  21320. * @augments Material
  21321. */
  21322. class PointsMaterial extends Material {
  21323. /**
  21324. * Constructs a new points material.
  21325. *
  21326. * @param {Object} [parameters] - An object with one or more properties
  21327. * defining the material's appearance. Any property of the material
  21328. * (including any property from inherited materials) can be passed
  21329. * in here. Color values can be passed any type of value accepted
  21330. * by {@link Color#set}.
  21331. */
  21332. constructor( parameters ) {
  21333. super();
  21334. /**
  21335. * This flag can be used for type testing.
  21336. *
  21337. * @type {boolean}
  21338. * @readonly
  21339. * @default true
  21340. */
  21341. this.isPointsMaterial = true;
  21342. this.type = 'PointsMaterial';
  21343. /**
  21344. * Color of the material.
  21345. *
  21346. * @type {Color}
  21347. * @default (1,1,1)
  21348. */
  21349. this.color = new Color( 0xffffff );
  21350. /**
  21351. * The color map. May optionally include an alpha channel, typically combined
  21352. * with {@link Material#transparent} or {@link Material#alphaTest}. The texture map
  21353. * color is modulated by the diffuse `color`.
  21354. *
  21355. * @type {?Texture}
  21356. * @default null
  21357. */
  21358. this.map = null;
  21359. /**
  21360. * The alpha map is a grayscale texture that controls the opacity across the
  21361. * surface (black: fully transparent; white: fully opaque).
  21362. *
  21363. * Only the color of the texture is used, ignoring the alpha channel if one
  21364. * exists. For RGB and RGBA textures, the renderer will use the green channel
  21365. * when sampling this texture due to the extra bit of precision provided for
  21366. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  21367. * luminance/alpha textures will also still work as expected.
  21368. *
  21369. * @type {?Texture}
  21370. * @default null
  21371. */
  21372. this.alphaMap = null;
  21373. /**
  21374. * Defines the size of the points in pixels.
  21375. *
  21376. * 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}.
  21377. *
  21378. * @type {number}
  21379. * @default 1
  21380. */
  21381. this.size = 1;
  21382. /**
  21383. * Specifies whether size of individual points is attenuated by the camera depth (perspective camera only).
  21384. *
  21385. * @type {boolean}
  21386. * @default true
  21387. */
  21388. this.sizeAttenuation = true;
  21389. /**
  21390. * Whether the material is affected by fog or not.
  21391. *
  21392. * @type {boolean}
  21393. * @default true
  21394. */
  21395. this.fog = true;
  21396. this.setValues( parameters );
  21397. }
  21398. copy( source ) {
  21399. super.copy( source );
  21400. this.color.copy( source.color );
  21401. this.map = source.map;
  21402. this.alphaMap = source.alphaMap;
  21403. this.size = source.size;
  21404. this.sizeAttenuation = source.sizeAttenuation;
  21405. this.fog = source.fog;
  21406. return this;
  21407. }
  21408. }
  21409. const _inverseMatrix = /*@__PURE__*/ new Matrix4();
  21410. const _ray = /*@__PURE__*/ new Ray();
  21411. const _sphere = /*@__PURE__*/ new Sphere();
  21412. const _position$2 = /*@__PURE__*/ new Vector3();
  21413. /**
  21414. * A class for displaying points or point clouds.
  21415. *
  21416. * @augments Object3D
  21417. */
  21418. class Points extends Object3D {
  21419. /**
  21420. * Constructs a new point cloud.
  21421. *
  21422. * @param {BufferGeometry} [geometry] - The points geometry.
  21423. * @param {Material|Array<Material>} [material] - The points material.
  21424. */
  21425. constructor( geometry = new BufferGeometry(), material = new PointsMaterial() ) {
  21426. super();
  21427. /**
  21428. * This flag can be used for type testing.
  21429. *
  21430. * @type {boolean}
  21431. * @readonly
  21432. * @default true
  21433. */
  21434. this.isPoints = true;
  21435. this.type = 'Points';
  21436. /**
  21437. * The points geometry.
  21438. *
  21439. * @type {BufferGeometry}
  21440. */
  21441. this.geometry = geometry;
  21442. /**
  21443. * The line material.
  21444. *
  21445. * @type {Material|Array<Material>}
  21446. * @default PointsMaterial
  21447. */
  21448. this.material = material;
  21449. /**
  21450. * A dictionary representing the morph targets in the geometry. The key is the
  21451. * morph targets name, the value its attribute index. This member is `undefined`
  21452. * by default and only set when morph targets are detected in the geometry.
  21453. *
  21454. * @type {Object<String,number>|undefined}
  21455. * @default undefined
  21456. */
  21457. this.morphTargetDictionary = undefined;
  21458. /**
  21459. * An array of weights typically in the range `[0,1]` that specify how much of the morph
  21460. * is applied. This member is `undefined` by default and only set when morph targets are
  21461. * detected in the geometry.
  21462. *
  21463. * @type {Array<number>|undefined}
  21464. * @default undefined
  21465. */
  21466. this.morphTargetInfluences = undefined;
  21467. this.updateMorphTargets();
  21468. }
  21469. copy( source, recursive ) {
  21470. super.copy( source, recursive );
  21471. this.material = Array.isArray( source.material ) ? source.material.slice() : source.material;
  21472. this.geometry = source.geometry;
  21473. return this;
  21474. }
  21475. /**
  21476. * Computes intersection points between a casted ray and this point cloud.
  21477. *
  21478. * @param {Raycaster} raycaster - The raycaster.
  21479. * @param {Array<Object>} intersects - The target array that holds the intersection points.
  21480. */
  21481. raycast( raycaster, intersects ) {
  21482. const geometry = this.geometry;
  21483. const matrixWorld = this.matrixWorld;
  21484. const threshold = raycaster.params.Points.threshold;
  21485. const drawRange = geometry.drawRange;
  21486. // Checking boundingSphere distance to ray
  21487. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  21488. _sphere.copy( geometry.boundingSphere );
  21489. _sphere.applyMatrix4( matrixWorld );
  21490. _sphere.radius += threshold;
  21491. if ( raycaster.ray.intersectsSphere( _sphere ) === false ) return;
  21492. //
  21493. _inverseMatrix.copy( matrixWorld ).invert();
  21494. _ray.copy( raycaster.ray ).applyMatrix4( _inverseMatrix );
  21495. const localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 );
  21496. const localThresholdSq = localThreshold * localThreshold;
  21497. const index = geometry.index;
  21498. const attributes = geometry.attributes;
  21499. const positionAttribute = attributes.position;
  21500. if ( index !== null ) {
  21501. const start = Math.max( 0, drawRange.start );
  21502. const end = Math.min( index.count, ( drawRange.start + drawRange.count ) );
  21503. for ( let i = start, il = end; i < il; i ++ ) {
  21504. const a = index.getX( i );
  21505. _position$2.fromBufferAttribute( positionAttribute, a );
  21506. testPoint( _position$2, a, localThresholdSq, matrixWorld, raycaster, intersects, this );
  21507. }
  21508. } else {
  21509. const start = Math.max( 0, drawRange.start );
  21510. const end = Math.min( positionAttribute.count, ( drawRange.start + drawRange.count ) );
  21511. for ( let i = start, l = end; i < l; i ++ ) {
  21512. _position$2.fromBufferAttribute( positionAttribute, i );
  21513. testPoint( _position$2, i, localThresholdSq, matrixWorld, raycaster, intersects, this );
  21514. }
  21515. }
  21516. }
  21517. /**
  21518. * Sets the values of {@link Points#morphTargetDictionary} and {@link Points#morphTargetInfluences}
  21519. * to make sure existing morph targets can influence this 3D object.
  21520. */
  21521. updateMorphTargets() {
  21522. const geometry = this.geometry;
  21523. const morphAttributes = geometry.morphAttributes;
  21524. const keys = Object.keys( morphAttributes );
  21525. if ( keys.length > 0 ) {
  21526. const morphAttribute = morphAttributes[ keys[ 0 ] ];
  21527. if ( morphAttribute !== undefined ) {
  21528. this.morphTargetInfluences = [];
  21529. this.morphTargetDictionary = {};
  21530. for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  21531. const name = morphAttribute[ m ].name || String( m );
  21532. this.morphTargetInfluences.push( 0 );
  21533. this.morphTargetDictionary[ name ] = m;
  21534. }
  21535. }
  21536. }
  21537. }
  21538. }
  21539. function testPoint( point, index, localThresholdSq, matrixWorld, raycaster, intersects, object ) {
  21540. const rayPointDistanceSq = _ray.distanceSqToPoint( point );
  21541. if ( rayPointDistanceSq < localThresholdSq ) {
  21542. const intersectPoint = new Vector3();
  21543. _ray.closestPointToPoint( point, intersectPoint );
  21544. intersectPoint.applyMatrix4( matrixWorld );
  21545. const distance = raycaster.ray.origin.distanceTo( intersectPoint );
  21546. if ( distance < raycaster.near || distance > raycaster.far ) return;
  21547. intersects.push( {
  21548. distance: distance,
  21549. distanceToRay: Math.sqrt( rayPointDistanceSq ),
  21550. point: intersectPoint,
  21551. index: index,
  21552. face: null,
  21553. faceIndex: null,
  21554. barycoord: null,
  21555. object: object
  21556. } );
  21557. }
  21558. }
  21559. /**
  21560. * A texture for use with a video.
  21561. *
  21562. * ```js
  21563. * // assuming you have created a HTML video element with id="video"
  21564. * const video = document.getElementById( 'video' );
  21565. * const texture = new THREE.VideoTexture( video );
  21566. * ```
  21567. *
  21568. * Note: After the initial use of a texture, its dimensions, format, and type
  21569. * cannot be changed. Instead, call {@link Texture#dispose} on the texture and instantiate a new one.
  21570. *
  21571. * @augments Texture
  21572. */
  21573. class VideoTexture extends Texture {
  21574. /**
  21575. * Constructs a new video texture.
  21576. *
  21577. * @param {HTMLVideoElement} video - The video element to use as a data source for the texture.
  21578. * @param {number} [mapping=Texture.DEFAULT_MAPPING] - The texture mapping.
  21579. * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value.
  21580. * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value.
  21581. * @param {number} [magFilter=LinearFilter] - The mag filter value.
  21582. * @param {number} [minFilter=LinearFilter] - The min filter value.
  21583. * @param {number} [format=RGBAFormat] - The texture format.
  21584. * @param {number} [type=UnsignedByteType] - The texture type.
  21585. * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value.
  21586. */
  21587. constructor( video, mapping, wrapS, wrapT, magFilter = LinearFilter, minFilter = LinearFilter, format, type, anisotropy ) {
  21588. super( video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  21589. /**
  21590. * This flag can be used for type testing.
  21591. *
  21592. * @type {boolean}
  21593. * @readonly
  21594. * @default true
  21595. */
  21596. this.isVideoTexture = true;
  21597. /**
  21598. * Whether to generate mipmaps (if possible) for a texture.
  21599. *
  21600. * Overwritten and set to `false` by default.
  21601. *
  21602. * @type {boolean}
  21603. * @default false
  21604. */
  21605. this.generateMipmaps = false;
  21606. const scope = this;
  21607. function updateVideo() {
  21608. scope.needsUpdate = true;
  21609. video.requestVideoFrameCallback( updateVideo );
  21610. }
  21611. if ( 'requestVideoFrameCallback' in video ) {
  21612. video.requestVideoFrameCallback( updateVideo );
  21613. }
  21614. }
  21615. clone() {
  21616. return new this.constructor( this.image ).copy( this );
  21617. }
  21618. /**
  21619. * This method is called automatically by the renderer and sets {@link Texture#needsUpdate}
  21620. * to `true` every time a new frame is available.
  21621. *
  21622. * Only relevant if `requestVideoFrameCallback` is not supported in the browser.
  21623. */
  21624. update() {
  21625. const video = this.image;
  21626. const hasVideoFrameCallback = 'requestVideoFrameCallback' in video;
  21627. if ( hasVideoFrameCallback === false && video.readyState >= video.HAVE_CURRENT_DATA ) {
  21628. this.needsUpdate = true;
  21629. }
  21630. }
  21631. }
  21632. /**
  21633. * This class can be used as an alternative way to define video data. Instead of using
  21634. * an instance of `HTMLVideoElement` like with `VideoTexture`, `VideoFrameTexture` expects each frame is
  21635. * defined manually via {@link VideoFrameTexture#setFrame}. A typical use case for this module is when
  21636. * video frames are decoded with the WebCodecs API.
  21637. *
  21638. * ```js
  21639. * const texture = new THREE.VideoFrameTexture();
  21640. * texture.setFrame( frame );
  21641. * ```
  21642. *
  21643. * @augments VideoTexture
  21644. */
  21645. class VideoFrameTexture extends VideoTexture {
  21646. /**
  21647. * Constructs a new video frame texture.
  21648. *
  21649. * @param {number} [mapping=Texture.DEFAULT_MAPPING] - The texture mapping.
  21650. * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value.
  21651. * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value.
  21652. * @param {number} [magFilter=LinearFilter] - The mag filter value.
  21653. * @param {number} [minFilter=LinearFilter] - The min filter value.
  21654. * @param {number} [format=RGBAFormat] - The texture format.
  21655. * @param {number} [type=UnsignedByteType] - The texture type.
  21656. * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value.
  21657. */
  21658. constructor( mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  21659. super( {}, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  21660. /**
  21661. * This flag can be used for type testing.
  21662. *
  21663. * @type {boolean}
  21664. * @readonly
  21665. * @default true
  21666. */
  21667. this.isVideoFrameTexture = true;
  21668. }
  21669. /**
  21670. * This method overwritten with an empty implementation since
  21671. * this type of texture is updated via `setFrame()`.
  21672. */
  21673. update() {}
  21674. clone() {
  21675. return new this.constructor().copy( this ); // restoring Texture.clone()
  21676. }
  21677. /**
  21678. * Sets the current frame of the video. This will automatically update the texture
  21679. * so the data can be used for rendering.
  21680. *
  21681. * @param {VideoFrame} frame - The video frame.
  21682. */
  21683. setFrame( frame ) {
  21684. this.image = frame;
  21685. this.needsUpdate = true;
  21686. }
  21687. }
  21688. /**
  21689. * This class can only be used in combination with `copyFramebufferToTexture()` methods
  21690. * of renderers. It extracts the contents of the current bound framebuffer and provides it
  21691. * as a texture for further usage.
  21692. *
  21693. * ```js
  21694. * const pixelRatio = window.devicePixelRatio;
  21695. * const textureSize = 128 * pixelRatio;
  21696. *
  21697. * const frameTexture = new FramebufferTexture( textureSize, textureSize );
  21698. *
  21699. * // calculate start position for copying part of the frame data
  21700. * const vector = new Vector2();
  21701. * vector.x = ( window.innerWidth * pixelRatio / 2 ) - ( textureSize / 2 );
  21702. * vector.y = ( window.innerHeight * pixelRatio / 2 ) - ( textureSize / 2 );
  21703. *
  21704. * renderer.render( scene, camera );
  21705. *
  21706. * // copy part of the rendered frame into the framebuffer texture
  21707. * renderer.copyFramebufferToTexture( frameTexture, vector );
  21708. * ```
  21709. *
  21710. * @augments Texture
  21711. */
  21712. class FramebufferTexture extends Texture {
  21713. /**
  21714. * Constructs a new framebuffer texture.
  21715. *
  21716. * @param {number} width - The width of the texture.
  21717. * @param {number} height - The height of the texture.
  21718. */
  21719. constructor( width, height ) {
  21720. super( { width, height } );
  21721. /**
  21722. * This flag can be used for type testing.
  21723. *
  21724. * @type {boolean}
  21725. * @readonly
  21726. * @default true
  21727. */
  21728. this.isFramebufferTexture = true;
  21729. /**
  21730. * How the texture is sampled when a texel covers more than one pixel.
  21731. *
  21732. * Overwritten and set to `NearestFilter` by default to disable filtering.
  21733. *
  21734. * @type {(NearestFilter|NearestMipmapNearestFilter|NearestMipmapLinearFilter|LinearFilter|LinearMipmapNearestFilter|LinearMipmapLinearFilter)}
  21735. * @default NearestFilter
  21736. */
  21737. this.magFilter = NearestFilter;
  21738. /**
  21739. * How the texture is sampled when a texel covers less than one pixel.
  21740. *
  21741. * Overwritten and set to `NearestFilter` by default to disable filtering.
  21742. *
  21743. * @type {(NearestFilter|NearestMipmapNearestFilter|NearestMipmapLinearFilter|LinearFilter|LinearMipmapNearestFilter|LinearMipmapLinearFilter)}
  21744. * @default NearestFilter
  21745. */
  21746. this.minFilter = NearestFilter;
  21747. /**
  21748. * Whether to generate mipmaps (if possible) for a texture.
  21749. *
  21750. * Overwritten and set to `false` by default.
  21751. *
  21752. * @type {boolean}
  21753. * @default false
  21754. */
  21755. this.generateMipmaps = false;
  21756. this.needsUpdate = true;
  21757. }
  21758. }
  21759. /**
  21760. * Creates a texture based on data in compressed form.
  21761. *
  21762. * These texture are usually loaded with {@link CompressedTextureLoader}.
  21763. *
  21764. * @augments Texture
  21765. */
  21766. class CompressedTexture extends Texture {
  21767. /**
  21768. * Constructs a new compressed texture.
  21769. *
  21770. * @param {Array<Object>} mipmaps - This array holds for all mipmaps (including the bases mip)
  21771. * the data and dimensions.
  21772. * @param {number} width - The width of the texture.
  21773. * @param {number} height - The height of the texture.
  21774. * @param {number} [format=RGBAFormat] - The texture format.
  21775. * @param {number} [type=UnsignedByteType] - The texture type.
  21776. * @param {number} [mapping=Texture.DEFAULT_MAPPING] - The texture mapping.
  21777. * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value.
  21778. * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value.
  21779. * @param {number} [magFilter=LinearFilter] - The mag filter value.
  21780. * @param {number} [minFilter=LinearMipmapLinearFilter] - The min filter value.
  21781. * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value.
  21782. * @param {string} [colorSpace=NoColorSpace] - The color space.
  21783. */
  21784. constructor( mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, colorSpace ) {
  21785. super( null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace );
  21786. /**
  21787. * This flag can be used for type testing.
  21788. *
  21789. * @type {boolean}
  21790. * @readonly
  21791. * @default true
  21792. */
  21793. this.isCompressedTexture = true;
  21794. /**
  21795. * The image property of a compressed texture just defines its dimensions.
  21796. *
  21797. * @type {{width:number,height:number}}
  21798. */
  21799. this.image = { width: width, height: height };
  21800. /**
  21801. * This array holds for all mipmaps (including the bases mip) the data and dimensions.
  21802. *
  21803. * @type {Array<Object>}
  21804. */
  21805. this.mipmaps = mipmaps;
  21806. /**
  21807. * If set to `true`, the texture is flipped along the vertical axis when
  21808. * uploaded to the GPU.
  21809. *
  21810. * Overwritten and set to `false` by default since it is not possible to
  21811. * flip compressed textures.
  21812. *
  21813. * @type {boolean}
  21814. * @default false
  21815. * @readonly
  21816. */
  21817. this.flipY = false;
  21818. /**
  21819. * Whether to generate mipmaps (if possible) for a texture.
  21820. *
  21821. * Overwritten and set to `false` by default since it is not
  21822. * possible to generate mipmaps for compressed data. Mipmaps
  21823. * must be embedded in the compressed texture file.
  21824. *
  21825. * @type {boolean}
  21826. * @default false
  21827. * @readonly
  21828. */
  21829. this.generateMipmaps = false;
  21830. }
  21831. }
  21832. /**
  21833. * Creates a texture 2D array based on data in compressed form.
  21834. *
  21835. * These texture are usually loaded with {@link CompressedTextureLoader}.
  21836. *
  21837. * @augments CompressedTexture
  21838. */
  21839. class CompressedArrayTexture extends CompressedTexture {
  21840. /**
  21841. * Constructs a new compressed array texture.
  21842. *
  21843. * @param {Array<Object>} mipmaps - This array holds for all mipmaps (including the bases mip)
  21844. * the data and dimensions.
  21845. * @param {number} width - The width of the texture.
  21846. * @param {number} height - The height of the texture.
  21847. * @param {number} depth - The depth of the texture.
  21848. * @param {number} [format=RGBAFormat] - The min filter value.
  21849. * @param {number} [type=UnsignedByteType] - The min filter value.
  21850. */
  21851. constructor( mipmaps, width, height, depth, format, type ) {
  21852. super( mipmaps, width, height, format, type );
  21853. /**
  21854. * This flag can be used for type testing.
  21855. *
  21856. * @type {boolean}
  21857. * @readonly
  21858. * @default true
  21859. */
  21860. this.isCompressedArrayTexture = true;
  21861. /**
  21862. * The image property of a compressed texture just defines its dimensions.
  21863. *
  21864. * @name CompressedArrayTexture#image
  21865. * @type {{width:number,height:number,depth:number}}
  21866. */
  21867. this.image.depth = depth;
  21868. /**
  21869. * This defines how the texture is wrapped in the depth and corresponds to
  21870. * *W* in UVW mapping.
  21871. *
  21872. * @type {(RepeatWrapping|ClampToEdgeWrapping|MirroredRepeatWrapping)}
  21873. * @default ClampToEdgeWrapping
  21874. */
  21875. this.wrapR = ClampToEdgeWrapping;
  21876. /**
  21877. * A set of all layers which need to be updated in the texture.
  21878. *
  21879. * @type {Set<number>}
  21880. */
  21881. this.layerUpdates = new Set();
  21882. }
  21883. /**
  21884. * Describes that a specific layer of the texture needs to be updated.
  21885. * Normally when {@link Texture#needsUpdate} is set to `true`, the
  21886. * entire compressed texture array is sent to the GPU. Marking specific
  21887. * layers will only transmit subsets of all mipmaps associated with a
  21888. * specific depth in the array which is often much more performant.
  21889. *
  21890. * @param {number} layerIndex - The layer index that should be updated.
  21891. */
  21892. addLayerUpdate( layerIndex ) {
  21893. this.layerUpdates.add( layerIndex );
  21894. }
  21895. /**
  21896. * Resets the layer updates registry.
  21897. */
  21898. clearLayerUpdates() {
  21899. this.layerUpdates.clear();
  21900. }
  21901. }
  21902. /**
  21903. * Creates a cube texture based on data in compressed form.
  21904. *
  21905. * These texture are usually loaded with {@link CompressedTextureLoader}.
  21906. *
  21907. * @augments CompressedTexture
  21908. */
  21909. class CompressedCubeTexture extends CompressedTexture {
  21910. /**
  21911. * Constructs a new compressed texture.
  21912. *
  21913. * @param {Array<CompressedTexture>} images - An array of compressed textures.
  21914. * @param {number} [format=RGBAFormat] - The texture format.
  21915. * @param {number} [type=UnsignedByteType] - The texture type.
  21916. */
  21917. constructor( images, format, type ) {
  21918. super( undefined, images[ 0 ].width, images[ 0 ].height, format, type, CubeReflectionMapping );
  21919. /**
  21920. * This flag can be used for type testing.
  21921. *
  21922. * @type {boolean}
  21923. * @readonly
  21924. * @default true
  21925. */
  21926. this.isCompressedCubeTexture = true;
  21927. /**
  21928. * This flag can be used for type testing.
  21929. *
  21930. * @type {boolean}
  21931. * @readonly
  21932. * @default true
  21933. */
  21934. this.isCubeTexture = true;
  21935. this.image = images;
  21936. }
  21937. }
  21938. /**
  21939. * Creates a texture from a canvas element.
  21940. *
  21941. * This is almost the same as the base texture class, except that it sets {@link Texture#needsUpdate}
  21942. * to `true` immediately since a canvas can directly be used for rendering.
  21943. *
  21944. * @augments Texture
  21945. */
  21946. class CanvasTexture extends Texture {
  21947. /**
  21948. * Constructs a new texture.
  21949. *
  21950. * @param {HTMLCanvasElement} [canvas] - The HTML canvas element.
  21951. * @param {number} [mapping=Texture.DEFAULT_MAPPING] - The texture mapping.
  21952. * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value.
  21953. * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value.
  21954. * @param {number} [magFilter=LinearFilter] - The mag filter value.
  21955. * @param {number} [minFilter=LinearMipmapLinearFilter] - The min filter value.
  21956. * @param {number} [format=RGBAFormat] - The texture format.
  21957. * @param {number} [type=UnsignedByteType] - The texture type.
  21958. * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value.
  21959. */
  21960. constructor( canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  21961. super( canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  21962. /**
  21963. * This flag can be used for type testing.
  21964. *
  21965. * @type {boolean}
  21966. * @readonly
  21967. * @default true
  21968. */
  21969. this.isCanvasTexture = true;
  21970. this.needsUpdate = true;
  21971. }
  21972. }
  21973. /**
  21974. * This class can be used to automatically save the depth information of a
  21975. * rendering into a texture.
  21976. *
  21977. * @augments Texture
  21978. */
  21979. class DepthTexture extends Texture {
  21980. /**
  21981. * Constructs a new depth texture.
  21982. *
  21983. * @param {number} width - The width of the texture.
  21984. * @param {number} height - The height of the texture.
  21985. * @param {number} [type=UnsignedIntType] - The texture type.
  21986. * @param {number} [mapping=Texture.DEFAULT_MAPPING] - The texture mapping.
  21987. * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value.
  21988. * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value.
  21989. * @param {number} [magFilter=LinearFilter] - The mag filter value.
  21990. * @param {number} [minFilter=LinearFilter] - The min filter value.
  21991. * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value.
  21992. * @param {number} [format=DepthFormat] - The texture format.
  21993. * @param {number} [depth=1] - The depth of the texture.
  21994. */
  21995. constructor( width, height, type = UnsignedIntType, mapping, wrapS, wrapT, magFilter = NearestFilter, minFilter = NearestFilter, anisotropy, format = DepthFormat, depth = 1 ) {
  21996. if ( format !== DepthFormat && format !== DepthStencilFormat ) {
  21997. throw new Error( 'DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat' );
  21998. }
  21999. const image = { width: width, height: height, depth: depth };
  22000. super( image, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  22001. /**
  22002. * This flag can be used for type testing.
  22003. *
  22004. * @type {boolean}
  22005. * @readonly
  22006. * @default true
  22007. */
  22008. this.isDepthTexture = true;
  22009. /**
  22010. * If set to `true`, the texture is flipped along the vertical axis when
  22011. * uploaded to the GPU.
  22012. *
  22013. * Overwritten and set to `false` by default.
  22014. *
  22015. * @type {boolean}
  22016. * @default false
  22017. */
  22018. this.flipY = false;
  22019. /**
  22020. * Whether to generate mipmaps (if possible) for a texture.
  22021. *
  22022. * Overwritten and set to `false` by default.
  22023. *
  22024. * @type {boolean}
  22025. * @default false
  22026. */
  22027. this.generateMipmaps = false;
  22028. /**
  22029. * Code corresponding to the depth compare function.
  22030. *
  22031. * @type {?(NeverCompare|LessCompare|EqualCompare|LessEqualCompare|GreaterCompare|NotEqualCompare|GreaterEqualCompare|AlwaysCompare)}
  22032. * @default null
  22033. */
  22034. this.compareFunction = null;
  22035. }
  22036. copy( source ) {
  22037. super.copy( source );
  22038. this.source = new Source( Object.assign( {}, source.image ) ); // see #30540
  22039. this.compareFunction = source.compareFunction;
  22040. return this;
  22041. }
  22042. toJSON( meta ) {
  22043. const data = super.toJSON( meta );
  22044. if ( this.compareFunction !== null ) data.compareFunction = this.compareFunction;
  22045. return data;
  22046. }
  22047. }
  22048. /**
  22049. * A geometry class for representing a capsule.
  22050. *
  22051. * ```js
  22052. * const geometry = new THREE.CapsuleGeometry( 1, 1, 4, 8, 1 );
  22053. * const material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } );
  22054. * const capsule = new THREE.Mesh( geometry, material );
  22055. * scene.add( capsule );
  22056. * ```
  22057. *
  22058. * @augments BufferGeometry
  22059. */
  22060. class CapsuleGeometry extends BufferGeometry {
  22061. /**
  22062. * Constructs a new capsule geometry.
  22063. *
  22064. * @param {number} [radius=1] - Radius of the capsule.
  22065. * @param {number} [height=1] - Height of the middle section.
  22066. * @param {number} [capSegments=4] - Number of curve segments used to build each cap.
  22067. * @param {number} [radialSegments=8] - Number of segmented faces around the circumference of the capsule. Must be an integer >= 3.
  22068. * @param {number} [heightSegments=1] - Number of rows of faces along the height of the middle section. Must be an integer >= 1.
  22069. */
  22070. constructor( radius = 1, height = 1, capSegments = 4, radialSegments = 8, heightSegments = 1 ) {
  22071. super();
  22072. this.type = 'CapsuleGeometry';
  22073. /**
  22074. * Holds the constructor parameters that have been
  22075. * used to generate the geometry. Any modification
  22076. * after instantiation does not change the geometry.
  22077. *
  22078. * @type {Object}
  22079. */
  22080. this.parameters = {
  22081. radius: radius,
  22082. height: height,
  22083. capSegments: capSegments,
  22084. radialSegments: radialSegments,
  22085. heightSegments: heightSegments,
  22086. };
  22087. height = Math.max( 0, height );
  22088. capSegments = Math.max( 1, Math.floor( capSegments ) );
  22089. radialSegments = Math.max( 3, Math.floor( radialSegments ) );
  22090. heightSegments = Math.max( 1, Math.floor( heightSegments ) );
  22091. // buffers
  22092. const indices = [];
  22093. const vertices = [];
  22094. const normals = [];
  22095. const uvs = [];
  22096. // helper variables
  22097. const halfHeight = height / 2;
  22098. const capArcLength = ( Math.PI / 2 ) * radius;
  22099. const cylinderPartLength = height;
  22100. const totalArcLength = 2 * capArcLength + cylinderPartLength;
  22101. const numVerticalSegments = capSegments * 2 + heightSegments;
  22102. const verticesPerRow = radialSegments + 1;
  22103. const normal = new Vector3();
  22104. const vertex = new Vector3();
  22105. // generate vertices, normals, and uvs
  22106. for ( let iy = 0; iy <= numVerticalSegments; iy ++ ) {
  22107. let currentArcLength = 0;
  22108. let profileY = 0;
  22109. let profileRadius = 0;
  22110. let normalYComponent = 0;
  22111. if ( iy <= capSegments ) {
  22112. // bottom cap
  22113. const segmentProgress = iy / capSegments;
  22114. const angle = ( segmentProgress * Math.PI ) / 2;
  22115. profileY = - halfHeight - radius * Math.cos( angle );
  22116. profileRadius = radius * Math.sin( angle );
  22117. normalYComponent = - radius * Math.cos( angle );
  22118. currentArcLength = segmentProgress * capArcLength;
  22119. } else if ( iy <= capSegments + heightSegments ) {
  22120. // middle section
  22121. const segmentProgress = ( iy - capSegments ) / heightSegments;
  22122. profileY = - halfHeight + segmentProgress * height;
  22123. profileRadius = radius;
  22124. normalYComponent = 0;
  22125. currentArcLength = capArcLength + segmentProgress * cylinderPartLength;
  22126. } else {
  22127. // top cap
  22128. const segmentProgress =
  22129. ( iy - capSegments - heightSegments ) / capSegments;
  22130. const angle = ( segmentProgress * Math.PI ) / 2;
  22131. profileY = halfHeight + radius * Math.sin( angle );
  22132. profileRadius = radius * Math.cos( angle );
  22133. normalYComponent = radius * Math.sin( angle );
  22134. currentArcLength =
  22135. capArcLength + cylinderPartLength + segmentProgress * capArcLength;
  22136. }
  22137. const v = Math.max( 0, Math.min( 1, currentArcLength / totalArcLength ) );
  22138. // special case for the poles
  22139. let uOffset = 0;
  22140. if ( iy === 0 ) {
  22141. uOffset = 0.5 / radialSegments;
  22142. } else if ( iy === numVerticalSegments ) {
  22143. uOffset = -0.5 / radialSegments;
  22144. }
  22145. for ( let ix = 0; ix <= radialSegments; ix ++ ) {
  22146. const u = ix / radialSegments;
  22147. const theta = u * Math.PI * 2;
  22148. const sinTheta = Math.sin( theta );
  22149. const cosTheta = Math.cos( theta );
  22150. // vertex
  22151. vertex.x = - profileRadius * cosTheta;
  22152. vertex.y = profileY;
  22153. vertex.z = profileRadius * sinTheta;
  22154. vertices.push( vertex.x, vertex.y, vertex.z );
  22155. // normal
  22156. normal.set(
  22157. - profileRadius * cosTheta,
  22158. normalYComponent,
  22159. profileRadius * sinTheta
  22160. );
  22161. normal.normalize();
  22162. normals.push( normal.x, normal.y, normal.z );
  22163. // uv
  22164. uvs.push( u + uOffset, v );
  22165. }
  22166. if ( iy > 0 ) {
  22167. const prevIndexRow = ( iy - 1 ) * verticesPerRow;
  22168. for ( let ix = 0; ix < radialSegments; ix ++ ) {
  22169. const i1 = prevIndexRow + ix;
  22170. const i2 = prevIndexRow + ix + 1;
  22171. const i3 = iy * verticesPerRow + ix;
  22172. const i4 = iy * verticesPerRow + ix + 1;
  22173. indices.push( i1, i2, i3 );
  22174. indices.push( i2, i4, i3 );
  22175. }
  22176. }
  22177. }
  22178. // build geometry
  22179. this.setIndex( indices );
  22180. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  22181. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  22182. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  22183. }
  22184. copy( source ) {
  22185. super.copy( source );
  22186. this.parameters = Object.assign( {}, source.parameters );
  22187. return this;
  22188. }
  22189. /**
  22190. * Factory method for creating an instance of this class from the given
  22191. * JSON object.
  22192. *
  22193. * @param {Object} data - A JSON object representing the serialized geometry.
  22194. * @return {CapsuleGeometry} A new instance.
  22195. */
  22196. static fromJSON( data ) {
  22197. return new CapsuleGeometry( data.radius, data.height, data.capSegments, data.radialSegments, data.heightSegments );
  22198. }
  22199. }
  22200. /**
  22201. * A simple shape of Euclidean geometry. It is constructed from a
  22202. * number of triangular segments that are oriented around a central point and
  22203. * extend as far out as a given radius. It is built counter-clockwise from a
  22204. * start angle and a given central angle. It can also be used to create
  22205. * regular polygons, where the number of segments determines the number of
  22206. * sides.
  22207. *
  22208. * ```js
  22209. * const geometry = new THREE.CircleGeometry( 5, 32 );
  22210. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  22211. * const circle = new THREE.Mesh( geometry, material );
  22212. * scene.add( circle )
  22213. * ```
  22214. *
  22215. * @augments BufferGeometry
  22216. */
  22217. class CircleGeometry extends BufferGeometry {
  22218. /**
  22219. * Constructs a new circle geometry.
  22220. *
  22221. * @param {number} [radius=1] - Radius of the circle.
  22222. * @param {number} [segments=32] - Number of segments (triangles), minimum = `3`.
  22223. * @param {number} [thetaStart=0] - Start angle for first segment in radians.
  22224. * @param {number} [thetaLength=Math.PI*2] - The central angle, often called theta,
  22225. * of the circular sector in radians. The default value results in a complete circle.
  22226. */
  22227. constructor( radius = 1, segments = 32, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  22228. super();
  22229. this.type = 'CircleGeometry';
  22230. /**
  22231. * Holds the constructor parameters that have been
  22232. * used to generate the geometry. Any modification
  22233. * after instantiation does not change the geometry.
  22234. *
  22235. * @type {Object}
  22236. */
  22237. this.parameters = {
  22238. radius: radius,
  22239. segments: segments,
  22240. thetaStart: thetaStart,
  22241. thetaLength: thetaLength
  22242. };
  22243. segments = Math.max( 3, segments );
  22244. // buffers
  22245. const indices = [];
  22246. const vertices = [];
  22247. const normals = [];
  22248. const uvs = [];
  22249. // helper variables
  22250. const vertex = new Vector3();
  22251. const uv = new Vector2();
  22252. // center point
  22253. vertices.push( 0, 0, 0 );
  22254. normals.push( 0, 0, 1 );
  22255. uvs.push( 0.5, 0.5 );
  22256. for ( let s = 0, i = 3; s <= segments; s ++, i += 3 ) {
  22257. const segment = thetaStart + s / segments * thetaLength;
  22258. // vertex
  22259. vertex.x = radius * Math.cos( segment );
  22260. vertex.y = radius * Math.sin( segment );
  22261. vertices.push( vertex.x, vertex.y, vertex.z );
  22262. // normal
  22263. normals.push( 0, 0, 1 );
  22264. // uvs
  22265. uv.x = ( vertices[ i ] / radius + 1 ) / 2;
  22266. uv.y = ( vertices[ i + 1 ] / radius + 1 ) / 2;
  22267. uvs.push( uv.x, uv.y );
  22268. }
  22269. // indices
  22270. for ( let i = 1; i <= segments; i ++ ) {
  22271. indices.push( i, i + 1, 0 );
  22272. }
  22273. // build geometry
  22274. this.setIndex( indices );
  22275. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  22276. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  22277. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  22278. }
  22279. copy( source ) {
  22280. super.copy( source );
  22281. this.parameters = Object.assign( {}, source.parameters );
  22282. return this;
  22283. }
  22284. /**
  22285. * Factory method for creating an instance of this class from the given
  22286. * JSON object.
  22287. *
  22288. * @param {Object} data - A JSON object representing the serialized geometry.
  22289. * @return {CircleGeometry} A new instance.
  22290. */
  22291. static fromJSON( data ) {
  22292. return new CircleGeometry( data.radius, data.segments, data.thetaStart, data.thetaLength );
  22293. }
  22294. }
  22295. /**
  22296. * A geometry class for representing a cylinder.
  22297. *
  22298. * ```js
  22299. * const geometry = new THREE.CylinderGeometry( 5, 5, 20, 32 );
  22300. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  22301. * const cylinder = new THREE.Mesh( geometry, material );
  22302. * scene.add( cylinder );
  22303. * ```
  22304. *
  22305. * @augments BufferGeometry
  22306. */
  22307. class CylinderGeometry extends BufferGeometry {
  22308. /**
  22309. * Constructs a new cylinder geometry.
  22310. *
  22311. * @param {number} [radiusTop=1] - Radius of the cylinder at the top.
  22312. * @param {number} [radiusBottom=1] - Radius of the cylinder at the bottom.
  22313. * @param {number} [height=1] - Height of the cylinder.
  22314. * @param {number} [radialSegments=32] - Number of segmented faces around the circumference of the cylinder.
  22315. * @param {number} [heightSegments=1] - Number of rows of faces along the height of the cylinder.
  22316. * @param {boolean} [openEnded=false] - Whether the base of the cylinder is open or capped.
  22317. * @param {number} [thetaStart=0] - Start angle for first segment, in radians.
  22318. * @param {number} [thetaLength=Math.PI*2] - The central angle, often called theta, of the circular sector, in radians.
  22319. * The default value results in a complete cylinder.
  22320. */
  22321. constructor( radiusTop = 1, radiusBottom = 1, height = 1, radialSegments = 32, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  22322. super();
  22323. this.type = 'CylinderGeometry';
  22324. /**
  22325. * Holds the constructor parameters that have been
  22326. * used to generate the geometry. Any modification
  22327. * after instantiation does not change the geometry.
  22328. *
  22329. * @type {Object}
  22330. */
  22331. this.parameters = {
  22332. radiusTop: radiusTop,
  22333. radiusBottom: radiusBottom,
  22334. height: height,
  22335. radialSegments: radialSegments,
  22336. heightSegments: heightSegments,
  22337. openEnded: openEnded,
  22338. thetaStart: thetaStart,
  22339. thetaLength: thetaLength
  22340. };
  22341. const scope = this;
  22342. radialSegments = Math.floor( radialSegments );
  22343. heightSegments = Math.floor( heightSegments );
  22344. // buffers
  22345. const indices = [];
  22346. const vertices = [];
  22347. const normals = [];
  22348. const uvs = [];
  22349. // helper variables
  22350. let index = 0;
  22351. const indexArray = [];
  22352. const halfHeight = height / 2;
  22353. let groupStart = 0;
  22354. // generate geometry
  22355. generateTorso();
  22356. if ( openEnded === false ) {
  22357. if ( radiusTop > 0 ) generateCap( true );
  22358. if ( radiusBottom > 0 ) generateCap( false );
  22359. }
  22360. // build geometry
  22361. this.setIndex( indices );
  22362. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  22363. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  22364. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  22365. function generateTorso() {
  22366. const normal = new Vector3();
  22367. const vertex = new Vector3();
  22368. let groupCount = 0;
  22369. // this will be used to calculate the normal
  22370. const slope = ( radiusBottom - radiusTop ) / height;
  22371. // generate vertices, normals and uvs
  22372. for ( let y = 0; y <= heightSegments; y ++ ) {
  22373. const indexRow = [];
  22374. const v = y / heightSegments;
  22375. // calculate the radius of the current row
  22376. const radius = v * ( radiusBottom - radiusTop ) + radiusTop;
  22377. for ( let x = 0; x <= radialSegments; x ++ ) {
  22378. const u = x / radialSegments;
  22379. const theta = u * thetaLength + thetaStart;
  22380. const sinTheta = Math.sin( theta );
  22381. const cosTheta = Math.cos( theta );
  22382. // vertex
  22383. vertex.x = radius * sinTheta;
  22384. vertex.y = - v * height + halfHeight;
  22385. vertex.z = radius * cosTheta;
  22386. vertices.push( vertex.x, vertex.y, vertex.z );
  22387. // normal
  22388. normal.set( sinTheta, slope, cosTheta ).normalize();
  22389. normals.push( normal.x, normal.y, normal.z );
  22390. // uv
  22391. uvs.push( u, 1 - v );
  22392. // save index of vertex in respective row
  22393. indexRow.push( index ++ );
  22394. }
  22395. // now save vertices of the row in our index array
  22396. indexArray.push( indexRow );
  22397. }
  22398. // generate indices
  22399. for ( let x = 0; x < radialSegments; x ++ ) {
  22400. for ( let y = 0; y < heightSegments; y ++ ) {
  22401. // we use the index array to access the correct indices
  22402. const a = indexArray[ y ][ x ];
  22403. const b = indexArray[ y + 1 ][ x ];
  22404. const c = indexArray[ y + 1 ][ x + 1 ];
  22405. const d = indexArray[ y ][ x + 1 ];
  22406. // faces
  22407. if ( radiusTop > 0 || y !== 0 ) {
  22408. indices.push( a, b, d );
  22409. groupCount += 3;
  22410. }
  22411. if ( radiusBottom > 0 || y !== heightSegments - 1 ) {
  22412. indices.push( b, c, d );
  22413. groupCount += 3;
  22414. }
  22415. }
  22416. }
  22417. // add a group to the geometry. this will ensure multi material support
  22418. scope.addGroup( groupStart, groupCount, 0 );
  22419. // calculate new start value for groups
  22420. groupStart += groupCount;
  22421. }
  22422. function generateCap( top ) {
  22423. // save the index of the first center vertex
  22424. const centerIndexStart = index;
  22425. const uv = new Vector2();
  22426. const vertex = new Vector3();
  22427. let groupCount = 0;
  22428. const radius = ( top === true ) ? radiusTop : radiusBottom;
  22429. const sign = ( top === true ) ? 1 : -1;
  22430. // first we generate the center vertex data of the cap.
  22431. // because the geometry needs one set of uvs per face,
  22432. // we must generate a center vertex per face/segment
  22433. for ( let x = 1; x <= radialSegments; x ++ ) {
  22434. // vertex
  22435. vertices.push( 0, halfHeight * sign, 0 );
  22436. // normal
  22437. normals.push( 0, sign, 0 );
  22438. // uv
  22439. uvs.push( 0.5, 0.5 );
  22440. // increase index
  22441. index ++;
  22442. }
  22443. // save the index of the last center vertex
  22444. const centerIndexEnd = index;
  22445. // now we generate the surrounding vertices, normals and uvs
  22446. for ( let x = 0; x <= radialSegments; x ++ ) {
  22447. const u = x / radialSegments;
  22448. const theta = u * thetaLength + thetaStart;
  22449. const cosTheta = Math.cos( theta );
  22450. const sinTheta = Math.sin( theta );
  22451. // vertex
  22452. vertex.x = radius * sinTheta;
  22453. vertex.y = halfHeight * sign;
  22454. vertex.z = radius * cosTheta;
  22455. vertices.push( vertex.x, vertex.y, vertex.z );
  22456. // normal
  22457. normals.push( 0, sign, 0 );
  22458. // uv
  22459. uv.x = ( cosTheta * 0.5 ) + 0.5;
  22460. uv.y = ( sinTheta * 0.5 * sign ) + 0.5;
  22461. uvs.push( uv.x, uv.y );
  22462. // increase index
  22463. index ++;
  22464. }
  22465. // generate indices
  22466. for ( let x = 0; x < radialSegments; x ++ ) {
  22467. const c = centerIndexStart + x;
  22468. const i = centerIndexEnd + x;
  22469. if ( top === true ) {
  22470. // face top
  22471. indices.push( i, i + 1, c );
  22472. } else {
  22473. // face bottom
  22474. indices.push( i + 1, i, c );
  22475. }
  22476. groupCount += 3;
  22477. }
  22478. // add a group to the geometry. this will ensure multi material support
  22479. scope.addGroup( groupStart, groupCount, top === true ? 1 : 2 );
  22480. // calculate new start value for groups
  22481. groupStart += groupCount;
  22482. }
  22483. }
  22484. copy( source ) {
  22485. super.copy( source );
  22486. this.parameters = Object.assign( {}, source.parameters );
  22487. return this;
  22488. }
  22489. /**
  22490. * Factory method for creating an instance of this class from the given
  22491. * JSON object.
  22492. *
  22493. * @param {Object} data - A JSON object representing the serialized geometry.
  22494. * @return {CylinderGeometry} A new instance.
  22495. */
  22496. static fromJSON( data ) {
  22497. return new CylinderGeometry( data.radiusTop, data.radiusBottom, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength );
  22498. }
  22499. }
  22500. /**
  22501. * A geometry class for representing a cone.
  22502. *
  22503. * ```js
  22504. * const geometry = new THREE.ConeGeometry( 5, 20, 32 );
  22505. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  22506. * const cone = new THREE.Mesh(geometry, material );
  22507. * scene.add( cone );
  22508. * ```
  22509. *
  22510. * @augments CylinderGeometry
  22511. */
  22512. class ConeGeometry extends CylinderGeometry {
  22513. /**
  22514. * Constructs a new cone geometry.
  22515. *
  22516. * @param {number} [radius=1] - Radius of the cone base.
  22517. * @param {number} [height=1] - Height of the cone.
  22518. * @param {number} [radialSegments=32] - Number of segmented faces around the circumference of the cone.
  22519. * @param {number} [heightSegments=1] - Number of rows of faces along the height of the cone.
  22520. * @param {boolean} [openEnded=false] - Whether the base of the cone is open or capped.
  22521. * @param {number} [thetaStart=0] - Start angle for first segment, in radians.
  22522. * @param {number} [thetaLength=Math.PI*2] - The central angle, often called theta, of the circular sector, in radians.
  22523. * The default value results in a complete cone.
  22524. */
  22525. constructor( radius = 1, height = 1, radialSegments = 32, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  22526. super( 0, radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength );
  22527. this.type = 'ConeGeometry';
  22528. /**
  22529. * Holds the constructor parameters that have been
  22530. * used to generate the geometry. Any modification
  22531. * after instantiation does not change the geometry.
  22532. *
  22533. * @type {Object}
  22534. */
  22535. this.parameters = {
  22536. radius: radius,
  22537. height: height,
  22538. radialSegments: radialSegments,
  22539. heightSegments: heightSegments,
  22540. openEnded: openEnded,
  22541. thetaStart: thetaStart,
  22542. thetaLength: thetaLength
  22543. };
  22544. }
  22545. /**
  22546. * Factory method for creating an instance of this class from the given
  22547. * JSON object.
  22548. *
  22549. * @param {Object} data - A JSON object representing the serialized geometry.
  22550. * @return {ConeGeometry} A new instance.
  22551. */
  22552. static fromJSON( data ) {
  22553. return new ConeGeometry( data.radius, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength );
  22554. }
  22555. }
  22556. /**
  22557. * A polyhedron is a solid in three dimensions with flat faces. This class
  22558. * will take an array of vertices, project them onto a sphere, and then
  22559. * divide them up to the desired level of detail.
  22560. *
  22561. * @augments BufferGeometry
  22562. */
  22563. class PolyhedronGeometry extends BufferGeometry {
  22564. /**
  22565. * Constructs a new polyhedron geometry.
  22566. *
  22567. * @param {Array<number>} [vertices] - A flat array of vertices describing the base shape.
  22568. * @param {Array<number>} [indices] - A flat array of indices describing the base shape.
  22569. * @param {number} [radius=1] - The radius of the shape.
  22570. * @param {number} [detail=0] - How many levels to subdivide the geometry. The more detail, the smoother the shape.
  22571. */
  22572. constructor( vertices = [], indices = [], radius = 1, detail = 0 ) {
  22573. super();
  22574. this.type = 'PolyhedronGeometry';
  22575. /**
  22576. * Holds the constructor parameters that have been
  22577. * used to generate the geometry. Any modification
  22578. * after instantiation does not change the geometry.
  22579. *
  22580. * @type {Object}
  22581. */
  22582. this.parameters = {
  22583. vertices: vertices,
  22584. indices: indices,
  22585. radius: radius,
  22586. detail: detail
  22587. };
  22588. // default buffer data
  22589. const vertexBuffer = [];
  22590. const uvBuffer = [];
  22591. // the subdivision creates the vertex buffer data
  22592. subdivide( detail );
  22593. // all vertices should lie on a conceptual sphere with a given radius
  22594. applyRadius( radius );
  22595. // finally, create the uv data
  22596. generateUVs();
  22597. // build non-indexed geometry
  22598. this.setAttribute( 'position', new Float32BufferAttribute( vertexBuffer, 3 ) );
  22599. this.setAttribute( 'normal', new Float32BufferAttribute( vertexBuffer.slice(), 3 ) );
  22600. this.setAttribute( 'uv', new Float32BufferAttribute( uvBuffer, 2 ) );
  22601. if ( detail === 0 ) {
  22602. this.computeVertexNormals(); // flat normals
  22603. } else {
  22604. this.normalizeNormals(); // smooth normals
  22605. }
  22606. // helper functions
  22607. function subdivide( detail ) {
  22608. const a = new Vector3();
  22609. const b = new Vector3();
  22610. const c = new Vector3();
  22611. // iterate over all faces and apply a subdivision with the given detail value
  22612. for ( let i = 0; i < indices.length; i += 3 ) {
  22613. // get the vertices of the face
  22614. getVertexByIndex( indices[ i + 0 ], a );
  22615. getVertexByIndex( indices[ i + 1 ], b );
  22616. getVertexByIndex( indices[ i + 2 ], c );
  22617. // perform subdivision
  22618. subdivideFace( a, b, c, detail );
  22619. }
  22620. }
  22621. function subdivideFace( a, b, c, detail ) {
  22622. const cols = detail + 1;
  22623. // we use this multidimensional array as a data structure for creating the subdivision
  22624. const v = [];
  22625. // construct all of the vertices for this subdivision
  22626. for ( let i = 0; i <= cols; i ++ ) {
  22627. v[ i ] = [];
  22628. const aj = a.clone().lerp( c, i / cols );
  22629. const bj = b.clone().lerp( c, i / cols );
  22630. const rows = cols - i;
  22631. for ( let j = 0; j <= rows; j ++ ) {
  22632. if ( j === 0 && i === cols ) {
  22633. v[ i ][ j ] = aj;
  22634. } else {
  22635. v[ i ][ j ] = aj.clone().lerp( bj, j / rows );
  22636. }
  22637. }
  22638. }
  22639. // construct all of the faces
  22640. for ( let i = 0; i < cols; i ++ ) {
  22641. for ( let j = 0; j < 2 * ( cols - i ) - 1; j ++ ) {
  22642. const k = Math.floor( j / 2 );
  22643. if ( j % 2 === 0 ) {
  22644. pushVertex( v[ i ][ k + 1 ] );
  22645. pushVertex( v[ i + 1 ][ k ] );
  22646. pushVertex( v[ i ][ k ] );
  22647. } else {
  22648. pushVertex( v[ i ][ k + 1 ] );
  22649. pushVertex( v[ i + 1 ][ k + 1 ] );
  22650. pushVertex( v[ i + 1 ][ k ] );
  22651. }
  22652. }
  22653. }
  22654. }
  22655. function applyRadius( radius ) {
  22656. const vertex = new Vector3();
  22657. // iterate over the entire buffer and apply the radius to each vertex
  22658. for ( let i = 0; i < vertexBuffer.length; i += 3 ) {
  22659. vertex.x = vertexBuffer[ i + 0 ];
  22660. vertex.y = vertexBuffer[ i + 1 ];
  22661. vertex.z = vertexBuffer[ i + 2 ];
  22662. vertex.normalize().multiplyScalar( radius );
  22663. vertexBuffer[ i + 0 ] = vertex.x;
  22664. vertexBuffer[ i + 1 ] = vertex.y;
  22665. vertexBuffer[ i + 2 ] = vertex.z;
  22666. }
  22667. }
  22668. function generateUVs() {
  22669. const vertex = new Vector3();
  22670. for ( let i = 0; i < vertexBuffer.length; i += 3 ) {
  22671. vertex.x = vertexBuffer[ i + 0 ];
  22672. vertex.y = vertexBuffer[ i + 1 ];
  22673. vertex.z = vertexBuffer[ i + 2 ];
  22674. const u = azimuth( vertex ) / 2 / Math.PI + 0.5;
  22675. const v = inclination( vertex ) / Math.PI + 0.5;
  22676. uvBuffer.push( u, 1 - v );
  22677. }
  22678. correctUVs();
  22679. correctSeam();
  22680. }
  22681. function correctSeam() {
  22682. // handle case when face straddles the seam, see #3269
  22683. for ( let i = 0; i < uvBuffer.length; i += 6 ) {
  22684. // uv data of a single face
  22685. const x0 = uvBuffer[ i + 0 ];
  22686. const x1 = uvBuffer[ i + 2 ];
  22687. const x2 = uvBuffer[ i + 4 ];
  22688. const max = Math.max( x0, x1, x2 );
  22689. const min = Math.min( x0, x1, x2 );
  22690. // 0.9 is somewhat arbitrary
  22691. if ( max > 0.9 && min < 0.1 ) {
  22692. if ( x0 < 0.2 ) uvBuffer[ i + 0 ] += 1;
  22693. if ( x1 < 0.2 ) uvBuffer[ i + 2 ] += 1;
  22694. if ( x2 < 0.2 ) uvBuffer[ i + 4 ] += 1;
  22695. }
  22696. }
  22697. }
  22698. function pushVertex( vertex ) {
  22699. vertexBuffer.push( vertex.x, vertex.y, vertex.z );
  22700. }
  22701. function getVertexByIndex( index, vertex ) {
  22702. const stride = index * 3;
  22703. vertex.x = vertices[ stride + 0 ];
  22704. vertex.y = vertices[ stride + 1 ];
  22705. vertex.z = vertices[ stride + 2 ];
  22706. }
  22707. function correctUVs() {
  22708. const a = new Vector3();
  22709. const b = new Vector3();
  22710. const c = new Vector3();
  22711. const centroid = new Vector3();
  22712. const uvA = new Vector2();
  22713. const uvB = new Vector2();
  22714. const uvC = new Vector2();
  22715. for ( let i = 0, j = 0; i < vertexBuffer.length; i += 9, j += 6 ) {
  22716. a.set( vertexBuffer[ i + 0 ], vertexBuffer[ i + 1 ], vertexBuffer[ i + 2 ] );
  22717. b.set( vertexBuffer[ i + 3 ], vertexBuffer[ i + 4 ], vertexBuffer[ i + 5 ] );
  22718. c.set( vertexBuffer[ i + 6 ], vertexBuffer[ i + 7 ], vertexBuffer[ i + 8 ] );
  22719. uvA.set( uvBuffer[ j + 0 ], uvBuffer[ j + 1 ] );
  22720. uvB.set( uvBuffer[ j + 2 ], uvBuffer[ j + 3 ] );
  22721. uvC.set( uvBuffer[ j + 4 ], uvBuffer[ j + 5 ] );
  22722. centroid.copy( a ).add( b ).add( c ).divideScalar( 3 );
  22723. const azi = azimuth( centroid );
  22724. correctUV( uvA, j + 0, a, azi );
  22725. correctUV( uvB, j + 2, b, azi );
  22726. correctUV( uvC, j + 4, c, azi );
  22727. }
  22728. }
  22729. function correctUV( uv, stride, vector, azimuth ) {
  22730. if ( ( azimuth < 0 ) && ( uv.x === 1 ) ) {
  22731. uvBuffer[ stride ] = uv.x - 1;
  22732. }
  22733. if ( ( vector.x === 0 ) && ( vector.z === 0 ) ) {
  22734. uvBuffer[ stride ] = azimuth / 2 / Math.PI + 0.5;
  22735. }
  22736. }
  22737. // Angle around the Y axis, counter-clockwise when looking from above.
  22738. function azimuth( vector ) {
  22739. return Math.atan2( vector.z, - vector.x );
  22740. }
  22741. // Angle above the XZ plane.
  22742. function inclination( vector ) {
  22743. return Math.atan2( - vector.y, Math.sqrt( ( vector.x * vector.x ) + ( vector.z * vector.z ) ) );
  22744. }
  22745. }
  22746. copy( source ) {
  22747. super.copy( source );
  22748. this.parameters = Object.assign( {}, source.parameters );
  22749. return this;
  22750. }
  22751. /**
  22752. * Factory method for creating an instance of this class from the given
  22753. * JSON object.
  22754. *
  22755. * @param {Object} data - A JSON object representing the serialized geometry.
  22756. * @return {PolyhedronGeometry} A new instance.
  22757. */
  22758. static fromJSON( data ) {
  22759. return new PolyhedronGeometry( data.vertices, data.indices, data.radius, data.details );
  22760. }
  22761. }
  22762. /**
  22763. * A geometry class for representing a dodecahedron.
  22764. *
  22765. * ```js
  22766. * const geometry = new THREE.DodecahedronGeometry();
  22767. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  22768. * const dodecahedron = new THREE.Mesh( geometry, material );
  22769. * scene.add( dodecahedron );
  22770. * ```
  22771. *
  22772. * @augments PolyhedronGeometry
  22773. */
  22774. class DodecahedronGeometry extends PolyhedronGeometry {
  22775. /**
  22776. * Constructs a new dodecahedron geometry.
  22777. *
  22778. * @param {number} [radius=1] - Radius of the dodecahedron.
  22779. * @param {number} [detail=0] - Setting this to a value greater than `0` adds vertices making it no longer a dodecahedron.
  22780. */
  22781. constructor( radius = 1, detail = 0 ) {
  22782. const t = ( 1 + Math.sqrt( 5 ) ) / 2;
  22783. const r = 1 / t;
  22784. const vertices = [
  22785. // (±1, ±1, ±1)
  22786. -1, -1, -1, -1, -1, 1,
  22787. -1, 1, -1, -1, 1, 1,
  22788. 1, -1, -1, 1, -1, 1,
  22789. 1, 1, -1, 1, 1, 1,
  22790. // (0, ±1/φ, ±φ)
  22791. 0, - r, - t, 0, - r, t,
  22792. 0, r, - t, 0, r, t,
  22793. // (±1/φ, ±φ, 0)
  22794. - r, - t, 0, - r, t, 0,
  22795. r, - t, 0, r, t, 0,
  22796. // (±φ, 0, ±1/φ)
  22797. - t, 0, - r, t, 0, - r,
  22798. - t, 0, r, t, 0, r
  22799. ];
  22800. const indices = [
  22801. 3, 11, 7, 3, 7, 15, 3, 15, 13,
  22802. 7, 19, 17, 7, 17, 6, 7, 6, 15,
  22803. 17, 4, 8, 17, 8, 10, 17, 10, 6,
  22804. 8, 0, 16, 8, 16, 2, 8, 2, 10,
  22805. 0, 12, 1, 0, 1, 18, 0, 18, 16,
  22806. 6, 10, 2, 6, 2, 13, 6, 13, 15,
  22807. 2, 16, 18, 2, 18, 3, 2, 3, 13,
  22808. 18, 1, 9, 18, 9, 11, 18, 11, 3,
  22809. 4, 14, 12, 4, 12, 0, 4, 0, 8,
  22810. 11, 9, 5, 11, 5, 19, 11, 19, 7,
  22811. 19, 5, 14, 19, 14, 4, 19, 4, 17,
  22812. 1, 12, 14, 1, 14, 5, 1, 5, 9
  22813. ];
  22814. super( vertices, indices, radius, detail );
  22815. this.type = 'DodecahedronGeometry';
  22816. /**
  22817. * Holds the constructor parameters that have been
  22818. * used to generate the geometry. Any modification
  22819. * after instantiation does not change the geometry.
  22820. *
  22821. * @type {Object}
  22822. */
  22823. this.parameters = {
  22824. radius: radius,
  22825. detail: detail
  22826. };
  22827. }
  22828. /**
  22829. * Factory method for creating an instance of this class from the given
  22830. * JSON object.
  22831. *
  22832. * @param {Object} data - A JSON object representing the serialized geometry.
  22833. * @return {DodecahedronGeometry} A new instance.
  22834. */
  22835. static fromJSON( data ) {
  22836. return new DodecahedronGeometry( data.radius, data.detail );
  22837. }
  22838. }
  22839. const _v0 = /*@__PURE__*/ new Vector3();
  22840. const _v1$1 = /*@__PURE__*/ new Vector3();
  22841. const _normal = /*@__PURE__*/ new Vector3();
  22842. const _triangle = /*@__PURE__*/ new Triangle();
  22843. /**
  22844. * Can be used as a helper object to view the edges of a geometry.
  22845. *
  22846. * ```js
  22847. * const geometry = new THREE.BoxGeometry();
  22848. * const edges = new THREE.EdgesGeometry( geometry );
  22849. * const line = new THREE.LineSegments( edges );
  22850. * scene.add( line );
  22851. * ```
  22852. *
  22853. * Note: It is not yet possible to serialize/deserialize instances of this class.
  22854. *
  22855. * @augments BufferGeometry
  22856. */
  22857. class EdgesGeometry extends BufferGeometry {
  22858. /**
  22859. * Constructs a new edges geometry.
  22860. *
  22861. * @param {?BufferGeometry} [geometry=null] - The geometry.
  22862. * @param {number} [thresholdAngle=1] - An edge is only rendered if the angle (in degrees)
  22863. * between the face normals of the adjoining faces exceeds this value.
  22864. */
  22865. constructor( geometry = null, thresholdAngle = 1 ) {
  22866. super();
  22867. this.type = 'EdgesGeometry';
  22868. /**
  22869. * Holds the constructor parameters that have been
  22870. * used to generate the geometry. Any modification
  22871. * after instantiation does not change the geometry.
  22872. *
  22873. * @type {Object}
  22874. */
  22875. this.parameters = {
  22876. geometry: geometry,
  22877. thresholdAngle: thresholdAngle
  22878. };
  22879. if ( geometry !== null ) {
  22880. const precisionPoints = 4;
  22881. const precision = Math.pow( 10, precisionPoints );
  22882. const thresholdDot = Math.cos( DEG2RAD * thresholdAngle );
  22883. const indexAttr = geometry.getIndex();
  22884. const positionAttr = geometry.getAttribute( 'position' );
  22885. const indexCount = indexAttr ? indexAttr.count : positionAttr.count;
  22886. const indexArr = [ 0, 0, 0 ];
  22887. const vertKeys = [ 'a', 'b', 'c' ];
  22888. const hashes = new Array( 3 );
  22889. const edgeData = {};
  22890. const vertices = [];
  22891. for ( let i = 0; i < indexCount; i += 3 ) {
  22892. if ( indexAttr ) {
  22893. indexArr[ 0 ] = indexAttr.getX( i );
  22894. indexArr[ 1 ] = indexAttr.getX( i + 1 );
  22895. indexArr[ 2 ] = indexAttr.getX( i + 2 );
  22896. } else {
  22897. indexArr[ 0 ] = i;
  22898. indexArr[ 1 ] = i + 1;
  22899. indexArr[ 2 ] = i + 2;
  22900. }
  22901. const { a, b, c } = _triangle;
  22902. a.fromBufferAttribute( positionAttr, indexArr[ 0 ] );
  22903. b.fromBufferAttribute( positionAttr, indexArr[ 1 ] );
  22904. c.fromBufferAttribute( positionAttr, indexArr[ 2 ] );
  22905. _triangle.getNormal( _normal );
  22906. // create hashes for the edge from the vertices
  22907. hashes[ 0 ] = `${ Math.round( a.x * precision ) },${ Math.round( a.y * precision ) },${ Math.round( a.z * precision ) }`;
  22908. hashes[ 1 ] = `${ Math.round( b.x * precision ) },${ Math.round( b.y * precision ) },${ Math.round( b.z * precision ) }`;
  22909. hashes[ 2 ] = `${ Math.round( c.x * precision ) },${ Math.round( c.y * precision ) },${ Math.round( c.z * precision ) }`;
  22910. // skip degenerate triangles
  22911. if ( hashes[ 0 ] === hashes[ 1 ] || hashes[ 1 ] === hashes[ 2 ] || hashes[ 2 ] === hashes[ 0 ] ) {
  22912. continue;
  22913. }
  22914. // iterate over every edge
  22915. for ( let j = 0; j < 3; j ++ ) {
  22916. // get the first and next vertex making up the edge
  22917. const jNext = ( j + 1 ) % 3;
  22918. const vecHash0 = hashes[ j ];
  22919. const vecHash1 = hashes[ jNext ];
  22920. const v0 = _triangle[ vertKeys[ j ] ];
  22921. const v1 = _triangle[ vertKeys[ jNext ] ];
  22922. const hash = `${ vecHash0 }_${ vecHash1 }`;
  22923. const reverseHash = `${ vecHash1 }_${ vecHash0 }`;
  22924. if ( reverseHash in edgeData && edgeData[ reverseHash ] ) {
  22925. // if we found a sibling edge add it into the vertex array if
  22926. // it meets the angle threshold and delete the edge from the map.
  22927. if ( _normal.dot( edgeData[ reverseHash ].normal ) <= thresholdDot ) {
  22928. vertices.push( v0.x, v0.y, v0.z );
  22929. vertices.push( v1.x, v1.y, v1.z );
  22930. }
  22931. edgeData[ reverseHash ] = null;
  22932. } else if ( ! ( hash in edgeData ) ) {
  22933. // if we've already got an edge here then skip adding a new one
  22934. edgeData[ hash ] = {
  22935. index0: indexArr[ j ],
  22936. index1: indexArr[ jNext ],
  22937. normal: _normal.clone(),
  22938. };
  22939. }
  22940. }
  22941. }
  22942. // iterate over all remaining, unmatched edges and add them to the vertex array
  22943. for ( const key in edgeData ) {
  22944. if ( edgeData[ key ] ) {
  22945. const { index0, index1 } = edgeData[ key ];
  22946. _v0.fromBufferAttribute( positionAttr, index0 );
  22947. _v1$1.fromBufferAttribute( positionAttr, index1 );
  22948. vertices.push( _v0.x, _v0.y, _v0.z );
  22949. vertices.push( _v1$1.x, _v1$1.y, _v1$1.z );
  22950. }
  22951. }
  22952. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  22953. }
  22954. }
  22955. copy( source ) {
  22956. super.copy( source );
  22957. this.parameters = Object.assign( {}, source.parameters );
  22958. return this;
  22959. }
  22960. }
  22961. /**
  22962. * An abstract base class for creating an analytic curve object that contains methods
  22963. * for interpolation.
  22964. *
  22965. * @abstract
  22966. */
  22967. class Curve {
  22968. /**
  22969. * Constructs a new curve.
  22970. */
  22971. constructor() {
  22972. /**
  22973. * The type property is used for detecting the object type
  22974. * in context of serialization/deserialization.
  22975. *
  22976. * @type {string}
  22977. * @readonly
  22978. */
  22979. this.type = 'Curve';
  22980. /**
  22981. * This value determines the amount of divisions when calculating the
  22982. * cumulative segment lengths of a curve via {@link Curve#getLengths}. To ensure
  22983. * precision when using methods like {@link Curve#getSpacedPoints}, it is
  22984. * recommended to increase the value of this property if the curve is very large.
  22985. *
  22986. * @type {number}
  22987. * @default 200
  22988. */
  22989. this.arcLengthDivisions = 200;
  22990. /**
  22991. * Must be set to `true` if the curve parameters have changed.
  22992. *
  22993. * @type {boolean}
  22994. * @default false
  22995. */
  22996. this.needsUpdate = false;
  22997. /**
  22998. * An internal cache that holds precomputed curve length values.
  22999. *
  23000. * @private
  23001. * @type {?Array<number>}
  23002. * @default null
  23003. */
  23004. this.cacheArcLengths = null;
  23005. }
  23006. /**
  23007. * This method returns a vector in 2D or 3D space (depending on the curve definition)
  23008. * for the given interpolation factor.
  23009. *
  23010. * @abstract
  23011. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  23012. * @param {(Vector2|Vector3)} [optionalTarget] - The optional target vector the result is written to.
  23013. * @return {(Vector2|Vector3)} The position on the curve. It can be a 2D or 3D vector depending on the curve definition.
  23014. */
  23015. getPoint( /* t, optionalTarget */ ) {
  23016. console.warn( 'THREE.Curve: .getPoint() not implemented.' );
  23017. }
  23018. /**
  23019. * This method returns a vector in 2D or 3D space (depending on the curve definition)
  23020. * for the given interpolation factor. Unlike {@link Curve#getPoint}, this method honors the length
  23021. * of the curve which equidistant samples.
  23022. *
  23023. * @param {number} u - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  23024. * @param {(Vector2|Vector3)} [optionalTarget] - The optional target vector the result is written to.
  23025. * @return {(Vector2|Vector3)} The position on the curve. It can be a 2D or 3D vector depending on the curve definition.
  23026. */
  23027. getPointAt( u, optionalTarget ) {
  23028. const t = this.getUtoTmapping( u );
  23029. return this.getPoint( t, optionalTarget );
  23030. }
  23031. /**
  23032. * This method samples the curve via {@link Curve#getPoint} and returns an array of points representing
  23033. * the curve shape.
  23034. *
  23035. * @param {number} [divisions=5] - The number of divisions.
  23036. * @return {Array<(Vector2|Vector3)>} An array holding the sampled curve values. The number of points is `divisions + 1`.
  23037. */
  23038. getPoints( divisions = 5 ) {
  23039. const points = [];
  23040. for ( let d = 0; d <= divisions; d ++ ) {
  23041. points.push( this.getPoint( d / divisions ) );
  23042. }
  23043. return points;
  23044. }
  23045. // Get sequence of points using getPointAt( u )
  23046. /**
  23047. * This method samples the curve via {@link Curve#getPointAt} and returns an array of points representing
  23048. * the curve shape. Unlike {@link Curve#getPoints}, this method returns equi-spaced points across the entire
  23049. * curve.
  23050. *
  23051. * @param {number} [divisions=5] - The number of divisions.
  23052. * @return {Array<(Vector2|Vector3)>} An array holding the sampled curve values. The number of points is `divisions + 1`.
  23053. */
  23054. getSpacedPoints( divisions = 5 ) {
  23055. const points = [];
  23056. for ( let d = 0; d <= divisions; d ++ ) {
  23057. points.push( this.getPointAt( d / divisions ) );
  23058. }
  23059. return points;
  23060. }
  23061. /**
  23062. * Returns the total arc length of the curve.
  23063. *
  23064. * @return {number} The length of the curve.
  23065. */
  23066. getLength() {
  23067. const lengths = this.getLengths();
  23068. return lengths[ lengths.length - 1 ];
  23069. }
  23070. /**
  23071. * Returns an array of cumulative segment lengths of the curve.
  23072. *
  23073. * @param {number} [divisions=this.arcLengthDivisions] - The number of divisions.
  23074. * @return {Array<number>} An array holding the cumulative segment lengths.
  23075. */
  23076. getLengths( divisions = this.arcLengthDivisions ) {
  23077. if ( this.cacheArcLengths &&
  23078. ( this.cacheArcLengths.length === divisions + 1 ) &&
  23079. ! this.needsUpdate ) {
  23080. return this.cacheArcLengths;
  23081. }
  23082. this.needsUpdate = false;
  23083. const cache = [];
  23084. let current, last = this.getPoint( 0 );
  23085. let sum = 0;
  23086. cache.push( 0 );
  23087. for ( let p = 1; p <= divisions; p ++ ) {
  23088. current = this.getPoint( p / divisions );
  23089. sum += current.distanceTo( last );
  23090. cache.push( sum );
  23091. last = current;
  23092. }
  23093. this.cacheArcLengths = cache;
  23094. return cache; // { sums: cache, sum: sum }; Sum is in the last element.
  23095. }
  23096. /**
  23097. * Update the cumulative segment distance cache. The method must be called
  23098. * every time curve parameters are changed. If an updated curve is part of a
  23099. * composed curve like {@link CurvePath}, this method must be called on the
  23100. * composed curve, too.
  23101. */
  23102. updateArcLengths() {
  23103. this.needsUpdate = true;
  23104. this.getLengths();
  23105. }
  23106. /**
  23107. * Given an interpolation factor in the range `[0,1]`, this method returns an updated
  23108. * interpolation factor in the same range that can be ued to sample equidistant points
  23109. * from a curve.
  23110. *
  23111. * @param {number} u - The interpolation factor.
  23112. * @param {?number} distance - An optional distance on the curve.
  23113. * @return {number} The updated interpolation factor.
  23114. */
  23115. getUtoTmapping( u, distance = null ) {
  23116. const arcLengths = this.getLengths();
  23117. let i = 0;
  23118. const il = arcLengths.length;
  23119. let targetArcLength; // The targeted u distance value to get
  23120. if ( distance ) {
  23121. targetArcLength = distance;
  23122. } else {
  23123. targetArcLength = u * arcLengths[ il - 1 ];
  23124. }
  23125. // binary search for the index with largest value smaller than target u distance
  23126. let low = 0, high = il - 1, comparison;
  23127. while ( low <= high ) {
  23128. 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
  23129. comparison = arcLengths[ i ] - targetArcLength;
  23130. if ( comparison < 0 ) {
  23131. low = i + 1;
  23132. } else if ( comparison > 0 ) {
  23133. high = i - 1;
  23134. } else {
  23135. high = i;
  23136. break;
  23137. // DONE
  23138. }
  23139. }
  23140. i = high;
  23141. if ( arcLengths[ i ] === targetArcLength ) {
  23142. return i / ( il - 1 );
  23143. }
  23144. // we could get finer grain at lengths, or use simple interpolation between two points
  23145. const lengthBefore = arcLengths[ i ];
  23146. const lengthAfter = arcLengths[ i + 1 ];
  23147. const segmentLength = lengthAfter - lengthBefore;
  23148. // determine where we are between the 'before' and 'after' points
  23149. const segmentFraction = ( targetArcLength - lengthBefore ) / segmentLength;
  23150. // add that fractional amount to t
  23151. const t = ( i + segmentFraction ) / ( il - 1 );
  23152. return t;
  23153. }
  23154. /**
  23155. * Returns a unit vector tangent for the given interpolation factor.
  23156. * If the derived curve does not implement its tangent derivation,
  23157. * two points a small delta apart will be used to find its gradient
  23158. * which seems to give a reasonable approximation.
  23159. *
  23160. * @param {number} t - The interpolation factor.
  23161. * @param {(Vector2|Vector3)} [optionalTarget] - The optional target vector the result is written to.
  23162. * @return {(Vector2|Vector3)} The tangent vector.
  23163. */
  23164. getTangent( t, optionalTarget ) {
  23165. const delta = 0.0001;
  23166. let t1 = t - delta;
  23167. let t2 = t + delta;
  23168. // Capping in case of danger
  23169. if ( t1 < 0 ) t1 = 0;
  23170. if ( t2 > 1 ) t2 = 1;
  23171. const pt1 = this.getPoint( t1 );
  23172. const pt2 = this.getPoint( t2 );
  23173. const tangent = optionalTarget || ( ( pt1.isVector2 ) ? new Vector2() : new Vector3() );
  23174. tangent.copy( pt2 ).sub( pt1 ).normalize();
  23175. return tangent;
  23176. }
  23177. /**
  23178. * Same as {@link Curve#getTangent} but with equidistant samples.
  23179. *
  23180. * @param {number} u - The interpolation factor.
  23181. * @param {(Vector2|Vector3)} [optionalTarget] - The optional target vector the result is written to.
  23182. * @return {(Vector2|Vector3)} The tangent vector.
  23183. * @see {@link Curve#getPointAt}
  23184. */
  23185. getTangentAt( u, optionalTarget ) {
  23186. const t = this.getUtoTmapping( u );
  23187. return this.getTangent( t, optionalTarget );
  23188. }
  23189. /**
  23190. * Generates the Frenet Frames. Requires a curve definition in 3D space. Used
  23191. * in geometries like {@link TubeGeometry} or {@link ExtrudeGeometry}.
  23192. *
  23193. * @param {number} segments - The number of segments.
  23194. * @param {boolean} [closed=false] - Whether the curve is closed or not.
  23195. * @return {{tangents: Array<Vector3>, normals: Array<Vector3>, binormals: Array<Vector3>}} The Frenet Frames.
  23196. */
  23197. computeFrenetFrames( segments, closed = false ) {
  23198. // see http://www.cs.indiana.edu/pub/techreports/TR425.pdf
  23199. const normal = new Vector3();
  23200. const tangents = [];
  23201. const normals = [];
  23202. const binormals = [];
  23203. const vec = new Vector3();
  23204. const mat = new Matrix4();
  23205. // compute the tangent vectors for each segment on the curve
  23206. for ( let i = 0; i <= segments; i ++ ) {
  23207. const u = i / segments;
  23208. tangents[ i ] = this.getTangentAt( u, new Vector3() );
  23209. }
  23210. // select an initial normal vector perpendicular to the first tangent vector,
  23211. // and in the direction of the minimum tangent xyz component
  23212. normals[ 0 ] = new Vector3();
  23213. binormals[ 0 ] = new Vector3();
  23214. let min = Number.MAX_VALUE;
  23215. const tx = Math.abs( tangents[ 0 ].x );
  23216. const ty = Math.abs( tangents[ 0 ].y );
  23217. const tz = Math.abs( tangents[ 0 ].z );
  23218. if ( tx <= min ) {
  23219. min = tx;
  23220. normal.set( 1, 0, 0 );
  23221. }
  23222. if ( ty <= min ) {
  23223. min = ty;
  23224. normal.set( 0, 1, 0 );
  23225. }
  23226. if ( tz <= min ) {
  23227. normal.set( 0, 0, 1 );
  23228. }
  23229. vec.crossVectors( tangents[ 0 ], normal ).normalize();
  23230. normals[ 0 ].crossVectors( tangents[ 0 ], vec );
  23231. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] );
  23232. // compute the slowly-varying normal and binormal vectors for each segment on the curve
  23233. for ( let i = 1; i <= segments; i ++ ) {
  23234. normals[ i ] = normals[ i - 1 ].clone();
  23235. binormals[ i ] = binormals[ i - 1 ].clone();
  23236. vec.crossVectors( tangents[ i - 1 ], tangents[ i ] );
  23237. if ( vec.length() > Number.EPSILON ) {
  23238. vec.normalize();
  23239. const theta = Math.acos( clamp( tangents[ i - 1 ].dot( tangents[ i ] ), -1, 1 ) ); // clamp for floating pt errors
  23240. normals[ i ].applyMatrix4( mat.makeRotationAxis( vec, theta ) );
  23241. }
  23242. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  23243. }
  23244. // if the curve is closed, postprocess the vectors so the first and last normal vectors are the same
  23245. if ( closed === true ) {
  23246. let theta = Math.acos( clamp( normals[ 0 ].dot( normals[ segments ] ), -1, 1 ) );
  23247. theta /= segments;
  23248. if ( tangents[ 0 ].dot( vec.crossVectors( normals[ 0 ], normals[ segments ] ) ) > 0 ) {
  23249. theta = - theta;
  23250. }
  23251. for ( let i = 1; i <= segments; i ++ ) {
  23252. // twist a little...
  23253. normals[ i ].applyMatrix4( mat.makeRotationAxis( tangents[ i ], theta * i ) );
  23254. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  23255. }
  23256. }
  23257. return {
  23258. tangents: tangents,
  23259. normals: normals,
  23260. binormals: binormals
  23261. };
  23262. }
  23263. /**
  23264. * Returns a new curve with copied values from this instance.
  23265. *
  23266. * @return {Curve} A clone of this instance.
  23267. */
  23268. clone() {
  23269. return new this.constructor().copy( this );
  23270. }
  23271. /**
  23272. * Copies the values of the given curve to this instance.
  23273. *
  23274. * @param {Curve} source - The curve to copy.
  23275. * @return {Curve} A reference to this curve.
  23276. */
  23277. copy( source ) {
  23278. this.arcLengthDivisions = source.arcLengthDivisions;
  23279. return this;
  23280. }
  23281. /**
  23282. * Serializes the curve into JSON.
  23283. *
  23284. * @return {Object} A JSON object representing the serialized curve.
  23285. * @see {@link ObjectLoader#parse}
  23286. */
  23287. toJSON() {
  23288. const data = {
  23289. metadata: {
  23290. version: 4.6,
  23291. type: 'Curve',
  23292. generator: 'Curve.toJSON'
  23293. }
  23294. };
  23295. data.arcLengthDivisions = this.arcLengthDivisions;
  23296. data.type = this.type;
  23297. return data;
  23298. }
  23299. /**
  23300. * Deserializes the curve from the given JSON.
  23301. *
  23302. * @param {Object} json - The JSON holding the serialized curve.
  23303. * @return {Curve} A reference to this curve.
  23304. */
  23305. fromJSON( json ) {
  23306. this.arcLengthDivisions = json.arcLengthDivisions;
  23307. return this;
  23308. }
  23309. }
  23310. /**
  23311. * A curve representing an ellipse.
  23312. *
  23313. * ```js
  23314. * const curve = new THREE.EllipseCurve(
  23315. * 0, 0,
  23316. * 10, 10,
  23317. * 0, 2 * Math.PI,
  23318. * false,
  23319. * 0
  23320. * );
  23321. *
  23322. * const points = curve.getPoints( 50 );
  23323. * const geometry = new THREE.BufferGeometry().setFromPoints( points );
  23324. *
  23325. * const material = new THREE.LineBasicMaterial( { color: 0xff0000 } );
  23326. *
  23327. * // Create the final object to add to the scene
  23328. * const ellipse = new THREE.Line( geometry, material );
  23329. * ```
  23330. *
  23331. * @augments Curve
  23332. */
  23333. class EllipseCurve extends Curve {
  23334. /**
  23335. * Constructs a new ellipse curve.
  23336. *
  23337. * @param {number} [aX=0] - The X center of the ellipse.
  23338. * @param {number} [aY=0] - The Y center of the ellipse.
  23339. * @param {number} [xRadius=1] - The radius of the ellipse in the x direction.
  23340. * @param {number} [yRadius=1] - The radius of the ellipse in the y direction.
  23341. * @param {number} [aStartAngle=0] - The start angle of the curve in radians starting from the positive X axis.
  23342. * @param {number} [aEndAngle=Math.PI*2] - The end angle of the curve in radians starting from the positive X axis.
  23343. * @param {boolean} [aClockwise=false] - Whether the ellipse is drawn clockwise or not.
  23344. * @param {number} [aRotation=0] - The rotation angle of the ellipse in radians, counterclockwise from the positive X axis.
  23345. */
  23346. constructor( aX = 0, aY = 0, xRadius = 1, yRadius = 1, aStartAngle = 0, aEndAngle = Math.PI * 2, aClockwise = false, aRotation = 0 ) {
  23347. super();
  23348. /**
  23349. * This flag can be used for type testing.
  23350. *
  23351. * @type {boolean}
  23352. * @readonly
  23353. * @default true
  23354. */
  23355. this.isEllipseCurve = true;
  23356. this.type = 'EllipseCurve';
  23357. /**
  23358. * The X center of the ellipse.
  23359. *
  23360. * @type {number}
  23361. * @default 0
  23362. */
  23363. this.aX = aX;
  23364. /**
  23365. * The Y center of the ellipse.
  23366. *
  23367. * @type {number}
  23368. * @default 0
  23369. */
  23370. this.aY = aY;
  23371. /**
  23372. * The radius of the ellipse in the x direction.
  23373. * Setting the this value equal to the {@link EllipseCurve#yRadius} will result in a circle.
  23374. *
  23375. * @type {number}
  23376. * @default 1
  23377. */
  23378. this.xRadius = xRadius;
  23379. /**
  23380. * The radius of the ellipse in the y direction.
  23381. * Setting the this value equal to the {@link EllipseCurve#xRadius} will result in a circle.
  23382. *
  23383. * @type {number}
  23384. * @default 1
  23385. */
  23386. this.yRadius = yRadius;
  23387. /**
  23388. * The start angle of the curve in radians starting from the positive X axis.
  23389. *
  23390. * @type {number}
  23391. * @default 0
  23392. */
  23393. this.aStartAngle = aStartAngle;
  23394. /**
  23395. * The end angle of the curve in radians starting from the positive X axis.
  23396. *
  23397. * @type {number}
  23398. * @default Math.PI*2
  23399. */
  23400. this.aEndAngle = aEndAngle;
  23401. /**
  23402. * Whether the ellipse is drawn clockwise or not.
  23403. *
  23404. * @type {boolean}
  23405. * @default false
  23406. */
  23407. this.aClockwise = aClockwise;
  23408. /**
  23409. * The rotation angle of the ellipse in radians, counterclockwise from the positive X axis.
  23410. *
  23411. * @type {number}
  23412. * @default 0
  23413. */
  23414. this.aRotation = aRotation;
  23415. }
  23416. /**
  23417. * Returns a point on the curve.
  23418. *
  23419. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  23420. * @param {Vector2} [optionalTarget] - The optional target vector the result is written to.
  23421. * @return {Vector2} The position on the curve.
  23422. */
  23423. getPoint( t, optionalTarget = new Vector2() ) {
  23424. const point = optionalTarget;
  23425. const twoPi = Math.PI * 2;
  23426. let deltaAngle = this.aEndAngle - this.aStartAngle;
  23427. const samePoints = Math.abs( deltaAngle ) < Number.EPSILON;
  23428. // ensures that deltaAngle is 0 .. 2 PI
  23429. while ( deltaAngle < 0 ) deltaAngle += twoPi;
  23430. while ( deltaAngle > twoPi ) deltaAngle -= twoPi;
  23431. if ( deltaAngle < Number.EPSILON ) {
  23432. if ( samePoints ) {
  23433. deltaAngle = 0;
  23434. } else {
  23435. deltaAngle = twoPi;
  23436. }
  23437. }
  23438. if ( this.aClockwise === true && ! samePoints ) {
  23439. if ( deltaAngle === twoPi ) {
  23440. deltaAngle = - twoPi;
  23441. } else {
  23442. deltaAngle = deltaAngle - twoPi;
  23443. }
  23444. }
  23445. const angle = this.aStartAngle + t * deltaAngle;
  23446. let x = this.aX + this.xRadius * Math.cos( angle );
  23447. let y = this.aY + this.yRadius * Math.sin( angle );
  23448. if ( this.aRotation !== 0 ) {
  23449. const cos = Math.cos( this.aRotation );
  23450. const sin = Math.sin( this.aRotation );
  23451. const tx = x - this.aX;
  23452. const ty = y - this.aY;
  23453. // Rotate the point about the center of the ellipse.
  23454. x = tx * cos - ty * sin + this.aX;
  23455. y = tx * sin + ty * cos + this.aY;
  23456. }
  23457. return point.set( x, y );
  23458. }
  23459. copy( source ) {
  23460. super.copy( source );
  23461. this.aX = source.aX;
  23462. this.aY = source.aY;
  23463. this.xRadius = source.xRadius;
  23464. this.yRadius = source.yRadius;
  23465. this.aStartAngle = source.aStartAngle;
  23466. this.aEndAngle = source.aEndAngle;
  23467. this.aClockwise = source.aClockwise;
  23468. this.aRotation = source.aRotation;
  23469. return this;
  23470. }
  23471. toJSON() {
  23472. const data = super.toJSON();
  23473. data.aX = this.aX;
  23474. data.aY = this.aY;
  23475. data.xRadius = this.xRadius;
  23476. data.yRadius = this.yRadius;
  23477. data.aStartAngle = this.aStartAngle;
  23478. data.aEndAngle = this.aEndAngle;
  23479. data.aClockwise = this.aClockwise;
  23480. data.aRotation = this.aRotation;
  23481. return data;
  23482. }
  23483. fromJSON( json ) {
  23484. super.fromJSON( json );
  23485. this.aX = json.aX;
  23486. this.aY = json.aY;
  23487. this.xRadius = json.xRadius;
  23488. this.yRadius = json.yRadius;
  23489. this.aStartAngle = json.aStartAngle;
  23490. this.aEndAngle = json.aEndAngle;
  23491. this.aClockwise = json.aClockwise;
  23492. this.aRotation = json.aRotation;
  23493. return this;
  23494. }
  23495. }
  23496. /**
  23497. * A curve representing an arc.
  23498. *
  23499. * @augments EllipseCurve
  23500. */
  23501. class ArcCurve extends EllipseCurve {
  23502. /**
  23503. * Constructs a new arc curve.
  23504. *
  23505. * @param {number} [aX=0] - The X center of the ellipse.
  23506. * @param {number} [aY=0] - The Y center of the ellipse.
  23507. * @param {number} [aRadius=1] - The radius of the ellipse in the x direction.
  23508. * @param {number} [aStartAngle=0] - The start angle of the curve in radians starting from the positive X axis.
  23509. * @param {number} [aEndAngle=Math.PI*2] - The end angle of the curve in radians starting from the positive X axis.
  23510. * @param {boolean} [aClockwise=false] - Whether the ellipse is drawn clockwise or not.
  23511. */
  23512. constructor( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  23513. super( aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  23514. /**
  23515. * This flag can be used for type testing.
  23516. *
  23517. * @type {boolean}
  23518. * @readonly
  23519. * @default true
  23520. */
  23521. this.isArcCurve = true;
  23522. this.type = 'ArcCurve';
  23523. }
  23524. }
  23525. function CubicPoly() {
  23526. /**
  23527. * Centripetal CatmullRom Curve - which is useful for avoiding
  23528. * cusps and self-intersections in non-uniform catmull rom curves.
  23529. * http://www.cemyuksel.com/research/catmullrom_param/catmullrom.pdf
  23530. *
  23531. * curve.type accepts centripetal(default), chordal and catmullrom
  23532. * curve.tension is used for catmullrom which defaults to 0.5
  23533. */
  23534. /*
  23535. Based on an optimized c++ solution in
  23536. - http://stackoverflow.com/questions/9489736/catmull-rom-curve-with-no-cusps-and-no-self-intersections/
  23537. - http://ideone.com/NoEbVM
  23538. This CubicPoly class could be used for reusing some variables and calculations,
  23539. but for three.js curve use, it could be possible inlined and flatten into a single function call
  23540. which can be placed in CurveUtils.
  23541. */
  23542. let c0 = 0, c1 = 0, c2 = 0, c3 = 0;
  23543. /*
  23544. * Compute coefficients for a cubic polynomial
  23545. * p(s) = c0 + c1*s + c2*s^2 + c3*s^3
  23546. * such that
  23547. * p(0) = x0, p(1) = x1
  23548. * and
  23549. * p'(0) = t0, p'(1) = t1.
  23550. */
  23551. function init( x0, x1, t0, t1 ) {
  23552. c0 = x0;
  23553. c1 = t0;
  23554. c2 = -3 * x0 + 3 * x1 - 2 * t0 - t1;
  23555. c3 = 2 * x0 - 2 * x1 + t0 + t1;
  23556. }
  23557. return {
  23558. initCatmullRom: function ( x0, x1, x2, x3, tension ) {
  23559. init( x1, x2, tension * ( x2 - x0 ), tension * ( x3 - x1 ) );
  23560. },
  23561. initNonuniformCatmullRom: function ( x0, x1, x2, x3, dt0, dt1, dt2 ) {
  23562. // compute tangents when parameterized in [t1,t2]
  23563. let t1 = ( x1 - x0 ) / dt0 - ( x2 - x0 ) / ( dt0 + dt1 ) + ( x2 - x1 ) / dt1;
  23564. let t2 = ( x2 - x1 ) / dt1 - ( x3 - x1 ) / ( dt1 + dt2 ) + ( x3 - x2 ) / dt2;
  23565. // rescale tangents for parametrization in [0,1]
  23566. t1 *= dt1;
  23567. t2 *= dt1;
  23568. init( x1, x2, t1, t2 );
  23569. },
  23570. calc: function ( t ) {
  23571. const t2 = t * t;
  23572. const t3 = t2 * t;
  23573. return c0 + c1 * t + c2 * t2 + c3 * t3;
  23574. }
  23575. };
  23576. }
  23577. //
  23578. const tmp = /*@__PURE__*/ new Vector3();
  23579. const px = /*@__PURE__*/ new CubicPoly();
  23580. const py = /*@__PURE__*/ new CubicPoly();
  23581. const pz = /*@__PURE__*/ new CubicPoly();
  23582. /**
  23583. * A curve representing a Catmull-Rom spline.
  23584. *
  23585. * ```js
  23586. * //Create a closed wavey loop
  23587. * const curve = new THREE.CatmullRomCurve3( [
  23588. * new THREE.Vector3( -10, 0, 10 ),
  23589. * new THREE.Vector3( -5, 5, 5 ),
  23590. * new THREE.Vector3( 0, 0, 0 ),
  23591. * new THREE.Vector3( 5, -5, 5 ),
  23592. * new THREE.Vector3( 10, 0, 10 )
  23593. * ] );
  23594. *
  23595. * const points = curve.getPoints( 50 );
  23596. * const geometry = new THREE.BufferGeometry().setFromPoints( points );
  23597. *
  23598. * const material = new THREE.LineBasicMaterial( { color: 0xff0000 } );
  23599. *
  23600. * // Create the final object to add to the scene
  23601. * const curveObject = new THREE.Line( geometry, material );
  23602. * ```
  23603. *
  23604. * @augments Curve
  23605. */
  23606. class CatmullRomCurve3 extends Curve {
  23607. /**
  23608. * Constructs a new Catmull-Rom curve.
  23609. *
  23610. * @param {Array<Vector3>} [points] - An array of 3D points defining the curve.
  23611. * @param {boolean} [closed=false] - Whether the curve is closed or not.
  23612. * @param {('centripetal'|'chordal'|'catmullrom')} [curveType='centripetal'] - The curve type.
  23613. * @param {number} [tension=0.5] - Tension of the curve.
  23614. */
  23615. constructor( points = [], closed = false, curveType = 'centripetal', tension = 0.5 ) {
  23616. super();
  23617. /**
  23618. * This flag can be used for type testing.
  23619. *
  23620. * @type {boolean}
  23621. * @readonly
  23622. * @default true
  23623. */
  23624. this.isCatmullRomCurve3 = true;
  23625. this.type = 'CatmullRomCurve3';
  23626. /**
  23627. * An array of 3D points defining the curve.
  23628. *
  23629. * @type {Array<Vector3>}
  23630. */
  23631. this.points = points;
  23632. /**
  23633. * Whether the curve is closed or not.
  23634. *
  23635. * @type {boolean}
  23636. * @default false
  23637. */
  23638. this.closed = closed;
  23639. /**
  23640. * The curve type.
  23641. *
  23642. * @type {('centripetal'|'chordal'|'catmullrom')}
  23643. * @default 'centripetal'
  23644. */
  23645. this.curveType = curveType;
  23646. /**
  23647. * Tension of the curve.
  23648. *
  23649. * @type {number}
  23650. * @default 0.5
  23651. */
  23652. this.tension = tension;
  23653. }
  23654. /**
  23655. * Returns a point on the curve.
  23656. *
  23657. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  23658. * @param {Vector3} [optionalTarget] - The optional target vector the result is written to.
  23659. * @return {Vector3} The position on the curve.
  23660. */
  23661. getPoint( t, optionalTarget = new Vector3() ) {
  23662. const point = optionalTarget;
  23663. const points = this.points;
  23664. const l = points.length;
  23665. const p = ( l - ( this.closed ? 0 : 1 ) ) * t;
  23666. let intPoint = Math.floor( p );
  23667. let weight = p - intPoint;
  23668. if ( this.closed ) {
  23669. intPoint += intPoint > 0 ? 0 : ( Math.floor( Math.abs( intPoint ) / l ) + 1 ) * l;
  23670. } else if ( weight === 0 && intPoint === l - 1 ) {
  23671. intPoint = l - 2;
  23672. weight = 1;
  23673. }
  23674. let p0, p3; // 4 points (p1 & p2 defined below)
  23675. if ( this.closed || intPoint > 0 ) {
  23676. p0 = points[ ( intPoint - 1 ) % l ];
  23677. } else {
  23678. // extrapolate first point
  23679. tmp.subVectors( points[ 0 ], points[ 1 ] ).add( points[ 0 ] );
  23680. p0 = tmp;
  23681. }
  23682. const p1 = points[ intPoint % l ];
  23683. const p2 = points[ ( intPoint + 1 ) % l ];
  23684. if ( this.closed || intPoint + 2 < l ) {
  23685. p3 = points[ ( intPoint + 2 ) % l ];
  23686. } else {
  23687. // extrapolate last point
  23688. tmp.subVectors( points[ l - 1 ], points[ l - 2 ] ).add( points[ l - 1 ] );
  23689. p3 = tmp;
  23690. }
  23691. if ( this.curveType === 'centripetal' || this.curveType === 'chordal' ) {
  23692. // init Centripetal / Chordal Catmull-Rom
  23693. const pow = this.curveType === 'chordal' ? 0.5 : 0.25;
  23694. let dt0 = Math.pow( p0.distanceToSquared( p1 ), pow );
  23695. let dt1 = Math.pow( p1.distanceToSquared( p2 ), pow );
  23696. let dt2 = Math.pow( p2.distanceToSquared( p3 ), pow );
  23697. // safety check for repeated points
  23698. if ( dt1 < 1e-4 ) dt1 = 1.0;
  23699. if ( dt0 < 1e-4 ) dt0 = dt1;
  23700. if ( dt2 < 1e-4 ) dt2 = dt1;
  23701. px.initNonuniformCatmullRom( p0.x, p1.x, p2.x, p3.x, dt0, dt1, dt2 );
  23702. py.initNonuniformCatmullRom( p0.y, p1.y, p2.y, p3.y, dt0, dt1, dt2 );
  23703. pz.initNonuniformCatmullRom( p0.z, p1.z, p2.z, p3.z, dt0, dt1, dt2 );
  23704. } else if ( this.curveType === 'catmullrom' ) {
  23705. px.initCatmullRom( p0.x, p1.x, p2.x, p3.x, this.tension );
  23706. py.initCatmullRom( p0.y, p1.y, p2.y, p3.y, this.tension );
  23707. pz.initCatmullRom( p0.z, p1.z, p2.z, p3.z, this.tension );
  23708. }
  23709. point.set(
  23710. px.calc( weight ),
  23711. py.calc( weight ),
  23712. pz.calc( weight )
  23713. );
  23714. return point;
  23715. }
  23716. copy( source ) {
  23717. super.copy( source );
  23718. this.points = [];
  23719. for ( let i = 0, l = source.points.length; i < l; i ++ ) {
  23720. const point = source.points[ i ];
  23721. this.points.push( point.clone() );
  23722. }
  23723. this.closed = source.closed;
  23724. this.curveType = source.curveType;
  23725. this.tension = source.tension;
  23726. return this;
  23727. }
  23728. toJSON() {
  23729. const data = super.toJSON();
  23730. data.points = [];
  23731. for ( let i = 0, l = this.points.length; i < l; i ++ ) {
  23732. const point = this.points[ i ];
  23733. data.points.push( point.toArray() );
  23734. }
  23735. data.closed = this.closed;
  23736. data.curveType = this.curveType;
  23737. data.tension = this.tension;
  23738. return data;
  23739. }
  23740. fromJSON( json ) {
  23741. super.fromJSON( json );
  23742. this.points = [];
  23743. for ( let i = 0, l = json.points.length; i < l; i ++ ) {
  23744. const point = json.points[ i ];
  23745. this.points.push( new Vector3().fromArray( point ) );
  23746. }
  23747. this.closed = json.closed;
  23748. this.curveType = json.curveType;
  23749. this.tension = json.tension;
  23750. return this;
  23751. }
  23752. }
  23753. // Bezier Curves formulas obtained from: https://en.wikipedia.org/wiki/B%C3%A9zier_curve
  23754. /**
  23755. * Computes a point on a Catmull-Rom spline.
  23756. *
  23757. * @param {number} t - The interpolation factor.
  23758. * @param {number} p0 - The first control point.
  23759. * @param {number} p1 - The second control point.
  23760. * @param {number} p2 - The third control point.
  23761. * @param {number} p3 - The fourth control point.
  23762. * @return {number} The calculated point on a Catmull-Rom spline.
  23763. */
  23764. function CatmullRom( t, p0, p1, p2, p3 ) {
  23765. const v0 = ( p2 - p0 ) * 0.5;
  23766. const v1 = ( p3 - p1 ) * 0.5;
  23767. const t2 = t * t;
  23768. const t3 = t * t2;
  23769. return ( 2 * p1 - 2 * p2 + v0 + v1 ) * t3 + ( -3 * p1 + 3 * p2 - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  23770. }
  23771. //
  23772. function QuadraticBezierP0( t, p ) {
  23773. const k = 1 - t;
  23774. return k * k * p;
  23775. }
  23776. function QuadraticBezierP1( t, p ) {
  23777. return 2 * ( 1 - t ) * t * p;
  23778. }
  23779. function QuadraticBezierP2( t, p ) {
  23780. return t * t * p;
  23781. }
  23782. /**
  23783. * Computes a point on a Quadratic Bezier curve.
  23784. *
  23785. * @param {number} t - The interpolation factor.
  23786. * @param {number} p0 - The first control point.
  23787. * @param {number} p1 - The second control point.
  23788. * @param {number} p2 - The third control point.
  23789. * @return {number} The calculated point on a Quadratic Bezier curve.
  23790. */
  23791. function QuadraticBezier( t, p0, p1, p2 ) {
  23792. return QuadraticBezierP0( t, p0 ) + QuadraticBezierP1( t, p1 ) +
  23793. QuadraticBezierP2( t, p2 );
  23794. }
  23795. //
  23796. function CubicBezierP0( t, p ) {
  23797. const k = 1 - t;
  23798. return k * k * k * p;
  23799. }
  23800. function CubicBezierP1( t, p ) {
  23801. const k = 1 - t;
  23802. return 3 * k * k * t * p;
  23803. }
  23804. function CubicBezierP2( t, p ) {
  23805. return 3 * ( 1 - t ) * t * t * p;
  23806. }
  23807. function CubicBezierP3( t, p ) {
  23808. return t * t * t * p;
  23809. }
  23810. /**
  23811. * Computes a point on a Cubic Bezier curve.
  23812. *
  23813. * @param {number} t - The interpolation factor.
  23814. * @param {number} p0 - The first control point.
  23815. * @param {number} p1 - The second control point.
  23816. * @param {number} p2 - The third control point.
  23817. * @param {number} p3 - The fourth control point.
  23818. * @return {number} The calculated point on a Cubic Bezier curve.
  23819. */
  23820. function CubicBezier( t, p0, p1, p2, p3 ) {
  23821. return CubicBezierP0( t, p0 ) + CubicBezierP1( t, p1 ) + CubicBezierP2( t, p2 ) +
  23822. CubicBezierP3( t, p3 );
  23823. }
  23824. /**
  23825. * A curve representing a 2D Cubic Bezier curve.
  23826. *
  23827. * ```js
  23828. * const curve = new THREE.CubicBezierCurve(
  23829. * new THREE.Vector2( - 0, 0 ),
  23830. * new THREE.Vector2( - 5, 15 ),
  23831. * new THREE.Vector2( 20, 15 ),
  23832. * new THREE.Vector2( 10, 0 )
  23833. * );
  23834. *
  23835. * const points = curve.getPoints( 50 );
  23836. * const geometry = new THREE.BufferGeometry().setFromPoints( points );
  23837. *
  23838. * const material = new THREE.LineBasicMaterial( { color: 0xff0000 } );
  23839. *
  23840. * // Create the final object to add to the scene
  23841. * const curveObject = new THREE.Line( geometry, material );
  23842. * ```
  23843. *
  23844. * @augments Curve
  23845. */
  23846. class CubicBezierCurve extends Curve {
  23847. /**
  23848. * Constructs a new Cubic Bezier curve.
  23849. *
  23850. * @param {Vector2} [v0] - The start point.
  23851. * @param {Vector2} [v1] - The first control point.
  23852. * @param {Vector2} [v2] - The second control point.
  23853. * @param {Vector2} [v3] - The end point.
  23854. */
  23855. constructor( v0 = new Vector2(), v1 = new Vector2(), v2 = new Vector2(), v3 = new Vector2() ) {
  23856. super();
  23857. /**
  23858. * This flag can be used for type testing.
  23859. *
  23860. * @type {boolean}
  23861. * @readonly
  23862. * @default true
  23863. */
  23864. this.isCubicBezierCurve = true;
  23865. this.type = 'CubicBezierCurve';
  23866. /**
  23867. * The start point.
  23868. *
  23869. * @type {Vector2}
  23870. */
  23871. this.v0 = v0;
  23872. /**
  23873. * The first control point.
  23874. *
  23875. * @type {Vector2}
  23876. */
  23877. this.v1 = v1;
  23878. /**
  23879. * The second control point.
  23880. *
  23881. * @type {Vector2}
  23882. */
  23883. this.v2 = v2;
  23884. /**
  23885. * The end point.
  23886. *
  23887. * @type {Vector2}
  23888. */
  23889. this.v3 = v3;
  23890. }
  23891. /**
  23892. * Returns a point on the curve.
  23893. *
  23894. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  23895. * @param {Vector2} [optionalTarget] - The optional target vector the result is written to.
  23896. * @return {Vector2} The position on the curve.
  23897. */
  23898. getPoint( t, optionalTarget = new Vector2() ) {
  23899. const point = optionalTarget;
  23900. const v0 = this.v0, v1 = this.v1, v2 = this.v2, v3 = this.v3;
  23901. point.set(
  23902. CubicBezier( t, v0.x, v1.x, v2.x, v3.x ),
  23903. CubicBezier( t, v0.y, v1.y, v2.y, v3.y )
  23904. );
  23905. return point;
  23906. }
  23907. copy( source ) {
  23908. super.copy( source );
  23909. this.v0.copy( source.v0 );
  23910. this.v1.copy( source.v1 );
  23911. this.v2.copy( source.v2 );
  23912. this.v3.copy( source.v3 );
  23913. return this;
  23914. }
  23915. toJSON() {
  23916. const data = super.toJSON();
  23917. data.v0 = this.v0.toArray();
  23918. data.v1 = this.v1.toArray();
  23919. data.v2 = this.v2.toArray();
  23920. data.v3 = this.v3.toArray();
  23921. return data;
  23922. }
  23923. fromJSON( json ) {
  23924. super.fromJSON( json );
  23925. this.v0.fromArray( json.v0 );
  23926. this.v1.fromArray( json.v1 );
  23927. this.v2.fromArray( json.v2 );
  23928. this.v3.fromArray( json.v3 );
  23929. return this;
  23930. }
  23931. }
  23932. /**
  23933. * A curve representing a 3D Cubic Bezier curve.
  23934. *
  23935. * @augments Curve
  23936. */
  23937. class CubicBezierCurve3 extends Curve {
  23938. /**
  23939. * Constructs a new Cubic Bezier curve.
  23940. *
  23941. * @param {Vector3} [v0] - The start point.
  23942. * @param {Vector3} [v1] - The first control point.
  23943. * @param {Vector3} [v2] - The second control point.
  23944. * @param {Vector3} [v3] - The end point.
  23945. */
  23946. constructor( v0 = new Vector3(), v1 = new Vector3(), v2 = new Vector3(), v3 = new Vector3() ) {
  23947. super();
  23948. /**
  23949. * This flag can be used for type testing.
  23950. *
  23951. * @type {boolean}
  23952. * @readonly
  23953. * @default true
  23954. */
  23955. this.isCubicBezierCurve3 = true;
  23956. this.type = 'CubicBezierCurve3';
  23957. /**
  23958. * The start point.
  23959. *
  23960. * @type {Vector3}
  23961. */
  23962. this.v0 = v0;
  23963. /**
  23964. * The first control point.
  23965. *
  23966. * @type {Vector3}
  23967. */
  23968. this.v1 = v1;
  23969. /**
  23970. * The second control point.
  23971. *
  23972. * @type {Vector3}
  23973. */
  23974. this.v2 = v2;
  23975. /**
  23976. * The end point.
  23977. *
  23978. * @type {Vector3}
  23979. */
  23980. this.v3 = v3;
  23981. }
  23982. /**
  23983. * Returns a point on the curve.
  23984. *
  23985. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  23986. * @param {Vector3} [optionalTarget] - The optional target vector the result is written to.
  23987. * @return {Vector3} The position on the curve.
  23988. */
  23989. getPoint( t, optionalTarget = new Vector3() ) {
  23990. const point = optionalTarget;
  23991. const v0 = this.v0, v1 = this.v1, v2 = this.v2, v3 = this.v3;
  23992. point.set(
  23993. CubicBezier( t, v0.x, v1.x, v2.x, v3.x ),
  23994. CubicBezier( t, v0.y, v1.y, v2.y, v3.y ),
  23995. CubicBezier( t, v0.z, v1.z, v2.z, v3.z )
  23996. );
  23997. return point;
  23998. }
  23999. copy( source ) {
  24000. super.copy( source );
  24001. this.v0.copy( source.v0 );
  24002. this.v1.copy( source.v1 );
  24003. this.v2.copy( source.v2 );
  24004. this.v3.copy( source.v3 );
  24005. return this;
  24006. }
  24007. toJSON() {
  24008. const data = super.toJSON();
  24009. data.v0 = this.v0.toArray();
  24010. data.v1 = this.v1.toArray();
  24011. data.v2 = this.v2.toArray();
  24012. data.v3 = this.v3.toArray();
  24013. return data;
  24014. }
  24015. fromJSON( json ) {
  24016. super.fromJSON( json );
  24017. this.v0.fromArray( json.v0 );
  24018. this.v1.fromArray( json.v1 );
  24019. this.v2.fromArray( json.v2 );
  24020. this.v3.fromArray( json.v3 );
  24021. return this;
  24022. }
  24023. }
  24024. /**
  24025. * A curve representing a 2D line segment.
  24026. *
  24027. * @augments Curve
  24028. */
  24029. class LineCurve extends Curve {
  24030. /**
  24031. * Constructs a new line curve.
  24032. *
  24033. * @param {Vector2} [v1] - The start point.
  24034. * @param {Vector2} [v2] - The end point.
  24035. */
  24036. constructor( v1 = new Vector2(), v2 = new Vector2() ) {
  24037. super();
  24038. /**
  24039. * This flag can be used for type testing.
  24040. *
  24041. * @type {boolean}
  24042. * @readonly
  24043. * @default true
  24044. */
  24045. this.isLineCurve = true;
  24046. this.type = 'LineCurve';
  24047. /**
  24048. * The start point.
  24049. *
  24050. * @type {Vector2}
  24051. */
  24052. this.v1 = v1;
  24053. /**
  24054. * The end point.
  24055. *
  24056. * @type {Vector2}
  24057. */
  24058. this.v2 = v2;
  24059. }
  24060. /**
  24061. * Returns a point on the line.
  24062. *
  24063. * @param {number} t - A interpolation factor representing a position on the line. Must be in the range `[0,1]`.
  24064. * @param {Vector2} [optionalTarget] - The optional target vector the result is written to.
  24065. * @return {Vector2} The position on the line.
  24066. */
  24067. getPoint( t, optionalTarget = new Vector2() ) {
  24068. const point = optionalTarget;
  24069. if ( t === 1 ) {
  24070. point.copy( this.v2 );
  24071. } else {
  24072. point.copy( this.v2 ).sub( this.v1 );
  24073. point.multiplyScalar( t ).add( this.v1 );
  24074. }
  24075. return point;
  24076. }
  24077. // Line curve is linear, so we can overwrite default getPointAt
  24078. getPointAt( u, optionalTarget ) {
  24079. return this.getPoint( u, optionalTarget );
  24080. }
  24081. getTangent( t, optionalTarget = new Vector2() ) {
  24082. return optionalTarget.subVectors( this.v2, this.v1 ).normalize();
  24083. }
  24084. getTangentAt( u, optionalTarget ) {
  24085. return this.getTangent( u, optionalTarget );
  24086. }
  24087. copy( source ) {
  24088. super.copy( source );
  24089. this.v1.copy( source.v1 );
  24090. this.v2.copy( source.v2 );
  24091. return this;
  24092. }
  24093. toJSON() {
  24094. const data = super.toJSON();
  24095. data.v1 = this.v1.toArray();
  24096. data.v2 = this.v2.toArray();
  24097. return data;
  24098. }
  24099. fromJSON( json ) {
  24100. super.fromJSON( json );
  24101. this.v1.fromArray( json.v1 );
  24102. this.v2.fromArray( json.v2 );
  24103. return this;
  24104. }
  24105. }
  24106. /**
  24107. * A curve representing a 3D line segment.
  24108. *
  24109. * @augments Curve
  24110. */
  24111. class LineCurve3 extends Curve {
  24112. /**
  24113. * Constructs a new line curve.
  24114. *
  24115. * @param {Vector3} [v1] - The start point.
  24116. * @param {Vector3} [v2] - The end point.
  24117. */
  24118. constructor( v1 = new Vector3(), v2 = new Vector3() ) {
  24119. super();
  24120. /**
  24121. * This flag can be used for type testing.
  24122. *
  24123. * @type {boolean}
  24124. * @readonly
  24125. * @default true
  24126. */
  24127. this.isLineCurve3 = true;
  24128. this.type = 'LineCurve3';
  24129. /**
  24130. * The start point.
  24131. *
  24132. * @type {Vector3}
  24133. */
  24134. this.v1 = v1;
  24135. /**
  24136. * The end point.
  24137. *
  24138. * @type {Vector2}
  24139. */
  24140. this.v2 = v2;
  24141. }
  24142. /**
  24143. * Returns a point on the line.
  24144. *
  24145. * @param {number} t - A interpolation factor representing a position on the line. Must be in the range `[0,1]`.
  24146. * @param {Vector3} [optionalTarget] - The optional target vector the result is written to.
  24147. * @return {Vector3} The position on the line.
  24148. */
  24149. getPoint( t, optionalTarget = new Vector3() ) {
  24150. const point = optionalTarget;
  24151. if ( t === 1 ) {
  24152. point.copy( this.v2 );
  24153. } else {
  24154. point.copy( this.v2 ).sub( this.v1 );
  24155. point.multiplyScalar( t ).add( this.v1 );
  24156. }
  24157. return point;
  24158. }
  24159. // Line curve is linear, so we can overwrite default getPointAt
  24160. getPointAt( u, optionalTarget ) {
  24161. return this.getPoint( u, optionalTarget );
  24162. }
  24163. getTangent( t, optionalTarget = new Vector3() ) {
  24164. return optionalTarget.subVectors( this.v2, this.v1 ).normalize();
  24165. }
  24166. getTangentAt( u, optionalTarget ) {
  24167. return this.getTangent( u, optionalTarget );
  24168. }
  24169. copy( source ) {
  24170. super.copy( source );
  24171. this.v1.copy( source.v1 );
  24172. this.v2.copy( source.v2 );
  24173. return this;
  24174. }
  24175. toJSON() {
  24176. const data = super.toJSON();
  24177. data.v1 = this.v1.toArray();
  24178. data.v2 = this.v2.toArray();
  24179. return data;
  24180. }
  24181. fromJSON( json ) {
  24182. super.fromJSON( json );
  24183. this.v1.fromArray( json.v1 );
  24184. this.v2.fromArray( json.v2 );
  24185. return this;
  24186. }
  24187. }
  24188. /**
  24189. * A curve representing a 2D Quadratic Bezier curve.
  24190. *
  24191. * ```js
  24192. * const curve = new THREE.QuadraticBezierCurve(
  24193. * new THREE.Vector2( - 10, 0 ),
  24194. * new THREE.Vector2( 20, 15 ),
  24195. * new THREE.Vector2( 10, 0 )
  24196. * )
  24197. *
  24198. * const points = curve.getPoints( 50 );
  24199. * const geometry = new THREE.BufferGeometry().setFromPoints( points );
  24200. *
  24201. * const material = new THREE.LineBasicMaterial( { color: 0xff0000 } );
  24202. *
  24203. * // Create the final object to add to the scene
  24204. * const curveObject = new THREE.Line( geometry, material );
  24205. * ```
  24206. *
  24207. * @augments Curve
  24208. */
  24209. class QuadraticBezierCurve extends Curve {
  24210. /**
  24211. * Constructs a new Quadratic Bezier curve.
  24212. *
  24213. * @param {Vector2} [v0] - The start point.
  24214. * @param {Vector2} [v1] - The control point.
  24215. * @param {Vector2} [v2] - The end point.
  24216. */
  24217. constructor( v0 = new Vector2(), v1 = new Vector2(), v2 = new Vector2() ) {
  24218. super();
  24219. /**
  24220. * This flag can be used for type testing.
  24221. *
  24222. * @type {boolean}
  24223. * @readonly
  24224. * @default true
  24225. */
  24226. this.isQuadraticBezierCurve = true;
  24227. this.type = 'QuadraticBezierCurve';
  24228. /**
  24229. * The start point.
  24230. *
  24231. * @type {Vector2}
  24232. */
  24233. this.v0 = v0;
  24234. /**
  24235. * The control point.
  24236. *
  24237. * @type {Vector2}
  24238. */
  24239. this.v1 = v1;
  24240. /**
  24241. * The end point.
  24242. *
  24243. * @type {Vector2}
  24244. */
  24245. this.v2 = v2;
  24246. }
  24247. /**
  24248. * Returns a point on the curve.
  24249. *
  24250. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  24251. * @param {Vector2} [optionalTarget] - The optional target vector the result is written to.
  24252. * @return {Vector2} The position on the curve.
  24253. */
  24254. getPoint( t, optionalTarget = new Vector2() ) {
  24255. const point = optionalTarget;
  24256. const v0 = this.v0, v1 = this.v1, v2 = this.v2;
  24257. point.set(
  24258. QuadraticBezier( t, v0.x, v1.x, v2.x ),
  24259. QuadraticBezier( t, v0.y, v1.y, v2.y )
  24260. );
  24261. return point;
  24262. }
  24263. copy( source ) {
  24264. super.copy( source );
  24265. this.v0.copy( source.v0 );
  24266. this.v1.copy( source.v1 );
  24267. this.v2.copy( source.v2 );
  24268. return this;
  24269. }
  24270. toJSON() {
  24271. const data = super.toJSON();
  24272. data.v0 = this.v0.toArray();
  24273. data.v1 = this.v1.toArray();
  24274. data.v2 = this.v2.toArray();
  24275. return data;
  24276. }
  24277. fromJSON( json ) {
  24278. super.fromJSON( json );
  24279. this.v0.fromArray( json.v0 );
  24280. this.v1.fromArray( json.v1 );
  24281. this.v2.fromArray( json.v2 );
  24282. return this;
  24283. }
  24284. }
  24285. /**
  24286. * A curve representing a 3D Quadratic Bezier curve.
  24287. *
  24288. * @augments Curve
  24289. */
  24290. class QuadraticBezierCurve3 extends Curve {
  24291. /**
  24292. * Constructs a new Quadratic Bezier curve.
  24293. *
  24294. * @param {Vector3} [v0] - The start point.
  24295. * @param {Vector3} [v1] - The control point.
  24296. * @param {Vector3} [v2] - The end point.
  24297. */
  24298. constructor( v0 = new Vector3(), v1 = new Vector3(), v2 = new Vector3() ) {
  24299. super();
  24300. /**
  24301. * This flag can be used for type testing.
  24302. *
  24303. * @type {boolean}
  24304. * @readonly
  24305. * @default true
  24306. */
  24307. this.isQuadraticBezierCurve3 = true;
  24308. this.type = 'QuadraticBezierCurve3';
  24309. /**
  24310. * The start point.
  24311. *
  24312. * @type {Vector3}
  24313. */
  24314. this.v0 = v0;
  24315. /**
  24316. * The control point.
  24317. *
  24318. * @type {Vector3}
  24319. */
  24320. this.v1 = v1;
  24321. /**
  24322. * The end point.
  24323. *
  24324. * @type {Vector3}
  24325. */
  24326. this.v2 = v2;
  24327. }
  24328. /**
  24329. * Returns a point on the curve.
  24330. *
  24331. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  24332. * @param {Vector3} [optionalTarget] - The optional target vector the result is written to.
  24333. * @return {Vector3} The position on the curve.
  24334. */
  24335. getPoint( t, optionalTarget = new Vector3() ) {
  24336. const point = optionalTarget;
  24337. const v0 = this.v0, v1 = this.v1, v2 = this.v2;
  24338. point.set(
  24339. QuadraticBezier( t, v0.x, v1.x, v2.x ),
  24340. QuadraticBezier( t, v0.y, v1.y, v2.y ),
  24341. QuadraticBezier( t, v0.z, v1.z, v2.z )
  24342. );
  24343. return point;
  24344. }
  24345. copy( source ) {
  24346. super.copy( source );
  24347. this.v0.copy( source.v0 );
  24348. this.v1.copy( source.v1 );
  24349. this.v2.copy( source.v2 );
  24350. return this;
  24351. }
  24352. toJSON() {
  24353. const data = super.toJSON();
  24354. data.v0 = this.v0.toArray();
  24355. data.v1 = this.v1.toArray();
  24356. data.v2 = this.v2.toArray();
  24357. return data;
  24358. }
  24359. fromJSON( json ) {
  24360. super.fromJSON( json );
  24361. this.v0.fromArray( json.v0 );
  24362. this.v1.fromArray( json.v1 );
  24363. this.v2.fromArray( json.v2 );
  24364. return this;
  24365. }
  24366. }
  24367. /**
  24368. * A curve representing a 2D spline curve.
  24369. *
  24370. * ```js
  24371. * // Create a sine-like wave
  24372. * const curve = new THREE.SplineCurve( [
  24373. * new THREE.Vector2( -10, 0 ),
  24374. * new THREE.Vector2( -5, 5 ),
  24375. * new THREE.Vector2( 0, 0 ),
  24376. * new THREE.Vector2( 5, -5 ),
  24377. * new THREE.Vector2( 10, 0 )
  24378. * ] );
  24379. *
  24380. * const points = curve.getPoints( 50 );
  24381. * const geometry = new THREE.BufferGeometry().setFromPoints( points );
  24382. *
  24383. * const material = new THREE.LineBasicMaterial( { color: 0xff0000 } );
  24384. *
  24385. * // Create the final object to add to the scene
  24386. * const splineObject = new THREE.Line( geometry, material );
  24387. * ```
  24388. *
  24389. * @augments Curve
  24390. */
  24391. class SplineCurve extends Curve {
  24392. /**
  24393. * Constructs a new 2D spline curve.
  24394. *
  24395. * @param {Array<Vector2>} [points] - An array of 2D points defining the curve.
  24396. */
  24397. constructor( points = [] ) {
  24398. super();
  24399. /**
  24400. * This flag can be used for type testing.
  24401. *
  24402. * @type {boolean}
  24403. * @readonly
  24404. * @default true
  24405. */
  24406. this.isSplineCurve = true;
  24407. this.type = 'SplineCurve';
  24408. /**
  24409. * An array of 2D points defining the curve.
  24410. *
  24411. * @type {Array<Vector2>}
  24412. */
  24413. this.points = points;
  24414. }
  24415. /**
  24416. * Returns a point on the curve.
  24417. *
  24418. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  24419. * @param {Vector2} [optionalTarget] - The optional target vector the result is written to.
  24420. * @return {Vector2} The position on the curve.
  24421. */
  24422. getPoint( t, optionalTarget = new Vector2() ) {
  24423. const point = optionalTarget;
  24424. const points = this.points;
  24425. const p = ( points.length - 1 ) * t;
  24426. const intPoint = Math.floor( p );
  24427. const weight = p - intPoint;
  24428. const p0 = points[ intPoint === 0 ? intPoint : intPoint - 1 ];
  24429. const p1 = points[ intPoint ];
  24430. const p2 = points[ intPoint > points.length - 2 ? points.length - 1 : intPoint + 1 ];
  24431. const p3 = points[ intPoint > points.length - 3 ? points.length - 1 : intPoint + 2 ];
  24432. point.set(
  24433. CatmullRom( weight, p0.x, p1.x, p2.x, p3.x ),
  24434. CatmullRom( weight, p0.y, p1.y, p2.y, p3.y )
  24435. );
  24436. return point;
  24437. }
  24438. copy( source ) {
  24439. super.copy( source );
  24440. this.points = [];
  24441. for ( let i = 0, l = source.points.length; i < l; i ++ ) {
  24442. const point = source.points[ i ];
  24443. this.points.push( point.clone() );
  24444. }
  24445. return this;
  24446. }
  24447. toJSON() {
  24448. const data = super.toJSON();
  24449. data.points = [];
  24450. for ( let i = 0, l = this.points.length; i < l; i ++ ) {
  24451. const point = this.points[ i ];
  24452. data.points.push( point.toArray() );
  24453. }
  24454. return data;
  24455. }
  24456. fromJSON( json ) {
  24457. super.fromJSON( json );
  24458. this.points = [];
  24459. for ( let i = 0, l = json.points.length; i < l; i ++ ) {
  24460. const point = json.points[ i ];
  24461. this.points.push( new Vector2().fromArray( point ) );
  24462. }
  24463. return this;
  24464. }
  24465. }
  24466. var Curves = /*#__PURE__*/Object.freeze({
  24467. __proto__: null,
  24468. ArcCurve: ArcCurve,
  24469. CatmullRomCurve3: CatmullRomCurve3,
  24470. CubicBezierCurve: CubicBezierCurve,
  24471. CubicBezierCurve3: CubicBezierCurve3,
  24472. EllipseCurve: EllipseCurve,
  24473. LineCurve: LineCurve,
  24474. LineCurve3: LineCurve3,
  24475. QuadraticBezierCurve: QuadraticBezierCurve,
  24476. QuadraticBezierCurve3: QuadraticBezierCurve3,
  24477. SplineCurve: SplineCurve
  24478. });
  24479. /**
  24480. * A base class extending {@link Curve}. `CurvePath` is simply an
  24481. * array of connected curves, but retains the API of a curve.
  24482. *
  24483. * @augments Curve
  24484. */
  24485. class CurvePath extends Curve {
  24486. /**
  24487. * Constructs a new curve path.
  24488. */
  24489. constructor() {
  24490. super();
  24491. this.type = 'CurvePath';
  24492. /**
  24493. * An array of curves defining the
  24494. * path.
  24495. *
  24496. * @type {Array<Curve>}
  24497. */
  24498. this.curves = [];
  24499. /**
  24500. * Whether the path should automatically be closed
  24501. * by a line curve.
  24502. *
  24503. * @type {boolean}
  24504. * @default false
  24505. */
  24506. this.autoClose = false;
  24507. }
  24508. /**
  24509. * Adds a curve to this curve path.
  24510. *
  24511. * @param {Curve} curve - The curve to add.
  24512. */
  24513. add( curve ) {
  24514. this.curves.push( curve );
  24515. }
  24516. /**
  24517. * Adds a line curve to close the path.
  24518. *
  24519. * @return {CurvePath} A reference to this curve path.
  24520. */
  24521. closePath() {
  24522. // Add a line curve if start and end of lines are not connected
  24523. const startPoint = this.curves[ 0 ].getPoint( 0 );
  24524. const endPoint = this.curves[ this.curves.length - 1 ].getPoint( 1 );
  24525. if ( ! startPoint.equals( endPoint ) ) {
  24526. const lineType = ( startPoint.isVector2 === true ) ? 'LineCurve' : 'LineCurve3';
  24527. this.curves.push( new Curves[ lineType ]( endPoint, startPoint ) );
  24528. }
  24529. return this;
  24530. }
  24531. /**
  24532. * This method returns a vector in 2D or 3D space (depending on the curve definitions)
  24533. * for the given interpolation factor.
  24534. *
  24535. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  24536. * @param {(Vector2|Vector3)} [optionalTarget] - The optional target vector the result is written to.
  24537. * @return {?(Vector2|Vector3)} The position on the curve. It can be a 2D or 3D vector depending on the curve definition.
  24538. */
  24539. getPoint( t, optionalTarget ) {
  24540. // To get accurate point with reference to
  24541. // entire path distance at time t,
  24542. // following has to be done:
  24543. // 1. Length of each sub path have to be known
  24544. // 2. Locate and identify type of curve
  24545. // 3. Get t for the curve
  24546. // 4. Return curve.getPointAt(t')
  24547. const d = t * this.getLength();
  24548. const curveLengths = this.getCurveLengths();
  24549. let i = 0;
  24550. // To think about boundaries points.
  24551. while ( i < curveLengths.length ) {
  24552. if ( curveLengths[ i ] >= d ) {
  24553. const diff = curveLengths[ i ] - d;
  24554. const curve = this.curves[ i ];
  24555. const segmentLength = curve.getLength();
  24556. const u = segmentLength === 0 ? 0 : 1 - diff / segmentLength;
  24557. return curve.getPointAt( u, optionalTarget );
  24558. }
  24559. i ++;
  24560. }
  24561. return null;
  24562. // loop where sum != 0, sum > d , sum+1 <d
  24563. }
  24564. getLength() {
  24565. // We cannot use the default THREE.Curve getPoint() with getLength() because in
  24566. // THREE.Curve, getLength() depends on getPoint() but in THREE.CurvePath
  24567. // getPoint() depends on getLength
  24568. const lens = this.getCurveLengths();
  24569. return lens[ lens.length - 1 ];
  24570. }
  24571. updateArcLengths() {
  24572. // cacheLengths must be recalculated.
  24573. this.needsUpdate = true;
  24574. this.cacheLengths = null;
  24575. this.getCurveLengths();
  24576. }
  24577. /**
  24578. * Returns list of cumulative curve lengths of the defined curves.
  24579. *
  24580. * @return {Array<number>} The curve lengths.
  24581. */
  24582. getCurveLengths() {
  24583. // Compute lengths and cache them
  24584. // We cannot overwrite getLengths() because UtoT mapping uses it.
  24585. // We use cache values if curves and cache array are same length
  24586. if ( this.cacheLengths && this.cacheLengths.length === this.curves.length ) {
  24587. return this.cacheLengths;
  24588. }
  24589. // Get length of sub-curve
  24590. // Push sums into cached array
  24591. const lengths = [];
  24592. let sums = 0;
  24593. for ( let i = 0, l = this.curves.length; i < l; i ++ ) {
  24594. sums += this.curves[ i ].getLength();
  24595. lengths.push( sums );
  24596. }
  24597. this.cacheLengths = lengths;
  24598. return lengths;
  24599. }
  24600. getSpacedPoints( divisions = 40 ) {
  24601. const points = [];
  24602. for ( let i = 0; i <= divisions; i ++ ) {
  24603. points.push( this.getPoint( i / divisions ) );
  24604. }
  24605. if ( this.autoClose ) {
  24606. points.push( points[ 0 ] );
  24607. }
  24608. return points;
  24609. }
  24610. getPoints( divisions = 12 ) {
  24611. const points = [];
  24612. let last;
  24613. for ( let i = 0, curves = this.curves; i < curves.length; i ++ ) {
  24614. const curve = curves[ i ];
  24615. const resolution = curve.isEllipseCurve ? divisions * 2
  24616. : ( curve.isLineCurve || curve.isLineCurve3 ) ? 1
  24617. : curve.isSplineCurve ? divisions * curve.points.length
  24618. : divisions;
  24619. const pts = curve.getPoints( resolution );
  24620. for ( let j = 0; j < pts.length; j ++ ) {
  24621. const point = pts[ j ];
  24622. if ( last && last.equals( point ) ) continue; // ensures no consecutive points are duplicates
  24623. points.push( point );
  24624. last = point;
  24625. }
  24626. }
  24627. if ( this.autoClose && points.length > 1 && ! points[ points.length - 1 ].equals( points[ 0 ] ) ) {
  24628. points.push( points[ 0 ] );
  24629. }
  24630. return points;
  24631. }
  24632. copy( source ) {
  24633. super.copy( source );
  24634. this.curves = [];
  24635. for ( let i = 0, l = source.curves.length; i < l; i ++ ) {
  24636. const curve = source.curves[ i ];
  24637. this.curves.push( curve.clone() );
  24638. }
  24639. this.autoClose = source.autoClose;
  24640. return this;
  24641. }
  24642. toJSON() {
  24643. const data = super.toJSON();
  24644. data.autoClose = this.autoClose;
  24645. data.curves = [];
  24646. for ( let i = 0, l = this.curves.length; i < l; i ++ ) {
  24647. const curve = this.curves[ i ];
  24648. data.curves.push( curve.toJSON() );
  24649. }
  24650. return data;
  24651. }
  24652. fromJSON( json ) {
  24653. super.fromJSON( json );
  24654. this.autoClose = json.autoClose;
  24655. this.curves = [];
  24656. for ( let i = 0, l = json.curves.length; i < l; i ++ ) {
  24657. const curve = json.curves[ i ];
  24658. this.curves.push( new Curves[ curve.type ]().fromJSON( curve ) );
  24659. }
  24660. return this;
  24661. }
  24662. }
  24663. /**
  24664. * A 2D path representation. The class provides methods for creating paths
  24665. * and contours of 2D shapes similar to the 2D Canvas API.
  24666. *
  24667. * ```js
  24668. * const path = new THREE.Path();
  24669. *
  24670. * path.lineTo( 0, 0.8 );
  24671. * path.quadraticCurveTo( 0, 1, 0.2, 1 );
  24672. * path.lineTo( 1, 1 );
  24673. *
  24674. * const points = path.getPoints();
  24675. *
  24676. * const geometry = new THREE.BufferGeometry().setFromPoints( points );
  24677. * const material = new THREE.LineBasicMaterial( { color: 0xffffff } );
  24678. *
  24679. * const line = new THREE.Line( geometry, material );
  24680. * scene.add( line );
  24681. * ```
  24682. *
  24683. * @augments CurvePath
  24684. */
  24685. class Path extends CurvePath {
  24686. /**
  24687. * Constructs a new path.
  24688. *
  24689. * @param {Array<Vector2>} [points] - An array of 2D points defining the path.
  24690. */
  24691. constructor( points ) {
  24692. super();
  24693. this.type = 'Path';
  24694. /**
  24695. * The current offset of the path. Any new curve added will start here.
  24696. *
  24697. * @type {Vector2}
  24698. */
  24699. this.currentPoint = new Vector2();
  24700. if ( points ) {
  24701. this.setFromPoints( points );
  24702. }
  24703. }
  24704. /**
  24705. * Creates a path from the given list of points. The points are added
  24706. * to the path as instances of {@link LineCurve}.
  24707. *
  24708. * @param {Array<Vector2>} points - An array of 2D points.
  24709. * @return {Path} A reference to this path.
  24710. */
  24711. setFromPoints( points ) {
  24712. this.moveTo( points[ 0 ].x, points[ 0 ].y );
  24713. for ( let i = 1, l = points.length; i < l; i ++ ) {
  24714. this.lineTo( points[ i ].x, points[ i ].y );
  24715. }
  24716. return this;
  24717. }
  24718. /**
  24719. * Moves {@link Path#currentPoint} to the given point.
  24720. *
  24721. * @param {number} x - The x coordinate.
  24722. * @param {number} y - The y coordinate.
  24723. * @return {Path} A reference to this path.
  24724. */
  24725. moveTo( x, y ) {
  24726. this.currentPoint.set( x, y ); // TODO consider referencing vectors instead of copying?
  24727. return this;
  24728. }
  24729. /**
  24730. * Adds an instance of {@link LineCurve} to the path by connecting
  24731. * the current point with the given one.
  24732. *
  24733. * @param {number} x - The x coordinate of the end point.
  24734. * @param {number} y - The y coordinate of the end point.
  24735. * @return {Path} A reference to this path.
  24736. */
  24737. lineTo( x, y ) {
  24738. const curve = new LineCurve( this.currentPoint.clone(), new Vector2( x, y ) );
  24739. this.curves.push( curve );
  24740. this.currentPoint.set( x, y );
  24741. return this;
  24742. }
  24743. /**
  24744. * Adds an instance of {@link QuadraticBezierCurve} to the path by connecting
  24745. * the current point with the given one.
  24746. *
  24747. * @param {number} aCPx - The x coordinate of the control point.
  24748. * @param {number} aCPy - The y coordinate of the control point.
  24749. * @param {number} aX - The x coordinate of the end point.
  24750. * @param {number} aY - The y coordinate of the end point.
  24751. * @return {Path} A reference to this path.
  24752. */
  24753. quadraticCurveTo( aCPx, aCPy, aX, aY ) {
  24754. const curve = new QuadraticBezierCurve(
  24755. this.currentPoint.clone(),
  24756. new Vector2( aCPx, aCPy ),
  24757. new Vector2( aX, aY )
  24758. );
  24759. this.curves.push( curve );
  24760. this.currentPoint.set( aX, aY );
  24761. return this;
  24762. }
  24763. /**
  24764. * Adds an instance of {@link CubicBezierCurve} to the path by connecting
  24765. * the current point with the given one.
  24766. *
  24767. * @param {number} aCP1x - The x coordinate of the first control point.
  24768. * @param {number} aCP1y - The y coordinate of the first control point.
  24769. * @param {number} aCP2x - The x coordinate of the second control point.
  24770. * @param {number} aCP2y - The y coordinate of the second control point.
  24771. * @param {number} aX - The x coordinate of the end point.
  24772. * @param {number} aY - The y coordinate of the end point.
  24773. * @return {Path} A reference to this path.
  24774. */
  24775. bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) {
  24776. const curve = new CubicBezierCurve(
  24777. this.currentPoint.clone(),
  24778. new Vector2( aCP1x, aCP1y ),
  24779. new Vector2( aCP2x, aCP2y ),
  24780. new Vector2( aX, aY )
  24781. );
  24782. this.curves.push( curve );
  24783. this.currentPoint.set( aX, aY );
  24784. return this;
  24785. }
  24786. /**
  24787. * Adds an instance of {@link SplineCurve} to the path by connecting
  24788. * the current point with the given list of points.
  24789. *
  24790. * @param {Array<Vector2>} pts - An array of points in 2D space.
  24791. * @return {Path} A reference to this path.
  24792. */
  24793. splineThru( pts ) {
  24794. const npts = [ this.currentPoint.clone() ].concat( pts );
  24795. const curve = new SplineCurve( npts );
  24796. this.curves.push( curve );
  24797. this.currentPoint.copy( pts[ pts.length - 1 ] );
  24798. return this;
  24799. }
  24800. /**
  24801. * Adds an arc as an instance of {@link EllipseCurve} to the path, positioned relative
  24802. * to the current point.
  24803. *
  24804. * @param {number} aX - The x coordinate of the center of the arc offsetted from the previous curve.
  24805. * @param {number} aY - The y coordinate of the center of the arc offsetted from the previous curve.
  24806. * @param {number} aRadius - The radius of the arc.
  24807. * @param {number} aStartAngle - The start angle in radians.
  24808. * @param {number} aEndAngle - The end angle in radians.
  24809. * @param {boolean} [aClockwise=false] - Whether to sweep the arc clockwise or not.
  24810. * @return {Path} A reference to this path.
  24811. */
  24812. arc( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  24813. const x0 = this.currentPoint.x;
  24814. const y0 = this.currentPoint.y;
  24815. this.absarc( aX + x0, aY + y0, aRadius,
  24816. aStartAngle, aEndAngle, aClockwise );
  24817. return this;
  24818. }
  24819. /**
  24820. * Adds an absolutely positioned arc as an instance of {@link EllipseCurve} to the path.
  24821. *
  24822. * @param {number} aX - The x coordinate of the center of the arc.
  24823. * @param {number} aY - The y coordinate of the center of the arc.
  24824. * @param {number} aRadius - The radius of the arc.
  24825. * @param {number} aStartAngle - The start angle in radians.
  24826. * @param {number} aEndAngle - The end angle in radians.
  24827. * @param {boolean} [aClockwise=false] - Whether to sweep the arc clockwise or not.
  24828. * @return {Path} A reference to this path.
  24829. */
  24830. absarc( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  24831. this.absellipse( aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  24832. return this;
  24833. }
  24834. /**
  24835. * Adds an ellipse as an instance of {@link EllipseCurve} to the path, positioned relative
  24836. * to the current point
  24837. *
  24838. * @param {number} aX - The x coordinate of the center of the ellipse offsetted from the previous curve.
  24839. * @param {number} aY - The y coordinate of the center of the ellipse offsetted from the previous curve.
  24840. * @param {number} xRadius - The radius of the ellipse in the x axis.
  24841. * @param {number} yRadius - The radius of the ellipse in the y axis.
  24842. * @param {number} aStartAngle - The start angle in radians.
  24843. * @param {number} aEndAngle - The end angle in radians.
  24844. * @param {boolean} [aClockwise=false] - Whether to sweep the ellipse clockwise or not.
  24845. * @param {number} [aRotation=0] - The rotation angle of the ellipse in radians, counterclockwise from the positive X axis.
  24846. * @return {Path} A reference to this path.
  24847. */
  24848. ellipse( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  24849. const x0 = this.currentPoint.x;
  24850. const y0 = this.currentPoint.y;
  24851. this.absellipse( aX + x0, aY + y0, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation );
  24852. return this;
  24853. }
  24854. /**
  24855. * Adds an absolutely positioned ellipse as an instance of {@link EllipseCurve} to the path.
  24856. *
  24857. * @param {number} aX - The x coordinate of the absolute center of the ellipse.
  24858. * @param {number} aY - The y coordinate of the absolute center of the ellipse.
  24859. * @param {number} xRadius - The radius of the ellipse in the x axis.
  24860. * @param {number} yRadius - The radius of the ellipse in the y axis.
  24861. * @param {number} aStartAngle - The start angle in radians.
  24862. * @param {number} aEndAngle - The end angle in radians.
  24863. * @param {boolean} [aClockwise=false] - Whether to sweep the ellipse clockwise or not.
  24864. * @param {number} [aRotation=0] - The rotation angle of the ellipse in radians, counterclockwise from the positive X axis.
  24865. * @return {Path} A reference to this path.
  24866. */
  24867. absellipse( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  24868. const curve = new EllipseCurve( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation );
  24869. if ( this.curves.length > 0 ) {
  24870. // if a previous curve is present, attempt to join
  24871. const firstPoint = curve.getPoint( 0 );
  24872. if ( ! firstPoint.equals( this.currentPoint ) ) {
  24873. this.lineTo( firstPoint.x, firstPoint.y );
  24874. }
  24875. }
  24876. this.curves.push( curve );
  24877. const lastPoint = curve.getPoint( 1 );
  24878. this.currentPoint.copy( lastPoint );
  24879. return this;
  24880. }
  24881. copy( source ) {
  24882. super.copy( source );
  24883. this.currentPoint.copy( source.currentPoint );
  24884. return this;
  24885. }
  24886. toJSON() {
  24887. const data = super.toJSON();
  24888. data.currentPoint = this.currentPoint.toArray();
  24889. return data;
  24890. }
  24891. fromJSON( json ) {
  24892. super.fromJSON( json );
  24893. this.currentPoint.fromArray( json.currentPoint );
  24894. return this;
  24895. }
  24896. }
  24897. /**
  24898. * Defines an arbitrary 2d shape plane using paths with optional holes. It
  24899. * can be used with {@link ExtrudeGeometry}, {@link ShapeGeometry}, to get
  24900. * points, or to get triangulated faces.
  24901. *
  24902. * ```js
  24903. * const heartShape = new THREE.Shape();
  24904. *
  24905. * heartShape.moveTo( 25, 25 );
  24906. * heartShape.bezierCurveTo( 25, 25, 20, 0, 0, 0 );
  24907. * heartShape.bezierCurveTo( - 30, 0, - 30, 35, - 30, 35 );
  24908. * heartShape.bezierCurveTo( - 30, 55, - 10, 77, 25, 95 );
  24909. * heartShape.bezierCurveTo( 60, 77, 80, 55, 80, 35 );
  24910. * heartShape.bezierCurveTo( 80, 35, 80, 0, 50, 0 );
  24911. * heartShape.bezierCurveTo( 35, 0, 25, 25, 25, 25 );
  24912. *
  24913. * const extrudeSettings = {
  24914. * depth: 8,
  24915. * bevelEnabled: true,
  24916. * bevelSegments: 2,
  24917. * steps: 2,
  24918. * bevelSize: 1,
  24919. * bevelThickness: 1
  24920. * };
  24921. *
  24922. * const geometry = new THREE.ExtrudeGeometry( heartShape, extrudeSettings );
  24923. * const mesh = new THREE.Mesh( geometry, new THREE.MeshBasicMaterial() );
  24924. * ```
  24925. *
  24926. * @augments Path
  24927. */
  24928. class Shape extends Path {
  24929. /**
  24930. * Constructs a new shape.
  24931. *
  24932. * @param {Array<Vector2>} [points] - An array of 2D points defining the shape.
  24933. */
  24934. constructor( points ) {
  24935. super( points );
  24936. /**
  24937. * The UUID of the shape.
  24938. *
  24939. * @type {string}
  24940. * @readonly
  24941. */
  24942. this.uuid = generateUUID();
  24943. this.type = 'Shape';
  24944. /**
  24945. * Defines the holes in the shape. Hole definitions must use the
  24946. * opposite winding order (CW/CCW) than the outer shape.
  24947. *
  24948. * @type {Array<Path>}
  24949. * @readonly
  24950. */
  24951. this.holes = [];
  24952. }
  24953. /**
  24954. * Returns an array representing each contour of the holes
  24955. * as a list of 2D points.
  24956. *
  24957. * @param {number} divisions - The fineness of the result.
  24958. * @return {Array<Array<Vector2>>} The holes as a series of 2D points.
  24959. */
  24960. getPointsHoles( divisions ) {
  24961. const holesPts = [];
  24962. for ( let i = 0, l = this.holes.length; i < l; i ++ ) {
  24963. holesPts[ i ] = this.holes[ i ].getPoints( divisions );
  24964. }
  24965. return holesPts;
  24966. }
  24967. // get points of shape and holes (keypoints based on segments parameter)
  24968. /**
  24969. * Returns an object that holds contour data for the shape and its holes as
  24970. * arrays of 2D points.
  24971. *
  24972. * @param {number} divisions - The fineness of the result.
  24973. * @return {{shape:Array<Vector2>,holes:Array<Array<Vector2>>}} An object with contour data.
  24974. */
  24975. extractPoints( divisions ) {
  24976. return {
  24977. shape: this.getPoints( divisions ),
  24978. holes: this.getPointsHoles( divisions )
  24979. };
  24980. }
  24981. copy( source ) {
  24982. super.copy( source );
  24983. this.holes = [];
  24984. for ( let i = 0, l = source.holes.length; i < l; i ++ ) {
  24985. const hole = source.holes[ i ];
  24986. this.holes.push( hole.clone() );
  24987. }
  24988. return this;
  24989. }
  24990. toJSON() {
  24991. const data = super.toJSON();
  24992. data.uuid = this.uuid;
  24993. data.holes = [];
  24994. for ( let i = 0, l = this.holes.length; i < l; i ++ ) {
  24995. const hole = this.holes[ i ];
  24996. data.holes.push( hole.toJSON() );
  24997. }
  24998. return data;
  24999. }
  25000. fromJSON( json ) {
  25001. super.fromJSON( json );
  25002. this.uuid = json.uuid;
  25003. this.holes = [];
  25004. for ( let i = 0, l = json.holes.length; i < l; i ++ ) {
  25005. const hole = json.holes[ i ];
  25006. this.holes.push( new Path().fromJSON( hole ) );
  25007. }
  25008. return this;
  25009. }
  25010. }
  25011. /* eslint-disable */
  25012. // copy of mapbox/earcut version 3.0.1
  25013. // https://github.com/mapbox/earcut/tree/v3.0.1
  25014. function earcut(data, holeIndices, dim = 2) {
  25015. const hasHoles = holeIndices && holeIndices.length;
  25016. const outerLen = hasHoles ? holeIndices[0] * dim : data.length;
  25017. let outerNode = linkedList(data, 0, outerLen, dim, true);
  25018. const triangles = [];
  25019. if (!outerNode || outerNode.next === outerNode.prev) return triangles;
  25020. let minX, minY, invSize;
  25021. if (hasHoles) outerNode = eliminateHoles(data, holeIndices, outerNode, dim);
  25022. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  25023. if (data.length > 80 * dim) {
  25024. minX = Infinity;
  25025. minY = Infinity;
  25026. let maxX = -Infinity;
  25027. let maxY = -Infinity;
  25028. for (let i = dim; i < outerLen; i += dim) {
  25029. const x = data[i];
  25030. const y = data[i + 1];
  25031. if (x < minX) minX = x;
  25032. if (y < minY) minY = y;
  25033. if (x > maxX) maxX = x;
  25034. if (y > maxY) maxY = y;
  25035. }
  25036. // minX, minY and invSize are later used to transform coords into integers for z-order calculation
  25037. invSize = Math.max(maxX - minX, maxY - minY);
  25038. invSize = invSize !== 0 ? 32767 / invSize : 0;
  25039. }
  25040. earcutLinked(outerNode, triangles, dim, minX, minY, invSize, 0);
  25041. return triangles;
  25042. }
  25043. // create a circular doubly linked list from polygon points in the specified winding order
  25044. function linkedList(data, start, end, dim, clockwise) {
  25045. let last;
  25046. if (clockwise === (signedArea(data, start, end, dim) > 0)) {
  25047. for (let i = start; i < end; i += dim) last = insertNode(i / dim | 0, data[i], data[i + 1], last);
  25048. } else {
  25049. for (let i = end - dim; i >= start; i -= dim) last = insertNode(i / dim | 0, data[i], data[i + 1], last);
  25050. }
  25051. if (last && equals(last, last.next)) {
  25052. removeNode(last);
  25053. last = last.next;
  25054. }
  25055. return last;
  25056. }
  25057. // eliminate colinear or duplicate points
  25058. function filterPoints(start, end) {
  25059. if (!start) return start;
  25060. if (!end) end = start;
  25061. let p = start,
  25062. again;
  25063. do {
  25064. again = false;
  25065. if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
  25066. removeNode(p);
  25067. p = end = p.prev;
  25068. if (p === p.next) break;
  25069. again = true;
  25070. } else {
  25071. p = p.next;
  25072. }
  25073. } while (again || p !== end);
  25074. return end;
  25075. }
  25076. // main ear slicing loop which triangulates a polygon (given as a linked list)
  25077. function earcutLinked(ear, triangles, dim, minX, minY, invSize, pass) {
  25078. if (!ear) return;
  25079. // interlink polygon nodes in z-order
  25080. if (!pass && invSize) indexCurve(ear, minX, minY, invSize);
  25081. let stop = ear;
  25082. // iterate through ears, slicing them one by one
  25083. while (ear.prev !== ear.next) {
  25084. const prev = ear.prev;
  25085. const next = ear.next;
  25086. if (invSize ? isEarHashed(ear, minX, minY, invSize) : isEar(ear)) {
  25087. triangles.push(prev.i, ear.i, next.i); // cut off the triangle
  25088. removeNode(ear);
  25089. // skipping the next vertex leads to less sliver triangles
  25090. ear = next.next;
  25091. stop = next.next;
  25092. continue;
  25093. }
  25094. ear = next;
  25095. // if we looped through the whole remaining polygon and can't find any more ears
  25096. if (ear === stop) {
  25097. // try filtering points and slicing again
  25098. if (!pass) {
  25099. earcutLinked(filterPoints(ear), triangles, dim, minX, minY, invSize, 1);
  25100. // if this didn't work, try curing all small self-intersections locally
  25101. } else if (pass === 1) {
  25102. ear = cureLocalIntersections(filterPoints(ear), triangles);
  25103. earcutLinked(ear, triangles, dim, minX, minY, invSize, 2);
  25104. // as a last resort, try splitting the remaining polygon into two
  25105. } else if (pass === 2) {
  25106. splitEarcut(ear, triangles, dim, minX, minY, invSize);
  25107. }
  25108. break;
  25109. }
  25110. }
  25111. }
  25112. // check whether a polygon node forms a valid ear with adjacent nodes
  25113. function isEar(ear) {
  25114. const a = ear.prev,
  25115. b = ear,
  25116. c = ear.next;
  25117. if (area(a, b, c) >= 0) return false; // reflex, can't be an ear
  25118. // now make sure we don't have other points inside the potential ear
  25119. const ax = a.x, bx = b.x, cx = c.x, ay = a.y, by = b.y, cy = c.y;
  25120. // triangle bbox
  25121. const x0 = Math.min(ax, bx, cx),
  25122. y0 = Math.min(ay, by, cy),
  25123. x1 = Math.max(ax, bx, cx),
  25124. y1 = Math.max(ay, by, cy);
  25125. let p = c.next;
  25126. while (p !== a) {
  25127. if (p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 &&
  25128. pointInTriangleExceptFirst(ax, ay, bx, by, cx, cy, p.x, p.y) &&
  25129. area(p.prev, p, p.next) >= 0) return false;
  25130. p = p.next;
  25131. }
  25132. return true;
  25133. }
  25134. function isEarHashed(ear, minX, minY, invSize) {
  25135. const a = ear.prev,
  25136. b = ear,
  25137. c = ear.next;
  25138. if (area(a, b, c) >= 0) return false; // reflex, can't be an ear
  25139. const ax = a.x, bx = b.x, cx = c.x, ay = a.y, by = b.y, cy = c.y;
  25140. // triangle bbox
  25141. const x0 = Math.min(ax, bx, cx),
  25142. y0 = Math.min(ay, by, cy),
  25143. x1 = Math.max(ax, bx, cx),
  25144. y1 = Math.max(ay, by, cy);
  25145. // z-order range for the current triangle bbox;
  25146. const minZ = zOrder(x0, y0, minX, minY, invSize),
  25147. maxZ = zOrder(x1, y1, minX, minY, invSize);
  25148. let p = ear.prevZ,
  25149. n = ear.nextZ;
  25150. // look for points inside the triangle in both directions
  25151. while (p && p.z >= minZ && n && n.z <= maxZ) {
  25152. if (p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 && p !== a && p !== c &&
  25153. pointInTriangleExceptFirst(ax, ay, bx, by, cx, cy, p.x, p.y) && area(p.prev, p, p.next) >= 0) return false;
  25154. p = p.prevZ;
  25155. if (n.x >= x0 && n.x <= x1 && n.y >= y0 && n.y <= y1 && n !== a && n !== c &&
  25156. pointInTriangleExceptFirst(ax, ay, bx, by, cx, cy, n.x, n.y) && area(n.prev, n, n.next) >= 0) return false;
  25157. n = n.nextZ;
  25158. }
  25159. // look for remaining points in decreasing z-order
  25160. while (p && p.z >= minZ) {
  25161. if (p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 && p !== a && p !== c &&
  25162. pointInTriangleExceptFirst(ax, ay, bx, by, cx, cy, p.x, p.y) && area(p.prev, p, p.next) >= 0) return false;
  25163. p = p.prevZ;
  25164. }
  25165. // look for remaining points in increasing z-order
  25166. while (n && n.z <= maxZ) {
  25167. if (n.x >= x0 && n.x <= x1 && n.y >= y0 && n.y <= y1 && n !== a && n !== c &&
  25168. pointInTriangleExceptFirst(ax, ay, bx, by, cx, cy, n.x, n.y) && area(n.prev, n, n.next) >= 0) return false;
  25169. n = n.nextZ;
  25170. }
  25171. return true;
  25172. }
  25173. // go through all polygon nodes and cure small local self-intersections
  25174. function cureLocalIntersections(start, triangles) {
  25175. let p = start;
  25176. do {
  25177. const a = p.prev,
  25178. b = p.next.next;
  25179. if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
  25180. triangles.push(a.i, p.i, b.i);
  25181. // remove two nodes involved
  25182. removeNode(p);
  25183. removeNode(p.next);
  25184. p = start = b;
  25185. }
  25186. p = p.next;
  25187. } while (p !== start);
  25188. return filterPoints(p);
  25189. }
  25190. // try splitting polygon into two and triangulate them independently
  25191. function splitEarcut(start, triangles, dim, minX, minY, invSize) {
  25192. // look for a valid diagonal that divides the polygon into two
  25193. let a = start;
  25194. do {
  25195. let b = a.next.next;
  25196. while (b !== a.prev) {
  25197. if (a.i !== b.i && isValidDiagonal(a, b)) {
  25198. // split the polygon in two by the diagonal
  25199. let c = splitPolygon(a, b);
  25200. // filter colinear points around the cuts
  25201. a = filterPoints(a, a.next);
  25202. c = filterPoints(c, c.next);
  25203. // run earcut on each half
  25204. earcutLinked(a, triangles, dim, minX, minY, invSize, 0);
  25205. earcutLinked(c, triangles, dim, minX, minY, invSize, 0);
  25206. return;
  25207. }
  25208. b = b.next;
  25209. }
  25210. a = a.next;
  25211. } while (a !== start);
  25212. }
  25213. // link every hole into the outer loop, producing a single-ring polygon without holes
  25214. function eliminateHoles(data, holeIndices, outerNode, dim) {
  25215. const queue = [];
  25216. for (let i = 0, len = holeIndices.length; i < len; i++) {
  25217. const start = holeIndices[i] * dim;
  25218. const end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  25219. const list = linkedList(data, start, end, dim, false);
  25220. if (list === list.next) list.steiner = true;
  25221. queue.push(getLeftmost(list));
  25222. }
  25223. queue.sort(compareXYSlope);
  25224. // process holes from left to right
  25225. for (let i = 0; i < queue.length; i++) {
  25226. outerNode = eliminateHole(queue[i], outerNode);
  25227. }
  25228. return outerNode;
  25229. }
  25230. function compareXYSlope(a, b) {
  25231. let result = a.x - b.x;
  25232. // when the left-most point of 2 holes meet at a vertex, sort the holes counterclockwise so that when we find
  25233. // the bridge to the outer shell is always the point that they meet at.
  25234. if (result === 0) {
  25235. result = a.y - b.y;
  25236. if (result === 0) {
  25237. const aSlope = (a.next.y - a.y) / (a.next.x - a.x);
  25238. const bSlope = (b.next.y - b.y) / (b.next.x - b.x);
  25239. result = aSlope - bSlope;
  25240. }
  25241. }
  25242. return result;
  25243. }
  25244. // find a bridge between vertices that connects hole with an outer ring and and link it
  25245. function eliminateHole(hole, outerNode) {
  25246. const bridge = findHoleBridge(hole, outerNode);
  25247. if (!bridge) {
  25248. return outerNode;
  25249. }
  25250. const bridgeReverse = splitPolygon(bridge, hole);
  25251. // filter collinear points around the cuts
  25252. filterPoints(bridgeReverse, bridgeReverse.next);
  25253. return filterPoints(bridge, bridge.next);
  25254. }
  25255. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  25256. function findHoleBridge(hole, outerNode) {
  25257. let p = outerNode;
  25258. const hx = hole.x;
  25259. const hy = hole.y;
  25260. let qx = -Infinity;
  25261. let m;
  25262. // find a segment intersected by a ray from the hole's leftmost point to the left;
  25263. // segment's endpoint with lesser x will be potential connection point
  25264. // unless they intersect at a vertex, then choose the vertex
  25265. if (equals(hole, p)) return p;
  25266. do {
  25267. if (equals(hole, p.next)) return p.next;
  25268. else if (hy <= p.y && hy >= p.next.y && p.next.y !== p.y) {
  25269. const x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
  25270. if (x <= hx && x > qx) {
  25271. qx = x;
  25272. m = p.x < p.next.x ? p : p.next;
  25273. if (x === hx) return m; // hole touches outer segment; pick leftmost endpoint
  25274. }
  25275. }
  25276. p = p.next;
  25277. } while (p !== outerNode);
  25278. if (!m) return null;
  25279. // look for points inside the triangle of hole point, segment intersection and endpoint;
  25280. // if there are no points found, we have a valid connection;
  25281. // otherwise choose the point of the minimum angle with the ray as connection point
  25282. const stop = m;
  25283. const mx = m.x;
  25284. const my = m.y;
  25285. let tanMin = Infinity;
  25286. p = m;
  25287. do {
  25288. if (hx >= p.x && p.x >= mx && hx !== p.x &&
  25289. pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {
  25290. const tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
  25291. if (locallyInside(p, hole) &&
  25292. (tan < tanMin || (tan === tanMin && (p.x > m.x || (p.x === m.x && sectorContainsSector(m, p)))))) {
  25293. m = p;
  25294. tanMin = tan;
  25295. }
  25296. }
  25297. p = p.next;
  25298. } while (p !== stop);
  25299. return m;
  25300. }
  25301. // whether sector in vertex m contains sector in vertex p in the same coordinates
  25302. function sectorContainsSector(m, p) {
  25303. return area(m.prev, m, p.prev) < 0 && area(p.next, m, m.next) < 0;
  25304. }
  25305. // interlink polygon nodes in z-order
  25306. function indexCurve(start, minX, minY, invSize) {
  25307. let p = start;
  25308. do {
  25309. if (p.z === 0) p.z = zOrder(p.x, p.y, minX, minY, invSize);
  25310. p.prevZ = p.prev;
  25311. p.nextZ = p.next;
  25312. p = p.next;
  25313. } while (p !== start);
  25314. p.prevZ.nextZ = null;
  25315. p.prevZ = null;
  25316. sortLinked(p);
  25317. }
  25318. // Simon Tatham's linked list merge sort algorithm
  25319. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  25320. function sortLinked(list) {
  25321. let numMerges;
  25322. let inSize = 1;
  25323. do {
  25324. let p = list;
  25325. let e;
  25326. list = null;
  25327. let tail = null;
  25328. numMerges = 0;
  25329. while (p) {
  25330. numMerges++;
  25331. let q = p;
  25332. let pSize = 0;
  25333. for (let i = 0; i < inSize; i++) {
  25334. pSize++;
  25335. q = q.nextZ;
  25336. if (!q) break;
  25337. }
  25338. let qSize = inSize;
  25339. while (pSize > 0 || (qSize > 0 && q)) {
  25340. if (pSize !== 0 && (qSize === 0 || !q || p.z <= q.z)) {
  25341. e = p;
  25342. p = p.nextZ;
  25343. pSize--;
  25344. } else {
  25345. e = q;
  25346. q = q.nextZ;
  25347. qSize--;
  25348. }
  25349. if (tail) tail.nextZ = e;
  25350. else list = e;
  25351. e.prevZ = tail;
  25352. tail = e;
  25353. }
  25354. p = q;
  25355. }
  25356. tail.nextZ = null;
  25357. inSize *= 2;
  25358. } while (numMerges > 1);
  25359. return list;
  25360. }
  25361. // z-order of a point given coords and inverse of the longer side of data bbox
  25362. function zOrder(x, y, minX, minY, invSize) {
  25363. // coords are transformed into non-negative 15-bit integer range
  25364. x = (x - minX) * invSize | 0;
  25365. y = (y - minY) * invSize | 0;
  25366. x = (x | (x << 8)) & 0x00FF00FF;
  25367. x = (x | (x << 4)) & 0x0F0F0F0F;
  25368. x = (x | (x << 2)) & 0x33333333;
  25369. x = (x | (x << 1)) & 0x55555555;
  25370. y = (y | (y << 8)) & 0x00FF00FF;
  25371. y = (y | (y << 4)) & 0x0F0F0F0F;
  25372. y = (y | (y << 2)) & 0x33333333;
  25373. y = (y | (y << 1)) & 0x55555555;
  25374. return x | (y << 1);
  25375. }
  25376. // find the leftmost node of a polygon ring
  25377. function getLeftmost(start) {
  25378. let p = start,
  25379. leftmost = start;
  25380. do {
  25381. if (p.x < leftmost.x || (p.x === leftmost.x && p.y < leftmost.y)) leftmost = p;
  25382. p = p.next;
  25383. } while (p !== start);
  25384. return leftmost;
  25385. }
  25386. // check if a point lies within a convex triangle
  25387. function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
  25388. return (cx - px) * (ay - py) >= (ax - px) * (cy - py) &&
  25389. (ax - px) * (by - py) >= (bx - px) * (ay - py) &&
  25390. (bx - px) * (cy - py) >= (cx - px) * (by - py);
  25391. }
  25392. // check if a point lies within a convex triangle but false if its equal to the first point of the triangle
  25393. function pointInTriangleExceptFirst(ax, ay, bx, by, cx, cy, px, py) {
  25394. return !(ax === px && ay === py) && pointInTriangle(ax, ay, bx, by, cx, cy, px, py);
  25395. }
  25396. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  25397. function isValidDiagonal(a, b) {
  25398. return a.next.i !== b.i && a.prev.i !== b.i && !intersectsPolygon(a, b) && // dones't intersect other edges
  25399. (locallyInside(a, b) && locallyInside(b, a) && middleInside(a, b) && // locally visible
  25400. (area(a.prev, a, b.prev) || area(a, b.prev, b)) || // does not create opposite-facing sectors
  25401. equals(a, b) && area(a.prev, a, a.next) > 0 && area(b.prev, b, b.next) > 0); // special zero-length case
  25402. }
  25403. // signed area of a triangle
  25404. function area(p, q, r) {
  25405. return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
  25406. }
  25407. // check if two points are equal
  25408. function equals(p1, p2) {
  25409. return p1.x === p2.x && p1.y === p2.y;
  25410. }
  25411. // check if two segments intersect
  25412. function intersects(p1, q1, p2, q2) {
  25413. const o1 = sign(area(p1, q1, p2));
  25414. const o2 = sign(area(p1, q1, q2));
  25415. const o3 = sign(area(p2, q2, p1));
  25416. const o4 = sign(area(p2, q2, q1));
  25417. if (o1 !== o2 && o3 !== o4) return true; // general case
  25418. if (o1 === 0 && onSegment(p1, p2, q1)) return true; // p1, q1 and p2 are collinear and p2 lies on p1q1
  25419. if (o2 === 0 && onSegment(p1, q2, q1)) return true; // p1, q1 and q2 are collinear and q2 lies on p1q1
  25420. if (o3 === 0 && onSegment(p2, p1, q2)) return true; // p2, q2 and p1 are collinear and p1 lies on p2q2
  25421. if (o4 === 0 && onSegment(p2, q1, q2)) return true; // p2, q2 and q1 are collinear and q1 lies on p2q2
  25422. return false;
  25423. }
  25424. // for collinear points p, q, r, check if point q lies on segment pr
  25425. function onSegment(p, q, r) {
  25426. 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);
  25427. }
  25428. function sign(num) {
  25429. return num > 0 ? 1 : num < 0 ? -1 : 0;
  25430. }
  25431. // check if a polygon diagonal intersects any polygon segments
  25432. function intersectsPolygon(a, b) {
  25433. let p = a;
  25434. do {
  25435. if (p.i !== a.i && p.next.i !== a.i && p.i !== b.i && p.next.i !== b.i &&
  25436. intersects(p, p.next, a, b)) return true;
  25437. p = p.next;
  25438. } while (p !== a);
  25439. return false;
  25440. }
  25441. // check if a polygon diagonal is locally inside the polygon
  25442. function locallyInside(a, b) {
  25443. return area(a.prev, a, a.next) < 0 ?
  25444. area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0 :
  25445. area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;
  25446. }
  25447. // check if the middle point of a polygon diagonal is inside the polygon
  25448. function middleInside(a, b) {
  25449. let p = a;
  25450. let inside = false;
  25451. const px = (a.x + b.x) / 2;
  25452. const py = (a.y + b.y) / 2;
  25453. do {
  25454. if (((p.y > py) !== (p.next.y > py)) && p.next.y !== p.y &&
  25455. (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x))
  25456. inside = !inside;
  25457. p = p.next;
  25458. } while (p !== a);
  25459. return inside;
  25460. }
  25461. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  25462. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  25463. function splitPolygon(a, b) {
  25464. const a2 = createNode(a.i, a.x, a.y),
  25465. b2 = createNode(b.i, b.x, b.y),
  25466. an = a.next,
  25467. bp = b.prev;
  25468. a.next = b;
  25469. b.prev = a;
  25470. a2.next = an;
  25471. an.prev = a2;
  25472. b2.next = a2;
  25473. a2.prev = b2;
  25474. bp.next = b2;
  25475. b2.prev = bp;
  25476. return b2;
  25477. }
  25478. // create a node and optionally link it with previous one (in a circular doubly linked list)
  25479. function insertNode(i, x, y, last) {
  25480. const p = createNode(i, x, y);
  25481. if (!last) {
  25482. p.prev = p;
  25483. p.next = p;
  25484. } else {
  25485. p.next = last.next;
  25486. p.prev = last;
  25487. last.next.prev = p;
  25488. last.next = p;
  25489. }
  25490. return p;
  25491. }
  25492. function removeNode(p) {
  25493. p.next.prev = p.prev;
  25494. p.prev.next = p.next;
  25495. if (p.prevZ) p.prevZ.nextZ = p.nextZ;
  25496. if (p.nextZ) p.nextZ.prevZ = p.prevZ;
  25497. }
  25498. function createNode(i, x, y) {
  25499. return {
  25500. i, // vertex index in coordinates array
  25501. x, y, // vertex coordinates
  25502. prev: null, // previous and next vertex nodes in a polygon ring
  25503. next: null,
  25504. z: 0, // z-order curve value
  25505. prevZ: null, // previous and next nodes in z-order
  25506. nextZ: null,
  25507. steiner: false // indicates whether this is a steiner point
  25508. };
  25509. }
  25510. function signedArea(data, start, end, dim) {
  25511. let sum = 0;
  25512. for (let i = start, j = end - dim; i < end; i += dim) {
  25513. sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
  25514. j = i;
  25515. }
  25516. return sum;
  25517. }
  25518. class Earcut {
  25519. /**
  25520. * Triangulates the given shape definition by returning an array of triangles.
  25521. *
  25522. * @param {Array<number>} data - An array with 2D points.
  25523. * @param {Array<number>} holeIndices - An array with indices defining holes.
  25524. * @param {number} [dim=2] - The number of coordinates per vertex in the input array.
  25525. * @return {Array<number>} An array representing the triangulated faces. Each face is defined by three consecutive numbers
  25526. * representing vertex indices.
  25527. */
  25528. static triangulate( data, holeIndices, dim = 2 ) {
  25529. return earcut( data, holeIndices, dim );
  25530. }
  25531. }
  25532. /**
  25533. * A class containing utility functions for shapes.
  25534. *
  25535. * @hideconstructor
  25536. */
  25537. class ShapeUtils {
  25538. /**
  25539. * Calculate area of a ( 2D ) contour polygon.
  25540. *
  25541. * @param {Array<Vector2>} contour - An array of 2D points.
  25542. * @return {number} The area.
  25543. */
  25544. static area( contour ) {
  25545. const n = contour.length;
  25546. let a = 0.0;
  25547. for ( let p = n - 1, q = 0; q < n; p = q ++ ) {
  25548. a += contour[ p ].x * contour[ q ].y - contour[ q ].x * contour[ p ].y;
  25549. }
  25550. return a * 0.5;
  25551. }
  25552. /**
  25553. * Returns `true` if the given contour uses a clockwise winding order.
  25554. *
  25555. * @param {Array<Vector2>} pts - An array of 2D points defining a polygon.
  25556. * @return {boolean} Whether the given contour uses a clockwise winding order or not.
  25557. */
  25558. static isClockWise( pts ) {
  25559. return ShapeUtils.area( pts ) < 0;
  25560. }
  25561. /**
  25562. * Triangulates the given shape definition.
  25563. *
  25564. * @param {Array<Vector2>} contour - An array of 2D points defining the contour.
  25565. * @param {Array<Array<Vector2>>} holes - An array that holds arrays of 2D points defining the holes.
  25566. * @return {Array<Array<number>>} An array that holds for each face definition an array with three indices.
  25567. */
  25568. static triangulateShape( contour, holes ) {
  25569. const vertices = []; // flat array of vertices like [ x0,y0, x1,y1, x2,y2, ... ]
  25570. const holeIndices = []; // array of hole indices
  25571. const faces = []; // final array of vertex indices like [ [ a,b,d ], [ b,c,d ] ]
  25572. removeDupEndPts( contour );
  25573. addContour( vertices, contour );
  25574. //
  25575. let holeIndex = contour.length;
  25576. holes.forEach( removeDupEndPts );
  25577. for ( let i = 0; i < holes.length; i ++ ) {
  25578. holeIndices.push( holeIndex );
  25579. holeIndex += holes[ i ].length;
  25580. addContour( vertices, holes[ i ] );
  25581. }
  25582. //
  25583. const triangles = Earcut.triangulate( vertices, holeIndices );
  25584. //
  25585. for ( let i = 0; i < triangles.length; i += 3 ) {
  25586. faces.push( triangles.slice( i, i + 3 ) );
  25587. }
  25588. return faces;
  25589. }
  25590. }
  25591. function removeDupEndPts( points ) {
  25592. const l = points.length;
  25593. if ( l > 2 && points[ l - 1 ].equals( points[ 0 ] ) ) {
  25594. points.pop();
  25595. }
  25596. }
  25597. function addContour( vertices, contour ) {
  25598. for ( let i = 0; i < contour.length; i ++ ) {
  25599. vertices.push( contour[ i ].x );
  25600. vertices.push( contour[ i ].y );
  25601. }
  25602. }
  25603. /**
  25604. * Creates extruded geometry from a path shape.
  25605. *
  25606. * ```js
  25607. * const length = 12, width = 8;
  25608. *
  25609. * const shape = new THREE.Shape();
  25610. * shape.moveTo( 0,0 );
  25611. * shape.lineTo( 0, width );
  25612. * shape.lineTo( length, width );
  25613. * shape.lineTo( length, 0 );
  25614. * shape.lineTo( 0, 0 );
  25615. *
  25616. * const geometry = new THREE.ExtrudeGeometry( shape );
  25617. * const material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } );
  25618. * const mesh = new THREE.Mesh( geometry, material ) ;
  25619. * scene.add( mesh );
  25620. * ```
  25621. *
  25622. * @augments BufferGeometry
  25623. */
  25624. class ExtrudeGeometry extends BufferGeometry {
  25625. /**
  25626. * Constructs a new extrude geometry.
  25627. *
  25628. * @param {Shape|Array<Shape>} [shapes] - A shape or an array of shapes.
  25629. * @param {ExtrudeGeometry~Options} [options] - The extrude settings.
  25630. */
  25631. 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 = {} ) {
  25632. super();
  25633. this.type = 'ExtrudeGeometry';
  25634. /**
  25635. * Holds the constructor parameters that have been
  25636. * used to generate the geometry. Any modification
  25637. * after instantiation does not change the geometry.
  25638. *
  25639. * @type {Object}
  25640. */
  25641. this.parameters = {
  25642. shapes: shapes,
  25643. options: options
  25644. };
  25645. shapes = Array.isArray( shapes ) ? shapes : [ shapes ];
  25646. const scope = this;
  25647. const verticesArray = [];
  25648. const uvArray = [];
  25649. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  25650. const shape = shapes[ i ];
  25651. addShape( shape );
  25652. }
  25653. // build geometry
  25654. this.setAttribute( 'position', new Float32BufferAttribute( verticesArray, 3 ) );
  25655. this.setAttribute( 'uv', new Float32BufferAttribute( uvArray, 2 ) );
  25656. this.computeVertexNormals();
  25657. // functions
  25658. function addShape( shape ) {
  25659. const placeholder = [];
  25660. // options
  25661. const curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  25662. const steps = options.steps !== undefined ? options.steps : 1;
  25663. const depth = options.depth !== undefined ? options.depth : 1;
  25664. let bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true;
  25665. let bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 0.2;
  25666. let bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 0.1;
  25667. let bevelOffset = options.bevelOffset !== undefined ? options.bevelOffset : 0;
  25668. let bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3;
  25669. const extrudePath = options.extrudePath;
  25670. const uvgen = options.UVGenerator !== undefined ? options.UVGenerator : WorldUVGenerator;
  25671. //
  25672. let extrudePts, extrudeByPath = false;
  25673. let splineTube, binormal, normal, position2;
  25674. if ( extrudePath ) {
  25675. extrudePts = extrudePath.getSpacedPoints( steps );
  25676. extrudeByPath = true;
  25677. bevelEnabled = false; // bevels not supported for path extrusion
  25678. // SETUP TNB variables
  25679. // TODO1 - have a .isClosed in spline?
  25680. splineTube = extrudePath.computeFrenetFrames( steps, false );
  25681. // console.log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length);
  25682. binormal = new Vector3();
  25683. normal = new Vector3();
  25684. position2 = new Vector3();
  25685. }
  25686. // Safeguards if bevels are not enabled
  25687. if ( ! bevelEnabled ) {
  25688. bevelSegments = 0;
  25689. bevelThickness = 0;
  25690. bevelSize = 0;
  25691. bevelOffset = 0;
  25692. }
  25693. // Variables initialization
  25694. const shapePoints = shape.extractPoints( curveSegments );
  25695. let vertices = shapePoints.shape;
  25696. const holes = shapePoints.holes;
  25697. const reverse = ! ShapeUtils.isClockWise( vertices );
  25698. if ( reverse ) {
  25699. vertices = vertices.reverse();
  25700. // Maybe we should also check if holes are in the opposite direction, just to be safe ...
  25701. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  25702. const ahole = holes[ h ];
  25703. if ( ShapeUtils.isClockWise( ahole ) ) {
  25704. holes[ h ] = ahole.reverse();
  25705. }
  25706. }
  25707. }
  25708. /**Merges index-adjacent points that are within a threshold distance of each other. Array is modified in-place. Threshold distance is empirical, and scaled based on the magnitude of point coordinates.
  25709. * @param {Array<Vector2>} points
  25710. */
  25711. function mergeOverlappingPoints( points ) {
  25712. const THRESHOLD = 1e-10;
  25713. const THRESHOLD_SQ = THRESHOLD * THRESHOLD;
  25714. let prevPos = points[ 0 ];
  25715. for ( let i = 1; i <= points.length; i ++ ) {
  25716. const currentIndex = i % points.length;
  25717. const currentPos = points[ currentIndex ];
  25718. const dx = currentPos.x - prevPos.x;
  25719. const dy = currentPos.y - prevPos.y;
  25720. const distSq = dx * dx + dy * dy;
  25721. const scalingFactorSqrt = Math.max(
  25722. Math.abs( currentPos.x ),
  25723. Math.abs( currentPos.y ),
  25724. Math.abs( prevPos.x ),
  25725. Math.abs( prevPos.y )
  25726. );
  25727. const thresholdSqScaled = THRESHOLD_SQ * scalingFactorSqrt * scalingFactorSqrt;
  25728. if ( distSq <= thresholdSqScaled ) {
  25729. points.splice( currentIndex, 1 );
  25730. i --;
  25731. continue;
  25732. }
  25733. prevPos = currentPos;
  25734. }
  25735. }
  25736. mergeOverlappingPoints( vertices );
  25737. holes.forEach( mergeOverlappingPoints );
  25738. const numHoles = holes.length;
  25739. /* Vertices */
  25740. const contour = vertices; // vertices has all points but contour has only points of circumference
  25741. for ( let h = 0; h < numHoles; h ++ ) {
  25742. const ahole = holes[ h ];
  25743. vertices = vertices.concat( ahole );
  25744. }
  25745. function scalePt2( pt, vec, size ) {
  25746. if ( ! vec ) console.error( 'THREE.ExtrudeGeometry: vec does not exist' );
  25747. return pt.clone().addScaledVector( vec, size );
  25748. }
  25749. const vlen = vertices.length;
  25750. // Find directions for point movement
  25751. function getBevelVec( inPt, inPrev, inNext ) {
  25752. // computes for inPt the corresponding point inPt' on a new contour
  25753. // shifted by 1 unit (length of normalized vector) to the left
  25754. // if we walk along contour clockwise, this new contour is outside the old one
  25755. //
  25756. // inPt' is the intersection of the two lines parallel to the two
  25757. // adjacent edges of inPt at a distance of 1 unit on the left side.
  25758. let v_trans_x, v_trans_y, shrink_by; // resulting translation vector for inPt
  25759. // good reading for geometry algorithms (here: line-line intersection)
  25760. // http://geomalgorithms.com/a05-_intersect-1.html
  25761. const v_prev_x = inPt.x - inPrev.x,
  25762. v_prev_y = inPt.y - inPrev.y;
  25763. const v_next_x = inNext.x - inPt.x,
  25764. v_next_y = inNext.y - inPt.y;
  25765. const v_prev_lensq = ( v_prev_x * v_prev_x + v_prev_y * v_prev_y );
  25766. // check for collinear edges
  25767. const collinear0 = ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  25768. if ( Math.abs( collinear0 ) > Number.EPSILON ) {
  25769. // not collinear
  25770. // length of vectors for normalizing
  25771. const v_prev_len = Math.sqrt( v_prev_lensq );
  25772. const v_next_len = Math.sqrt( v_next_x * v_next_x + v_next_y * v_next_y );
  25773. // shift adjacent points by unit vectors to the left
  25774. const ptPrevShift_x = ( inPrev.x - v_prev_y / v_prev_len );
  25775. const ptPrevShift_y = ( inPrev.y + v_prev_x / v_prev_len );
  25776. const ptNextShift_x = ( inNext.x - v_next_y / v_next_len );
  25777. const ptNextShift_y = ( inNext.y + v_next_x / v_next_len );
  25778. // scaling factor for v_prev to intersection point
  25779. const sf = ( ( ptNextShift_x - ptPrevShift_x ) * v_next_y -
  25780. ( ptNextShift_y - ptPrevShift_y ) * v_next_x ) /
  25781. ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  25782. // vector from inPt to intersection point
  25783. v_trans_x = ( ptPrevShift_x + v_prev_x * sf - inPt.x );
  25784. v_trans_y = ( ptPrevShift_y + v_prev_y * sf - inPt.y );
  25785. // Don't normalize!, otherwise sharp corners become ugly
  25786. // but prevent crazy spikes
  25787. const v_trans_lensq = ( v_trans_x * v_trans_x + v_trans_y * v_trans_y );
  25788. if ( v_trans_lensq <= 2 ) {
  25789. return new Vector2( v_trans_x, v_trans_y );
  25790. } else {
  25791. shrink_by = Math.sqrt( v_trans_lensq / 2 );
  25792. }
  25793. } else {
  25794. // handle special case of collinear edges
  25795. let direction_eq = false; // assumes: opposite
  25796. if ( v_prev_x > Number.EPSILON ) {
  25797. if ( v_next_x > Number.EPSILON ) {
  25798. direction_eq = true;
  25799. }
  25800. } else {
  25801. if ( v_prev_x < - Number.EPSILON ) {
  25802. if ( v_next_x < - Number.EPSILON ) {
  25803. direction_eq = true;
  25804. }
  25805. } else {
  25806. if ( Math.sign( v_prev_y ) === Math.sign( v_next_y ) ) {
  25807. direction_eq = true;
  25808. }
  25809. }
  25810. }
  25811. if ( direction_eq ) {
  25812. // console.log("Warning: lines are a straight sequence");
  25813. v_trans_x = - v_prev_y;
  25814. v_trans_y = v_prev_x;
  25815. shrink_by = Math.sqrt( v_prev_lensq );
  25816. } else {
  25817. // console.log("Warning: lines are a straight spike");
  25818. v_trans_x = v_prev_x;
  25819. v_trans_y = v_prev_y;
  25820. shrink_by = Math.sqrt( v_prev_lensq / 2 );
  25821. }
  25822. }
  25823. return new Vector2( v_trans_x / shrink_by, v_trans_y / shrink_by );
  25824. }
  25825. const contourMovements = [];
  25826. for ( let i = 0, il = contour.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  25827. if ( j === il ) j = 0;
  25828. if ( k === il ) k = 0;
  25829. // (j)---(i)---(k)
  25830. // console.log('i,j,k', i, j , k)
  25831. contourMovements[ i ] = getBevelVec( contour[ i ], contour[ j ], contour[ k ] );
  25832. }
  25833. const holesMovements = [];
  25834. let oneHoleMovements, verticesMovements = contourMovements.concat();
  25835. for ( let h = 0, hl = numHoles; h < hl; h ++ ) {
  25836. const ahole = holes[ h ];
  25837. oneHoleMovements = [];
  25838. for ( let i = 0, il = ahole.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  25839. if ( j === il ) j = 0;
  25840. if ( k === il ) k = 0;
  25841. // (j)---(i)---(k)
  25842. oneHoleMovements[ i ] = getBevelVec( ahole[ i ], ahole[ j ], ahole[ k ] );
  25843. }
  25844. holesMovements.push( oneHoleMovements );
  25845. verticesMovements = verticesMovements.concat( oneHoleMovements );
  25846. }
  25847. let faces;
  25848. if ( bevelSegments === 0 ) {
  25849. faces = ShapeUtils.triangulateShape( contour, holes );
  25850. } else {
  25851. const contractedContourVertices = [];
  25852. const expandedHoleVertices = [];
  25853. // Loop bevelSegments, 1 for the front, 1 for the back
  25854. for ( let b = 0; b < bevelSegments; b ++ ) {
  25855. //for ( b = bevelSegments; b > 0; b -- ) {
  25856. const t = b / bevelSegments;
  25857. const z = bevelThickness * Math.cos( t * Math.PI / 2 );
  25858. const bs = bevelSize * Math.sin( t * Math.PI / 2 ) + bevelOffset;
  25859. // contract shape
  25860. for ( let i = 0, il = contour.length; i < il; i ++ ) {
  25861. const vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  25862. v( vert.x, vert.y, - z );
  25863. if ( t === 0 ) contractedContourVertices.push( vert );
  25864. }
  25865. // expand holes
  25866. for ( let h = 0, hl = numHoles; h < hl; h ++ ) {
  25867. const ahole = holes[ h ];
  25868. oneHoleMovements = holesMovements[ h ];
  25869. const oneHoleVertices = [];
  25870. for ( let i = 0, il = ahole.length; i < il; i ++ ) {
  25871. const vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  25872. v( vert.x, vert.y, - z );
  25873. if ( t === 0 ) oneHoleVertices.push( vert );
  25874. }
  25875. if ( t === 0 ) expandedHoleVertices.push( oneHoleVertices );
  25876. }
  25877. }
  25878. faces = ShapeUtils.triangulateShape( contractedContourVertices, expandedHoleVertices );
  25879. }
  25880. const flen = faces.length;
  25881. const bs = bevelSize + bevelOffset;
  25882. // Back facing vertices
  25883. for ( let i = 0; i < vlen; i ++ ) {
  25884. const vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  25885. if ( ! extrudeByPath ) {
  25886. v( vert.x, vert.y, 0 );
  25887. } else {
  25888. // v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x );
  25889. normal.copy( splineTube.normals[ 0 ] ).multiplyScalar( vert.x );
  25890. binormal.copy( splineTube.binormals[ 0 ] ).multiplyScalar( vert.y );
  25891. position2.copy( extrudePts[ 0 ] ).add( normal ).add( binormal );
  25892. v( position2.x, position2.y, position2.z );
  25893. }
  25894. }
  25895. // Add stepped vertices...
  25896. // Including front facing vertices
  25897. for ( let s = 1; s <= steps; s ++ ) {
  25898. for ( let i = 0; i < vlen; i ++ ) {
  25899. const vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  25900. if ( ! extrudeByPath ) {
  25901. v( vert.x, vert.y, depth / steps * s );
  25902. } else {
  25903. // v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x );
  25904. normal.copy( splineTube.normals[ s ] ).multiplyScalar( vert.x );
  25905. binormal.copy( splineTube.binormals[ s ] ).multiplyScalar( vert.y );
  25906. position2.copy( extrudePts[ s ] ).add( normal ).add( binormal );
  25907. v( position2.x, position2.y, position2.z );
  25908. }
  25909. }
  25910. }
  25911. // Add bevel segments planes
  25912. //for ( b = 1; b <= bevelSegments; b ++ ) {
  25913. for ( let b = bevelSegments - 1; b >= 0; b -- ) {
  25914. const t = b / bevelSegments;
  25915. const z = bevelThickness * Math.cos( t * Math.PI / 2 );
  25916. const bs = bevelSize * Math.sin( t * Math.PI / 2 ) + bevelOffset;
  25917. // contract shape
  25918. for ( let i = 0, il = contour.length; i < il; i ++ ) {
  25919. const vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  25920. v( vert.x, vert.y, depth + z );
  25921. }
  25922. // expand holes
  25923. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  25924. const ahole = holes[ h ];
  25925. oneHoleMovements = holesMovements[ h ];
  25926. for ( let i = 0, il = ahole.length; i < il; i ++ ) {
  25927. const vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  25928. if ( ! extrudeByPath ) {
  25929. v( vert.x, vert.y, depth + z );
  25930. } else {
  25931. v( vert.x, vert.y + extrudePts[ steps - 1 ].y, extrudePts[ steps - 1 ].x + z );
  25932. }
  25933. }
  25934. }
  25935. }
  25936. /* Faces */
  25937. // Top and bottom faces
  25938. buildLidFaces();
  25939. // Sides faces
  25940. buildSideFaces();
  25941. ///// Internal functions
  25942. function buildLidFaces() {
  25943. const start = verticesArray.length / 3;
  25944. if ( bevelEnabled ) {
  25945. let layer = 0; // steps + 1
  25946. let offset = vlen * layer;
  25947. // Bottom faces
  25948. for ( let i = 0; i < flen; i ++ ) {
  25949. const face = faces[ i ];
  25950. f3( face[ 2 ] + offset, face[ 1 ] + offset, face[ 0 ] + offset );
  25951. }
  25952. layer = steps + bevelSegments * 2;
  25953. offset = vlen * layer;
  25954. // Top faces
  25955. for ( let i = 0; i < flen; i ++ ) {
  25956. const face = faces[ i ];
  25957. f3( face[ 0 ] + offset, face[ 1 ] + offset, face[ 2 ] + offset );
  25958. }
  25959. } else {
  25960. // Bottom faces
  25961. for ( let i = 0; i < flen; i ++ ) {
  25962. const face = faces[ i ];
  25963. f3( face[ 2 ], face[ 1 ], face[ 0 ] );
  25964. }
  25965. // Top faces
  25966. for ( let i = 0; i < flen; i ++ ) {
  25967. const face = faces[ i ];
  25968. f3( face[ 0 ] + vlen * steps, face[ 1 ] + vlen * steps, face[ 2 ] + vlen * steps );
  25969. }
  25970. }
  25971. scope.addGroup( start, verticesArray.length / 3 - start, 0 );
  25972. }
  25973. // Create faces for the z-sides of the shape
  25974. function buildSideFaces() {
  25975. const start = verticesArray.length / 3;
  25976. let layeroffset = 0;
  25977. sidewalls( contour, layeroffset );
  25978. layeroffset += contour.length;
  25979. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  25980. const ahole = holes[ h ];
  25981. sidewalls( ahole, layeroffset );
  25982. //, true
  25983. layeroffset += ahole.length;
  25984. }
  25985. scope.addGroup( start, verticesArray.length / 3 - start, 1 );
  25986. }
  25987. function sidewalls( contour, layeroffset ) {
  25988. let i = contour.length;
  25989. while ( -- i >= 0 ) {
  25990. const j = i;
  25991. let k = i - 1;
  25992. if ( k < 0 ) k = contour.length - 1;
  25993. //console.log('b', i,j, i-1, k,vertices.length);
  25994. for ( let s = 0, sl = ( steps + bevelSegments * 2 ); s < sl; s ++ ) {
  25995. const slen1 = vlen * s;
  25996. const slen2 = vlen * ( s + 1 );
  25997. const a = layeroffset + j + slen1,
  25998. b = layeroffset + k + slen1,
  25999. c = layeroffset + k + slen2,
  26000. d = layeroffset + j + slen2;
  26001. f4( a, b, c, d );
  26002. }
  26003. }
  26004. }
  26005. function v( x, y, z ) {
  26006. placeholder.push( x );
  26007. placeholder.push( y );
  26008. placeholder.push( z );
  26009. }
  26010. function f3( a, b, c ) {
  26011. addVertex( a );
  26012. addVertex( b );
  26013. addVertex( c );
  26014. const nextIndex = verticesArray.length / 3;
  26015. const uvs = uvgen.generateTopUV( scope, verticesArray, nextIndex - 3, nextIndex - 2, nextIndex - 1 );
  26016. addUV( uvs[ 0 ] );
  26017. addUV( uvs[ 1 ] );
  26018. addUV( uvs[ 2 ] );
  26019. }
  26020. function f4( a, b, c, d ) {
  26021. addVertex( a );
  26022. addVertex( b );
  26023. addVertex( d );
  26024. addVertex( b );
  26025. addVertex( c );
  26026. addVertex( d );
  26027. const nextIndex = verticesArray.length / 3;
  26028. const uvs = uvgen.generateSideWallUV( scope, verticesArray, nextIndex - 6, nextIndex - 3, nextIndex - 2, nextIndex - 1 );
  26029. addUV( uvs[ 0 ] );
  26030. addUV( uvs[ 1 ] );
  26031. addUV( uvs[ 3 ] );
  26032. addUV( uvs[ 1 ] );
  26033. addUV( uvs[ 2 ] );
  26034. addUV( uvs[ 3 ] );
  26035. }
  26036. function addVertex( index ) {
  26037. verticesArray.push( placeholder[ index * 3 + 0 ] );
  26038. verticesArray.push( placeholder[ index * 3 + 1 ] );
  26039. verticesArray.push( placeholder[ index * 3 + 2 ] );
  26040. }
  26041. function addUV( vector2 ) {
  26042. uvArray.push( vector2.x );
  26043. uvArray.push( vector2.y );
  26044. }
  26045. }
  26046. }
  26047. copy( source ) {
  26048. super.copy( source );
  26049. this.parameters = Object.assign( {}, source.parameters );
  26050. return this;
  26051. }
  26052. toJSON() {
  26053. const data = super.toJSON();
  26054. const shapes = this.parameters.shapes;
  26055. const options = this.parameters.options;
  26056. return toJSON$1( shapes, options, data );
  26057. }
  26058. /**
  26059. * Factory method for creating an instance of this class from the given
  26060. * JSON object.
  26061. *
  26062. * @param {Object} data - A JSON object representing the serialized geometry.
  26063. * @param {Array<Shape>} shapes - An array of shapes.
  26064. * @return {ExtrudeGeometry} A new instance.
  26065. */
  26066. static fromJSON( data, shapes ) {
  26067. const geometryShapes = [];
  26068. for ( let j = 0, jl = data.shapes.length; j < jl; j ++ ) {
  26069. const shape = shapes[ data.shapes[ j ] ];
  26070. geometryShapes.push( shape );
  26071. }
  26072. const extrudePath = data.options.extrudePath;
  26073. if ( extrudePath !== undefined ) {
  26074. data.options.extrudePath = new Curves[ extrudePath.type ]().fromJSON( extrudePath );
  26075. }
  26076. return new ExtrudeGeometry( geometryShapes, data.options );
  26077. }
  26078. }
  26079. const WorldUVGenerator = {
  26080. generateTopUV: function ( geometry, vertices, indexA, indexB, indexC ) {
  26081. const a_x = vertices[ indexA * 3 ];
  26082. const a_y = vertices[ indexA * 3 + 1 ];
  26083. const b_x = vertices[ indexB * 3 ];
  26084. const b_y = vertices[ indexB * 3 + 1 ];
  26085. const c_x = vertices[ indexC * 3 ];
  26086. const c_y = vertices[ indexC * 3 + 1 ];
  26087. return [
  26088. new Vector2( a_x, a_y ),
  26089. new Vector2( b_x, b_y ),
  26090. new Vector2( c_x, c_y )
  26091. ];
  26092. },
  26093. generateSideWallUV: function ( geometry, vertices, indexA, indexB, indexC, indexD ) {
  26094. const a_x = vertices[ indexA * 3 ];
  26095. const a_y = vertices[ indexA * 3 + 1 ];
  26096. const a_z = vertices[ indexA * 3 + 2 ];
  26097. const b_x = vertices[ indexB * 3 ];
  26098. const b_y = vertices[ indexB * 3 + 1 ];
  26099. const b_z = vertices[ indexB * 3 + 2 ];
  26100. const c_x = vertices[ indexC * 3 ];
  26101. const c_y = vertices[ indexC * 3 + 1 ];
  26102. const c_z = vertices[ indexC * 3 + 2 ];
  26103. const d_x = vertices[ indexD * 3 ];
  26104. const d_y = vertices[ indexD * 3 + 1 ];
  26105. const d_z = vertices[ indexD * 3 + 2 ];
  26106. if ( Math.abs( a_y - b_y ) < Math.abs( a_x - b_x ) ) {
  26107. return [
  26108. new Vector2( a_x, 1 - a_z ),
  26109. new Vector2( b_x, 1 - b_z ),
  26110. new Vector2( c_x, 1 - c_z ),
  26111. new Vector2( d_x, 1 - d_z )
  26112. ];
  26113. } else {
  26114. return [
  26115. new Vector2( a_y, 1 - a_z ),
  26116. new Vector2( b_y, 1 - b_z ),
  26117. new Vector2( c_y, 1 - c_z ),
  26118. new Vector2( d_y, 1 - d_z )
  26119. ];
  26120. }
  26121. }
  26122. };
  26123. function toJSON$1( shapes, options, data ) {
  26124. data.shapes = [];
  26125. if ( Array.isArray( shapes ) ) {
  26126. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  26127. const shape = shapes[ i ];
  26128. data.shapes.push( shape.uuid );
  26129. }
  26130. } else {
  26131. data.shapes.push( shapes.uuid );
  26132. }
  26133. data.options = Object.assign( {}, options );
  26134. if ( options.extrudePath !== undefined ) data.options.extrudePath = options.extrudePath.toJSON();
  26135. return data;
  26136. }
  26137. /**
  26138. * A geometry class for representing an icosahedron.
  26139. *
  26140. * ```js
  26141. * const geometry = new THREE.IcosahedronGeometry();
  26142. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  26143. * const icosahedron = new THREE.Mesh( geometry, material );
  26144. * scene.add( icosahedron );
  26145. * ```
  26146. *
  26147. * @augments PolyhedronGeometry
  26148. */
  26149. class IcosahedronGeometry extends PolyhedronGeometry {
  26150. /**
  26151. * Constructs a new icosahedron geometry.
  26152. *
  26153. * @param {number} [radius=1] - Radius of the icosahedron.
  26154. * @param {number} [detail=0] - Setting this to a value greater than `0` adds vertices making it no longer a icosahedron.
  26155. */
  26156. constructor( radius = 1, detail = 0 ) {
  26157. const t = ( 1 + Math.sqrt( 5 ) ) / 2;
  26158. const vertices = [
  26159. -1, t, 0, 1, t, 0, -1, - t, 0, 1, - t, 0,
  26160. 0, -1, t, 0, 1, t, 0, -1, - t, 0, 1, - t,
  26161. t, 0, -1, t, 0, 1, - t, 0, -1, - t, 0, 1
  26162. ];
  26163. const indices = [
  26164. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 0, 10, 11,
  26165. 1, 5, 9, 5, 11, 4, 11, 10, 2, 10, 7, 6, 7, 1, 8,
  26166. 3, 9, 4, 3, 4, 2, 3, 2, 6, 3, 6, 8, 3, 8, 9,
  26167. 4, 9, 5, 2, 4, 11, 6, 2, 10, 8, 6, 7, 9, 8, 1
  26168. ];
  26169. super( vertices, indices, radius, detail );
  26170. this.type = 'IcosahedronGeometry';
  26171. /**
  26172. * Holds the constructor parameters that have been
  26173. * used to generate the geometry. Any modification
  26174. * after instantiation does not change the geometry.
  26175. *
  26176. * @type {Object}
  26177. */
  26178. this.parameters = {
  26179. radius: radius,
  26180. detail: detail
  26181. };
  26182. }
  26183. /**
  26184. * Factory method for creating an instance of this class from the given
  26185. * JSON object.
  26186. *
  26187. * @param {Object} data - A JSON object representing the serialized geometry.
  26188. * @return {IcosahedronGeometry} A new instance.
  26189. */
  26190. static fromJSON( data ) {
  26191. return new IcosahedronGeometry( data.radius, data.detail );
  26192. }
  26193. }
  26194. /**
  26195. * Creates meshes with axial symmetry like vases. The lathe rotates around the Y axis.
  26196. *
  26197. * ```js
  26198. * const points = [];
  26199. * for ( let i = 0; i < 10; i ++ ) {
  26200. * points.push( new THREE.Vector2( Math.sin( i * 0.2 ) * 10 + 5, ( i - 5 ) * 2 ) );
  26201. * }
  26202. * const geometry = new THREE.LatheGeometry( points );
  26203. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  26204. * const lathe = new THREE.Mesh( geometry, material );
  26205. * scene.add( lathe );
  26206. * ```
  26207. *
  26208. * @augments BufferGeometry
  26209. */
  26210. class LatheGeometry extends BufferGeometry {
  26211. /**
  26212. * Constructs a new lathe geometry.
  26213. *
  26214. * @param {Array<Vector2|Vector3>} [points] - An array of points in 2D space. The x-coordinate of each point
  26215. * must be greater than zero.
  26216. * @param {number} [segments=12] - The number of circumference segments to generate.
  26217. * @param {number} [phiStart=0] - The starting angle in radians.
  26218. * @param {number} [phiLength=Math.PI*2] - The radian (0 to 2PI) range of the lathed section 2PI is a
  26219. * closed lathe, less than 2PI is a portion.
  26220. */
  26221. 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 ) {
  26222. super();
  26223. this.type = 'LatheGeometry';
  26224. /**
  26225. * Holds the constructor parameters that have been
  26226. * used to generate the geometry. Any modification
  26227. * after instantiation does not change the geometry.
  26228. *
  26229. * @type {Object}
  26230. */
  26231. this.parameters = {
  26232. points: points,
  26233. segments: segments,
  26234. phiStart: phiStart,
  26235. phiLength: phiLength
  26236. };
  26237. segments = Math.floor( segments );
  26238. // clamp phiLength so it's in range of [ 0, 2PI ]
  26239. phiLength = clamp( phiLength, 0, Math.PI * 2 );
  26240. // buffers
  26241. const indices = [];
  26242. const vertices = [];
  26243. const uvs = [];
  26244. const initNormals = [];
  26245. const normals = [];
  26246. // helper variables
  26247. const inverseSegments = 1.0 / segments;
  26248. const vertex = new Vector3();
  26249. const uv = new Vector2();
  26250. const normal = new Vector3();
  26251. const curNormal = new Vector3();
  26252. const prevNormal = new Vector3();
  26253. let dx = 0;
  26254. let dy = 0;
  26255. // pre-compute normals for initial "meridian"
  26256. for ( let j = 0; j <= ( points.length - 1 ); j ++ ) {
  26257. switch ( j ) {
  26258. case 0: // special handling for 1st vertex on path
  26259. dx = points[ j + 1 ].x - points[ j ].x;
  26260. dy = points[ j + 1 ].y - points[ j ].y;
  26261. normal.x = dy * 1.0;
  26262. normal.y = - dx;
  26263. normal.z = dy * 0.0;
  26264. prevNormal.copy( normal );
  26265. normal.normalize();
  26266. initNormals.push( normal.x, normal.y, normal.z );
  26267. break;
  26268. case ( points.length - 1 ): // special handling for last Vertex on path
  26269. initNormals.push( prevNormal.x, prevNormal.y, prevNormal.z );
  26270. break;
  26271. default: // default handling for all vertices in between
  26272. dx = points[ j + 1 ].x - points[ j ].x;
  26273. dy = points[ j + 1 ].y - points[ j ].y;
  26274. normal.x = dy * 1.0;
  26275. normal.y = - dx;
  26276. normal.z = dy * 0.0;
  26277. curNormal.copy( normal );
  26278. normal.x += prevNormal.x;
  26279. normal.y += prevNormal.y;
  26280. normal.z += prevNormal.z;
  26281. normal.normalize();
  26282. initNormals.push( normal.x, normal.y, normal.z );
  26283. prevNormal.copy( curNormal );
  26284. }
  26285. }
  26286. // generate vertices, uvs and normals
  26287. for ( let i = 0; i <= segments; i ++ ) {
  26288. const phi = phiStart + i * inverseSegments * phiLength;
  26289. const sin = Math.sin( phi );
  26290. const cos = Math.cos( phi );
  26291. for ( let j = 0; j <= ( points.length - 1 ); j ++ ) {
  26292. // vertex
  26293. vertex.x = points[ j ].x * sin;
  26294. vertex.y = points[ j ].y;
  26295. vertex.z = points[ j ].x * cos;
  26296. vertices.push( vertex.x, vertex.y, vertex.z );
  26297. // uv
  26298. uv.x = i / segments;
  26299. uv.y = j / ( points.length - 1 );
  26300. uvs.push( uv.x, uv.y );
  26301. // normal
  26302. const x = initNormals[ 3 * j + 0 ] * sin;
  26303. const y = initNormals[ 3 * j + 1 ];
  26304. const z = initNormals[ 3 * j + 0 ] * cos;
  26305. normals.push( x, y, z );
  26306. }
  26307. }
  26308. // indices
  26309. for ( let i = 0; i < segments; i ++ ) {
  26310. for ( let j = 0; j < ( points.length - 1 ); j ++ ) {
  26311. const base = j + i * points.length;
  26312. const a = base;
  26313. const b = base + points.length;
  26314. const c = base + points.length + 1;
  26315. const d = base + 1;
  26316. // faces
  26317. indices.push( a, b, d );
  26318. indices.push( c, d, b );
  26319. }
  26320. }
  26321. // build geometry
  26322. this.setIndex( indices );
  26323. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  26324. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  26325. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  26326. }
  26327. copy( source ) {
  26328. super.copy( source );
  26329. this.parameters = Object.assign( {}, source.parameters );
  26330. return this;
  26331. }
  26332. /**
  26333. * Factory method for creating an instance of this class from the given
  26334. * JSON object.
  26335. *
  26336. * @param {Object} data - A JSON object representing the serialized geometry.
  26337. * @return {LatheGeometry} A new instance.
  26338. */
  26339. static fromJSON( data ) {
  26340. return new LatheGeometry( data.points, data.segments, data.phiStart, data.phiLength );
  26341. }
  26342. }
  26343. /**
  26344. * A geometry class for representing an octahedron.
  26345. *
  26346. * ```js
  26347. * const geometry = new THREE.OctahedronGeometry();
  26348. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  26349. * const octahedron = new THREE.Mesh( geometry, material );
  26350. * scene.add( octahedron );
  26351. * ```
  26352. *
  26353. * @augments PolyhedronGeometry
  26354. */
  26355. class OctahedronGeometry extends PolyhedronGeometry {
  26356. /**
  26357. * Constructs a new octahedron geometry.
  26358. *
  26359. * @param {number} [radius=1] - Radius of the octahedron.
  26360. * @param {number} [detail=0] - Setting this to a value greater than `0` adds vertices making it no longer a octahedron.
  26361. */
  26362. constructor( radius = 1, detail = 0 ) {
  26363. const vertices = [
  26364. 1, 0, 0, -1, 0, 0, 0, 1, 0,
  26365. 0, -1, 0, 0, 0, 1, 0, 0, -1
  26366. ];
  26367. const indices = [
  26368. 0, 2, 4, 0, 4, 3, 0, 3, 5,
  26369. 0, 5, 2, 1, 2, 5, 1, 5, 3,
  26370. 1, 3, 4, 1, 4, 2
  26371. ];
  26372. super( vertices, indices, radius, detail );
  26373. this.type = 'OctahedronGeometry';
  26374. /**
  26375. * Holds the constructor parameters that have been
  26376. * used to generate the geometry. Any modification
  26377. * after instantiation does not change the geometry.
  26378. *
  26379. * @type {Object}
  26380. */
  26381. this.parameters = {
  26382. radius: radius,
  26383. detail: detail
  26384. };
  26385. }
  26386. /**
  26387. * Factory method for creating an instance of this class from the given
  26388. * JSON object.
  26389. *
  26390. * @param {Object} data - A JSON object representing the serialized geometry.
  26391. * @return {OctahedronGeometry} A new instance.
  26392. */
  26393. static fromJSON( data ) {
  26394. return new OctahedronGeometry( data.radius, data.detail );
  26395. }
  26396. }
  26397. /**
  26398. * A geometry class for representing a plane.
  26399. *
  26400. * ```js
  26401. * const geometry = new THREE.PlaneGeometry( 1, 1 );
  26402. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00, side: THREE.DoubleSide } );
  26403. * const plane = new THREE.Mesh( geometry, material );
  26404. * scene.add( plane );
  26405. * ```
  26406. *
  26407. * @augments BufferGeometry
  26408. */
  26409. class PlaneGeometry extends BufferGeometry {
  26410. /**
  26411. * Constructs a new plane geometry.
  26412. *
  26413. * @param {number} [width=1] - The width along the X axis.
  26414. * @param {number} [height=1] - The height along the Y axis
  26415. * @param {number} [widthSegments=1] - The number of segments along the X axis.
  26416. * @param {number} [heightSegments=1] - The number of segments along the Y axis.
  26417. */
  26418. constructor( width = 1, height = 1, widthSegments = 1, heightSegments = 1 ) {
  26419. super();
  26420. this.type = 'PlaneGeometry';
  26421. /**
  26422. * Holds the constructor parameters that have been
  26423. * used to generate the geometry. Any modification
  26424. * after instantiation does not change the geometry.
  26425. *
  26426. * @type {Object}
  26427. */
  26428. this.parameters = {
  26429. width: width,
  26430. height: height,
  26431. widthSegments: widthSegments,
  26432. heightSegments: heightSegments
  26433. };
  26434. const width_half = width / 2;
  26435. const height_half = height / 2;
  26436. const gridX = Math.floor( widthSegments );
  26437. const gridY = Math.floor( heightSegments );
  26438. const gridX1 = gridX + 1;
  26439. const gridY1 = gridY + 1;
  26440. const segment_width = width / gridX;
  26441. const segment_height = height / gridY;
  26442. //
  26443. const indices = [];
  26444. const vertices = [];
  26445. const normals = [];
  26446. const uvs = [];
  26447. for ( let iy = 0; iy < gridY1; iy ++ ) {
  26448. const y = iy * segment_height - height_half;
  26449. for ( let ix = 0; ix < gridX1; ix ++ ) {
  26450. const x = ix * segment_width - width_half;
  26451. vertices.push( x, - y, 0 );
  26452. normals.push( 0, 0, 1 );
  26453. uvs.push( ix / gridX );
  26454. uvs.push( 1 - ( iy / gridY ) );
  26455. }
  26456. }
  26457. for ( let iy = 0; iy < gridY; iy ++ ) {
  26458. for ( let ix = 0; ix < gridX; ix ++ ) {
  26459. const a = ix + gridX1 * iy;
  26460. const b = ix + gridX1 * ( iy + 1 );
  26461. const c = ( ix + 1 ) + gridX1 * ( iy + 1 );
  26462. const d = ( ix + 1 ) + gridX1 * iy;
  26463. indices.push( a, b, d );
  26464. indices.push( b, c, d );
  26465. }
  26466. }
  26467. this.setIndex( indices );
  26468. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  26469. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  26470. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  26471. }
  26472. copy( source ) {
  26473. super.copy( source );
  26474. this.parameters = Object.assign( {}, source.parameters );
  26475. return this;
  26476. }
  26477. /**
  26478. * Factory method for creating an instance of this class from the given
  26479. * JSON object.
  26480. *
  26481. * @param {Object} data - A JSON object representing the serialized geometry.
  26482. * @return {PlaneGeometry} A new instance.
  26483. */
  26484. static fromJSON( data ) {
  26485. return new PlaneGeometry( data.width, data.height, data.widthSegments, data.heightSegments );
  26486. }
  26487. }
  26488. /**
  26489. * A class for generating a two-dimensional ring geometry.
  26490. *
  26491. * ```js
  26492. * const geometry = new THREE.RingGeometry( 1, 5, 32 );
  26493. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00, side: THREE.DoubleSide } );
  26494. * const mesh = new THREE.Mesh( geometry, material );
  26495. * scene.add( mesh );
  26496. * ```
  26497. *
  26498. * @augments BufferGeometry
  26499. */
  26500. class RingGeometry extends BufferGeometry {
  26501. /**
  26502. * Constructs a new ring geometry.
  26503. *
  26504. * @param {number} [innerRadius=0.5] - The inner radius of the ring.
  26505. * @param {number} [outerRadius=1] - The outer radius of the ring.
  26506. * @param {number} [thetaSegments=32] - Number of segments. A higher number means the ring will be more round. Minimum is `3`.
  26507. * @param {number} [phiSegments=1] - Number of segments per ring segment. Minimum is `1`.
  26508. * @param {number} [thetaStart=0] - Starting angle in radians.
  26509. * @param {number} [thetaLength=Math.PI*2] - Central angle in radians.
  26510. */
  26511. constructor( innerRadius = 0.5, outerRadius = 1, thetaSegments = 32, phiSegments = 1, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  26512. super();
  26513. this.type = 'RingGeometry';
  26514. /**
  26515. * Holds the constructor parameters that have been
  26516. * used to generate the geometry. Any modification
  26517. * after instantiation does not change the geometry.
  26518. *
  26519. * @type {Object}
  26520. */
  26521. this.parameters = {
  26522. innerRadius: innerRadius,
  26523. outerRadius: outerRadius,
  26524. thetaSegments: thetaSegments,
  26525. phiSegments: phiSegments,
  26526. thetaStart: thetaStart,
  26527. thetaLength: thetaLength
  26528. };
  26529. thetaSegments = Math.max( 3, thetaSegments );
  26530. phiSegments = Math.max( 1, phiSegments );
  26531. // buffers
  26532. const indices = [];
  26533. const vertices = [];
  26534. const normals = [];
  26535. const uvs = [];
  26536. // some helper variables
  26537. let radius = innerRadius;
  26538. const radiusStep = ( ( outerRadius - innerRadius ) / phiSegments );
  26539. const vertex = new Vector3();
  26540. const uv = new Vector2();
  26541. // generate vertices, normals and uvs
  26542. for ( let j = 0; j <= phiSegments; j ++ ) {
  26543. for ( let i = 0; i <= thetaSegments; i ++ ) {
  26544. // values are generate from the inside of the ring to the outside
  26545. const segment = thetaStart + i / thetaSegments * thetaLength;
  26546. // vertex
  26547. vertex.x = radius * Math.cos( segment );
  26548. vertex.y = radius * Math.sin( segment );
  26549. vertices.push( vertex.x, vertex.y, vertex.z );
  26550. // normal
  26551. normals.push( 0, 0, 1 );
  26552. // uv
  26553. uv.x = ( vertex.x / outerRadius + 1 ) / 2;
  26554. uv.y = ( vertex.y / outerRadius + 1 ) / 2;
  26555. uvs.push( uv.x, uv.y );
  26556. }
  26557. // increase the radius for next row of vertices
  26558. radius += radiusStep;
  26559. }
  26560. // indices
  26561. for ( let j = 0; j < phiSegments; j ++ ) {
  26562. const thetaSegmentLevel = j * ( thetaSegments + 1 );
  26563. for ( let i = 0; i < thetaSegments; i ++ ) {
  26564. const segment = i + thetaSegmentLevel;
  26565. const a = segment;
  26566. const b = segment + thetaSegments + 1;
  26567. const c = segment + thetaSegments + 2;
  26568. const d = segment + 1;
  26569. // faces
  26570. indices.push( a, b, d );
  26571. indices.push( b, c, d );
  26572. }
  26573. }
  26574. // build geometry
  26575. this.setIndex( indices );
  26576. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  26577. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  26578. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  26579. }
  26580. copy( source ) {
  26581. super.copy( source );
  26582. this.parameters = Object.assign( {}, source.parameters );
  26583. return this;
  26584. }
  26585. /**
  26586. * Factory method for creating an instance of this class from the given
  26587. * JSON object.
  26588. *
  26589. * @param {Object} data - A JSON object representing the serialized geometry.
  26590. * @return {RingGeometry} A new instance.
  26591. */
  26592. static fromJSON( data ) {
  26593. return new RingGeometry( data.innerRadius, data.outerRadius, data.thetaSegments, data.phiSegments, data.thetaStart, data.thetaLength );
  26594. }
  26595. }
  26596. /**
  26597. * Creates an one-sided polygonal geometry from one or more path shapes.
  26598. *
  26599. * ```js
  26600. * const arcShape = new THREE.Shape()
  26601. * .moveTo( 5, 1 )
  26602. * .absarc( 1, 1, 4, 0, Math.PI * 2, false );
  26603. *
  26604. * const geometry = new THREE.ShapeGeometry( arcShape );
  26605. * const material = new THREE.MeshBasicMaterial( { color: 0x00ff00, side: THREE.DoubleSide } );
  26606. * const mesh = new THREE.Mesh( geometry, material ) ;
  26607. * scene.add( mesh );
  26608. * ```
  26609. *
  26610. * @augments BufferGeometry
  26611. */
  26612. class ShapeGeometry extends BufferGeometry {
  26613. /**
  26614. * Constructs a new shape geometry.
  26615. *
  26616. * @param {Shape|Array<Shape>} [shapes] - A shape or an array of shapes.
  26617. * @param {number} [curveSegments=12] - Number of segments per shape.
  26618. */
  26619. constructor( shapes = new Shape( [ new Vector2( 0, 0.5 ), new Vector2( -0.5, -0.5 ), new Vector2( 0.5, -0.5 ) ] ), curveSegments = 12 ) {
  26620. super();
  26621. this.type = 'ShapeGeometry';
  26622. /**
  26623. * Holds the constructor parameters that have been
  26624. * used to generate the geometry. Any modification
  26625. * after instantiation does not change the geometry.
  26626. *
  26627. * @type {Object}
  26628. */
  26629. this.parameters = {
  26630. shapes: shapes,
  26631. curveSegments: curveSegments
  26632. };
  26633. // buffers
  26634. const indices = [];
  26635. const vertices = [];
  26636. const normals = [];
  26637. const uvs = [];
  26638. // helper variables
  26639. let groupStart = 0;
  26640. let groupCount = 0;
  26641. // allow single and array values for "shapes" parameter
  26642. if ( Array.isArray( shapes ) === false ) {
  26643. addShape( shapes );
  26644. } else {
  26645. for ( let i = 0; i < shapes.length; i ++ ) {
  26646. addShape( shapes[ i ] );
  26647. this.addGroup( groupStart, groupCount, i ); // enables MultiMaterial support
  26648. groupStart += groupCount;
  26649. groupCount = 0;
  26650. }
  26651. }
  26652. // build geometry
  26653. this.setIndex( indices );
  26654. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  26655. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  26656. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  26657. // helper functions
  26658. function addShape( shape ) {
  26659. const indexOffset = vertices.length / 3;
  26660. const points = shape.extractPoints( curveSegments );
  26661. let shapeVertices = points.shape;
  26662. const shapeHoles = points.holes;
  26663. // check direction of vertices
  26664. if ( ShapeUtils.isClockWise( shapeVertices ) === false ) {
  26665. shapeVertices = shapeVertices.reverse();
  26666. }
  26667. for ( let i = 0, l = shapeHoles.length; i < l; i ++ ) {
  26668. const shapeHole = shapeHoles[ i ];
  26669. if ( ShapeUtils.isClockWise( shapeHole ) === true ) {
  26670. shapeHoles[ i ] = shapeHole.reverse();
  26671. }
  26672. }
  26673. const faces = ShapeUtils.triangulateShape( shapeVertices, shapeHoles );
  26674. // join vertices of inner and outer paths to a single array
  26675. for ( let i = 0, l = shapeHoles.length; i < l; i ++ ) {
  26676. const shapeHole = shapeHoles[ i ];
  26677. shapeVertices = shapeVertices.concat( shapeHole );
  26678. }
  26679. // vertices, normals, uvs
  26680. for ( let i = 0, l = shapeVertices.length; i < l; i ++ ) {
  26681. const vertex = shapeVertices[ i ];
  26682. vertices.push( vertex.x, vertex.y, 0 );
  26683. normals.push( 0, 0, 1 );
  26684. uvs.push( vertex.x, vertex.y ); // world uvs
  26685. }
  26686. // indices
  26687. for ( let i = 0, l = faces.length; i < l; i ++ ) {
  26688. const face = faces[ i ];
  26689. const a = face[ 0 ] + indexOffset;
  26690. const b = face[ 1 ] + indexOffset;
  26691. const c = face[ 2 ] + indexOffset;
  26692. indices.push( a, b, c );
  26693. groupCount += 3;
  26694. }
  26695. }
  26696. }
  26697. copy( source ) {
  26698. super.copy( source );
  26699. this.parameters = Object.assign( {}, source.parameters );
  26700. return this;
  26701. }
  26702. toJSON() {
  26703. const data = super.toJSON();
  26704. const shapes = this.parameters.shapes;
  26705. return toJSON( shapes, data );
  26706. }
  26707. /**
  26708. * Factory method for creating an instance of this class from the given
  26709. * JSON object.
  26710. *
  26711. * @param {Object} data - A JSON object representing the serialized geometry.
  26712. * @param {Array<Shape>} shapes - An array of shapes.
  26713. * @return {ShapeGeometry} A new instance.
  26714. */
  26715. static fromJSON( data, shapes ) {
  26716. const geometryShapes = [];
  26717. for ( let j = 0, jl = data.shapes.length; j < jl; j ++ ) {
  26718. const shape = shapes[ data.shapes[ j ] ];
  26719. geometryShapes.push( shape );
  26720. }
  26721. return new ShapeGeometry( geometryShapes, data.curveSegments );
  26722. }
  26723. }
  26724. function toJSON( shapes, data ) {
  26725. data.shapes = [];
  26726. if ( Array.isArray( shapes ) ) {
  26727. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  26728. const shape = shapes[ i ];
  26729. data.shapes.push( shape.uuid );
  26730. }
  26731. } else {
  26732. data.shapes.push( shapes.uuid );
  26733. }
  26734. return data;
  26735. }
  26736. /**
  26737. * A class for generating a sphere geometry.
  26738. *
  26739. * ```js
  26740. * const geometry = new THREE.SphereGeometry( 15, 32, 16 );
  26741. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  26742. * const sphere = new THREE.Mesh( geometry, material );
  26743. * scene.add( sphere );
  26744. * ```
  26745. *
  26746. * @augments BufferGeometry
  26747. */
  26748. class SphereGeometry extends BufferGeometry {
  26749. /**
  26750. * Constructs a new sphere geometry.
  26751. *
  26752. * @param {number} [radius=1] - The sphere radius.
  26753. * @param {number} [widthSegments=32] - The number of horizontal segments. Minimum value is `3`.
  26754. * @param {number} [heightSegments=16] - The number of vertical segments. Minimum value is `2`.
  26755. * @param {number} [phiStart=0] - The horizontal starting angle in radians.
  26756. * @param {number} [phiLength=Math.PI*2] - The horizontal sweep angle size.
  26757. * @param {number} [thetaStart=0] - The vertical starting angle in radians.
  26758. * @param {number} [thetaLength=Math.PI] - The vertical sweep angle size.
  26759. */
  26760. constructor( radius = 1, widthSegments = 32, heightSegments = 16, phiStart = 0, phiLength = Math.PI * 2, thetaStart = 0, thetaLength = Math.PI ) {
  26761. super();
  26762. this.type = 'SphereGeometry';
  26763. /**
  26764. * Holds the constructor parameters that have been
  26765. * used to generate the geometry. Any modification
  26766. * after instantiation does not change the geometry.
  26767. *
  26768. * @type {Object}
  26769. */
  26770. this.parameters = {
  26771. radius: radius,
  26772. widthSegments: widthSegments,
  26773. heightSegments: heightSegments,
  26774. phiStart: phiStart,
  26775. phiLength: phiLength,
  26776. thetaStart: thetaStart,
  26777. thetaLength: thetaLength
  26778. };
  26779. widthSegments = Math.max( 3, Math.floor( widthSegments ) );
  26780. heightSegments = Math.max( 2, Math.floor( heightSegments ) );
  26781. const thetaEnd = Math.min( thetaStart + thetaLength, Math.PI );
  26782. let index = 0;
  26783. const grid = [];
  26784. const vertex = new Vector3();
  26785. const normal = new Vector3();
  26786. // buffers
  26787. const indices = [];
  26788. const vertices = [];
  26789. const normals = [];
  26790. const uvs = [];
  26791. // generate vertices, normals and uvs
  26792. for ( let iy = 0; iy <= heightSegments; iy ++ ) {
  26793. const verticesRow = [];
  26794. const v = iy / heightSegments;
  26795. // special case for the poles
  26796. let uOffset = 0;
  26797. if ( iy === 0 && thetaStart === 0 ) {
  26798. uOffset = 0.5 / widthSegments;
  26799. } else if ( iy === heightSegments && thetaEnd === Math.PI ) {
  26800. uOffset = -0.5 / widthSegments;
  26801. }
  26802. for ( let ix = 0; ix <= widthSegments; ix ++ ) {
  26803. const u = ix / widthSegments;
  26804. // vertex
  26805. vertex.x = - radius * Math.cos( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  26806. vertex.y = radius * Math.cos( thetaStart + v * thetaLength );
  26807. vertex.z = radius * Math.sin( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  26808. vertices.push( vertex.x, vertex.y, vertex.z );
  26809. // normal
  26810. normal.copy( vertex ).normalize();
  26811. normals.push( normal.x, normal.y, normal.z );
  26812. // uv
  26813. uvs.push( u + uOffset, 1 - v );
  26814. verticesRow.push( index ++ );
  26815. }
  26816. grid.push( verticesRow );
  26817. }
  26818. // indices
  26819. for ( let iy = 0; iy < heightSegments; iy ++ ) {
  26820. for ( let ix = 0; ix < widthSegments; ix ++ ) {
  26821. const a = grid[ iy ][ ix + 1 ];
  26822. const b = grid[ iy ][ ix ];
  26823. const c = grid[ iy + 1 ][ ix ];
  26824. const d = grid[ iy + 1 ][ ix + 1 ];
  26825. if ( iy !== 0 || thetaStart > 0 ) indices.push( a, b, d );
  26826. if ( iy !== heightSegments - 1 || thetaEnd < Math.PI ) indices.push( b, c, d );
  26827. }
  26828. }
  26829. // build geometry
  26830. this.setIndex( indices );
  26831. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  26832. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  26833. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  26834. }
  26835. copy( source ) {
  26836. super.copy( source );
  26837. this.parameters = Object.assign( {}, source.parameters );
  26838. return this;
  26839. }
  26840. /**
  26841. * Factory method for creating an instance of this class from the given
  26842. * JSON object.
  26843. *
  26844. * @param {Object} data - A JSON object representing the serialized geometry.
  26845. * @return {SphereGeometry} A new instance.
  26846. */
  26847. static fromJSON( data ) {
  26848. return new SphereGeometry( data.radius, data.widthSegments, data.heightSegments, data.phiStart, data.phiLength, data.thetaStart, data.thetaLength );
  26849. }
  26850. }
  26851. /**
  26852. * A geometry class for representing an tetrahedron.
  26853. *
  26854. * ```js
  26855. * const geometry = new THREE.TetrahedronGeometry();
  26856. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  26857. * const tetrahedron = new THREE.Mesh( geometry, material );
  26858. * scene.add( tetrahedron );
  26859. * ```
  26860. *
  26861. * @augments PolyhedronGeometry
  26862. */
  26863. class TetrahedronGeometry extends PolyhedronGeometry {
  26864. /**
  26865. * Constructs a new tetrahedron geometry.
  26866. *
  26867. * @param {number} [radius=1] - Radius of the tetrahedron.
  26868. * @param {number} [detail=0] - Setting this to a value greater than `0` adds vertices making it no longer a tetrahedron.
  26869. */
  26870. constructor( radius = 1, detail = 0 ) {
  26871. const vertices = [
  26872. 1, 1, 1, -1, -1, 1, -1, 1, -1, 1, -1, -1
  26873. ];
  26874. const indices = [
  26875. 2, 1, 0, 0, 3, 2, 1, 3, 0, 2, 3, 1
  26876. ];
  26877. super( vertices, indices, radius, detail );
  26878. this.type = 'TetrahedronGeometry';
  26879. /**
  26880. * Holds the constructor parameters that have been
  26881. * used to generate the geometry. Any modification
  26882. * after instantiation does not change the geometry.
  26883. *
  26884. * @type {Object}
  26885. */
  26886. this.parameters = {
  26887. radius: radius,
  26888. detail: detail
  26889. };
  26890. }
  26891. /**
  26892. * Factory method for creating an instance of this class from the given
  26893. * JSON object.
  26894. *
  26895. * @param {Object} data - A JSON object representing the serialized geometry.
  26896. * @return {TetrahedronGeometry} A new instance.
  26897. */
  26898. static fromJSON( data ) {
  26899. return new TetrahedronGeometry( data.radius, data.detail );
  26900. }
  26901. }
  26902. /**
  26903. * A geometry class for representing an torus.
  26904. *
  26905. * ```js
  26906. * const geometry = new THREE.TorusGeometry( 10, 3, 16, 100 );
  26907. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  26908. * const torus = new THREE.Mesh( geometry, material );
  26909. * scene.add( torus );
  26910. * ```
  26911. *
  26912. * @augments BufferGeometry
  26913. */
  26914. class TorusGeometry extends BufferGeometry {
  26915. /**
  26916. * Constructs a new torus geometry.
  26917. *
  26918. * @param {number} [radius=1] - Radius of the torus, from the center of the torus to the center of the tube.
  26919. * @param {number} [tube=0.4] - Radius of the tube. Must be smaller than `radius`.
  26920. * @param {number} [radialSegments=12] - The number of radial segments.
  26921. * @param {number} [tubularSegments=48] - The number of tubular segments.
  26922. * @param {number} [arc=Math.PI*2] - Central angle in radians.
  26923. */
  26924. constructor( radius = 1, tube = 0.4, radialSegments = 12, tubularSegments = 48, arc = Math.PI * 2 ) {
  26925. super();
  26926. this.type = 'TorusGeometry';
  26927. /**
  26928. * Holds the constructor parameters that have been
  26929. * used to generate the geometry. Any modification
  26930. * after instantiation does not change the geometry.
  26931. *
  26932. * @type {Object}
  26933. */
  26934. this.parameters = {
  26935. radius: radius,
  26936. tube: tube,
  26937. radialSegments: radialSegments,
  26938. tubularSegments: tubularSegments,
  26939. arc: arc
  26940. };
  26941. radialSegments = Math.floor( radialSegments );
  26942. tubularSegments = Math.floor( tubularSegments );
  26943. // buffers
  26944. const indices = [];
  26945. const vertices = [];
  26946. const normals = [];
  26947. const uvs = [];
  26948. // helper variables
  26949. const center = new Vector3();
  26950. const vertex = new Vector3();
  26951. const normal = new Vector3();
  26952. // generate vertices, normals and uvs
  26953. for ( let j = 0; j <= radialSegments; j ++ ) {
  26954. for ( let i = 0; i <= tubularSegments; i ++ ) {
  26955. const u = i / tubularSegments * arc;
  26956. const v = j / radialSegments * Math.PI * 2;
  26957. // vertex
  26958. vertex.x = ( radius + tube * Math.cos( v ) ) * Math.cos( u );
  26959. vertex.y = ( radius + tube * Math.cos( v ) ) * Math.sin( u );
  26960. vertex.z = tube * Math.sin( v );
  26961. vertices.push( vertex.x, vertex.y, vertex.z );
  26962. // normal
  26963. center.x = radius * Math.cos( u );
  26964. center.y = radius * Math.sin( u );
  26965. normal.subVectors( vertex, center ).normalize();
  26966. normals.push( normal.x, normal.y, normal.z );
  26967. // uv
  26968. uvs.push( i / tubularSegments );
  26969. uvs.push( j / radialSegments );
  26970. }
  26971. }
  26972. // generate indices
  26973. for ( let j = 1; j <= radialSegments; j ++ ) {
  26974. for ( let i = 1; i <= tubularSegments; i ++ ) {
  26975. // indices
  26976. const a = ( tubularSegments + 1 ) * j + i - 1;
  26977. const b = ( tubularSegments + 1 ) * ( j - 1 ) + i - 1;
  26978. const c = ( tubularSegments + 1 ) * ( j - 1 ) + i;
  26979. const d = ( tubularSegments + 1 ) * j + i;
  26980. // faces
  26981. indices.push( a, b, d );
  26982. indices.push( b, c, d );
  26983. }
  26984. }
  26985. // build geometry
  26986. this.setIndex( indices );
  26987. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  26988. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  26989. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  26990. }
  26991. copy( source ) {
  26992. super.copy( source );
  26993. this.parameters = Object.assign( {}, source.parameters );
  26994. return this;
  26995. }
  26996. /**
  26997. * Factory method for creating an instance of this class from the given
  26998. * JSON object.
  26999. *
  27000. * @param {Object} data - A JSON object representing the serialized geometry.
  27001. * @return {TorusGeometry} A new instance.
  27002. */
  27003. static fromJSON( data ) {
  27004. return new TorusGeometry( data.radius, data.tube, data.radialSegments, data.tubularSegments, data.arc );
  27005. }
  27006. }
  27007. /**
  27008. * Creates a torus knot, the particular shape of which is defined by a pair
  27009. * of coprime integers, p and q. If p and q are not coprime, the result will
  27010. * be a torus link.
  27011. *
  27012. * ```js
  27013. * const geometry = new THREE.TorusKnotGeometry( 10, 3, 100, 16 );
  27014. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  27015. * const torusKnot = new THREE.Mesh( geometry, material );
  27016. * scene.add( torusKnot );
  27017. * ```
  27018. *
  27019. * @augments BufferGeometry
  27020. */
  27021. class TorusKnotGeometry extends BufferGeometry {
  27022. /**
  27023. * Constructs a new torus knot geometry.
  27024. *
  27025. * @param {number} [radius=1] - Radius of the torus knot.
  27026. * @param {number} [tube=0.4] - Radius of the tube.
  27027. * @param {number} [tubularSegments=64] - The number of tubular segments.
  27028. * @param {number} [radialSegments=8] - The number of radial segments.
  27029. * @param {number} [p=2] - This value determines, how many times the geometry winds around its axis of rotational symmetry.
  27030. * @param {number} [q=3] - This value determines, how many times the geometry winds around a circle in the interior of the torus.
  27031. */
  27032. constructor( radius = 1, tube = 0.4, tubularSegments = 64, radialSegments = 8, p = 2, q = 3 ) {
  27033. super();
  27034. this.type = 'TorusKnotGeometry';
  27035. /**
  27036. * Holds the constructor parameters that have been
  27037. * used to generate the geometry. Any modification
  27038. * after instantiation does not change the geometry.
  27039. *
  27040. * @type {Object}
  27041. */
  27042. this.parameters = {
  27043. radius: radius,
  27044. tube: tube,
  27045. tubularSegments: tubularSegments,
  27046. radialSegments: radialSegments,
  27047. p: p,
  27048. q: q
  27049. };
  27050. tubularSegments = Math.floor( tubularSegments );
  27051. radialSegments = Math.floor( radialSegments );
  27052. // buffers
  27053. const indices = [];
  27054. const vertices = [];
  27055. const normals = [];
  27056. const uvs = [];
  27057. // helper variables
  27058. const vertex = new Vector3();
  27059. const normal = new Vector3();
  27060. const P1 = new Vector3();
  27061. const P2 = new Vector3();
  27062. const B = new Vector3();
  27063. const T = new Vector3();
  27064. const N = new Vector3();
  27065. // generate vertices, normals and uvs
  27066. for ( let i = 0; i <= tubularSegments; ++ i ) {
  27067. // the radian "u" is used to calculate the position on the torus curve of the current tubular segment
  27068. const u = i / tubularSegments * p * Math.PI * 2;
  27069. // now we calculate two points. P1 is our current position on the curve, P2 is a little farther ahead.
  27070. // these points are used to create a special "coordinate space", which is necessary to calculate the correct vertex positions
  27071. calculatePositionOnCurve( u, p, q, radius, P1 );
  27072. calculatePositionOnCurve( u + 0.01, p, q, radius, P2 );
  27073. // calculate orthonormal basis
  27074. T.subVectors( P2, P1 );
  27075. N.addVectors( P2, P1 );
  27076. B.crossVectors( T, N );
  27077. N.crossVectors( B, T );
  27078. // normalize B, N. T can be ignored, we don't use it
  27079. B.normalize();
  27080. N.normalize();
  27081. for ( let j = 0; j <= radialSegments; ++ j ) {
  27082. // now calculate the vertices. they are nothing more than an extrusion of the torus curve.
  27083. // because we extrude a shape in the xy-plane, there is no need to calculate a z-value.
  27084. const v = j / radialSegments * Math.PI * 2;
  27085. const cx = - tube * Math.cos( v );
  27086. const cy = tube * Math.sin( v );
  27087. // now calculate the final vertex position.
  27088. // first we orient the extrusion with our basis vectors, then we add it to the current position on the curve
  27089. vertex.x = P1.x + ( cx * N.x + cy * B.x );
  27090. vertex.y = P1.y + ( cx * N.y + cy * B.y );
  27091. vertex.z = P1.z + ( cx * N.z + cy * B.z );
  27092. vertices.push( vertex.x, vertex.y, vertex.z );
  27093. // normal (P1 is always the center/origin of the extrusion, thus we can use it to calculate the normal)
  27094. normal.subVectors( vertex, P1 ).normalize();
  27095. normals.push( normal.x, normal.y, normal.z );
  27096. // uv
  27097. uvs.push( i / tubularSegments );
  27098. uvs.push( j / radialSegments );
  27099. }
  27100. }
  27101. // generate indices
  27102. for ( let j = 1; j <= tubularSegments; j ++ ) {
  27103. for ( let i = 1; i <= radialSegments; i ++ ) {
  27104. // indices
  27105. const a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 );
  27106. const b = ( radialSegments + 1 ) * j + ( i - 1 );
  27107. const c = ( radialSegments + 1 ) * j + i;
  27108. const d = ( radialSegments + 1 ) * ( j - 1 ) + i;
  27109. // faces
  27110. indices.push( a, b, d );
  27111. indices.push( b, c, d );
  27112. }
  27113. }
  27114. // build geometry
  27115. this.setIndex( indices );
  27116. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  27117. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  27118. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  27119. // this function calculates the current position on the torus curve
  27120. function calculatePositionOnCurve( u, p, q, radius, position ) {
  27121. const cu = Math.cos( u );
  27122. const su = Math.sin( u );
  27123. const quOverP = q / p * u;
  27124. const cs = Math.cos( quOverP );
  27125. position.x = radius * ( 2 + cs ) * 0.5 * cu;
  27126. position.y = radius * ( 2 + cs ) * su * 0.5;
  27127. position.z = radius * Math.sin( quOverP ) * 0.5;
  27128. }
  27129. }
  27130. copy( source ) {
  27131. super.copy( source );
  27132. this.parameters = Object.assign( {}, source.parameters );
  27133. return this;
  27134. }
  27135. /**
  27136. * Factory method for creating an instance of this class from the given
  27137. * JSON object.
  27138. *
  27139. * @param {Object} data - A JSON object representing the serialized geometry.
  27140. * @return {TorusKnotGeometry} A new instance.
  27141. */
  27142. static fromJSON( data ) {
  27143. return new TorusKnotGeometry( data.radius, data.tube, data.tubularSegments, data.radialSegments, data.p, data.q );
  27144. }
  27145. }
  27146. /**
  27147. * Creates a tube that extrudes along a 3D curve.
  27148. *
  27149. * ```js
  27150. * class CustomSinCurve extends THREE.Curve {
  27151. *
  27152. * getPoint( t, optionalTarget = new THREE.Vector3() ) {
  27153. *
  27154. * const tx = t * 3 - 1.5;
  27155. * const ty = Math.sin( 2 * Math.PI * t );
  27156. * const tz = 0;
  27157. *
  27158. * return optionalTarget.set( tx, ty, tz );
  27159. * }
  27160. *
  27161. * }
  27162. *
  27163. * const path = new CustomSinCurve( 10 );
  27164. * const geometry = new THREE.TubeGeometry( path, 20, 2, 8, false );
  27165. * const material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } );
  27166. * const mesh = new THREE.Mesh( geometry, material );
  27167. * scene.add( mesh );
  27168. * ```
  27169. *
  27170. * @augments BufferGeometry
  27171. */
  27172. class TubeGeometry extends BufferGeometry {
  27173. /**
  27174. * Constructs a new tube geometry.
  27175. *
  27176. * @param {Curve} [path=QuadraticBezierCurve3] - A 3D curve defining the path of the tube.
  27177. * @param {number} [tubularSegments=64] - The number of segments that make up the tube.
  27178. * @param {number} [radius=1] -The radius of the tube.
  27179. * @param {number} [radialSegments=8] - The number of segments that make up the cross-section.
  27180. * @param {boolean} [closed=false] - Whether the tube is closed or not.
  27181. */
  27182. 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 ) {
  27183. super();
  27184. this.type = 'TubeGeometry';
  27185. /**
  27186. * Holds the constructor parameters that have been
  27187. * used to generate the geometry. Any modification
  27188. * after instantiation does not change the geometry.
  27189. *
  27190. * @type {Object}
  27191. */
  27192. this.parameters = {
  27193. path: path,
  27194. tubularSegments: tubularSegments,
  27195. radius: radius,
  27196. radialSegments: radialSegments,
  27197. closed: closed
  27198. };
  27199. const frames = path.computeFrenetFrames( tubularSegments, closed );
  27200. // expose internals
  27201. this.tangents = frames.tangents;
  27202. this.normals = frames.normals;
  27203. this.binormals = frames.binormals;
  27204. // helper variables
  27205. const vertex = new Vector3();
  27206. const normal = new Vector3();
  27207. const uv = new Vector2();
  27208. let P = new Vector3();
  27209. // buffer
  27210. const vertices = [];
  27211. const normals = [];
  27212. const uvs = [];
  27213. const indices = [];
  27214. // create buffer data
  27215. generateBufferData();
  27216. // build geometry
  27217. this.setIndex( indices );
  27218. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  27219. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  27220. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  27221. // functions
  27222. function generateBufferData() {
  27223. for ( let i = 0; i < tubularSegments; i ++ ) {
  27224. generateSegment( i );
  27225. }
  27226. // if the geometry is not closed, generate the last row of vertices and normals
  27227. // at the regular position on the given path
  27228. //
  27229. // if the geometry is closed, duplicate the first row of vertices and normals (uvs will differ)
  27230. generateSegment( ( closed === false ) ? tubularSegments : 0 );
  27231. // uvs are generated in a separate function.
  27232. // this makes it easy compute correct values for closed geometries
  27233. generateUVs();
  27234. // finally create faces
  27235. generateIndices();
  27236. }
  27237. function generateSegment( i ) {
  27238. // we use getPointAt to sample evenly distributed points from the given path
  27239. P = path.getPointAt( i / tubularSegments, P );
  27240. // retrieve corresponding normal and binormal
  27241. const N = frames.normals[ i ];
  27242. const B = frames.binormals[ i ];
  27243. // generate normals and vertices for the current segment
  27244. for ( let j = 0; j <= radialSegments; j ++ ) {
  27245. const v = j / radialSegments * Math.PI * 2;
  27246. const sin = Math.sin( v );
  27247. const cos = - Math.cos( v );
  27248. // normal
  27249. normal.x = ( cos * N.x + sin * B.x );
  27250. normal.y = ( cos * N.y + sin * B.y );
  27251. normal.z = ( cos * N.z + sin * B.z );
  27252. normal.normalize();
  27253. normals.push( normal.x, normal.y, normal.z );
  27254. // vertex
  27255. vertex.x = P.x + radius * normal.x;
  27256. vertex.y = P.y + radius * normal.y;
  27257. vertex.z = P.z + radius * normal.z;
  27258. vertices.push( vertex.x, vertex.y, vertex.z );
  27259. }
  27260. }
  27261. function generateIndices() {
  27262. for ( let j = 1; j <= tubularSegments; j ++ ) {
  27263. for ( let i = 1; i <= radialSegments; i ++ ) {
  27264. const a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 );
  27265. const b = ( radialSegments + 1 ) * j + ( i - 1 );
  27266. const c = ( radialSegments + 1 ) * j + i;
  27267. const d = ( radialSegments + 1 ) * ( j - 1 ) + i;
  27268. // faces
  27269. indices.push( a, b, d );
  27270. indices.push( b, c, d );
  27271. }
  27272. }
  27273. }
  27274. function generateUVs() {
  27275. for ( let i = 0; i <= tubularSegments; i ++ ) {
  27276. for ( let j = 0; j <= radialSegments; j ++ ) {
  27277. uv.x = i / tubularSegments;
  27278. uv.y = j / radialSegments;
  27279. uvs.push( uv.x, uv.y );
  27280. }
  27281. }
  27282. }
  27283. }
  27284. copy( source ) {
  27285. super.copy( source );
  27286. this.parameters = Object.assign( {}, source.parameters );
  27287. return this;
  27288. }
  27289. toJSON() {
  27290. const data = super.toJSON();
  27291. data.path = this.parameters.path.toJSON();
  27292. return data;
  27293. }
  27294. /**
  27295. * Factory method for creating an instance of this class from the given
  27296. * JSON object.
  27297. *
  27298. * @param {Object} data - A JSON object representing the serialized geometry.
  27299. * @return {TubeGeometry} A new instance.
  27300. */
  27301. static fromJSON( data ) {
  27302. // This only works for built-in curves (e.g. CatmullRomCurve3).
  27303. // User defined curves or instances of CurvePath will not be deserialized.
  27304. return new TubeGeometry(
  27305. new Curves[ data.path.type ]().fromJSON( data.path ),
  27306. data.tubularSegments,
  27307. data.radius,
  27308. data.radialSegments,
  27309. data.closed
  27310. );
  27311. }
  27312. }
  27313. /**
  27314. * Can be used as a helper object to visualize a geometry as a wireframe.
  27315. *
  27316. * ```js
  27317. * const geometry = new THREE.SphereGeometry();
  27318. *
  27319. * const wireframe = new THREE.WireframeGeometry( geometry );
  27320. *
  27321. * const line = new THREE.LineSegments( wireframe );
  27322. * line.material.depthWrite = false;
  27323. * line.material.opacity = 0.25;
  27324. * line.material.transparent = true;
  27325. *
  27326. * scene.add( line );
  27327. * ```
  27328. *
  27329. * Note: It is not yet possible to serialize/deserialize instances of this class.
  27330. *
  27331. * @augments BufferGeometry
  27332. */
  27333. class WireframeGeometry extends BufferGeometry {
  27334. /**
  27335. * Constructs a new wireframe geometry.
  27336. *
  27337. * @param {?BufferGeometry} [geometry=null] - The geometry.
  27338. */
  27339. constructor( geometry = null ) {
  27340. super();
  27341. this.type = 'WireframeGeometry';
  27342. /**
  27343. * Holds the constructor parameters that have been
  27344. * used to generate the geometry. Any modification
  27345. * after instantiation does not change the geometry.
  27346. *
  27347. * @type {Object}
  27348. */
  27349. this.parameters = {
  27350. geometry: geometry
  27351. };
  27352. if ( geometry !== null ) {
  27353. // buffer
  27354. const vertices = [];
  27355. const edges = new Set();
  27356. // helper variables
  27357. const start = new Vector3();
  27358. const end = new Vector3();
  27359. if ( geometry.index !== null ) {
  27360. // indexed BufferGeometry
  27361. const position = geometry.attributes.position;
  27362. const indices = geometry.index;
  27363. let groups = geometry.groups;
  27364. if ( groups.length === 0 ) {
  27365. groups = [ { start: 0, count: indices.count, materialIndex: 0 } ];
  27366. }
  27367. // create a data structure that contains all edges without duplicates
  27368. for ( let o = 0, ol = groups.length; o < ol; ++ o ) {
  27369. const group = groups[ o ];
  27370. const groupStart = group.start;
  27371. const groupCount = group.count;
  27372. for ( let i = groupStart, l = ( groupStart + groupCount ); i < l; i += 3 ) {
  27373. for ( let j = 0; j < 3; j ++ ) {
  27374. const index1 = indices.getX( i + j );
  27375. const index2 = indices.getX( i + ( j + 1 ) % 3 );
  27376. start.fromBufferAttribute( position, index1 );
  27377. end.fromBufferAttribute( position, index2 );
  27378. if ( isUniqueEdge( start, end, edges ) === true ) {
  27379. vertices.push( start.x, start.y, start.z );
  27380. vertices.push( end.x, end.y, end.z );
  27381. }
  27382. }
  27383. }
  27384. }
  27385. } else {
  27386. // non-indexed BufferGeometry
  27387. const position = geometry.attributes.position;
  27388. for ( let i = 0, l = ( position.count / 3 ); i < l; i ++ ) {
  27389. for ( let j = 0; j < 3; j ++ ) {
  27390. // three edges per triangle, an edge is represented as (index1, index2)
  27391. // e.g. the first triangle has the following edges: (0,1),(1,2),(2,0)
  27392. const index1 = 3 * i + j;
  27393. const index2 = 3 * i + ( ( j + 1 ) % 3 );
  27394. start.fromBufferAttribute( position, index1 );
  27395. end.fromBufferAttribute( position, index2 );
  27396. if ( isUniqueEdge( start, end, edges ) === true ) {
  27397. vertices.push( start.x, start.y, start.z );
  27398. vertices.push( end.x, end.y, end.z );
  27399. }
  27400. }
  27401. }
  27402. }
  27403. // build geometry
  27404. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  27405. }
  27406. }
  27407. copy( source ) {
  27408. super.copy( source );
  27409. this.parameters = Object.assign( {}, source.parameters );
  27410. return this;
  27411. }
  27412. }
  27413. function isUniqueEdge( start, end, edges ) {
  27414. const hash1 = `${start.x},${start.y},${start.z}-${end.x},${end.y},${end.z}`;
  27415. const hash2 = `${end.x},${end.y},${end.z}-${start.x},${start.y},${start.z}`; // coincident edge
  27416. if ( edges.has( hash1 ) === true || edges.has( hash2 ) === true ) {
  27417. return false;
  27418. } else {
  27419. edges.add( hash1 );
  27420. edges.add( hash2 );
  27421. return true;
  27422. }
  27423. }
  27424. var Geometries = /*#__PURE__*/Object.freeze({
  27425. __proto__: null,
  27426. BoxGeometry: BoxGeometry,
  27427. CapsuleGeometry: CapsuleGeometry,
  27428. CircleGeometry: CircleGeometry,
  27429. ConeGeometry: ConeGeometry,
  27430. CylinderGeometry: CylinderGeometry,
  27431. DodecahedronGeometry: DodecahedronGeometry,
  27432. EdgesGeometry: EdgesGeometry,
  27433. ExtrudeGeometry: ExtrudeGeometry,
  27434. IcosahedronGeometry: IcosahedronGeometry,
  27435. LatheGeometry: LatheGeometry,
  27436. OctahedronGeometry: OctahedronGeometry,
  27437. PlaneGeometry: PlaneGeometry,
  27438. PolyhedronGeometry: PolyhedronGeometry,
  27439. RingGeometry: RingGeometry,
  27440. ShapeGeometry: ShapeGeometry,
  27441. SphereGeometry: SphereGeometry,
  27442. TetrahedronGeometry: TetrahedronGeometry,
  27443. TorusGeometry: TorusGeometry,
  27444. TorusKnotGeometry: TorusKnotGeometry,
  27445. TubeGeometry: TubeGeometry,
  27446. WireframeGeometry: WireframeGeometry
  27447. });
  27448. /**
  27449. * This material can receive shadows, but otherwise is completely transparent.
  27450. *
  27451. * ```js
  27452. * const geometry = new THREE.PlaneGeometry( 2000, 2000 );
  27453. * geometry.rotateX( - Math.PI / 2 );
  27454. *
  27455. * const material = new THREE.ShadowMaterial();
  27456. * material.opacity = 0.2;
  27457. *
  27458. * const plane = new THREE.Mesh( geometry, material );
  27459. * plane.position.y = -200;
  27460. * plane.receiveShadow = true;
  27461. * scene.add( plane );
  27462. * ```
  27463. *
  27464. * @augments Material
  27465. */
  27466. class ShadowMaterial extends Material {
  27467. /**
  27468. * Constructs a new shadow material.
  27469. *
  27470. * @param {Object} [parameters] - An object with one or more properties
  27471. * defining the material's appearance. Any property of the material
  27472. * (including any property from inherited materials) can be passed
  27473. * in here. Color values can be passed any type of value accepted
  27474. * by {@link Color#set}.
  27475. */
  27476. constructor( parameters ) {
  27477. super();
  27478. /**
  27479. * This flag can be used for type testing.
  27480. *
  27481. * @type {boolean}
  27482. * @readonly
  27483. * @default true
  27484. */
  27485. this.isShadowMaterial = true;
  27486. this.type = 'ShadowMaterial';
  27487. /**
  27488. * Color of the material.
  27489. *
  27490. * @type {Color}
  27491. * @default (0,0,0)
  27492. */
  27493. this.color = new Color( 0x000000 );
  27494. /**
  27495. * Overwritten since shadow materials are transparent
  27496. * by default.
  27497. *
  27498. * @type {boolean}
  27499. * @default true
  27500. */
  27501. this.transparent = true;
  27502. /**
  27503. * Whether the material is affected by fog or not.
  27504. *
  27505. * @type {boolean}
  27506. * @default true
  27507. */
  27508. this.fog = true;
  27509. this.setValues( parameters );
  27510. }
  27511. copy( source ) {
  27512. super.copy( source );
  27513. this.color.copy( source.color );
  27514. this.fog = source.fog;
  27515. return this;
  27516. }
  27517. }
  27518. /**
  27519. * This class works just like {@link ShaderMaterial}, except that definitions
  27520. * of built-in uniforms and attributes are not automatically prepended to the
  27521. * GLSL shader code.
  27522. *
  27523. * `RawShaderMaterial` can only be used with {@link WebGLRenderer}.
  27524. *
  27525. * @augments ShaderMaterial
  27526. */
  27527. class RawShaderMaterial extends ShaderMaterial {
  27528. /**
  27529. * Constructs a new raw shader material.
  27530. *
  27531. * @param {Object} [parameters] - An object with one or more properties
  27532. * defining the material's appearance. Any property of the material
  27533. * (including any property from inherited materials) can be passed
  27534. * in here. Color values can be passed any type of value accepted
  27535. * by {@link Color#set}.
  27536. */
  27537. constructor( parameters ) {
  27538. super( parameters );
  27539. /**
  27540. * This flag can be used for type testing.
  27541. *
  27542. * @type {boolean}
  27543. * @readonly
  27544. * @default true
  27545. */
  27546. this.isRawShaderMaterial = true;
  27547. this.type = 'RawShaderMaterial';
  27548. }
  27549. }
  27550. /**
  27551. * A standard physically based material, using Metallic-Roughness workflow.
  27552. *
  27553. * Physically based rendering (PBR) has recently become the standard in many
  27554. * 3D applications, such as [Unity]{@link https://blogs.unity3d.com/2014/10/29/physically-based-shading-in-unity-5-a-primer/},
  27555. * [Unreal]{@link https://docs.unrealengine.com/latest/INT/Engine/Rendering/Materials/PhysicallyBased/} and
  27556. * [3D Studio Max]{@link http://area.autodesk.com/blogs/the-3ds-max-blog/what039s-new-for-rendering-in-3ds-max-2017}.
  27557. *
  27558. * This approach differs from older approaches in that instead of using
  27559. * approximations for the way in which light interacts with a surface, a
  27560. * physically correct model is used. The idea is that, instead of tweaking
  27561. * materials to look good under specific lighting, a material can be created
  27562. * that will react 'correctly' under all lighting scenarios.
  27563. *
  27564. * In practice this gives a more accurate and realistic looking result than
  27565. * the {@link MeshLambertMaterial} or {@link MeshPhongMaterial}, at the cost of
  27566. * being somewhat more computationally expensive. `MeshStandardMaterial` uses per-fragment
  27567. * shading.
  27568. *
  27569. * Note that for best results you should always specify an environment map when using this material.
  27570. *
  27571. * For a non-technical introduction to the concept of PBR and how to set up a
  27572. * PBR material, check out these articles by the people at [marmoset]{@link https://www.marmoset.co}:
  27573. *
  27574. * - [Basic Theory of Physically Based Rendering]{@link https://www.marmoset.co/posts/basic-theory-of-physically-based-rendering/}
  27575. * - [Physically Based Rendering and You Can Too]{@link https://www.marmoset.co/posts/physically-based-rendering-and-you-can-too/}
  27576. *
  27577. * Technical details of the approach used in three.js (and most other PBR systems) can be found is this
  27578. * [paper from Disney]{@link https://media.disneyanimation.com/uploads/production/publication_asset/48/asset/s2012_pbs_disney_brdf_notes_v3.pdf}
  27579. * (pdf), by Brent Burley.
  27580. *
  27581. * @augments Material
  27582. */
  27583. class MeshStandardMaterial extends Material {
  27584. /**
  27585. * Constructs a new mesh standard material.
  27586. *
  27587. * @param {Object} [parameters] - An object with one or more properties
  27588. * defining the material's appearance. Any property of the material
  27589. * (including any property from inherited materials) can be passed
  27590. * in here. Color values can be passed any type of value accepted
  27591. * by {@link Color#set}.
  27592. */
  27593. constructor( parameters ) {
  27594. super();
  27595. /**
  27596. * This flag can be used for type testing.
  27597. *
  27598. * @type {boolean}
  27599. * @readonly
  27600. * @default true
  27601. */
  27602. this.isMeshStandardMaterial = true;
  27603. this.type = 'MeshStandardMaterial';
  27604. this.defines = { 'STANDARD': '' };
  27605. /**
  27606. * Color of the material.
  27607. *
  27608. * @type {Color}
  27609. * @default (1,1,1)
  27610. */
  27611. this.color = new Color( 0xffffff ); // diffuse
  27612. /**
  27613. * How rough the material appears. `0.0` means a smooth mirror reflection, `1.0`
  27614. * means fully diffuse. If `roughnessMap` is also provided,
  27615. * both values are multiplied.
  27616. *
  27617. * @type {number}
  27618. * @default 1
  27619. */
  27620. this.roughness = 1.0;
  27621. /**
  27622. * How much the material is like a metal. Non-metallic materials such as wood
  27623. * or stone use `0.0`, metallic use `1.0`, with nothing (usually) in between.
  27624. * A value between `0.0` and `1.0` could be used for a rusty metal look.
  27625. * If `metalnessMap` is also provided, both values are multiplied.
  27626. *
  27627. * @type {number}
  27628. * @default 0
  27629. */
  27630. this.metalness = 0.0;
  27631. /**
  27632. * The color map. May optionally include an alpha channel, typically combined
  27633. * with {@link Material#transparent} or {@link Material#alphaTest}. The texture map
  27634. * color is modulated by the diffuse `color`.
  27635. *
  27636. * @type {?Texture}
  27637. * @default null
  27638. */
  27639. this.map = null;
  27640. /**
  27641. * The light map. Requires a second set of UVs.
  27642. *
  27643. * @type {?Texture}
  27644. * @default null
  27645. */
  27646. this.lightMap = null;
  27647. /**
  27648. * Intensity of the baked light.
  27649. *
  27650. * @type {number}
  27651. * @default 1
  27652. */
  27653. this.lightMapIntensity = 1.0;
  27654. /**
  27655. * The red channel of this texture is used as the ambient occlusion map.
  27656. * Requires a second set of UVs.
  27657. *
  27658. * @type {?Texture}
  27659. * @default null
  27660. */
  27661. this.aoMap = null;
  27662. /**
  27663. * Intensity of the ambient occlusion effect. Range is `[0,1]`, where `0`
  27664. * disables ambient occlusion. Where intensity is `1` and the AO map's
  27665. * red channel is also `1`, ambient light is fully occluded on a surface.
  27666. *
  27667. * @type {number}
  27668. * @default 1
  27669. */
  27670. this.aoMapIntensity = 1.0;
  27671. /**
  27672. * Emissive (light) color of the material, essentially a solid color
  27673. * unaffected by other lighting.
  27674. *
  27675. * @type {Color}
  27676. * @default (0,0,0)
  27677. */
  27678. this.emissive = new Color( 0x000000 );
  27679. /**
  27680. * Intensity of the emissive light. Modulates the emissive color.
  27681. *
  27682. * @type {number}
  27683. * @default 1
  27684. */
  27685. this.emissiveIntensity = 1.0;
  27686. /**
  27687. * Set emissive (glow) map. The emissive map color is modulated by the
  27688. * emissive color and the emissive intensity. If you have an emissive map,
  27689. * be sure to set the emissive color to something other than black.
  27690. *
  27691. * @type {?Texture}
  27692. * @default null
  27693. */
  27694. this.emissiveMap = null;
  27695. /**
  27696. * The texture to create a bump map. The black and white values map to the
  27697. * perceived depth in relation to the lights. Bump doesn't actually affect
  27698. * the geometry of the object, only the lighting. If a normal map is defined
  27699. * this will be ignored.
  27700. *
  27701. * @type {?Texture}
  27702. * @default null
  27703. */
  27704. this.bumpMap = null;
  27705. /**
  27706. * How much the bump map affects the material. Typical range is `[0,1]`.
  27707. *
  27708. * @type {number}
  27709. * @default 1
  27710. */
  27711. this.bumpScale = 1;
  27712. /**
  27713. * The texture to create a normal map. The RGB values affect the surface
  27714. * normal for each pixel fragment and change the way the color is lit. Normal
  27715. * maps do not change the actual shape of the surface, only the lighting. In
  27716. * case the material has a normal map authored using the left handed
  27717. * convention, the `y` component of `normalScale` should be negated to compensate
  27718. * for the different handedness.
  27719. *
  27720. * @type {?Texture}
  27721. * @default null
  27722. */
  27723. this.normalMap = null;
  27724. /**
  27725. * The type of normal map.
  27726. *
  27727. * @type {(TangentSpaceNormalMap|ObjectSpaceNormalMap)}
  27728. * @default TangentSpaceNormalMap
  27729. */
  27730. this.normalMapType = TangentSpaceNormalMap;
  27731. /**
  27732. * How much the normal map affects the material. Typical value range is `[0,1]`.
  27733. *
  27734. * @type {Vector2}
  27735. * @default (1,1)
  27736. */
  27737. this.normalScale = new Vector2( 1, 1 );
  27738. /**
  27739. * The displacement map affects the position of the mesh's vertices. Unlike
  27740. * other maps which only affect the light and shade of the material the
  27741. * displaced vertices can cast shadows, block other objects, and otherwise
  27742. * act as real geometry. The displacement texture is an image where the value
  27743. * of each pixel (white being the highest) is mapped against, and
  27744. * repositions, the vertices of the mesh.
  27745. *
  27746. * @type {?Texture}
  27747. * @default null
  27748. */
  27749. this.displacementMap = null;
  27750. /**
  27751. * How much the displacement map affects the mesh (where black is no
  27752. * displacement, and white is maximum displacement). Without a displacement
  27753. * map set, this value is not applied.
  27754. *
  27755. * @type {number}
  27756. * @default 0
  27757. */
  27758. this.displacementScale = 1;
  27759. /**
  27760. * The offset of the displacement map's values on the mesh's vertices.
  27761. * The bias is added to the scaled sample of the displacement map.
  27762. * Without a displacement map set, this value is not applied.
  27763. *
  27764. * @type {number}
  27765. * @default 0
  27766. */
  27767. this.displacementBias = 0;
  27768. /**
  27769. * The green channel of this texture is used to alter the roughness of the
  27770. * material.
  27771. *
  27772. * @type {?Texture}
  27773. * @default null
  27774. */
  27775. this.roughnessMap = null;
  27776. /**
  27777. * The blue channel of this texture is used to alter the metalness of the
  27778. * material.
  27779. *
  27780. * @type {?Texture}
  27781. * @default null
  27782. */
  27783. this.metalnessMap = null;
  27784. /**
  27785. * The alpha map is a grayscale texture that controls the opacity across the
  27786. * surface (black: fully transparent; white: fully opaque).
  27787. *
  27788. * Only the color of the texture is used, ignoring the alpha channel if one
  27789. * exists. For RGB and RGBA textures, the renderer will use the green channel
  27790. * when sampling this texture due to the extra bit of precision provided for
  27791. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  27792. * luminance/alpha textures will also still work as expected.
  27793. *
  27794. * @type {?Texture}
  27795. * @default null
  27796. */
  27797. this.alphaMap = null;
  27798. /**
  27799. * The environment map. To ensure a physically correct rendering, environment maps
  27800. * are internally pre-processed with {@link PMREMGenerator}.
  27801. *
  27802. * @type {?Texture}
  27803. * @default null
  27804. */
  27805. this.envMap = null;
  27806. /**
  27807. * The rotation of the environment map in radians.
  27808. *
  27809. * @type {Euler}
  27810. * @default (0,0,0)
  27811. */
  27812. this.envMapRotation = new Euler();
  27813. /**
  27814. * Scales the effect of the environment map by multiplying its color.
  27815. *
  27816. * @type {number}
  27817. * @default 1
  27818. */
  27819. this.envMapIntensity = 1.0;
  27820. /**
  27821. * Renders the geometry as a wireframe.
  27822. *
  27823. * @type {boolean}
  27824. * @default false
  27825. */
  27826. this.wireframe = false;
  27827. /**
  27828. * Controls the thickness of the wireframe.
  27829. *
  27830. * Can only be used with {@link SVGRenderer}.
  27831. *
  27832. * @type {number}
  27833. * @default 1
  27834. */
  27835. this.wireframeLinewidth = 1;
  27836. /**
  27837. * Defines appearance of wireframe ends.
  27838. *
  27839. * Can only be used with {@link SVGRenderer}.
  27840. *
  27841. * @type {('round'|'bevel'|'miter')}
  27842. * @default 'round'
  27843. */
  27844. this.wireframeLinecap = 'round';
  27845. /**
  27846. * Defines appearance of wireframe joints.
  27847. *
  27848. * Can only be used with {@link SVGRenderer}.
  27849. *
  27850. * @type {('round'|'bevel'|'miter')}
  27851. * @default 'round'
  27852. */
  27853. this.wireframeLinejoin = 'round';
  27854. /**
  27855. * Whether the material is rendered with flat shading or not.
  27856. *
  27857. * @type {boolean}
  27858. * @default false
  27859. */
  27860. this.flatShading = false;
  27861. /**
  27862. * Whether the material is affected by fog or not.
  27863. *
  27864. * @type {boolean}
  27865. * @default true
  27866. */
  27867. this.fog = true;
  27868. this.setValues( parameters );
  27869. }
  27870. copy( source ) {
  27871. super.copy( source );
  27872. this.defines = { 'STANDARD': '' };
  27873. this.color.copy( source.color );
  27874. this.roughness = source.roughness;
  27875. this.metalness = source.metalness;
  27876. this.map = source.map;
  27877. this.lightMap = source.lightMap;
  27878. this.lightMapIntensity = source.lightMapIntensity;
  27879. this.aoMap = source.aoMap;
  27880. this.aoMapIntensity = source.aoMapIntensity;
  27881. this.emissive.copy( source.emissive );
  27882. this.emissiveMap = source.emissiveMap;
  27883. this.emissiveIntensity = source.emissiveIntensity;
  27884. this.bumpMap = source.bumpMap;
  27885. this.bumpScale = source.bumpScale;
  27886. this.normalMap = source.normalMap;
  27887. this.normalMapType = source.normalMapType;
  27888. this.normalScale.copy( source.normalScale );
  27889. this.displacementMap = source.displacementMap;
  27890. this.displacementScale = source.displacementScale;
  27891. this.displacementBias = source.displacementBias;
  27892. this.roughnessMap = source.roughnessMap;
  27893. this.metalnessMap = source.metalnessMap;
  27894. this.alphaMap = source.alphaMap;
  27895. this.envMap = source.envMap;
  27896. this.envMapRotation.copy( source.envMapRotation );
  27897. this.envMapIntensity = source.envMapIntensity;
  27898. this.wireframe = source.wireframe;
  27899. this.wireframeLinewidth = source.wireframeLinewidth;
  27900. this.wireframeLinecap = source.wireframeLinecap;
  27901. this.wireframeLinejoin = source.wireframeLinejoin;
  27902. this.flatShading = source.flatShading;
  27903. this.fog = source.fog;
  27904. return this;
  27905. }
  27906. }
  27907. /**
  27908. * An extension of the {@link MeshStandardMaterial}, providing more advanced
  27909. * physically-based rendering properties:
  27910. *
  27911. * - Anisotropy: Ability to represent the anisotropic property of materials
  27912. * as observable with brushed metals.
  27913. * - Clearcoat: Some materials — like car paints, carbon fiber, and wet surfaces — require
  27914. * a clear, reflective layer on top of another layer that may be irregular or rough.
  27915. * Clearcoat approximates this effect, without the need for a separate transparent surface.
  27916. * - Iridescence: Allows to render the effect where hue varies depending on the viewing
  27917. * angle and illumination angle. This can be seen on soap bubbles, oil films, or on the
  27918. * wings of many insects.
  27919. * - Physically-based transparency: One limitation of {@link Material#opacity} is that highly
  27920. * transparent materials are less reflective. Physically-based transmission provides a more
  27921. * realistic option for thin, transparent surfaces like glass.
  27922. * - Advanced reflectivity: More flexible reflectivity for non-metallic materials.
  27923. * - Sheen: Can be used for representing cloth and fabric materials.
  27924. *
  27925. * As a result of these complex shading features, `MeshPhysicalMaterial` has a
  27926. * higher performance cost, per pixel, than other three.js materials. Most
  27927. * effects are disabled by default, and add cost as they are enabled. For
  27928. * best results, always specify an environment map when using this material.
  27929. *
  27930. * @augments MeshStandardMaterial
  27931. */
  27932. class MeshPhysicalMaterial extends MeshStandardMaterial {
  27933. /**
  27934. * Constructs a new mesh physical material.
  27935. *
  27936. * @param {Object} [parameters] - An object with one or more properties
  27937. * defining the material's appearance. Any property of the material
  27938. * (including any property from inherited materials) can be passed
  27939. * in here. Color values can be passed any type of value accepted
  27940. * by {@link Color#set}.
  27941. */
  27942. constructor( parameters ) {
  27943. super();
  27944. /**
  27945. * This flag can be used for type testing.
  27946. *
  27947. * @type {boolean}
  27948. * @readonly
  27949. * @default true
  27950. */
  27951. this.isMeshPhysicalMaterial = true;
  27952. this.defines = {
  27953. 'STANDARD': '',
  27954. 'PHYSICAL': ''
  27955. };
  27956. this.type = 'MeshPhysicalMaterial';
  27957. /**
  27958. * The rotation of the anisotropy in tangent, bitangent space, measured in radians
  27959. * counter-clockwise from the tangent. When `anisotropyMap` is present, this
  27960. * property provides additional rotation to the vectors in the texture.
  27961. *
  27962. * @type {number}
  27963. * @default 1
  27964. */
  27965. this.anisotropyRotation = 0;
  27966. /**
  27967. * Red and green channels represent the anisotropy direction in `[-1, 1]` tangent,
  27968. * bitangent space, to be rotated by `anisotropyRotation`. The blue channel
  27969. * contains strength as `[0, 1]` to be multiplied by `anisotropy`.
  27970. *
  27971. * @type {?Texture}
  27972. * @default null
  27973. */
  27974. this.anisotropyMap = null;
  27975. /**
  27976. * The red channel of this texture is multiplied against `clearcoat`,
  27977. * for per-pixel control over a coating's intensity.
  27978. *
  27979. * @type {?Texture}
  27980. * @default null
  27981. */
  27982. this.clearcoatMap = null;
  27983. /**
  27984. * Roughness of the clear coat layer, from `0.0` to `1.0`.
  27985. *
  27986. * @type {number}
  27987. * @default 0
  27988. */
  27989. this.clearcoatRoughness = 0.0;
  27990. /**
  27991. * The green channel of this texture is multiplied against
  27992. * `clearcoatRoughness`, for per-pixel control over a coating's roughness.
  27993. *
  27994. * @type {?Texture}
  27995. * @default null
  27996. */
  27997. this.clearcoatRoughnessMap = null;
  27998. /**
  27999. * How much `clearcoatNormalMap` affects the clear coat layer, from
  28000. * `(0,0)` to `(1,1)`.
  28001. *
  28002. * @type {Vector2}
  28003. * @default (1,1)
  28004. */
  28005. this.clearcoatNormalScale = new Vector2( 1, 1 );
  28006. /**
  28007. * Can be used to enable independent normals for the clear coat layer.
  28008. *
  28009. * @type {?Texture}
  28010. * @default null
  28011. */
  28012. this.clearcoatNormalMap = null;
  28013. /**
  28014. * Index-of-refraction for non-metallic materials, from `1.0` to `2.333`.
  28015. *
  28016. * @type {number}
  28017. * @default 1.5
  28018. */
  28019. this.ior = 1.5;
  28020. /**
  28021. * Degree of reflectivity, from `0.0` to `1.0`. Default is `0.5`, which
  28022. * corresponds to an index-of-refraction of `1.5`.
  28023. *
  28024. * This models the reflectivity of non-metallic materials. It has no effect
  28025. * when `metalness` is `1.0`
  28026. *
  28027. * @name MeshPhysicalMaterial#reflectivity
  28028. * @type {number}
  28029. * @default 0.5
  28030. */
  28031. Object.defineProperty( this, 'reflectivity', {
  28032. get: function () {
  28033. return ( clamp( 2.5 * ( this.ior - 1 ) / ( this.ior + 1 ), 0, 1 ) );
  28034. },
  28035. set: function ( reflectivity ) {
  28036. this.ior = ( 1 + 0.4 * reflectivity ) / ( 1 - 0.4 * reflectivity );
  28037. }
  28038. } );
  28039. /**
  28040. * The red channel of this texture is multiplied against `iridescence`, for per-pixel
  28041. * control over iridescence.
  28042. *
  28043. * @type {?Texture}
  28044. * @default null
  28045. */
  28046. this.iridescenceMap = null;
  28047. /**
  28048. * Strength of the iridescence RGB color shift effect, represented by an index-of-refraction.
  28049. * Between `1.0` to `2.333`.
  28050. *
  28051. * @type {number}
  28052. * @default 1.3
  28053. */
  28054. this.iridescenceIOR = 1.3;
  28055. /**
  28056. *Array of exactly 2 elements, specifying minimum and maximum thickness of the iridescence layer.
  28057. Thickness of iridescence layer has an equivalent effect of the one `thickness` has on `ior`.
  28058. *
  28059. * @type {Array<number,number>}
  28060. * @default [100,400]
  28061. */
  28062. this.iridescenceThicknessRange = [ 100, 400 ];
  28063. /**
  28064. * A texture that defines the thickness of the iridescence layer, stored in the green channel.
  28065. * Minimum and maximum values of thickness are defined by `iridescenceThicknessRange` array:
  28066. * - `0.0` in the green channel will result in thickness equal to first element of the array.
  28067. * - `1.0` in the green channel will result in thickness equal to second element of the array.
  28068. * - Values in-between will linearly interpolate between the elements of the array.
  28069. *
  28070. * @type {?Texture}
  28071. * @default null
  28072. */
  28073. this.iridescenceThicknessMap = null;
  28074. /**
  28075. * The sheen tint.
  28076. *
  28077. * @type {Color}
  28078. * @default (0,0,0)
  28079. */
  28080. this.sheenColor = new Color( 0x000000 );
  28081. /**
  28082. * The RGB channels of this texture are multiplied against `sheenColor`, for per-pixel control
  28083. * over sheen tint.
  28084. *
  28085. * @type {?Texture}
  28086. * @default null
  28087. */
  28088. this.sheenColorMap = null;
  28089. /**
  28090. * Roughness of the sheen layer, from `0.0` to `1.0`.
  28091. *
  28092. * @type {number}
  28093. * @default 1
  28094. */
  28095. this.sheenRoughness = 1.0;
  28096. /**
  28097. * The alpha channel of this texture is multiplied against `sheenRoughness`, for per-pixel control
  28098. * over sheen roughness.
  28099. *
  28100. * @type {?Texture}
  28101. * @default null
  28102. */
  28103. this.sheenRoughnessMap = null;
  28104. /**
  28105. * The red channel of this texture is multiplied against `transmission`, for per-pixel control over
  28106. * optical transparency.
  28107. *
  28108. * @type {?Texture}
  28109. * @default null
  28110. */
  28111. this.transmissionMap = null;
  28112. /**
  28113. * The thickness of the volume beneath the surface. The value is given in the
  28114. * coordinate space of the mesh. If the value is `0` the material is
  28115. * thin-walled. Otherwise the material is a volume boundary.
  28116. *
  28117. * @type {number}
  28118. * @default 0
  28119. */
  28120. this.thickness = 0;
  28121. /**
  28122. * A texture that defines the thickness, stored in the green channel. This will
  28123. * be multiplied by `thickness`.
  28124. *
  28125. * @type {?Texture}
  28126. * @default null
  28127. */
  28128. this.thicknessMap = null;
  28129. /**
  28130. * Density of the medium given as the average distance that light travels in
  28131. * the medium before interacting with a particle. The value is given in world
  28132. * space units, and must be greater than zero.
  28133. *
  28134. * @type {number}
  28135. * @default Infinity
  28136. */
  28137. this.attenuationDistance = Infinity;
  28138. /**
  28139. * The color that white light turns into due to absorption when reaching the
  28140. * attenuation distance.
  28141. *
  28142. * @type {Color}
  28143. * @default (1,1,1)
  28144. */
  28145. this.attenuationColor = new Color( 1, 1, 1 );
  28146. /**
  28147. * A float that scales the amount of specular reflection for non-metals only.
  28148. * When set to zero, the model is effectively Lambertian. From `0.0` to `1.0`.
  28149. *
  28150. * @type {number}
  28151. * @default 1
  28152. */
  28153. this.specularIntensity = 1.0;
  28154. /**
  28155. * The alpha channel of this texture is multiplied against `specularIntensity`,
  28156. * for per-pixel control over specular intensity.
  28157. *
  28158. * @type {?Texture}
  28159. * @default null
  28160. */
  28161. this.specularIntensityMap = null;
  28162. /**
  28163. * Tints the specular reflection at normal incidence for non-metals only.
  28164. *
  28165. * @type {Color}
  28166. * @default (1,1,1)
  28167. */
  28168. this.specularColor = new Color( 1, 1, 1 );
  28169. /**
  28170. * The RGB channels of this texture are multiplied against `specularColor`,
  28171. * for per-pixel control over specular color.
  28172. *
  28173. * @type {?Texture}
  28174. * @default null
  28175. */
  28176. this.specularColorMap = null;
  28177. this._anisotropy = 0;
  28178. this._clearcoat = 0;
  28179. this._dispersion = 0;
  28180. this._iridescence = 0;
  28181. this._sheen = 0.0;
  28182. this._transmission = 0;
  28183. this.setValues( parameters );
  28184. }
  28185. /**
  28186. * The anisotropy strength.
  28187. *
  28188. * @type {number}
  28189. * @default 0
  28190. */
  28191. get anisotropy() {
  28192. return this._anisotropy;
  28193. }
  28194. set anisotropy( value ) {
  28195. if ( this._anisotropy > 0 !== value > 0 ) {
  28196. this.version ++;
  28197. }
  28198. this._anisotropy = value;
  28199. }
  28200. /**
  28201. * Represents the intensity of the clear coat layer, from `0.0` to `1.0`. Use
  28202. * clear coat related properties to enable multilayer materials that have a
  28203. * thin translucent layer over the base layer.
  28204. *
  28205. * @type {number}
  28206. * @default 0
  28207. */
  28208. get clearcoat() {
  28209. return this._clearcoat;
  28210. }
  28211. set clearcoat( value ) {
  28212. if ( this._clearcoat > 0 !== value > 0 ) {
  28213. this.version ++;
  28214. }
  28215. this._clearcoat = value;
  28216. }
  28217. /**
  28218. * The intensity of the iridescence layer, simulating RGB color shift based on the angle between
  28219. * the surface and the viewer, from `0.0` to `1.0`.
  28220. *
  28221. * @type {number}
  28222. * @default 0
  28223. */
  28224. get iridescence() {
  28225. return this._iridescence;
  28226. }
  28227. set iridescence( value ) {
  28228. if ( this._iridescence > 0 !== value > 0 ) {
  28229. this.version ++;
  28230. }
  28231. this._iridescence = value;
  28232. }
  28233. /**
  28234. * Defines the strength of the angular separation of colors (chromatic aberration) transmitting
  28235. * through a relatively clear volume. Any value zero or larger is valid, the typical range of
  28236. * realistic values is `[0, 1]`. This property can be only be used with transmissive objects.
  28237. *
  28238. * @type {number}
  28239. * @default 0
  28240. */
  28241. get dispersion() {
  28242. return this._dispersion;
  28243. }
  28244. set dispersion( value ) {
  28245. if ( this._dispersion > 0 !== value > 0 ) {
  28246. this.version ++;
  28247. }
  28248. this._dispersion = value;
  28249. }
  28250. /**
  28251. * The intensity of the sheen layer, from `0.0` to `1.0`.
  28252. *
  28253. * @type {number}
  28254. * @default 0
  28255. */
  28256. get sheen() {
  28257. return this._sheen;
  28258. }
  28259. set sheen( value ) {
  28260. if ( this._sheen > 0 !== value > 0 ) {
  28261. this.version ++;
  28262. }
  28263. this._sheen = value;
  28264. }
  28265. /**
  28266. * Degree of transmission (or optical transparency), from `0.0` to `1.0`.
  28267. *
  28268. * Thin, transparent or semitransparent, plastic or glass materials remain
  28269. * largely reflective even if they are fully transmissive. The transmission
  28270. * property can be used to model these materials.
  28271. *
  28272. * When transmission is non-zero, `opacity` should be set to `1`.
  28273. *
  28274. * @type {number}
  28275. * @default 0
  28276. */
  28277. get transmission() {
  28278. return this._transmission;
  28279. }
  28280. set transmission( value ) {
  28281. if ( this._transmission > 0 !== value > 0 ) {
  28282. this.version ++;
  28283. }
  28284. this._transmission = value;
  28285. }
  28286. copy( source ) {
  28287. super.copy( source );
  28288. this.defines = {
  28289. 'STANDARD': '',
  28290. 'PHYSICAL': ''
  28291. };
  28292. this.anisotropy = source.anisotropy;
  28293. this.anisotropyRotation = source.anisotropyRotation;
  28294. this.anisotropyMap = source.anisotropyMap;
  28295. this.clearcoat = source.clearcoat;
  28296. this.clearcoatMap = source.clearcoatMap;
  28297. this.clearcoatRoughness = source.clearcoatRoughness;
  28298. this.clearcoatRoughnessMap = source.clearcoatRoughnessMap;
  28299. this.clearcoatNormalMap = source.clearcoatNormalMap;
  28300. this.clearcoatNormalScale.copy( source.clearcoatNormalScale );
  28301. this.dispersion = source.dispersion;
  28302. this.ior = source.ior;
  28303. this.iridescence = source.iridescence;
  28304. this.iridescenceMap = source.iridescenceMap;
  28305. this.iridescenceIOR = source.iridescenceIOR;
  28306. this.iridescenceThicknessRange = [ ...source.iridescenceThicknessRange ];
  28307. this.iridescenceThicknessMap = source.iridescenceThicknessMap;
  28308. this.sheen = source.sheen;
  28309. this.sheenColor.copy( source.sheenColor );
  28310. this.sheenColorMap = source.sheenColorMap;
  28311. this.sheenRoughness = source.sheenRoughness;
  28312. this.sheenRoughnessMap = source.sheenRoughnessMap;
  28313. this.transmission = source.transmission;
  28314. this.transmissionMap = source.transmissionMap;
  28315. this.thickness = source.thickness;
  28316. this.thicknessMap = source.thicknessMap;
  28317. this.attenuationDistance = source.attenuationDistance;
  28318. this.attenuationColor.copy( source.attenuationColor );
  28319. this.specularIntensity = source.specularIntensity;
  28320. this.specularIntensityMap = source.specularIntensityMap;
  28321. this.specularColor.copy( source.specularColor );
  28322. this.specularColorMap = source.specularColorMap;
  28323. return this;
  28324. }
  28325. }
  28326. /**
  28327. * A material for shiny surfaces with specular highlights.
  28328. *
  28329. * The material uses a non-physically based [Blinn-Phong]{@link https://en.wikipedia.org/wiki/Blinn-Phong_shading_model}
  28330. * model for calculating reflectance. Unlike the Lambertian model used in the
  28331. * {@link MeshLambertMaterial} this can simulate shiny surfaces with specular
  28332. * highlights (such as varnished wood). `MeshPhongMaterial` uses per-fragment shading.
  28333. *
  28334. * Performance will generally be greater when using this material over the
  28335. * {@link MeshStandardMaterial} or {@link MeshPhysicalMaterial}, at the cost of
  28336. * some graphical accuracy.
  28337. *
  28338. * @augments Material
  28339. */
  28340. class MeshPhongMaterial extends Material {
  28341. /**
  28342. * Constructs a new mesh phong material.
  28343. *
  28344. * @param {Object} [parameters] - An object with one or more properties
  28345. * defining the material's appearance. Any property of the material
  28346. * (including any property from inherited materials) can be passed
  28347. * in here. Color values can be passed any type of value accepted
  28348. * by {@link Color#set}.
  28349. */
  28350. constructor( parameters ) {
  28351. super();
  28352. /**
  28353. * This flag can be used for type testing.
  28354. *
  28355. * @type {boolean}
  28356. * @readonly
  28357. * @default true
  28358. */
  28359. this.isMeshPhongMaterial = true;
  28360. this.type = 'MeshPhongMaterial';
  28361. /**
  28362. * Color of the material.
  28363. *
  28364. * @type {Color}
  28365. * @default (1,1,1)
  28366. */
  28367. this.color = new Color( 0xffffff ); // diffuse
  28368. /**
  28369. * Specular color of the material. The default color is set to `0x111111` (very dark grey)
  28370. *
  28371. * This defines how shiny the material is and the color of its shine.
  28372. *
  28373. * @type {Color}
  28374. */
  28375. this.specular = new Color( 0x111111 );
  28376. /**
  28377. * How shiny the specular highlight is; a higher value gives a sharper highlight.
  28378. *
  28379. * @type {number}
  28380. * @default 30
  28381. */
  28382. this.shininess = 30;
  28383. /**
  28384. * The color map. May optionally include an alpha channel, typically combined
  28385. * with {@link Material#transparent} or {@link Material#alphaTest}. The texture map
  28386. * color is modulated by the diffuse `color`.
  28387. *
  28388. * @type {?Texture}
  28389. * @default null
  28390. */
  28391. this.map = null;
  28392. /**
  28393. * The light map. Requires a second set of UVs.
  28394. *
  28395. * @type {?Texture}
  28396. * @default null
  28397. */
  28398. this.lightMap = null;
  28399. /**
  28400. * Intensity of the baked light.
  28401. *
  28402. * @type {number}
  28403. * @default 1
  28404. */
  28405. this.lightMapIntensity = 1.0;
  28406. /**
  28407. * The red channel of this texture is used as the ambient occlusion map.
  28408. * Requires a second set of UVs.
  28409. *
  28410. * @type {?Texture}
  28411. * @default null
  28412. */
  28413. this.aoMap = null;
  28414. /**
  28415. * Intensity of the ambient occlusion effect. Range is `[0,1]`, where `0`
  28416. * disables ambient occlusion. Where intensity is `1` and the AO map's
  28417. * red channel is also `1`, ambient light is fully occluded on a surface.
  28418. *
  28419. * @type {number}
  28420. * @default 1
  28421. */
  28422. this.aoMapIntensity = 1.0;
  28423. /**
  28424. * Emissive (light) color of the material, essentially a solid color
  28425. * unaffected by other lighting.
  28426. *
  28427. * @type {Color}
  28428. * @default (0,0,0)
  28429. */
  28430. this.emissive = new Color( 0x000000 );
  28431. /**
  28432. * Intensity of the emissive light. Modulates the emissive color.
  28433. *
  28434. * @type {number}
  28435. * @default 1
  28436. */
  28437. this.emissiveIntensity = 1.0;
  28438. /**
  28439. * Set emissive (glow) map. The emissive map color is modulated by the
  28440. * emissive color and the emissive intensity. If you have an emissive map,
  28441. * be sure to set the emissive color to something other than black.
  28442. *
  28443. * @type {?Texture}
  28444. * @default null
  28445. */
  28446. this.emissiveMap = null;
  28447. /**
  28448. * The texture to create a bump map. The black and white values map to the
  28449. * perceived depth in relation to the lights. Bump doesn't actually affect
  28450. * the geometry of the object, only the lighting. If a normal map is defined
  28451. * this will be ignored.
  28452. *
  28453. * @type {?Texture}
  28454. * @default null
  28455. */
  28456. this.bumpMap = null;
  28457. /**
  28458. * How much the bump map affects the material. Typical range is `[0,1]`.
  28459. *
  28460. * @type {number}
  28461. * @default 1
  28462. */
  28463. this.bumpScale = 1;
  28464. /**
  28465. * The texture to create a normal map. The RGB values affect the surface
  28466. * normal for each pixel fragment and change the way the color is lit. Normal
  28467. * maps do not change the actual shape of the surface, only the lighting. In
  28468. * case the material has a normal map authored using the left handed
  28469. * convention, the `y` component of `normalScale` should be negated to compensate
  28470. * for the different handedness.
  28471. *
  28472. * @type {?Texture}
  28473. * @default null
  28474. */
  28475. this.normalMap = null;
  28476. /**
  28477. * The type of normal map.
  28478. *
  28479. * @type {(TangentSpaceNormalMap|ObjectSpaceNormalMap)}
  28480. * @default TangentSpaceNormalMap
  28481. */
  28482. this.normalMapType = TangentSpaceNormalMap;
  28483. /**
  28484. * How much the normal map affects the material. Typical value range is `[0,1]`.
  28485. *
  28486. * @type {Vector2}
  28487. * @default (1,1)
  28488. */
  28489. this.normalScale = new Vector2( 1, 1 );
  28490. /**
  28491. * The displacement map affects the position of the mesh's vertices. Unlike
  28492. * other maps which only affect the light and shade of the material the
  28493. * displaced vertices can cast shadows, block other objects, and otherwise
  28494. * act as real geometry. The displacement texture is an image where the value
  28495. * of each pixel (white being the highest) is mapped against, and
  28496. * repositions, the vertices of the mesh.
  28497. *
  28498. * @type {?Texture}
  28499. * @default null
  28500. */
  28501. this.displacementMap = null;
  28502. /**
  28503. * How much the displacement map affects the mesh (where black is no
  28504. * displacement, and white is maximum displacement). Without a displacement
  28505. * map set, this value is not applied.
  28506. *
  28507. * @type {number}
  28508. * @default 0
  28509. */
  28510. this.displacementScale = 1;
  28511. /**
  28512. * The offset of the displacement map's values on the mesh's vertices.
  28513. * The bias is added to the scaled sample of the displacement map.
  28514. * Without a displacement map set, this value is not applied.
  28515. *
  28516. * @type {number}
  28517. * @default 0
  28518. */
  28519. this.displacementBias = 0;
  28520. /**
  28521. * The specular map value affects both how much the specular surface
  28522. * highlight contributes and how much of the environment map affects the
  28523. * surface.
  28524. *
  28525. * @type {?Texture}
  28526. * @default null
  28527. */
  28528. this.specularMap = null;
  28529. /**
  28530. * The alpha map is a grayscale texture that controls the opacity across the
  28531. * surface (black: fully transparent; white: fully opaque).
  28532. *
  28533. * Only the color of the texture is used, ignoring the alpha channel if one
  28534. * exists. For RGB and RGBA textures, the renderer will use the green channel
  28535. * when sampling this texture due to the extra bit of precision provided for
  28536. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  28537. * luminance/alpha textures will also still work as expected.
  28538. *
  28539. * @type {?Texture}
  28540. * @default null
  28541. */
  28542. this.alphaMap = null;
  28543. /**
  28544. * The environment map.
  28545. *
  28546. * @type {?Texture}
  28547. * @default null
  28548. */
  28549. this.envMap = null;
  28550. /**
  28551. * The rotation of the environment map in radians.
  28552. *
  28553. * @type {Euler}
  28554. * @default (0,0,0)
  28555. */
  28556. this.envMapRotation = new Euler();
  28557. /**
  28558. * How to combine the result of the surface's color with the environment map, if any.
  28559. *
  28560. * When set to `MixOperation`, the {@link MeshBasicMaterial#reflectivity} is used to
  28561. * blend between the two colors.
  28562. *
  28563. * @type {(MultiplyOperation|MixOperation|AddOperation)}
  28564. * @default MultiplyOperation
  28565. */
  28566. this.combine = MultiplyOperation;
  28567. /**
  28568. * How much the environment map affects the surface.
  28569. * The valid range is between `0` (no reflections) and `1` (full reflections).
  28570. *
  28571. * @type {number}
  28572. * @default 1
  28573. */
  28574. this.reflectivity = 1;
  28575. /**
  28576. * The index of refraction (IOR) of air (approximately 1) divided by the
  28577. * index of refraction of the material. It is used with environment mapping
  28578. * modes {@link CubeRefractionMapping} and {@link EquirectangularRefractionMapping}.
  28579. * The refraction ratio should not exceed `1`.
  28580. *
  28581. * @type {number}
  28582. * @default 0.98
  28583. */
  28584. this.refractionRatio = 0.98;
  28585. /**
  28586. * Renders the geometry as a wireframe.
  28587. *
  28588. * @type {boolean}
  28589. * @default false
  28590. */
  28591. this.wireframe = false;
  28592. /**
  28593. * Controls the thickness of the wireframe.
  28594. *
  28595. * Can only be used with {@link SVGRenderer}.
  28596. *
  28597. * @type {number}
  28598. * @default 1
  28599. */
  28600. this.wireframeLinewidth = 1;
  28601. /**
  28602. * Defines appearance of wireframe ends.
  28603. *
  28604. * Can only be used with {@link SVGRenderer}.
  28605. *
  28606. * @type {('round'|'bevel'|'miter')}
  28607. * @default 'round'
  28608. */
  28609. this.wireframeLinecap = 'round';
  28610. /**
  28611. * Defines appearance of wireframe joints.
  28612. *
  28613. * Can only be used with {@link SVGRenderer}.
  28614. *
  28615. * @type {('round'|'bevel'|'miter')}
  28616. * @default 'round'
  28617. */
  28618. this.wireframeLinejoin = 'round';
  28619. /**
  28620. * Whether the material is rendered with flat shading or not.
  28621. *
  28622. * @type {boolean}
  28623. * @default false
  28624. */
  28625. this.flatShading = false;
  28626. /**
  28627. * Whether the material is affected by fog or not.
  28628. *
  28629. * @type {boolean}
  28630. * @default true
  28631. */
  28632. this.fog = true;
  28633. this.setValues( parameters );
  28634. }
  28635. copy( source ) {
  28636. super.copy( source );
  28637. this.color.copy( source.color );
  28638. this.specular.copy( source.specular );
  28639. this.shininess = source.shininess;
  28640. this.map = source.map;
  28641. this.lightMap = source.lightMap;
  28642. this.lightMapIntensity = source.lightMapIntensity;
  28643. this.aoMap = source.aoMap;
  28644. this.aoMapIntensity = source.aoMapIntensity;
  28645. this.emissive.copy( source.emissive );
  28646. this.emissiveMap = source.emissiveMap;
  28647. this.emissiveIntensity = source.emissiveIntensity;
  28648. this.bumpMap = source.bumpMap;
  28649. this.bumpScale = source.bumpScale;
  28650. this.normalMap = source.normalMap;
  28651. this.normalMapType = source.normalMapType;
  28652. this.normalScale.copy( source.normalScale );
  28653. this.displacementMap = source.displacementMap;
  28654. this.displacementScale = source.displacementScale;
  28655. this.displacementBias = source.displacementBias;
  28656. this.specularMap = source.specularMap;
  28657. this.alphaMap = source.alphaMap;
  28658. this.envMap = source.envMap;
  28659. this.envMapRotation.copy( source.envMapRotation );
  28660. this.combine = source.combine;
  28661. this.reflectivity = source.reflectivity;
  28662. this.refractionRatio = source.refractionRatio;
  28663. this.wireframe = source.wireframe;
  28664. this.wireframeLinewidth = source.wireframeLinewidth;
  28665. this.wireframeLinecap = source.wireframeLinecap;
  28666. this.wireframeLinejoin = source.wireframeLinejoin;
  28667. this.flatShading = source.flatShading;
  28668. this.fog = source.fog;
  28669. return this;
  28670. }
  28671. }
  28672. /**
  28673. * A material implementing toon shading.
  28674. *
  28675. * @augments Material
  28676. */
  28677. class MeshToonMaterial extends Material {
  28678. /**
  28679. * Constructs a new mesh toon material.
  28680. *
  28681. * @param {Object} [parameters] - An object with one or more properties
  28682. * defining the material's appearance. Any property of the material
  28683. * (including any property from inherited materials) can be passed
  28684. * in here. Color values can be passed any type of value accepted
  28685. * by {@link Color#set}.
  28686. */
  28687. constructor( parameters ) {
  28688. super();
  28689. /**
  28690. * This flag can be used for type testing.
  28691. *
  28692. * @type {boolean}
  28693. * @readonly
  28694. * @default true
  28695. */
  28696. this.isMeshToonMaterial = true;
  28697. this.defines = { 'TOON': '' };
  28698. this.type = 'MeshToonMaterial';
  28699. /**
  28700. * Color of the material.
  28701. *
  28702. * @type {Color}
  28703. * @default (1,1,1)
  28704. */
  28705. this.color = new Color( 0xffffff );
  28706. /**
  28707. * The color map. May optionally include an alpha channel, typically combined
  28708. * with {@link Material#transparent} or {@link Material#alphaTest}. The texture map
  28709. * color is modulated by the diffuse `color`.
  28710. *
  28711. * @type {?Texture}
  28712. * @default null
  28713. */
  28714. this.map = null;
  28715. /**
  28716. * Gradient map for toon shading. It's required to set
  28717. * {@link Texture#minFilter} and {@link Texture#magFilter} to {@linkNearestFilter}
  28718. * when using this type of texture.
  28719. *
  28720. * @type {?Texture}
  28721. * @default null
  28722. */
  28723. this.gradientMap = null;
  28724. /**
  28725. * The light map. Requires a second set of UVs.
  28726. *
  28727. * @type {?Texture}
  28728. * @default null
  28729. */
  28730. this.lightMap = null;
  28731. /**
  28732. * Intensity of the baked light.
  28733. *
  28734. * @type {number}
  28735. * @default 1
  28736. */
  28737. this.lightMapIntensity = 1.0;
  28738. /**
  28739. * The red channel of this texture is used as the ambient occlusion map.
  28740. * Requires a second set of UVs.
  28741. *
  28742. * @type {?Texture}
  28743. * @default null
  28744. */
  28745. this.aoMap = null;
  28746. /**
  28747. * Intensity of the ambient occlusion effect. Range is `[0,1]`, where `0`
  28748. * disables ambient occlusion. Where intensity is `1` and the AO map's
  28749. * red channel is also `1`, ambient light is fully occluded on a surface.
  28750. *
  28751. * @type {number}
  28752. * @default 1
  28753. */
  28754. this.aoMapIntensity = 1.0;
  28755. /**
  28756. * Emissive (light) color of the material, essentially a solid color
  28757. * unaffected by other lighting.
  28758. *
  28759. * @type {Color}
  28760. * @default (0,0,0)
  28761. */
  28762. this.emissive = new Color( 0x000000 );
  28763. /**
  28764. * Intensity of the emissive light. Modulates the emissive color.
  28765. *
  28766. * @type {number}
  28767. * @default 1
  28768. */
  28769. this.emissiveIntensity = 1.0;
  28770. /**
  28771. * Set emissive (glow) map. The emissive map color is modulated by the
  28772. * emissive color and the emissive intensity. If you have an emissive map,
  28773. * be sure to set the emissive color to something other than black.
  28774. *
  28775. * @type {?Texture}
  28776. * @default null
  28777. */
  28778. this.emissiveMap = null;
  28779. /**
  28780. * The texture to create a bump map. The black and white values map to the
  28781. * perceived depth in relation to the lights. Bump doesn't actually affect
  28782. * the geometry of the object, only the lighting. If a normal map is defined
  28783. * this will be ignored.
  28784. *
  28785. * @type {?Texture}
  28786. * @default null
  28787. */
  28788. this.bumpMap = null;
  28789. /**
  28790. * How much the bump map affects the material. Typical range is `[0,1]`.
  28791. *
  28792. * @type {number}
  28793. * @default 1
  28794. */
  28795. this.bumpScale = 1;
  28796. /**
  28797. * The texture to create a normal map. The RGB values affect the surface
  28798. * normal for each pixel fragment and change the way the color is lit. Normal
  28799. * maps do not change the actual shape of the surface, only the lighting. In
  28800. * case the material has a normal map authored using the left handed
  28801. * convention, the `y` component of `normalScale` should be negated to compensate
  28802. * for the different handedness.
  28803. *
  28804. * @type {?Texture}
  28805. * @default null
  28806. */
  28807. this.normalMap = null;
  28808. /**
  28809. * The type of normal map.
  28810. *
  28811. * @type {(TangentSpaceNormalMap|ObjectSpaceNormalMap)}
  28812. * @default TangentSpaceNormalMap
  28813. */
  28814. this.normalMapType = TangentSpaceNormalMap;
  28815. /**
  28816. * How much the normal map affects the material. Typical value range is `[0,1]`.
  28817. *
  28818. * @type {Vector2}
  28819. * @default (1,1)
  28820. */
  28821. this.normalScale = new Vector2( 1, 1 );
  28822. /**
  28823. * The displacement map affects the position of the mesh's vertices. Unlike
  28824. * other maps which only affect the light and shade of the material the
  28825. * displaced vertices can cast shadows, block other objects, and otherwise
  28826. * act as real geometry. The displacement texture is an image where the value
  28827. * of each pixel (white being the highest) is mapped against, and
  28828. * repositions, the vertices of the mesh.
  28829. *
  28830. * @type {?Texture}
  28831. * @default null
  28832. */
  28833. this.displacementMap = null;
  28834. /**
  28835. * How much the displacement map affects the mesh (where black is no
  28836. * displacement, and white is maximum displacement). Without a displacement
  28837. * map set, this value is not applied.
  28838. *
  28839. * @type {number}
  28840. * @default 0
  28841. */
  28842. this.displacementScale = 1;
  28843. /**
  28844. * The offset of the displacement map's values on the mesh's vertices.
  28845. * The bias is added to the scaled sample of the displacement map.
  28846. * Without a displacement map set, this value is not applied.
  28847. *
  28848. * @type {number}
  28849. * @default 0
  28850. */
  28851. this.displacementBias = 0;
  28852. /**
  28853. * The alpha map is a grayscale texture that controls the opacity across the
  28854. * surface (black: fully transparent; white: fully opaque).
  28855. *
  28856. * Only the color of the texture is used, ignoring the alpha channel if one
  28857. * exists. For RGB and RGBA textures, the renderer will use the green channel
  28858. * when sampling this texture due to the extra bit of precision provided for
  28859. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  28860. * luminance/alpha textures will also still work as expected.
  28861. *
  28862. * @type {?Texture}
  28863. * @default null
  28864. */
  28865. this.alphaMap = null;
  28866. /**
  28867. * Renders the geometry as a wireframe.
  28868. *
  28869. * @type {boolean}
  28870. * @default false
  28871. */
  28872. this.wireframe = false;
  28873. /**
  28874. * Controls the thickness of the wireframe.
  28875. *
  28876. * Can only be used with {@link SVGRenderer}.
  28877. *
  28878. * @type {number}
  28879. * @default 1
  28880. */
  28881. this.wireframeLinewidth = 1;
  28882. /**
  28883. * Defines appearance of wireframe ends.
  28884. *
  28885. * Can only be used with {@link SVGRenderer}.
  28886. *
  28887. * @type {('round'|'bevel'|'miter')}
  28888. * @default 'round'
  28889. */
  28890. this.wireframeLinecap = 'round';
  28891. /**
  28892. * Defines appearance of wireframe joints.
  28893. *
  28894. * Can only be used with {@link SVGRenderer}.
  28895. *
  28896. * @type {('round'|'bevel'|'miter')}
  28897. * @default 'round'
  28898. */
  28899. this.wireframeLinejoin = 'round';
  28900. /**
  28901. * Whether the material is affected by fog or not.
  28902. *
  28903. * @type {boolean}
  28904. * @default true
  28905. */
  28906. this.fog = true;
  28907. this.setValues( parameters );
  28908. }
  28909. copy( source ) {
  28910. super.copy( source );
  28911. this.color.copy( source.color );
  28912. this.map = source.map;
  28913. this.gradientMap = source.gradientMap;
  28914. this.lightMap = source.lightMap;
  28915. this.lightMapIntensity = source.lightMapIntensity;
  28916. this.aoMap = source.aoMap;
  28917. this.aoMapIntensity = source.aoMapIntensity;
  28918. this.emissive.copy( source.emissive );
  28919. this.emissiveMap = source.emissiveMap;
  28920. this.emissiveIntensity = source.emissiveIntensity;
  28921. this.bumpMap = source.bumpMap;
  28922. this.bumpScale = source.bumpScale;
  28923. this.normalMap = source.normalMap;
  28924. this.normalMapType = source.normalMapType;
  28925. this.normalScale.copy( source.normalScale );
  28926. this.displacementMap = source.displacementMap;
  28927. this.displacementScale = source.displacementScale;
  28928. this.displacementBias = source.displacementBias;
  28929. this.alphaMap = source.alphaMap;
  28930. this.wireframe = source.wireframe;
  28931. this.wireframeLinewidth = source.wireframeLinewidth;
  28932. this.wireframeLinecap = source.wireframeLinecap;
  28933. this.wireframeLinejoin = source.wireframeLinejoin;
  28934. this.fog = source.fog;
  28935. return this;
  28936. }
  28937. }
  28938. /**
  28939. * A material that maps the normal vectors to RGB colors.
  28940. *
  28941. * @augments Material
  28942. */
  28943. class MeshNormalMaterial extends Material {
  28944. /**
  28945. * Constructs a new mesh normal material.
  28946. *
  28947. * @param {Object} [parameters] - An object with one or more properties
  28948. * defining the material's appearance. Any property of the material
  28949. * (including any property from inherited materials) can be passed
  28950. * in here. Color values can be passed any type of value accepted
  28951. * by {@link Color#set}.
  28952. */
  28953. constructor( parameters ) {
  28954. super();
  28955. /**
  28956. * This flag can be used for type testing.
  28957. *
  28958. * @type {boolean}
  28959. * @readonly
  28960. * @default true
  28961. */
  28962. this.isMeshNormalMaterial = true;
  28963. this.type = 'MeshNormalMaterial';
  28964. /**
  28965. * The texture to create a bump map. The black and white values map to the
  28966. * perceived depth in relation to the lights. Bump doesn't actually affect
  28967. * the geometry of the object, only the lighting. If a normal map is defined
  28968. * this will be ignored.
  28969. *
  28970. * @type {?Texture}
  28971. * @default null
  28972. */
  28973. this.bumpMap = null;
  28974. /**
  28975. * How much the bump map affects the material. Typical range is `[0,1]`.
  28976. *
  28977. * @type {number}
  28978. * @default 1
  28979. */
  28980. this.bumpScale = 1;
  28981. /**
  28982. * The texture to create a normal map. The RGB values affect the surface
  28983. * normal for each pixel fragment and change the way the color is lit. Normal
  28984. * maps do not change the actual shape of the surface, only the lighting. In
  28985. * case the material has a normal map authored using the left handed
  28986. * convention, the `y` component of `normalScale` should be negated to compensate
  28987. * for the different handedness.
  28988. *
  28989. * @type {?Texture}
  28990. * @default null
  28991. */
  28992. this.normalMap = null;
  28993. /**
  28994. * The type of normal map.
  28995. *
  28996. * @type {(TangentSpaceNormalMap|ObjectSpaceNormalMap)}
  28997. * @default TangentSpaceNormalMap
  28998. */
  28999. this.normalMapType = TangentSpaceNormalMap;
  29000. /**
  29001. * How much the normal map affects the material. Typical value range is `[0,1]`.
  29002. *
  29003. * @type {Vector2}
  29004. * @default (1,1)
  29005. */
  29006. this.normalScale = new Vector2( 1, 1 );
  29007. /**
  29008. * The displacement map affects the position of the mesh's vertices. Unlike
  29009. * other maps which only affect the light and shade of the material the
  29010. * displaced vertices can cast shadows, block other objects, and otherwise
  29011. * act as real geometry. The displacement texture is an image where the value
  29012. * of each pixel (white being the highest) is mapped against, and
  29013. * repositions, the vertices of the mesh.
  29014. *
  29015. * @type {?Texture}
  29016. * @default null
  29017. */
  29018. this.displacementMap = null;
  29019. /**
  29020. * How much the displacement map affects the mesh (where black is no
  29021. * displacement, and white is maximum displacement). Without a displacement
  29022. * map set, this value is not applied.
  29023. *
  29024. * @type {number}
  29025. * @default 0
  29026. */
  29027. this.displacementScale = 1;
  29028. /**
  29029. * The offset of the displacement map's values on the mesh's vertices.
  29030. * The bias is added to the scaled sample of the displacement map.
  29031. * Without a displacement map set, this value is not applied.
  29032. *
  29033. * @type {number}
  29034. * @default 0
  29035. */
  29036. this.displacementBias = 0;
  29037. /**
  29038. * Renders the geometry as a wireframe.
  29039. *
  29040. * @type {boolean}
  29041. * @default false
  29042. */
  29043. this.wireframe = false;
  29044. /**
  29045. * Controls the thickness of the wireframe.
  29046. *
  29047. * WebGL and WebGPU ignore this property and always render
  29048. * 1 pixel wide lines.
  29049. *
  29050. * @type {number}
  29051. * @default 1
  29052. */
  29053. this.wireframeLinewidth = 1;
  29054. /**
  29055. * Whether the material is rendered with flat shading or not.
  29056. *
  29057. * @type {boolean}
  29058. * @default false
  29059. */
  29060. this.flatShading = false;
  29061. this.setValues( parameters );
  29062. }
  29063. copy( source ) {
  29064. super.copy( source );
  29065. this.bumpMap = source.bumpMap;
  29066. this.bumpScale = source.bumpScale;
  29067. this.normalMap = source.normalMap;
  29068. this.normalMapType = source.normalMapType;
  29069. this.normalScale.copy( source.normalScale );
  29070. this.displacementMap = source.displacementMap;
  29071. this.displacementScale = source.displacementScale;
  29072. this.displacementBias = source.displacementBias;
  29073. this.wireframe = source.wireframe;
  29074. this.wireframeLinewidth = source.wireframeLinewidth;
  29075. this.flatShading = source.flatShading;
  29076. return this;
  29077. }
  29078. }
  29079. /**
  29080. * A material for non-shiny surfaces, without specular highlights.
  29081. *
  29082. * The material uses a non-physically based [Lambertian]{@link https://en.wikipedia.org/wiki/Lambertian_reflectance}
  29083. * model for calculating reflectance. This can simulate some surfaces (such
  29084. * as untreated wood or stone) well, but cannot simulate shiny surfaces with
  29085. * specular highlights (such as varnished wood). `MeshLambertMaterial` uses per-fragment
  29086. * shading.
  29087. *
  29088. * Due to the simplicity of the reflectance and illumination models,
  29089. * performance will be greater when using this material over the
  29090. * {@link MeshPhongMaterial}, {@link MeshStandardMaterial} or
  29091. * {@link MeshPhysicalMaterial}, at the cost of some graphical accuracy.
  29092. *
  29093. * @augments Material
  29094. */
  29095. class MeshLambertMaterial extends Material {
  29096. /**
  29097. * Constructs a new mesh lambert material.
  29098. *
  29099. * @param {Object} [parameters] - An object with one or more properties
  29100. * defining the material's appearance. Any property of the material
  29101. * (including any property from inherited materials) can be passed
  29102. * in here. Color values can be passed any type of value accepted
  29103. * by {@link Color#set}.
  29104. */
  29105. constructor( parameters ) {
  29106. super();
  29107. /**
  29108. * This flag can be used for type testing.
  29109. *
  29110. * @type {boolean}
  29111. * @readonly
  29112. * @default true
  29113. */
  29114. this.isMeshLambertMaterial = true;
  29115. this.type = 'MeshLambertMaterial';
  29116. /**
  29117. * Color of the material.
  29118. *
  29119. * @type {Color}
  29120. * @default (1,1,1)
  29121. */
  29122. this.color = new Color( 0xffffff ); // diffuse
  29123. /**
  29124. * The color map. May optionally include an alpha channel, typically combined
  29125. * with {@link Material#transparent} or {@link Material#alphaTest}. The texture map
  29126. * color is modulated by the diffuse `color`.
  29127. *
  29128. * @type {?Texture}
  29129. * @default null
  29130. */
  29131. this.map = null;
  29132. /**
  29133. * The light map. Requires a second set of UVs.
  29134. *
  29135. * @type {?Texture}
  29136. * @default null
  29137. */
  29138. this.lightMap = null;
  29139. /**
  29140. * Intensity of the baked light.
  29141. *
  29142. * @type {number}
  29143. * @default 1
  29144. */
  29145. this.lightMapIntensity = 1.0;
  29146. /**
  29147. * The red channel of this texture is used as the ambient occlusion map.
  29148. * Requires a second set of UVs.
  29149. *
  29150. * @type {?Texture}
  29151. * @default null
  29152. */
  29153. this.aoMap = null;
  29154. /**
  29155. * Intensity of the ambient occlusion effect. Range is `[0,1]`, where `0`
  29156. * disables ambient occlusion. Where intensity is `1` and the AO map's
  29157. * red channel is also `1`, ambient light is fully occluded on a surface.
  29158. *
  29159. * @type {number}
  29160. * @default 1
  29161. */
  29162. this.aoMapIntensity = 1.0;
  29163. /**
  29164. * Emissive (light) color of the material, essentially a solid color
  29165. * unaffected by other lighting.
  29166. *
  29167. * @type {Color}
  29168. * @default (0,0,0)
  29169. */
  29170. this.emissive = new Color( 0x000000 );
  29171. /**
  29172. * Intensity of the emissive light. Modulates the emissive color.
  29173. *
  29174. * @type {number}
  29175. * @default 1
  29176. */
  29177. this.emissiveIntensity = 1.0;
  29178. /**
  29179. * Set emissive (glow) map. The emissive map color is modulated by the
  29180. * emissive color and the emissive intensity. If you have an emissive map,
  29181. * be sure to set the emissive color to something other than black.
  29182. *
  29183. * @type {?Texture}
  29184. * @default null
  29185. */
  29186. this.emissiveMap = null;
  29187. /**
  29188. * The texture to create a bump map. The black and white values map to the
  29189. * perceived depth in relation to the lights. Bump doesn't actually affect
  29190. * the geometry of the object, only the lighting. If a normal map is defined
  29191. * this will be ignored.
  29192. *
  29193. * @type {?Texture}
  29194. * @default null
  29195. */
  29196. this.bumpMap = null;
  29197. /**
  29198. * How much the bump map affects the material. Typical range is `[0,1]`.
  29199. *
  29200. * @type {number}
  29201. * @default 1
  29202. */
  29203. this.bumpScale = 1;
  29204. /**
  29205. * The texture to create a normal map. The RGB values affect the surface
  29206. * normal for each pixel fragment and change the way the color is lit. Normal
  29207. * maps do not change the actual shape of the surface, only the lighting. In
  29208. * case the material has a normal map authored using the left handed
  29209. * convention, the `y` component of `normalScale` should be negated to compensate
  29210. * for the different handedness.
  29211. *
  29212. * @type {?Texture}
  29213. * @default null
  29214. */
  29215. this.normalMap = null;
  29216. /**
  29217. * The type of normal map.
  29218. *
  29219. * @type {(TangentSpaceNormalMap|ObjectSpaceNormalMap)}
  29220. * @default TangentSpaceNormalMap
  29221. */
  29222. this.normalMapType = TangentSpaceNormalMap;
  29223. /**
  29224. * How much the normal map affects the material. Typical value range is `[0,1]`.
  29225. *
  29226. * @type {Vector2}
  29227. * @default (1,1)
  29228. */
  29229. this.normalScale = new Vector2( 1, 1 );
  29230. /**
  29231. * The displacement map affects the position of the mesh's vertices. Unlike
  29232. * other maps which only affect the light and shade of the material the
  29233. * displaced vertices can cast shadows, block other objects, and otherwise
  29234. * act as real geometry. The displacement texture is an image where the value
  29235. * of each pixel (white being the highest) is mapped against, and
  29236. * repositions, the vertices of the mesh.
  29237. *
  29238. * @type {?Texture}
  29239. * @default null
  29240. */
  29241. this.displacementMap = null;
  29242. /**
  29243. * How much the displacement map affects the mesh (where black is no
  29244. * displacement, and white is maximum displacement). Without a displacement
  29245. * map set, this value is not applied.
  29246. *
  29247. * @type {number}
  29248. * @default 0
  29249. */
  29250. this.displacementScale = 1;
  29251. /**
  29252. * The offset of the displacement map's values on the mesh's vertices.
  29253. * The bias is added to the scaled sample of the displacement map.
  29254. * Without a displacement map set, this value is not applied.
  29255. *
  29256. * @type {number}
  29257. * @default 0
  29258. */
  29259. this.displacementBias = 0;
  29260. /**
  29261. * Specular map used by the material.
  29262. *
  29263. * @type {?Texture}
  29264. * @default null
  29265. */
  29266. this.specularMap = null;
  29267. /**
  29268. * The alpha map is a grayscale texture that controls the opacity across the
  29269. * surface (black: fully transparent; white: fully opaque).
  29270. *
  29271. * Only the color of the texture is used, ignoring the alpha channel if one
  29272. * exists. For RGB and RGBA textures, the renderer will use the green channel
  29273. * when sampling this texture due to the extra bit of precision provided for
  29274. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  29275. * luminance/alpha textures will also still work as expected.
  29276. *
  29277. * @type {?Texture}
  29278. * @default null
  29279. */
  29280. this.alphaMap = null;
  29281. /**
  29282. * The environment map.
  29283. *
  29284. * @type {?Texture}
  29285. * @default null
  29286. */
  29287. this.envMap = null;
  29288. /**
  29289. * The rotation of the environment map in radians.
  29290. *
  29291. * @type {Euler}
  29292. * @default (0,0,0)
  29293. */
  29294. this.envMapRotation = new Euler();
  29295. /**
  29296. * How to combine the result of the surface's color with the environment map, if any.
  29297. *
  29298. * When set to `MixOperation`, the {@link MeshBasicMaterial#reflectivity} is used to
  29299. * blend between the two colors.
  29300. *
  29301. * @type {(MultiplyOperation|MixOperation|AddOperation)}
  29302. * @default MultiplyOperation
  29303. */
  29304. this.combine = MultiplyOperation;
  29305. /**
  29306. * How much the environment map affects the surface.
  29307. * The valid range is between `0` (no reflections) and `1` (full reflections).
  29308. *
  29309. * @type {number}
  29310. * @default 1
  29311. */
  29312. this.reflectivity = 1;
  29313. /**
  29314. * The index of refraction (IOR) of air (approximately 1) divided by the
  29315. * index of refraction of the material. It is used with environment mapping
  29316. * modes {@link CubeRefractionMapping} and {@link EquirectangularRefractionMapping}.
  29317. * The refraction ratio should not exceed `1`.
  29318. *
  29319. * @type {number}
  29320. * @default 0.98
  29321. */
  29322. this.refractionRatio = 0.98;
  29323. /**
  29324. * Renders the geometry as a wireframe.
  29325. *
  29326. * @type {boolean}
  29327. * @default false
  29328. */
  29329. this.wireframe = false;
  29330. /**
  29331. * Controls the thickness of the wireframe.
  29332. *
  29333. * Can only be used with {@link SVGRenderer}.
  29334. *
  29335. * @type {number}
  29336. * @default 1
  29337. */
  29338. this.wireframeLinewidth = 1;
  29339. /**
  29340. * Defines appearance of wireframe ends.
  29341. *
  29342. * Can only be used with {@link SVGRenderer}.
  29343. *
  29344. * @type {('round'|'bevel'|'miter')}
  29345. * @default 'round'
  29346. */
  29347. this.wireframeLinecap = 'round';
  29348. /**
  29349. * Defines appearance of wireframe joints.
  29350. *
  29351. * Can only be used with {@link SVGRenderer}.
  29352. *
  29353. * @type {('round'|'bevel'|'miter')}
  29354. * @default 'round'
  29355. */
  29356. this.wireframeLinejoin = 'round';
  29357. /**
  29358. * Whether the material is rendered with flat shading or not.
  29359. *
  29360. * @type {boolean}
  29361. * @default false
  29362. */
  29363. this.flatShading = false;
  29364. /**
  29365. * Whether the material is affected by fog or not.
  29366. *
  29367. * @type {boolean}
  29368. * @default true
  29369. */
  29370. this.fog = true;
  29371. this.setValues( parameters );
  29372. }
  29373. copy( source ) {
  29374. super.copy( source );
  29375. this.color.copy( source.color );
  29376. this.map = source.map;
  29377. this.lightMap = source.lightMap;
  29378. this.lightMapIntensity = source.lightMapIntensity;
  29379. this.aoMap = source.aoMap;
  29380. this.aoMapIntensity = source.aoMapIntensity;
  29381. this.emissive.copy( source.emissive );
  29382. this.emissiveMap = source.emissiveMap;
  29383. this.emissiveIntensity = source.emissiveIntensity;
  29384. this.bumpMap = source.bumpMap;
  29385. this.bumpScale = source.bumpScale;
  29386. this.normalMap = source.normalMap;
  29387. this.normalMapType = source.normalMapType;
  29388. this.normalScale.copy( source.normalScale );
  29389. this.displacementMap = source.displacementMap;
  29390. this.displacementScale = source.displacementScale;
  29391. this.displacementBias = source.displacementBias;
  29392. this.specularMap = source.specularMap;
  29393. this.alphaMap = source.alphaMap;
  29394. this.envMap = source.envMap;
  29395. this.envMapRotation.copy( source.envMapRotation );
  29396. this.combine = source.combine;
  29397. this.reflectivity = source.reflectivity;
  29398. this.refractionRatio = source.refractionRatio;
  29399. this.wireframe = source.wireframe;
  29400. this.wireframeLinewidth = source.wireframeLinewidth;
  29401. this.wireframeLinecap = source.wireframeLinecap;
  29402. this.wireframeLinejoin = source.wireframeLinejoin;
  29403. this.flatShading = source.flatShading;
  29404. this.fog = source.fog;
  29405. return this;
  29406. }
  29407. }
  29408. /**
  29409. * A material for drawing geometry by depth. Depth is based off of the camera
  29410. * near and far plane. White is nearest, black is farthest.
  29411. *
  29412. * @augments Material
  29413. */
  29414. class MeshDepthMaterial extends Material {
  29415. /**
  29416. * Constructs a new mesh depth material.
  29417. *
  29418. * @param {Object} [parameters] - An object with one or more properties
  29419. * defining the material's appearance. Any property of the material
  29420. * (including any property from inherited materials) can be passed
  29421. * in here. Color values can be passed any type of value accepted
  29422. * by {@link Color#set}.
  29423. */
  29424. constructor( parameters ) {
  29425. super();
  29426. /**
  29427. * This flag can be used for type testing.
  29428. *
  29429. * @type {boolean}
  29430. * @readonly
  29431. * @default true
  29432. */
  29433. this.isMeshDepthMaterial = true;
  29434. this.type = 'MeshDepthMaterial';
  29435. /**
  29436. * Type for depth packing.
  29437. *
  29438. * @type {(BasicDepthPacking|RGBADepthPacking|RGBDepthPacking|RGDepthPacking)}
  29439. * @default BasicDepthPacking
  29440. */
  29441. this.depthPacking = BasicDepthPacking;
  29442. /**
  29443. * The color map. May optionally include an alpha channel, typically combined
  29444. * with {@link Material#transparent} or {@link Material#alphaTest}.
  29445. *
  29446. * @type {?Texture}
  29447. * @default null
  29448. */
  29449. this.map = null;
  29450. /**
  29451. * The alpha map is a grayscale texture that controls the opacity across the
  29452. * surface (black: fully transparent; white: fully opaque).
  29453. *
  29454. * Only the color of the texture is used, ignoring the alpha channel if one
  29455. * exists. For RGB and RGBA textures, the renderer will use the green channel
  29456. * when sampling this texture due to the extra bit of precision provided for
  29457. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  29458. * luminance/alpha textures will also still work as expected.
  29459. *
  29460. * @type {?Texture}
  29461. * @default null
  29462. */
  29463. this.alphaMap = null;
  29464. /**
  29465. * The displacement map affects the position of the mesh's vertices. Unlike
  29466. * other maps which only affect the light and shade of the material the
  29467. * displaced vertices can cast shadows, block other objects, and otherwise
  29468. * act as real geometry. The displacement texture is an image where the value
  29469. * of each pixel (white being the highest) is mapped against, and
  29470. * repositions, the vertices of the mesh.
  29471. *
  29472. * @type {?Texture}
  29473. * @default null
  29474. */
  29475. this.displacementMap = null;
  29476. /**
  29477. * How much the displacement map affects the mesh (where black is no
  29478. * displacement, and white is maximum displacement). Without a displacement
  29479. * map set, this value is not applied.
  29480. *
  29481. * @type {number}
  29482. * @default 0
  29483. */
  29484. this.displacementScale = 1;
  29485. /**
  29486. * The offset of the displacement map's values on the mesh's vertices.
  29487. * The bias is added to the scaled sample of the displacement map.
  29488. * Without a displacement map set, this value is not applied.
  29489. *
  29490. * @type {number}
  29491. * @default 0
  29492. */
  29493. this.displacementBias = 0;
  29494. /**
  29495. * Renders the geometry as a wireframe.
  29496. *
  29497. * @type {boolean}
  29498. * @default false
  29499. */
  29500. this.wireframe = false;
  29501. /**
  29502. * Controls the thickness of the wireframe.
  29503. *
  29504. * WebGL and WebGPU ignore this property and always render
  29505. * 1 pixel wide lines.
  29506. *
  29507. * @type {number}
  29508. * @default 1
  29509. */
  29510. this.wireframeLinewidth = 1;
  29511. this.setValues( parameters );
  29512. }
  29513. copy( source ) {
  29514. super.copy( source );
  29515. this.depthPacking = source.depthPacking;
  29516. this.map = source.map;
  29517. this.alphaMap = source.alphaMap;
  29518. this.displacementMap = source.displacementMap;
  29519. this.displacementScale = source.displacementScale;
  29520. this.displacementBias = source.displacementBias;
  29521. this.wireframe = source.wireframe;
  29522. this.wireframeLinewidth = source.wireframeLinewidth;
  29523. return this;
  29524. }
  29525. }
  29526. /**
  29527. * A material used internally for implementing shadow mapping with
  29528. * point lights.
  29529. *
  29530. * Can also be used to customize the shadow casting of an object by assigning
  29531. * an instance of `MeshDistanceMaterial` to {@link Object3D#customDistanceMaterial}.
  29532. * The following examples demonstrates this approach in order to ensure
  29533. * transparent parts of objects do no cast shadows.
  29534. *
  29535. * @augments Material
  29536. */
  29537. class MeshDistanceMaterial extends Material {
  29538. /**
  29539. * Constructs a new mesh distance material.
  29540. *
  29541. * @param {Object} [parameters] - An object with one or more properties
  29542. * defining the material's appearance. Any property of the material
  29543. * (including any property from inherited materials) can be passed
  29544. * in here. Color values can be passed any type of value accepted
  29545. * by {@link Color#set}.
  29546. */
  29547. constructor( parameters ) {
  29548. super();
  29549. /**
  29550. * This flag can be used for type testing.
  29551. *
  29552. * @type {boolean}
  29553. * @readonly
  29554. * @default true
  29555. */
  29556. this.isMeshDistanceMaterial = true;
  29557. this.type = 'MeshDistanceMaterial';
  29558. /**
  29559. * The color map. May optionally include an alpha channel, typically combined
  29560. * with {@link Material#transparent} or {@link Material#alphaTest}.
  29561. *
  29562. * @type {?Texture}
  29563. * @default null
  29564. */
  29565. this.map = null;
  29566. /**
  29567. * The alpha map is a grayscale texture that controls the opacity across the
  29568. * surface (black: fully transparent; white: fully opaque).
  29569. *
  29570. * Only the color of the texture is used, ignoring the alpha channel if one
  29571. * exists. For RGB and RGBA textures, the renderer will use the green channel
  29572. * when sampling this texture due to the extra bit of precision provided for
  29573. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  29574. * luminance/alpha textures will also still work as expected.
  29575. *
  29576. * @type {?Texture}
  29577. * @default null
  29578. */
  29579. this.alphaMap = null;
  29580. /**
  29581. * The displacement map affects the position of the mesh's vertices. Unlike
  29582. * other maps which only affect the light and shade of the material the
  29583. * displaced vertices can cast shadows, block other objects, and otherwise
  29584. * act as real geometry. The displacement texture is an image where the value
  29585. * of each pixel (white being the highest) is mapped against, and
  29586. * repositions, the vertices of the mesh.
  29587. *
  29588. * @type {?Texture}
  29589. * @default null
  29590. */
  29591. this.displacementMap = null;
  29592. /**
  29593. * How much the displacement map affects the mesh (where black is no
  29594. * displacement, and white is maximum displacement). Without a displacement
  29595. * map set, this value is not applied.
  29596. *
  29597. * @type {number}
  29598. * @default 0
  29599. */
  29600. this.displacementScale = 1;
  29601. /**
  29602. * The offset of the displacement map's values on the mesh's vertices.
  29603. * The bias is added to the scaled sample of the displacement map.
  29604. * Without a displacement map set, this value is not applied.
  29605. *
  29606. * @type {number}
  29607. * @default 0
  29608. */
  29609. this.displacementBias = 0;
  29610. this.setValues( parameters );
  29611. }
  29612. copy( source ) {
  29613. super.copy( source );
  29614. this.map = source.map;
  29615. this.alphaMap = source.alphaMap;
  29616. this.displacementMap = source.displacementMap;
  29617. this.displacementScale = source.displacementScale;
  29618. this.displacementBias = source.displacementBias;
  29619. return this;
  29620. }
  29621. }
  29622. /**
  29623. * This material is defined by a MatCap (or Lit Sphere) texture, which encodes the
  29624. * material color and shading.
  29625. *
  29626. * `MeshMatcapMaterial` does not respond to lights since the matcap image file encodes
  29627. * baked lighting. It will cast a shadow onto an object that receives shadows
  29628. * (and shadow clipping works), but it will not self-shadow or receive
  29629. * shadows.
  29630. *
  29631. * @augments Material
  29632. */
  29633. class MeshMatcapMaterial extends Material {
  29634. /**
  29635. * Constructs a new mesh matcap material.
  29636. *
  29637. * @param {Object} [parameters] - An object with one or more properties
  29638. * defining the material's appearance. Any property of the material
  29639. * (including any property from inherited materials) can be passed
  29640. * in here. Color values can be passed any type of value accepted
  29641. * by {@link Color#set}.
  29642. */
  29643. constructor( parameters ) {
  29644. super();
  29645. /**
  29646. * This flag can be used for type testing.
  29647. *
  29648. * @type {boolean}
  29649. * @readonly
  29650. * @default true
  29651. */
  29652. this.isMeshMatcapMaterial = true;
  29653. this.defines = { 'MATCAP': '' };
  29654. this.type = 'MeshMatcapMaterial';
  29655. /**
  29656. * Color of the material.
  29657. *
  29658. * @type {Color}
  29659. * @default (1,1,1)
  29660. */
  29661. this.color = new Color( 0xffffff ); // diffuse
  29662. /**
  29663. * The matcap map.
  29664. *
  29665. * @type {?Texture}
  29666. * @default null
  29667. */
  29668. this.matcap = null;
  29669. /**
  29670. * The color map. May optionally include an alpha channel, typically combined
  29671. * with {@link Material#transparent} or {@link Material#alphaTest}. The texture map
  29672. * color is modulated by the diffuse `color`.
  29673. *
  29674. * @type {?Texture}
  29675. * @default null
  29676. */
  29677. this.map = null;
  29678. /**
  29679. * The texture to create a bump map. The black and white values map to the
  29680. * perceived depth in relation to the lights. Bump doesn't actually affect
  29681. * the geometry of the object, only the lighting. If a normal map is defined
  29682. * this will be ignored.
  29683. *
  29684. * @type {?Texture}
  29685. * @default null
  29686. */
  29687. this.bumpMap = null;
  29688. /**
  29689. * How much the bump map affects the material. Typical range is `[0,1]`.
  29690. *
  29691. * @type {number}
  29692. * @default 1
  29693. */
  29694. this.bumpScale = 1;
  29695. /**
  29696. * The texture to create a normal map. The RGB values affect the surface
  29697. * normal for each pixel fragment and change the way the color is lit. Normal
  29698. * maps do not change the actual shape of the surface, only the lighting. In
  29699. * case the material has a normal map authored using the left handed
  29700. * convention, the `y` component of `normalScale` should be negated to compensate
  29701. * for the different handedness.
  29702. *
  29703. * @type {?Texture}
  29704. * @default null
  29705. */
  29706. this.normalMap = null;
  29707. /**
  29708. * The type of normal map.
  29709. *
  29710. * @type {(TangentSpaceNormalMap|ObjectSpaceNormalMap)}
  29711. * @default TangentSpaceNormalMap
  29712. */
  29713. this.normalMapType = TangentSpaceNormalMap;
  29714. /**
  29715. * How much the normal map affects the material. Typical value range is `[0,1]`.
  29716. *
  29717. * @type {Vector2}
  29718. * @default (1,1)
  29719. */
  29720. this.normalScale = new Vector2( 1, 1 );
  29721. /**
  29722. * The displacement map affects the position of the mesh's vertices. Unlike
  29723. * other maps which only affect the light and shade of the material the
  29724. * displaced vertices can cast shadows, block other objects, and otherwise
  29725. * act as real geometry. The displacement texture is an image where the value
  29726. * of each pixel (white being the highest) is mapped against, and
  29727. * repositions, the vertices of the mesh.
  29728. *
  29729. * @type {?Texture}
  29730. * @default null
  29731. */
  29732. this.displacementMap = null;
  29733. /**
  29734. * How much the displacement map affects the mesh (where black is no
  29735. * displacement, and white is maximum displacement). Without a displacement
  29736. * map set, this value is not applied.
  29737. *
  29738. * @type {number}
  29739. * @default 0
  29740. */
  29741. this.displacementScale = 1;
  29742. /**
  29743. * The offset of the displacement map's values on the mesh's vertices.
  29744. * The bias is added to the scaled sample of the displacement map.
  29745. * Without a displacement map set, this value is not applied.
  29746. *
  29747. * @type {number}
  29748. * @default 0
  29749. */
  29750. this.displacementBias = 0;
  29751. /**
  29752. * The alpha map is a grayscale texture that controls the opacity across the
  29753. * surface (black: fully transparent; white: fully opaque).
  29754. *
  29755. * Only the color of the texture is used, ignoring the alpha channel if one
  29756. * exists. For RGB and RGBA textures, the renderer will use the green channel
  29757. * when sampling this texture due to the extra bit of precision provided for
  29758. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  29759. * luminance/alpha textures will also still work as expected.
  29760. *
  29761. * @type {?Texture}
  29762. * @default null
  29763. */
  29764. this.alphaMap = null;
  29765. /**
  29766. * Whether the material is rendered with flat shading or not.
  29767. *
  29768. * @type {boolean}
  29769. * @default false
  29770. */
  29771. this.flatShading = false;
  29772. /**
  29773. * Whether the material is affected by fog or not.
  29774. *
  29775. * @type {boolean}
  29776. * @default true
  29777. */
  29778. this.fog = true;
  29779. this.setValues( parameters );
  29780. }
  29781. copy( source ) {
  29782. super.copy( source );
  29783. this.defines = { 'MATCAP': '' };
  29784. this.color.copy( source.color );
  29785. this.matcap = source.matcap;
  29786. this.map = source.map;
  29787. this.bumpMap = source.bumpMap;
  29788. this.bumpScale = source.bumpScale;
  29789. this.normalMap = source.normalMap;
  29790. this.normalMapType = source.normalMapType;
  29791. this.normalScale.copy( source.normalScale );
  29792. this.displacementMap = source.displacementMap;
  29793. this.displacementScale = source.displacementScale;
  29794. this.displacementBias = source.displacementBias;
  29795. this.alphaMap = source.alphaMap;
  29796. this.flatShading = source.flatShading;
  29797. this.fog = source.fog;
  29798. return this;
  29799. }
  29800. }
  29801. /**
  29802. * A material for rendering line primitives.
  29803. *
  29804. * Materials define the appearance of renderable 3D objects.
  29805. *
  29806. * ```js
  29807. * const material = new THREE.LineDashedMaterial( {
  29808. * color: 0xffffff,
  29809. * scale: 1,
  29810. * dashSize: 3,
  29811. * gapSize: 1,
  29812. * } );
  29813. * ```
  29814. *
  29815. * @augments LineBasicMaterial
  29816. */
  29817. class LineDashedMaterial extends LineBasicMaterial {
  29818. /**
  29819. * Constructs a new line dashed material.
  29820. *
  29821. * @param {Object} [parameters] - An object with one or more properties
  29822. * defining the material's appearance. Any property of the material
  29823. * (including any property from inherited materials) can be passed
  29824. * in here. Color values can be passed any type of value accepted
  29825. * by {@link Color#set}.
  29826. */
  29827. constructor( parameters ) {
  29828. super();
  29829. /**
  29830. * This flag can be used for type testing.
  29831. *
  29832. * @type {boolean}
  29833. * @readonly
  29834. * @default true
  29835. */
  29836. this.isLineDashedMaterial = true;
  29837. this.type = 'LineDashedMaterial';
  29838. /**
  29839. * The scale of the dashed part of a line.
  29840. *
  29841. * @type {number}
  29842. * @default 1
  29843. */
  29844. this.scale = 1;
  29845. /**
  29846. * The size of the dash. This is both the gap with the stroke.
  29847. *
  29848. * @type {number}
  29849. * @default 3
  29850. */
  29851. this.dashSize = 3;
  29852. /**
  29853. * The size of the gap.
  29854. *
  29855. * @type {number}
  29856. * @default 1
  29857. */
  29858. this.gapSize = 1;
  29859. this.setValues( parameters );
  29860. }
  29861. copy( source ) {
  29862. super.copy( source );
  29863. this.scale = source.scale;
  29864. this.dashSize = source.dashSize;
  29865. this.gapSize = source.gapSize;
  29866. return this;
  29867. }
  29868. }
  29869. /**
  29870. * Converts an array to a specific type.
  29871. *
  29872. * @param {TypedArray|Array} array - The array to convert.
  29873. * @param {TypedArray.constructor} type - The constructor of a typed array that defines the new type.
  29874. * @return {TypedArray} The converted array.
  29875. */
  29876. function convertArray( array, type ) {
  29877. if ( ! array || array.constructor === type ) return array;
  29878. if ( typeof type.BYTES_PER_ELEMENT === 'number' ) {
  29879. return new type( array ); // create typed array
  29880. }
  29881. return Array.prototype.slice.call( array ); // create Array
  29882. }
  29883. /**
  29884. * Returns `true` if the given object is a typed array.
  29885. *
  29886. * @param {any} object - The object to check.
  29887. * @return {boolean} Whether the given object is a typed array.
  29888. */
  29889. function isTypedArray( object ) {
  29890. return ArrayBuffer.isView( object ) && ! ( object instanceof DataView );
  29891. }
  29892. /**
  29893. * Returns an array by which times and values can be sorted.
  29894. *
  29895. * @param {Array<number>} times - The keyframe time values.
  29896. * @return {Array<number>} The array.
  29897. */
  29898. function getKeyframeOrder( times ) {
  29899. function compareTime( i, j ) {
  29900. return times[ i ] - times[ j ];
  29901. }
  29902. const n = times.length;
  29903. const result = new Array( n );
  29904. for ( let i = 0; i !== n; ++ i ) result[ i ] = i;
  29905. result.sort( compareTime );
  29906. return result;
  29907. }
  29908. /**
  29909. * Sorts the given array by the previously computed order via `getKeyframeOrder()`.
  29910. *
  29911. * @param {Array<number>} values - The values to sort.
  29912. * @param {number} stride - The stride.
  29913. * @param {Array<number>} order - The sort order.
  29914. * @return {Array<number>} The sorted values.
  29915. */
  29916. function sortedArray( values, stride, order ) {
  29917. const nValues = values.length;
  29918. const result = new values.constructor( nValues );
  29919. for ( let i = 0, dstOffset = 0; dstOffset !== nValues; ++ i ) {
  29920. const srcOffset = order[ i ] * stride;
  29921. for ( let j = 0; j !== stride; ++ j ) {
  29922. result[ dstOffset ++ ] = values[ srcOffset + j ];
  29923. }
  29924. }
  29925. return result;
  29926. }
  29927. /**
  29928. * Used for parsing AOS keyframe formats.
  29929. *
  29930. * @param {Array<number>} jsonKeys - A list of JSON keyframes.
  29931. * @param {Array<number>} times - This array will be filled with keyframe times by this function.
  29932. * @param {Array<number>} values - This array will be filled with keyframe values by this function.
  29933. * @param {string} valuePropertyName - The name of the property to use.
  29934. */
  29935. function flattenJSON( jsonKeys, times, values, valuePropertyName ) {
  29936. let i = 1, key = jsonKeys[ 0 ];
  29937. while ( key !== undefined && key[ valuePropertyName ] === undefined ) {
  29938. key = jsonKeys[ i ++ ];
  29939. }
  29940. if ( key === undefined ) return; // no data
  29941. let value = key[ valuePropertyName ];
  29942. if ( value === undefined ) return; // no data
  29943. if ( Array.isArray( value ) ) {
  29944. do {
  29945. value = key[ valuePropertyName ];
  29946. if ( value !== undefined ) {
  29947. times.push( key.time );
  29948. values.push( ...value ); // push all elements
  29949. }
  29950. key = jsonKeys[ i ++ ];
  29951. } while ( key !== undefined );
  29952. } else if ( value.toArray !== undefined ) {
  29953. // ...assume THREE.Math-ish
  29954. do {
  29955. value = key[ valuePropertyName ];
  29956. if ( value !== undefined ) {
  29957. times.push( key.time );
  29958. value.toArray( values, values.length );
  29959. }
  29960. key = jsonKeys[ i ++ ];
  29961. } while ( key !== undefined );
  29962. } else {
  29963. // otherwise push as-is
  29964. do {
  29965. value = key[ valuePropertyName ];
  29966. if ( value !== undefined ) {
  29967. times.push( key.time );
  29968. values.push( value );
  29969. }
  29970. key = jsonKeys[ i ++ ];
  29971. } while ( key !== undefined );
  29972. }
  29973. }
  29974. /**
  29975. * Creates a new clip, containing only the segment of the original clip between the given frames.
  29976. *
  29977. * @param {AnimationClip} sourceClip - The values to sort.
  29978. * @param {string} name - The name of the clip.
  29979. * @param {number} startFrame - The start frame.
  29980. * @param {number} endFrame - The end frame.
  29981. * @param {number} [fps=30] - The FPS.
  29982. * @return {AnimationClip} The new sub clip.
  29983. */
  29984. function subclip( sourceClip, name, startFrame, endFrame, fps = 30 ) {
  29985. const clip = sourceClip.clone();
  29986. clip.name = name;
  29987. const tracks = [];
  29988. for ( let i = 0; i < clip.tracks.length; ++ i ) {
  29989. const track = clip.tracks[ i ];
  29990. const valueSize = track.getValueSize();
  29991. const times = [];
  29992. const values = [];
  29993. for ( let j = 0; j < track.times.length; ++ j ) {
  29994. const frame = track.times[ j ] * fps;
  29995. if ( frame < startFrame || frame >= endFrame ) continue;
  29996. times.push( track.times[ j ] );
  29997. for ( let k = 0; k < valueSize; ++ k ) {
  29998. values.push( track.values[ j * valueSize + k ] );
  29999. }
  30000. }
  30001. if ( times.length === 0 ) continue;
  30002. track.times = convertArray( times, track.times.constructor );
  30003. track.values = convertArray( values, track.values.constructor );
  30004. tracks.push( track );
  30005. }
  30006. clip.tracks = tracks;
  30007. // find minimum .times value across all tracks in the trimmed clip
  30008. let minStartTime = Infinity;
  30009. for ( let i = 0; i < clip.tracks.length; ++ i ) {
  30010. if ( minStartTime > clip.tracks[ i ].times[ 0 ] ) {
  30011. minStartTime = clip.tracks[ i ].times[ 0 ];
  30012. }
  30013. }
  30014. // shift all tracks such that clip begins at t=0
  30015. for ( let i = 0; i < clip.tracks.length; ++ i ) {
  30016. clip.tracks[ i ].shift( -1 * minStartTime );
  30017. }
  30018. clip.resetDuration();
  30019. return clip;
  30020. }
  30021. /**
  30022. * Converts the keyframes of the given animation clip to an additive format.
  30023. *
  30024. * @param {AnimationClip} targetClip - The clip to make additive.
  30025. * @param {number} [referenceFrame=0] - The reference frame.
  30026. * @param {AnimationClip} [referenceClip=targetClip] - The reference clip.
  30027. * @param {number} [fps=30] - The FPS.
  30028. * @return {AnimationClip} The updated clip which is now additive.
  30029. */
  30030. function makeClipAdditive( targetClip, referenceFrame = 0, referenceClip = targetClip, fps = 30 ) {
  30031. if ( fps <= 0 ) fps = 30;
  30032. const numTracks = referenceClip.tracks.length;
  30033. const referenceTime = referenceFrame / fps;
  30034. // Make each track's values relative to the values at the reference frame
  30035. for ( let i = 0; i < numTracks; ++ i ) {
  30036. const referenceTrack = referenceClip.tracks[ i ];
  30037. const referenceTrackType = referenceTrack.ValueTypeName;
  30038. // Skip this track if it's non-numeric
  30039. if ( referenceTrackType === 'bool' || referenceTrackType === 'string' ) continue;
  30040. // Find the track in the target clip whose name and type matches the reference track
  30041. const targetTrack = targetClip.tracks.find( function ( track ) {
  30042. return track.name === referenceTrack.name
  30043. && track.ValueTypeName === referenceTrackType;
  30044. } );
  30045. if ( targetTrack === undefined ) continue;
  30046. let referenceOffset = 0;
  30047. const referenceValueSize = referenceTrack.getValueSize();
  30048. if ( referenceTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline ) {
  30049. referenceOffset = referenceValueSize / 3;
  30050. }
  30051. let targetOffset = 0;
  30052. const targetValueSize = targetTrack.getValueSize();
  30053. if ( targetTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline ) {
  30054. targetOffset = targetValueSize / 3;
  30055. }
  30056. const lastIndex = referenceTrack.times.length - 1;
  30057. let referenceValue;
  30058. // Find the value to subtract out of the track
  30059. if ( referenceTime <= referenceTrack.times[ 0 ] ) {
  30060. // Reference frame is earlier than the first keyframe, so just use the first keyframe
  30061. const startIndex = referenceOffset;
  30062. const endIndex = referenceValueSize - referenceOffset;
  30063. referenceValue = referenceTrack.values.slice( startIndex, endIndex );
  30064. } else if ( referenceTime >= referenceTrack.times[ lastIndex ] ) {
  30065. // Reference frame is after the last keyframe, so just use the last keyframe
  30066. const startIndex = lastIndex * referenceValueSize + referenceOffset;
  30067. const endIndex = startIndex + referenceValueSize - referenceOffset;
  30068. referenceValue = referenceTrack.values.slice( startIndex, endIndex );
  30069. } else {
  30070. // Interpolate to the reference value
  30071. const interpolant = referenceTrack.createInterpolant();
  30072. const startIndex = referenceOffset;
  30073. const endIndex = referenceValueSize - referenceOffset;
  30074. interpolant.evaluate( referenceTime );
  30075. referenceValue = interpolant.resultBuffer.slice( startIndex, endIndex );
  30076. }
  30077. // Conjugate the quaternion
  30078. if ( referenceTrackType === 'quaternion' ) {
  30079. const referenceQuat = new Quaternion().fromArray( referenceValue ).normalize().conjugate();
  30080. referenceQuat.toArray( referenceValue );
  30081. }
  30082. // Subtract the reference value from all of the track values
  30083. const numTimes = targetTrack.times.length;
  30084. for ( let j = 0; j < numTimes; ++ j ) {
  30085. const valueStart = j * targetValueSize + targetOffset;
  30086. if ( referenceTrackType === 'quaternion' ) {
  30087. // Multiply the conjugate for quaternion track types
  30088. Quaternion.multiplyQuaternionsFlat(
  30089. targetTrack.values,
  30090. valueStart,
  30091. referenceValue,
  30092. 0,
  30093. targetTrack.values,
  30094. valueStart
  30095. );
  30096. } else {
  30097. const valueEnd = targetValueSize - targetOffset * 2;
  30098. // Subtract each value for all other numeric track types
  30099. for ( let k = 0; k < valueEnd; ++ k ) {
  30100. targetTrack.values[ valueStart + k ] -= referenceValue[ k ];
  30101. }
  30102. }
  30103. }
  30104. }
  30105. targetClip.blendMode = AdditiveAnimationBlendMode;
  30106. return targetClip;
  30107. }
  30108. /**
  30109. * A class with various methods to assist with animations.
  30110. *
  30111. * @hideconstructor
  30112. */
  30113. class AnimationUtils {
  30114. /**
  30115. * Converts an array to a specific type
  30116. *
  30117. * @static
  30118. * @param {TypedArray|Array} array - The array to convert.
  30119. * @param {TypedArray.constructor} type - The constructor of a type array.
  30120. * @return {TypedArray} The converted array
  30121. */
  30122. static convertArray( array, type ) {
  30123. return convertArray( array, type );
  30124. }
  30125. /**
  30126. * Returns `true` if the given object is a typed array.
  30127. *
  30128. * @static
  30129. * @param {any} object - The object to check.
  30130. * @return {boolean} Whether the given object is a typed array.
  30131. */
  30132. static isTypedArray( object ) {
  30133. return isTypedArray( object );
  30134. }
  30135. /**
  30136. * Returns an array by which times and values can be sorted.
  30137. *
  30138. * @static
  30139. * @param {Array<number>} times - The keyframe time values.
  30140. * @return {Array<number>} The array.
  30141. */
  30142. static getKeyframeOrder( times ) {
  30143. return getKeyframeOrder( times );
  30144. }
  30145. /**
  30146. * Sorts the given array by the previously computed order via `getKeyframeOrder()`.
  30147. *
  30148. * @static
  30149. * @param {Array<number>} values - The values to sort.
  30150. * @param {number} stride - The stride.
  30151. * @param {Array<number>} order - The sort order.
  30152. * @return {Array<number>} The sorted values.
  30153. */
  30154. static sortedArray( values, stride, order ) {
  30155. return sortedArray( values, stride, order );
  30156. }
  30157. /**
  30158. * Used for parsing AOS keyframe formats.
  30159. *
  30160. * @static
  30161. * @param {Array<number>} jsonKeys - A list of JSON keyframes.
  30162. * @param {Array<number>} times - This array will be filled with keyframe times by this method.
  30163. * @param {Array<number>} values - This array will be filled with keyframe values by this method.
  30164. * @param {string} valuePropertyName - The name of the property to use.
  30165. */
  30166. static flattenJSON( jsonKeys, times, values, valuePropertyName ) {
  30167. flattenJSON( jsonKeys, times, values, valuePropertyName );
  30168. }
  30169. /**
  30170. * Creates a new clip, containing only the segment of the original clip between the given frames.
  30171. *
  30172. * @static
  30173. * @param {AnimationClip} sourceClip - The values to sort.
  30174. * @param {string} name - The name of the clip.
  30175. * @param {number} startFrame - The start frame.
  30176. * @param {number} endFrame - The end frame.
  30177. * @param {number} [fps=30] - The FPS.
  30178. * @return {AnimationClip} The new sub clip.
  30179. */
  30180. static subclip( sourceClip, name, startFrame, endFrame, fps = 30 ) {
  30181. return subclip( sourceClip, name, startFrame, endFrame, fps );
  30182. }
  30183. /**
  30184. * Converts the keyframes of the given animation clip to an additive format.
  30185. *
  30186. * @static
  30187. * @param {AnimationClip} targetClip - The clip to make additive.
  30188. * @param {number} [referenceFrame=0] - The reference frame.
  30189. * @param {AnimationClip} [referenceClip=targetClip] - The reference clip.
  30190. * @param {number} [fps=30] - The FPS.
  30191. * @return {AnimationClip} The updated clip which is now additive.
  30192. */
  30193. static makeClipAdditive( targetClip, referenceFrame = 0, referenceClip = targetClip, fps = 30 ) {
  30194. return makeClipAdditive( targetClip, referenceFrame, referenceClip, fps );
  30195. }
  30196. }
  30197. /**
  30198. * Abstract base class of interpolants over parametric samples.
  30199. *
  30200. * The parameter domain is one dimensional, typically the time or a path
  30201. * along a curve defined by the data.
  30202. *
  30203. * The sample values can have any dimensionality and derived classes may
  30204. * apply special interpretations to the data.
  30205. *
  30206. * This class provides the interval seek in a Template Method, deferring
  30207. * the actual interpolation to derived classes.
  30208. *
  30209. * Time complexity is O(1) for linear access crossing at most two points
  30210. * and O(log N) for random access, where N is the number of positions.
  30211. *
  30212. * References: {@link http://www.oodesign.com/template-method-pattern.html}
  30213. *
  30214. * @abstract
  30215. */
  30216. class Interpolant {
  30217. /**
  30218. * Constructs a new interpolant.
  30219. *
  30220. * @param {TypedArray} parameterPositions - The parameter positions hold the interpolation factors.
  30221. * @param {TypedArray} sampleValues - The sample values.
  30222. * @param {number} sampleSize - The sample size
  30223. * @param {TypedArray} [resultBuffer] - The result buffer.
  30224. */
  30225. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  30226. /**
  30227. * The parameter positions.
  30228. *
  30229. * @type {TypedArray}
  30230. */
  30231. this.parameterPositions = parameterPositions;
  30232. /**
  30233. * A cache index.
  30234. *
  30235. * @private
  30236. * @type {number}
  30237. * @default 0
  30238. */
  30239. this._cachedIndex = 0;
  30240. /**
  30241. * The result buffer.
  30242. *
  30243. * @type {TypedArray}
  30244. */
  30245. this.resultBuffer = resultBuffer !== undefined ? resultBuffer : new sampleValues.constructor( sampleSize );
  30246. /**
  30247. * The sample values.
  30248. *
  30249. * @type {TypedArray}
  30250. */
  30251. this.sampleValues = sampleValues;
  30252. /**
  30253. * The value size.
  30254. *
  30255. * @type {TypedArray}
  30256. */
  30257. this.valueSize = sampleSize;
  30258. /**
  30259. * The interpolation settings.
  30260. *
  30261. * @type {?Object}
  30262. * @default null
  30263. */
  30264. this.settings = null;
  30265. /**
  30266. * The default settings object.
  30267. *
  30268. * @type {Object}
  30269. */
  30270. this.DefaultSettings_ = {};
  30271. }
  30272. /**
  30273. * Evaluate the interpolant at position `t`.
  30274. *
  30275. * @param {number} t - The interpolation factor.
  30276. * @return {TypedArray} The result buffer.
  30277. */
  30278. evaluate( t ) {
  30279. const pp = this.parameterPositions;
  30280. let i1 = this._cachedIndex,
  30281. t1 = pp[ i1 ],
  30282. t0 = pp[ i1 - 1 ];
  30283. validate_interval: {
  30284. seek: {
  30285. let right;
  30286. linear_scan: {
  30287. //- See http://jsperf.com/comparison-to-undefined/3
  30288. //- slower code:
  30289. //-
  30290. //- if ( t >= t1 || t1 === undefined ) {
  30291. forward_scan: if ( ! ( t < t1 ) ) {
  30292. for ( let giveUpAt = i1 + 2; ; ) {
  30293. if ( t1 === undefined ) {
  30294. if ( t < t0 ) break forward_scan;
  30295. // after end
  30296. i1 = pp.length;
  30297. this._cachedIndex = i1;
  30298. return this.copySampleValue_( i1 - 1 );
  30299. }
  30300. if ( i1 === giveUpAt ) break; // this loop
  30301. t0 = t1;
  30302. t1 = pp[ ++ i1 ];
  30303. if ( t < t1 ) {
  30304. // we have arrived at the sought interval
  30305. break seek;
  30306. }
  30307. }
  30308. // prepare binary search on the right side of the index
  30309. right = pp.length;
  30310. break linear_scan;
  30311. }
  30312. //- slower code:
  30313. //- if ( t < t0 || t0 === undefined ) {
  30314. if ( ! ( t >= t0 ) ) {
  30315. // looping?
  30316. const t1global = pp[ 1 ];
  30317. if ( t < t1global ) {
  30318. i1 = 2; // + 1, using the scan for the details
  30319. t0 = t1global;
  30320. }
  30321. // linear reverse scan
  30322. for ( let giveUpAt = i1 - 2; ; ) {
  30323. if ( t0 === undefined ) {
  30324. // before start
  30325. this._cachedIndex = 0;
  30326. return this.copySampleValue_( 0 );
  30327. }
  30328. if ( i1 === giveUpAt ) break; // this loop
  30329. t1 = t0;
  30330. t0 = pp[ -- i1 - 1 ];
  30331. if ( t >= t0 ) {
  30332. // we have arrived at the sought interval
  30333. break seek;
  30334. }
  30335. }
  30336. // prepare binary search on the left side of the index
  30337. right = i1;
  30338. i1 = 0;
  30339. break linear_scan;
  30340. }
  30341. // the interval is valid
  30342. break validate_interval;
  30343. } // linear scan
  30344. // binary search
  30345. while ( i1 < right ) {
  30346. const mid = ( i1 + right ) >>> 1;
  30347. if ( t < pp[ mid ] ) {
  30348. right = mid;
  30349. } else {
  30350. i1 = mid + 1;
  30351. }
  30352. }
  30353. t1 = pp[ i1 ];
  30354. t0 = pp[ i1 - 1 ];
  30355. // check boundary cases, again
  30356. if ( t0 === undefined ) {
  30357. this._cachedIndex = 0;
  30358. return this.copySampleValue_( 0 );
  30359. }
  30360. if ( t1 === undefined ) {
  30361. i1 = pp.length;
  30362. this._cachedIndex = i1;
  30363. return this.copySampleValue_( i1 - 1 );
  30364. }
  30365. } // seek
  30366. this._cachedIndex = i1;
  30367. this.intervalChanged_( i1, t0, t1 );
  30368. } // validate_interval
  30369. return this.interpolate_( i1, t0, t, t1 );
  30370. }
  30371. /**
  30372. * Returns the interpolation settings.
  30373. *
  30374. * @return {Object} The interpolation settings.
  30375. */
  30376. getSettings_() {
  30377. return this.settings || this.DefaultSettings_;
  30378. }
  30379. /**
  30380. * Copies a sample value to the result buffer.
  30381. *
  30382. * @param {number} index - An index into the sample value buffer.
  30383. * @return {TypedArray} The result buffer.
  30384. */
  30385. copySampleValue_( index ) {
  30386. // copies a sample value to the result buffer
  30387. const result = this.resultBuffer,
  30388. values = this.sampleValues,
  30389. stride = this.valueSize,
  30390. offset = index * stride;
  30391. for ( let i = 0; i !== stride; ++ i ) {
  30392. result[ i ] = values[ offset + i ];
  30393. }
  30394. return result;
  30395. }
  30396. /**
  30397. * Copies a sample value to the result buffer.
  30398. *
  30399. * @abstract
  30400. * @param {number} i1 - An index into the sample value buffer.
  30401. * @param {number} t0 - The previous interpolation factor.
  30402. * @param {number} t - The current interpolation factor.
  30403. * @param {number} t1 - The next interpolation factor.
  30404. * @return {TypedArray} The result buffer.
  30405. */
  30406. interpolate_( /* i1, t0, t, t1 */ ) {
  30407. throw new Error( 'call to abstract method' );
  30408. // implementations shall return this.resultBuffer
  30409. }
  30410. /**
  30411. * Optional method that is executed when the interval has changed.
  30412. *
  30413. * @param {number} i1 - An index into the sample value buffer.
  30414. * @param {number} t0 - The previous interpolation factor.
  30415. * @param {number} t - The current interpolation factor.
  30416. */
  30417. intervalChanged_( /* i1, t0, t1 */ ) {
  30418. // empty
  30419. }
  30420. }
  30421. /**
  30422. * Fast and simple cubic spline interpolant.
  30423. *
  30424. * It was derived from a Hermitian construction setting the first derivative
  30425. * at each sample position to the linear slope between neighboring positions
  30426. * over their parameter interval.
  30427. *
  30428. * @augments Interpolant
  30429. */
  30430. class CubicInterpolant extends Interpolant {
  30431. /**
  30432. * Constructs a new cubic interpolant.
  30433. *
  30434. * @param {TypedArray} parameterPositions - The parameter positions hold the interpolation factors.
  30435. * @param {TypedArray} sampleValues - The sample values.
  30436. * @param {number} sampleSize - The sample size
  30437. * @param {TypedArray} [resultBuffer] - The result buffer.
  30438. */
  30439. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  30440. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  30441. this._weightPrev = -0;
  30442. this._offsetPrev = -0;
  30443. this._weightNext = -0;
  30444. this._offsetNext = -0;
  30445. this.DefaultSettings_ = {
  30446. endingStart: ZeroCurvatureEnding,
  30447. endingEnd: ZeroCurvatureEnding
  30448. };
  30449. }
  30450. intervalChanged_( i1, t0, t1 ) {
  30451. const pp = this.parameterPositions;
  30452. let iPrev = i1 - 2,
  30453. iNext = i1 + 1,
  30454. tPrev = pp[ iPrev ],
  30455. tNext = pp[ iNext ];
  30456. if ( tPrev === undefined ) {
  30457. switch ( this.getSettings_().endingStart ) {
  30458. case ZeroSlopeEnding:
  30459. // f'(t0) = 0
  30460. iPrev = i1;
  30461. tPrev = 2 * t0 - t1;
  30462. break;
  30463. case WrapAroundEnding:
  30464. // use the other end of the curve
  30465. iPrev = pp.length - 2;
  30466. tPrev = t0 + pp[ iPrev ] - pp[ iPrev + 1 ];
  30467. break;
  30468. default: // ZeroCurvatureEnding
  30469. // f''(t0) = 0 a.k.a. Natural Spline
  30470. iPrev = i1;
  30471. tPrev = t1;
  30472. }
  30473. }
  30474. if ( tNext === undefined ) {
  30475. switch ( this.getSettings_().endingEnd ) {
  30476. case ZeroSlopeEnding:
  30477. // f'(tN) = 0
  30478. iNext = i1;
  30479. tNext = 2 * t1 - t0;
  30480. break;
  30481. case WrapAroundEnding:
  30482. // use the other end of the curve
  30483. iNext = 1;
  30484. tNext = t1 + pp[ 1 ] - pp[ 0 ];
  30485. break;
  30486. default: // ZeroCurvatureEnding
  30487. // f''(tN) = 0, a.k.a. Natural Spline
  30488. iNext = i1 - 1;
  30489. tNext = t0;
  30490. }
  30491. }
  30492. const halfDt = ( t1 - t0 ) * 0.5,
  30493. stride = this.valueSize;
  30494. this._weightPrev = halfDt / ( t0 - tPrev );
  30495. this._weightNext = halfDt / ( tNext - t1 );
  30496. this._offsetPrev = iPrev * stride;
  30497. this._offsetNext = iNext * stride;
  30498. }
  30499. interpolate_( i1, t0, t, t1 ) {
  30500. const result = this.resultBuffer,
  30501. values = this.sampleValues,
  30502. stride = this.valueSize,
  30503. o1 = i1 * stride, o0 = o1 - stride,
  30504. oP = this._offsetPrev, oN = this._offsetNext,
  30505. wP = this._weightPrev, wN = this._weightNext,
  30506. p = ( t - t0 ) / ( t1 - t0 ),
  30507. pp = p * p,
  30508. ppp = pp * p;
  30509. // evaluate polynomials
  30510. const sP = - wP * ppp + 2 * wP * pp - wP * p;
  30511. const s0 = ( 1 + wP ) * ppp + ( -1.5 - 2 * wP ) * pp + ( -0.5 + wP ) * p + 1;
  30512. const s1 = ( -1 - wN ) * ppp + ( 1.5 + wN ) * pp + 0.5 * p;
  30513. const sN = wN * ppp - wN * pp;
  30514. // combine data linearly
  30515. for ( let i = 0; i !== stride; ++ i ) {
  30516. result[ i ] =
  30517. sP * values[ oP + i ] +
  30518. s0 * values[ o0 + i ] +
  30519. s1 * values[ o1 + i ] +
  30520. sN * values[ oN + i ];
  30521. }
  30522. return result;
  30523. }
  30524. }
  30525. /**
  30526. * A basic linear interpolant.
  30527. *
  30528. * @augments Interpolant
  30529. */
  30530. class LinearInterpolant extends Interpolant {
  30531. /**
  30532. * Constructs a new linear interpolant.
  30533. *
  30534. * @param {TypedArray} parameterPositions - The parameter positions hold the interpolation factors.
  30535. * @param {TypedArray} sampleValues - The sample values.
  30536. * @param {number} sampleSize - The sample size
  30537. * @param {TypedArray} [resultBuffer] - The result buffer.
  30538. */
  30539. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  30540. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  30541. }
  30542. interpolate_( i1, t0, t, t1 ) {
  30543. const result = this.resultBuffer,
  30544. values = this.sampleValues,
  30545. stride = this.valueSize,
  30546. offset1 = i1 * stride,
  30547. offset0 = offset1 - stride,
  30548. weight1 = ( t - t0 ) / ( t1 - t0 ),
  30549. weight0 = 1 - weight1;
  30550. for ( let i = 0; i !== stride; ++ i ) {
  30551. result[ i ] =
  30552. values[ offset0 + i ] * weight0 +
  30553. values[ offset1 + i ] * weight1;
  30554. }
  30555. return result;
  30556. }
  30557. }
  30558. /**
  30559. * Interpolant that evaluates to the sample value at the position preceding
  30560. * the parameter.
  30561. *
  30562. * @augments Interpolant
  30563. */
  30564. class DiscreteInterpolant extends Interpolant {
  30565. /**
  30566. * Constructs a new discrete interpolant.
  30567. *
  30568. * @param {TypedArray} parameterPositions - The parameter positions hold the interpolation factors.
  30569. * @param {TypedArray} sampleValues - The sample values.
  30570. * @param {number} sampleSize - The sample size
  30571. * @param {TypedArray} [resultBuffer] - The result buffer.
  30572. */
  30573. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  30574. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  30575. }
  30576. interpolate_( i1 /*, t0, t, t1 */ ) {
  30577. return this.copySampleValue_( i1 - 1 );
  30578. }
  30579. }
  30580. /**
  30581. * Represents s a timed sequence of keyframes, which are composed of lists of
  30582. * times and related values, and which are used to animate a specific property
  30583. * of an object.
  30584. */
  30585. class KeyframeTrack {
  30586. /**
  30587. * Constructs a new keyframe track.
  30588. *
  30589. * @param {string} name - The keyframe track's name.
  30590. * @param {Array<number>} times - A list of keyframe times.
  30591. * @param {Array<number>} values - A list of keyframe values.
  30592. * @param {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)} [interpolation] - The interpolation type.
  30593. */
  30594. constructor( name, times, values, interpolation ) {
  30595. if ( name === undefined ) throw new Error( 'THREE.KeyframeTrack: track name is undefined' );
  30596. if ( times === undefined || times.length === 0 ) throw new Error( 'THREE.KeyframeTrack: no keyframes in track named ' + name );
  30597. /**
  30598. * The track's name can refer to morph targets or bones or
  30599. * possibly other values within an animated object. See {@link PropertyBinding#parseTrackName}
  30600. * for the forms of strings that can be parsed for property binding.
  30601. *
  30602. * @type {string}
  30603. */
  30604. this.name = name;
  30605. /**
  30606. * The keyframe times.
  30607. *
  30608. * @type {Float32Array}
  30609. */
  30610. this.times = convertArray( times, this.TimeBufferType );
  30611. /**
  30612. * The keyframe values.
  30613. *
  30614. * @type {Float32Array}
  30615. */
  30616. this.values = convertArray( values, this.ValueBufferType );
  30617. this.setInterpolation( interpolation || this.DefaultInterpolation );
  30618. }
  30619. /**
  30620. * Converts the keyframe track to JSON.
  30621. *
  30622. * @static
  30623. * @param {KeyframeTrack} track - The keyframe track to serialize.
  30624. * @return {Object} The serialized keyframe track as JSON.
  30625. */
  30626. static toJSON( track ) {
  30627. const trackType = track.constructor;
  30628. let json;
  30629. // derived classes can define a static toJSON method
  30630. if ( trackType.toJSON !== this.toJSON ) {
  30631. json = trackType.toJSON( track );
  30632. } else {
  30633. // by default, we assume the data can be serialized as-is
  30634. json = {
  30635. 'name': track.name,
  30636. 'times': convertArray( track.times, Array ),
  30637. 'values': convertArray( track.values, Array )
  30638. };
  30639. const interpolation = track.getInterpolation();
  30640. if ( interpolation !== track.DefaultInterpolation ) {
  30641. json.interpolation = interpolation;
  30642. }
  30643. }
  30644. json.type = track.ValueTypeName; // mandatory
  30645. return json;
  30646. }
  30647. /**
  30648. * Factory method for creating a new discrete interpolant.
  30649. *
  30650. * @static
  30651. * @param {TypedArray} [result] - The result buffer.
  30652. * @return {DiscreteInterpolant} The new interpolant.
  30653. */
  30654. InterpolantFactoryMethodDiscrete( result ) {
  30655. return new DiscreteInterpolant( this.times, this.values, this.getValueSize(), result );
  30656. }
  30657. /**
  30658. * Factory method for creating a new linear interpolant.
  30659. *
  30660. * @static
  30661. * @param {TypedArray} [result] - The result buffer.
  30662. * @return {LinearInterpolant} The new interpolant.
  30663. */
  30664. InterpolantFactoryMethodLinear( result ) {
  30665. return new LinearInterpolant( this.times, this.values, this.getValueSize(), result );
  30666. }
  30667. /**
  30668. * Factory method for creating a new smooth interpolant.
  30669. *
  30670. * @static
  30671. * @param {TypedArray} [result] - The result buffer.
  30672. * @return {CubicInterpolant} The new interpolant.
  30673. */
  30674. InterpolantFactoryMethodSmooth( result ) {
  30675. return new CubicInterpolant( this.times, this.values, this.getValueSize(), result );
  30676. }
  30677. /**
  30678. * Defines the interpolation factor method for this keyframe track.
  30679. *
  30680. * @param {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)} interpolation - The interpolation type.
  30681. * @return {KeyframeTrack} A reference to this keyframe track.
  30682. */
  30683. setInterpolation( interpolation ) {
  30684. let factoryMethod;
  30685. switch ( interpolation ) {
  30686. case InterpolateDiscrete:
  30687. factoryMethod = this.InterpolantFactoryMethodDiscrete;
  30688. break;
  30689. case InterpolateLinear:
  30690. factoryMethod = this.InterpolantFactoryMethodLinear;
  30691. break;
  30692. case InterpolateSmooth:
  30693. factoryMethod = this.InterpolantFactoryMethodSmooth;
  30694. break;
  30695. }
  30696. if ( factoryMethod === undefined ) {
  30697. const message = 'unsupported interpolation for ' +
  30698. this.ValueTypeName + ' keyframe track named ' + this.name;
  30699. if ( this.createInterpolant === undefined ) {
  30700. // fall back to default, unless the default itself is messed up
  30701. if ( interpolation !== this.DefaultInterpolation ) {
  30702. this.setInterpolation( this.DefaultInterpolation );
  30703. } else {
  30704. throw new Error( message ); // fatal, in this case
  30705. }
  30706. }
  30707. console.warn( 'THREE.KeyframeTrack:', message );
  30708. return this;
  30709. }
  30710. this.createInterpolant = factoryMethod;
  30711. return this;
  30712. }
  30713. /**
  30714. * Returns the current interpolation type.
  30715. *
  30716. * @return {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)} The interpolation type.
  30717. */
  30718. getInterpolation() {
  30719. switch ( this.createInterpolant ) {
  30720. case this.InterpolantFactoryMethodDiscrete:
  30721. return InterpolateDiscrete;
  30722. case this.InterpolantFactoryMethodLinear:
  30723. return InterpolateLinear;
  30724. case this.InterpolantFactoryMethodSmooth:
  30725. return InterpolateSmooth;
  30726. }
  30727. }
  30728. /**
  30729. * Returns the value size.
  30730. *
  30731. * @return {number} The value size.
  30732. */
  30733. getValueSize() {
  30734. return this.values.length / this.times.length;
  30735. }
  30736. /**
  30737. * Moves all keyframes either forward or backward in time.
  30738. *
  30739. * @param {number} timeOffset - The offset to move the time values.
  30740. * @return {KeyframeTrack} A reference to this keyframe track.
  30741. */
  30742. shift( timeOffset ) {
  30743. if ( timeOffset !== 0.0 ) {
  30744. const times = this.times;
  30745. for ( let i = 0, n = times.length; i !== n; ++ i ) {
  30746. times[ i ] += timeOffset;
  30747. }
  30748. }
  30749. return this;
  30750. }
  30751. /**
  30752. * Scale all keyframe times by a factor (useful for frame - seconds conversions).
  30753. *
  30754. * @param {number} timeScale - The time scale.
  30755. * @return {KeyframeTrack} A reference to this keyframe track.
  30756. */
  30757. scale( timeScale ) {
  30758. if ( timeScale !== 1.0 ) {
  30759. const times = this.times;
  30760. for ( let i = 0, n = times.length; i !== n; ++ i ) {
  30761. times[ i ] *= timeScale;
  30762. }
  30763. }
  30764. return this;
  30765. }
  30766. /**
  30767. * Removes keyframes before and after animation without changing any values within the defined time range.
  30768. *
  30769. * Note: The method does not shift around keys to the start of the track time, because for interpolated
  30770. * keys this will change their values
  30771. *
  30772. * @param {number} startTime - The start time.
  30773. * @param {number} endTime - The end time.
  30774. * @return {KeyframeTrack} A reference to this keyframe track.
  30775. */
  30776. trim( startTime, endTime ) {
  30777. const times = this.times,
  30778. nKeys = times.length;
  30779. let from = 0,
  30780. to = nKeys - 1;
  30781. while ( from !== nKeys && times[ from ] < startTime ) {
  30782. ++ from;
  30783. }
  30784. while ( to !== -1 && times[ to ] > endTime ) {
  30785. -- to;
  30786. }
  30787. ++ to; // inclusive -> exclusive bound
  30788. if ( from !== 0 || to !== nKeys ) {
  30789. // empty tracks are forbidden, so keep at least one keyframe
  30790. if ( from >= to ) {
  30791. to = Math.max( to, 1 );
  30792. from = to - 1;
  30793. }
  30794. const stride = this.getValueSize();
  30795. this.times = times.slice( from, to );
  30796. this.values = this.values.slice( from * stride, to * stride );
  30797. }
  30798. return this;
  30799. }
  30800. /**
  30801. * Performs minimal validation on the keyframe track. Returns `true` if the values
  30802. * are valid.
  30803. *
  30804. * @return {boolean} Whether the keyframes are valid or not.
  30805. */
  30806. validate() {
  30807. let valid = true;
  30808. const valueSize = this.getValueSize();
  30809. if ( valueSize - Math.floor( valueSize ) !== 0 ) {
  30810. console.error( 'THREE.KeyframeTrack: Invalid value size in track.', this );
  30811. valid = false;
  30812. }
  30813. const times = this.times,
  30814. values = this.values,
  30815. nKeys = times.length;
  30816. if ( nKeys === 0 ) {
  30817. console.error( 'THREE.KeyframeTrack: Track is empty.', this );
  30818. valid = false;
  30819. }
  30820. let prevTime = null;
  30821. for ( let i = 0; i !== nKeys; i ++ ) {
  30822. const currTime = times[ i ];
  30823. if ( typeof currTime === 'number' && isNaN( currTime ) ) {
  30824. console.error( 'THREE.KeyframeTrack: Time is not a valid number.', this, i, currTime );
  30825. valid = false;
  30826. break;
  30827. }
  30828. if ( prevTime !== null && prevTime > currTime ) {
  30829. console.error( 'THREE.KeyframeTrack: Out of order keys.', this, i, currTime, prevTime );
  30830. valid = false;
  30831. break;
  30832. }
  30833. prevTime = currTime;
  30834. }
  30835. if ( values !== undefined ) {
  30836. if ( isTypedArray( values ) ) {
  30837. for ( let i = 0, n = values.length; i !== n; ++ i ) {
  30838. const value = values[ i ];
  30839. if ( isNaN( value ) ) {
  30840. console.error( 'THREE.KeyframeTrack: Value is not a valid number.', this, i, value );
  30841. valid = false;
  30842. break;
  30843. }
  30844. }
  30845. }
  30846. }
  30847. return valid;
  30848. }
  30849. /**
  30850. * Optimizes this keyframe track by removing equivalent sequential keys (which are
  30851. * common in morph target sequences).
  30852. *
  30853. * @return {AnimationClip} A reference to this animation clip.
  30854. */
  30855. optimize() {
  30856. // (0,0,0,0,1,1,1,0,0,0,0,0,0,0) --> (0,0,1,1,0,0)
  30857. // times or values may be shared with other tracks, so overwriting is unsafe
  30858. const times = this.times.slice(),
  30859. values = this.values.slice(),
  30860. stride = this.getValueSize(),
  30861. smoothInterpolation = this.getInterpolation() === InterpolateSmooth,
  30862. lastIndex = times.length - 1;
  30863. let writeIndex = 1;
  30864. for ( let i = 1; i < lastIndex; ++ i ) {
  30865. let keep = false;
  30866. const time = times[ i ];
  30867. const timeNext = times[ i + 1 ];
  30868. // remove adjacent keyframes scheduled at the same time
  30869. if ( time !== timeNext && ( i !== 1 || time !== times[ 0 ] ) ) {
  30870. if ( ! smoothInterpolation ) {
  30871. // remove unnecessary keyframes same as their neighbors
  30872. const offset = i * stride,
  30873. offsetP = offset - stride,
  30874. offsetN = offset + stride;
  30875. for ( let j = 0; j !== stride; ++ j ) {
  30876. const value = values[ offset + j ];
  30877. if ( value !== values[ offsetP + j ] ||
  30878. value !== values[ offsetN + j ] ) {
  30879. keep = true;
  30880. break;
  30881. }
  30882. }
  30883. } else {
  30884. keep = true;
  30885. }
  30886. }
  30887. // in-place compaction
  30888. if ( keep ) {
  30889. if ( i !== writeIndex ) {
  30890. times[ writeIndex ] = times[ i ];
  30891. const readOffset = i * stride,
  30892. writeOffset = writeIndex * stride;
  30893. for ( let j = 0; j !== stride; ++ j ) {
  30894. values[ writeOffset + j ] = values[ readOffset + j ];
  30895. }
  30896. }
  30897. ++ writeIndex;
  30898. }
  30899. }
  30900. // flush last keyframe (compaction looks ahead)
  30901. if ( lastIndex > 0 ) {
  30902. times[ writeIndex ] = times[ lastIndex ];
  30903. for ( let readOffset = lastIndex * stride, writeOffset = writeIndex * stride, j = 0; j !== stride; ++ j ) {
  30904. values[ writeOffset + j ] = values[ readOffset + j ];
  30905. }
  30906. ++ writeIndex;
  30907. }
  30908. if ( writeIndex !== times.length ) {
  30909. this.times = times.slice( 0, writeIndex );
  30910. this.values = values.slice( 0, writeIndex * stride );
  30911. } else {
  30912. this.times = times;
  30913. this.values = values;
  30914. }
  30915. return this;
  30916. }
  30917. /**
  30918. * Returns a new keyframe track with copied values from this instance.
  30919. *
  30920. * @return {KeyframeTrack} A clone of this instance.
  30921. */
  30922. clone() {
  30923. const times = this.times.slice();
  30924. const values = this.values.slice();
  30925. const TypedKeyframeTrack = this.constructor;
  30926. const track = new TypedKeyframeTrack( this.name, times, values );
  30927. // Interpolant argument to constructor is not saved, so copy the factory method directly.
  30928. track.createInterpolant = this.createInterpolant;
  30929. return track;
  30930. }
  30931. }
  30932. /**
  30933. * The value type name.
  30934. *
  30935. * @type {String}
  30936. * @default ''
  30937. */
  30938. KeyframeTrack.prototype.ValueTypeName = '';
  30939. /**
  30940. * The time buffer type of this keyframe track.
  30941. *
  30942. * @type {TypedArray|Array}
  30943. * @default Float32Array.constructor
  30944. */
  30945. KeyframeTrack.prototype.TimeBufferType = Float32Array;
  30946. /**
  30947. * The value buffer type of this keyframe track.
  30948. *
  30949. * @type {TypedArray|Array}
  30950. * @default Float32Array.constructor
  30951. */
  30952. KeyframeTrack.prototype.ValueBufferType = Float32Array;
  30953. /**
  30954. * The default interpolation type of this keyframe track.
  30955. *
  30956. * @type {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)}
  30957. * @default InterpolateLinear
  30958. */
  30959. KeyframeTrack.prototype.DefaultInterpolation = InterpolateLinear;
  30960. /**
  30961. * A track for boolean keyframe values.
  30962. *
  30963. * @augments KeyframeTrack
  30964. */
  30965. class BooleanKeyframeTrack extends KeyframeTrack {
  30966. /**
  30967. * Constructs a new boolean keyframe track.
  30968. *
  30969. * This keyframe track type has no `interpolation` parameter because the
  30970. * interpolation is always discrete.
  30971. *
  30972. * @param {string} name - The keyframe track's name.
  30973. * @param {Array<number>} times - A list of keyframe times.
  30974. * @param {Array<number>} values - A list of keyframe values.
  30975. */
  30976. constructor( name, times, values ) {
  30977. super( name, times, values );
  30978. }
  30979. }
  30980. /**
  30981. * The value type name.
  30982. *
  30983. * @type {String}
  30984. * @default 'bool'
  30985. */
  30986. BooleanKeyframeTrack.prototype.ValueTypeName = 'bool';
  30987. /**
  30988. * The value buffer type of this keyframe track.
  30989. *
  30990. * @type {TypedArray|Array}
  30991. * @default Array.constructor
  30992. */
  30993. BooleanKeyframeTrack.prototype.ValueBufferType = Array;
  30994. /**
  30995. * The default interpolation type of this keyframe track.
  30996. *
  30997. * @type {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)}
  30998. * @default InterpolateDiscrete
  30999. */
  31000. BooleanKeyframeTrack.prototype.DefaultInterpolation = InterpolateDiscrete;
  31001. BooleanKeyframeTrack.prototype.InterpolantFactoryMethodLinear = undefined;
  31002. BooleanKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  31003. /**
  31004. * A track for color keyframe values.
  31005. *
  31006. * @augments KeyframeTrack
  31007. */
  31008. class ColorKeyframeTrack extends KeyframeTrack {
  31009. /**
  31010. * Constructs a new color keyframe track.
  31011. *
  31012. * @param {string} name - The keyframe track's name.
  31013. * @param {Array<number>} times - A list of keyframe times.
  31014. * @param {Array<number>} values - A list of keyframe values.
  31015. * @param {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)} [interpolation] - The interpolation type.
  31016. */
  31017. constructor( name, times, values, interpolation ) {
  31018. super( name, times, values, interpolation );
  31019. }
  31020. }
  31021. /**
  31022. * The value type name.
  31023. *
  31024. * @type {String}
  31025. * @default 'color'
  31026. */
  31027. ColorKeyframeTrack.prototype.ValueTypeName = 'color';
  31028. /**
  31029. * A track for numeric keyframe values.
  31030. *
  31031. * @augments KeyframeTrack
  31032. */
  31033. class NumberKeyframeTrack extends KeyframeTrack {
  31034. /**
  31035. * Constructs a new number keyframe track.
  31036. *
  31037. * @param {string} name - The keyframe track's name.
  31038. * @param {Array<number>} times - A list of keyframe times.
  31039. * @param {Array<number>} values - A list of keyframe values.
  31040. * @param {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)} [interpolation] - The interpolation type.
  31041. */
  31042. constructor( name, times, values, interpolation ) {
  31043. super( name, times, values, interpolation );
  31044. }
  31045. }
  31046. /**
  31047. * The value type name.
  31048. *
  31049. * @type {String}
  31050. * @default 'number'
  31051. */
  31052. NumberKeyframeTrack.prototype.ValueTypeName = 'number';
  31053. /**
  31054. * Spherical linear unit quaternion interpolant.
  31055. *
  31056. * @augments Interpolant
  31057. */
  31058. class QuaternionLinearInterpolant extends Interpolant {
  31059. /**
  31060. * Constructs a new SLERP interpolant.
  31061. *
  31062. * @param {TypedArray} parameterPositions - The parameter positions hold the interpolation factors.
  31063. * @param {TypedArray} sampleValues - The sample values.
  31064. * @param {number} sampleSize - The sample size
  31065. * @param {TypedArray} [resultBuffer] - The result buffer.
  31066. */
  31067. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  31068. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  31069. }
  31070. interpolate_( i1, t0, t, t1 ) {
  31071. const result = this.resultBuffer,
  31072. values = this.sampleValues,
  31073. stride = this.valueSize,
  31074. alpha = ( t - t0 ) / ( t1 - t0 );
  31075. let offset = i1 * stride;
  31076. for ( let end = offset + stride; offset !== end; offset += 4 ) {
  31077. Quaternion.slerpFlat( result, 0, values, offset - stride, values, offset, alpha );
  31078. }
  31079. return result;
  31080. }
  31081. }
  31082. /**
  31083. * A track for Quaternion keyframe values.
  31084. *
  31085. * @augments KeyframeTrack
  31086. */
  31087. class QuaternionKeyframeTrack extends KeyframeTrack {
  31088. /**
  31089. * Constructs a new Quaternion keyframe track.
  31090. *
  31091. * @param {string} name - The keyframe track's name.
  31092. * @param {Array<number>} times - A list of keyframe times.
  31093. * @param {Array<number>} values - A list of keyframe values.
  31094. * @param {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)} [interpolation] - The interpolation type.
  31095. */
  31096. constructor( name, times, values, interpolation ) {
  31097. super( name, times, values, interpolation );
  31098. }
  31099. /**
  31100. * Overwritten so the method returns Quaternion based interpolant.
  31101. *
  31102. * @static
  31103. * @param {TypedArray} [result] - The result buffer.
  31104. * @return {QuaternionLinearInterpolant} The new interpolant.
  31105. */
  31106. InterpolantFactoryMethodLinear( result ) {
  31107. return new QuaternionLinearInterpolant( this.times, this.values, this.getValueSize(), result );
  31108. }
  31109. }
  31110. /**
  31111. * The value type name.
  31112. *
  31113. * @type {String}
  31114. * @default 'quaternion'
  31115. */
  31116. QuaternionKeyframeTrack.prototype.ValueTypeName = 'quaternion';
  31117. // ValueBufferType is inherited
  31118. // DefaultInterpolation is inherited;
  31119. QuaternionKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  31120. /**
  31121. * A track for string keyframe values.
  31122. *
  31123. * @augments KeyframeTrack
  31124. */
  31125. class StringKeyframeTrack extends KeyframeTrack {
  31126. /**
  31127. * Constructs a new string keyframe track.
  31128. *
  31129. * This keyframe track type has no `interpolation` parameter because the
  31130. * interpolation is always discrete.
  31131. *
  31132. * @param {string} name - The keyframe track's name.
  31133. * @param {Array<number>} times - A list of keyframe times.
  31134. * @param {Array<number>} values - A list of keyframe values.
  31135. */
  31136. constructor( name, times, values ) {
  31137. super( name, times, values );
  31138. }
  31139. }
  31140. /**
  31141. * The value type name.
  31142. *
  31143. * @type {String}
  31144. * @default 'string'
  31145. */
  31146. StringKeyframeTrack.prototype.ValueTypeName = 'string';
  31147. /**
  31148. * The value buffer type of this keyframe track.
  31149. *
  31150. * @type {TypedArray|Array}
  31151. * @default Array.constructor
  31152. */
  31153. StringKeyframeTrack.prototype.ValueBufferType = Array;
  31154. /**
  31155. * The default interpolation type of this keyframe track.
  31156. *
  31157. * @type {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)}
  31158. * @default InterpolateDiscrete
  31159. */
  31160. StringKeyframeTrack.prototype.DefaultInterpolation = InterpolateDiscrete;
  31161. StringKeyframeTrack.prototype.InterpolantFactoryMethodLinear = undefined;
  31162. StringKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  31163. /**
  31164. * A track for vector keyframe values.
  31165. *
  31166. * @augments KeyframeTrack
  31167. */
  31168. class VectorKeyframeTrack extends KeyframeTrack {
  31169. /**
  31170. * Constructs a new vector keyframe track.
  31171. *
  31172. * @param {string} name - The keyframe track's name.
  31173. * @param {Array<number>} times - A list of keyframe times.
  31174. * @param {Array<number>} values - A list of keyframe values.
  31175. * @param {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)} [interpolation] - The interpolation type.
  31176. */
  31177. constructor( name, times, values, interpolation ) {
  31178. super( name, times, values, interpolation );
  31179. }
  31180. }
  31181. /**
  31182. * The value type name.
  31183. *
  31184. * @type {String}
  31185. * @default 'vector'
  31186. */
  31187. VectorKeyframeTrack.prototype.ValueTypeName = 'vector';
  31188. /**
  31189. * A reusable set of keyframe tracks which represent an animation.
  31190. */
  31191. class AnimationClip {
  31192. /**
  31193. * Constructs a new animation clip.
  31194. *
  31195. * Note: Instead of instantiating an AnimationClip directly with the constructor, you can
  31196. * use the static interface of this class for creating clips. In most cases though, animation clips
  31197. * will automatically be created by loaders when importing animated 3D assets.
  31198. *
  31199. * @param {string} [name=''] - The clip's name.
  31200. * @param {number} [duration=-1] - The clip's duration in seconds. If a negative value is passed,
  31201. * the duration will be calculated from the passed keyframes.
  31202. * @param {Array<KeyframeTrack>} tracks - An array of keyframe tracks.
  31203. * @param {(NormalAnimationBlendMode|AdditiveAnimationBlendMode)} [blendMode=NormalAnimationBlendMode] - Defines how the animation
  31204. * is blended/combined when two or more animations are simultaneously played.
  31205. */
  31206. constructor( name = '', duration = -1, tracks = [], blendMode = NormalAnimationBlendMode ) {
  31207. /**
  31208. * The clip's name.
  31209. *
  31210. * @type {string}
  31211. */
  31212. this.name = name;
  31213. /**
  31214. * An array of keyframe tracks.
  31215. *
  31216. * @type {Array<KeyframeTrack>}
  31217. */
  31218. this.tracks = tracks;
  31219. /**
  31220. * The clip's duration in seconds.
  31221. *
  31222. * @type {number}
  31223. */
  31224. this.duration = duration;
  31225. /**
  31226. * Defines how the animation is blended/combined when two or more animations
  31227. * are simultaneously played.
  31228. *
  31229. * @type {(NormalAnimationBlendMode|AdditiveAnimationBlendMode)}
  31230. */
  31231. this.blendMode = blendMode;
  31232. /**
  31233. * The UUID of the animation clip.
  31234. *
  31235. * @type {string}
  31236. * @readonly
  31237. */
  31238. this.uuid = generateUUID();
  31239. // this means it should figure out its duration by scanning the tracks
  31240. if ( this.duration < 0 ) {
  31241. this.resetDuration();
  31242. }
  31243. }
  31244. /**
  31245. * Factory method for creating an animation clip from the given JSON.
  31246. *
  31247. * @static
  31248. * @param {Object} json - The serialized animation clip.
  31249. * @return {AnimationClip} The new animation clip.
  31250. */
  31251. static parse( json ) {
  31252. const tracks = [],
  31253. jsonTracks = json.tracks,
  31254. frameTime = 1.0 / ( json.fps || 1.0 );
  31255. for ( let i = 0, n = jsonTracks.length; i !== n; ++ i ) {
  31256. tracks.push( parseKeyframeTrack( jsonTracks[ i ] ).scale( frameTime ) );
  31257. }
  31258. const clip = new this( json.name, json.duration, tracks, json.blendMode );
  31259. clip.uuid = json.uuid;
  31260. return clip;
  31261. }
  31262. /**
  31263. * Serializes the given animation clip into JSON.
  31264. *
  31265. * @static
  31266. * @param {AnimationClip} clip - The animation clip to serialize.
  31267. * @return {Object} The JSON object.
  31268. */
  31269. static toJSON( clip ) {
  31270. const tracks = [],
  31271. clipTracks = clip.tracks;
  31272. const json = {
  31273. 'name': clip.name,
  31274. 'duration': clip.duration,
  31275. 'tracks': tracks,
  31276. 'uuid': clip.uuid,
  31277. 'blendMode': clip.blendMode
  31278. };
  31279. for ( let i = 0, n = clipTracks.length; i !== n; ++ i ) {
  31280. tracks.push( KeyframeTrack.toJSON( clipTracks[ i ] ) );
  31281. }
  31282. return json;
  31283. }
  31284. /**
  31285. * Returns a new animation clip from the passed morph targets array of a
  31286. * geometry, taking a name and the number of frames per second.
  31287. *
  31288. * Note: The fps parameter is required, but the animation speed can be
  31289. * overridden via {@link AnimationAction#setDuration}.
  31290. *
  31291. * @static
  31292. * @param {string} name - The name of the animation clip.
  31293. * @param {Array<Object>} morphTargetSequence - A sequence of morph targets.
  31294. * @param {number} fps - The Frames-Per-Second value.
  31295. * @param {boolean} noLoop - Whether the clip should be no loop or not.
  31296. * @return {AnimationClip} The new animation clip.
  31297. */
  31298. static CreateFromMorphTargetSequence( name, morphTargetSequence, fps, noLoop ) {
  31299. const numMorphTargets = morphTargetSequence.length;
  31300. const tracks = [];
  31301. for ( let i = 0; i < numMorphTargets; i ++ ) {
  31302. let times = [];
  31303. let values = [];
  31304. times.push(
  31305. ( i + numMorphTargets - 1 ) % numMorphTargets,
  31306. i,
  31307. ( i + 1 ) % numMorphTargets );
  31308. values.push( 0, 1, 0 );
  31309. const order = getKeyframeOrder( times );
  31310. times = sortedArray( times, 1, order );
  31311. values = sortedArray( values, 1, order );
  31312. // if there is a key at the first frame, duplicate it as the
  31313. // last frame as well for perfect loop.
  31314. if ( ! noLoop && times[ 0 ] === 0 ) {
  31315. times.push( numMorphTargets );
  31316. values.push( values[ 0 ] );
  31317. }
  31318. tracks.push(
  31319. new NumberKeyframeTrack(
  31320. '.morphTargetInfluences[' + morphTargetSequence[ i ].name + ']',
  31321. times, values
  31322. ).scale( 1.0 / fps ) );
  31323. }
  31324. return new this( name, -1, tracks );
  31325. }
  31326. /**
  31327. * Searches for an animation clip by name, taking as its first parameter
  31328. * either an array of clips, or a mesh or geometry that contains an
  31329. * array named "animations" property.
  31330. *
  31331. * @static
  31332. * @param {(Array<AnimationClip>|Object3D)} objectOrClipArray - The array or object to search through.
  31333. * @param {string} name - The name to search for.
  31334. * @return {?AnimationClip} The found animation clip. Returns `null` if no clip has been found.
  31335. */
  31336. static findByName( objectOrClipArray, name ) {
  31337. let clipArray = objectOrClipArray;
  31338. if ( ! Array.isArray( objectOrClipArray ) ) {
  31339. const o = objectOrClipArray;
  31340. clipArray = o.geometry && o.geometry.animations || o.animations;
  31341. }
  31342. for ( let i = 0; i < clipArray.length; i ++ ) {
  31343. if ( clipArray[ i ].name === name ) {
  31344. return clipArray[ i ];
  31345. }
  31346. }
  31347. return null;
  31348. }
  31349. /**
  31350. * Returns an array of new AnimationClips created from the morph target
  31351. * sequences of a geometry, trying to sort morph target names into
  31352. * animation-group-based patterns like "Walk_001, Walk_002, Run_001, Run_002...".
  31353. *
  31354. * See {@link MD2Loader#parse} as an example for how the method should be used.
  31355. *
  31356. * @static
  31357. * @param {Array<Object>} morphTargets - A sequence of morph targets.
  31358. * @param {number} fps - The Frames-Per-Second value.
  31359. * @param {boolean} noLoop - Whether the clip should be no loop or not.
  31360. * @return {Array<AnimationClip>} An array of new animation clips.
  31361. */
  31362. static CreateClipsFromMorphTargetSequences( morphTargets, fps, noLoop ) {
  31363. const animationToMorphTargets = {};
  31364. // tested with https://regex101.com/ on trick sequences
  31365. // such flamingo_flyA_003, flamingo_run1_003, crdeath0059
  31366. const pattern = /^([\w-]*?)([\d]+)$/;
  31367. // sort morph target names into animation groups based
  31368. // patterns like Walk_001, Walk_002, Run_001, Run_002
  31369. for ( let i = 0, il = morphTargets.length; i < il; i ++ ) {
  31370. const morphTarget = morphTargets[ i ];
  31371. const parts = morphTarget.name.match( pattern );
  31372. if ( parts && parts.length > 1 ) {
  31373. const name = parts[ 1 ];
  31374. let animationMorphTargets = animationToMorphTargets[ name ];
  31375. if ( ! animationMorphTargets ) {
  31376. animationToMorphTargets[ name ] = animationMorphTargets = [];
  31377. }
  31378. animationMorphTargets.push( morphTarget );
  31379. }
  31380. }
  31381. const clips = [];
  31382. for ( const name in animationToMorphTargets ) {
  31383. clips.push( this.CreateFromMorphTargetSequence( name, animationToMorphTargets[ name ], fps, noLoop ) );
  31384. }
  31385. return clips;
  31386. }
  31387. /**
  31388. * Parses the `animation.hierarchy` format and returns a new animation clip.
  31389. *
  31390. * @static
  31391. * @deprecated since r175.
  31392. * @param {Object} animation - A serialized animation clip as JSON.
  31393. * @param {Array<Bones>} bones - An array of bones.
  31394. * @return {?AnimationClip} The new animation clip.
  31395. */
  31396. static parseAnimation( animation, bones ) {
  31397. console.warn( 'THREE.AnimationClip: parseAnimation() is deprecated and will be removed with r185' );
  31398. if ( ! animation ) {
  31399. console.error( 'THREE.AnimationClip: No animation in JSONLoader data.' );
  31400. return null;
  31401. }
  31402. const addNonemptyTrack = function ( trackType, trackName, animationKeys, propertyName, destTracks ) {
  31403. // only return track if there are actually keys.
  31404. if ( animationKeys.length !== 0 ) {
  31405. const times = [];
  31406. const values = [];
  31407. flattenJSON( animationKeys, times, values, propertyName );
  31408. // empty keys are filtered out, so check again
  31409. if ( times.length !== 0 ) {
  31410. destTracks.push( new trackType( trackName, times, values ) );
  31411. }
  31412. }
  31413. };
  31414. const tracks = [];
  31415. const clipName = animation.name || 'default';
  31416. const fps = animation.fps || 30;
  31417. const blendMode = animation.blendMode;
  31418. // automatic length determination in AnimationClip.
  31419. let duration = animation.length || -1;
  31420. const hierarchyTracks = animation.hierarchy || [];
  31421. for ( let h = 0; h < hierarchyTracks.length; h ++ ) {
  31422. const animationKeys = hierarchyTracks[ h ].keys;
  31423. // skip empty tracks
  31424. if ( ! animationKeys || animationKeys.length === 0 ) continue;
  31425. // process morph targets
  31426. if ( animationKeys[ 0 ].morphTargets ) {
  31427. // figure out all morph targets used in this track
  31428. const morphTargetNames = {};
  31429. let k;
  31430. for ( k = 0; k < animationKeys.length; k ++ ) {
  31431. if ( animationKeys[ k ].morphTargets ) {
  31432. for ( let m = 0; m < animationKeys[ k ].morphTargets.length; m ++ ) {
  31433. morphTargetNames[ animationKeys[ k ].morphTargets[ m ] ] = -1;
  31434. }
  31435. }
  31436. }
  31437. // create a track for each morph target with all zero
  31438. // morphTargetInfluences except for the keys in which
  31439. // the morphTarget is named.
  31440. for ( const morphTargetName in morphTargetNames ) {
  31441. const times = [];
  31442. const values = [];
  31443. for ( let m = 0; m !== animationKeys[ k ].morphTargets.length; ++ m ) {
  31444. const animationKey = animationKeys[ k ];
  31445. times.push( animationKey.time );
  31446. values.push( ( animationKey.morphTarget === morphTargetName ) ? 1 : 0 );
  31447. }
  31448. tracks.push( new NumberKeyframeTrack( '.morphTargetInfluence[' + morphTargetName + ']', times, values ) );
  31449. }
  31450. duration = morphTargetNames.length * fps;
  31451. } else {
  31452. // ...assume skeletal animation
  31453. const boneName = '.bones[' + bones[ h ].name + ']';
  31454. addNonemptyTrack(
  31455. VectorKeyframeTrack, boneName + '.position',
  31456. animationKeys, 'pos', tracks );
  31457. addNonemptyTrack(
  31458. QuaternionKeyframeTrack, boneName + '.quaternion',
  31459. animationKeys, 'rot', tracks );
  31460. addNonemptyTrack(
  31461. VectorKeyframeTrack, boneName + '.scale',
  31462. animationKeys, 'scl', tracks );
  31463. }
  31464. }
  31465. if ( tracks.length === 0 ) {
  31466. return null;
  31467. }
  31468. const clip = new this( clipName, duration, tracks, blendMode );
  31469. return clip;
  31470. }
  31471. /**
  31472. * Sets the duration of this clip to the duration of its longest keyframe track.
  31473. *
  31474. * @return {AnimationClip} A reference to this animation clip.
  31475. */
  31476. resetDuration() {
  31477. const tracks = this.tracks;
  31478. let duration = 0;
  31479. for ( let i = 0, n = tracks.length; i !== n; ++ i ) {
  31480. const track = this.tracks[ i ];
  31481. duration = Math.max( duration, track.times[ track.times.length - 1 ] );
  31482. }
  31483. this.duration = duration;
  31484. return this;
  31485. }
  31486. /**
  31487. * Trims all tracks to the clip's duration.
  31488. *
  31489. * @return {AnimationClip} A reference to this animation clip.
  31490. */
  31491. trim() {
  31492. for ( let i = 0; i < this.tracks.length; i ++ ) {
  31493. this.tracks[ i ].trim( 0, this.duration );
  31494. }
  31495. return this;
  31496. }
  31497. /**
  31498. * Performs minimal validation on each track in the clip. Returns `true` if all
  31499. * tracks are valid.
  31500. *
  31501. * @return {boolean} Whether the clip's keyframes are valid or not.
  31502. */
  31503. validate() {
  31504. let valid = true;
  31505. for ( let i = 0; i < this.tracks.length; i ++ ) {
  31506. valid = valid && this.tracks[ i ].validate();
  31507. }
  31508. return valid;
  31509. }
  31510. /**
  31511. * Optimizes each track by removing equivalent sequential keys (which are
  31512. * common in morph target sequences).
  31513. *
  31514. * @return {AnimationClip} A reference to this animation clip.
  31515. */
  31516. optimize() {
  31517. for ( let i = 0; i < this.tracks.length; i ++ ) {
  31518. this.tracks[ i ].optimize();
  31519. }
  31520. return this;
  31521. }
  31522. /**
  31523. * Returns a new animation clip with copied values from this instance.
  31524. *
  31525. * @return {AnimationClip} A clone of this instance.
  31526. */
  31527. clone() {
  31528. const tracks = [];
  31529. for ( let i = 0; i < this.tracks.length; i ++ ) {
  31530. tracks.push( this.tracks[ i ].clone() );
  31531. }
  31532. return new this.constructor( this.name, this.duration, tracks, this.blendMode );
  31533. }
  31534. /**
  31535. * Serializes this animation clip into JSON.
  31536. *
  31537. * @return {Object} The JSON object.
  31538. */
  31539. toJSON() {
  31540. return this.constructor.toJSON( this );
  31541. }
  31542. }
  31543. function getTrackTypeForValueTypeName( typeName ) {
  31544. switch ( typeName.toLowerCase() ) {
  31545. case 'scalar':
  31546. case 'double':
  31547. case 'float':
  31548. case 'number':
  31549. case 'integer':
  31550. return NumberKeyframeTrack;
  31551. case 'vector':
  31552. case 'vector2':
  31553. case 'vector3':
  31554. case 'vector4':
  31555. return VectorKeyframeTrack;
  31556. case 'color':
  31557. return ColorKeyframeTrack;
  31558. case 'quaternion':
  31559. return QuaternionKeyframeTrack;
  31560. case 'bool':
  31561. case 'boolean':
  31562. return BooleanKeyframeTrack;
  31563. case 'string':
  31564. return StringKeyframeTrack;
  31565. }
  31566. throw new Error( 'THREE.KeyframeTrack: Unsupported typeName: ' + typeName );
  31567. }
  31568. function parseKeyframeTrack( json ) {
  31569. if ( json.type === undefined ) {
  31570. throw new Error( 'THREE.KeyframeTrack: track type undefined, can not parse' );
  31571. }
  31572. const trackType = getTrackTypeForValueTypeName( json.type );
  31573. if ( json.times === undefined ) {
  31574. const times = [], values = [];
  31575. flattenJSON( json.keys, times, values, 'value' );
  31576. json.times = times;
  31577. json.values = values;
  31578. }
  31579. // derived classes can define a static parse method
  31580. if ( trackType.parse !== undefined ) {
  31581. return trackType.parse( json );
  31582. } else {
  31583. // by default, we assume a constructor compatible with the base
  31584. return new trackType( json.name, json.times, json.values, json.interpolation );
  31585. }
  31586. }
  31587. /**
  31588. * @class
  31589. * @classdesc A simple caching system, used internally by {@link FileLoader}.
  31590. * To enable caching across all loaders that use {@link FileLoader}, add `THREE.Cache.enabled = true.` once in your app.
  31591. * @hideconstructor
  31592. */
  31593. const Cache = {
  31594. /**
  31595. * Whether caching is enabled or not.
  31596. *
  31597. * @static
  31598. * @type {boolean}
  31599. * @default false
  31600. */
  31601. enabled: false,
  31602. /**
  31603. * A dictionary that holds cached files.
  31604. *
  31605. * @static
  31606. * @type {Object<string,Object>}
  31607. */
  31608. files: {},
  31609. /**
  31610. * Adds a cache entry with a key to reference the file. If this key already
  31611. * holds a file, it is overwritten.
  31612. *
  31613. * @static
  31614. * @param {string} key - The key to reference the cached file.
  31615. * @param {Object} file - The file to be cached.
  31616. */
  31617. add: function ( key, file ) {
  31618. if ( this.enabled === false ) return;
  31619. // console.log( 'THREE.Cache', 'Adding key:', key );
  31620. this.files[ key ] = file;
  31621. },
  31622. /**
  31623. * Gets the cached value for the given key.
  31624. *
  31625. * @static
  31626. * @param {string} key - The key to reference the cached file.
  31627. * @return {Object|undefined} The cached file. If the key does not exist `undefined` is returned.
  31628. */
  31629. get: function ( key ) {
  31630. if ( this.enabled === false ) return;
  31631. // console.log( 'THREE.Cache', 'Checking key:', key );
  31632. return this.files[ key ];
  31633. },
  31634. /**
  31635. * Removes the cached file associated with the given key.
  31636. *
  31637. * @static
  31638. * @param {string} key - The key to reference the cached file.
  31639. */
  31640. remove: function ( key ) {
  31641. delete this.files[ key ];
  31642. },
  31643. /**
  31644. * Remove all values from the cache.
  31645. *
  31646. * @static
  31647. */
  31648. clear: function () {
  31649. this.files = {};
  31650. }
  31651. };
  31652. /**
  31653. * Handles and keeps track of loaded and pending data. A default global
  31654. * instance of this class is created and used by loaders if not supplied
  31655. * manually.
  31656. *
  31657. * In general that should be sufficient, however there are times when it can
  31658. * be useful to have separate loaders - for example if you want to show
  31659. * separate loading bars for objects and textures.
  31660. *
  31661. * ```js
  31662. * const manager = new THREE.LoadingManager();
  31663. * manager.onLoad = () => console.log( 'Loading complete!' );
  31664. *
  31665. * const loader1 = new OBJLoader( manager );
  31666. * const loader2 = new ColladaLoader( manager );
  31667. * ```
  31668. */
  31669. class LoadingManager {
  31670. /**
  31671. * Constructs a new loading manager.
  31672. *
  31673. * @param {Function} [onLoad] - Executes when all items have been loaded.
  31674. * @param {Function} [onProgress] - Executes when single items have been loaded.
  31675. * @param {Function} [onError] - Executes when an error occurs.
  31676. */
  31677. constructor( onLoad, onProgress, onError ) {
  31678. const scope = this;
  31679. let isLoading = false;
  31680. let itemsLoaded = 0;
  31681. let itemsTotal = 0;
  31682. let urlModifier = undefined;
  31683. const handlers = [];
  31684. // Refer to #5689 for the reason why we don't set .onStart
  31685. // in the constructor
  31686. /**
  31687. * Executes when an item starts loading.
  31688. *
  31689. * @type {Function|undefined}
  31690. * @default undefined
  31691. */
  31692. this.onStart = undefined;
  31693. /**
  31694. * Executes when all items have been loaded.
  31695. *
  31696. * @type {Function|undefined}
  31697. * @default undefined
  31698. */
  31699. this.onLoad = onLoad;
  31700. /**
  31701. * Executes when single items have been loaded.
  31702. *
  31703. * @type {Function|undefined}
  31704. * @default undefined
  31705. */
  31706. this.onProgress = onProgress;
  31707. /**
  31708. * Executes when an error occurs.
  31709. *
  31710. * @type {Function|undefined}
  31711. * @default undefined
  31712. */
  31713. this.onError = onError;
  31714. /**
  31715. * This should be called by any loader using the manager when the loader
  31716. * starts loading an item.
  31717. *
  31718. * @param {string} url - The URL to load.
  31719. */
  31720. this.itemStart = function ( url ) {
  31721. itemsTotal ++;
  31722. if ( isLoading === false ) {
  31723. if ( scope.onStart !== undefined ) {
  31724. scope.onStart( url, itemsLoaded, itemsTotal );
  31725. }
  31726. }
  31727. isLoading = true;
  31728. };
  31729. /**
  31730. * This should be called by any loader using the manager when the loader
  31731. * ended loading an item.
  31732. *
  31733. * @param {string} url - The URL of the loaded item.
  31734. */
  31735. this.itemEnd = function ( url ) {
  31736. itemsLoaded ++;
  31737. if ( scope.onProgress !== undefined ) {
  31738. scope.onProgress( url, itemsLoaded, itemsTotal );
  31739. }
  31740. if ( itemsLoaded === itemsTotal ) {
  31741. isLoading = false;
  31742. if ( scope.onLoad !== undefined ) {
  31743. scope.onLoad();
  31744. }
  31745. }
  31746. };
  31747. /**
  31748. * This should be called by any loader using the manager when the loader
  31749. * encounters an error when loading an item.
  31750. *
  31751. * @param {string} url - The URL of the item that produces an error.
  31752. */
  31753. this.itemError = function ( url ) {
  31754. if ( scope.onError !== undefined ) {
  31755. scope.onError( url );
  31756. }
  31757. };
  31758. /**
  31759. * Given a URL, uses the URL modifier callback (if any) and returns a
  31760. * resolved URL. If no URL modifier is set, returns the original URL.
  31761. *
  31762. * @param {string} url - The URL to load.
  31763. * @return {string} The resolved URL.
  31764. */
  31765. this.resolveURL = function ( url ) {
  31766. if ( urlModifier ) {
  31767. return urlModifier( url );
  31768. }
  31769. return url;
  31770. };
  31771. /**
  31772. * If provided, the callback will be passed each resource URL before a
  31773. * request is sent. The callback may return the original URL, or a new URL to
  31774. * override loading behavior. This behavior can be used to load assets from
  31775. * .ZIP files, drag-and-drop APIs, and Data URIs.
  31776. *
  31777. * ```js
  31778. * const blobs = {'fish.gltf': blob1, 'diffuse.png': blob2, 'normal.png': blob3};
  31779. *
  31780. * const manager = new THREE.LoadingManager();
  31781. *
  31782. * // Initialize loading manager with URL callback.
  31783. * const objectURLs = [];
  31784. * manager.setURLModifier( ( url ) => {
  31785. *
  31786. * url = URL.createObjectURL( blobs[ url ] );
  31787. * objectURLs.push( url );
  31788. * return url;
  31789. *
  31790. * } );
  31791. *
  31792. * // Load as usual, then revoke the blob URLs.
  31793. * const loader = new GLTFLoader( manager );
  31794. * loader.load( 'fish.gltf', (gltf) => {
  31795. *
  31796. * scene.add( gltf.scene );
  31797. * objectURLs.forEach( ( url ) => URL.revokeObjectURL( url ) );
  31798. *
  31799. * } );
  31800. * ```
  31801. *
  31802. * @param {function(string):string} transform - URL modifier callback. Called with an URL and must return a resolved URL.
  31803. * @return {LoadingManager} A reference to this loading manager.
  31804. */
  31805. this.setURLModifier = function ( transform ) {
  31806. urlModifier = transform;
  31807. return this;
  31808. };
  31809. /**
  31810. * Registers a loader with the given regular expression. Can be used to
  31811. * define what loader should be used in order to load specific files. A
  31812. * typical use case is to overwrite the default loader for textures.
  31813. *
  31814. * ```js
  31815. * // add handler for TGA textures
  31816. * manager.addHandler( /\.tga$/i, new TGALoader() );
  31817. * ```
  31818. *
  31819. * @param {string} regex - A regular expression.
  31820. * @param {Loader} loader - A loader that should handle matched cases.
  31821. * @return {LoadingManager} A reference to this loading manager.
  31822. */
  31823. this.addHandler = function ( regex, loader ) {
  31824. handlers.push( regex, loader );
  31825. return this;
  31826. };
  31827. /**
  31828. * Removes the loader for the given regular expression.
  31829. *
  31830. * @param {string} regex - A regular expression.
  31831. * @return {LoadingManager} A reference to this loading manager.
  31832. */
  31833. this.removeHandler = function ( regex ) {
  31834. const index = handlers.indexOf( regex );
  31835. if ( index !== -1 ) {
  31836. handlers.splice( index, 2 );
  31837. }
  31838. return this;
  31839. };
  31840. /**
  31841. * Can be used to retrieve the registered loader for the given file path.
  31842. *
  31843. * @param {string} file - The file path.
  31844. * @return {?Loader} The registered loader. Returns `null` if no loader was found.
  31845. */
  31846. this.getHandler = function ( file ) {
  31847. for ( let i = 0, l = handlers.length; i < l; i += 2 ) {
  31848. const regex = handlers[ i ];
  31849. const loader = handlers[ i + 1 ];
  31850. if ( regex.global ) regex.lastIndex = 0; // see #17920
  31851. if ( regex.test( file ) ) {
  31852. return loader;
  31853. }
  31854. }
  31855. return null;
  31856. };
  31857. }
  31858. }
  31859. /**
  31860. * The global default loading manager.
  31861. *
  31862. * @constant
  31863. * @type {LoadingManager}
  31864. */
  31865. const DefaultLoadingManager = /*@__PURE__*/ new LoadingManager();
  31866. /**
  31867. * Abstract base class for loaders.
  31868. *
  31869. * @abstract
  31870. */
  31871. class Loader {
  31872. /**
  31873. * Constructs a new loader.
  31874. *
  31875. * @param {LoadingManager} [manager] - The loading manager.
  31876. */
  31877. constructor( manager ) {
  31878. /**
  31879. * The loading manager.
  31880. *
  31881. * @type {LoadingManager}
  31882. * @default DefaultLoadingManager
  31883. */
  31884. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  31885. /**
  31886. * The crossOrigin string to implement CORS for loading the url from a
  31887. * different domain that allows CORS.
  31888. *
  31889. * @type {string}
  31890. * @default 'anonymous'
  31891. */
  31892. this.crossOrigin = 'anonymous';
  31893. /**
  31894. * Whether the XMLHttpRequest uses credentials.
  31895. *
  31896. * @type {boolean}
  31897. * @default false
  31898. */
  31899. this.withCredentials = false;
  31900. /**
  31901. * The base path from which the asset will be loaded.
  31902. *
  31903. * @type {string}
  31904. */
  31905. this.path = '';
  31906. /**
  31907. * The base path from which additional resources like textures will be loaded.
  31908. *
  31909. * @type {string}
  31910. */
  31911. this.resourcePath = '';
  31912. /**
  31913. * The [request header]{@link https://developer.mozilla.org/en-US/docs/Glossary/Request_header}
  31914. * used in HTTP request.
  31915. *
  31916. * @type {Object<string, any>}
  31917. */
  31918. this.requestHeader = {};
  31919. }
  31920. /**
  31921. * This method needs to be implemented by all concrete loaders. It holds the
  31922. * logic for loading assets from the backend.
  31923. *
  31924. * @param {string} url - The path/URL of the file to be loaded.
  31925. * @param {Function} onLoad - Executed when the loading process has been finished.
  31926. * @param {onProgressCallback} [onProgress] - Executed while the loading is in progress.
  31927. * @param {onErrorCallback} [onError] - Executed when errors occur.
  31928. */
  31929. load( /* url, onLoad, onProgress, onError */ ) {}
  31930. /**
  31931. * A async version of {@link Loader#load}.
  31932. *
  31933. * @param {string} url - The path/URL of the file to be loaded.
  31934. * @param {onProgressCallback} [onProgress] - Executed while the loading is in progress.
  31935. * @return {Promise} A Promise that resolves when the asset has been loaded.
  31936. */
  31937. loadAsync( url, onProgress ) {
  31938. const scope = this;
  31939. return new Promise( function ( resolve, reject ) {
  31940. scope.load( url, resolve, onProgress, reject );
  31941. } );
  31942. }
  31943. /**
  31944. * This method needs to be implemented by all concrete loaders. It holds the
  31945. * logic for parsing the asset into three.js entities.
  31946. *
  31947. * @param {any} data - The data to parse.
  31948. */
  31949. parse( /* data */ ) {}
  31950. /**
  31951. * Sets the `crossOrigin` String to implement CORS for loading the URL
  31952. * from a different domain that allows CORS.
  31953. *
  31954. * @param {string} crossOrigin - The `crossOrigin` value.
  31955. * @return {Loader} A reference to this instance.
  31956. */
  31957. setCrossOrigin( crossOrigin ) {
  31958. this.crossOrigin = crossOrigin;
  31959. return this;
  31960. }
  31961. /**
  31962. * Whether the XMLHttpRequest uses credentials such as cookies, authorization
  31963. * headers or TLS client certificates, see [XMLHttpRequest.withCredentials]{@link https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/withCredentials}.
  31964. *
  31965. * Note: This setting has no effect if you are loading files locally or from the same domain.
  31966. *
  31967. * @param {boolean} value - The `withCredentials` value.
  31968. * @return {Loader} A reference to this instance.
  31969. */
  31970. setWithCredentials( value ) {
  31971. this.withCredentials = value;
  31972. return this;
  31973. }
  31974. /**
  31975. * Sets the base path for the asset.
  31976. *
  31977. * @param {string} path - The base path.
  31978. * @return {Loader} A reference to this instance.
  31979. */
  31980. setPath( path ) {
  31981. this.path = path;
  31982. return this;
  31983. }
  31984. /**
  31985. * Sets the base path for dependent resources like textures.
  31986. *
  31987. * @param {string} resourcePath - The resource path.
  31988. * @return {Loader} A reference to this instance.
  31989. */
  31990. setResourcePath( resourcePath ) {
  31991. this.resourcePath = resourcePath;
  31992. return this;
  31993. }
  31994. /**
  31995. * Sets the given request header.
  31996. *
  31997. * @param {Object} requestHeader - A [request header]{@link https://developer.mozilla.org/en-US/docs/Glossary/Request_header}
  31998. * for configuring the HTTP request.
  31999. * @return {Loader} A reference to this instance.
  32000. */
  32001. setRequestHeader( requestHeader ) {
  32002. this.requestHeader = requestHeader;
  32003. return this;
  32004. }
  32005. }
  32006. /**
  32007. * Callback for onProgress in loaders.
  32008. *
  32009. * @callback onProgressCallback
  32010. * @param {ProgressEvent} event - An instance of `ProgressEvent` that represents the current loading status.
  32011. */
  32012. /**
  32013. * Callback for onError in loaders.
  32014. *
  32015. * @callback onErrorCallback
  32016. * @param {Error} error - The error which occurred during the loading process.
  32017. */
  32018. /**
  32019. * The default material name that is used by loaders
  32020. * when creating materials for loaded 3D objects.
  32021. *
  32022. * Note: Not all loaders might honor this setting.
  32023. *
  32024. * @static
  32025. * @type {string}
  32026. * @default '__DEFAULT'
  32027. */
  32028. Loader.DEFAULT_MATERIAL_NAME = '__DEFAULT';
  32029. const loading = {};
  32030. class HttpError extends Error {
  32031. constructor( message, response ) {
  32032. super( message );
  32033. this.response = response;
  32034. }
  32035. }
  32036. /**
  32037. * A low level class for loading resources with the Fetch API, used internally by
  32038. * most loaders. It can also be used directly to load any file type that does
  32039. * not have a loader.
  32040. *
  32041. * This loader supports caching. If you want to use it, add `THREE.Cache.enabled = true;`
  32042. * once to your application.
  32043. *
  32044. * ```js
  32045. * const loader = new THREE.FileLoader();
  32046. * const data = await loader.loadAsync( 'example.txt' );
  32047. * ```
  32048. *
  32049. * @augments Loader
  32050. */
  32051. class FileLoader extends Loader {
  32052. /**
  32053. * Constructs a new file loader.
  32054. *
  32055. * @param {LoadingManager} [manager] - The loading manager.
  32056. */
  32057. constructor( manager ) {
  32058. super( manager );
  32059. /**
  32060. * The expected mime type.
  32061. *
  32062. * @type {string}
  32063. */
  32064. this.mimeType = '';
  32065. /**
  32066. * The expected response type.
  32067. *
  32068. * @type {('arraybuffer'|'blob'|'document'|'json'|'')}
  32069. * @default ''
  32070. */
  32071. this.responseType = '';
  32072. }
  32073. /**
  32074. * Starts loading from the given URL and pass the loaded response to the `onLoad()` callback.
  32075. *
  32076. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  32077. * @param {function(any)} onLoad - Executed when the loading process has been finished.
  32078. * @param {onProgressCallback} [onProgress] - Executed while the loading is in progress.
  32079. * @param {onErrorCallback} [onError] - Executed when errors occur.
  32080. * @return {any|undefined} The cached resource if available.
  32081. */
  32082. load( url, onLoad, onProgress, onError ) {
  32083. if ( url === undefined ) url = '';
  32084. if ( this.path !== undefined ) url = this.path + url;
  32085. url = this.manager.resolveURL( url );
  32086. const cached = Cache.get( url );
  32087. if ( cached !== undefined ) {
  32088. this.manager.itemStart( url );
  32089. setTimeout( () => {
  32090. if ( onLoad ) onLoad( cached );
  32091. this.manager.itemEnd( url );
  32092. }, 0 );
  32093. return cached;
  32094. }
  32095. // Check if request is duplicate
  32096. if ( loading[ url ] !== undefined ) {
  32097. loading[ url ].push( {
  32098. onLoad: onLoad,
  32099. onProgress: onProgress,
  32100. onError: onError
  32101. } );
  32102. return;
  32103. }
  32104. // Initialise array for duplicate requests
  32105. loading[ url ] = [];
  32106. loading[ url ].push( {
  32107. onLoad: onLoad,
  32108. onProgress: onProgress,
  32109. onError: onError,
  32110. } );
  32111. // create request
  32112. const req = new Request( url, {
  32113. headers: new Headers( this.requestHeader ),
  32114. credentials: this.withCredentials ? 'include' : 'same-origin',
  32115. // An abort controller could be added within a future PR
  32116. } );
  32117. // record states ( avoid data race )
  32118. const mimeType = this.mimeType;
  32119. const responseType = this.responseType;
  32120. // start the fetch
  32121. fetch( req )
  32122. .then( response => {
  32123. if ( response.status === 200 || response.status === 0 ) {
  32124. // Some browsers return HTTP Status 0 when using non-http protocol
  32125. // e.g. 'file://' or 'data://'. Handle as success.
  32126. if ( response.status === 0 ) {
  32127. console.warn( 'THREE.FileLoader: HTTP Status 0 received.' );
  32128. }
  32129. // Workaround: Checking if response.body === undefined for Alipay browser #23548
  32130. if ( typeof ReadableStream === 'undefined' || response.body === undefined || response.body.getReader === undefined ) {
  32131. return response;
  32132. }
  32133. const callbacks = loading[ url ];
  32134. const reader = response.body.getReader();
  32135. // Nginx needs X-File-Size check
  32136. // https://serverfault.com/questions/482875/why-does-nginx-remove-content-length-header-for-chunked-content
  32137. const contentLength = response.headers.get( 'X-File-Size' ) || response.headers.get( 'Content-Length' );
  32138. const total = contentLength ? parseInt( contentLength ) : 0;
  32139. const lengthComputable = total !== 0;
  32140. let loaded = 0;
  32141. // periodically read data into the new stream tracking while download progress
  32142. const stream = new ReadableStream( {
  32143. start( controller ) {
  32144. readData();
  32145. function readData() {
  32146. reader.read().then( ( { done, value } ) => {
  32147. if ( done ) {
  32148. controller.close();
  32149. } else {
  32150. loaded += value.byteLength;
  32151. const event = new ProgressEvent( 'progress', { lengthComputable, loaded, total } );
  32152. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  32153. const callback = callbacks[ i ];
  32154. if ( callback.onProgress ) callback.onProgress( event );
  32155. }
  32156. controller.enqueue( value );
  32157. readData();
  32158. }
  32159. }, ( e ) => {
  32160. controller.error( e );
  32161. } );
  32162. }
  32163. }
  32164. } );
  32165. return new Response( stream );
  32166. } else {
  32167. throw new HttpError( `fetch for "${response.url}" responded with ${response.status}: ${response.statusText}`, response );
  32168. }
  32169. } )
  32170. .then( response => {
  32171. switch ( responseType ) {
  32172. case 'arraybuffer':
  32173. return response.arrayBuffer();
  32174. case 'blob':
  32175. return response.blob();
  32176. case 'document':
  32177. return response.text()
  32178. .then( text => {
  32179. const parser = new DOMParser();
  32180. return parser.parseFromString( text, mimeType );
  32181. } );
  32182. case 'json':
  32183. return response.json();
  32184. default:
  32185. if ( mimeType === '' ) {
  32186. return response.text();
  32187. } else {
  32188. // sniff encoding
  32189. const re = /charset="?([^;"\s]*)"?/i;
  32190. const exec = re.exec( mimeType );
  32191. const label = exec && exec[ 1 ] ? exec[ 1 ].toLowerCase() : undefined;
  32192. const decoder = new TextDecoder( label );
  32193. return response.arrayBuffer().then( ab => decoder.decode( ab ) );
  32194. }
  32195. }
  32196. } )
  32197. .then( data => {
  32198. // Add to cache only on HTTP success, so that we do not cache
  32199. // error response bodies as proper responses to requests.
  32200. Cache.add( url, data );
  32201. const callbacks = loading[ url ];
  32202. delete loading[ url ];
  32203. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  32204. const callback = callbacks[ i ];
  32205. if ( callback.onLoad ) callback.onLoad( data );
  32206. }
  32207. } )
  32208. .catch( err => {
  32209. // Abort errors and other errors are handled the same
  32210. const callbacks = loading[ url ];
  32211. if ( callbacks === undefined ) {
  32212. // When onLoad was called and url was deleted in `loading`
  32213. this.manager.itemError( url );
  32214. throw err;
  32215. }
  32216. delete loading[ url ];
  32217. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  32218. const callback = callbacks[ i ];
  32219. if ( callback.onError ) callback.onError( err );
  32220. }
  32221. this.manager.itemError( url );
  32222. } )
  32223. .finally( () => {
  32224. this.manager.itemEnd( url );
  32225. } );
  32226. this.manager.itemStart( url );
  32227. }
  32228. /**
  32229. * Sets the expected response type.
  32230. *
  32231. * @param {('arraybuffer'|'blob'|'document'|'json'|'')} value - The response type.
  32232. * @return {FileLoader} A reference to this file loader.
  32233. */
  32234. setResponseType( value ) {
  32235. this.responseType = value;
  32236. return this;
  32237. }
  32238. /**
  32239. * Sets the expected mime type of the loaded file.
  32240. *
  32241. * @param {string} value - The mime type.
  32242. * @return {FileLoader} A reference to this file loader.
  32243. */
  32244. setMimeType( value ) {
  32245. this.mimeType = value;
  32246. return this;
  32247. }
  32248. }
  32249. /**
  32250. * Class for loading animation clips in the JSON format. The files are internally
  32251. * loaded via {@link FileLoader}.
  32252. *
  32253. * ```js
  32254. * const loader = new THREE.AnimationLoader();
  32255. * const animations = await loader.loadAsync( 'animations/animation.js' );
  32256. * ```
  32257. *
  32258. * @augments Loader
  32259. */
  32260. class AnimationLoader extends Loader {
  32261. /**
  32262. * Constructs a new animation loader.
  32263. *
  32264. * @param {LoadingManager} [manager] - The loading manager.
  32265. */
  32266. constructor( manager ) {
  32267. super( manager );
  32268. }
  32269. /**
  32270. * Starts loading from the given URL and pass the loaded animations as an array
  32271. * holding instances of {@link AnimationClip} to the `onLoad()` callback.
  32272. *
  32273. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  32274. * @param {function(Array<AnimationClip>)} onLoad - Executed when the loading process has been finished.
  32275. * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
  32276. * @param {onErrorCallback} onError - Executed when errors occur.
  32277. */
  32278. load( url, onLoad, onProgress, onError ) {
  32279. const scope = this;
  32280. const loader = new FileLoader( this.manager );
  32281. loader.setPath( this.path );
  32282. loader.setRequestHeader( this.requestHeader );
  32283. loader.setWithCredentials( this.withCredentials );
  32284. loader.load( url, function ( text ) {
  32285. try {
  32286. onLoad( scope.parse( JSON.parse( text ) ) );
  32287. } catch ( e ) {
  32288. if ( onError ) {
  32289. onError( e );
  32290. } else {
  32291. console.error( e );
  32292. }
  32293. scope.manager.itemError( url );
  32294. }
  32295. }, onProgress, onError );
  32296. }
  32297. /**
  32298. * Parses the given JSON object and returns an array of animation clips.
  32299. *
  32300. * @param {Object} json - The serialized animation clips.
  32301. * @return {Array<AnimationClip>} The parsed animation clips.
  32302. */
  32303. parse( json ) {
  32304. const animations = [];
  32305. for ( let i = 0; i < json.length; i ++ ) {
  32306. const clip = AnimationClip.parse( json[ i ] );
  32307. animations.push( clip );
  32308. }
  32309. return animations;
  32310. }
  32311. }
  32312. /**
  32313. * Abstract base class for loading compressed texture formats S3TC, ASTC or ETC.
  32314. * Textures are internally loaded via {@link FileLoader}.
  32315. *
  32316. * Derived classes have to implement the `parse()` method which holds the parsing
  32317. * for the respective format.
  32318. *
  32319. * @abstract
  32320. * @augments Loader
  32321. */
  32322. class CompressedTextureLoader extends Loader {
  32323. /**
  32324. * Constructs a new compressed texture loader.
  32325. *
  32326. * @param {LoadingManager} [manager] - The loading manager.
  32327. */
  32328. constructor( manager ) {
  32329. super( manager );
  32330. }
  32331. /**
  32332. * Starts loading from the given URL and passes the loaded compressed texture
  32333. * to the `onLoad()` callback. The method also returns a new texture object which can
  32334. * directly be used for material creation. If you do it this way, the texture
  32335. * may pop up in your scene once the respective loading process is finished.
  32336. *
  32337. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  32338. * @param {function(CompressedTexture)} onLoad - Executed when the loading process has been finished.
  32339. * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
  32340. * @param {onErrorCallback} onError - Executed when errors occur.
  32341. * @return {CompressedTexture} The compressed texture.
  32342. */
  32343. load( url, onLoad, onProgress, onError ) {
  32344. const scope = this;
  32345. const images = [];
  32346. const texture = new CompressedTexture();
  32347. const loader = new FileLoader( this.manager );
  32348. loader.setPath( this.path );
  32349. loader.setResponseType( 'arraybuffer' );
  32350. loader.setRequestHeader( this.requestHeader );
  32351. loader.setWithCredentials( scope.withCredentials );
  32352. let loaded = 0;
  32353. function loadTexture( i ) {
  32354. loader.load( url[ i ], function ( buffer ) {
  32355. const texDatas = scope.parse( buffer, true );
  32356. images[ i ] = {
  32357. width: texDatas.width,
  32358. height: texDatas.height,
  32359. format: texDatas.format,
  32360. mipmaps: texDatas.mipmaps
  32361. };
  32362. loaded += 1;
  32363. if ( loaded === 6 ) {
  32364. if ( texDatas.mipmapCount === 1 ) texture.minFilter = LinearFilter;
  32365. texture.image = images;
  32366. texture.format = texDatas.format;
  32367. texture.needsUpdate = true;
  32368. if ( onLoad ) onLoad( texture );
  32369. }
  32370. }, onProgress, onError );
  32371. }
  32372. if ( Array.isArray( url ) ) {
  32373. for ( let i = 0, il = url.length; i < il; ++ i ) {
  32374. loadTexture( i );
  32375. }
  32376. } else {
  32377. // compressed cubemap texture stored in a single DDS file
  32378. loader.load( url, function ( buffer ) {
  32379. const texDatas = scope.parse( buffer, true );
  32380. if ( texDatas.isCubemap ) {
  32381. const faces = texDatas.mipmaps.length / texDatas.mipmapCount;
  32382. for ( let f = 0; f < faces; f ++ ) {
  32383. images[ f ] = { mipmaps: [] };
  32384. for ( let i = 0; i < texDatas.mipmapCount; i ++ ) {
  32385. images[ f ].mipmaps.push( texDatas.mipmaps[ f * texDatas.mipmapCount + i ] );
  32386. images[ f ].format = texDatas.format;
  32387. images[ f ].width = texDatas.width;
  32388. images[ f ].height = texDatas.height;
  32389. }
  32390. }
  32391. texture.image = images;
  32392. } else {
  32393. texture.image.width = texDatas.width;
  32394. texture.image.height = texDatas.height;
  32395. texture.mipmaps = texDatas.mipmaps;
  32396. }
  32397. if ( texDatas.mipmapCount === 1 ) {
  32398. texture.minFilter = LinearFilter;
  32399. }
  32400. texture.format = texDatas.format;
  32401. texture.needsUpdate = true;
  32402. if ( onLoad ) onLoad( texture );
  32403. }, onProgress, onError );
  32404. }
  32405. return texture;
  32406. }
  32407. }
  32408. /**
  32409. * A loader for loading images. The class loads images with the HTML `Image` API.
  32410. *
  32411. * ```js
  32412. * const loader = new THREE.ImageLoader();
  32413. * const image = await loader.loadAsync( 'image.png' );
  32414. * ```
  32415. * Please note that `ImageLoader` has dropped support for progress
  32416. * events in `r84`. For an `ImageLoader` that supports progress events, see
  32417. * [this thread]{@link https://github.com/mrdoob/three.js/issues/10439#issuecomment-275785639}.
  32418. *
  32419. * @augments Loader
  32420. */
  32421. class ImageLoader extends Loader {
  32422. /**
  32423. * Constructs a new image loader.
  32424. *
  32425. * @param {LoadingManager} [manager] - The loading manager.
  32426. */
  32427. constructor( manager ) {
  32428. super( manager );
  32429. }
  32430. /**
  32431. * Starts loading from the given URL and passes the loaded image
  32432. * to the `onLoad()` callback. The method also returns a new `Image` object which can
  32433. * directly be used for texture creation. If you do it this way, the texture
  32434. * may pop up in your scene once the respective loading process is finished.
  32435. *
  32436. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  32437. * @param {function(Image)} onLoad - Executed when the loading process has been finished.
  32438. * @param {onProgressCallback} onProgress - Unsupported in this loader.
  32439. * @param {onErrorCallback} onError - Executed when errors occur.
  32440. * @return {Image} The image.
  32441. */
  32442. load( url, onLoad, onProgress, onError ) {
  32443. if ( this.path !== undefined ) url = this.path + url;
  32444. url = this.manager.resolveURL( url );
  32445. const scope = this;
  32446. const cached = Cache.get( url );
  32447. if ( cached !== undefined ) {
  32448. scope.manager.itemStart( url );
  32449. setTimeout( function () {
  32450. if ( onLoad ) onLoad( cached );
  32451. scope.manager.itemEnd( url );
  32452. }, 0 );
  32453. return cached;
  32454. }
  32455. const image = createElementNS( 'img' );
  32456. function onImageLoad() {
  32457. removeEventListeners();
  32458. Cache.add( url, this );
  32459. if ( onLoad ) onLoad( this );
  32460. scope.manager.itemEnd( url );
  32461. }
  32462. function onImageError( event ) {
  32463. removeEventListeners();
  32464. if ( onError ) onError( event );
  32465. scope.manager.itemError( url );
  32466. scope.manager.itemEnd( url );
  32467. }
  32468. function removeEventListeners() {
  32469. image.removeEventListener( 'load', onImageLoad, false );
  32470. image.removeEventListener( 'error', onImageError, false );
  32471. }
  32472. image.addEventListener( 'load', onImageLoad, false );
  32473. image.addEventListener( 'error', onImageError, false );
  32474. if ( url.slice( 0, 5 ) !== 'data:' ) {
  32475. if ( this.crossOrigin !== undefined ) image.crossOrigin = this.crossOrigin;
  32476. }
  32477. scope.manager.itemStart( url );
  32478. image.src = url;
  32479. return image;
  32480. }
  32481. }
  32482. /**
  32483. * Class for loading cube textures. Images are internally loaded via {@link ImageLoader}.
  32484. *
  32485. * The loader returns an instance of {@link CubeTexture} and expects the cube map to
  32486. * be defined as six separate images representing the sides of a cube. Other cube map definitions
  32487. * like vertical and horizontal cross, column and row layouts are not supported.
  32488. *
  32489. * Note that, by convention, cube maps are specified in a coordinate system
  32490. * in which positive-x is to the right when looking up the positive-z axis --
  32491. * in other words, using a left-handed coordinate system. Since three.js uses
  32492. * a right-handed coordinate system, environment maps used in three.js will
  32493. * have pos-x and neg-x swapped.
  32494. *
  32495. * The loaded cube texture is in sRGB color space. Meaning {@link Texture#colorSpace}
  32496. * is set to `SRGBColorSpace` by default.
  32497. *
  32498. * ```js
  32499. * const loader = new THREE.CubeTextureLoader().setPath( 'textures/cubeMaps/' );
  32500. * const cubeTexture = await loader.loadAsync( [
  32501. * 'px.png', 'nx.png', 'py.png', 'ny.png', 'pz.png', 'nz.png'
  32502. * ] );
  32503. * scene.background = cubeTexture;
  32504. * ```
  32505. *
  32506. * @augments Loader
  32507. */
  32508. class CubeTextureLoader extends Loader {
  32509. /**
  32510. * Constructs a new cube texture loader.
  32511. *
  32512. * @param {LoadingManager} [manager] - The loading manager.
  32513. */
  32514. constructor( manager ) {
  32515. super( manager );
  32516. }
  32517. /**
  32518. * Starts loading from the given URL and pass the fully loaded cube texture
  32519. * to the `onLoad()` callback. The method also returns a new cube texture object which can
  32520. * directly be used for material creation. If you do it this way, the cube texture
  32521. * may pop up in your scene once the respective loading process is finished.
  32522. *
  32523. * @param {Array<string>} urls - Array of 6 URLs to images, one for each side of the
  32524. * cube texture. The urls should be specified in the following order: pos-x,
  32525. * neg-x, pos-y, neg-y, pos-z, neg-z. An array of data URIs are allowed as well.
  32526. * @param {function(CubeTexture)} onLoad - Executed when the loading process has been finished.
  32527. * @param {onProgressCallback} onProgress - Unsupported in this loader.
  32528. * @param {onErrorCallback} onError - Executed when errors occur.
  32529. * @return {CubeTexture} The cube texture.
  32530. */
  32531. load( urls, onLoad, onProgress, onError ) {
  32532. const texture = new CubeTexture();
  32533. texture.colorSpace = SRGBColorSpace;
  32534. const loader = new ImageLoader( this.manager );
  32535. loader.setCrossOrigin( this.crossOrigin );
  32536. loader.setPath( this.path );
  32537. let loaded = 0;
  32538. function loadTexture( i ) {
  32539. loader.load( urls[ i ], function ( image ) {
  32540. texture.images[ i ] = image;
  32541. loaded ++;
  32542. if ( loaded === 6 ) {
  32543. texture.needsUpdate = true;
  32544. if ( onLoad ) onLoad( texture );
  32545. }
  32546. }, undefined, onError );
  32547. }
  32548. for ( let i = 0; i < urls.length; ++ i ) {
  32549. loadTexture( i );
  32550. }
  32551. return texture;
  32552. }
  32553. }
  32554. /**
  32555. * Abstract base class for loading binary texture formats RGBE, EXR or TGA.
  32556. * Textures are internally loaded via {@link FileLoader}.
  32557. *
  32558. * Derived classes have to implement the `parse()` method which holds the parsing
  32559. * for the respective format.
  32560. *
  32561. * @abstract
  32562. * @augments Loader
  32563. */
  32564. class DataTextureLoader extends Loader {
  32565. /**
  32566. * Constructs a new data texture loader.
  32567. *
  32568. * @param {LoadingManager} [manager] - The loading manager.
  32569. */
  32570. constructor( manager ) {
  32571. super( manager );
  32572. }
  32573. /**
  32574. * Starts loading from the given URL and passes the loaded data texture
  32575. * to the `onLoad()` callback. The method also returns a new texture object which can
  32576. * directly be used for material creation. If you do it this way, the texture
  32577. * may pop up in your scene once the respective loading process is finished.
  32578. *
  32579. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  32580. * @param {function(DataTexture)} onLoad - Executed when the loading process has been finished.
  32581. * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
  32582. * @param {onErrorCallback} onError - Executed when errors occur.
  32583. * @return {DataTexture} The data texture.
  32584. */
  32585. load( url, onLoad, onProgress, onError ) {
  32586. const scope = this;
  32587. const texture = new DataTexture();
  32588. const loader = new FileLoader( this.manager );
  32589. loader.setResponseType( 'arraybuffer' );
  32590. loader.setRequestHeader( this.requestHeader );
  32591. loader.setPath( this.path );
  32592. loader.setWithCredentials( scope.withCredentials );
  32593. loader.load( url, function ( buffer ) {
  32594. let texData;
  32595. try {
  32596. texData = scope.parse( buffer );
  32597. } catch ( error ) {
  32598. if ( onError !== undefined ) {
  32599. onError( error );
  32600. } else {
  32601. console.error( error );
  32602. return;
  32603. }
  32604. }
  32605. if ( texData.image !== undefined ) {
  32606. texture.image = texData.image;
  32607. } else if ( texData.data !== undefined ) {
  32608. texture.image.width = texData.width;
  32609. texture.image.height = texData.height;
  32610. texture.image.data = texData.data;
  32611. }
  32612. texture.wrapS = texData.wrapS !== undefined ? texData.wrapS : ClampToEdgeWrapping;
  32613. texture.wrapT = texData.wrapT !== undefined ? texData.wrapT : ClampToEdgeWrapping;
  32614. texture.magFilter = texData.magFilter !== undefined ? texData.magFilter : LinearFilter;
  32615. texture.minFilter = texData.minFilter !== undefined ? texData.minFilter : LinearFilter;
  32616. texture.anisotropy = texData.anisotropy !== undefined ? texData.anisotropy : 1;
  32617. if ( texData.colorSpace !== undefined ) {
  32618. texture.colorSpace = texData.colorSpace;
  32619. }
  32620. if ( texData.flipY !== undefined ) {
  32621. texture.flipY = texData.flipY;
  32622. }
  32623. if ( texData.format !== undefined ) {
  32624. texture.format = texData.format;
  32625. }
  32626. if ( texData.type !== undefined ) {
  32627. texture.type = texData.type;
  32628. }
  32629. if ( texData.mipmaps !== undefined ) {
  32630. texture.mipmaps = texData.mipmaps;
  32631. texture.minFilter = LinearMipmapLinearFilter; // presumably...
  32632. }
  32633. if ( texData.mipmapCount === 1 ) {
  32634. texture.minFilter = LinearFilter;
  32635. }
  32636. if ( texData.generateMipmaps !== undefined ) {
  32637. texture.generateMipmaps = texData.generateMipmaps;
  32638. }
  32639. texture.needsUpdate = true;
  32640. if ( onLoad ) onLoad( texture, texData );
  32641. }, onProgress, onError );
  32642. return texture;
  32643. }
  32644. }
  32645. /**
  32646. * Class for loading textures. Images are internally
  32647. * loaded via {@link ImageLoader}.
  32648. *
  32649. * ```js
  32650. * const loader = new THREE.TextureLoader();
  32651. * const texture = await loader.loadAsync( 'textures/land_ocean_ice_cloud_2048.jpg' );
  32652. *
  32653. * const material = new THREE.MeshBasicMaterial( { map:texture } );
  32654. * ```
  32655. * Please note that `TextureLoader` has dropped support for progress
  32656. * events in `r84`. For a `TextureLoader` that supports progress events, see
  32657. * [this thread]{@link https://github.com/mrdoob/three.js/issues/10439#issuecomment-293260145}.
  32658. *
  32659. * @augments Loader
  32660. */
  32661. class TextureLoader extends Loader {
  32662. /**
  32663. * Constructs a new texture loader.
  32664. *
  32665. * @param {LoadingManager} [manager] - The loading manager.
  32666. */
  32667. constructor( manager ) {
  32668. super( manager );
  32669. }
  32670. /**
  32671. * Starts loading from the given URL and pass the fully loaded texture
  32672. * to the `onLoad()` callback. The method also returns a new texture object which can
  32673. * directly be used for material creation. If you do it this way, the texture
  32674. * may pop up in your scene once the respective loading process is finished.
  32675. *
  32676. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  32677. * @param {function(Texture)} onLoad - Executed when the loading process has been finished.
  32678. * @param {onProgressCallback} onProgress - Unsupported in this loader.
  32679. * @param {onErrorCallback} onError - Executed when errors occur.
  32680. * @return {Texture} The texture.
  32681. */
  32682. load( url, onLoad, onProgress, onError ) {
  32683. const texture = new Texture();
  32684. const loader = new ImageLoader( this.manager );
  32685. loader.setCrossOrigin( this.crossOrigin );
  32686. loader.setPath( this.path );
  32687. loader.load( url, function ( image ) {
  32688. texture.image = image;
  32689. texture.needsUpdate = true;
  32690. if ( onLoad !== undefined ) {
  32691. onLoad( texture );
  32692. }
  32693. }, onProgress, onError );
  32694. return texture;
  32695. }
  32696. }
  32697. /**
  32698. * Abstract base class for lights - all other light types inherit the
  32699. * properties and methods described here.
  32700. *
  32701. * @abstract
  32702. * @augments Object3D
  32703. */
  32704. class Light extends Object3D {
  32705. /**
  32706. * Constructs a new light.
  32707. *
  32708. * @param {(number|Color|string)} [color=0xffffff] - The light's color.
  32709. * @param {number} [intensity=1] - The light's strength/intensity.
  32710. */
  32711. constructor( color, intensity = 1 ) {
  32712. super();
  32713. /**
  32714. * This flag can be used for type testing.
  32715. *
  32716. * @type {boolean}
  32717. * @readonly
  32718. * @default true
  32719. */
  32720. this.isLight = true;
  32721. this.type = 'Light';
  32722. /**
  32723. * The light's color.
  32724. *
  32725. * @type {Color}
  32726. */
  32727. this.color = new Color( color );
  32728. /**
  32729. * The light's intensity.
  32730. *
  32731. * @type {number}
  32732. * @default 1
  32733. */
  32734. this.intensity = intensity;
  32735. }
  32736. /**
  32737. * Frees the GPU-related resources allocated by this instance. Call this
  32738. * method whenever this instance is no longer used in your app.
  32739. */
  32740. dispose() {
  32741. // Empty here in base class; some subclasses override.
  32742. }
  32743. copy( source, recursive ) {
  32744. super.copy( source, recursive );
  32745. this.color.copy( source.color );
  32746. this.intensity = source.intensity;
  32747. return this;
  32748. }
  32749. toJSON( meta ) {
  32750. const data = super.toJSON( meta );
  32751. data.object.color = this.color.getHex();
  32752. data.object.intensity = this.intensity;
  32753. if ( this.groundColor !== undefined ) data.object.groundColor = this.groundColor.getHex();
  32754. if ( this.distance !== undefined ) data.object.distance = this.distance;
  32755. if ( this.angle !== undefined ) data.object.angle = this.angle;
  32756. if ( this.decay !== undefined ) data.object.decay = this.decay;
  32757. if ( this.penumbra !== undefined ) data.object.penumbra = this.penumbra;
  32758. if ( this.shadow !== undefined ) data.object.shadow = this.shadow.toJSON();
  32759. if ( this.target !== undefined ) data.object.target = this.target.uuid;
  32760. return data;
  32761. }
  32762. }
  32763. /**
  32764. * A light source positioned directly above the scene, with color fading from
  32765. * the sky color to the ground color.
  32766. *
  32767. * This light cannot be used to cast shadows.
  32768. *
  32769. * ```js
  32770. * const light = new THREE.HemisphereLight( 0xffffbb, 0x080820, 1 );
  32771. * scene.add( light );
  32772. * ```
  32773. *
  32774. * @augments Light
  32775. */
  32776. class HemisphereLight extends Light {
  32777. /**
  32778. * Constructs a new hemisphere light.
  32779. *
  32780. * @param {(number|Color|string)} [skyColor=0xffffff] - The light's sky color.
  32781. * @param {(number|Color|string)} [groundColor=0xffffff] - The light's ground color.
  32782. * @param {number} [intensity=1] - The light's strength/intensity.
  32783. */
  32784. constructor( skyColor, groundColor, intensity ) {
  32785. super( skyColor, intensity );
  32786. /**
  32787. * This flag can be used for type testing.
  32788. *
  32789. * @type {boolean}
  32790. * @readonly
  32791. * @default true
  32792. */
  32793. this.isHemisphereLight = true;
  32794. this.type = 'HemisphereLight';
  32795. this.position.copy( Object3D.DEFAULT_UP );
  32796. this.updateMatrix();
  32797. /**
  32798. * The light's ground color.
  32799. *
  32800. * @type {Color}
  32801. */
  32802. this.groundColor = new Color( groundColor );
  32803. }
  32804. copy( source, recursive ) {
  32805. super.copy( source, recursive );
  32806. this.groundColor.copy( source.groundColor );
  32807. return this;
  32808. }
  32809. }
  32810. const _projScreenMatrix$1 = /*@__PURE__*/ new Matrix4();
  32811. const _lightPositionWorld$1 = /*@__PURE__*/ new Vector3();
  32812. const _lookTarget$1 = /*@__PURE__*/ new Vector3();
  32813. /**
  32814. * Abstract base class for light shadow classes. These classes
  32815. * represent the shadow configuration for different light types.
  32816. *
  32817. * @abstract
  32818. */
  32819. class LightShadow {
  32820. /**
  32821. * Constructs a new light shadow.
  32822. *
  32823. * @param {Camera} camera - The light's view of the world.
  32824. */
  32825. constructor( camera ) {
  32826. /**
  32827. * The light's view of the world.
  32828. *
  32829. * @type {Camera}
  32830. */
  32831. this.camera = camera;
  32832. /**
  32833. * The intensity of the shadow. The default is `1`.
  32834. * Valid values are in the range `[0, 1]`.
  32835. *
  32836. * @type {number}
  32837. * @default 1
  32838. */
  32839. this.intensity = 1;
  32840. /**
  32841. * Shadow map bias, how much to add or subtract from the normalized depth
  32842. * when deciding whether a surface is in shadow.
  32843. *
  32844. * The default is `0`. Very tiny adjustments here (in the order of `0.0001`)
  32845. * may help reduce artifacts in shadows.
  32846. *
  32847. * @type {number}
  32848. * @default 0
  32849. */
  32850. this.bias = 0;
  32851. /**
  32852. * Defines how much the position used to query the shadow map is offset along
  32853. * the object normal. The default is `0`. Increasing this value can be used to
  32854. * reduce shadow acne especially in large scenes where light shines onto
  32855. * geometry at a shallow angle. The cost is that shadows may appear distorted.
  32856. *
  32857. * @type {number}
  32858. * @default 0
  32859. */
  32860. this.normalBias = 0;
  32861. /**
  32862. * Setting this to values greater than 1 will blur the edges of the shadow.
  32863. * High values will cause unwanted banding effects in the shadows - a greater
  32864. * map size will allow for a higher value to be used here before these effects
  32865. * become visible.
  32866. *
  32867. * The property has no effect when the shadow map type is `PCFSoftShadowMap` and
  32868. * and it is recommended to increase softness by decreasing the shadow map size instead.
  32869. *
  32870. * The property has no effect when the shadow map type is `BasicShadowMap`.
  32871. *
  32872. * @type {number}
  32873. * @default 1
  32874. */
  32875. this.radius = 1;
  32876. /**
  32877. * The amount of samples to use when blurring a VSM shadow map.
  32878. *
  32879. * @type {number}
  32880. * @default 8
  32881. */
  32882. this.blurSamples = 8;
  32883. /**
  32884. * Defines the width and height of the shadow map. Higher values give better quality
  32885. * shadows at the cost of computation time. Values must be powers of two.
  32886. *
  32887. * @type {Vector2}
  32888. * @default (512,512)
  32889. */
  32890. this.mapSize = new Vector2( 512, 512 );
  32891. /**
  32892. * The type of shadow texture. The default is `UnsignedByteType`.
  32893. *
  32894. * @type {number}
  32895. * @default UnsignedByteType
  32896. */
  32897. this.mapType = UnsignedByteType;
  32898. /**
  32899. * The depth map generated using the internal camera; a location beyond a
  32900. * pixel's depth is in shadow. Computed internally during rendering.
  32901. *
  32902. * @type {?RenderTarget}
  32903. * @default null
  32904. */
  32905. this.map = null;
  32906. /**
  32907. * The distribution map generated using the internal camera; an occlusion is
  32908. * calculated based on the distribution of depths. Computed internally during
  32909. * rendering.
  32910. *
  32911. * @type {?RenderTarget}
  32912. * @default null
  32913. */
  32914. this.mapPass = null;
  32915. /**
  32916. * Model to shadow camera space, to compute location and depth in shadow map.
  32917. * This is computed internally during rendering.
  32918. *
  32919. * @type {Matrix4}
  32920. */
  32921. this.matrix = new Matrix4();
  32922. /**
  32923. * Enables automatic updates of the light's shadow. If you do not require dynamic
  32924. * lighting / shadows, you may set this to `false`.
  32925. *
  32926. * @type {boolean}
  32927. * @default true
  32928. */
  32929. this.autoUpdate = true;
  32930. /**
  32931. * When set to `true`, shadow maps will be updated in the next `render` call.
  32932. * If you have set {@link LightShadow#autoUpdate} to `false`, you will need to
  32933. * set this property to `true` and then make a render call to update the light's shadow.
  32934. *
  32935. * @type {boolean}
  32936. * @default false
  32937. */
  32938. this.needsUpdate = false;
  32939. this._frustum = new Frustum();
  32940. this._frameExtents = new Vector2( 1, 1 );
  32941. this._viewportCount = 1;
  32942. this._viewports = [
  32943. new Vector4( 0, 0, 1, 1 )
  32944. ];
  32945. }
  32946. /**
  32947. * Used internally by the renderer to get the number of viewports that need
  32948. * to be rendered for this shadow.
  32949. *
  32950. * @return {number} The viewport count.
  32951. */
  32952. getViewportCount() {
  32953. return this._viewportCount;
  32954. }
  32955. /**
  32956. * Gets the shadow cameras frustum. Used internally by the renderer to cull objects.
  32957. *
  32958. * @return {Frustum} The shadow camera frustum.
  32959. */
  32960. getFrustum() {
  32961. return this._frustum;
  32962. }
  32963. /**
  32964. * Update the matrices for the camera and shadow, used internally by the renderer.
  32965. *
  32966. * @param {Light} light - The light for which the shadow is being rendered.
  32967. */
  32968. updateMatrices( light ) {
  32969. const shadowCamera = this.camera;
  32970. const shadowMatrix = this.matrix;
  32971. _lightPositionWorld$1.setFromMatrixPosition( light.matrixWorld );
  32972. shadowCamera.position.copy( _lightPositionWorld$1 );
  32973. _lookTarget$1.setFromMatrixPosition( light.target.matrixWorld );
  32974. shadowCamera.lookAt( _lookTarget$1 );
  32975. shadowCamera.updateMatrixWorld();
  32976. _projScreenMatrix$1.multiplyMatrices( shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse );
  32977. this._frustum.setFromProjectionMatrix( _projScreenMatrix$1 );
  32978. shadowMatrix.set(
  32979. 0.5, 0.0, 0.0, 0.5,
  32980. 0.0, 0.5, 0.0, 0.5,
  32981. 0.0, 0.0, 0.5, 0.5,
  32982. 0.0, 0.0, 0.0, 1.0
  32983. );
  32984. shadowMatrix.multiply( _projScreenMatrix$1 );
  32985. }
  32986. /**
  32987. * Returns a viewport definition for the given viewport index.
  32988. *
  32989. * @param {number} viewportIndex - The viewport index.
  32990. * @return {Vector4} The viewport.
  32991. */
  32992. getViewport( viewportIndex ) {
  32993. return this._viewports[ viewportIndex ];
  32994. }
  32995. /**
  32996. * Returns the frame extends.
  32997. *
  32998. * @return {Vector2} The frame extends.
  32999. */
  33000. getFrameExtents() {
  33001. return this._frameExtents;
  33002. }
  33003. /**
  33004. * Frees the GPU-related resources allocated by this instance. Call this
  33005. * method whenever this instance is no longer used in your app.
  33006. */
  33007. dispose() {
  33008. if ( this.map ) {
  33009. this.map.dispose();
  33010. }
  33011. if ( this.mapPass ) {
  33012. this.mapPass.dispose();
  33013. }
  33014. }
  33015. /**
  33016. * Copies the values of the given light shadow instance to this instance.
  33017. *
  33018. * @param {LightShadow} source - The light shadow to copy.
  33019. * @return {LightShadow} A reference to this light shadow instance.
  33020. */
  33021. copy( source ) {
  33022. this.camera = source.camera.clone();
  33023. this.intensity = source.intensity;
  33024. this.bias = source.bias;
  33025. this.radius = source.radius;
  33026. this.autoUpdate = source.autoUpdate;
  33027. this.needsUpdate = source.needsUpdate;
  33028. this.normalBias = source.normalBias;
  33029. this.blurSamples = source.blurSamples;
  33030. this.mapSize.copy( source.mapSize );
  33031. return this;
  33032. }
  33033. /**
  33034. * Returns a new light shadow instance with copied values from this instance.
  33035. *
  33036. * @return {LightShadow} A clone of this instance.
  33037. */
  33038. clone() {
  33039. return new this.constructor().copy( this );
  33040. }
  33041. /**
  33042. * Serializes the light shadow into JSON.
  33043. *
  33044. * @return {Object} A JSON object representing the serialized light shadow.
  33045. * @see {@link ObjectLoader#parse}
  33046. */
  33047. toJSON() {
  33048. const object = {};
  33049. if ( this.intensity !== 1 ) object.intensity = this.intensity;
  33050. if ( this.bias !== 0 ) object.bias = this.bias;
  33051. if ( this.normalBias !== 0 ) object.normalBias = this.normalBias;
  33052. if ( this.radius !== 1 ) object.radius = this.radius;
  33053. if ( this.mapSize.x !== 512 || this.mapSize.y !== 512 ) object.mapSize = this.mapSize.toArray();
  33054. object.camera = this.camera.toJSON( false ).object;
  33055. delete object.camera.matrix;
  33056. return object;
  33057. }
  33058. }
  33059. /**
  33060. * Represents the shadow configuration of directional lights.
  33061. *
  33062. * @augments LightShadow
  33063. */
  33064. class SpotLightShadow extends LightShadow {
  33065. /**
  33066. * Constructs a new spot light shadow.
  33067. */
  33068. constructor() {
  33069. super( new PerspectiveCamera( 50, 1, 0.5, 500 ) );
  33070. /**
  33071. * This flag can be used for type testing.
  33072. *
  33073. * @type {boolean}
  33074. * @readonly
  33075. * @default true
  33076. */
  33077. this.isSpotLightShadow = true;
  33078. /**
  33079. * Used to focus the shadow camera. The camera's field of view is set as a
  33080. * percentage of the spotlight's field-of-view. Range is `[0, 1]`.
  33081. *
  33082. * @type {number}
  33083. * @default 1
  33084. */
  33085. this.focus = 1;
  33086. /**
  33087. * Texture aspect ratio.
  33088. *
  33089. * @type {number}
  33090. * @default 1
  33091. */
  33092. this.aspect = 1;
  33093. }
  33094. updateMatrices( light ) {
  33095. const camera = this.camera;
  33096. const fov = RAD2DEG * 2 * light.angle * this.focus;
  33097. const aspect = ( this.mapSize.width / this.mapSize.height ) * this.aspect;
  33098. const far = light.distance || camera.far;
  33099. if ( fov !== camera.fov || aspect !== camera.aspect || far !== camera.far ) {
  33100. camera.fov = fov;
  33101. camera.aspect = aspect;
  33102. camera.far = far;
  33103. camera.updateProjectionMatrix();
  33104. }
  33105. super.updateMatrices( light );
  33106. }
  33107. copy( source ) {
  33108. super.copy( source );
  33109. this.focus = source.focus;
  33110. return this;
  33111. }
  33112. }
  33113. /**
  33114. * This light gets emitted from a single point in one direction, along a cone
  33115. * that increases in size the further from the light it gets.
  33116. *
  33117. * This light can cast shadows - see the {@link SpotLightShadow} for details.
  33118. *
  33119. * ```js
  33120. * // white spotlight shining from the side, modulated by a texture
  33121. * const spotLight = new THREE.SpotLight( 0xffffff );
  33122. * spotLight.position.set( 100, 1000, 100 );
  33123. * spotLight.map = new THREE.TextureLoader().load( url );
  33124. *
  33125. * spotLight.castShadow = true;
  33126. * spotLight.shadow.mapSize.width = 1024;
  33127. * spotLight.shadow.mapSize.height = 1024;
  33128. * spotLight.shadow.camera.near = 500;
  33129. * spotLight.shadow.camera.far = 4000;
  33130. * spotLight.shadow.camera.fov = 30;s
  33131. * ```
  33132. *
  33133. * @augments Light
  33134. */
  33135. class SpotLight extends Light {
  33136. /**
  33137. * Constructs a new spot light.
  33138. *
  33139. * @param {(number|Color|string)} [color=0xffffff] - The light's color.
  33140. * @param {number} [intensity=1] - The light's strength/intensity measured in candela (cd).
  33141. * @param {number} [distance=0] - Maximum range of the light. `0` means no limit.
  33142. * @param {number} [angle=Math.PI/3] - Maximum angle of light dispersion from its direction whose upper bound is `Math.PI/2`.
  33143. * @param {number} [penumbra=0] - Percent of the spotlight cone that is attenuated due to penumbra. Value range is `[0,1]`.
  33144. * @param {number} [decay=2] - The amount the light dims along the distance of the light.
  33145. */
  33146. constructor( color, intensity, distance = 0, angle = Math.PI / 3, penumbra = 0, decay = 2 ) {
  33147. super( color, intensity );
  33148. /**
  33149. * This flag can be used for type testing.
  33150. *
  33151. * @type {boolean}
  33152. * @readonly
  33153. * @default true
  33154. */
  33155. this.isSpotLight = true;
  33156. this.type = 'SpotLight';
  33157. this.position.copy( Object3D.DEFAULT_UP );
  33158. this.updateMatrix();
  33159. /**
  33160. * The spot light points from its position to the
  33161. * target's position.
  33162. *
  33163. * For the target's position to be changed to anything other
  33164. * than the default, it must be added to the scene.
  33165. *
  33166. * It is also possible to set the target to be another 3D object
  33167. * in the scene. The light will now track the target object.
  33168. *
  33169. * @type {Object3D}
  33170. */
  33171. this.target = new Object3D();
  33172. /**
  33173. * Maximum range of the light. `0` means no limit.
  33174. *
  33175. * @type {number}
  33176. * @default 0
  33177. */
  33178. this.distance = distance;
  33179. /**
  33180. * Maximum angle of light dispersion from its direction whose upper bound is `Math.PI/2`.
  33181. *
  33182. * @type {number}
  33183. * @default Math.PI/3
  33184. */
  33185. this.angle = angle;
  33186. /**
  33187. * Percent of the spotlight cone that is attenuated due to penumbra.
  33188. * Value range is `[0,1]`.
  33189. *
  33190. * @type {number}
  33191. * @default 0
  33192. */
  33193. this.penumbra = penumbra;
  33194. /**
  33195. * The amount the light dims along the distance of the light. In context of
  33196. * physically-correct rendering the default value should not be changed.
  33197. *
  33198. * @type {number}
  33199. * @default 2
  33200. */
  33201. this.decay = decay;
  33202. /**
  33203. * A texture used to modulate the color of the light. The spot light
  33204. * color is mixed with the RGB value of this texture, with a ratio
  33205. * corresponding to its alpha value. The cookie-like masking effect is
  33206. * reproduced using pixel values (0, 0, 0, 1-cookie_value).
  33207. *
  33208. * *Warning*: This property is disabled if {@link Object3D#castShadow} is set to `false`.
  33209. *
  33210. * @type {?Texture}
  33211. * @default null
  33212. */
  33213. this.map = null;
  33214. /**
  33215. * This property holds the light's shadow configuration.
  33216. *
  33217. * @type {SpotLightShadow}
  33218. */
  33219. this.shadow = new SpotLightShadow();
  33220. }
  33221. /**
  33222. * The light's power. Power is the luminous power of the light measured in lumens (lm).
  33223. * Changing the power will also change the light's intensity.
  33224. *
  33225. * @type {number}
  33226. */
  33227. get power() {
  33228. // compute the light's luminous power (in lumens) from its intensity (in candela)
  33229. // by convention for a spotlight, luminous power (lm) = π * luminous intensity (cd)
  33230. return this.intensity * Math.PI;
  33231. }
  33232. set power( power ) {
  33233. // set the light's intensity (in candela) from the desired luminous power (in lumens)
  33234. this.intensity = power / Math.PI;
  33235. }
  33236. dispose() {
  33237. this.shadow.dispose();
  33238. }
  33239. copy( source, recursive ) {
  33240. super.copy( source, recursive );
  33241. this.distance = source.distance;
  33242. this.angle = source.angle;
  33243. this.penumbra = source.penumbra;
  33244. this.decay = source.decay;
  33245. this.target = source.target.clone();
  33246. this.shadow = source.shadow.clone();
  33247. return this;
  33248. }
  33249. }
  33250. const _projScreenMatrix = /*@__PURE__*/ new Matrix4();
  33251. const _lightPositionWorld = /*@__PURE__*/ new Vector3();
  33252. const _lookTarget = /*@__PURE__*/ new Vector3();
  33253. /**
  33254. * Represents the shadow configuration of point lights.
  33255. *
  33256. * @augments LightShadow
  33257. */
  33258. class PointLightShadow extends LightShadow {
  33259. /**
  33260. * Constructs a new point light shadow.
  33261. */
  33262. constructor() {
  33263. super( new PerspectiveCamera( 90, 1, 0.5, 500 ) );
  33264. /**
  33265. * This flag can be used for type testing.
  33266. *
  33267. * @type {boolean}
  33268. * @readonly
  33269. * @default true
  33270. */
  33271. this.isPointLightShadow = true;
  33272. this._frameExtents = new Vector2( 4, 2 );
  33273. this._viewportCount = 6;
  33274. this._viewports = [
  33275. // These viewports map a cube-map onto a 2D texture with the
  33276. // following orientation:
  33277. //
  33278. // xzXZ
  33279. // y Y
  33280. //
  33281. // X - Positive x direction
  33282. // x - Negative x direction
  33283. // Y - Positive y direction
  33284. // y - Negative y direction
  33285. // Z - Positive z direction
  33286. // z - Negative z direction
  33287. // positive X
  33288. new Vector4( 2, 1, 1, 1 ),
  33289. // negative X
  33290. new Vector4( 0, 1, 1, 1 ),
  33291. // positive Z
  33292. new Vector4( 3, 1, 1, 1 ),
  33293. // negative Z
  33294. new Vector4( 1, 1, 1, 1 ),
  33295. // positive Y
  33296. new Vector4( 3, 0, 1, 1 ),
  33297. // negative Y
  33298. new Vector4( 1, 0, 1, 1 )
  33299. ];
  33300. this._cubeDirections = [
  33301. new Vector3( 1, 0, 0 ), new Vector3( -1, 0, 0 ), new Vector3( 0, 0, 1 ),
  33302. new Vector3( 0, 0, -1 ), new Vector3( 0, 1, 0 ), new Vector3( 0, -1, 0 )
  33303. ];
  33304. this._cubeUps = [
  33305. new Vector3( 0, 1, 0 ), new Vector3( 0, 1, 0 ), new Vector3( 0, 1, 0 ),
  33306. new Vector3( 0, 1, 0 ), new Vector3( 0, 0, 1 ), new Vector3( 0, 0, -1 )
  33307. ];
  33308. }
  33309. /**
  33310. * Update the matrices for the camera and shadow, used internally by the renderer.
  33311. *
  33312. * @param {Light} light - The light for which the shadow is being rendered.
  33313. * @param {number} [viewportIndex=0] - The viewport index.
  33314. */
  33315. updateMatrices( light, viewportIndex = 0 ) {
  33316. const camera = this.camera;
  33317. const shadowMatrix = this.matrix;
  33318. const far = light.distance || camera.far;
  33319. if ( far !== camera.far ) {
  33320. camera.far = far;
  33321. camera.updateProjectionMatrix();
  33322. }
  33323. _lightPositionWorld.setFromMatrixPosition( light.matrixWorld );
  33324. camera.position.copy( _lightPositionWorld );
  33325. _lookTarget.copy( camera.position );
  33326. _lookTarget.add( this._cubeDirections[ viewportIndex ] );
  33327. camera.up.copy( this._cubeUps[ viewportIndex ] );
  33328. camera.lookAt( _lookTarget );
  33329. camera.updateMatrixWorld();
  33330. shadowMatrix.makeTranslation( - _lightPositionWorld.x, - _lightPositionWorld.y, - _lightPositionWorld.z );
  33331. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  33332. this._frustum.setFromProjectionMatrix( _projScreenMatrix );
  33333. }
  33334. }
  33335. /**
  33336. * A light that gets emitted from a single point in all directions. A common
  33337. * use case for this is to replicate the light emitted from a bare
  33338. * lightbulb.
  33339. *
  33340. * This light can cast shadows - see the {@link PointLightShadow} for details.
  33341. *
  33342. * ```js
  33343. * const light = new THREE.PointLight( 0xff0000, 1, 100 );
  33344. * light.position.set( 50, 50, 50 );
  33345. * scene.add( light );
  33346. * ```
  33347. *
  33348. * @augments Light
  33349. */
  33350. class PointLight extends Light {
  33351. /**
  33352. * Constructs a new point light.
  33353. *
  33354. * @param {(number|Color|string)} [color=0xffffff] - The light's color.
  33355. * @param {number} [intensity=1] - The light's strength/intensity measured in candela (cd).
  33356. * @param {number} [distance=0] - Maximum range of the light. `0` means no limit.
  33357. * @param {number} [decay=2] - The amount the light dims along the distance of the light.
  33358. */
  33359. constructor( color, intensity, distance = 0, decay = 2 ) {
  33360. super( color, intensity );
  33361. /**
  33362. * This flag can be used for type testing.
  33363. *
  33364. * @type {boolean}
  33365. * @readonly
  33366. * @default true
  33367. */
  33368. this.isPointLight = true;
  33369. this.type = 'PointLight';
  33370. /**
  33371. * When distance is zero, light will attenuate according to inverse-square
  33372. * law to infinite distance. When distance is non-zero, light will attenuate
  33373. * according to inverse-square law until near the distance cutoff, where it
  33374. * will then attenuate quickly and smoothly to 0. Inherently, cutoffs are not
  33375. * physically correct.
  33376. *
  33377. * @type {number}
  33378. * @default 0
  33379. */
  33380. this.distance = distance;
  33381. /**
  33382. * The amount the light dims along the distance of the light. In context of
  33383. * physically-correct rendering the default value should not be changed.
  33384. *
  33385. * @type {number}
  33386. * @default 2
  33387. */
  33388. this.decay = decay;
  33389. /**
  33390. * This property holds the light's shadow configuration.
  33391. *
  33392. * @type {PointLightShadow}
  33393. */
  33394. this.shadow = new PointLightShadow();
  33395. }
  33396. /**
  33397. * The light's power. Power is the luminous power of the light measured in lumens (lm).
  33398. * Changing the power will also change the light's intensity.
  33399. *
  33400. * @type {number}
  33401. */
  33402. get power() {
  33403. // compute the light's luminous power (in lumens) from its intensity (in candela)
  33404. // for an isotropic light source, luminous power (lm) = 4 π luminous intensity (cd)
  33405. return this.intensity * 4 * Math.PI;
  33406. }
  33407. set power( power ) {
  33408. // set the light's intensity (in candela) from the desired luminous power (in lumens)
  33409. this.intensity = power / ( 4 * Math.PI );
  33410. }
  33411. dispose() {
  33412. this.shadow.dispose();
  33413. }
  33414. copy( source, recursive ) {
  33415. super.copy( source, recursive );
  33416. this.distance = source.distance;
  33417. this.decay = source.decay;
  33418. this.shadow = source.shadow.clone();
  33419. return this;
  33420. }
  33421. }
  33422. /**
  33423. * Camera that uses [orthographic projection]{@link https://en.wikipedia.org/wiki/Orthographic_projection}.
  33424. *
  33425. * In this projection mode, an object's size in the rendered image stays
  33426. * constant regardless of its distance from the camera. This can be useful
  33427. * for rendering 2D scenes and UI elements, amongst other things.
  33428. *
  33429. * ```js
  33430. * const camera = new THREE.OrthographicCamera( width / - 2, width / 2, height / 2, height / - 2, 1, 1000 );
  33431. * scene.add( camera );
  33432. * ```
  33433. *
  33434. * @augments Camera
  33435. */
  33436. class OrthographicCamera extends Camera {
  33437. /**
  33438. * Constructs a new orthographic camera.
  33439. *
  33440. * @param {number} [left=-1] - The left plane of the camera's frustum.
  33441. * @param {number} [right=1] - The right plane of the camera's frustum.
  33442. * @param {number} [top=1] - The top plane of the camera's frustum.
  33443. * @param {number} [bottom=-1] - The bottom plane of the camera's frustum.
  33444. * @param {number} [near=0.1] - The camera's near plane.
  33445. * @param {number} [far=2000] - The camera's far plane.
  33446. */
  33447. constructor( left = -1, right = 1, top = 1, bottom = -1, near = 0.1, far = 2000 ) {
  33448. super();
  33449. /**
  33450. * This flag can be used for type testing.
  33451. *
  33452. * @type {boolean}
  33453. * @readonly
  33454. * @default true
  33455. */
  33456. this.isOrthographicCamera = true;
  33457. this.type = 'OrthographicCamera';
  33458. /**
  33459. * The zoom factor of the camera.
  33460. *
  33461. * @type {number}
  33462. * @default 1
  33463. */
  33464. this.zoom = 1;
  33465. /**
  33466. * Represents the frustum window specification. This property should not be edited
  33467. * directly but via {@link PerspectiveCamera#setViewOffset} and {@link PerspectiveCamera#clearViewOffset}.
  33468. *
  33469. * @type {?Object}
  33470. * @default null
  33471. */
  33472. this.view = null;
  33473. /**
  33474. * The left plane of the camera's frustum.
  33475. *
  33476. * @type {number}
  33477. * @default -1
  33478. */
  33479. this.left = left;
  33480. /**
  33481. * The right plane of the camera's frustum.
  33482. *
  33483. * @type {number}
  33484. * @default 1
  33485. */
  33486. this.right = right;
  33487. /**
  33488. * The top plane of the camera's frustum.
  33489. *
  33490. * @type {number}
  33491. * @default 1
  33492. */
  33493. this.top = top;
  33494. /**
  33495. * The bottom plane of the camera's frustum.
  33496. *
  33497. * @type {number}
  33498. * @default -1
  33499. */
  33500. this.bottom = bottom;
  33501. /**
  33502. * The camera's near plane. The valid range is greater than `0`
  33503. * and less than the current value of {@link OrthographicCamera#far}.
  33504. *
  33505. * Note that, unlike for the {@link PerspectiveCamera}, `0` is a
  33506. * valid value for an orthographic camera's near plane.
  33507. *
  33508. * @type {number}
  33509. * @default 0.1
  33510. */
  33511. this.near = near;
  33512. /**
  33513. * The camera's far plane. Must be greater than the
  33514. * current value of {@link OrthographicCamera#near}.
  33515. *
  33516. * @type {number}
  33517. * @default 2000
  33518. */
  33519. this.far = far;
  33520. this.updateProjectionMatrix();
  33521. }
  33522. copy( source, recursive ) {
  33523. super.copy( source, recursive );
  33524. this.left = source.left;
  33525. this.right = source.right;
  33526. this.top = source.top;
  33527. this.bottom = source.bottom;
  33528. this.near = source.near;
  33529. this.far = source.far;
  33530. this.zoom = source.zoom;
  33531. this.view = source.view === null ? null : Object.assign( {}, source.view );
  33532. return this;
  33533. }
  33534. /**
  33535. * Sets an offset in a larger frustum. This is useful for multi-window or
  33536. * multi-monitor/multi-machine setups.
  33537. *
  33538. * @param {number} fullWidth - The full width of multiview setup.
  33539. * @param {number} fullHeight - The full height of multiview setup.
  33540. * @param {number} x - The horizontal offset of the subcamera.
  33541. * @param {number} y - The vertical offset of the subcamera.
  33542. * @param {number} width - The width of subcamera.
  33543. * @param {number} height - The height of subcamera.
  33544. * @see {@link PerspectiveCamera#setViewOffset}
  33545. */
  33546. setViewOffset( fullWidth, fullHeight, x, y, width, height ) {
  33547. if ( this.view === null ) {
  33548. this.view = {
  33549. enabled: true,
  33550. fullWidth: 1,
  33551. fullHeight: 1,
  33552. offsetX: 0,
  33553. offsetY: 0,
  33554. width: 1,
  33555. height: 1
  33556. };
  33557. }
  33558. this.view.enabled = true;
  33559. this.view.fullWidth = fullWidth;
  33560. this.view.fullHeight = fullHeight;
  33561. this.view.offsetX = x;
  33562. this.view.offsetY = y;
  33563. this.view.width = width;
  33564. this.view.height = height;
  33565. this.updateProjectionMatrix();
  33566. }
  33567. /**
  33568. * Removes the view offset from the projection matrix.
  33569. */
  33570. clearViewOffset() {
  33571. if ( this.view !== null ) {
  33572. this.view.enabled = false;
  33573. }
  33574. this.updateProjectionMatrix();
  33575. }
  33576. /**
  33577. * Updates the camera's projection matrix. Must be called after any change of
  33578. * camera properties.
  33579. */
  33580. updateProjectionMatrix() {
  33581. const dx = ( this.right - this.left ) / ( 2 * this.zoom );
  33582. const dy = ( this.top - this.bottom ) / ( 2 * this.zoom );
  33583. const cx = ( this.right + this.left ) / 2;
  33584. const cy = ( this.top + this.bottom ) / 2;
  33585. let left = cx - dx;
  33586. let right = cx + dx;
  33587. let top = cy + dy;
  33588. let bottom = cy - dy;
  33589. if ( this.view !== null && this.view.enabled ) {
  33590. const scaleW = ( this.right - this.left ) / this.view.fullWidth / this.zoom;
  33591. const scaleH = ( this.top - this.bottom ) / this.view.fullHeight / this.zoom;
  33592. left += scaleW * this.view.offsetX;
  33593. right = left + scaleW * this.view.width;
  33594. top -= scaleH * this.view.offsetY;
  33595. bottom = top - scaleH * this.view.height;
  33596. }
  33597. this.projectionMatrix.makeOrthographic( left, right, top, bottom, this.near, this.far, this.coordinateSystem );
  33598. this.projectionMatrixInverse.copy( this.projectionMatrix ).invert();
  33599. }
  33600. toJSON( meta ) {
  33601. const data = super.toJSON( meta );
  33602. data.object.zoom = this.zoom;
  33603. data.object.left = this.left;
  33604. data.object.right = this.right;
  33605. data.object.top = this.top;
  33606. data.object.bottom = this.bottom;
  33607. data.object.near = this.near;
  33608. data.object.far = this.far;
  33609. if ( this.view !== null ) data.object.view = Object.assign( {}, this.view );
  33610. return data;
  33611. }
  33612. }
  33613. /**
  33614. * Represents the shadow configuration of directional lights.
  33615. *
  33616. * @augments LightShadow
  33617. */
  33618. class DirectionalLightShadow extends LightShadow {
  33619. /**
  33620. * Constructs a new directional light shadow.
  33621. */
  33622. constructor() {
  33623. super( new OrthographicCamera( -5, 5, 5, -5, 0.5, 500 ) );
  33624. /**
  33625. * This flag can be used for type testing.
  33626. *
  33627. * @type {boolean}
  33628. * @readonly
  33629. * @default true
  33630. */
  33631. this.isDirectionalLightShadow = true;
  33632. }
  33633. }
  33634. /**
  33635. * A light that gets emitted in a specific direction. This light will behave
  33636. * as though it is infinitely far away and the rays produced from it are all
  33637. * parallel. The common use case for this is to simulate daylight; the sun is
  33638. * far enough away that its position can be considered to be infinite, and
  33639. * all light rays coming from it are parallel.
  33640. *
  33641. * A common point of confusion for directional lights is that setting the
  33642. * rotation has no effect. This is because three.js's DirectionalLight is the
  33643. * equivalent to what is often called a 'Target Direct Light' in other
  33644. * applications.
  33645. *
  33646. * This means that its direction is calculated as pointing from the light's
  33647. * {@link Object3D#position} to the {@link DirectionalLight#target} position
  33648. * (as opposed to a 'Free Direct Light' that just has a rotation
  33649. * component).
  33650. *
  33651. * This light can cast shadows - see the {@link DirectionalLightShadow} for details.
  33652. *
  33653. * ```js
  33654. * // White directional light at half intensity shining from the top.
  33655. * const directionalLight = new THREE.DirectionalLight( 0xffffff, 0.5 );
  33656. * scene.add( directionalLight );
  33657. * ```
  33658. *
  33659. * @augments Light
  33660. */
  33661. class DirectionalLight extends Light {
  33662. /**
  33663. * Constructs a new directional light.
  33664. *
  33665. * @param {(number|Color|string)} [color=0xffffff] - The light's color.
  33666. * @param {number} [intensity=1] - The light's strength/intensity.
  33667. */
  33668. constructor( color, intensity ) {
  33669. super( color, intensity );
  33670. /**
  33671. * This flag can be used for type testing.
  33672. *
  33673. * @type {boolean}
  33674. * @readonly
  33675. * @default true
  33676. */
  33677. this.isDirectionalLight = true;
  33678. this.type = 'DirectionalLight';
  33679. this.position.copy( Object3D.DEFAULT_UP );
  33680. this.updateMatrix();
  33681. /**
  33682. * The directional light points from its position to the
  33683. * target's position.
  33684. *
  33685. * For the target's position to be changed to anything other
  33686. * than the default, it must be added to the scene.
  33687. *
  33688. * It is also possible to set the target to be another 3D object
  33689. * in the scene. The light will now track the target object.
  33690. *
  33691. * @type {Object3D}
  33692. */
  33693. this.target = new Object3D();
  33694. /**
  33695. * This property holds the light's shadow configuration.
  33696. *
  33697. * @type {DirectionalLightShadow}
  33698. */
  33699. this.shadow = new DirectionalLightShadow();
  33700. }
  33701. dispose() {
  33702. this.shadow.dispose();
  33703. }
  33704. copy( source ) {
  33705. super.copy( source );
  33706. this.target = source.target.clone();
  33707. this.shadow = source.shadow.clone();
  33708. return this;
  33709. }
  33710. }
  33711. /**
  33712. * This light globally illuminates all objects in the scene equally.
  33713. *
  33714. * It cannot be used to cast shadows as it does not have a direction.
  33715. *
  33716. * ```js
  33717. * const light = new THREE.AmbientLight( 0x404040 ); // soft white light
  33718. * scene.add( light );
  33719. * ```
  33720. *
  33721. * @augments Light
  33722. */
  33723. class AmbientLight extends Light {
  33724. /**
  33725. * Constructs a new ambient light.
  33726. *
  33727. * @param {(number|Color|string)} [color=0xffffff] - The light's color.
  33728. * @param {number} [intensity=1] - The light's strength/intensity.
  33729. */
  33730. constructor( color, intensity ) {
  33731. super( color, intensity );
  33732. /**
  33733. * This flag can be used for type testing.
  33734. *
  33735. * @type {boolean}
  33736. * @readonly
  33737. * @default true
  33738. */
  33739. this.isAmbientLight = true;
  33740. this.type = 'AmbientLight';
  33741. }
  33742. }
  33743. /**
  33744. * This class emits light uniformly across the face a rectangular plane.
  33745. * This light type can be used to simulate light sources such as bright
  33746. * windows or strip lighting.
  33747. *
  33748. * Important Notes:
  33749. *
  33750. * - There is no shadow support.
  33751. * - Only PBR materials are supported.
  33752. * - You have to include `RectAreaLightUniformsLib` (`WebGLRenderer`) or `RectAreaLightTexturesLib` (`WebGPURenderer`)
  33753. * into your app and init the uniforms/textures.
  33754. *
  33755. * ```js
  33756. * RectAreaLightUniformsLib.init(); // only relevant for WebGLRenderer
  33757. * THREE.RectAreaLightNode.setLTC( RectAreaLightTexturesLib.init() ); // only relevant for WebGPURenderer
  33758. *
  33759. * const intensity = 1; const width = 10; const height = 10;
  33760. * const rectLight = new THREE.RectAreaLight( 0xffffff, intensity, width, height );
  33761. * rectLight.position.set( 5, 5, 0 );
  33762. * rectLight.lookAt( 0, 0, 0 );
  33763. * scene.add( rectLight )
  33764. * ```
  33765. *
  33766. * @augments Light
  33767. */
  33768. class RectAreaLight extends Light {
  33769. /**
  33770. * Constructs a new area light.
  33771. *
  33772. * @param {(number|Color|string)} [color=0xffffff] - The light's color.
  33773. * @param {number} [intensity=1] - The light's strength/intensity.
  33774. * @param {number} [width=10] - The width of the light.
  33775. * @param {number} [height=10] - The height of the light.
  33776. */
  33777. constructor( color, intensity, width = 10, height = 10 ) {
  33778. super( color, intensity );
  33779. /**
  33780. * This flag can be used for type testing.
  33781. *
  33782. * @type {boolean}
  33783. * @readonly
  33784. * @default true
  33785. */
  33786. this.isRectAreaLight = true;
  33787. this.type = 'RectAreaLight';
  33788. /**
  33789. * The width of the light.
  33790. *
  33791. * @type {number}
  33792. * @default 10
  33793. */
  33794. this.width = width;
  33795. /**
  33796. * The height of the light.
  33797. *
  33798. * @type {number}
  33799. * @default 10
  33800. */
  33801. this.height = height;
  33802. }
  33803. /**
  33804. * The light's power. Power is the luminous power of the light measured in lumens (lm).
  33805. * Changing the power will also change the light's intensity.
  33806. *
  33807. * @type {number}
  33808. */
  33809. get power() {
  33810. // compute the light's luminous power (in lumens) from its intensity (in nits)
  33811. return this.intensity * this.width * this.height * Math.PI;
  33812. }
  33813. set power( power ) {
  33814. // set the light's intensity (in nits) from the desired luminous power (in lumens)
  33815. this.intensity = power / ( this.width * this.height * Math.PI );
  33816. }
  33817. copy( source ) {
  33818. super.copy( source );
  33819. this.width = source.width;
  33820. this.height = source.height;
  33821. return this;
  33822. }
  33823. toJSON( meta ) {
  33824. const data = super.toJSON( meta );
  33825. data.object.width = this.width;
  33826. data.object.height = this.height;
  33827. return data;
  33828. }
  33829. }
  33830. /**
  33831. * Represents a third-order spherical harmonics (SH). Light probes use this class
  33832. * to encode lighting information.
  33833. *
  33834. * - Primary reference: {@link https://graphics.stanford.edu/papers/envmap/envmap.pdf}
  33835. * - Secondary reference: {@link https://www.ppsloan.org/publications/StupidSH36.pdf}
  33836. */
  33837. class SphericalHarmonics3 {
  33838. /**
  33839. * Constructs a new spherical harmonics.
  33840. */
  33841. constructor() {
  33842. /**
  33843. * This flag can be used for type testing.
  33844. *
  33845. * @type {boolean}
  33846. * @readonly
  33847. * @default true
  33848. */
  33849. this.isSphericalHarmonics3 = true;
  33850. /**
  33851. * An array holding the (9) SH coefficients.
  33852. *
  33853. * @type {Array<Vector3>}
  33854. */
  33855. this.coefficients = [];
  33856. for ( let i = 0; i < 9; i ++ ) {
  33857. this.coefficients.push( new Vector3() );
  33858. }
  33859. }
  33860. /**
  33861. * Sets the given SH coefficients to this instance by copying
  33862. * the values.
  33863. *
  33864. * @param {Array<Vector3>} coefficients - The SH coefficients.
  33865. * @return {SphericalHarmonics3} A reference to this spherical harmonics.
  33866. */
  33867. set( coefficients ) {
  33868. for ( let i = 0; i < 9; i ++ ) {
  33869. this.coefficients[ i ].copy( coefficients[ i ] );
  33870. }
  33871. return this;
  33872. }
  33873. /**
  33874. * Sets all SH coefficients to `0`.
  33875. *
  33876. * @return {SphericalHarmonics3} A reference to this spherical harmonics.
  33877. */
  33878. zero() {
  33879. for ( let i = 0; i < 9; i ++ ) {
  33880. this.coefficients[ i ].set( 0, 0, 0 );
  33881. }
  33882. return this;
  33883. }
  33884. /**
  33885. * Returns the radiance in the direction of the given normal.
  33886. *
  33887. * @param {Vector3} normal - The normal vector (assumed to be unit length)
  33888. * @param {Vector3} target - The target vector that is used to store the method's result.
  33889. * @return {Vector3} The radiance.
  33890. */
  33891. getAt( normal, target ) {
  33892. // normal is assumed to be unit length
  33893. const x = normal.x, y = normal.y, z = normal.z;
  33894. const coeff = this.coefficients;
  33895. // band 0
  33896. target.copy( coeff[ 0 ] ).multiplyScalar( 0.282095 );
  33897. // band 1
  33898. target.addScaledVector( coeff[ 1 ], 0.488603 * y );
  33899. target.addScaledVector( coeff[ 2 ], 0.488603 * z );
  33900. target.addScaledVector( coeff[ 3 ], 0.488603 * x );
  33901. // band 2
  33902. target.addScaledVector( coeff[ 4 ], 1.092548 * ( x * y ) );
  33903. target.addScaledVector( coeff[ 5 ], 1.092548 * ( y * z ) );
  33904. target.addScaledVector( coeff[ 6 ], 0.315392 * ( 3.0 * z * z - 1.0 ) );
  33905. target.addScaledVector( coeff[ 7 ], 1.092548 * ( x * z ) );
  33906. target.addScaledVector( coeff[ 8 ], 0.546274 * ( x * x - y * y ) );
  33907. return target;
  33908. }
  33909. /**
  33910. * Returns the irradiance (radiance convolved with cosine lobe) in the
  33911. * direction of the given normal.
  33912. *
  33913. * @param {Vector3} normal - The normal vector (assumed to be unit length)
  33914. * @param {Vector3} target - The target vector that is used to store the method's result.
  33915. * @return {Vector3} The irradiance.
  33916. */
  33917. getIrradianceAt( normal, target ) {
  33918. // normal is assumed to be unit length
  33919. const x = normal.x, y = normal.y, z = normal.z;
  33920. const coeff = this.coefficients;
  33921. // band 0
  33922. target.copy( coeff[ 0 ] ).multiplyScalar( 0.886227 ); // π * 0.282095
  33923. // band 1
  33924. target.addScaledVector( coeff[ 1 ], 2.0 * 0.511664 * y ); // ( 2 * π / 3 ) * 0.488603
  33925. target.addScaledVector( coeff[ 2 ], 2.0 * 0.511664 * z );
  33926. target.addScaledVector( coeff[ 3 ], 2.0 * 0.511664 * x );
  33927. // band 2
  33928. target.addScaledVector( coeff[ 4 ], 2.0 * 0.429043 * x * y ); // ( π / 4 ) * 1.092548
  33929. target.addScaledVector( coeff[ 5 ], 2.0 * 0.429043 * y * z );
  33930. target.addScaledVector( coeff[ 6 ], 0.743125 * z * z - 0.247708 ); // ( π / 4 ) * 0.315392 * 3
  33931. target.addScaledVector( coeff[ 7 ], 2.0 * 0.429043 * x * z );
  33932. target.addScaledVector( coeff[ 8 ], 0.429043 * ( x * x - y * y ) ); // ( π / 4 ) * 0.546274
  33933. return target;
  33934. }
  33935. /**
  33936. * Adds the given SH to this instance.
  33937. *
  33938. * @param {SphericalHarmonics3} sh - The SH to add.
  33939. * @return {SphericalHarmonics3} A reference to this spherical harmonics.
  33940. */
  33941. add( sh ) {
  33942. for ( let i = 0; i < 9; i ++ ) {
  33943. this.coefficients[ i ].add( sh.coefficients[ i ] );
  33944. }
  33945. return this;
  33946. }
  33947. /**
  33948. * A convenience method for performing {@link SphericalHarmonics3#add} and
  33949. * {@link SphericalHarmonics3#scale} at once.
  33950. *
  33951. * @param {SphericalHarmonics3} sh - The SH to add.
  33952. * @param {number} s - The scale factor.
  33953. * @return {SphericalHarmonics3} A reference to this spherical harmonics.
  33954. */
  33955. addScaledSH( sh, s ) {
  33956. for ( let i = 0; i < 9; i ++ ) {
  33957. this.coefficients[ i ].addScaledVector( sh.coefficients[ i ], s );
  33958. }
  33959. return this;
  33960. }
  33961. /**
  33962. * Scales this SH by the given scale factor.
  33963. *
  33964. * @param {number} s - The scale factor.
  33965. * @return {SphericalHarmonics3} A reference to this spherical harmonics.
  33966. */
  33967. scale( s ) {
  33968. for ( let i = 0; i < 9; i ++ ) {
  33969. this.coefficients[ i ].multiplyScalar( s );
  33970. }
  33971. return this;
  33972. }
  33973. /**
  33974. * Linear interpolates between the given SH and this instance by the given
  33975. * alpha factor.
  33976. *
  33977. * @param {SphericalHarmonics3} sh - The SH to interpolate with.
  33978. * @param {number} alpha - The alpha factor.
  33979. * @return {SphericalHarmonics3} A reference to this spherical harmonics.
  33980. */
  33981. lerp( sh, alpha ) {
  33982. for ( let i = 0; i < 9; i ++ ) {
  33983. this.coefficients[ i ].lerp( sh.coefficients[ i ], alpha );
  33984. }
  33985. return this;
  33986. }
  33987. /**
  33988. * Returns `true` if this spherical harmonics is equal with the given one.
  33989. *
  33990. * @param {SphericalHarmonics3} sh - The spherical harmonics to test for equality.
  33991. * @return {boolean} Whether this spherical harmonics is equal with the given one.
  33992. */
  33993. equals( sh ) {
  33994. for ( let i = 0; i < 9; i ++ ) {
  33995. if ( ! this.coefficients[ i ].equals( sh.coefficients[ i ] ) ) {
  33996. return false;
  33997. }
  33998. }
  33999. return true;
  34000. }
  34001. /**
  34002. * Copies the values of the given spherical harmonics to this instance.
  34003. *
  34004. * @param {SphericalHarmonics3} sh - The spherical harmonics to copy.
  34005. * @return {SphericalHarmonics3} A reference to this spherical harmonics.
  34006. */
  34007. copy( sh ) {
  34008. return this.set( sh.coefficients );
  34009. }
  34010. /**
  34011. * Returns a new spherical harmonics with copied values from this instance.
  34012. *
  34013. * @return {SphericalHarmonics3} A clone of this instance.
  34014. */
  34015. clone() {
  34016. return new this.constructor().copy( this );
  34017. }
  34018. /**
  34019. * Sets the SH coefficients of this instance from the given array.
  34020. *
  34021. * @param {Array<number>} array - An array holding the SH coefficients.
  34022. * @param {number} [offset=0] - The array offset where to start copying.
  34023. * @return {SphericalHarmonics3} A clone of this instance.
  34024. */
  34025. fromArray( array, offset = 0 ) {
  34026. const coefficients = this.coefficients;
  34027. for ( let i = 0; i < 9; i ++ ) {
  34028. coefficients[ i ].fromArray( array, offset + ( i * 3 ) );
  34029. }
  34030. return this;
  34031. }
  34032. /**
  34033. * Returns an array with the SH coefficients, or copies them into the provided
  34034. * array. The coefficients are represented as numbers.
  34035. *
  34036. * @param {Array<number>} [array=[]] - The target array.
  34037. * @param {number} [offset=0] - The array offset where to start copying.
  34038. * @return {Array<number>} An array with flat SH coefficients.
  34039. */
  34040. toArray( array = [], offset = 0 ) {
  34041. const coefficients = this.coefficients;
  34042. for ( let i = 0; i < 9; i ++ ) {
  34043. coefficients[ i ].toArray( array, offset + ( i * 3 ) );
  34044. }
  34045. return array;
  34046. }
  34047. /**
  34048. * Computes the SH basis for the given normal vector.
  34049. *
  34050. * @param {Vector3} normal - The normal.
  34051. * @param {Array<number>} shBasis - The target array holding the SH basis.
  34052. */
  34053. static getBasisAt( normal, shBasis ) {
  34054. // normal is assumed to be unit length
  34055. const x = normal.x, y = normal.y, z = normal.z;
  34056. // band 0
  34057. shBasis[ 0 ] = 0.282095;
  34058. // band 1
  34059. shBasis[ 1 ] = 0.488603 * y;
  34060. shBasis[ 2 ] = 0.488603 * z;
  34061. shBasis[ 3 ] = 0.488603 * x;
  34062. // band 2
  34063. shBasis[ 4 ] = 1.092548 * x * y;
  34064. shBasis[ 5 ] = 1.092548 * y * z;
  34065. shBasis[ 6 ] = 0.315392 * ( 3 * z * z - 1 );
  34066. shBasis[ 7 ] = 1.092548 * x * z;
  34067. shBasis[ 8 ] = 0.546274 * ( x * x - y * y );
  34068. }
  34069. }
  34070. /**
  34071. * Light probes are an alternative way of adding light to a 3D scene. Unlike
  34072. * classical light sources (e.g. directional, point or spot lights), light
  34073. * probes do not emit light. Instead they store information about light
  34074. * passing through 3D space. During rendering, the light that hits a 3D
  34075. * object is approximated by using the data from the light probe.
  34076. *
  34077. * Light probes are usually created from (radiance) environment maps. The
  34078. * class {@link LightProbeGenerator} can be used to create light probes from
  34079. * cube textures or render targets. However, light estimation data could also
  34080. * be provided in other forms e.g. by WebXR. This enables the rendering of
  34081. * augmented reality content that reacts to real world lighting.
  34082. *
  34083. * The current probe implementation in three.js supports so-called diffuse
  34084. * light probes. This type of light probe is functionally equivalent to an
  34085. * irradiance environment map.
  34086. *
  34087. * @augments Light
  34088. */
  34089. class LightProbe extends Light {
  34090. /**
  34091. * Constructs a new light probe.
  34092. *
  34093. * @param {SphericalHarmonics3} sh - The spherical harmonics which represents encoded lighting information.
  34094. * @param {number} [intensity=1] - The light's strength/intensity.
  34095. */
  34096. constructor( sh = new SphericalHarmonics3(), intensity = 1 ) {
  34097. super( undefined, intensity );
  34098. /**
  34099. * This flag can be used for type testing.
  34100. *
  34101. * @type {boolean}
  34102. * @readonly
  34103. * @default true
  34104. */
  34105. this.isLightProbe = true;
  34106. /**
  34107. * A light probe uses spherical harmonics to encode lighting information.
  34108. *
  34109. * @type {SphericalHarmonics3}
  34110. */
  34111. this.sh = sh;
  34112. }
  34113. copy( source ) {
  34114. super.copy( source );
  34115. this.sh.copy( source.sh );
  34116. return this;
  34117. }
  34118. /**
  34119. * Deserializes the light prove from the given JSON.
  34120. *
  34121. * @param {Object} json - The JSON holding the serialized light probe.
  34122. * @return {LightProbe} A reference to this light probe.
  34123. */
  34124. fromJSON( json ) {
  34125. this.intensity = json.intensity; // TODO: Move this bit to Light.fromJSON();
  34126. this.sh.fromArray( json.sh );
  34127. return this;
  34128. }
  34129. toJSON( meta ) {
  34130. const data = super.toJSON( meta );
  34131. data.object.sh = this.sh.toArray();
  34132. return data;
  34133. }
  34134. }
  34135. /**
  34136. * Class for loading geometries. The files are internally
  34137. * loaded via {@link FileLoader}.
  34138. *
  34139. * ```js
  34140. * const loader = new THREE.MaterialLoader();
  34141. * const material = await loader.loadAsync( 'material.json' );
  34142. * ```
  34143. * This loader does not support node materials. Use {@link NodeMaterialLoader} instead.
  34144. *
  34145. * @augments Loader
  34146. */
  34147. class MaterialLoader extends Loader {
  34148. /**
  34149. * Constructs a new material loader.
  34150. *
  34151. * @param {LoadingManager} [manager] - The loading manager.
  34152. */
  34153. constructor( manager ) {
  34154. super( manager );
  34155. /**
  34156. * A dictionary holding textures used by the material.
  34157. *
  34158. * @type {Object<string,Texture>}
  34159. */
  34160. this.textures = {};
  34161. }
  34162. /**
  34163. * Starts loading from the given URL and pass the loaded material to the `onLoad()` callback.
  34164. *
  34165. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  34166. * @param {function(Material)} onLoad - Executed when the loading process has been finished.
  34167. * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
  34168. * @param {onErrorCallback} onError - Executed when errors occur.
  34169. */
  34170. load( url, onLoad, onProgress, onError ) {
  34171. const scope = this;
  34172. const loader = new FileLoader( scope.manager );
  34173. loader.setPath( scope.path );
  34174. loader.setRequestHeader( scope.requestHeader );
  34175. loader.setWithCredentials( scope.withCredentials );
  34176. loader.load( url, function ( text ) {
  34177. try {
  34178. onLoad( scope.parse( JSON.parse( text ) ) );
  34179. } catch ( e ) {
  34180. if ( onError ) {
  34181. onError( e );
  34182. } else {
  34183. console.error( e );
  34184. }
  34185. scope.manager.itemError( url );
  34186. }
  34187. }, onProgress, onError );
  34188. }
  34189. /**
  34190. * Parses the given JSON object and returns a material.
  34191. *
  34192. * @param {Object} json - The serialized material.
  34193. * @return {Material} The parsed material.
  34194. */
  34195. parse( json ) {
  34196. const textures = this.textures;
  34197. function getTexture( name ) {
  34198. if ( textures[ name ] === undefined ) {
  34199. console.warn( 'THREE.MaterialLoader: Undefined texture', name );
  34200. }
  34201. return textures[ name ];
  34202. }
  34203. const material = this.createMaterialFromType( json.type );
  34204. if ( json.uuid !== undefined ) material.uuid = json.uuid;
  34205. if ( json.name !== undefined ) material.name = json.name;
  34206. if ( json.color !== undefined && material.color !== undefined ) material.color.setHex( json.color );
  34207. if ( json.roughness !== undefined ) material.roughness = json.roughness;
  34208. if ( json.metalness !== undefined ) material.metalness = json.metalness;
  34209. if ( json.sheen !== undefined ) material.sheen = json.sheen;
  34210. if ( json.sheenColor !== undefined ) material.sheenColor = new Color().setHex( json.sheenColor );
  34211. if ( json.sheenRoughness !== undefined ) material.sheenRoughness = json.sheenRoughness;
  34212. if ( json.emissive !== undefined && material.emissive !== undefined ) material.emissive.setHex( json.emissive );
  34213. if ( json.specular !== undefined && material.specular !== undefined ) material.specular.setHex( json.specular );
  34214. if ( json.specularIntensity !== undefined ) material.specularIntensity = json.specularIntensity;
  34215. if ( json.specularColor !== undefined && material.specularColor !== undefined ) material.specularColor.setHex( json.specularColor );
  34216. if ( json.shininess !== undefined ) material.shininess = json.shininess;
  34217. if ( json.clearcoat !== undefined ) material.clearcoat = json.clearcoat;
  34218. if ( json.clearcoatRoughness !== undefined ) material.clearcoatRoughness = json.clearcoatRoughness;
  34219. if ( json.dispersion !== undefined ) material.dispersion = json.dispersion;
  34220. if ( json.iridescence !== undefined ) material.iridescence = json.iridescence;
  34221. if ( json.iridescenceIOR !== undefined ) material.iridescenceIOR = json.iridescenceIOR;
  34222. if ( json.iridescenceThicknessRange !== undefined ) material.iridescenceThicknessRange = json.iridescenceThicknessRange;
  34223. if ( json.transmission !== undefined ) material.transmission = json.transmission;
  34224. if ( json.thickness !== undefined ) material.thickness = json.thickness;
  34225. if ( json.attenuationDistance !== undefined ) material.attenuationDistance = json.attenuationDistance;
  34226. if ( json.attenuationColor !== undefined && material.attenuationColor !== undefined ) material.attenuationColor.setHex( json.attenuationColor );
  34227. if ( json.anisotropy !== undefined ) material.anisotropy = json.anisotropy;
  34228. if ( json.anisotropyRotation !== undefined ) material.anisotropyRotation = json.anisotropyRotation;
  34229. if ( json.fog !== undefined ) material.fog = json.fog;
  34230. if ( json.flatShading !== undefined ) material.flatShading = json.flatShading;
  34231. if ( json.blending !== undefined ) material.blending = json.blending;
  34232. if ( json.combine !== undefined ) material.combine = json.combine;
  34233. if ( json.side !== undefined ) material.side = json.side;
  34234. if ( json.shadowSide !== undefined ) material.shadowSide = json.shadowSide;
  34235. if ( json.opacity !== undefined ) material.opacity = json.opacity;
  34236. if ( json.transparent !== undefined ) material.transparent = json.transparent;
  34237. if ( json.alphaTest !== undefined ) material.alphaTest = json.alphaTest;
  34238. if ( json.alphaHash !== undefined ) material.alphaHash = json.alphaHash;
  34239. if ( json.depthFunc !== undefined ) material.depthFunc = json.depthFunc;
  34240. if ( json.depthTest !== undefined ) material.depthTest = json.depthTest;
  34241. if ( json.depthWrite !== undefined ) material.depthWrite = json.depthWrite;
  34242. if ( json.colorWrite !== undefined ) material.colorWrite = json.colorWrite;
  34243. if ( json.blendSrc !== undefined ) material.blendSrc = json.blendSrc;
  34244. if ( json.blendDst !== undefined ) material.blendDst = json.blendDst;
  34245. if ( json.blendEquation !== undefined ) material.blendEquation = json.blendEquation;
  34246. if ( json.blendSrcAlpha !== undefined ) material.blendSrcAlpha = json.blendSrcAlpha;
  34247. if ( json.blendDstAlpha !== undefined ) material.blendDstAlpha = json.blendDstAlpha;
  34248. if ( json.blendEquationAlpha !== undefined ) material.blendEquationAlpha = json.blendEquationAlpha;
  34249. if ( json.blendColor !== undefined && material.blendColor !== undefined ) material.blendColor.setHex( json.blendColor );
  34250. if ( json.blendAlpha !== undefined ) material.blendAlpha = json.blendAlpha;
  34251. if ( json.stencilWriteMask !== undefined ) material.stencilWriteMask = json.stencilWriteMask;
  34252. if ( json.stencilFunc !== undefined ) material.stencilFunc = json.stencilFunc;
  34253. if ( json.stencilRef !== undefined ) material.stencilRef = json.stencilRef;
  34254. if ( json.stencilFuncMask !== undefined ) material.stencilFuncMask = json.stencilFuncMask;
  34255. if ( json.stencilFail !== undefined ) material.stencilFail = json.stencilFail;
  34256. if ( json.stencilZFail !== undefined ) material.stencilZFail = json.stencilZFail;
  34257. if ( json.stencilZPass !== undefined ) material.stencilZPass = json.stencilZPass;
  34258. if ( json.stencilWrite !== undefined ) material.stencilWrite = json.stencilWrite;
  34259. if ( json.wireframe !== undefined ) material.wireframe = json.wireframe;
  34260. if ( json.wireframeLinewidth !== undefined ) material.wireframeLinewidth = json.wireframeLinewidth;
  34261. if ( json.wireframeLinecap !== undefined ) material.wireframeLinecap = json.wireframeLinecap;
  34262. if ( json.wireframeLinejoin !== undefined ) material.wireframeLinejoin = json.wireframeLinejoin;
  34263. if ( json.rotation !== undefined ) material.rotation = json.rotation;
  34264. if ( json.linewidth !== undefined ) material.linewidth = json.linewidth;
  34265. if ( json.dashSize !== undefined ) material.dashSize = json.dashSize;
  34266. if ( json.gapSize !== undefined ) material.gapSize = json.gapSize;
  34267. if ( json.scale !== undefined ) material.scale = json.scale;
  34268. if ( json.polygonOffset !== undefined ) material.polygonOffset = json.polygonOffset;
  34269. if ( json.polygonOffsetFactor !== undefined ) material.polygonOffsetFactor = json.polygonOffsetFactor;
  34270. if ( json.polygonOffsetUnits !== undefined ) material.polygonOffsetUnits = json.polygonOffsetUnits;
  34271. if ( json.dithering !== undefined ) material.dithering = json.dithering;
  34272. if ( json.alphaToCoverage !== undefined ) material.alphaToCoverage = json.alphaToCoverage;
  34273. if ( json.premultipliedAlpha !== undefined ) material.premultipliedAlpha = json.premultipliedAlpha;
  34274. if ( json.forceSinglePass !== undefined ) material.forceSinglePass = json.forceSinglePass;
  34275. if ( json.visible !== undefined ) material.visible = json.visible;
  34276. if ( json.toneMapped !== undefined ) material.toneMapped = json.toneMapped;
  34277. if ( json.userData !== undefined ) material.userData = json.userData;
  34278. if ( json.vertexColors !== undefined ) {
  34279. if ( typeof json.vertexColors === 'number' ) {
  34280. material.vertexColors = ( json.vertexColors > 0 ) ? true : false;
  34281. } else {
  34282. material.vertexColors = json.vertexColors;
  34283. }
  34284. }
  34285. // Shader Material
  34286. if ( json.uniforms !== undefined ) {
  34287. for ( const name in json.uniforms ) {
  34288. const uniform = json.uniforms[ name ];
  34289. material.uniforms[ name ] = {};
  34290. switch ( uniform.type ) {
  34291. case 't':
  34292. material.uniforms[ name ].value = getTexture( uniform.value );
  34293. break;
  34294. case 'c':
  34295. material.uniforms[ name ].value = new Color().setHex( uniform.value );
  34296. break;
  34297. case 'v2':
  34298. material.uniforms[ name ].value = new Vector2().fromArray( uniform.value );
  34299. break;
  34300. case 'v3':
  34301. material.uniforms[ name ].value = new Vector3().fromArray( uniform.value );
  34302. break;
  34303. case 'v4':
  34304. material.uniforms[ name ].value = new Vector4().fromArray( uniform.value );
  34305. break;
  34306. case 'm3':
  34307. material.uniforms[ name ].value = new Matrix3().fromArray( uniform.value );
  34308. break;
  34309. case 'm4':
  34310. material.uniforms[ name ].value = new Matrix4().fromArray( uniform.value );
  34311. break;
  34312. default:
  34313. material.uniforms[ name ].value = uniform.value;
  34314. }
  34315. }
  34316. }
  34317. if ( json.defines !== undefined ) material.defines = json.defines;
  34318. if ( json.vertexShader !== undefined ) material.vertexShader = json.vertexShader;
  34319. if ( json.fragmentShader !== undefined ) material.fragmentShader = json.fragmentShader;
  34320. if ( json.glslVersion !== undefined ) material.glslVersion = json.glslVersion;
  34321. if ( json.extensions !== undefined ) {
  34322. for ( const key in json.extensions ) {
  34323. material.extensions[ key ] = json.extensions[ key ];
  34324. }
  34325. }
  34326. if ( json.lights !== undefined ) material.lights = json.lights;
  34327. if ( json.clipping !== undefined ) material.clipping = json.clipping;
  34328. // for PointsMaterial
  34329. if ( json.size !== undefined ) material.size = json.size;
  34330. if ( json.sizeAttenuation !== undefined ) material.sizeAttenuation = json.sizeAttenuation;
  34331. // maps
  34332. if ( json.map !== undefined ) material.map = getTexture( json.map );
  34333. if ( json.matcap !== undefined ) material.matcap = getTexture( json.matcap );
  34334. if ( json.alphaMap !== undefined ) material.alphaMap = getTexture( json.alphaMap );
  34335. if ( json.bumpMap !== undefined ) material.bumpMap = getTexture( json.bumpMap );
  34336. if ( json.bumpScale !== undefined ) material.bumpScale = json.bumpScale;
  34337. if ( json.normalMap !== undefined ) material.normalMap = getTexture( json.normalMap );
  34338. if ( json.normalMapType !== undefined ) material.normalMapType = json.normalMapType;
  34339. if ( json.normalScale !== undefined ) {
  34340. let normalScale = json.normalScale;
  34341. if ( Array.isArray( normalScale ) === false ) {
  34342. // Blender exporter used to export a scalar. See #7459
  34343. normalScale = [ normalScale, normalScale ];
  34344. }
  34345. material.normalScale = new Vector2().fromArray( normalScale );
  34346. }
  34347. if ( json.displacementMap !== undefined ) material.displacementMap = getTexture( json.displacementMap );
  34348. if ( json.displacementScale !== undefined ) material.displacementScale = json.displacementScale;
  34349. if ( json.displacementBias !== undefined ) material.displacementBias = json.displacementBias;
  34350. if ( json.roughnessMap !== undefined ) material.roughnessMap = getTexture( json.roughnessMap );
  34351. if ( json.metalnessMap !== undefined ) material.metalnessMap = getTexture( json.metalnessMap );
  34352. if ( json.emissiveMap !== undefined ) material.emissiveMap = getTexture( json.emissiveMap );
  34353. if ( json.emissiveIntensity !== undefined ) material.emissiveIntensity = json.emissiveIntensity;
  34354. if ( json.specularMap !== undefined ) material.specularMap = getTexture( json.specularMap );
  34355. if ( json.specularIntensityMap !== undefined ) material.specularIntensityMap = getTexture( json.specularIntensityMap );
  34356. if ( json.specularColorMap !== undefined ) material.specularColorMap = getTexture( json.specularColorMap );
  34357. if ( json.envMap !== undefined ) material.envMap = getTexture( json.envMap );
  34358. if ( json.envMapRotation !== undefined ) material.envMapRotation.fromArray( json.envMapRotation );
  34359. if ( json.envMapIntensity !== undefined ) material.envMapIntensity = json.envMapIntensity;
  34360. if ( json.reflectivity !== undefined ) material.reflectivity = json.reflectivity;
  34361. if ( json.refractionRatio !== undefined ) material.refractionRatio = json.refractionRatio;
  34362. if ( json.lightMap !== undefined ) material.lightMap = getTexture( json.lightMap );
  34363. if ( json.lightMapIntensity !== undefined ) material.lightMapIntensity = json.lightMapIntensity;
  34364. if ( json.aoMap !== undefined ) material.aoMap = getTexture( json.aoMap );
  34365. if ( json.aoMapIntensity !== undefined ) material.aoMapIntensity = json.aoMapIntensity;
  34366. if ( json.gradientMap !== undefined ) material.gradientMap = getTexture( json.gradientMap );
  34367. if ( json.clearcoatMap !== undefined ) material.clearcoatMap = getTexture( json.clearcoatMap );
  34368. if ( json.clearcoatRoughnessMap !== undefined ) material.clearcoatRoughnessMap = getTexture( json.clearcoatRoughnessMap );
  34369. if ( json.clearcoatNormalMap !== undefined ) material.clearcoatNormalMap = getTexture( json.clearcoatNormalMap );
  34370. if ( json.clearcoatNormalScale !== undefined ) material.clearcoatNormalScale = new Vector2().fromArray( json.clearcoatNormalScale );
  34371. if ( json.iridescenceMap !== undefined ) material.iridescenceMap = getTexture( json.iridescenceMap );
  34372. if ( json.iridescenceThicknessMap !== undefined ) material.iridescenceThicknessMap = getTexture( json.iridescenceThicknessMap );
  34373. if ( json.transmissionMap !== undefined ) material.transmissionMap = getTexture( json.transmissionMap );
  34374. if ( json.thicknessMap !== undefined ) material.thicknessMap = getTexture( json.thicknessMap );
  34375. if ( json.anisotropyMap !== undefined ) material.anisotropyMap = getTexture( json.anisotropyMap );
  34376. if ( json.sheenColorMap !== undefined ) material.sheenColorMap = getTexture( json.sheenColorMap );
  34377. if ( json.sheenRoughnessMap !== undefined ) material.sheenRoughnessMap = getTexture( json.sheenRoughnessMap );
  34378. return material;
  34379. }
  34380. /**
  34381. * Textures are not embedded in the material JSON so they have
  34382. * to be injected before the loading process starts.
  34383. *
  34384. * @param {Object} value - A dictionary holding textures for material properties.
  34385. * @return {MaterialLoader} A reference to this material loader.
  34386. */
  34387. setTextures( value ) {
  34388. this.textures = value;
  34389. return this;
  34390. }
  34391. /**
  34392. * Creates a material for the given type.
  34393. *
  34394. * @param {string} type - The material type.
  34395. * @return {Material} The new material.
  34396. */
  34397. createMaterialFromType( type ) {
  34398. return MaterialLoader.createMaterialFromType( type );
  34399. }
  34400. /**
  34401. * Creates a material for the given type.
  34402. *
  34403. * @static
  34404. * @param {string} type - The material type.
  34405. * @return {Material} The new material.
  34406. */
  34407. static createMaterialFromType( type ) {
  34408. const materialLib = {
  34409. ShadowMaterial,
  34410. SpriteMaterial,
  34411. RawShaderMaterial,
  34412. ShaderMaterial,
  34413. PointsMaterial,
  34414. MeshPhysicalMaterial,
  34415. MeshStandardMaterial,
  34416. MeshPhongMaterial,
  34417. MeshToonMaterial,
  34418. MeshNormalMaterial,
  34419. MeshLambertMaterial,
  34420. MeshDepthMaterial,
  34421. MeshDistanceMaterial,
  34422. MeshBasicMaterial,
  34423. MeshMatcapMaterial,
  34424. LineDashedMaterial,
  34425. LineBasicMaterial,
  34426. Material
  34427. };
  34428. return new materialLib[ type ]();
  34429. }
  34430. }
  34431. /**
  34432. * A class with loader utility functions.
  34433. */
  34434. class LoaderUtils {
  34435. /**
  34436. * Extracts the base URL from the given URL.
  34437. *
  34438. * @param {string} url -The URL to extract the base URL from.
  34439. * @return {string} The extracted base URL.
  34440. */
  34441. static extractUrlBase( url ) {
  34442. const index = url.lastIndexOf( '/' );
  34443. if ( index === -1 ) return './';
  34444. return url.slice( 0, index + 1 );
  34445. }
  34446. /**
  34447. * Resolves relative URLs against the given path. Absolute paths, data urls,
  34448. * and blob URLs will be returned as is. Invalid URLs will return an empty
  34449. * string.
  34450. *
  34451. * @param {string} url -The URL to resolve.
  34452. * @param {string} path - The base path for relative URLs to be resolved against.
  34453. * @return {string} The resolved URL.
  34454. */
  34455. static resolveURL( url, path ) {
  34456. // Invalid URL
  34457. if ( typeof url !== 'string' || url === '' ) return '';
  34458. // Host Relative URL
  34459. if ( /^https?:\/\//i.test( path ) && /^\//.test( url ) ) {
  34460. path = path.replace( /(^https?:\/\/[^\/]+).*/i, '$1' );
  34461. }
  34462. // Absolute URL http://,https://,//
  34463. if ( /^(https?:)?\/\//i.test( url ) ) return url;
  34464. // Data URI
  34465. if ( /^data:.*,.*$/i.test( url ) ) return url;
  34466. // Blob URL
  34467. if ( /^blob:.*$/i.test( url ) ) return url;
  34468. // Relative URL
  34469. return path + url;
  34470. }
  34471. }
  34472. /**
  34473. * An instanced version of a geometry.
  34474. */
  34475. class InstancedBufferGeometry extends BufferGeometry {
  34476. /**
  34477. * Constructs a new instanced buffer geometry.
  34478. */
  34479. constructor() {
  34480. super();
  34481. /**
  34482. * This flag can be used for type testing.
  34483. *
  34484. * @type {boolean}
  34485. * @readonly
  34486. * @default true
  34487. */
  34488. this.isInstancedBufferGeometry = true;
  34489. this.type = 'InstancedBufferGeometry';
  34490. /**
  34491. * The instance count.
  34492. *
  34493. * @type {number}
  34494. * @default Infinity
  34495. */
  34496. this.instanceCount = Infinity;
  34497. }
  34498. copy( source ) {
  34499. super.copy( source );
  34500. this.instanceCount = source.instanceCount;
  34501. return this;
  34502. }
  34503. toJSON() {
  34504. const data = super.toJSON();
  34505. data.instanceCount = this.instanceCount;
  34506. data.isInstancedBufferGeometry = true;
  34507. return data;
  34508. }
  34509. }
  34510. /**
  34511. * Class for loading geometries. The files are internally
  34512. * loaded via {@link FileLoader}.
  34513. *
  34514. * ```js
  34515. * const loader = new THREE.BufferGeometryLoader();
  34516. * const geometry = await loader.loadAsync( 'models/json/pressure.json' );
  34517. *
  34518. * const material = new THREE.MeshBasicMaterial( { color: 0xF5F5F5 } );
  34519. * const object = new THREE.Mesh( geometry, material );
  34520. * scene.add( object );
  34521. * ```
  34522. *
  34523. * @augments Loader
  34524. */
  34525. class BufferGeometryLoader extends Loader {
  34526. /**
  34527. * Constructs a new geometry loader.
  34528. *
  34529. * @param {LoadingManager} [manager] - The loading manager.
  34530. */
  34531. constructor( manager ) {
  34532. super( manager );
  34533. }
  34534. /**
  34535. * Starts loading from the given URL and pass the loaded geometry to the `onLoad()` callback.
  34536. *
  34537. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  34538. * @param {function(BufferGeometry)} onLoad - Executed when the loading process has been finished.
  34539. * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
  34540. * @param {onErrorCallback} onError - Executed when errors occur.
  34541. */
  34542. load( url, onLoad, onProgress, onError ) {
  34543. const scope = this;
  34544. const loader = new FileLoader( scope.manager );
  34545. loader.setPath( scope.path );
  34546. loader.setRequestHeader( scope.requestHeader );
  34547. loader.setWithCredentials( scope.withCredentials );
  34548. loader.load( url, function ( text ) {
  34549. try {
  34550. onLoad( scope.parse( JSON.parse( text ) ) );
  34551. } catch ( e ) {
  34552. if ( onError ) {
  34553. onError( e );
  34554. } else {
  34555. console.error( e );
  34556. }
  34557. scope.manager.itemError( url );
  34558. }
  34559. }, onProgress, onError );
  34560. }
  34561. /**
  34562. * Parses the given JSON object and returns a geometry.
  34563. *
  34564. * @param {Object} json - The serialized geometry.
  34565. * @return {BufferGeometry} The parsed geometry.
  34566. */
  34567. parse( json ) {
  34568. const interleavedBufferMap = {};
  34569. const arrayBufferMap = {};
  34570. function getInterleavedBuffer( json, uuid ) {
  34571. if ( interleavedBufferMap[ uuid ] !== undefined ) return interleavedBufferMap[ uuid ];
  34572. const interleavedBuffers = json.interleavedBuffers;
  34573. const interleavedBuffer = interleavedBuffers[ uuid ];
  34574. const buffer = getArrayBuffer( json, interleavedBuffer.buffer );
  34575. const array = getTypedArray( interleavedBuffer.type, buffer );
  34576. const ib = new InterleavedBuffer( array, interleavedBuffer.stride );
  34577. ib.uuid = interleavedBuffer.uuid;
  34578. interleavedBufferMap[ uuid ] = ib;
  34579. return ib;
  34580. }
  34581. function getArrayBuffer( json, uuid ) {
  34582. if ( arrayBufferMap[ uuid ] !== undefined ) return arrayBufferMap[ uuid ];
  34583. const arrayBuffers = json.arrayBuffers;
  34584. const arrayBuffer = arrayBuffers[ uuid ];
  34585. const ab = new Uint32Array( arrayBuffer ).buffer;
  34586. arrayBufferMap[ uuid ] = ab;
  34587. return ab;
  34588. }
  34589. const geometry = json.isInstancedBufferGeometry ? new InstancedBufferGeometry() : new BufferGeometry();
  34590. const index = json.data.index;
  34591. if ( index !== undefined ) {
  34592. const typedArray = getTypedArray( index.type, index.array );
  34593. geometry.setIndex( new BufferAttribute( typedArray, 1 ) );
  34594. }
  34595. const attributes = json.data.attributes;
  34596. for ( const key in attributes ) {
  34597. const attribute = attributes[ key ];
  34598. let bufferAttribute;
  34599. if ( attribute.isInterleavedBufferAttribute ) {
  34600. const interleavedBuffer = getInterleavedBuffer( json.data, attribute.data );
  34601. bufferAttribute = new InterleavedBufferAttribute( interleavedBuffer, attribute.itemSize, attribute.offset, attribute.normalized );
  34602. } else {
  34603. const typedArray = getTypedArray( attribute.type, attribute.array );
  34604. const bufferAttributeConstr = attribute.isInstancedBufferAttribute ? InstancedBufferAttribute : BufferAttribute;
  34605. bufferAttribute = new bufferAttributeConstr( typedArray, attribute.itemSize, attribute.normalized );
  34606. }
  34607. if ( attribute.name !== undefined ) bufferAttribute.name = attribute.name;
  34608. if ( attribute.usage !== undefined ) bufferAttribute.setUsage( attribute.usage );
  34609. geometry.setAttribute( key, bufferAttribute );
  34610. }
  34611. const morphAttributes = json.data.morphAttributes;
  34612. if ( morphAttributes ) {
  34613. for ( const key in morphAttributes ) {
  34614. const attributeArray = morphAttributes[ key ];
  34615. const array = [];
  34616. for ( let i = 0, il = attributeArray.length; i < il; i ++ ) {
  34617. const attribute = attributeArray[ i ];
  34618. let bufferAttribute;
  34619. if ( attribute.isInterleavedBufferAttribute ) {
  34620. const interleavedBuffer = getInterleavedBuffer( json.data, attribute.data );
  34621. bufferAttribute = new InterleavedBufferAttribute( interleavedBuffer, attribute.itemSize, attribute.offset, attribute.normalized );
  34622. } else {
  34623. const typedArray = getTypedArray( attribute.type, attribute.array );
  34624. bufferAttribute = new BufferAttribute( typedArray, attribute.itemSize, attribute.normalized );
  34625. }
  34626. if ( attribute.name !== undefined ) bufferAttribute.name = attribute.name;
  34627. array.push( bufferAttribute );
  34628. }
  34629. geometry.morphAttributes[ key ] = array;
  34630. }
  34631. }
  34632. const morphTargetsRelative = json.data.morphTargetsRelative;
  34633. if ( morphTargetsRelative ) {
  34634. geometry.morphTargetsRelative = true;
  34635. }
  34636. const groups = json.data.groups || json.data.drawcalls || json.data.offsets;
  34637. if ( groups !== undefined ) {
  34638. for ( let i = 0, n = groups.length; i !== n; ++ i ) {
  34639. const group = groups[ i ];
  34640. geometry.addGroup( group.start, group.count, group.materialIndex );
  34641. }
  34642. }
  34643. const boundingSphere = json.data.boundingSphere;
  34644. if ( boundingSphere !== undefined ) {
  34645. geometry.boundingSphere = new Sphere().fromJSON( boundingSphere );
  34646. }
  34647. if ( json.name ) geometry.name = json.name;
  34648. if ( json.userData ) geometry.userData = json.userData;
  34649. return geometry;
  34650. }
  34651. }
  34652. /**
  34653. * 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}.
  34654. * The files are internally loaded via {@link FileLoader}.
  34655. *
  34656. * ```js
  34657. * const loader = new THREE.ObjectLoader();
  34658. * const obj = await loader.loadAsync( 'models/json/example.json' );
  34659. * scene.add( obj );
  34660. *
  34661. * // Alternatively, to parse a previously loaded JSON structure
  34662. * const object = await loader.parseAsync( a_json_object );
  34663. * scene.add( object );
  34664. * ```
  34665. *
  34666. * @augments Loader
  34667. */
  34668. class ObjectLoader extends Loader {
  34669. /**
  34670. * Constructs a new object loader.
  34671. *
  34672. * @param {LoadingManager} [manager] - The loading manager.
  34673. */
  34674. constructor( manager ) {
  34675. super( manager );
  34676. }
  34677. /**
  34678. * Starts loading from the given URL and pass the loaded 3D object to the `onLoad()` callback.
  34679. *
  34680. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  34681. * @param {function(Object3D)} onLoad - Executed when the loading process has been finished.
  34682. * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
  34683. * @param {onErrorCallback} onError - Executed when errors occur.
  34684. */
  34685. load( url, onLoad, onProgress, onError ) {
  34686. const scope = this;
  34687. const path = ( this.path === '' ) ? LoaderUtils.extractUrlBase( url ) : this.path;
  34688. this.resourcePath = this.resourcePath || path;
  34689. const loader = new FileLoader( this.manager );
  34690. loader.setPath( this.path );
  34691. loader.setRequestHeader( this.requestHeader );
  34692. loader.setWithCredentials( this.withCredentials );
  34693. loader.load( url, function ( text ) {
  34694. let json = null;
  34695. try {
  34696. json = JSON.parse( text );
  34697. } catch ( error ) {
  34698. if ( onError !== undefined ) onError( error );
  34699. console.error( 'THREE:ObjectLoader: Can\'t parse ' + url + '.', error.message );
  34700. return;
  34701. }
  34702. const metadata = json.metadata;
  34703. if ( metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry' ) {
  34704. if ( onError !== undefined ) onError( new Error( 'THREE.ObjectLoader: Can\'t load ' + url ) );
  34705. console.error( 'THREE.ObjectLoader: Can\'t load ' + url );
  34706. return;
  34707. }
  34708. scope.parse( json, onLoad );
  34709. }, onProgress, onError );
  34710. }
  34711. /**
  34712. * Async version of {@link ObjectLoader#load}.
  34713. *
  34714. * @async
  34715. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  34716. * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
  34717. * @return {Promise<Object3D>} A Promise that resolves with the loaded 3D object.
  34718. */
  34719. async loadAsync( url, onProgress ) {
  34720. const scope = this;
  34721. const path = ( this.path === '' ) ? LoaderUtils.extractUrlBase( url ) : this.path;
  34722. this.resourcePath = this.resourcePath || path;
  34723. const loader = new FileLoader( this.manager );
  34724. loader.setPath( this.path );
  34725. loader.setRequestHeader( this.requestHeader );
  34726. loader.setWithCredentials( this.withCredentials );
  34727. const text = await loader.loadAsync( url, onProgress );
  34728. const json = JSON.parse( text );
  34729. const metadata = json.metadata;
  34730. if ( metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry' ) {
  34731. throw new Error( 'THREE.ObjectLoader: Can\'t load ' + url );
  34732. }
  34733. return await scope.parseAsync( json );
  34734. }
  34735. /**
  34736. * Parses the given JSON. This is used internally by {@link ObjectLoader#load}
  34737. * but can also be used directly to parse a previously loaded JSON structure.
  34738. *
  34739. * @param {Object} json - The serialized 3D object.
  34740. * @param {onLoad} onLoad - Executed when all resources (e.g. textures) have been fully loaded.
  34741. * @return {Object3D} The parsed 3D object.
  34742. */
  34743. parse( json, onLoad ) {
  34744. const animations = this.parseAnimations( json.animations );
  34745. const shapes = this.parseShapes( json.shapes );
  34746. const geometries = this.parseGeometries( json.geometries, shapes );
  34747. const images = this.parseImages( json.images, function () {
  34748. if ( onLoad !== undefined ) onLoad( object );
  34749. } );
  34750. const textures = this.parseTextures( json.textures, images );
  34751. const materials = this.parseMaterials( json.materials, textures );
  34752. const object = this.parseObject( json.object, geometries, materials, textures, animations );
  34753. const skeletons = this.parseSkeletons( json.skeletons, object );
  34754. this.bindSkeletons( object, skeletons );
  34755. this.bindLightTargets( object );
  34756. //
  34757. if ( onLoad !== undefined ) {
  34758. let hasImages = false;
  34759. for ( const uuid in images ) {
  34760. if ( images[ uuid ].data instanceof HTMLImageElement ) {
  34761. hasImages = true;
  34762. break;
  34763. }
  34764. }
  34765. if ( hasImages === false ) onLoad( object );
  34766. }
  34767. return object;
  34768. }
  34769. /**
  34770. * Async version of {@link ObjectLoader#parse}.
  34771. *
  34772. * @param {Object} json - The serialized 3D object.
  34773. * @return {Promise<Object3D>} A Promise that resolves with the parsed 3D object.
  34774. */
  34775. async parseAsync( json ) {
  34776. const animations = this.parseAnimations( json.animations );
  34777. const shapes = this.parseShapes( json.shapes );
  34778. const geometries = this.parseGeometries( json.geometries, shapes );
  34779. const images = await this.parseImagesAsync( json.images );
  34780. const textures = this.parseTextures( json.textures, images );
  34781. const materials = this.parseMaterials( json.materials, textures );
  34782. const object = this.parseObject( json.object, geometries, materials, textures, animations );
  34783. const skeletons = this.parseSkeletons( json.skeletons, object );
  34784. this.bindSkeletons( object, skeletons );
  34785. this.bindLightTargets( object );
  34786. return object;
  34787. }
  34788. // internals
  34789. parseShapes( json ) {
  34790. const shapes = {};
  34791. if ( json !== undefined ) {
  34792. for ( let i = 0, l = json.length; i < l; i ++ ) {
  34793. const shape = new Shape().fromJSON( json[ i ] );
  34794. shapes[ shape.uuid ] = shape;
  34795. }
  34796. }
  34797. return shapes;
  34798. }
  34799. parseSkeletons( json, object ) {
  34800. const skeletons = {};
  34801. const bones = {};
  34802. // generate bone lookup table
  34803. object.traverse( function ( child ) {
  34804. if ( child.isBone ) bones[ child.uuid ] = child;
  34805. } );
  34806. // create skeletons
  34807. if ( json !== undefined ) {
  34808. for ( let i = 0, l = json.length; i < l; i ++ ) {
  34809. const skeleton = new Skeleton().fromJSON( json[ i ], bones );
  34810. skeletons[ skeleton.uuid ] = skeleton;
  34811. }
  34812. }
  34813. return skeletons;
  34814. }
  34815. parseGeometries( json, shapes ) {
  34816. const geometries = {};
  34817. if ( json !== undefined ) {
  34818. const bufferGeometryLoader = new BufferGeometryLoader();
  34819. for ( let i = 0, l = json.length; i < l; i ++ ) {
  34820. let geometry;
  34821. const data = json[ i ];
  34822. switch ( data.type ) {
  34823. case 'BufferGeometry':
  34824. case 'InstancedBufferGeometry':
  34825. geometry = bufferGeometryLoader.parse( data );
  34826. break;
  34827. default:
  34828. if ( data.type in Geometries ) {
  34829. geometry = Geometries[ data.type ].fromJSON( data, shapes );
  34830. } else {
  34831. console.warn( `THREE.ObjectLoader: Unsupported geometry type "${ data.type }"` );
  34832. }
  34833. }
  34834. geometry.uuid = data.uuid;
  34835. if ( data.name !== undefined ) geometry.name = data.name;
  34836. if ( data.userData !== undefined ) geometry.userData = data.userData;
  34837. geometries[ data.uuid ] = geometry;
  34838. }
  34839. }
  34840. return geometries;
  34841. }
  34842. parseMaterials( json, textures ) {
  34843. const cache = {}; // MultiMaterial
  34844. const materials = {};
  34845. if ( json !== undefined ) {
  34846. const loader = new MaterialLoader();
  34847. loader.setTextures( textures );
  34848. for ( let i = 0, l = json.length; i < l; i ++ ) {
  34849. const data = json[ i ];
  34850. if ( cache[ data.uuid ] === undefined ) {
  34851. cache[ data.uuid ] = loader.parse( data );
  34852. }
  34853. materials[ data.uuid ] = cache[ data.uuid ];
  34854. }
  34855. }
  34856. return materials;
  34857. }
  34858. parseAnimations( json ) {
  34859. const animations = {};
  34860. if ( json !== undefined ) {
  34861. for ( let i = 0; i < json.length; i ++ ) {
  34862. const data = json[ i ];
  34863. const clip = AnimationClip.parse( data );
  34864. animations[ clip.uuid ] = clip;
  34865. }
  34866. }
  34867. return animations;
  34868. }
  34869. parseImages( json, onLoad ) {
  34870. const scope = this;
  34871. const images = {};
  34872. let loader;
  34873. function loadImage( url ) {
  34874. scope.manager.itemStart( url );
  34875. return loader.load( url, function () {
  34876. scope.manager.itemEnd( url );
  34877. }, undefined, function () {
  34878. scope.manager.itemError( url );
  34879. scope.manager.itemEnd( url );
  34880. } );
  34881. }
  34882. function deserializeImage( image ) {
  34883. if ( typeof image === 'string' ) {
  34884. const url = image;
  34885. const path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test( url ) ? url : scope.resourcePath + url;
  34886. return loadImage( path );
  34887. } else {
  34888. if ( image.data ) {
  34889. return {
  34890. data: getTypedArray( image.type, image.data ),
  34891. width: image.width,
  34892. height: image.height
  34893. };
  34894. } else {
  34895. return null;
  34896. }
  34897. }
  34898. }
  34899. if ( json !== undefined && json.length > 0 ) {
  34900. const manager = new LoadingManager( onLoad );
  34901. loader = new ImageLoader( manager );
  34902. loader.setCrossOrigin( this.crossOrigin );
  34903. for ( let i = 0, il = json.length; i < il; i ++ ) {
  34904. const image = json[ i ];
  34905. const url = image.url;
  34906. if ( Array.isArray( url ) ) {
  34907. // load array of images e.g CubeTexture
  34908. const imageArray = [];
  34909. for ( let j = 0, jl = url.length; j < jl; j ++ ) {
  34910. const currentUrl = url[ j ];
  34911. const deserializedImage = deserializeImage( currentUrl );
  34912. if ( deserializedImage !== null ) {
  34913. if ( deserializedImage instanceof HTMLImageElement ) {
  34914. imageArray.push( deserializedImage );
  34915. } else {
  34916. // special case: handle array of data textures for cube textures
  34917. imageArray.push( new DataTexture( deserializedImage.data, deserializedImage.width, deserializedImage.height ) );
  34918. }
  34919. }
  34920. }
  34921. images[ image.uuid ] = new Source( imageArray );
  34922. } else {
  34923. // load single image
  34924. const deserializedImage = deserializeImage( image.url );
  34925. images[ image.uuid ] = new Source( deserializedImage );
  34926. }
  34927. }
  34928. }
  34929. return images;
  34930. }
  34931. async parseImagesAsync( json ) {
  34932. const scope = this;
  34933. const images = {};
  34934. let loader;
  34935. async function deserializeImage( image ) {
  34936. if ( typeof image === 'string' ) {
  34937. const url = image;
  34938. const path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test( url ) ? url : scope.resourcePath + url;
  34939. return await loader.loadAsync( path );
  34940. } else {
  34941. if ( image.data ) {
  34942. return {
  34943. data: getTypedArray( image.type, image.data ),
  34944. width: image.width,
  34945. height: image.height
  34946. };
  34947. } else {
  34948. return null;
  34949. }
  34950. }
  34951. }
  34952. if ( json !== undefined && json.length > 0 ) {
  34953. loader = new ImageLoader( this.manager );
  34954. loader.setCrossOrigin( this.crossOrigin );
  34955. for ( let i = 0, il = json.length; i < il; i ++ ) {
  34956. const image = json[ i ];
  34957. const url = image.url;
  34958. if ( Array.isArray( url ) ) {
  34959. // load array of images e.g CubeTexture
  34960. const imageArray = [];
  34961. for ( let j = 0, jl = url.length; j < jl; j ++ ) {
  34962. const currentUrl = url[ j ];
  34963. const deserializedImage = await deserializeImage( currentUrl );
  34964. if ( deserializedImage !== null ) {
  34965. if ( deserializedImage instanceof HTMLImageElement ) {
  34966. imageArray.push( deserializedImage );
  34967. } else {
  34968. // special case: handle array of data textures for cube textures
  34969. imageArray.push( new DataTexture( deserializedImage.data, deserializedImage.width, deserializedImage.height ) );
  34970. }
  34971. }
  34972. }
  34973. images[ image.uuid ] = new Source( imageArray );
  34974. } else {
  34975. // load single image
  34976. const deserializedImage = await deserializeImage( image.url );
  34977. images[ image.uuid ] = new Source( deserializedImage );
  34978. }
  34979. }
  34980. }
  34981. return images;
  34982. }
  34983. parseTextures( json, images ) {
  34984. function parseConstant( value, type ) {
  34985. if ( typeof value === 'number' ) return value;
  34986. console.warn( 'THREE.ObjectLoader.parseTexture: Constant should be in numeric form.', value );
  34987. return type[ value ];
  34988. }
  34989. const textures = {};
  34990. if ( json !== undefined ) {
  34991. for ( let i = 0, l = json.length; i < l; i ++ ) {
  34992. const data = json[ i ];
  34993. if ( data.image === undefined ) {
  34994. console.warn( 'THREE.ObjectLoader: No "image" specified for', data.uuid );
  34995. }
  34996. if ( images[ data.image ] === undefined ) {
  34997. console.warn( 'THREE.ObjectLoader: Undefined image', data.image );
  34998. }
  34999. const source = images[ data.image ];
  35000. const image = source.data;
  35001. let texture;
  35002. if ( Array.isArray( image ) ) {
  35003. texture = new CubeTexture();
  35004. if ( image.length === 6 ) texture.needsUpdate = true;
  35005. } else {
  35006. if ( image && image.data ) {
  35007. texture = new DataTexture();
  35008. } else {
  35009. texture = new Texture();
  35010. }
  35011. if ( image ) texture.needsUpdate = true; // textures can have undefined image data
  35012. }
  35013. texture.source = source;
  35014. texture.uuid = data.uuid;
  35015. if ( data.name !== undefined ) texture.name = data.name;
  35016. if ( data.mapping !== undefined ) texture.mapping = parseConstant( data.mapping, TEXTURE_MAPPING );
  35017. if ( data.channel !== undefined ) texture.channel = data.channel;
  35018. if ( data.offset !== undefined ) texture.offset.fromArray( data.offset );
  35019. if ( data.repeat !== undefined ) texture.repeat.fromArray( data.repeat );
  35020. if ( data.center !== undefined ) texture.center.fromArray( data.center );
  35021. if ( data.rotation !== undefined ) texture.rotation = data.rotation;
  35022. if ( data.wrap !== undefined ) {
  35023. texture.wrapS = parseConstant( data.wrap[ 0 ], TEXTURE_WRAPPING );
  35024. texture.wrapT = parseConstant( data.wrap[ 1 ], TEXTURE_WRAPPING );
  35025. }
  35026. if ( data.format !== undefined ) texture.format = data.format;
  35027. if ( data.internalFormat !== undefined ) texture.internalFormat = data.internalFormat;
  35028. if ( data.type !== undefined ) texture.type = data.type;
  35029. if ( data.colorSpace !== undefined ) texture.colorSpace = data.colorSpace;
  35030. if ( data.minFilter !== undefined ) texture.minFilter = parseConstant( data.minFilter, TEXTURE_FILTER );
  35031. if ( data.magFilter !== undefined ) texture.magFilter = parseConstant( data.magFilter, TEXTURE_FILTER );
  35032. if ( data.anisotropy !== undefined ) texture.anisotropy = data.anisotropy;
  35033. if ( data.flipY !== undefined ) texture.flipY = data.flipY;
  35034. if ( data.generateMipmaps !== undefined ) texture.generateMipmaps = data.generateMipmaps;
  35035. if ( data.premultiplyAlpha !== undefined ) texture.premultiplyAlpha = data.premultiplyAlpha;
  35036. if ( data.unpackAlignment !== undefined ) texture.unpackAlignment = data.unpackAlignment;
  35037. if ( data.compareFunction !== undefined ) texture.compareFunction = data.compareFunction;
  35038. if ( data.userData !== undefined ) texture.userData = data.userData;
  35039. textures[ data.uuid ] = texture;
  35040. }
  35041. }
  35042. return textures;
  35043. }
  35044. parseObject( data, geometries, materials, textures, animations ) {
  35045. let object;
  35046. function getGeometry( name ) {
  35047. if ( geometries[ name ] === undefined ) {
  35048. console.warn( 'THREE.ObjectLoader: Undefined geometry', name );
  35049. }
  35050. return geometries[ name ];
  35051. }
  35052. function getMaterial( name ) {
  35053. if ( name === undefined ) return undefined;
  35054. if ( Array.isArray( name ) ) {
  35055. const array = [];
  35056. for ( let i = 0, l = name.length; i < l; i ++ ) {
  35057. const uuid = name[ i ];
  35058. if ( materials[ uuid ] === undefined ) {
  35059. console.warn( 'THREE.ObjectLoader: Undefined material', uuid );
  35060. }
  35061. array.push( materials[ uuid ] );
  35062. }
  35063. return array;
  35064. }
  35065. if ( materials[ name ] === undefined ) {
  35066. console.warn( 'THREE.ObjectLoader: Undefined material', name );
  35067. }
  35068. return materials[ name ];
  35069. }
  35070. function getTexture( uuid ) {
  35071. if ( textures[ uuid ] === undefined ) {
  35072. console.warn( 'THREE.ObjectLoader: Undefined texture', uuid );
  35073. }
  35074. return textures[ uuid ];
  35075. }
  35076. let geometry, material;
  35077. switch ( data.type ) {
  35078. case 'Scene':
  35079. object = new Scene();
  35080. if ( data.background !== undefined ) {
  35081. if ( Number.isInteger( data.background ) ) {
  35082. object.background = new Color( data.background );
  35083. } else {
  35084. object.background = getTexture( data.background );
  35085. }
  35086. }
  35087. if ( data.environment !== undefined ) {
  35088. object.environment = getTexture( data.environment );
  35089. }
  35090. if ( data.fog !== undefined ) {
  35091. if ( data.fog.type === 'Fog' ) {
  35092. object.fog = new Fog( data.fog.color, data.fog.near, data.fog.far );
  35093. } else if ( data.fog.type === 'FogExp2' ) {
  35094. object.fog = new FogExp2( data.fog.color, data.fog.density );
  35095. }
  35096. if ( data.fog.name !== '' ) {
  35097. object.fog.name = data.fog.name;
  35098. }
  35099. }
  35100. if ( data.backgroundBlurriness !== undefined ) object.backgroundBlurriness = data.backgroundBlurriness;
  35101. if ( data.backgroundIntensity !== undefined ) object.backgroundIntensity = data.backgroundIntensity;
  35102. if ( data.backgroundRotation !== undefined ) object.backgroundRotation.fromArray( data.backgroundRotation );
  35103. if ( data.environmentIntensity !== undefined ) object.environmentIntensity = data.environmentIntensity;
  35104. if ( data.environmentRotation !== undefined ) object.environmentRotation.fromArray( data.environmentRotation );
  35105. break;
  35106. case 'PerspectiveCamera':
  35107. object = new PerspectiveCamera( data.fov, data.aspect, data.near, data.far );
  35108. if ( data.focus !== undefined ) object.focus = data.focus;
  35109. if ( data.zoom !== undefined ) object.zoom = data.zoom;
  35110. if ( data.filmGauge !== undefined ) object.filmGauge = data.filmGauge;
  35111. if ( data.filmOffset !== undefined ) object.filmOffset = data.filmOffset;
  35112. if ( data.view !== undefined ) object.view = Object.assign( {}, data.view );
  35113. break;
  35114. case 'OrthographicCamera':
  35115. object = new OrthographicCamera( data.left, data.right, data.top, data.bottom, data.near, data.far );
  35116. if ( data.zoom !== undefined ) object.zoom = data.zoom;
  35117. if ( data.view !== undefined ) object.view = Object.assign( {}, data.view );
  35118. break;
  35119. case 'AmbientLight':
  35120. object = new AmbientLight( data.color, data.intensity );
  35121. break;
  35122. case 'DirectionalLight':
  35123. object = new DirectionalLight( data.color, data.intensity );
  35124. object.target = data.target || '';
  35125. break;
  35126. case 'PointLight':
  35127. object = new PointLight( data.color, data.intensity, data.distance, data.decay );
  35128. break;
  35129. case 'RectAreaLight':
  35130. object = new RectAreaLight( data.color, data.intensity, data.width, data.height );
  35131. break;
  35132. case 'SpotLight':
  35133. object = new SpotLight( data.color, data.intensity, data.distance, data.angle, data.penumbra, data.decay );
  35134. object.target = data.target || '';
  35135. break;
  35136. case 'HemisphereLight':
  35137. object = new HemisphereLight( data.color, data.groundColor, data.intensity );
  35138. break;
  35139. case 'LightProbe':
  35140. object = new LightProbe().fromJSON( data );
  35141. break;
  35142. case 'SkinnedMesh':
  35143. geometry = getGeometry( data.geometry );
  35144. material = getMaterial( data.material );
  35145. object = new SkinnedMesh( geometry, material );
  35146. if ( data.bindMode !== undefined ) object.bindMode = data.bindMode;
  35147. if ( data.bindMatrix !== undefined ) object.bindMatrix.fromArray( data.bindMatrix );
  35148. if ( data.skeleton !== undefined ) object.skeleton = data.skeleton;
  35149. break;
  35150. case 'Mesh':
  35151. geometry = getGeometry( data.geometry );
  35152. material = getMaterial( data.material );
  35153. object = new Mesh( geometry, material );
  35154. break;
  35155. case 'InstancedMesh':
  35156. geometry = getGeometry( data.geometry );
  35157. material = getMaterial( data.material );
  35158. const count = data.count;
  35159. const instanceMatrix = data.instanceMatrix;
  35160. const instanceColor = data.instanceColor;
  35161. object = new InstancedMesh( geometry, material, count );
  35162. object.instanceMatrix = new InstancedBufferAttribute( new Float32Array( instanceMatrix.array ), 16 );
  35163. if ( instanceColor !== undefined ) object.instanceColor = new InstancedBufferAttribute( new Float32Array( instanceColor.array ), instanceColor.itemSize );
  35164. break;
  35165. case 'BatchedMesh':
  35166. geometry = getGeometry( data.geometry );
  35167. material = getMaterial( data.material );
  35168. object = new BatchedMesh( data.maxInstanceCount, data.maxVertexCount, data.maxIndexCount, material );
  35169. object.geometry = geometry;
  35170. object.perObjectFrustumCulled = data.perObjectFrustumCulled;
  35171. object.sortObjects = data.sortObjects;
  35172. object._drawRanges = data.drawRanges;
  35173. object._reservedRanges = data.reservedRanges;
  35174. object._geometryInfo = data.geometryInfo.map( info => {
  35175. let box = null;
  35176. let sphere = null;
  35177. if ( info.boundingBox !== undefined ) {
  35178. box = new Box3().fromJSON( info.boundingBox );
  35179. }
  35180. if ( info.boundingSphere !== undefined ) {
  35181. sphere = new Sphere().fromJSON( info.boundingSphere );
  35182. }
  35183. return {
  35184. ...info,
  35185. boundingBox: box,
  35186. boundingSphere: sphere
  35187. };
  35188. } );
  35189. object._instanceInfo = data.instanceInfo;
  35190. object._availableInstanceIds = data._availableInstanceIds;
  35191. object._availableGeometryIds = data._availableGeometryIds;
  35192. object._nextIndexStart = data.nextIndexStart;
  35193. object._nextVertexStart = data.nextVertexStart;
  35194. object._geometryCount = data.geometryCount;
  35195. object._maxInstanceCount = data.maxInstanceCount;
  35196. object._maxVertexCount = data.maxVertexCount;
  35197. object._maxIndexCount = data.maxIndexCount;
  35198. object._geometryInitialized = data.geometryInitialized;
  35199. object._matricesTexture = getTexture( data.matricesTexture.uuid );
  35200. object._indirectTexture = getTexture( data.indirectTexture.uuid );
  35201. if ( data.colorsTexture !== undefined ) {
  35202. object._colorsTexture = getTexture( data.colorsTexture.uuid );
  35203. }
  35204. if ( data.boundingSphere !== undefined ) {
  35205. object.boundingSphere = new Sphere().fromJSON( data.boundingSphere );
  35206. }
  35207. if ( data.boundingBox !== undefined ) {
  35208. object.boundingBox = new Box3().fromJSON( data.boundingBox );
  35209. }
  35210. break;
  35211. case 'LOD':
  35212. object = new LOD();
  35213. break;
  35214. case 'Line':
  35215. object = new Line( getGeometry( data.geometry ), getMaterial( data.material ) );
  35216. break;
  35217. case 'LineLoop':
  35218. object = new LineLoop( getGeometry( data.geometry ), getMaterial( data.material ) );
  35219. break;
  35220. case 'LineSegments':
  35221. object = new LineSegments( getGeometry( data.geometry ), getMaterial( data.material ) );
  35222. break;
  35223. case 'PointCloud':
  35224. case 'Points':
  35225. object = new Points( getGeometry( data.geometry ), getMaterial( data.material ) );
  35226. break;
  35227. case 'Sprite':
  35228. object = new Sprite( getMaterial( data.material ) );
  35229. break;
  35230. case 'Group':
  35231. object = new Group();
  35232. break;
  35233. case 'Bone':
  35234. object = new Bone();
  35235. break;
  35236. default:
  35237. object = new Object3D();
  35238. }
  35239. object.uuid = data.uuid;
  35240. if ( data.name !== undefined ) object.name = data.name;
  35241. if ( data.matrix !== undefined ) {
  35242. object.matrix.fromArray( data.matrix );
  35243. if ( data.matrixAutoUpdate !== undefined ) object.matrixAutoUpdate = data.matrixAutoUpdate;
  35244. if ( object.matrixAutoUpdate ) object.matrix.decompose( object.position, object.quaternion, object.scale );
  35245. } else {
  35246. if ( data.position !== undefined ) object.position.fromArray( data.position );
  35247. if ( data.rotation !== undefined ) object.rotation.fromArray( data.rotation );
  35248. if ( data.quaternion !== undefined ) object.quaternion.fromArray( data.quaternion );
  35249. if ( data.scale !== undefined ) object.scale.fromArray( data.scale );
  35250. }
  35251. if ( data.up !== undefined ) object.up.fromArray( data.up );
  35252. if ( data.castShadow !== undefined ) object.castShadow = data.castShadow;
  35253. if ( data.receiveShadow !== undefined ) object.receiveShadow = data.receiveShadow;
  35254. if ( data.shadow ) {
  35255. if ( data.shadow.intensity !== undefined ) object.shadow.intensity = data.shadow.intensity;
  35256. if ( data.shadow.bias !== undefined ) object.shadow.bias = data.shadow.bias;
  35257. if ( data.shadow.normalBias !== undefined ) object.shadow.normalBias = data.shadow.normalBias;
  35258. if ( data.shadow.radius !== undefined ) object.shadow.radius = data.shadow.radius;
  35259. if ( data.shadow.mapSize !== undefined ) object.shadow.mapSize.fromArray( data.shadow.mapSize );
  35260. if ( data.shadow.camera !== undefined ) object.shadow.camera = this.parseObject( data.shadow.camera );
  35261. }
  35262. if ( data.visible !== undefined ) object.visible = data.visible;
  35263. if ( data.frustumCulled !== undefined ) object.frustumCulled = data.frustumCulled;
  35264. if ( data.renderOrder !== undefined ) object.renderOrder = data.renderOrder;
  35265. if ( data.userData !== undefined ) object.userData = data.userData;
  35266. if ( data.layers !== undefined ) object.layers.mask = data.layers;
  35267. if ( data.children !== undefined ) {
  35268. const children = data.children;
  35269. for ( let i = 0; i < children.length; i ++ ) {
  35270. object.add( this.parseObject( children[ i ], geometries, materials, textures, animations ) );
  35271. }
  35272. }
  35273. if ( data.animations !== undefined ) {
  35274. const objectAnimations = data.animations;
  35275. for ( let i = 0; i < objectAnimations.length; i ++ ) {
  35276. const uuid = objectAnimations[ i ];
  35277. object.animations.push( animations[ uuid ] );
  35278. }
  35279. }
  35280. if ( data.type === 'LOD' ) {
  35281. if ( data.autoUpdate !== undefined ) object.autoUpdate = data.autoUpdate;
  35282. const levels = data.levels;
  35283. for ( let l = 0; l < levels.length; l ++ ) {
  35284. const level = levels[ l ];
  35285. const child = object.getObjectByProperty( 'uuid', level.object );
  35286. if ( child !== undefined ) {
  35287. object.addLevel( child, level.distance, level.hysteresis );
  35288. }
  35289. }
  35290. }
  35291. return object;
  35292. }
  35293. bindSkeletons( object, skeletons ) {
  35294. if ( Object.keys( skeletons ).length === 0 ) return;
  35295. object.traverse( function ( child ) {
  35296. if ( child.isSkinnedMesh === true && child.skeleton !== undefined ) {
  35297. const skeleton = skeletons[ child.skeleton ];
  35298. if ( skeleton === undefined ) {
  35299. console.warn( 'THREE.ObjectLoader: No skeleton found with UUID:', child.skeleton );
  35300. } else {
  35301. child.bind( skeleton, child.bindMatrix );
  35302. }
  35303. }
  35304. } );
  35305. }
  35306. bindLightTargets( object ) {
  35307. object.traverse( function ( child ) {
  35308. if ( child.isDirectionalLight || child.isSpotLight ) {
  35309. const uuid = child.target;
  35310. const target = object.getObjectByProperty( 'uuid', uuid );
  35311. if ( target !== undefined ) {
  35312. child.target = target;
  35313. } else {
  35314. child.target = new Object3D();
  35315. }
  35316. }
  35317. } );
  35318. }
  35319. }
  35320. const TEXTURE_MAPPING = {
  35321. UVMapping: UVMapping,
  35322. CubeReflectionMapping: CubeReflectionMapping,
  35323. CubeRefractionMapping: CubeRefractionMapping,
  35324. EquirectangularReflectionMapping: EquirectangularReflectionMapping,
  35325. EquirectangularRefractionMapping: EquirectangularRefractionMapping,
  35326. CubeUVReflectionMapping: CubeUVReflectionMapping
  35327. };
  35328. const TEXTURE_WRAPPING = {
  35329. RepeatWrapping: RepeatWrapping,
  35330. ClampToEdgeWrapping: ClampToEdgeWrapping,
  35331. MirroredRepeatWrapping: MirroredRepeatWrapping
  35332. };
  35333. const TEXTURE_FILTER = {
  35334. NearestFilter: NearestFilter,
  35335. NearestMipmapNearestFilter: NearestMipmapNearestFilter,
  35336. NearestMipmapLinearFilter: NearestMipmapLinearFilter,
  35337. LinearFilter: LinearFilter,
  35338. LinearMipmapNearestFilter: LinearMipmapNearestFilter,
  35339. LinearMipmapLinearFilter: LinearMipmapLinearFilter
  35340. };
  35341. const _errorMap = new WeakMap();
  35342. /**
  35343. * A loader for loading images as an [ImageBitmap]{@link https://developer.mozilla.org/en-US/docs/Web/API/ImageBitmap}.
  35344. * An `ImageBitmap` provides an asynchronous and resource efficient pathway to prepare
  35345. * textures for rendering.
  35346. *
  35347. * Note that {@link Texture#flipY} and {@link Texture#premultiplyAlpha} are ignored with image bitmaps.
  35348. * They needs these configuration on bitmap creation unlike regular images need them on uploading to GPU.
  35349. *
  35350. * You need to set the equivalent options via {@link ImageBitmapLoader#setOptions} instead.
  35351. *
  35352. * Also note that unlike {@link FileLoader}, this loader avoids multiple concurrent requests to the same URL only if `Cache` is enabled.
  35353. *
  35354. * ```js
  35355. * const loader = new THREE.ImageBitmapLoader();
  35356. * loader.setOptions( { imageOrientation: 'flipY' } ); // set options if needed
  35357. * const imageBitmap = await loader.loadAsync( 'image.png' );
  35358. *
  35359. * const texture = new THREE.Texture( imageBitmap );
  35360. * texture.needsUpdate = true;
  35361. * ```
  35362. *
  35363. * @augments Loader
  35364. */
  35365. class ImageBitmapLoader extends Loader {
  35366. /**
  35367. * Constructs a new image bitmap loader.
  35368. *
  35369. * @param {LoadingManager} [manager] - The loading manager.
  35370. */
  35371. constructor( manager ) {
  35372. super( manager );
  35373. /**
  35374. * This flag can be used for type testing.
  35375. *
  35376. * @type {boolean}
  35377. * @readonly
  35378. * @default true
  35379. */
  35380. this.isImageBitmapLoader = true;
  35381. if ( typeof createImageBitmap === 'undefined' ) {
  35382. console.warn( 'THREE.ImageBitmapLoader: createImageBitmap() not supported.' );
  35383. }
  35384. if ( typeof fetch === 'undefined' ) {
  35385. console.warn( 'THREE.ImageBitmapLoader: fetch() not supported.' );
  35386. }
  35387. /**
  35388. * Represents the loader options.
  35389. *
  35390. * @type {Object}
  35391. * @default {premultiplyAlpha:'none'}
  35392. */
  35393. this.options = { premultiplyAlpha: 'none' };
  35394. }
  35395. /**
  35396. * Sets the given loader options. The structure of the object must match the `options` parameter of
  35397. * [createImageBitmap]{@link https://developer.mozilla.org/en-US/docs/Web/API/Window/createImageBitmap}.
  35398. *
  35399. * @param {Object} options - The loader options to set.
  35400. * @return {ImageBitmapLoader} A reference to this image bitmap loader.
  35401. */
  35402. setOptions( options ) {
  35403. this.options = options;
  35404. return this;
  35405. }
  35406. /**
  35407. * Starts loading from the given URL and pass the loaded image bitmap to the `onLoad()` callback.
  35408. *
  35409. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  35410. * @param {function(ImageBitmap)} onLoad - Executed when the loading process has been finished.
  35411. * @param {onProgressCallback} onProgress - Unsupported in this loader.
  35412. * @param {onErrorCallback} onError - Executed when errors occur.
  35413. * @return {ImageBitmap|undefined} The image bitmap.
  35414. */
  35415. load( url, onLoad, onProgress, onError ) {
  35416. if ( url === undefined ) url = '';
  35417. if ( this.path !== undefined ) url = this.path + url;
  35418. url = this.manager.resolveURL( url );
  35419. const scope = this;
  35420. const cached = Cache.get( url );
  35421. if ( cached !== undefined ) {
  35422. scope.manager.itemStart( url );
  35423. // If cached is a promise, wait for it to resolve
  35424. if ( cached.then ) {
  35425. cached.then( imageBitmap => {
  35426. // check if there is an error for the cached promise
  35427. if ( _errorMap.has( cached ) === true ) {
  35428. if ( onError ) onError( _errorMap.get( cached ) );
  35429. scope.manager.itemError( url );
  35430. scope.manager.itemEnd( url );
  35431. } else {
  35432. if ( onLoad ) onLoad( imageBitmap );
  35433. scope.manager.itemEnd( url );
  35434. return imageBitmap;
  35435. }
  35436. } );
  35437. return;
  35438. }
  35439. // If cached is not a promise (i.e., it's already an imageBitmap)
  35440. setTimeout( function () {
  35441. if ( onLoad ) onLoad( cached );
  35442. scope.manager.itemEnd( url );
  35443. }, 0 );
  35444. return cached;
  35445. }
  35446. const fetchOptions = {};
  35447. fetchOptions.credentials = ( this.crossOrigin === 'anonymous' ) ? 'same-origin' : 'include';
  35448. fetchOptions.headers = this.requestHeader;
  35449. const promise = fetch( url, fetchOptions ).then( function ( res ) {
  35450. return res.blob();
  35451. } ).then( function ( blob ) {
  35452. return createImageBitmap( blob, Object.assign( scope.options, { colorSpaceConversion: 'none' } ) );
  35453. } ).then( function ( imageBitmap ) {
  35454. Cache.add( url, imageBitmap );
  35455. if ( onLoad ) onLoad( imageBitmap );
  35456. scope.manager.itemEnd( url );
  35457. return imageBitmap;
  35458. } ).catch( function ( e ) {
  35459. if ( onError ) onError( e );
  35460. _errorMap.set( promise, e );
  35461. Cache.remove( url );
  35462. scope.manager.itemError( url );
  35463. scope.manager.itemEnd( url );
  35464. } );
  35465. Cache.add( url, promise );
  35466. scope.manager.itemStart( url );
  35467. }
  35468. }
  35469. let _context;
  35470. /**
  35471. * Manages the global audio context in the engine.
  35472. *
  35473. * @hideconstructor
  35474. */
  35475. class AudioContext {
  35476. /**
  35477. * Returns the global native audio context.
  35478. *
  35479. * @return {AudioContext} The native audio context.
  35480. */
  35481. static getContext() {
  35482. if ( _context === undefined ) {
  35483. _context = new ( window.AudioContext || window.webkitAudioContext )();
  35484. }
  35485. return _context;
  35486. }
  35487. /**
  35488. * Allows to set the global native audio context from outside.
  35489. *
  35490. * @param {AudioContext} value - The native context to set.
  35491. */
  35492. static setContext( value ) {
  35493. _context = value;
  35494. }
  35495. }
  35496. /**
  35497. * Class for loading audio buffers. Audios are internally
  35498. * loaded via {@link FileLoader}.
  35499. *
  35500. * ```js
  35501. * const audioListener = new THREE.AudioListener();
  35502. * const ambientSound = new THREE.Audio( audioListener );
  35503. *
  35504. * const loader = new THREE.AudioLoader();
  35505. * const audioBuffer = await loader.loadAsync( 'audio/ambient_ocean.ogg' );
  35506. *
  35507. * ambientSound.setBuffer( audioBuffer );
  35508. * ambientSound.play();
  35509. * ```
  35510. *
  35511. * @augments Loader
  35512. */
  35513. class AudioLoader extends Loader {
  35514. /**
  35515. * Constructs a new audio loader.
  35516. *
  35517. * @param {LoadingManager} [manager] - The loading manager.
  35518. */
  35519. constructor( manager ) {
  35520. super( manager );
  35521. }
  35522. /**
  35523. * Starts loading from the given URL and passes the loaded audio buffer
  35524. * to the `onLoad()` callback.
  35525. *
  35526. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  35527. * @param {function(AudioBuffer)} onLoad - Executed when the loading process has been finished.
  35528. * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
  35529. * @param {onErrorCallback} onError - Executed when errors occur.
  35530. */
  35531. load( url, onLoad, onProgress, onError ) {
  35532. const scope = this;
  35533. const loader = new FileLoader( this.manager );
  35534. loader.setResponseType( 'arraybuffer' );
  35535. loader.setPath( this.path );
  35536. loader.setRequestHeader( this.requestHeader );
  35537. loader.setWithCredentials( this.withCredentials );
  35538. loader.load( url, function ( buffer ) {
  35539. try {
  35540. // Create a copy of the buffer. The `decodeAudioData` method
  35541. // detaches the buffer when complete, preventing reuse.
  35542. const bufferCopy = buffer.slice( 0 );
  35543. const context = AudioContext.getContext();
  35544. context.decodeAudioData( bufferCopy, function ( audioBuffer ) {
  35545. onLoad( audioBuffer );
  35546. } ).catch( handleError );
  35547. } catch ( e ) {
  35548. handleError( e );
  35549. }
  35550. }, onProgress, onError );
  35551. function handleError( e ) {
  35552. if ( onError ) {
  35553. onError( e );
  35554. } else {
  35555. console.error( e );
  35556. }
  35557. scope.manager.itemError( url );
  35558. }
  35559. }
  35560. }
  35561. const _eyeRight = /*@__PURE__*/ new Matrix4();
  35562. const _eyeLeft = /*@__PURE__*/ new Matrix4();
  35563. const _projectionMatrix = /*@__PURE__*/ new Matrix4();
  35564. /**
  35565. * A special type of camera that uses two perspective cameras with
  35566. * stereoscopic projection. Can be used for rendering stereo effects
  35567. * like [3D Anaglyph]{@link https://en.wikipedia.org/wiki/Anaglyph_3D} or
  35568. * [Parallax Barrier]{@link https://en.wikipedia.org/wiki/parallax_barrier}.
  35569. */
  35570. class StereoCamera {
  35571. /**
  35572. * Constructs a new stereo camera.
  35573. */
  35574. constructor() {
  35575. /**
  35576. * The type property is used for detecting the object type
  35577. * in context of serialization/deserialization.
  35578. *
  35579. * @type {string}
  35580. * @readonly
  35581. */
  35582. this.type = 'StereoCamera';
  35583. /**
  35584. * The aspect.
  35585. *
  35586. * @type {number}
  35587. * @default 1
  35588. */
  35589. this.aspect = 1;
  35590. /**
  35591. * The eye separation which represents the distance
  35592. * between the left and right camera.
  35593. *
  35594. * @type {number}
  35595. * @default 0.064
  35596. */
  35597. this.eyeSep = 0.064;
  35598. /**
  35599. * The camera representing the left eye. This is added to layer `1` so objects to be
  35600. * rendered by the left camera must also be added to this layer.
  35601. *
  35602. * @type {PerspectiveCamera}
  35603. */
  35604. this.cameraL = new PerspectiveCamera();
  35605. this.cameraL.layers.enable( 1 );
  35606. this.cameraL.matrixAutoUpdate = false;
  35607. /**
  35608. * The camera representing the right eye. This is added to layer `2` so objects to be
  35609. * rendered by the right camera must also be added to this layer.
  35610. *
  35611. * @type {PerspectiveCamera}
  35612. */
  35613. this.cameraR = new PerspectiveCamera();
  35614. this.cameraR.layers.enable( 2 );
  35615. this.cameraR.matrixAutoUpdate = false;
  35616. this._cache = {
  35617. focus: null,
  35618. fov: null,
  35619. aspect: null,
  35620. near: null,
  35621. far: null,
  35622. zoom: null,
  35623. eyeSep: null
  35624. };
  35625. }
  35626. /**
  35627. * Updates the stereo camera based on the given perspective camera.
  35628. *
  35629. * @param {PerspectiveCamera} camera - The perspective camera.
  35630. */
  35631. update( camera ) {
  35632. const cache = this._cache;
  35633. const needsUpdate = cache.focus !== camera.focus || cache.fov !== camera.fov ||
  35634. cache.aspect !== camera.aspect * this.aspect || cache.near !== camera.near ||
  35635. cache.far !== camera.far || cache.zoom !== camera.zoom || cache.eyeSep !== this.eyeSep;
  35636. if ( needsUpdate ) {
  35637. cache.focus = camera.focus;
  35638. cache.fov = camera.fov;
  35639. cache.aspect = camera.aspect * this.aspect;
  35640. cache.near = camera.near;
  35641. cache.far = camera.far;
  35642. cache.zoom = camera.zoom;
  35643. cache.eyeSep = this.eyeSep;
  35644. // Off-axis stereoscopic effect based on
  35645. // http://paulbourke.net/stereographics/stereorender/
  35646. _projectionMatrix.copy( camera.projectionMatrix );
  35647. const eyeSepHalf = cache.eyeSep / 2;
  35648. const eyeSepOnProjection = eyeSepHalf * cache.near / cache.focus;
  35649. const ymax = ( cache.near * Math.tan( DEG2RAD * cache.fov * 0.5 ) ) / cache.zoom;
  35650. let xmin, xmax;
  35651. // translate xOffset
  35652. _eyeLeft.elements[ 12 ] = - eyeSepHalf;
  35653. _eyeRight.elements[ 12 ] = eyeSepHalf;
  35654. // for left eye
  35655. xmin = - ymax * cache.aspect + eyeSepOnProjection;
  35656. xmax = ymax * cache.aspect + eyeSepOnProjection;
  35657. _projectionMatrix.elements[ 0 ] = 2 * cache.near / ( xmax - xmin );
  35658. _projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin );
  35659. this.cameraL.projectionMatrix.copy( _projectionMatrix );
  35660. // for right eye
  35661. xmin = - ymax * cache.aspect - eyeSepOnProjection;
  35662. xmax = ymax * cache.aspect - eyeSepOnProjection;
  35663. _projectionMatrix.elements[ 0 ] = 2 * cache.near / ( xmax - xmin );
  35664. _projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin );
  35665. this.cameraR.projectionMatrix.copy( _projectionMatrix );
  35666. }
  35667. this.cameraL.matrixWorld.copy( camera.matrixWorld ).multiply( _eyeLeft );
  35668. this.cameraR.matrixWorld.copy( camera.matrixWorld ).multiply( _eyeRight );
  35669. }
  35670. }
  35671. /**
  35672. * This type of camera can be used in order to efficiently render a scene with a
  35673. * predefined set of cameras. This is an important performance aspect for
  35674. * rendering VR scenes.
  35675. *
  35676. * An instance of `ArrayCamera` always has an array of sub cameras. It's mandatory
  35677. * to define for each sub camera the `viewport` property which determines the
  35678. * part of the viewport that is rendered with this camera.
  35679. *
  35680. * @augments PerspectiveCamera
  35681. */
  35682. class ArrayCamera extends PerspectiveCamera {
  35683. /**
  35684. * Constructs a new array camera.
  35685. *
  35686. * @param {Array<PerspectiveCamera>} [array=[]] - An array of perspective sub cameras.
  35687. */
  35688. constructor( array = [] ) {
  35689. super();
  35690. /**
  35691. * This flag can be used for type testing.
  35692. *
  35693. * @type {boolean}
  35694. * @readonly
  35695. * @default true
  35696. */
  35697. this.isArrayCamera = true;
  35698. /**
  35699. * Whether this camera is used with multiview rendering or not.
  35700. *
  35701. * @type {boolean}
  35702. * @readonly
  35703. * @default false
  35704. */
  35705. this.isMultiViewCamera = false;
  35706. /**
  35707. * An array of perspective sub cameras.
  35708. *
  35709. * @type {Array<PerspectiveCamera>}
  35710. */
  35711. this.cameras = array;
  35712. }
  35713. }
  35714. /**
  35715. * Class for keeping track of time.
  35716. */
  35717. class Clock {
  35718. /**
  35719. * Constructs a new clock.
  35720. *
  35721. * @param {boolean} [autoStart=true] - Whether to automatically start the clock when
  35722. * `getDelta()` is called for the first time.
  35723. */
  35724. constructor( autoStart = true ) {
  35725. /**
  35726. * If set to `true`, the clock starts automatically when `getDelta()` is called
  35727. * for the first time.
  35728. *
  35729. * @type {boolean}
  35730. * @default true
  35731. */
  35732. this.autoStart = autoStart;
  35733. /**
  35734. * Holds the time at which the clock's `start()` method was last called.
  35735. *
  35736. * @type {number}
  35737. * @default 0
  35738. */
  35739. this.startTime = 0;
  35740. /**
  35741. * Holds the time at which the clock's `start()`, `getElapsedTime()` or
  35742. * `getDelta()` methods were last called.
  35743. *
  35744. * @type {number}
  35745. * @default 0
  35746. */
  35747. this.oldTime = 0;
  35748. /**
  35749. * Keeps track of the total time that the clock has been running.
  35750. *
  35751. * @type {number}
  35752. * @default 0
  35753. */
  35754. this.elapsedTime = 0;
  35755. /**
  35756. * Whether the clock is running or not.
  35757. *
  35758. * @type {boolean}
  35759. * @default true
  35760. */
  35761. this.running = false;
  35762. }
  35763. /**
  35764. * Starts the clock. When `autoStart` is set to `true`, the method is automatically
  35765. * called by the class.
  35766. */
  35767. start() {
  35768. this.startTime = now();
  35769. this.oldTime = this.startTime;
  35770. this.elapsedTime = 0;
  35771. this.running = true;
  35772. }
  35773. /**
  35774. * Stops the clock.
  35775. */
  35776. stop() {
  35777. this.getElapsedTime();
  35778. this.running = false;
  35779. this.autoStart = false;
  35780. }
  35781. /**
  35782. * Returns the elapsed time in seconds.
  35783. *
  35784. * @return {number} The elapsed time.
  35785. */
  35786. getElapsedTime() {
  35787. this.getDelta();
  35788. return this.elapsedTime;
  35789. }
  35790. /**
  35791. * Returns the delta time in seconds.
  35792. *
  35793. * @return {number} The delta time.
  35794. */
  35795. getDelta() {
  35796. let diff = 0;
  35797. if ( this.autoStart && ! this.running ) {
  35798. this.start();
  35799. return 0;
  35800. }
  35801. if ( this.running ) {
  35802. const newTime = now();
  35803. diff = ( newTime - this.oldTime ) / 1000;
  35804. this.oldTime = newTime;
  35805. this.elapsedTime += diff;
  35806. }
  35807. return diff;
  35808. }
  35809. }
  35810. function now() {
  35811. return performance.now();
  35812. }
  35813. const _position$1 = /*@__PURE__*/ new Vector3();
  35814. const _quaternion$1 = /*@__PURE__*/ new Quaternion();
  35815. const _scale$1 = /*@__PURE__*/ new Vector3();
  35816. const _forward = /*@__PURE__*/ new Vector3();
  35817. const _up = /*@__PURE__*/ new Vector3();
  35818. /**
  35819. * The class represents a virtual listener of the all positional and non-positional audio effects
  35820. * in the scene. A three.js application usually creates a single listener. It is a mandatory
  35821. * constructor parameter for audios entities like {@link Audio} and {@link PositionalAudio}.
  35822. *
  35823. * In most cases, the listener object is a child of the camera. So the 3D transformation of the
  35824. * camera represents the 3D transformation of the listener.
  35825. *
  35826. * @augments Object3D
  35827. */
  35828. class AudioListener extends Object3D {
  35829. /**
  35830. * Constructs a new audio listener.
  35831. */
  35832. constructor() {
  35833. super();
  35834. this.type = 'AudioListener';
  35835. /**
  35836. * The native audio context.
  35837. *
  35838. * @type {AudioContext}
  35839. * @readonly
  35840. */
  35841. this.context = AudioContext.getContext();
  35842. /**
  35843. * The gain node used for volume control.
  35844. *
  35845. * @type {GainNode}
  35846. * @readonly
  35847. */
  35848. this.gain = this.context.createGain();
  35849. this.gain.connect( this.context.destination );
  35850. /**
  35851. * An optional filter.
  35852. *
  35853. * Defined via {@link AudioListener#setFilter}.
  35854. *
  35855. * @type {?AudioNode}
  35856. * @default null
  35857. * @readonly
  35858. */
  35859. this.filter = null;
  35860. /**
  35861. * Time delta values required for `linearRampToValueAtTime()` usage.
  35862. *
  35863. * @type {number}
  35864. * @default 0
  35865. * @readonly
  35866. */
  35867. this.timeDelta = 0;
  35868. // private
  35869. this._clock = new Clock();
  35870. }
  35871. /**
  35872. * Returns the listener's input node.
  35873. *
  35874. * This method is used by other audio nodes to connect to this listener.
  35875. *
  35876. * @return {GainNode} The input node.
  35877. */
  35878. getInput() {
  35879. return this.gain;
  35880. }
  35881. /**
  35882. * Removes the current filter from this listener.
  35883. *
  35884. * @return {AudioListener} A reference to this listener.
  35885. */
  35886. removeFilter() {
  35887. if ( this.filter !== null ) {
  35888. this.gain.disconnect( this.filter );
  35889. this.filter.disconnect( this.context.destination );
  35890. this.gain.connect( this.context.destination );
  35891. this.filter = null;
  35892. }
  35893. return this;
  35894. }
  35895. /**
  35896. * Returns the current set filter.
  35897. *
  35898. * @return {?AudioNode} The filter.
  35899. */
  35900. getFilter() {
  35901. return this.filter;
  35902. }
  35903. /**
  35904. * Sets the given filter to this listener.
  35905. *
  35906. * @param {AudioNode} value - The filter to set.
  35907. * @return {AudioListener} A reference to this listener.
  35908. */
  35909. setFilter( value ) {
  35910. if ( this.filter !== null ) {
  35911. this.gain.disconnect( this.filter );
  35912. this.filter.disconnect( this.context.destination );
  35913. } else {
  35914. this.gain.disconnect( this.context.destination );
  35915. }
  35916. this.filter = value;
  35917. this.gain.connect( this.filter );
  35918. this.filter.connect( this.context.destination );
  35919. return this;
  35920. }
  35921. /**
  35922. * Returns the applications master volume.
  35923. *
  35924. * @return {number} The master volume.
  35925. */
  35926. getMasterVolume() {
  35927. return this.gain.gain.value;
  35928. }
  35929. /**
  35930. * Sets the applications master volume. This volume setting affects
  35931. * all audio nodes in the scene.
  35932. *
  35933. * @param {number} value - The master volume to set.
  35934. * @return {AudioListener} A reference to this listener.
  35935. */
  35936. setMasterVolume( value ) {
  35937. this.gain.gain.setTargetAtTime( value, this.context.currentTime, 0.01 );
  35938. return this;
  35939. }
  35940. updateMatrixWorld( force ) {
  35941. super.updateMatrixWorld( force );
  35942. const listener = this.context.listener;
  35943. this.timeDelta = this._clock.getDelta();
  35944. this.matrixWorld.decompose( _position$1, _quaternion$1, _scale$1 );
  35945. // the initial forward and up directions must be orthogonal
  35946. _forward.set( 0, 0, -1 ).applyQuaternion( _quaternion$1 );
  35947. _up.set( 0, 1, 0 ).applyQuaternion( _quaternion$1 );
  35948. if ( listener.positionX ) {
  35949. // code path for Chrome (see #14393)
  35950. const endTime = this.context.currentTime + this.timeDelta;
  35951. listener.positionX.linearRampToValueAtTime( _position$1.x, endTime );
  35952. listener.positionY.linearRampToValueAtTime( _position$1.y, endTime );
  35953. listener.positionZ.linearRampToValueAtTime( _position$1.z, endTime );
  35954. listener.forwardX.linearRampToValueAtTime( _forward.x, endTime );
  35955. listener.forwardY.linearRampToValueAtTime( _forward.y, endTime );
  35956. listener.forwardZ.linearRampToValueAtTime( _forward.z, endTime );
  35957. listener.upX.linearRampToValueAtTime( _up.x, endTime );
  35958. listener.upY.linearRampToValueAtTime( _up.y, endTime );
  35959. listener.upZ.linearRampToValueAtTime( _up.z, endTime );
  35960. } else {
  35961. listener.setPosition( _position$1.x, _position$1.y, _position$1.z );
  35962. listener.setOrientation( _forward.x, _forward.y, _forward.z, _up.x, _up.y, _up.z );
  35963. }
  35964. }
  35965. }
  35966. /**
  35967. * Represents a non-positional ( global ) audio object.
  35968. *
  35969. * This and related audio modules make use of the [Web Audio API]{@link https://www.w3.org/TR/webaudio-1.1/}.
  35970. *
  35971. * ```js
  35972. * // create an AudioListener and add it to the camera
  35973. * const listener = new THREE.AudioListener();
  35974. * camera.add( listener );
  35975. *
  35976. * // create a global audio source
  35977. * const sound = new THREE.Audio( listener );
  35978. *
  35979. * // load a sound and set it as the Audio object's buffer
  35980. * const audioLoader = new THREE.AudioLoader();
  35981. * audioLoader.load( 'sounds/ambient.ogg', function( buffer ) {
  35982. * sound.setBuffer( buffer );
  35983. * sound.setLoop( true );
  35984. * sound.setVolume( 0.5 );
  35985. * sound.play();
  35986. * });
  35987. * ```
  35988. *
  35989. * @augments Object3D
  35990. */
  35991. class Audio extends Object3D {
  35992. /**
  35993. * Constructs a new audio.
  35994. *
  35995. * @param {AudioListener} listener - The global audio listener.
  35996. */
  35997. constructor( listener ) {
  35998. super();
  35999. this.type = 'Audio';
  36000. /**
  36001. * The global audio listener.
  36002. *
  36003. * @type {AudioListener}
  36004. * @readonly
  36005. */
  36006. this.listener = listener;
  36007. /**
  36008. * The audio context.
  36009. *
  36010. * @type {AudioContext}
  36011. * @readonly
  36012. */
  36013. this.context = listener.context;
  36014. /**
  36015. * The gain node used for volume control.
  36016. *
  36017. * @type {GainNode}
  36018. * @readonly
  36019. */
  36020. this.gain = this.context.createGain();
  36021. this.gain.connect( listener.getInput() );
  36022. /**
  36023. * Whether to start playback automatically or not.
  36024. *
  36025. * @type {boolean}
  36026. * @default false
  36027. */
  36028. this.autoplay = false;
  36029. /**
  36030. * A reference to an audio buffer.
  36031. *
  36032. * Defined via {@link Audio#setBuffer}.
  36033. *
  36034. * @type {?AudioBuffer}
  36035. * @default null
  36036. * @readonly
  36037. */
  36038. this.buffer = null;
  36039. /**
  36040. * Modify pitch, measured in cents. +/- 100 is a semitone.
  36041. * +/- 1200 is an octave.
  36042. *
  36043. * Defined via {@link Audio#setDetune}.
  36044. *
  36045. * @type {number}
  36046. * @default 0
  36047. * @readonly
  36048. */
  36049. this.detune = 0;
  36050. /**
  36051. * Whether the audio should loop or not.
  36052. *
  36053. * Defined via {@link Audio#setLoop}.
  36054. *
  36055. * @type {boolean}
  36056. * @default false
  36057. * @readonly
  36058. */
  36059. this.loop = false;
  36060. /**
  36061. * Defines where in the audio buffer the replay should
  36062. * start, in seconds.
  36063. *
  36064. * @type {number}
  36065. * @default 0
  36066. */
  36067. this.loopStart = 0;
  36068. /**
  36069. * Defines where in the audio buffer the replay should
  36070. * stop, in seconds.
  36071. *
  36072. * @type {number}
  36073. * @default 0
  36074. */
  36075. this.loopEnd = 0;
  36076. /**
  36077. * An offset to the time within the audio buffer the playback
  36078. * should begin, in seconds.
  36079. *
  36080. * @type {number}
  36081. * @default 0
  36082. */
  36083. this.offset = 0;
  36084. /**
  36085. * Overrides the default duration of the audio.
  36086. *
  36087. * @type {undefined|number}
  36088. * @default undefined
  36089. */
  36090. this.duration = undefined;
  36091. /**
  36092. * The playback speed.
  36093. *
  36094. * Defined via {@link Audio#setPlaybackRate}.
  36095. *
  36096. * @type {number}
  36097. * @readonly
  36098. * @default 1
  36099. */
  36100. this.playbackRate = 1;
  36101. /**
  36102. * Indicates whether the audio is playing or not.
  36103. *
  36104. * This flag will be automatically set when using {@link Audio#play},
  36105. * {@link Audio#pause}, {@link Audio#stop}.
  36106. *
  36107. * @type {boolean}
  36108. * @readonly
  36109. * @default false
  36110. */
  36111. this.isPlaying = false;
  36112. /**
  36113. * Indicates whether the audio playback can be controlled
  36114. * with method like {@link Audio#play} or {@link Audio#pause}.
  36115. *
  36116. * This flag will be automatically set when audio sources are
  36117. * defined.
  36118. *
  36119. * @type {boolean}
  36120. * @readonly
  36121. * @default true
  36122. */
  36123. this.hasPlaybackControl = true;
  36124. /**
  36125. * Holds a reference to the current audio source.
  36126. *
  36127. * The property is automatically by one of the `set*()` methods.
  36128. *
  36129. * @type {?AudioNode}
  36130. * @readonly
  36131. * @default null
  36132. */
  36133. this.source = null;
  36134. /**
  36135. * Defines the source type.
  36136. *
  36137. * The property is automatically by one of the `set*()` methods.
  36138. *
  36139. * @type {('empty'|'audioNode'|'mediaNode'|'mediaStreamNode'|'buffer')}
  36140. * @readonly
  36141. * @default 'empty'
  36142. */
  36143. this.sourceType = 'empty';
  36144. this._startedAt = 0;
  36145. this._progress = 0;
  36146. this._connected = false;
  36147. /**
  36148. * Can be used to apply a variety of low-order filters to create
  36149. * more complex sound effects e.g. via `BiquadFilterNode`.
  36150. *
  36151. * The property is automatically set by {@link Audio#setFilters}.
  36152. *
  36153. * @type {Array<AudioNode>}
  36154. * @readonly
  36155. */
  36156. this.filters = [];
  36157. }
  36158. /**
  36159. * Returns the output audio node.
  36160. *
  36161. * @return {GainNode} The output node.
  36162. */
  36163. getOutput() {
  36164. return this.gain;
  36165. }
  36166. /**
  36167. * Sets the given audio node as the source of this instance.
  36168. *
  36169. * {@link Audio#sourceType} is set to `audioNode` and {@link Audio#hasPlaybackControl} to `false`.
  36170. *
  36171. * @param {AudioNode} audioNode - The audio node like an instance of `OscillatorNode`.
  36172. * @return {Audio} A reference to this instance.
  36173. */
  36174. setNodeSource( audioNode ) {
  36175. this.hasPlaybackControl = false;
  36176. this.sourceType = 'audioNode';
  36177. this.source = audioNode;
  36178. this.connect();
  36179. return this;
  36180. }
  36181. /**
  36182. * Sets the given media element as the source of this instance.
  36183. *
  36184. * {@link Audio#sourceType} is set to `mediaNode` and {@link Audio#hasPlaybackControl} to `false`.
  36185. *
  36186. * @param {HTMLMediaElement} mediaElement - The media element.
  36187. * @return {Audio} A reference to this instance.
  36188. */
  36189. setMediaElementSource( mediaElement ) {
  36190. this.hasPlaybackControl = false;
  36191. this.sourceType = 'mediaNode';
  36192. this.source = this.context.createMediaElementSource( mediaElement );
  36193. this.connect();
  36194. return this;
  36195. }
  36196. /**
  36197. * Sets the given media stream as the source of this instance.
  36198. *
  36199. * {@link Audio#sourceType} is set to `mediaStreamNode` and {@link Audio#hasPlaybackControl} to `false`.
  36200. *
  36201. * @param {MediaStream} mediaStream - The media stream.
  36202. * @return {Audio} A reference to this instance.
  36203. */
  36204. setMediaStreamSource( mediaStream ) {
  36205. this.hasPlaybackControl = false;
  36206. this.sourceType = 'mediaStreamNode';
  36207. this.source = this.context.createMediaStreamSource( mediaStream );
  36208. this.connect();
  36209. return this;
  36210. }
  36211. /**
  36212. * Sets the given audio buffer as the source of this instance.
  36213. *
  36214. * {@link Audio#sourceType} is set to `buffer` and {@link Audio#hasPlaybackControl} to `true`.
  36215. *
  36216. * @param {AudioBuffer} audioBuffer - The audio buffer.
  36217. * @return {Audio} A reference to this instance.
  36218. */
  36219. setBuffer( audioBuffer ) {
  36220. this.buffer = audioBuffer;
  36221. this.sourceType = 'buffer';
  36222. if ( this.autoplay ) this.play();
  36223. return this;
  36224. }
  36225. /**
  36226. * Starts the playback of the audio.
  36227. *
  36228. * Can only be used with compatible audio sources that allow playback control.
  36229. *
  36230. * @param {number} [delay=0] - The delay, in seconds, at which the audio should start playing.
  36231. * @return {Audio|undefined} A reference to this instance.
  36232. */
  36233. play( delay = 0 ) {
  36234. if ( this.isPlaying === true ) {
  36235. console.warn( 'THREE.Audio: Audio is already playing.' );
  36236. return;
  36237. }
  36238. if ( this.hasPlaybackControl === false ) {
  36239. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  36240. return;
  36241. }
  36242. this._startedAt = this.context.currentTime + delay;
  36243. const source = this.context.createBufferSource();
  36244. source.buffer = this.buffer;
  36245. source.loop = this.loop;
  36246. source.loopStart = this.loopStart;
  36247. source.loopEnd = this.loopEnd;
  36248. source.onended = this.onEnded.bind( this );
  36249. source.start( this._startedAt, this._progress + this.offset, this.duration );
  36250. this.isPlaying = true;
  36251. this.source = source;
  36252. this.setDetune( this.detune );
  36253. this.setPlaybackRate( this.playbackRate );
  36254. return this.connect();
  36255. }
  36256. /**
  36257. * Pauses the playback of the audio.
  36258. *
  36259. * Can only be used with compatible audio sources that allow playback control.
  36260. *
  36261. * @return {Audio|undefined} A reference to this instance.
  36262. */
  36263. pause() {
  36264. if ( this.hasPlaybackControl === false ) {
  36265. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  36266. return;
  36267. }
  36268. if ( this.isPlaying === true ) {
  36269. // update current progress
  36270. this._progress += Math.max( this.context.currentTime - this._startedAt, 0 ) * this.playbackRate;
  36271. if ( this.loop === true ) {
  36272. // ensure _progress does not exceed duration with looped audios
  36273. this._progress = this._progress % ( this.duration || this.buffer.duration );
  36274. }
  36275. this.source.stop();
  36276. this.source.onended = null;
  36277. this.isPlaying = false;
  36278. }
  36279. return this;
  36280. }
  36281. /**
  36282. * Stops the playback of the audio.
  36283. *
  36284. * Can only be used with compatible audio sources that allow playback control.
  36285. *
  36286. * @param {number} [delay=0] - The delay, in seconds, at which the audio should stop playing.
  36287. * @return {Audio|undefined} A reference to this instance.
  36288. */
  36289. stop( delay = 0 ) {
  36290. if ( this.hasPlaybackControl === false ) {
  36291. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  36292. return;
  36293. }
  36294. this._progress = 0;
  36295. if ( this.source !== null ) {
  36296. this.source.stop( this.context.currentTime + delay );
  36297. this.source.onended = null;
  36298. }
  36299. this.isPlaying = false;
  36300. return this;
  36301. }
  36302. /**
  36303. * Connects to the audio source. This is used internally on
  36304. * initialisation and when setting / removing filters.
  36305. *
  36306. * @return {Audio} A reference to this instance.
  36307. */
  36308. connect() {
  36309. if ( this.filters.length > 0 ) {
  36310. this.source.connect( this.filters[ 0 ] );
  36311. for ( let i = 1, l = this.filters.length; i < l; i ++ ) {
  36312. this.filters[ i - 1 ].connect( this.filters[ i ] );
  36313. }
  36314. this.filters[ this.filters.length - 1 ].connect( this.getOutput() );
  36315. } else {
  36316. this.source.connect( this.getOutput() );
  36317. }
  36318. this._connected = true;
  36319. return this;
  36320. }
  36321. /**
  36322. * Disconnects to the audio source. This is used internally on
  36323. * initialisation and when setting / removing filters.
  36324. *
  36325. * @return {Audio|undefined} A reference to this instance.
  36326. */
  36327. disconnect() {
  36328. if ( this._connected === false ) {
  36329. return;
  36330. }
  36331. if ( this.filters.length > 0 ) {
  36332. this.source.disconnect( this.filters[ 0 ] );
  36333. for ( let i = 1, l = this.filters.length; i < l; i ++ ) {
  36334. this.filters[ i - 1 ].disconnect( this.filters[ i ] );
  36335. }
  36336. this.filters[ this.filters.length - 1 ].disconnect( this.getOutput() );
  36337. } else {
  36338. this.source.disconnect( this.getOutput() );
  36339. }
  36340. this._connected = false;
  36341. return this;
  36342. }
  36343. /**
  36344. * Returns the current set filters.
  36345. *
  36346. * @return {Array<AudioNode>} The list of filters.
  36347. */
  36348. getFilters() {
  36349. return this.filters;
  36350. }
  36351. /**
  36352. * Sets an array of filters and connects them with the audio source.
  36353. *
  36354. * @param {Array<AudioNode>} [value] - A list of filters.
  36355. * @return {Audio} A reference to this instance.
  36356. */
  36357. setFilters( value ) {
  36358. if ( ! value ) value = [];
  36359. if ( this._connected === true ) {
  36360. this.disconnect();
  36361. this.filters = value.slice();
  36362. this.connect();
  36363. } else {
  36364. this.filters = value.slice();
  36365. }
  36366. return this;
  36367. }
  36368. /**
  36369. * Defines the detuning of oscillation in cents.
  36370. *
  36371. * @param {number} value - The detuning of oscillation in cents.
  36372. * @return {Audio} A reference to this instance.
  36373. */
  36374. setDetune( value ) {
  36375. this.detune = value;
  36376. if ( this.isPlaying === true && this.source.detune !== undefined ) {
  36377. this.source.detune.setTargetAtTime( this.detune, this.context.currentTime, 0.01 );
  36378. }
  36379. return this;
  36380. }
  36381. /**
  36382. * Returns the detuning of oscillation in cents.
  36383. *
  36384. * @return {number} The detuning of oscillation in cents.
  36385. */
  36386. getDetune() {
  36387. return this.detune;
  36388. }
  36389. /**
  36390. * Returns the first filter in the list of filters.
  36391. *
  36392. * @return {AudioNode|undefined} The first filter in the list of filters.
  36393. */
  36394. getFilter() {
  36395. return this.getFilters()[ 0 ];
  36396. }
  36397. /**
  36398. * Applies a single filter node to the audio.
  36399. *
  36400. * @param {AudioNode} [filter] - The filter to set.
  36401. * @return {Audio} A reference to this instance.
  36402. */
  36403. setFilter( filter ) {
  36404. return this.setFilters( filter ? [ filter ] : [] );
  36405. }
  36406. /**
  36407. * Sets the playback rate.
  36408. *
  36409. * Can only be used with compatible audio sources that allow playback control.
  36410. *
  36411. * @param {number} [value] - The playback rate to set.
  36412. * @return {Audio|undefined} A reference to this instance.
  36413. */
  36414. setPlaybackRate( value ) {
  36415. if ( this.hasPlaybackControl === false ) {
  36416. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  36417. return;
  36418. }
  36419. this.playbackRate = value;
  36420. if ( this.isPlaying === true ) {
  36421. this.source.playbackRate.setTargetAtTime( this.playbackRate, this.context.currentTime, 0.01 );
  36422. }
  36423. return this;
  36424. }
  36425. /**
  36426. * Returns the current playback rate.
  36427. * @return {number} The playback rate.
  36428. */
  36429. getPlaybackRate() {
  36430. return this.playbackRate;
  36431. }
  36432. /**
  36433. * Automatically called when playback finished.
  36434. */
  36435. onEnded() {
  36436. this.isPlaying = false;
  36437. this._progress = 0;
  36438. }
  36439. /**
  36440. * Returns the loop flag.
  36441. *
  36442. * Can only be used with compatible audio sources that allow playback control.
  36443. *
  36444. * @return {boolean} Whether the audio should loop or not.
  36445. */
  36446. getLoop() {
  36447. if ( this.hasPlaybackControl === false ) {
  36448. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  36449. return false;
  36450. }
  36451. return this.loop;
  36452. }
  36453. /**
  36454. * Sets the loop flag.
  36455. *
  36456. * Can only be used with compatible audio sources that allow playback control.
  36457. *
  36458. * @param {boolean} value - Whether the audio should loop or not.
  36459. * @return {Audio|undefined} A reference to this instance.
  36460. */
  36461. setLoop( value ) {
  36462. if ( this.hasPlaybackControl === false ) {
  36463. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  36464. return;
  36465. }
  36466. this.loop = value;
  36467. if ( this.isPlaying === true ) {
  36468. this.source.loop = this.loop;
  36469. }
  36470. return this;
  36471. }
  36472. /**
  36473. * Sets the loop start value which defines where in the audio buffer the replay should
  36474. * start, in seconds.
  36475. *
  36476. * @param {number} value - The loop start value.
  36477. * @return {Audio} A reference to this instance.
  36478. */
  36479. setLoopStart( value ) {
  36480. this.loopStart = value;
  36481. return this;
  36482. }
  36483. /**
  36484. * Sets the loop end value which defines where in the audio buffer the replay should
  36485. * stop, in seconds.
  36486. *
  36487. * @param {number} value - The loop end value.
  36488. * @return {Audio} A reference to this instance.
  36489. */
  36490. setLoopEnd( value ) {
  36491. this.loopEnd = value;
  36492. return this;
  36493. }
  36494. /**
  36495. * Returns the volume.
  36496. *
  36497. * @return {number} The volume.
  36498. */
  36499. getVolume() {
  36500. return this.gain.gain.value;
  36501. }
  36502. /**
  36503. * Sets the volume.
  36504. *
  36505. * @param {number} value - The volume to set.
  36506. * @return {Audio} A reference to this instance.
  36507. */
  36508. setVolume( value ) {
  36509. this.gain.gain.setTargetAtTime( value, this.context.currentTime, 0.01 );
  36510. return this;
  36511. }
  36512. copy( source, recursive ) {
  36513. super.copy( source, recursive );
  36514. if ( source.sourceType !== 'buffer' ) {
  36515. console.warn( 'THREE.Audio: Audio source type cannot be copied.' );
  36516. return this;
  36517. }
  36518. this.autoplay = source.autoplay;
  36519. this.buffer = source.buffer;
  36520. this.detune = source.detune;
  36521. this.loop = source.loop;
  36522. this.loopStart = source.loopStart;
  36523. this.loopEnd = source.loopEnd;
  36524. this.offset = source.offset;
  36525. this.duration = source.duration;
  36526. this.playbackRate = source.playbackRate;
  36527. this.hasPlaybackControl = source.hasPlaybackControl;
  36528. this.sourceType = source.sourceType;
  36529. this.filters = source.filters.slice();
  36530. return this;
  36531. }
  36532. clone( recursive ) {
  36533. return new this.constructor( this.listener ).copy( this, recursive );
  36534. }
  36535. }
  36536. const _position = /*@__PURE__*/ new Vector3();
  36537. const _quaternion = /*@__PURE__*/ new Quaternion();
  36538. const _scale = /*@__PURE__*/ new Vector3();
  36539. const _orientation = /*@__PURE__*/ new Vector3();
  36540. /**
  36541. * Represents a positional audio object.
  36542. *
  36543. * ```js
  36544. * // create an AudioListener and add it to the camera
  36545. * const listener = new THREE.AudioListener();
  36546. * camera.add( listener );
  36547. *
  36548. * // create the PositionalAudio object (passing in the listener)
  36549. * const sound = new THREE.PositionalAudio( listener );
  36550. *
  36551. * // load a sound and set it as the PositionalAudio object's buffer
  36552. * const audioLoader = new THREE.AudioLoader();
  36553. * audioLoader.load( 'sounds/song.ogg', function( buffer ) {
  36554. * sound.setBuffer( buffer );
  36555. * sound.setRefDistance( 20 );
  36556. * sound.play();
  36557. * });
  36558. *
  36559. * // create an object for the sound to play from
  36560. * const sphere = new THREE.SphereGeometry( 20, 32, 16 );
  36561. * const material = new THREE.MeshPhongMaterial( { color: 0xff2200 } );
  36562. * const mesh = new THREE.Mesh( sphere, material );
  36563. * scene.add( mesh );
  36564. *
  36565. * // finally add the sound to the mesh
  36566. * mesh.add( sound );
  36567. *
  36568. * @augments Audio
  36569. */
  36570. class PositionalAudio extends Audio {
  36571. /**
  36572. * Constructs a positional audio.
  36573. *
  36574. * @param {AudioListener} listener - The global audio listener.
  36575. */
  36576. constructor( listener ) {
  36577. super( listener );
  36578. /**
  36579. * The panner node represents the location, direction, and behavior of an audio
  36580. * source in 3D space.
  36581. *
  36582. * @type {PannerNode}
  36583. * @readonly
  36584. */
  36585. this.panner = this.context.createPanner();
  36586. this.panner.panningModel = 'HRTF';
  36587. this.panner.connect( this.gain );
  36588. }
  36589. connect() {
  36590. super.connect();
  36591. this.panner.connect( this.gain );
  36592. return this;
  36593. }
  36594. disconnect() {
  36595. super.disconnect();
  36596. this.panner.disconnect( this.gain );
  36597. return this;
  36598. }
  36599. getOutput() {
  36600. return this.panner;
  36601. }
  36602. /**
  36603. * Returns the current reference distance.
  36604. *
  36605. * @return {number} The reference distance.
  36606. */
  36607. getRefDistance() {
  36608. return this.panner.refDistance;
  36609. }
  36610. /**
  36611. * Defines the reference distance for reducing volume as the audio source moves
  36612. * further from the listener – i.e. the distance at which the volume reduction
  36613. * starts taking effect.
  36614. *
  36615. * @param {number} value - The reference distance to set.
  36616. * @return {PositionalAudio} A reference to this instance.
  36617. */
  36618. setRefDistance( value ) {
  36619. this.panner.refDistance = value;
  36620. return this;
  36621. }
  36622. /**
  36623. * Returns the current rolloff factor.
  36624. *
  36625. * @return {number} The rolloff factor.
  36626. */
  36627. getRolloffFactor() {
  36628. return this.panner.rolloffFactor;
  36629. }
  36630. /**
  36631. * Defines how quickly the volume is reduced as the source moves away from the listener.
  36632. *
  36633. * @param {number} value - The rolloff factor.
  36634. * @return {PositionalAudio} A reference to this instance.
  36635. */
  36636. setRolloffFactor( value ) {
  36637. this.panner.rolloffFactor = value;
  36638. return this;
  36639. }
  36640. /**
  36641. * Returns the current distance model.
  36642. *
  36643. * @return {('linear'|'inverse'|'exponential')} The distance model.
  36644. */
  36645. getDistanceModel() {
  36646. return this.panner.distanceModel;
  36647. }
  36648. /**
  36649. * Defines which algorithm to use to reduce the volume of the audio source
  36650. * as it moves away from the listener.
  36651. *
  36652. * Read [the spec]{@link https://www.w3.org/TR/webaudio-1.1/#enumdef-distancemodeltype}
  36653. * for more details.
  36654. *
  36655. * @param {('linear'|'inverse'|'exponential')} value - The distance model to set.
  36656. * @return {PositionalAudio} A reference to this instance.
  36657. */
  36658. setDistanceModel( value ) {
  36659. this.panner.distanceModel = value;
  36660. return this;
  36661. }
  36662. /**
  36663. * Returns the current max distance.
  36664. *
  36665. * @return {number} The max distance.
  36666. */
  36667. getMaxDistance() {
  36668. return this.panner.maxDistance;
  36669. }
  36670. /**
  36671. * Defines the maximum distance between the audio source and the listener,
  36672. * after which the volume is not reduced any further.
  36673. *
  36674. * This value is used only by the `linear` distance model.
  36675. *
  36676. * @param {number} value - The max distance.
  36677. * @return {PositionalAudio} A reference to this instance.
  36678. */
  36679. setMaxDistance( value ) {
  36680. this.panner.maxDistance = value;
  36681. return this;
  36682. }
  36683. /**
  36684. * Sets the directional cone in which the audio can be listened.
  36685. *
  36686. * @param {number} coneInnerAngle - An angle, in degrees, of a cone inside of which there will be no volume reduction.
  36687. * @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.
  36688. * @param {number} coneOuterGain - The amount of volume reduction outside the cone defined by the `coneOuterAngle`. When set to `0`, no sound can be heard.
  36689. * @return {PositionalAudio} A reference to this instance.
  36690. */
  36691. setDirectionalCone( coneInnerAngle, coneOuterAngle, coneOuterGain ) {
  36692. this.panner.coneInnerAngle = coneInnerAngle;
  36693. this.panner.coneOuterAngle = coneOuterAngle;
  36694. this.panner.coneOuterGain = coneOuterGain;
  36695. return this;
  36696. }
  36697. updateMatrixWorld( force ) {
  36698. super.updateMatrixWorld( force );
  36699. if ( this.hasPlaybackControl === true && this.isPlaying === false ) return;
  36700. this.matrixWorld.decompose( _position, _quaternion, _scale );
  36701. _orientation.set( 0, 0, 1 ).applyQuaternion( _quaternion );
  36702. const panner = this.panner;
  36703. if ( panner.positionX ) {
  36704. // code path for Chrome and Firefox (see #14393)
  36705. const endTime = this.context.currentTime + this.listener.timeDelta;
  36706. panner.positionX.linearRampToValueAtTime( _position.x, endTime );
  36707. panner.positionY.linearRampToValueAtTime( _position.y, endTime );
  36708. panner.positionZ.linearRampToValueAtTime( _position.z, endTime );
  36709. panner.orientationX.linearRampToValueAtTime( _orientation.x, endTime );
  36710. panner.orientationY.linearRampToValueAtTime( _orientation.y, endTime );
  36711. panner.orientationZ.linearRampToValueAtTime( _orientation.z, endTime );
  36712. } else {
  36713. panner.setPosition( _position.x, _position.y, _position.z );
  36714. panner.setOrientation( _orientation.x, _orientation.y, _orientation.z );
  36715. }
  36716. }
  36717. }
  36718. /**
  36719. * This class can be used to analyse audio data.
  36720. *
  36721. * ```js
  36722. * // create an AudioListener and add it to the camera
  36723. * const listener = new THREE.AudioListener();
  36724. * camera.add( listener );
  36725. *
  36726. * // create an Audio source
  36727. * const sound = new THREE.Audio( listener );
  36728. *
  36729. * // load a sound and set it as the Audio object's buffer
  36730. * const audioLoader = new THREE.AudioLoader();
  36731. * audioLoader.load( 'sounds/ambient.ogg', function( buffer ) {
  36732. * sound.setBuffer( buffer );
  36733. * sound.setLoop(true);
  36734. * sound.setVolume(0.5);
  36735. * sound.play();
  36736. * });
  36737. *
  36738. * // create an AudioAnalyser, passing in the sound and desired fftSize
  36739. * const analyser = new THREE.AudioAnalyser( sound, 32 );
  36740. *
  36741. * // get the average frequency of the sound
  36742. * const data = analyser.getAverageFrequency();
  36743. * ```
  36744. */
  36745. class AudioAnalyser {
  36746. /**
  36747. * Constructs a new audio analyzer.
  36748. *
  36749. * @param {Audio} audio - The audio to analyze.
  36750. * @param {number} [fftSize=2048] - The window size in samples that is used when performing a Fast Fourier Transform (FFT) to get frequency domain data.
  36751. */
  36752. constructor( audio, fftSize = 2048 ) {
  36753. /**
  36754. * The global audio listener.
  36755. *
  36756. * @type {AnalyserNode}
  36757. */
  36758. this.analyser = audio.context.createAnalyser();
  36759. this.analyser.fftSize = fftSize;
  36760. /**
  36761. * Holds the analyzed data.
  36762. *
  36763. * @type {Uint8Array}
  36764. */
  36765. this.data = new Uint8Array( this.analyser.frequencyBinCount );
  36766. audio.getOutput().connect( this.analyser );
  36767. }
  36768. /**
  36769. * Returns an array with frequency data of the audio.
  36770. *
  36771. * Each item in the array represents the decibel value for a specific frequency.
  36772. * The frequencies are spread linearly from 0 to 1/2 of the sample rate.
  36773. * For example, for 48000 sample rate, the last item of the array will represent
  36774. * the decibel value for 24000 Hz.
  36775. *
  36776. * @return {Uint8Array} The frequency data.
  36777. */
  36778. getFrequencyData() {
  36779. this.analyser.getByteFrequencyData( this.data );
  36780. return this.data;
  36781. }
  36782. /**
  36783. * Returns the average of the frequencies returned by {@link AudioAnalyser#getFrequencyData}.
  36784. *
  36785. * @return {number} The average frequency.
  36786. */
  36787. getAverageFrequency() {
  36788. let value = 0;
  36789. const data = this.getFrequencyData();
  36790. for ( let i = 0; i < data.length; i ++ ) {
  36791. value += data[ i ];
  36792. }
  36793. return value / data.length;
  36794. }
  36795. }
  36796. /**
  36797. * Buffered scene graph property that allows weighted accumulation; used internally.
  36798. */
  36799. class PropertyMixer {
  36800. /**
  36801. * Constructs a new property mixer.
  36802. *
  36803. * @param {PropertyBinding} binding - The property binding.
  36804. * @param {string} typeName - The keyframe track type name.
  36805. * @param {number} valueSize - The keyframe track value size.
  36806. */
  36807. constructor( binding, typeName, valueSize ) {
  36808. /**
  36809. * The property binding.
  36810. *
  36811. * @type {PropertyBinding}
  36812. */
  36813. this.binding = binding;
  36814. /**
  36815. * The keyframe track value size.
  36816. *
  36817. * @type {number}
  36818. */
  36819. this.valueSize = valueSize;
  36820. let mixFunction,
  36821. mixFunctionAdditive,
  36822. setIdentity;
  36823. // buffer layout: [ incoming | accu0 | accu1 | orig | addAccu | (optional work) ]
  36824. //
  36825. // interpolators can use .buffer as their .result
  36826. // the data then goes to 'incoming'
  36827. //
  36828. // 'accu0' and 'accu1' are used frame-interleaved for
  36829. // the cumulative result and are compared to detect
  36830. // changes
  36831. //
  36832. // 'orig' stores the original state of the property
  36833. //
  36834. // 'add' is used for additive cumulative results
  36835. //
  36836. // 'work' is optional and is only present for quaternion types. It is used
  36837. // to store intermediate quaternion multiplication results
  36838. switch ( typeName ) {
  36839. case 'quaternion':
  36840. mixFunction = this._slerp;
  36841. mixFunctionAdditive = this._slerpAdditive;
  36842. setIdentity = this._setAdditiveIdentityQuaternion;
  36843. this.buffer = new Float64Array( valueSize * 6 );
  36844. this._workIndex = 5;
  36845. break;
  36846. case 'string':
  36847. case 'bool':
  36848. mixFunction = this._select;
  36849. // Use the regular mix function and for additive on these types,
  36850. // additive is not relevant for non-numeric types
  36851. mixFunctionAdditive = this._select;
  36852. setIdentity = this._setAdditiveIdentityOther;
  36853. this.buffer = new Array( valueSize * 5 );
  36854. break;
  36855. default:
  36856. mixFunction = this._lerp;
  36857. mixFunctionAdditive = this._lerpAdditive;
  36858. setIdentity = this._setAdditiveIdentityNumeric;
  36859. this.buffer = new Float64Array( valueSize * 5 );
  36860. }
  36861. this._mixBufferRegion = mixFunction;
  36862. this._mixBufferRegionAdditive = mixFunctionAdditive;
  36863. this._setIdentity = setIdentity;
  36864. this._origIndex = 3;
  36865. this._addIndex = 4;
  36866. /**
  36867. * TODO
  36868. *
  36869. * @type {number}
  36870. * @default 0
  36871. */
  36872. this.cumulativeWeight = 0;
  36873. /**
  36874. * TODO
  36875. *
  36876. * @type {number}
  36877. * @default 0
  36878. */
  36879. this.cumulativeWeightAdditive = 0;
  36880. /**
  36881. * TODO
  36882. *
  36883. * @type {number}
  36884. * @default 0
  36885. */
  36886. this.useCount = 0;
  36887. /**
  36888. * TODO
  36889. *
  36890. * @type {number}
  36891. * @default 0
  36892. */
  36893. this.referenceCount = 0;
  36894. }
  36895. /**
  36896. * Accumulates data in the `incoming` region into `accu<i>`.
  36897. *
  36898. * @param {number} accuIndex - The accumulation index.
  36899. * @param {number} weight - The weight.
  36900. */
  36901. accumulate( accuIndex, weight ) {
  36902. // note: happily accumulating nothing when weight = 0, the caller knows
  36903. // the weight and shouldn't have made the call in the first place
  36904. const buffer = this.buffer,
  36905. stride = this.valueSize,
  36906. offset = accuIndex * stride + stride;
  36907. let currentWeight = this.cumulativeWeight;
  36908. if ( currentWeight === 0 ) {
  36909. // accuN := incoming * weight
  36910. for ( let i = 0; i !== stride; ++ i ) {
  36911. buffer[ offset + i ] = buffer[ i ];
  36912. }
  36913. currentWeight = weight;
  36914. } else {
  36915. // accuN := accuN + incoming * weight
  36916. currentWeight += weight;
  36917. const mix = weight / currentWeight;
  36918. this._mixBufferRegion( buffer, offset, 0, mix, stride );
  36919. }
  36920. this.cumulativeWeight = currentWeight;
  36921. }
  36922. /**
  36923. * Accumulates data in the `incoming` region into `add`.
  36924. *
  36925. * @param {number} weight - The weight.
  36926. */
  36927. accumulateAdditive( weight ) {
  36928. const buffer = this.buffer,
  36929. stride = this.valueSize,
  36930. offset = stride * this._addIndex;
  36931. if ( this.cumulativeWeightAdditive === 0 ) {
  36932. // add = identity
  36933. this._setIdentity();
  36934. }
  36935. // add := add + incoming * weight
  36936. this._mixBufferRegionAdditive( buffer, offset, 0, weight, stride );
  36937. this.cumulativeWeightAdditive += weight;
  36938. }
  36939. /**
  36940. * Applies the state of `accu<i>` to the binding when accus differ.
  36941. *
  36942. * @param {number} accuIndex - The accumulation index.
  36943. */
  36944. apply( accuIndex ) {
  36945. const stride = this.valueSize,
  36946. buffer = this.buffer,
  36947. offset = accuIndex * stride + stride,
  36948. weight = this.cumulativeWeight,
  36949. weightAdditive = this.cumulativeWeightAdditive,
  36950. binding = this.binding;
  36951. this.cumulativeWeight = 0;
  36952. this.cumulativeWeightAdditive = 0;
  36953. if ( weight < 1 ) {
  36954. // accuN := accuN + original * ( 1 - cumulativeWeight )
  36955. const originalValueOffset = stride * this._origIndex;
  36956. this._mixBufferRegion(
  36957. buffer, offset, originalValueOffset, 1 - weight, stride );
  36958. }
  36959. if ( weightAdditive > 0 ) {
  36960. // accuN := accuN + additive accuN
  36961. this._mixBufferRegionAdditive( buffer, offset, this._addIndex * stride, 1, stride );
  36962. }
  36963. for ( let i = stride, e = stride + stride; i !== e; ++ i ) {
  36964. if ( buffer[ i ] !== buffer[ i + stride ] ) {
  36965. // value has changed -> update scene graph
  36966. binding.setValue( buffer, offset );
  36967. break;
  36968. }
  36969. }
  36970. }
  36971. /**
  36972. * Remembers the state of the bound property and copy it to both accus.
  36973. */
  36974. saveOriginalState() {
  36975. const binding = this.binding;
  36976. const buffer = this.buffer,
  36977. stride = this.valueSize,
  36978. originalValueOffset = stride * this._origIndex;
  36979. binding.getValue( buffer, originalValueOffset );
  36980. // accu[0..1] := orig -- initially detect changes against the original
  36981. for ( let i = stride, e = originalValueOffset; i !== e; ++ i ) {
  36982. buffer[ i ] = buffer[ originalValueOffset + ( i % stride ) ];
  36983. }
  36984. // Add to identity for additive
  36985. this._setIdentity();
  36986. this.cumulativeWeight = 0;
  36987. this.cumulativeWeightAdditive = 0;
  36988. }
  36989. /**
  36990. * Applies the state previously taken via {@link PropertyMixer#saveOriginalState} to the binding.
  36991. */
  36992. restoreOriginalState() {
  36993. const originalValueOffset = this.valueSize * 3;
  36994. this.binding.setValue( this.buffer, originalValueOffset );
  36995. }
  36996. // internals
  36997. _setAdditiveIdentityNumeric() {
  36998. const startIndex = this._addIndex * this.valueSize;
  36999. const endIndex = startIndex + this.valueSize;
  37000. for ( let i = startIndex; i < endIndex; i ++ ) {
  37001. this.buffer[ i ] = 0;
  37002. }
  37003. }
  37004. _setAdditiveIdentityQuaternion() {
  37005. this._setAdditiveIdentityNumeric();
  37006. this.buffer[ this._addIndex * this.valueSize + 3 ] = 1;
  37007. }
  37008. _setAdditiveIdentityOther() {
  37009. const startIndex = this._origIndex * this.valueSize;
  37010. const targetIndex = this._addIndex * this.valueSize;
  37011. for ( let i = 0; i < this.valueSize; i ++ ) {
  37012. this.buffer[ targetIndex + i ] = this.buffer[ startIndex + i ];
  37013. }
  37014. }
  37015. // mix functions
  37016. _select( buffer, dstOffset, srcOffset, t, stride ) {
  37017. if ( t >= 0.5 ) {
  37018. for ( let i = 0; i !== stride; ++ i ) {
  37019. buffer[ dstOffset + i ] = buffer[ srcOffset + i ];
  37020. }
  37021. }
  37022. }
  37023. _slerp( buffer, dstOffset, srcOffset, t ) {
  37024. Quaternion.slerpFlat( buffer, dstOffset, buffer, dstOffset, buffer, srcOffset, t );
  37025. }
  37026. _slerpAdditive( buffer, dstOffset, srcOffset, t, stride ) {
  37027. const workOffset = this._workIndex * stride;
  37028. // Store result in intermediate buffer offset
  37029. Quaternion.multiplyQuaternionsFlat( buffer, workOffset, buffer, dstOffset, buffer, srcOffset );
  37030. // Slerp to the intermediate result
  37031. Quaternion.slerpFlat( buffer, dstOffset, buffer, dstOffset, buffer, workOffset, t );
  37032. }
  37033. _lerp( buffer, dstOffset, srcOffset, t, stride ) {
  37034. const s = 1 - t;
  37035. for ( let i = 0; i !== stride; ++ i ) {
  37036. const j = dstOffset + i;
  37037. buffer[ j ] = buffer[ j ] * s + buffer[ srcOffset + i ] * t;
  37038. }
  37039. }
  37040. _lerpAdditive( buffer, dstOffset, srcOffset, t, stride ) {
  37041. for ( let i = 0; i !== stride; ++ i ) {
  37042. const j = dstOffset + i;
  37043. buffer[ j ] = buffer[ j ] + buffer[ srcOffset + i ] * t;
  37044. }
  37045. }
  37046. }
  37047. // Characters [].:/ are reserved for track binding syntax.
  37048. const _RESERVED_CHARS_RE = '\\[\\]\\.:\\/';
  37049. const _reservedRe = new RegExp( '[' + _RESERVED_CHARS_RE + ']', 'g' );
  37050. // Attempts to allow node names from any language. ES5's `\w` regexp matches
  37051. // only latin characters, and the unicode \p{L} is not yet supported. So
  37052. // instead, we exclude reserved characters and match everything else.
  37053. const _wordChar = '[^' + _RESERVED_CHARS_RE + ']';
  37054. const _wordCharOrDot = '[^' + _RESERVED_CHARS_RE.replace( '\\.', '' ) + ']';
  37055. // Parent directories, delimited by '/' or ':'. Currently unused, but must
  37056. // be matched to parse the rest of the track name.
  37057. const _directoryRe = /*@__PURE__*/ /((?:WC+[\/:])*)/.source.replace( 'WC', _wordChar );
  37058. // Target node. May contain word characters (a-zA-Z0-9_) and '.' or '-'.
  37059. const _nodeRe = /*@__PURE__*/ /(WCOD+)?/.source.replace( 'WCOD', _wordCharOrDot );
  37060. // Object on target node, and accessor. May not contain reserved
  37061. // characters. Accessor may contain any character except closing bracket.
  37062. const _objectRe = /*@__PURE__*/ /(?:\.(WC+)(?:\[(.+)\])?)?/.source.replace( 'WC', _wordChar );
  37063. // Property and accessor. May not contain reserved characters. Accessor may
  37064. // contain any non-bracket characters.
  37065. const _propertyRe = /*@__PURE__*/ /\.(WC+)(?:\[(.+)\])?/.source.replace( 'WC', _wordChar );
  37066. const _trackRe = new RegExp( ''
  37067. + '^'
  37068. + _directoryRe
  37069. + _nodeRe
  37070. + _objectRe
  37071. + _propertyRe
  37072. + '$'
  37073. );
  37074. const _supportedObjectNames = [ 'material', 'materials', 'bones', 'map' ];
  37075. class Composite {
  37076. constructor( targetGroup, path, optionalParsedPath ) {
  37077. const parsedPath = optionalParsedPath || PropertyBinding.parseTrackName( path );
  37078. this._targetGroup = targetGroup;
  37079. this._bindings = targetGroup.subscribe_( path, parsedPath );
  37080. }
  37081. getValue( array, offset ) {
  37082. this.bind(); // bind all binding
  37083. const firstValidIndex = this._targetGroup.nCachedObjects_,
  37084. binding = this._bindings[ firstValidIndex ];
  37085. // and only call .getValue on the first
  37086. if ( binding !== undefined ) binding.getValue( array, offset );
  37087. }
  37088. setValue( array, offset ) {
  37089. const bindings = this._bindings;
  37090. for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  37091. bindings[ i ].setValue( array, offset );
  37092. }
  37093. }
  37094. bind() {
  37095. const bindings = this._bindings;
  37096. for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  37097. bindings[ i ].bind();
  37098. }
  37099. }
  37100. unbind() {
  37101. const bindings = this._bindings;
  37102. for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  37103. bindings[ i ].unbind();
  37104. }
  37105. }
  37106. }
  37107. // Note: This class uses a State pattern on a per-method basis:
  37108. // 'bind' sets 'this.getValue' / 'setValue' and shadows the
  37109. // prototype version of these methods with one that represents
  37110. // the bound state. When the property is not found, the methods
  37111. // become no-ops.
  37112. /**
  37113. * This holds a reference to a real property in the scene graph; used internally.
  37114. */
  37115. class PropertyBinding {
  37116. /**
  37117. * Constructs a new property binding.
  37118. *
  37119. * @param {Object} rootNode - The root node.
  37120. * @param {string} path - The path.
  37121. * @param {?Object} [parsedPath] - The parsed path.
  37122. */
  37123. constructor( rootNode, path, parsedPath ) {
  37124. /**
  37125. * The object path to the animated property.
  37126. *
  37127. * @type {string}
  37128. */
  37129. this.path = path;
  37130. /**
  37131. * An object holding information about the path.
  37132. *
  37133. * @type {Object}
  37134. */
  37135. this.parsedPath = parsedPath || PropertyBinding.parseTrackName( path );
  37136. /**
  37137. * The object owns the animated property.
  37138. *
  37139. * @type {?Object}
  37140. */
  37141. this.node = PropertyBinding.findNode( rootNode, this.parsedPath.nodeName );
  37142. /**
  37143. * The root node.
  37144. *
  37145. * @type {Object3D|Skeleton}
  37146. */
  37147. this.rootNode = rootNode;
  37148. // initial state of these methods that calls 'bind'
  37149. this.getValue = this._getValue_unbound;
  37150. this.setValue = this._setValue_unbound;
  37151. }
  37152. /**
  37153. * Factory method for creating a property binding from the given parameters.
  37154. *
  37155. * @static
  37156. * @param {Object} root - The root node.
  37157. * @param {string} path - The path.
  37158. * @param {?Object} [parsedPath] - The parsed path.
  37159. * @return {PropertyBinding|Composite} The created property binding or composite.
  37160. */
  37161. static create( root, path, parsedPath ) {
  37162. if ( ! ( root && root.isAnimationObjectGroup ) ) {
  37163. return new PropertyBinding( root, path, parsedPath );
  37164. } else {
  37165. return new PropertyBinding.Composite( root, path, parsedPath );
  37166. }
  37167. }
  37168. /**
  37169. * Replaces spaces with underscores and removes unsupported characters from
  37170. * node names, to ensure compatibility with parseTrackName().
  37171. *
  37172. * @param {string} name - Node name to be sanitized.
  37173. * @return {string} The sanitized node name.
  37174. */
  37175. static sanitizeNodeName( name ) {
  37176. return name.replace( /\s/g, '_' ).replace( _reservedRe, '' );
  37177. }
  37178. /**
  37179. * Parses the given track name (an object path to an animated property) and
  37180. * returns an object with information about the path. Matches strings in the following forms:
  37181. *
  37182. * - nodeName.property
  37183. * - nodeName.property[accessor]
  37184. * - nodeName.material.property[accessor]
  37185. * - uuid.property[accessor]
  37186. * - uuid.objectName[objectIndex].propertyName[propertyIndex]
  37187. * - parentName/nodeName.property
  37188. * - parentName/parentName/nodeName.property[index]
  37189. * - .bone[Armature.DEF_cog].position
  37190. * - scene:helium_balloon_model:helium_balloon_model.position
  37191. *
  37192. * @static
  37193. * @param {string} trackName - The track name to parse.
  37194. * @return {Object} The parsed track name as an object.
  37195. */
  37196. static parseTrackName( trackName ) {
  37197. const matches = _trackRe.exec( trackName );
  37198. if ( matches === null ) {
  37199. throw new Error( 'PropertyBinding: Cannot parse trackName: ' + trackName );
  37200. }
  37201. const results = {
  37202. // directoryName: matches[ 1 ], // (tschw) currently unused
  37203. nodeName: matches[ 2 ],
  37204. objectName: matches[ 3 ],
  37205. objectIndex: matches[ 4 ],
  37206. propertyName: matches[ 5 ], // required
  37207. propertyIndex: matches[ 6 ]
  37208. };
  37209. const lastDot = results.nodeName && results.nodeName.lastIndexOf( '.' );
  37210. if ( lastDot !== undefined && lastDot !== -1 ) {
  37211. const objectName = results.nodeName.substring( lastDot + 1 );
  37212. // Object names must be checked against an allowlist. Otherwise, there
  37213. // is no way to parse 'foo.bar.baz': 'baz' must be a property, but
  37214. // 'bar' could be the objectName, or part of a nodeName (which can
  37215. // include '.' characters).
  37216. if ( _supportedObjectNames.indexOf( objectName ) !== -1 ) {
  37217. results.nodeName = results.nodeName.substring( 0, lastDot );
  37218. results.objectName = objectName;
  37219. }
  37220. }
  37221. if ( results.propertyName === null || results.propertyName.length === 0 ) {
  37222. throw new Error( 'PropertyBinding: can not parse propertyName from trackName: ' + trackName );
  37223. }
  37224. return results;
  37225. }
  37226. /**
  37227. * Searches for a node in the hierarchy of the given root object by the given
  37228. * node name.
  37229. *
  37230. * @static
  37231. * @param {Object} root - The root object.
  37232. * @param {string|number} nodeName - The name of the node.
  37233. * @return {?Object} The found node. Returns `null` if no object was found.
  37234. */
  37235. static findNode( root, nodeName ) {
  37236. if ( nodeName === undefined || nodeName === '' || nodeName === '.' || nodeName === -1 || nodeName === root.name || nodeName === root.uuid ) {
  37237. return root;
  37238. }
  37239. // search into skeleton bones.
  37240. if ( root.skeleton ) {
  37241. const bone = root.skeleton.getBoneByName( nodeName );
  37242. if ( bone !== undefined ) {
  37243. return bone;
  37244. }
  37245. }
  37246. // search into node subtree.
  37247. if ( root.children ) {
  37248. const searchNodeSubtree = function ( children ) {
  37249. for ( let i = 0; i < children.length; i ++ ) {
  37250. const childNode = children[ i ];
  37251. if ( childNode.name === nodeName || childNode.uuid === nodeName ) {
  37252. return childNode;
  37253. }
  37254. const result = searchNodeSubtree( childNode.children );
  37255. if ( result ) return result;
  37256. }
  37257. return null;
  37258. };
  37259. const subTreeNode = searchNodeSubtree( root.children );
  37260. if ( subTreeNode ) {
  37261. return subTreeNode;
  37262. }
  37263. }
  37264. return null;
  37265. }
  37266. // these are used to "bind" a nonexistent property
  37267. _getValue_unavailable() {}
  37268. _setValue_unavailable() {}
  37269. // Getters
  37270. _getValue_direct( buffer, offset ) {
  37271. buffer[ offset ] = this.targetObject[ this.propertyName ];
  37272. }
  37273. _getValue_array( buffer, offset ) {
  37274. const source = this.resolvedProperty;
  37275. for ( let i = 0, n = source.length; i !== n; ++ i ) {
  37276. buffer[ offset ++ ] = source[ i ];
  37277. }
  37278. }
  37279. _getValue_arrayElement( buffer, offset ) {
  37280. buffer[ offset ] = this.resolvedProperty[ this.propertyIndex ];
  37281. }
  37282. _getValue_toArray( buffer, offset ) {
  37283. this.resolvedProperty.toArray( buffer, offset );
  37284. }
  37285. // Direct
  37286. _setValue_direct( buffer, offset ) {
  37287. this.targetObject[ this.propertyName ] = buffer[ offset ];
  37288. }
  37289. _setValue_direct_setNeedsUpdate( buffer, offset ) {
  37290. this.targetObject[ this.propertyName ] = buffer[ offset ];
  37291. this.targetObject.needsUpdate = true;
  37292. }
  37293. _setValue_direct_setMatrixWorldNeedsUpdate( buffer, offset ) {
  37294. this.targetObject[ this.propertyName ] = buffer[ offset ];
  37295. this.targetObject.matrixWorldNeedsUpdate = true;
  37296. }
  37297. // EntireArray
  37298. _setValue_array( buffer, offset ) {
  37299. const dest = this.resolvedProperty;
  37300. for ( let i = 0, n = dest.length; i !== n; ++ i ) {
  37301. dest[ i ] = buffer[ offset ++ ];
  37302. }
  37303. }
  37304. _setValue_array_setNeedsUpdate( buffer, offset ) {
  37305. const dest = this.resolvedProperty;
  37306. for ( let i = 0, n = dest.length; i !== n; ++ i ) {
  37307. dest[ i ] = buffer[ offset ++ ];
  37308. }
  37309. this.targetObject.needsUpdate = true;
  37310. }
  37311. _setValue_array_setMatrixWorldNeedsUpdate( buffer, offset ) {
  37312. const dest = this.resolvedProperty;
  37313. for ( let i = 0, n = dest.length; i !== n; ++ i ) {
  37314. dest[ i ] = buffer[ offset ++ ];
  37315. }
  37316. this.targetObject.matrixWorldNeedsUpdate = true;
  37317. }
  37318. // ArrayElement
  37319. _setValue_arrayElement( buffer, offset ) {
  37320. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  37321. }
  37322. _setValue_arrayElement_setNeedsUpdate( buffer, offset ) {
  37323. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  37324. this.targetObject.needsUpdate = true;
  37325. }
  37326. _setValue_arrayElement_setMatrixWorldNeedsUpdate( buffer, offset ) {
  37327. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  37328. this.targetObject.matrixWorldNeedsUpdate = true;
  37329. }
  37330. // HasToFromArray
  37331. _setValue_fromArray( buffer, offset ) {
  37332. this.resolvedProperty.fromArray( buffer, offset );
  37333. }
  37334. _setValue_fromArray_setNeedsUpdate( buffer, offset ) {
  37335. this.resolvedProperty.fromArray( buffer, offset );
  37336. this.targetObject.needsUpdate = true;
  37337. }
  37338. _setValue_fromArray_setMatrixWorldNeedsUpdate( buffer, offset ) {
  37339. this.resolvedProperty.fromArray( buffer, offset );
  37340. this.targetObject.matrixWorldNeedsUpdate = true;
  37341. }
  37342. _getValue_unbound( targetArray, offset ) {
  37343. this.bind();
  37344. this.getValue( targetArray, offset );
  37345. }
  37346. _setValue_unbound( sourceArray, offset ) {
  37347. this.bind();
  37348. this.setValue( sourceArray, offset );
  37349. }
  37350. /**
  37351. * Creates a getter / setter pair for the property tracked by this binding.
  37352. */
  37353. bind() {
  37354. let targetObject = this.node;
  37355. const parsedPath = this.parsedPath;
  37356. const objectName = parsedPath.objectName;
  37357. const propertyName = parsedPath.propertyName;
  37358. let propertyIndex = parsedPath.propertyIndex;
  37359. if ( ! targetObject ) {
  37360. targetObject = PropertyBinding.findNode( this.rootNode, parsedPath.nodeName );
  37361. this.node = targetObject;
  37362. }
  37363. // set fail state so we can just 'return' on error
  37364. this.getValue = this._getValue_unavailable;
  37365. this.setValue = this._setValue_unavailable;
  37366. // ensure there is a value node
  37367. if ( ! targetObject ) {
  37368. console.warn( 'THREE.PropertyBinding: No target node found for track: ' + this.path + '.' );
  37369. return;
  37370. }
  37371. if ( objectName ) {
  37372. let objectIndex = parsedPath.objectIndex;
  37373. // special cases were we need to reach deeper into the hierarchy to get the face materials....
  37374. switch ( objectName ) {
  37375. case 'materials':
  37376. if ( ! targetObject.material ) {
  37377. console.error( 'THREE.PropertyBinding: Can not bind to material as node does not have a material.', this );
  37378. return;
  37379. }
  37380. if ( ! targetObject.material.materials ) {
  37381. console.error( 'THREE.PropertyBinding: Can not bind to material.materials as node.material does not have a materials array.', this );
  37382. return;
  37383. }
  37384. targetObject = targetObject.material.materials;
  37385. break;
  37386. case 'bones':
  37387. if ( ! targetObject.skeleton ) {
  37388. console.error( 'THREE.PropertyBinding: Can not bind to bones as node does not have a skeleton.', this );
  37389. return;
  37390. }
  37391. // potential future optimization: skip this if propertyIndex is already an integer
  37392. // and convert the integer string to a true integer.
  37393. targetObject = targetObject.skeleton.bones;
  37394. // support resolving morphTarget names into indices.
  37395. for ( let i = 0; i < targetObject.length; i ++ ) {
  37396. if ( targetObject[ i ].name === objectIndex ) {
  37397. objectIndex = i;
  37398. break;
  37399. }
  37400. }
  37401. break;
  37402. case 'map':
  37403. if ( 'map' in targetObject ) {
  37404. targetObject = targetObject.map;
  37405. break;
  37406. }
  37407. if ( ! targetObject.material ) {
  37408. console.error( 'THREE.PropertyBinding: Can not bind to material as node does not have a material.', this );
  37409. return;
  37410. }
  37411. if ( ! targetObject.material.map ) {
  37412. console.error( 'THREE.PropertyBinding: Can not bind to material.map as node.material does not have a map.', this );
  37413. return;
  37414. }
  37415. targetObject = targetObject.material.map;
  37416. break;
  37417. default:
  37418. if ( targetObject[ objectName ] === undefined ) {
  37419. console.error( 'THREE.PropertyBinding: Can not bind to objectName of node undefined.', this );
  37420. return;
  37421. }
  37422. targetObject = targetObject[ objectName ];
  37423. }
  37424. if ( objectIndex !== undefined ) {
  37425. if ( targetObject[ objectIndex ] === undefined ) {
  37426. console.error( 'THREE.PropertyBinding: Trying to bind to objectIndex of objectName, but is undefined.', this, targetObject );
  37427. return;
  37428. }
  37429. targetObject = targetObject[ objectIndex ];
  37430. }
  37431. }
  37432. // resolve property
  37433. const nodeProperty = targetObject[ propertyName ];
  37434. if ( nodeProperty === undefined ) {
  37435. const nodeName = parsedPath.nodeName;
  37436. console.error( 'THREE.PropertyBinding: Trying to update property for track: ' + nodeName +
  37437. '.' + propertyName + ' but it wasn\'t found.', targetObject );
  37438. return;
  37439. }
  37440. // determine versioning scheme
  37441. let versioning = this.Versioning.None;
  37442. this.targetObject = targetObject;
  37443. if ( targetObject.isMaterial === true ) {
  37444. versioning = this.Versioning.NeedsUpdate;
  37445. } else if ( targetObject.isObject3D === true ) {
  37446. versioning = this.Versioning.MatrixWorldNeedsUpdate;
  37447. }
  37448. // determine how the property gets bound
  37449. let bindingType = this.BindingType.Direct;
  37450. if ( propertyIndex !== undefined ) {
  37451. // access a sub element of the property array (only primitives are supported right now)
  37452. if ( propertyName === 'morphTargetInfluences' ) {
  37453. // potential optimization, skip this if propertyIndex is already an integer, and convert the integer string to a true integer.
  37454. // support resolving morphTarget names into indices.
  37455. if ( ! targetObject.geometry ) {
  37456. console.error( 'THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.', this );
  37457. return;
  37458. }
  37459. if ( ! targetObject.geometry.morphAttributes ) {
  37460. console.error( 'THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.morphAttributes.', this );
  37461. return;
  37462. }
  37463. if ( targetObject.morphTargetDictionary[ propertyIndex ] !== undefined ) {
  37464. propertyIndex = targetObject.morphTargetDictionary[ propertyIndex ];
  37465. }
  37466. }
  37467. bindingType = this.BindingType.ArrayElement;
  37468. this.resolvedProperty = nodeProperty;
  37469. this.propertyIndex = propertyIndex;
  37470. } else if ( nodeProperty.fromArray !== undefined && nodeProperty.toArray !== undefined ) {
  37471. // must use copy for Object3D.Euler/Quaternion
  37472. bindingType = this.BindingType.HasFromToArray;
  37473. this.resolvedProperty = nodeProperty;
  37474. } else if ( Array.isArray( nodeProperty ) ) {
  37475. bindingType = this.BindingType.EntireArray;
  37476. this.resolvedProperty = nodeProperty;
  37477. } else {
  37478. this.propertyName = propertyName;
  37479. }
  37480. // select getter / setter
  37481. this.getValue = this.GetterByBindingType[ bindingType ];
  37482. this.setValue = this.SetterByBindingTypeAndVersioning[ bindingType ][ versioning ];
  37483. }
  37484. /**
  37485. * Unbinds the property.
  37486. */
  37487. unbind() {
  37488. this.node = null;
  37489. // back to the prototype version of getValue / setValue
  37490. // note: avoiding to mutate the shape of 'this' via 'delete'
  37491. this.getValue = this._getValue_unbound;
  37492. this.setValue = this._setValue_unbound;
  37493. }
  37494. }
  37495. PropertyBinding.Composite = Composite;
  37496. PropertyBinding.prototype.BindingType = {
  37497. Direct: 0,
  37498. EntireArray: 1,
  37499. ArrayElement: 2,
  37500. HasFromToArray: 3
  37501. };
  37502. PropertyBinding.prototype.Versioning = {
  37503. None: 0,
  37504. NeedsUpdate: 1,
  37505. MatrixWorldNeedsUpdate: 2
  37506. };
  37507. PropertyBinding.prototype.GetterByBindingType = [
  37508. PropertyBinding.prototype._getValue_direct,
  37509. PropertyBinding.prototype._getValue_array,
  37510. PropertyBinding.prototype._getValue_arrayElement,
  37511. PropertyBinding.prototype._getValue_toArray,
  37512. ];
  37513. PropertyBinding.prototype.SetterByBindingTypeAndVersioning = [
  37514. [
  37515. // Direct
  37516. PropertyBinding.prototype._setValue_direct,
  37517. PropertyBinding.prototype._setValue_direct_setNeedsUpdate,
  37518. PropertyBinding.prototype._setValue_direct_setMatrixWorldNeedsUpdate,
  37519. ], [
  37520. // EntireArray
  37521. PropertyBinding.prototype._setValue_array,
  37522. PropertyBinding.prototype._setValue_array_setNeedsUpdate,
  37523. PropertyBinding.prototype._setValue_array_setMatrixWorldNeedsUpdate,
  37524. ], [
  37525. // ArrayElement
  37526. PropertyBinding.prototype._setValue_arrayElement,
  37527. PropertyBinding.prototype._setValue_arrayElement_setNeedsUpdate,
  37528. PropertyBinding.prototype._setValue_arrayElement_setMatrixWorldNeedsUpdate,
  37529. ], [
  37530. // HasToFromArray
  37531. PropertyBinding.prototype._setValue_fromArray,
  37532. PropertyBinding.prototype._setValue_fromArray_setNeedsUpdate,
  37533. PropertyBinding.prototype._setValue_fromArray_setMatrixWorldNeedsUpdate,
  37534. ]
  37535. ];
  37536. /**
  37537. * A group of objects that receives a shared animation state.
  37538. *
  37539. * Usage:
  37540. *
  37541. * - Add objects you would otherwise pass as 'root' to the
  37542. * constructor or the .clipAction method of AnimationMixer.
  37543. * - Instead pass this object as 'root'.
  37544. * - You can also add and remove objects later when the mixer is running.
  37545. *
  37546. * Note:
  37547. *
  37548. * - Objects of this class appear as one object to the mixer,
  37549. * so cache control of the individual objects must be done on the group.
  37550. *
  37551. * Limitation:
  37552. *
  37553. * - The animated properties must be compatible among the all objects in the group.
  37554. * - A single property can either be controlled through a target group or directly, but not both.
  37555. */
  37556. class AnimationObjectGroup {
  37557. /**
  37558. * Constructs a new animation group.
  37559. *
  37560. * @param {...Object3D} arguments - An arbitrary number of 3D objects that share the same animation state.
  37561. */
  37562. constructor() {
  37563. /**
  37564. * This flag can be used for type testing.
  37565. *
  37566. * @type {boolean}
  37567. * @readonly
  37568. * @default true
  37569. */
  37570. this.isAnimationObjectGroup = true;
  37571. /**
  37572. * The UUID of the 3D object.
  37573. *
  37574. * @type {string}
  37575. * @readonly
  37576. */
  37577. this.uuid = generateUUID();
  37578. // cached objects followed by the active ones
  37579. this._objects = Array.prototype.slice.call( arguments );
  37580. this.nCachedObjects_ = 0; // threshold
  37581. // note: read by PropertyBinding.Composite
  37582. const indices = {};
  37583. this._indicesByUUID = indices; // for bookkeeping
  37584. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  37585. indices[ arguments[ i ].uuid ] = i;
  37586. }
  37587. this._paths = []; // inside: string
  37588. this._parsedPaths = []; // inside: { we don't care, here }
  37589. this._bindings = []; // inside: Array< PropertyBinding >
  37590. this._bindingsIndicesByPath = {}; // inside: indices in these arrays
  37591. const scope = this;
  37592. this.stats = {
  37593. objects: {
  37594. get total() {
  37595. return scope._objects.length;
  37596. },
  37597. get inUse() {
  37598. return this.total - scope.nCachedObjects_;
  37599. }
  37600. },
  37601. get bindingsPerObject() {
  37602. return scope._bindings.length;
  37603. }
  37604. };
  37605. }
  37606. /**
  37607. * Adds an arbitrary number of objects to this animation group.
  37608. *
  37609. * @param {...Object3D} arguments - The 3D objects to add.
  37610. */
  37611. add() {
  37612. const objects = this._objects,
  37613. indicesByUUID = this._indicesByUUID,
  37614. paths = this._paths,
  37615. parsedPaths = this._parsedPaths,
  37616. bindings = this._bindings,
  37617. nBindings = bindings.length;
  37618. let knownObject = undefined,
  37619. nObjects = objects.length,
  37620. nCachedObjects = this.nCachedObjects_;
  37621. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  37622. const object = arguments[ i ],
  37623. uuid = object.uuid;
  37624. let index = indicesByUUID[ uuid ];
  37625. if ( index === undefined ) {
  37626. // unknown object -> add it to the ACTIVE region
  37627. index = nObjects ++;
  37628. indicesByUUID[ uuid ] = index;
  37629. objects.push( object );
  37630. // accounting is done, now do the same for all bindings
  37631. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  37632. bindings[ j ].push( new PropertyBinding( object, paths[ j ], parsedPaths[ j ] ) );
  37633. }
  37634. } else if ( index < nCachedObjects ) {
  37635. knownObject = objects[ index ];
  37636. // move existing object to the ACTIVE region
  37637. const firstActiveIndex = -- nCachedObjects,
  37638. lastCachedObject = objects[ firstActiveIndex ];
  37639. indicesByUUID[ lastCachedObject.uuid ] = index;
  37640. objects[ index ] = lastCachedObject;
  37641. indicesByUUID[ uuid ] = firstActiveIndex;
  37642. objects[ firstActiveIndex ] = object;
  37643. // accounting is done, now do the same for all bindings
  37644. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  37645. const bindingsForPath = bindings[ j ],
  37646. lastCached = bindingsForPath[ firstActiveIndex ];
  37647. let binding = bindingsForPath[ index ];
  37648. bindingsForPath[ index ] = lastCached;
  37649. if ( binding === undefined ) {
  37650. // since we do not bother to create new bindings
  37651. // for objects that are cached, the binding may
  37652. // or may not exist
  37653. binding = new PropertyBinding( object, paths[ j ], parsedPaths[ j ] );
  37654. }
  37655. bindingsForPath[ firstActiveIndex ] = binding;
  37656. }
  37657. } else if ( objects[ index ] !== knownObject ) {
  37658. console.error( 'THREE.AnimationObjectGroup: Different objects with the same UUID ' +
  37659. 'detected. Clean the caches or recreate your infrastructure when reloading scenes.' );
  37660. } // else the object is already where we want it to be
  37661. } // for arguments
  37662. this.nCachedObjects_ = nCachedObjects;
  37663. }
  37664. /**
  37665. * Removes an arbitrary number of objects to this animation group
  37666. *
  37667. * @param {...Object3D} arguments - The 3D objects to remove.
  37668. */
  37669. remove() {
  37670. const objects = this._objects,
  37671. indicesByUUID = this._indicesByUUID,
  37672. bindings = this._bindings,
  37673. nBindings = bindings.length;
  37674. let nCachedObjects = this.nCachedObjects_;
  37675. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  37676. const object = arguments[ i ],
  37677. uuid = object.uuid,
  37678. index = indicesByUUID[ uuid ];
  37679. if ( index !== undefined && index >= nCachedObjects ) {
  37680. // move existing object into the CACHED region
  37681. const lastCachedIndex = nCachedObjects ++,
  37682. firstActiveObject = objects[ lastCachedIndex ];
  37683. indicesByUUID[ firstActiveObject.uuid ] = index;
  37684. objects[ index ] = firstActiveObject;
  37685. indicesByUUID[ uuid ] = lastCachedIndex;
  37686. objects[ lastCachedIndex ] = object;
  37687. // accounting is done, now do the same for all bindings
  37688. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  37689. const bindingsForPath = bindings[ j ],
  37690. firstActive = bindingsForPath[ lastCachedIndex ],
  37691. binding = bindingsForPath[ index ];
  37692. bindingsForPath[ index ] = firstActive;
  37693. bindingsForPath[ lastCachedIndex ] = binding;
  37694. }
  37695. }
  37696. } // for arguments
  37697. this.nCachedObjects_ = nCachedObjects;
  37698. }
  37699. /**
  37700. * Deallocates all memory resources for the passed 3D objects of this animation group.
  37701. *
  37702. * @param {...Object3D} arguments - The 3D objects to uncache.
  37703. */
  37704. uncache() {
  37705. const objects = this._objects,
  37706. indicesByUUID = this._indicesByUUID,
  37707. bindings = this._bindings,
  37708. nBindings = bindings.length;
  37709. let nCachedObjects = this.nCachedObjects_,
  37710. nObjects = objects.length;
  37711. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  37712. const object = arguments[ i ],
  37713. uuid = object.uuid,
  37714. index = indicesByUUID[ uuid ];
  37715. if ( index !== undefined ) {
  37716. delete indicesByUUID[ uuid ];
  37717. if ( index < nCachedObjects ) {
  37718. // object is cached, shrink the CACHED region
  37719. const firstActiveIndex = -- nCachedObjects,
  37720. lastCachedObject = objects[ firstActiveIndex ],
  37721. lastIndex = -- nObjects,
  37722. lastObject = objects[ lastIndex ];
  37723. // last cached object takes this object's place
  37724. indicesByUUID[ lastCachedObject.uuid ] = index;
  37725. objects[ index ] = lastCachedObject;
  37726. // last object goes to the activated slot and pop
  37727. indicesByUUID[ lastObject.uuid ] = firstActiveIndex;
  37728. objects[ firstActiveIndex ] = lastObject;
  37729. objects.pop();
  37730. // accounting is done, now do the same for all bindings
  37731. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  37732. const bindingsForPath = bindings[ j ],
  37733. lastCached = bindingsForPath[ firstActiveIndex ],
  37734. last = bindingsForPath[ lastIndex ];
  37735. bindingsForPath[ index ] = lastCached;
  37736. bindingsForPath[ firstActiveIndex ] = last;
  37737. bindingsForPath.pop();
  37738. }
  37739. } else {
  37740. // object is active, just swap with the last and pop
  37741. const lastIndex = -- nObjects,
  37742. lastObject = objects[ lastIndex ];
  37743. if ( lastIndex > 0 ) {
  37744. indicesByUUID[ lastObject.uuid ] = index;
  37745. }
  37746. objects[ index ] = lastObject;
  37747. objects.pop();
  37748. // accounting is done, now do the same for all bindings
  37749. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  37750. const bindingsForPath = bindings[ j ];
  37751. bindingsForPath[ index ] = bindingsForPath[ lastIndex ];
  37752. bindingsForPath.pop();
  37753. }
  37754. } // cached or active
  37755. } // if object is known
  37756. } // for arguments
  37757. this.nCachedObjects_ = nCachedObjects;
  37758. }
  37759. // Internal interface used by befriended PropertyBinding.Composite:
  37760. subscribe_( path, parsedPath ) {
  37761. // returns an array of bindings for the given path that is changed
  37762. // according to the contained objects in the group
  37763. const indicesByPath = this._bindingsIndicesByPath;
  37764. let index = indicesByPath[ path ];
  37765. const bindings = this._bindings;
  37766. if ( index !== undefined ) return bindings[ index ];
  37767. const paths = this._paths,
  37768. parsedPaths = this._parsedPaths,
  37769. objects = this._objects,
  37770. nObjects = objects.length,
  37771. nCachedObjects = this.nCachedObjects_,
  37772. bindingsForPath = new Array( nObjects );
  37773. index = bindings.length;
  37774. indicesByPath[ path ] = index;
  37775. paths.push( path );
  37776. parsedPaths.push( parsedPath );
  37777. bindings.push( bindingsForPath );
  37778. for ( let i = nCachedObjects, n = objects.length; i !== n; ++ i ) {
  37779. const object = objects[ i ];
  37780. bindingsForPath[ i ] = new PropertyBinding( object, path, parsedPath );
  37781. }
  37782. return bindingsForPath;
  37783. }
  37784. unsubscribe_( path ) {
  37785. // tells the group to forget about a property path and no longer
  37786. // update the array previously obtained with 'subscribe_'
  37787. const indicesByPath = this._bindingsIndicesByPath,
  37788. index = indicesByPath[ path ];
  37789. if ( index !== undefined ) {
  37790. const paths = this._paths,
  37791. parsedPaths = this._parsedPaths,
  37792. bindings = this._bindings,
  37793. lastBindingsIndex = bindings.length - 1,
  37794. lastBindings = bindings[ lastBindingsIndex ],
  37795. lastBindingsPath = path[ lastBindingsIndex ];
  37796. indicesByPath[ lastBindingsPath ] = index;
  37797. bindings[ index ] = lastBindings;
  37798. bindings.pop();
  37799. parsedPaths[ index ] = parsedPaths[ lastBindingsIndex ];
  37800. parsedPaths.pop();
  37801. paths[ index ] = paths[ lastBindingsIndex ];
  37802. paths.pop();
  37803. }
  37804. }
  37805. }
  37806. /**
  37807. * An instance of `AnimationAction` schedules the playback of an animation which is
  37808. * stored in {@link AnimationClip}.
  37809. */
  37810. class AnimationAction {
  37811. /**
  37812. * Constructs a new animation action.
  37813. *
  37814. * @param {AnimationMixer} mixer - The mixer that is controlled by this action.
  37815. * @param {AnimationClip} clip - The animation clip that holds the actual keyframes.
  37816. * @param {?Object3D} [localRoot=null] - The root object on which this action is performed.
  37817. * @param {(NormalAnimationBlendMode|AdditiveAnimationBlendMode)} [blendMode] - The blend mode.
  37818. */
  37819. constructor( mixer, clip, localRoot = null, blendMode = clip.blendMode ) {
  37820. this._mixer = mixer;
  37821. this._clip = clip;
  37822. this._localRoot = localRoot;
  37823. /**
  37824. * Defines how the animation is blended/combined when two or more animations
  37825. * are simultaneously played.
  37826. *
  37827. * @type {(NormalAnimationBlendMode|AdditiveAnimationBlendMode)}
  37828. */
  37829. this.blendMode = blendMode;
  37830. const tracks = clip.tracks,
  37831. nTracks = tracks.length,
  37832. interpolants = new Array( nTracks );
  37833. const interpolantSettings = {
  37834. endingStart: ZeroCurvatureEnding,
  37835. endingEnd: ZeroCurvatureEnding
  37836. };
  37837. for ( let i = 0; i !== nTracks; ++ i ) {
  37838. const interpolant = tracks[ i ].createInterpolant( null );
  37839. interpolants[ i ] = interpolant;
  37840. interpolant.settings = interpolantSettings;
  37841. }
  37842. this._interpolantSettings = interpolantSettings;
  37843. this._interpolants = interpolants; // bound by the mixer
  37844. // inside: PropertyMixer (managed by the mixer)
  37845. this._propertyBindings = new Array( nTracks );
  37846. this._cacheIndex = null; // for the memory manager
  37847. this._byClipCacheIndex = null; // for the memory manager
  37848. this._timeScaleInterpolant = null;
  37849. this._weightInterpolant = null;
  37850. /**
  37851. * The loop mode, set via {@link AnimationAction#setLoop}.
  37852. *
  37853. * @type {(LoopRepeat|LoopOnce|LoopPingPong)}
  37854. * @default LoopRepeat
  37855. */
  37856. this.loop = LoopRepeat;
  37857. this._loopCount = -1;
  37858. // global mixer time when the action is to be started
  37859. // it's set back to 'null' upon start of the action
  37860. this._startTime = null;
  37861. /**
  37862. * The local time of this action (in seconds, starting with `0`).
  37863. *
  37864. * The value gets clamped or wrapped to `[0,clip.duration]` (according to the
  37865. * loop state).
  37866. *
  37867. * @type {number}
  37868. * @default Infinity
  37869. */
  37870. this.time = 0;
  37871. /**
  37872. * Scaling factor for the {@link AnimationAction#time}. A value of `0` causes the
  37873. * animation to pause. Negative values cause the animation to play backwards.
  37874. *
  37875. * @type {number}
  37876. * @default 1
  37877. */
  37878. this.timeScale = 1;
  37879. this._effectiveTimeScale = 1;
  37880. /**
  37881. * The degree of influence of this action (in the interval `[0, 1]`). Values
  37882. * between `0` (no impact) and `1` (full impact) can be used to blend between
  37883. * several actions.
  37884. *
  37885. * @type {number}
  37886. * @default 1
  37887. */
  37888. this.weight = 1;
  37889. this._effectiveWeight = 1;
  37890. /**
  37891. * The number of repetitions of the performed clip over the course of this action.
  37892. * Can be set via {@link AnimationAction#setLoop}.
  37893. *
  37894. * Setting this number has no effect if {@link AnimationAction#loop} is set to
  37895. * `THREE:LoopOnce`.
  37896. *
  37897. * @type {number}
  37898. * @default Infinity
  37899. */
  37900. this.repetitions = Infinity;
  37901. /**
  37902. * If set to `true`, the playback of the action is paused.
  37903. *
  37904. * @type {boolean}
  37905. * @default false
  37906. */
  37907. this.paused = false;
  37908. /**
  37909. * If set to `false`, the action is disabled so it has no impact.
  37910. *
  37911. * When the action is re-enabled, the animation continues from its current
  37912. * time (setting `enabled` to `false` doesn't reset the action).
  37913. *
  37914. * @type {boolean}
  37915. * @default true
  37916. */
  37917. this.enabled = true;
  37918. /**
  37919. * If set to true the animation will automatically be paused on its last frame.
  37920. *
  37921. * If set to false, {@link AnimationAction#enabled} will automatically be switched
  37922. * to `false` when the last loop of the action has finished, so that this action has
  37923. * no further impact.
  37924. *
  37925. * Note: This member has no impact if the action is interrupted (it
  37926. * has only an effect if its last loop has really finished).
  37927. *
  37928. * @type {boolean}
  37929. * @default false
  37930. */
  37931. this.clampWhenFinished = false;
  37932. /**
  37933. * Enables smooth interpolation without separate clips for start, loop and end.
  37934. *
  37935. * @type {boolean}
  37936. * @default true
  37937. */
  37938. this.zeroSlopeAtStart = true;
  37939. /**
  37940. * Enables smooth interpolation without separate clips for start, loop and end.
  37941. *
  37942. * @type {boolean}
  37943. * @default true
  37944. */
  37945. this.zeroSlopeAtEnd = true;
  37946. }
  37947. /**
  37948. * Starts the playback of the animation.
  37949. *
  37950. * @return {AnimationAction} A reference to this animation action.
  37951. */
  37952. play() {
  37953. this._mixer._activateAction( this );
  37954. return this;
  37955. }
  37956. /**
  37957. * Stops the playback of the animation.
  37958. *
  37959. * @return {AnimationAction} A reference to this animation action.
  37960. */
  37961. stop() {
  37962. this._mixer._deactivateAction( this );
  37963. return this.reset();
  37964. }
  37965. /**
  37966. * Resets the playback of the animation.
  37967. *
  37968. * @return {AnimationAction} A reference to this animation action.
  37969. */
  37970. reset() {
  37971. this.paused = false;
  37972. this.enabled = true;
  37973. this.time = 0; // restart clip
  37974. this._loopCount = -1;// forget previous loops
  37975. this._startTime = null;// forget scheduling
  37976. return this.stopFading().stopWarping();
  37977. }
  37978. /**
  37979. * Returns `true` if the animation is running.
  37980. *
  37981. * @return {boolean} Whether the animation is running or not.
  37982. */
  37983. isRunning() {
  37984. return this.enabled && ! this.paused && this.timeScale !== 0 &&
  37985. this._startTime === null && this._mixer._isActiveAction( this );
  37986. }
  37987. /**
  37988. * Returns `true` when {@link AnimationAction#play} has been called.
  37989. *
  37990. * @return {boolean} Whether the animation is scheduled or not.
  37991. */
  37992. isScheduled() {
  37993. return this._mixer._isActiveAction( this );
  37994. }
  37995. /**
  37996. * Defines the time when the animation should start.
  37997. *
  37998. * @param {number} time - The start time in seconds.
  37999. * @return {AnimationAction} A reference to this animation action.
  38000. */
  38001. startAt( time ) {
  38002. this._startTime = time;
  38003. return this;
  38004. }
  38005. /**
  38006. * Configures the loop settings for this action.
  38007. *
  38008. * @param {(LoopRepeat|LoopOnce|LoopPingPong)} mode - The loop mode.
  38009. * @param {number} repetitions - The number of repetitions.
  38010. * @return {AnimationAction} A reference to this animation action.
  38011. */
  38012. setLoop( mode, repetitions ) {
  38013. this.loop = mode;
  38014. this.repetitions = repetitions;
  38015. return this;
  38016. }
  38017. /**
  38018. * Sets the effective weight of this action.
  38019. *
  38020. * An action has no effect and thus an effective weight of zero when the
  38021. * action is disabled.
  38022. *
  38023. * @param {number} weight - The weight to set.
  38024. * @return {AnimationAction} A reference to this animation action.
  38025. */
  38026. setEffectiveWeight( weight ) {
  38027. this.weight = weight;
  38028. // note: same logic as when updated at runtime
  38029. this._effectiveWeight = this.enabled ? weight : 0;
  38030. return this.stopFading();
  38031. }
  38032. /**
  38033. * Returns the effective weight of this action.
  38034. *
  38035. * @return {number} The effective weight.
  38036. */
  38037. getEffectiveWeight() {
  38038. return this._effectiveWeight;
  38039. }
  38040. /**
  38041. * Fades the animation in by increasing its weight gradually from `0` to `1`,
  38042. * within the passed time interval.
  38043. *
  38044. * @param {number} duration - The duration of the fade.
  38045. * @return {AnimationAction} A reference to this animation action.
  38046. */
  38047. fadeIn( duration ) {
  38048. return this._scheduleFading( duration, 0, 1 );
  38049. }
  38050. /**
  38051. * Fades the animation out by decreasing its weight gradually from `1` to `0`,
  38052. * within the passed time interval.
  38053. *
  38054. * @param {number} duration - The duration of the fade.
  38055. * @return {AnimationAction} A reference to this animation action.
  38056. */
  38057. fadeOut( duration ) {
  38058. return this._scheduleFading( duration, 1, 0 );
  38059. }
  38060. /**
  38061. * Causes this action to fade in and the given action to fade out,
  38062. * within the passed time interval.
  38063. *
  38064. * @param {AnimationAction} fadeOutAction - The animation action to fade out.
  38065. * @param {number} duration - The duration of the fade.
  38066. * @param {boolean} [warp=false] - Whether warping should be used or not.
  38067. * @return {AnimationAction} A reference to this animation action.
  38068. */
  38069. crossFadeFrom( fadeOutAction, duration, warp = false ) {
  38070. fadeOutAction.fadeOut( duration );
  38071. this.fadeIn( duration );
  38072. if ( warp === true ) {
  38073. const fadeInDuration = this._clip.duration,
  38074. fadeOutDuration = fadeOutAction._clip.duration,
  38075. startEndRatio = fadeOutDuration / fadeInDuration,
  38076. endStartRatio = fadeInDuration / fadeOutDuration;
  38077. fadeOutAction.warp( 1.0, startEndRatio, duration );
  38078. this.warp( endStartRatio, 1.0, duration );
  38079. }
  38080. return this;
  38081. }
  38082. /**
  38083. * Causes this action to fade out and the given action to fade in,
  38084. * within the passed time interval.
  38085. *
  38086. * @param {AnimationAction} fadeInAction - The animation action to fade in.
  38087. * @param {number} duration - The duration of the fade.
  38088. * @param {boolean} [warp=false] - Whether warping should be used or not.
  38089. * @return {AnimationAction} A reference to this animation action.
  38090. */
  38091. crossFadeTo( fadeInAction, duration, warp = false ) {
  38092. return fadeInAction.crossFadeFrom( this, duration, warp );
  38093. }
  38094. /**
  38095. * Stops any fading which is applied to this action.
  38096. *
  38097. * @return {AnimationAction} A reference to this animation action.
  38098. */
  38099. stopFading() {
  38100. const weightInterpolant = this._weightInterpolant;
  38101. if ( weightInterpolant !== null ) {
  38102. this._weightInterpolant = null;
  38103. this._mixer._takeBackControlInterpolant( weightInterpolant );
  38104. }
  38105. return this;
  38106. }
  38107. /**
  38108. * Sets the effective time scale of this action.
  38109. *
  38110. * An action has no effect and thus an effective time scale of zero when the
  38111. * action is paused.
  38112. *
  38113. * @param {number} timeScale - The time scale to set.
  38114. * @return {AnimationAction} A reference to this animation action.
  38115. */
  38116. setEffectiveTimeScale( timeScale ) {
  38117. this.timeScale = timeScale;
  38118. this._effectiveTimeScale = this.paused ? 0 : timeScale;
  38119. return this.stopWarping();
  38120. }
  38121. /**
  38122. * Returns the effective time scale of this action.
  38123. *
  38124. * @return {number} The effective time scale.
  38125. */
  38126. getEffectiveTimeScale() {
  38127. return this._effectiveTimeScale;
  38128. }
  38129. /**
  38130. * Sets the duration for a single loop of this action.
  38131. *
  38132. * @param {number} duration - The duration to set.
  38133. * @return {AnimationAction} A reference to this animation action.
  38134. */
  38135. setDuration( duration ) {
  38136. this.timeScale = this._clip.duration / duration;
  38137. return this.stopWarping();
  38138. }
  38139. /**
  38140. * Synchronizes this action with the passed other action.
  38141. *
  38142. * @param {AnimationAction} action - The action to sync with.
  38143. * @return {AnimationAction} A reference to this animation action.
  38144. */
  38145. syncWith( action ) {
  38146. this.time = action.time;
  38147. this.timeScale = action.timeScale;
  38148. return this.stopWarping();
  38149. }
  38150. /**
  38151. * Decelerates this animation's speed to `0` within the passed time interval.
  38152. *
  38153. * @param {number} duration - The duration.
  38154. * @return {AnimationAction} A reference to this animation action.
  38155. */
  38156. halt( duration ) {
  38157. return this.warp( this._effectiveTimeScale, 0, duration );
  38158. }
  38159. /**
  38160. * Changes the playback speed, within the passed time interval, by modifying
  38161. * {@link AnimationAction#timeScale} gradually from `startTimeScale` to
  38162. * `endTimeScale`.
  38163. *
  38164. * @param {number} startTimeScale - The start time scale.
  38165. * @param {number} endTimeScale - The end time scale.
  38166. * @param {number} duration - The duration.
  38167. * @return {AnimationAction} A reference to this animation action.
  38168. */
  38169. warp( startTimeScale, endTimeScale, duration ) {
  38170. const mixer = this._mixer,
  38171. now = mixer.time,
  38172. timeScale = this.timeScale;
  38173. let interpolant = this._timeScaleInterpolant;
  38174. if ( interpolant === null ) {
  38175. interpolant = mixer._lendControlInterpolant();
  38176. this._timeScaleInterpolant = interpolant;
  38177. }
  38178. const times = interpolant.parameterPositions,
  38179. values = interpolant.sampleValues;
  38180. times[ 0 ] = now;
  38181. times[ 1 ] = now + duration;
  38182. values[ 0 ] = startTimeScale / timeScale;
  38183. values[ 1 ] = endTimeScale / timeScale;
  38184. return this;
  38185. }
  38186. /**
  38187. * Stops any scheduled warping which is applied to this action.
  38188. *
  38189. * @return {AnimationAction} A reference to this animation action.
  38190. */
  38191. stopWarping() {
  38192. const timeScaleInterpolant = this._timeScaleInterpolant;
  38193. if ( timeScaleInterpolant !== null ) {
  38194. this._timeScaleInterpolant = null;
  38195. this._mixer._takeBackControlInterpolant( timeScaleInterpolant );
  38196. }
  38197. return this;
  38198. }
  38199. /**
  38200. * Returns the animation mixer of this animation action.
  38201. *
  38202. * @return {AnimationMixer} The animation mixer.
  38203. */
  38204. getMixer() {
  38205. return this._mixer;
  38206. }
  38207. /**
  38208. * Returns the animation clip of this animation action.
  38209. *
  38210. * @return {AnimationClip} The animation clip.
  38211. */
  38212. getClip() {
  38213. return this._clip;
  38214. }
  38215. /**
  38216. * Returns the root object of this animation action.
  38217. *
  38218. * @return {Object3D} The root object.
  38219. */
  38220. getRoot() {
  38221. return this._localRoot || this._mixer._root;
  38222. }
  38223. // Interna
  38224. _update( time, deltaTime, timeDirection, accuIndex ) {
  38225. // called by the mixer
  38226. if ( ! this.enabled ) {
  38227. // call ._updateWeight() to update ._effectiveWeight
  38228. this._updateWeight( time );
  38229. return;
  38230. }
  38231. const startTime = this._startTime;
  38232. if ( startTime !== null ) {
  38233. // check for scheduled start of action
  38234. const timeRunning = ( time - startTime ) * timeDirection;
  38235. if ( timeRunning < 0 || timeDirection === 0 ) {
  38236. deltaTime = 0;
  38237. } else {
  38238. this._startTime = null; // unschedule
  38239. deltaTime = timeDirection * timeRunning;
  38240. }
  38241. }
  38242. // apply time scale and advance time
  38243. deltaTime *= this._updateTimeScale( time );
  38244. const clipTime = this._updateTime( deltaTime );
  38245. // note: _updateTime may disable the action resulting in
  38246. // an effective weight of 0
  38247. const weight = this._updateWeight( time );
  38248. if ( weight > 0 ) {
  38249. const interpolants = this._interpolants;
  38250. const propertyMixers = this._propertyBindings;
  38251. switch ( this.blendMode ) {
  38252. case AdditiveAnimationBlendMode:
  38253. for ( let j = 0, m = interpolants.length; j !== m; ++ j ) {
  38254. interpolants[ j ].evaluate( clipTime );
  38255. propertyMixers[ j ].accumulateAdditive( weight );
  38256. }
  38257. break;
  38258. case NormalAnimationBlendMode:
  38259. default:
  38260. for ( let j = 0, m = interpolants.length; j !== m; ++ j ) {
  38261. interpolants[ j ].evaluate( clipTime );
  38262. propertyMixers[ j ].accumulate( accuIndex, weight );
  38263. }
  38264. }
  38265. }
  38266. }
  38267. _updateWeight( time ) {
  38268. let weight = 0;
  38269. if ( this.enabled ) {
  38270. weight = this.weight;
  38271. const interpolant = this._weightInterpolant;
  38272. if ( interpolant !== null ) {
  38273. const interpolantValue = interpolant.evaluate( time )[ 0 ];
  38274. weight *= interpolantValue;
  38275. if ( time > interpolant.parameterPositions[ 1 ] ) {
  38276. this.stopFading();
  38277. if ( interpolantValue === 0 ) {
  38278. // faded out, disable
  38279. this.enabled = false;
  38280. }
  38281. }
  38282. }
  38283. }
  38284. this._effectiveWeight = weight;
  38285. return weight;
  38286. }
  38287. _updateTimeScale( time ) {
  38288. let timeScale = 0;
  38289. if ( ! this.paused ) {
  38290. timeScale = this.timeScale;
  38291. const interpolant = this._timeScaleInterpolant;
  38292. if ( interpolant !== null ) {
  38293. const interpolantValue = interpolant.evaluate( time )[ 0 ];
  38294. timeScale *= interpolantValue;
  38295. if ( time > interpolant.parameterPositions[ 1 ] ) {
  38296. this.stopWarping();
  38297. if ( timeScale === 0 ) {
  38298. // motion has halted, pause
  38299. this.paused = true;
  38300. } else {
  38301. // warp done - apply final time scale
  38302. this.timeScale = timeScale;
  38303. }
  38304. }
  38305. }
  38306. }
  38307. this._effectiveTimeScale = timeScale;
  38308. return timeScale;
  38309. }
  38310. _updateTime( deltaTime ) {
  38311. const duration = this._clip.duration;
  38312. const loop = this.loop;
  38313. let time = this.time + deltaTime;
  38314. let loopCount = this._loopCount;
  38315. const pingPong = ( loop === LoopPingPong );
  38316. if ( deltaTime === 0 ) {
  38317. if ( loopCount === -1 ) return time;
  38318. return ( pingPong && ( loopCount & 1 ) === 1 ) ? duration - time : time;
  38319. }
  38320. if ( loop === LoopOnce ) {
  38321. if ( loopCount === -1 ) {
  38322. // just started
  38323. this._loopCount = 0;
  38324. this._setEndings( true, true, false );
  38325. }
  38326. handle_stop: {
  38327. if ( time >= duration ) {
  38328. time = duration;
  38329. } else if ( time < 0 ) {
  38330. time = 0;
  38331. } else {
  38332. this.time = time;
  38333. break handle_stop;
  38334. }
  38335. if ( this.clampWhenFinished ) this.paused = true;
  38336. else this.enabled = false;
  38337. this.time = time;
  38338. this._mixer.dispatchEvent( {
  38339. type: 'finished', action: this,
  38340. direction: deltaTime < 0 ? -1 : 1
  38341. } );
  38342. }
  38343. } else { // repetitive Repeat or PingPong
  38344. if ( loopCount === -1 ) {
  38345. // just started
  38346. if ( deltaTime >= 0 ) {
  38347. loopCount = 0;
  38348. this._setEndings( true, this.repetitions === 0, pingPong );
  38349. } else {
  38350. // when looping in reverse direction, the initial
  38351. // transition through zero counts as a repetition,
  38352. // so leave loopCount at -1
  38353. this._setEndings( this.repetitions === 0, true, pingPong );
  38354. }
  38355. }
  38356. if ( time >= duration || time < 0 ) {
  38357. // wrap around
  38358. const loopDelta = Math.floor( time / duration ); // signed
  38359. time -= duration * loopDelta;
  38360. loopCount += Math.abs( loopDelta );
  38361. const pending = this.repetitions - loopCount;
  38362. if ( pending <= 0 ) {
  38363. // have to stop (switch state, clamp time, fire event)
  38364. if ( this.clampWhenFinished ) this.paused = true;
  38365. else this.enabled = false;
  38366. time = deltaTime > 0 ? duration : 0;
  38367. this.time = time;
  38368. this._mixer.dispatchEvent( {
  38369. type: 'finished', action: this,
  38370. direction: deltaTime > 0 ? 1 : -1
  38371. } );
  38372. } else {
  38373. // keep running
  38374. if ( pending === 1 ) {
  38375. // entering the last round
  38376. const atStart = deltaTime < 0;
  38377. this._setEndings( atStart, ! atStart, pingPong );
  38378. } else {
  38379. this._setEndings( false, false, pingPong );
  38380. }
  38381. this._loopCount = loopCount;
  38382. this.time = time;
  38383. this._mixer.dispatchEvent( {
  38384. type: 'loop', action: this, loopDelta: loopDelta
  38385. } );
  38386. }
  38387. } else {
  38388. this.time = time;
  38389. }
  38390. if ( pingPong && ( loopCount & 1 ) === 1 ) {
  38391. // invert time for the "pong round"
  38392. return duration - time;
  38393. }
  38394. }
  38395. return time;
  38396. }
  38397. _setEndings( atStart, atEnd, pingPong ) {
  38398. const settings = this._interpolantSettings;
  38399. if ( pingPong ) {
  38400. settings.endingStart = ZeroSlopeEnding;
  38401. settings.endingEnd = ZeroSlopeEnding;
  38402. } else {
  38403. // assuming for LoopOnce atStart == atEnd == true
  38404. if ( atStart ) {
  38405. settings.endingStart = this.zeroSlopeAtStart ? ZeroSlopeEnding : ZeroCurvatureEnding;
  38406. } else {
  38407. settings.endingStart = WrapAroundEnding;
  38408. }
  38409. if ( atEnd ) {
  38410. settings.endingEnd = this.zeroSlopeAtEnd ? ZeroSlopeEnding : ZeroCurvatureEnding;
  38411. } else {
  38412. settings.endingEnd = WrapAroundEnding;
  38413. }
  38414. }
  38415. }
  38416. _scheduleFading( duration, weightNow, weightThen ) {
  38417. const mixer = this._mixer, now = mixer.time;
  38418. let interpolant = this._weightInterpolant;
  38419. if ( interpolant === null ) {
  38420. interpolant = mixer._lendControlInterpolant();
  38421. this._weightInterpolant = interpolant;
  38422. }
  38423. const times = interpolant.parameterPositions,
  38424. values = interpolant.sampleValues;
  38425. times[ 0 ] = now;
  38426. values[ 0 ] = weightNow;
  38427. times[ 1 ] = now + duration;
  38428. values[ 1 ] = weightThen;
  38429. return this;
  38430. }
  38431. }
  38432. const _controlInterpolantsResultBuffer = new Float32Array( 1 );
  38433. /**
  38434. * `AnimationMixer` is a player for animations on a particular object in
  38435. * the scene. When multiple objects in the scene are animated independently,
  38436. * one `AnimationMixer` may be used for each object.
  38437. */
  38438. class AnimationMixer extends EventDispatcher {
  38439. /**
  38440. * Constructs a new animation mixer.
  38441. *
  38442. * @param {Object3D} root - The object whose animations shall be played by this mixer.
  38443. */
  38444. constructor( root ) {
  38445. super();
  38446. this._root = root;
  38447. this._initMemoryManager();
  38448. this._accuIndex = 0;
  38449. /**
  38450. * The global mixer time (in seconds; starting with `0` on the mixer's creation).
  38451. *
  38452. * @type {number}
  38453. * @default 0
  38454. */
  38455. this.time = 0;
  38456. /**
  38457. * A scaling factor for the global time.
  38458. *
  38459. * Note: Setting this member to `0` and later back to `1` is a
  38460. * possibility to pause/unpause all actions that are controlled by this
  38461. * mixer.
  38462. *
  38463. * @type {number}
  38464. * @default 1
  38465. */
  38466. this.timeScale = 1.0;
  38467. }
  38468. _bindAction( action, prototypeAction ) {
  38469. const root = action._localRoot || this._root,
  38470. tracks = action._clip.tracks,
  38471. nTracks = tracks.length,
  38472. bindings = action._propertyBindings,
  38473. interpolants = action._interpolants,
  38474. rootUuid = root.uuid,
  38475. bindingsByRoot = this._bindingsByRootAndName;
  38476. let bindingsByName = bindingsByRoot[ rootUuid ];
  38477. if ( bindingsByName === undefined ) {
  38478. bindingsByName = {};
  38479. bindingsByRoot[ rootUuid ] = bindingsByName;
  38480. }
  38481. for ( let i = 0; i !== nTracks; ++ i ) {
  38482. const track = tracks[ i ],
  38483. trackName = track.name;
  38484. let binding = bindingsByName[ trackName ];
  38485. if ( binding !== undefined ) {
  38486. ++ binding.referenceCount;
  38487. bindings[ i ] = binding;
  38488. } else {
  38489. binding = bindings[ i ];
  38490. if ( binding !== undefined ) {
  38491. // existing binding, make sure the cache knows
  38492. if ( binding._cacheIndex === null ) {
  38493. ++ binding.referenceCount;
  38494. this._addInactiveBinding( binding, rootUuid, trackName );
  38495. }
  38496. continue;
  38497. }
  38498. const path = prototypeAction && prototypeAction.
  38499. _propertyBindings[ i ].binding.parsedPath;
  38500. binding = new PropertyMixer(
  38501. PropertyBinding.create( root, trackName, path ),
  38502. track.ValueTypeName, track.getValueSize() );
  38503. ++ binding.referenceCount;
  38504. this._addInactiveBinding( binding, rootUuid, trackName );
  38505. bindings[ i ] = binding;
  38506. }
  38507. interpolants[ i ].resultBuffer = binding.buffer;
  38508. }
  38509. }
  38510. _activateAction( action ) {
  38511. if ( ! this._isActiveAction( action ) ) {
  38512. if ( action._cacheIndex === null ) {
  38513. // this action has been forgotten by the cache, but the user
  38514. // appears to be still using it -> rebind
  38515. const rootUuid = ( action._localRoot || this._root ).uuid,
  38516. clipUuid = action._clip.uuid,
  38517. actionsForClip = this._actionsByClip[ clipUuid ];
  38518. this._bindAction( action,
  38519. actionsForClip && actionsForClip.knownActions[ 0 ] );
  38520. this._addInactiveAction( action, clipUuid, rootUuid );
  38521. }
  38522. const bindings = action._propertyBindings;
  38523. // increment reference counts / sort out state
  38524. for ( let i = 0, n = bindings.length; i !== n; ++ i ) {
  38525. const binding = bindings[ i ];
  38526. if ( binding.useCount ++ === 0 ) {
  38527. this._lendBinding( binding );
  38528. binding.saveOriginalState();
  38529. }
  38530. }
  38531. this._lendAction( action );
  38532. }
  38533. }
  38534. _deactivateAction( action ) {
  38535. if ( this._isActiveAction( action ) ) {
  38536. const bindings = action._propertyBindings;
  38537. // decrement reference counts / sort out state
  38538. for ( let i = 0, n = bindings.length; i !== n; ++ i ) {
  38539. const binding = bindings[ i ];
  38540. if ( -- binding.useCount === 0 ) {
  38541. binding.restoreOriginalState();
  38542. this._takeBackBinding( binding );
  38543. }
  38544. }
  38545. this._takeBackAction( action );
  38546. }
  38547. }
  38548. // Memory manager
  38549. _initMemoryManager() {
  38550. this._actions = []; // 'nActiveActions' followed by inactive ones
  38551. this._nActiveActions = 0;
  38552. this._actionsByClip = {};
  38553. // inside:
  38554. // {
  38555. // knownActions: Array< AnimationAction > - used as prototypes
  38556. // actionByRoot: AnimationAction - lookup
  38557. // }
  38558. this._bindings = []; // 'nActiveBindings' followed by inactive ones
  38559. this._nActiveBindings = 0;
  38560. this._bindingsByRootAndName = {}; // inside: Map< name, PropertyMixer >
  38561. this._controlInterpolants = []; // same game as above
  38562. this._nActiveControlInterpolants = 0;
  38563. const scope = this;
  38564. this.stats = {
  38565. actions: {
  38566. get total() {
  38567. return scope._actions.length;
  38568. },
  38569. get inUse() {
  38570. return scope._nActiveActions;
  38571. }
  38572. },
  38573. bindings: {
  38574. get total() {
  38575. return scope._bindings.length;
  38576. },
  38577. get inUse() {
  38578. return scope._nActiveBindings;
  38579. }
  38580. },
  38581. controlInterpolants: {
  38582. get total() {
  38583. return scope._controlInterpolants.length;
  38584. },
  38585. get inUse() {
  38586. return scope._nActiveControlInterpolants;
  38587. }
  38588. }
  38589. };
  38590. }
  38591. // Memory management for AnimationAction objects
  38592. _isActiveAction( action ) {
  38593. const index = action._cacheIndex;
  38594. return index !== null && index < this._nActiveActions;
  38595. }
  38596. _addInactiveAction( action, clipUuid, rootUuid ) {
  38597. const actions = this._actions,
  38598. actionsByClip = this._actionsByClip;
  38599. let actionsForClip = actionsByClip[ clipUuid ];
  38600. if ( actionsForClip === undefined ) {
  38601. actionsForClip = {
  38602. knownActions: [ action ],
  38603. actionByRoot: {}
  38604. };
  38605. action._byClipCacheIndex = 0;
  38606. actionsByClip[ clipUuid ] = actionsForClip;
  38607. } else {
  38608. const knownActions = actionsForClip.knownActions;
  38609. action._byClipCacheIndex = knownActions.length;
  38610. knownActions.push( action );
  38611. }
  38612. action._cacheIndex = actions.length;
  38613. actions.push( action );
  38614. actionsForClip.actionByRoot[ rootUuid ] = action;
  38615. }
  38616. _removeInactiveAction( action ) {
  38617. const actions = this._actions,
  38618. lastInactiveAction = actions[ actions.length - 1 ],
  38619. cacheIndex = action._cacheIndex;
  38620. lastInactiveAction._cacheIndex = cacheIndex;
  38621. actions[ cacheIndex ] = lastInactiveAction;
  38622. actions.pop();
  38623. action._cacheIndex = null;
  38624. const clipUuid = action._clip.uuid,
  38625. actionsByClip = this._actionsByClip,
  38626. actionsForClip = actionsByClip[ clipUuid ],
  38627. knownActionsForClip = actionsForClip.knownActions,
  38628. lastKnownAction =
  38629. knownActionsForClip[ knownActionsForClip.length - 1 ],
  38630. byClipCacheIndex = action._byClipCacheIndex;
  38631. lastKnownAction._byClipCacheIndex = byClipCacheIndex;
  38632. knownActionsForClip[ byClipCacheIndex ] = lastKnownAction;
  38633. knownActionsForClip.pop();
  38634. action._byClipCacheIndex = null;
  38635. const actionByRoot = actionsForClip.actionByRoot,
  38636. rootUuid = ( action._localRoot || this._root ).uuid;
  38637. delete actionByRoot[ rootUuid ];
  38638. if ( knownActionsForClip.length === 0 ) {
  38639. delete actionsByClip[ clipUuid ];
  38640. }
  38641. this._removeInactiveBindingsForAction( action );
  38642. }
  38643. _removeInactiveBindingsForAction( action ) {
  38644. const bindings = action._propertyBindings;
  38645. for ( let i = 0, n = bindings.length; i !== n; ++ i ) {
  38646. const binding = bindings[ i ];
  38647. if ( -- binding.referenceCount === 0 ) {
  38648. this._removeInactiveBinding( binding );
  38649. }
  38650. }
  38651. }
  38652. _lendAction( action ) {
  38653. // [ active actions | inactive actions ]
  38654. // [ active actions >| inactive actions ]
  38655. // s a
  38656. // <-swap->
  38657. // a s
  38658. const actions = this._actions,
  38659. prevIndex = action._cacheIndex,
  38660. lastActiveIndex = this._nActiveActions ++,
  38661. firstInactiveAction = actions[ lastActiveIndex ];
  38662. action._cacheIndex = lastActiveIndex;
  38663. actions[ lastActiveIndex ] = action;
  38664. firstInactiveAction._cacheIndex = prevIndex;
  38665. actions[ prevIndex ] = firstInactiveAction;
  38666. }
  38667. _takeBackAction( action ) {
  38668. // [ active actions | inactive actions ]
  38669. // [ active actions |< inactive actions ]
  38670. // a s
  38671. // <-swap->
  38672. // s a
  38673. const actions = this._actions,
  38674. prevIndex = action._cacheIndex,
  38675. firstInactiveIndex = -- this._nActiveActions,
  38676. lastActiveAction = actions[ firstInactiveIndex ];
  38677. action._cacheIndex = firstInactiveIndex;
  38678. actions[ firstInactiveIndex ] = action;
  38679. lastActiveAction._cacheIndex = prevIndex;
  38680. actions[ prevIndex ] = lastActiveAction;
  38681. }
  38682. // Memory management for PropertyMixer objects
  38683. _addInactiveBinding( binding, rootUuid, trackName ) {
  38684. const bindingsByRoot = this._bindingsByRootAndName,
  38685. bindings = this._bindings;
  38686. let bindingByName = bindingsByRoot[ rootUuid ];
  38687. if ( bindingByName === undefined ) {
  38688. bindingByName = {};
  38689. bindingsByRoot[ rootUuid ] = bindingByName;
  38690. }
  38691. bindingByName[ trackName ] = binding;
  38692. binding._cacheIndex = bindings.length;
  38693. bindings.push( binding );
  38694. }
  38695. _removeInactiveBinding( binding ) {
  38696. const bindings = this._bindings,
  38697. propBinding = binding.binding,
  38698. rootUuid = propBinding.rootNode.uuid,
  38699. trackName = propBinding.path,
  38700. bindingsByRoot = this._bindingsByRootAndName,
  38701. bindingByName = bindingsByRoot[ rootUuid ],
  38702. lastInactiveBinding = bindings[ bindings.length - 1 ],
  38703. cacheIndex = binding._cacheIndex;
  38704. lastInactiveBinding._cacheIndex = cacheIndex;
  38705. bindings[ cacheIndex ] = lastInactiveBinding;
  38706. bindings.pop();
  38707. delete bindingByName[ trackName ];
  38708. if ( Object.keys( bindingByName ).length === 0 ) {
  38709. delete bindingsByRoot[ rootUuid ];
  38710. }
  38711. }
  38712. _lendBinding( binding ) {
  38713. const bindings = this._bindings,
  38714. prevIndex = binding._cacheIndex,
  38715. lastActiveIndex = this._nActiveBindings ++,
  38716. firstInactiveBinding = bindings[ lastActiveIndex ];
  38717. binding._cacheIndex = lastActiveIndex;
  38718. bindings[ lastActiveIndex ] = binding;
  38719. firstInactiveBinding._cacheIndex = prevIndex;
  38720. bindings[ prevIndex ] = firstInactiveBinding;
  38721. }
  38722. _takeBackBinding( binding ) {
  38723. const bindings = this._bindings,
  38724. prevIndex = binding._cacheIndex,
  38725. firstInactiveIndex = -- this._nActiveBindings,
  38726. lastActiveBinding = bindings[ firstInactiveIndex ];
  38727. binding._cacheIndex = firstInactiveIndex;
  38728. bindings[ firstInactiveIndex ] = binding;
  38729. lastActiveBinding._cacheIndex = prevIndex;
  38730. bindings[ prevIndex ] = lastActiveBinding;
  38731. }
  38732. // Memory management of Interpolants for weight and time scale
  38733. _lendControlInterpolant() {
  38734. const interpolants = this._controlInterpolants,
  38735. lastActiveIndex = this._nActiveControlInterpolants ++;
  38736. let interpolant = interpolants[ lastActiveIndex ];
  38737. if ( interpolant === undefined ) {
  38738. interpolant = new LinearInterpolant(
  38739. new Float32Array( 2 ), new Float32Array( 2 ),
  38740. 1, _controlInterpolantsResultBuffer );
  38741. interpolant.__cacheIndex = lastActiveIndex;
  38742. interpolants[ lastActiveIndex ] = interpolant;
  38743. }
  38744. return interpolant;
  38745. }
  38746. _takeBackControlInterpolant( interpolant ) {
  38747. const interpolants = this._controlInterpolants,
  38748. prevIndex = interpolant.__cacheIndex,
  38749. firstInactiveIndex = -- this._nActiveControlInterpolants,
  38750. lastActiveInterpolant = interpolants[ firstInactiveIndex ];
  38751. interpolant.__cacheIndex = firstInactiveIndex;
  38752. interpolants[ firstInactiveIndex ] = interpolant;
  38753. lastActiveInterpolant.__cacheIndex = prevIndex;
  38754. interpolants[ prevIndex ] = lastActiveInterpolant;
  38755. }
  38756. /**
  38757. * Returns an instance of {@link AnimationAction} for the passed clip.
  38758. *
  38759. * If an action fitting the clip and root parameters doesn't yet exist, it
  38760. * will be created by this method. Calling this method several times with the
  38761. * same clip and root parameters always returns the same action.
  38762. *
  38763. * @param {AnimationClip|string} clip - An animation clip or alternatively the name of the animation clip.
  38764. * @param {Object3D} [optionalRoot] - An alternative root object.
  38765. * @param {(NormalAnimationBlendMode|AdditiveAnimationBlendMode)} [blendMode] - The blend mode.
  38766. * @return {?AnimationAction} The animation action.
  38767. */
  38768. clipAction( clip, optionalRoot, blendMode ) {
  38769. const root = optionalRoot || this._root,
  38770. rootUuid = root.uuid;
  38771. let clipObject = typeof clip === 'string' ? AnimationClip.findByName( root, clip ) : clip;
  38772. const clipUuid = clipObject !== null ? clipObject.uuid : clip;
  38773. const actionsForClip = this._actionsByClip[ clipUuid ];
  38774. let prototypeAction = null;
  38775. if ( blendMode === undefined ) {
  38776. if ( clipObject !== null ) {
  38777. blendMode = clipObject.blendMode;
  38778. } else {
  38779. blendMode = NormalAnimationBlendMode;
  38780. }
  38781. }
  38782. if ( actionsForClip !== undefined ) {
  38783. const existingAction = actionsForClip.actionByRoot[ rootUuid ];
  38784. if ( existingAction !== undefined && existingAction.blendMode === blendMode ) {
  38785. return existingAction;
  38786. }
  38787. // we know the clip, so we don't have to parse all
  38788. // the bindings again but can just copy
  38789. prototypeAction = actionsForClip.knownActions[ 0 ];
  38790. // also, take the clip from the prototype action
  38791. if ( clipObject === null )
  38792. clipObject = prototypeAction._clip;
  38793. }
  38794. // clip must be known when specified via string
  38795. if ( clipObject === null ) return null;
  38796. // allocate all resources required to run it
  38797. const newAction = new AnimationAction( this, clipObject, optionalRoot, blendMode );
  38798. this._bindAction( newAction, prototypeAction );
  38799. // and make the action known to the memory manager
  38800. this._addInactiveAction( newAction, clipUuid, rootUuid );
  38801. return newAction;
  38802. }
  38803. /**
  38804. * Returns an existing animation action for the passed clip.
  38805. *
  38806. * @param {AnimationClip|string} clip - An animation clip or alternatively the name of the animation clip.
  38807. * @param {Object3D} [optionalRoot] - An alternative root object.
  38808. * @return {?AnimationAction} The animation action. Returns `null` if no action was found.
  38809. */
  38810. existingAction( clip, optionalRoot ) {
  38811. const root = optionalRoot || this._root,
  38812. rootUuid = root.uuid,
  38813. clipObject = typeof clip === 'string' ?
  38814. AnimationClip.findByName( root, clip ) : clip,
  38815. clipUuid = clipObject ? clipObject.uuid : clip,
  38816. actionsForClip = this._actionsByClip[ clipUuid ];
  38817. if ( actionsForClip !== undefined ) {
  38818. return actionsForClip.actionByRoot[ rootUuid ] || null;
  38819. }
  38820. return null;
  38821. }
  38822. /**
  38823. * Deactivates all previously scheduled actions on this mixer.
  38824. *
  38825. * @return {AnimationMixer} A reference to thi animation mixer.
  38826. */
  38827. stopAllAction() {
  38828. const actions = this._actions,
  38829. nActions = this._nActiveActions;
  38830. for ( let i = nActions - 1; i >= 0; -- i ) {
  38831. actions[ i ].stop();
  38832. }
  38833. return this;
  38834. }
  38835. /**
  38836. * Advances the global mixer time and updates the animation.
  38837. *
  38838. * This is usually done in the render loop by passing the delta
  38839. * time from {@link Clock} or {@link Timer}.
  38840. *
  38841. * @param {number} deltaTime - The delta time in seconds.
  38842. * @return {AnimationMixer} A reference to thi animation mixer.
  38843. */
  38844. update( deltaTime ) {
  38845. deltaTime *= this.timeScale;
  38846. const actions = this._actions,
  38847. nActions = this._nActiveActions,
  38848. time = this.time += deltaTime,
  38849. timeDirection = Math.sign( deltaTime ),
  38850. accuIndex = this._accuIndex ^= 1;
  38851. // run active actions
  38852. for ( let i = 0; i !== nActions; ++ i ) {
  38853. const action = actions[ i ];
  38854. action._update( time, deltaTime, timeDirection, accuIndex );
  38855. }
  38856. // update scene graph
  38857. const bindings = this._bindings,
  38858. nBindings = this._nActiveBindings;
  38859. for ( let i = 0; i !== nBindings; ++ i ) {
  38860. bindings[ i ].apply( accuIndex );
  38861. }
  38862. return this;
  38863. }
  38864. /**
  38865. * Sets the global mixer to a specific time and updates the animation accordingly.
  38866. *
  38867. * This is useful when you need to jump to an exact time in an animation. The
  38868. * input parameter will be scaled by {@link AnimationMixer#timeScale}
  38869. *
  38870. * @param {number} time - The time to set in seconds.
  38871. * @return {AnimationMixer} A reference to thi animation mixer.
  38872. */
  38873. setTime( time ) {
  38874. this.time = 0; // Zero out time attribute for AnimationMixer object;
  38875. for ( let i = 0; i < this._actions.length; i ++ ) {
  38876. this._actions[ i ].time = 0; // Zero out time attribute for all associated AnimationAction objects.
  38877. }
  38878. return this.update( time ); // Update used to set exact time. Returns "this" AnimationMixer object.
  38879. }
  38880. /**
  38881. * Returns this mixer's root object.
  38882. *
  38883. * @return {Object3D} The mixer's root object.
  38884. */
  38885. getRoot() {
  38886. return this._root;
  38887. }
  38888. /**
  38889. * Deallocates all memory resources for a clip. Before using this method make
  38890. * sure to call {@link AnimationAction#stop} for all related actions.
  38891. *
  38892. * @param {AnimationClip} clip - The clip to uncache.
  38893. */
  38894. uncacheClip( clip ) {
  38895. const actions = this._actions,
  38896. clipUuid = clip.uuid,
  38897. actionsByClip = this._actionsByClip,
  38898. actionsForClip = actionsByClip[ clipUuid ];
  38899. if ( actionsForClip !== undefined ) {
  38900. // note: just calling _removeInactiveAction would mess up the
  38901. // iteration state and also require updating the state we can
  38902. // just throw away
  38903. const actionsToRemove = actionsForClip.knownActions;
  38904. for ( let i = 0, n = actionsToRemove.length; i !== n; ++ i ) {
  38905. const action = actionsToRemove[ i ];
  38906. this._deactivateAction( action );
  38907. const cacheIndex = action._cacheIndex,
  38908. lastInactiveAction = actions[ actions.length - 1 ];
  38909. action._cacheIndex = null;
  38910. action._byClipCacheIndex = null;
  38911. lastInactiveAction._cacheIndex = cacheIndex;
  38912. actions[ cacheIndex ] = lastInactiveAction;
  38913. actions.pop();
  38914. this._removeInactiveBindingsForAction( action );
  38915. }
  38916. delete actionsByClip[ clipUuid ];
  38917. }
  38918. }
  38919. /**
  38920. * Deallocates all memory resources for a root object. Before using this
  38921. * method make sure to call {@link AnimationAction#stop} for all related
  38922. * actions or alternatively {@link AnimationMixer#stopAllAction} when the
  38923. * mixer operates on a single root.
  38924. *
  38925. * @param {Object3D} root - The root object to uncache.
  38926. */
  38927. uncacheRoot( root ) {
  38928. const rootUuid = root.uuid,
  38929. actionsByClip = this._actionsByClip;
  38930. for ( const clipUuid in actionsByClip ) {
  38931. const actionByRoot = actionsByClip[ clipUuid ].actionByRoot,
  38932. action = actionByRoot[ rootUuid ];
  38933. if ( action !== undefined ) {
  38934. this._deactivateAction( action );
  38935. this._removeInactiveAction( action );
  38936. }
  38937. }
  38938. const bindingsByRoot = this._bindingsByRootAndName,
  38939. bindingByName = bindingsByRoot[ rootUuid ];
  38940. if ( bindingByName !== undefined ) {
  38941. for ( const trackName in bindingByName ) {
  38942. const binding = bindingByName[ trackName ];
  38943. binding.restoreOriginalState();
  38944. this._removeInactiveBinding( binding );
  38945. }
  38946. }
  38947. }
  38948. /**
  38949. * Deallocates all memory resources for an action. The action is identified by the
  38950. * given clip and an optional root object. Before using this method make
  38951. * sure to call {@link AnimationAction#stop} to deactivate the action.
  38952. *
  38953. * @param {AnimationClip|string} clip - An animation clip or alternatively the name of the animation clip.
  38954. * @param {Object3D} [optionalRoot] - An alternative root object.
  38955. */
  38956. uncacheAction( clip, optionalRoot ) {
  38957. const action = this.existingAction( clip, optionalRoot );
  38958. if ( action !== null ) {
  38959. this._deactivateAction( action );
  38960. this._removeInactiveAction( action );
  38961. }
  38962. }
  38963. }
  38964. /**
  38965. * Represents a 3D render target.
  38966. *
  38967. * @augments RenderTarget
  38968. */
  38969. class RenderTarget3D extends RenderTarget {
  38970. /**
  38971. * Constructs a new 3D render target.
  38972. *
  38973. * @param {number} [width=1] - The width of the render target.
  38974. * @param {number} [height=1] - The height of the render target.
  38975. * @param {number} [depth=1] - The height of the render target.
  38976. * @param {RenderTarget~Options} [options] - The configuration object.
  38977. */
  38978. constructor( width = 1, height = 1, depth = 1, options = {} ) {
  38979. super( width, height, options );
  38980. /**
  38981. * This flag can be used for type testing.
  38982. *
  38983. * @type {boolean}
  38984. * @readonly
  38985. * @default true
  38986. */
  38987. this.isRenderTarget3D = true;
  38988. this.depth = depth;
  38989. /**
  38990. * Overwritten with a different texture type.
  38991. *
  38992. * @type {Data3DTexture}
  38993. */
  38994. this.texture = new Data3DTexture( null, width, height, depth );
  38995. this._setTextureOptions( options );
  38996. this.texture.isRenderTargetTexture = true;
  38997. }
  38998. }
  38999. /**
  39000. * Represents a uniform which is a global shader variable. They are passed to shader programs.
  39001. *
  39002. * When declaring a uniform of a {@link ShaderMaterial}, it is declared by value or by object.
  39003. * ```js
  39004. * uniforms: {
  39005. * time: { value: 1.0 },
  39006. * resolution: new Uniform( new Vector2() )
  39007. * };
  39008. * ```
  39009. * Since this class can only be used in context of {@link ShaderMaterial}, it is only supported
  39010. * in {@link WebGLRenderer}.
  39011. */
  39012. class Uniform {
  39013. /**
  39014. * Constructs a new uniform.
  39015. *
  39016. * @param {any} value - The uniform value.
  39017. */
  39018. constructor( value ) {
  39019. /**
  39020. * The uniform value.
  39021. *
  39022. * @type {any}
  39023. */
  39024. this.value = value;
  39025. }
  39026. /**
  39027. * Returns a new uniform with copied values from this instance.
  39028. * If the value has a `clone()` method, the value is cloned as well.
  39029. *
  39030. * @return {Uniform} A clone of this instance.
  39031. */
  39032. clone() {
  39033. return new Uniform( this.value.clone === undefined ? this.value : this.value.clone() );
  39034. }
  39035. }
  39036. let _id = 0;
  39037. /**
  39038. * A class for managing multiple uniforms in a single group. The renderer will process
  39039. * such a definition as a single UBO.
  39040. *
  39041. * Since this class can only be used in context of {@link ShaderMaterial}, it is only supported
  39042. * in {@link WebGLRenderer}.
  39043. *
  39044. * @augments EventDispatcher
  39045. */
  39046. class UniformsGroup extends EventDispatcher {
  39047. /**
  39048. * Constructs a new uniforms group.
  39049. */
  39050. constructor() {
  39051. super();
  39052. /**
  39053. * This flag can be used for type testing.
  39054. *
  39055. * @type {boolean}
  39056. * @readonly
  39057. * @default true
  39058. */
  39059. this.isUniformsGroup = true;
  39060. /**
  39061. * The ID of the 3D object.
  39062. *
  39063. * @name UniformsGroup#id
  39064. * @type {number}
  39065. * @readonly
  39066. */
  39067. Object.defineProperty( this, 'id', { value: _id ++ } );
  39068. /**
  39069. * The name of the uniforms group.
  39070. *
  39071. * @type {string}
  39072. */
  39073. this.name = '';
  39074. /**
  39075. * The buffer usage.
  39076. *
  39077. * @type {(StaticDrawUsage|DynamicDrawUsage|StreamDrawUsage|StaticReadUsage|DynamicReadUsage|StreamReadUsage|StaticCopyUsage|DynamicCopyUsage|StreamCopyUsage)}
  39078. * @default StaticDrawUsage
  39079. */
  39080. this.usage = StaticDrawUsage;
  39081. /**
  39082. * An array holding the uniforms.
  39083. *
  39084. * @type {Array<Uniform>}
  39085. */
  39086. this.uniforms = [];
  39087. }
  39088. /**
  39089. * Adds the given uniform to this uniforms group.
  39090. *
  39091. * @param {Uniform} uniform - The uniform to add.
  39092. * @return {UniformsGroup} A reference to this uniforms group.
  39093. */
  39094. add( uniform ) {
  39095. this.uniforms.push( uniform );
  39096. return this;
  39097. }
  39098. /**
  39099. * Removes the given uniform from this uniforms group.
  39100. *
  39101. * @param {Uniform} uniform - The uniform to remove.
  39102. * @return {UniformsGroup} A reference to this uniforms group.
  39103. */
  39104. remove( uniform ) {
  39105. const index = this.uniforms.indexOf( uniform );
  39106. if ( index !== -1 ) this.uniforms.splice( index, 1 );
  39107. return this;
  39108. }
  39109. /**
  39110. * Sets the name of this uniforms group.
  39111. *
  39112. * @param {string} name - The name to set.
  39113. * @return {UniformsGroup} A reference to this uniforms group.
  39114. */
  39115. setName( name ) {
  39116. this.name = name;
  39117. return this;
  39118. }
  39119. /**
  39120. * Sets the usage of this uniforms group.
  39121. *
  39122. * @param {(StaticDrawUsage|DynamicDrawUsage|StreamDrawUsage|StaticReadUsage|DynamicReadUsage|StreamReadUsage|StaticCopyUsage|DynamicCopyUsage|StreamCopyUsage)} value - The usage to set.
  39123. * @return {UniformsGroup} A reference to this uniforms group.
  39124. */
  39125. setUsage( value ) {
  39126. this.usage = value;
  39127. return this;
  39128. }
  39129. /**
  39130. * Frees the GPU-related resources allocated by this instance. Call this
  39131. * method whenever this instance is no longer used in your app.
  39132. *
  39133. * @fires Texture#dispose
  39134. */
  39135. dispose() {
  39136. this.dispatchEvent( { type: 'dispose' } );
  39137. }
  39138. /**
  39139. * Copies the values of the given uniforms group to this instance.
  39140. *
  39141. * @param {UniformsGroup} source - The uniforms group to copy.
  39142. * @return {UniformsGroup} A reference to this uniforms group.
  39143. */
  39144. copy( source ) {
  39145. this.name = source.name;
  39146. this.usage = source.usage;
  39147. const uniformsSource = source.uniforms;
  39148. this.uniforms.length = 0;
  39149. for ( let i = 0, l = uniformsSource.length; i < l; i ++ ) {
  39150. const uniforms = Array.isArray( uniformsSource[ i ] ) ? uniformsSource[ i ] : [ uniformsSource[ i ] ];
  39151. for ( let j = 0; j < uniforms.length; j ++ ) {
  39152. this.uniforms.push( uniforms[ j ].clone() );
  39153. }
  39154. }
  39155. return this;
  39156. }
  39157. /**
  39158. * Returns a new uniforms group with copied values from this instance.
  39159. *
  39160. * @return {UniformsGroup} A clone of this instance.
  39161. */
  39162. clone() {
  39163. return new this.constructor().copy( this );
  39164. }
  39165. }
  39166. /**
  39167. * An instanced version of an interleaved buffer.
  39168. *
  39169. * @augments InterleavedBuffer
  39170. */
  39171. class InstancedInterleavedBuffer extends InterleavedBuffer {
  39172. /**
  39173. * Constructs a new instanced interleaved buffer.
  39174. *
  39175. * @param {TypedArray} array - A typed array with a shared buffer storing attribute data.
  39176. * @param {number} stride - The number of typed-array elements per vertex.
  39177. * @param {number} [meshPerAttribute=1] - Defines how often a value of this interleaved buffer should be repeated.
  39178. */
  39179. constructor( array, stride, meshPerAttribute = 1 ) {
  39180. super( array, stride );
  39181. /**
  39182. * This flag can be used for type testing.
  39183. *
  39184. * @type {boolean}
  39185. * @readonly
  39186. * @default true
  39187. */
  39188. this.isInstancedInterleavedBuffer = true;
  39189. /**
  39190. * Defines how often a value of this buffer attribute should be repeated,
  39191. * see {@link InstancedBufferAttribute#meshPerAttribute}.
  39192. *
  39193. * @type {number}
  39194. * @default 1
  39195. */
  39196. this.meshPerAttribute = meshPerAttribute;
  39197. }
  39198. copy( source ) {
  39199. super.copy( source );
  39200. this.meshPerAttribute = source.meshPerAttribute;
  39201. return this;
  39202. }
  39203. clone( data ) {
  39204. const ib = super.clone( data );
  39205. ib.meshPerAttribute = this.meshPerAttribute;
  39206. return ib;
  39207. }
  39208. toJSON( data ) {
  39209. const json = super.toJSON( data );
  39210. json.isInstancedInterleavedBuffer = true;
  39211. json.meshPerAttribute = this.meshPerAttribute;
  39212. return json;
  39213. }
  39214. }
  39215. /**
  39216. * An alternative version of a buffer attribute with more control over the VBO.
  39217. *
  39218. * The renderer does not construct a VBO for this kind of attribute. Instead, it uses
  39219. * whatever VBO is passed in constructor and can later be altered via the `buffer` property.
  39220. *
  39221. * The most common use case for this class is when some kind of GPGPU calculation interferes
  39222. * or even produces the VBOs in question.
  39223. *
  39224. * Notice that this class can only be used with {@link WebGLRenderer}.
  39225. */
  39226. class GLBufferAttribute {
  39227. /**
  39228. * Constructs a new GL buffer attribute.
  39229. *
  39230. * @param {WebGLBuffer} buffer - The native WebGL buffer.
  39231. * @param {number} type - The native data type (e.g. `gl.FLOAT`).
  39232. * @param {number} itemSize - The item size.
  39233. * @param {number} elementSize - The corresponding size (in bytes) for the given `type` parameter.
  39234. * @param {number} count - The expected number of vertices in VBO.
  39235. */
  39236. constructor( buffer, type, itemSize, elementSize, count ) {
  39237. /**
  39238. * This flag can be used for type testing.
  39239. *
  39240. * @type {boolean}
  39241. * @readonly
  39242. * @default true
  39243. */
  39244. this.isGLBufferAttribute = true;
  39245. /**
  39246. * The name of the buffer attribute.
  39247. *
  39248. * @type {string}
  39249. */
  39250. this.name = '';
  39251. /**
  39252. * The native WebGL buffer.
  39253. *
  39254. * @type {WebGLBuffer}
  39255. */
  39256. this.buffer = buffer;
  39257. /**
  39258. * The native data type.
  39259. *
  39260. * @type {number}
  39261. */
  39262. this.type = type;
  39263. /**
  39264. * The item size, see {@link BufferAttribute#itemSize}.
  39265. *
  39266. * @type {number}
  39267. */
  39268. this.itemSize = itemSize;
  39269. /**
  39270. * The corresponding size (in bytes) for the given `type` parameter.
  39271. *
  39272. * @type {number}
  39273. */
  39274. this.elementSize = elementSize;
  39275. /**
  39276. * The expected number of vertices in VBO.
  39277. *
  39278. * @type {number}
  39279. */
  39280. this.count = count;
  39281. /**
  39282. * A version number, incremented every time the `needsUpdate` is set to `true`.
  39283. *
  39284. * @type {number}
  39285. */
  39286. this.version = 0;
  39287. }
  39288. /**
  39289. * Flag to indicate that this attribute has changed and should be re-sent to
  39290. * the GPU. Set this to `true` when you modify the value of the array.
  39291. *
  39292. * @type {number}
  39293. * @default false
  39294. * @param {boolean} value
  39295. */
  39296. set needsUpdate( value ) {
  39297. if ( value === true ) this.version ++;
  39298. }
  39299. /**
  39300. * Sets the given native WebGL buffer.
  39301. *
  39302. * @param {WebGLBuffer} buffer - The buffer to set.
  39303. * @return {BufferAttribute} A reference to this instance.
  39304. */
  39305. setBuffer( buffer ) {
  39306. this.buffer = buffer;
  39307. return this;
  39308. }
  39309. /**
  39310. * Sets the given native data type and element size.
  39311. *
  39312. * @param {number} type - The native data type (e.g. `gl.FLOAT`).
  39313. * @param {number} elementSize - The corresponding size (in bytes) for the given `type` parameter.
  39314. * @return {BufferAttribute} A reference to this instance.
  39315. */
  39316. setType( type, elementSize ) {
  39317. this.type = type;
  39318. this.elementSize = elementSize;
  39319. return this;
  39320. }
  39321. /**
  39322. * Sets the item size.
  39323. *
  39324. * @param {number} itemSize - The item size.
  39325. * @return {BufferAttribute} A reference to this instance.
  39326. */
  39327. setItemSize( itemSize ) {
  39328. this.itemSize = itemSize;
  39329. return this;
  39330. }
  39331. /**
  39332. * Sets the count (the expected number of vertices in VBO).
  39333. *
  39334. * @param {number} count - The count.
  39335. * @return {BufferAttribute} A reference to this instance.
  39336. */
  39337. setCount( count ) {
  39338. this.count = count;
  39339. return this;
  39340. }
  39341. }
  39342. const _matrix = /*@__PURE__*/ new Matrix4();
  39343. /**
  39344. * This class is designed to assist with raycasting. Raycasting is used for
  39345. * mouse picking (working out what objects in the 3d space the mouse is over)
  39346. * amongst other things.
  39347. */
  39348. class Raycaster {
  39349. /**
  39350. * Constructs a new raycaster.
  39351. *
  39352. * @param {Vector3} origin - The origin vector where the ray casts from.
  39353. * @param {Vector3} direction - The (normalized) direction vector that gives direction to the ray.
  39354. * @param {number} [near=0] - All results returned are further away than near. Near can't be negative.
  39355. * @param {number} [far=Infinity] - All results returned are closer than far. Far can't be lower than near.
  39356. */
  39357. constructor( origin, direction, near = 0, far = Infinity ) {
  39358. /**
  39359. * The ray used for raycasting.
  39360. *
  39361. * @type {Ray}
  39362. */
  39363. this.ray = new Ray( origin, direction );
  39364. /**
  39365. * All results returned are further away than near. Near can't be negative.
  39366. *
  39367. * @type {number}
  39368. * @default 0
  39369. */
  39370. this.near = near;
  39371. /**
  39372. * All results returned are further away than near. Near can't be negative.
  39373. *
  39374. * @type {number}
  39375. * @default Infinity
  39376. */
  39377. this.far = far;
  39378. /**
  39379. * The camera to use when raycasting against view-dependent objects such as
  39380. * billboarded objects like sprites. This field can be set manually or
  39381. * is set when calling `setFromCamera()`.
  39382. *
  39383. * @type {?Camera}
  39384. * @default null
  39385. */
  39386. this.camera = null;
  39387. /**
  39388. * Allows to selectively ignore 3D objects when performing intersection tests.
  39389. * The following code example ensures that only 3D objects on layer `1` will be
  39390. * honored by raycaster.
  39391. * ```js
  39392. * raycaster.layers.set( 1 );
  39393. * object.layers.enable( 1 );
  39394. * ```
  39395. *
  39396. * @type {Layers}
  39397. */
  39398. this.layers = new Layers();
  39399. /**
  39400. * A parameter object that configures the raycasting. It has the structure:
  39401. *
  39402. * ```
  39403. * {
  39404. * Mesh: {},
  39405. * Line: { threshold: 1 },
  39406. * LOD: {},
  39407. * Points: { threshold: 1 },
  39408. * Sprite: {}
  39409. * }
  39410. * ```
  39411. * Where `threshold` is the precision of the raycaster when intersecting objects, in world units.
  39412. *
  39413. * @type {Object}
  39414. */
  39415. this.params = {
  39416. Mesh: {},
  39417. Line: { threshold: 1 },
  39418. LOD: {},
  39419. Points: { threshold: 1 },
  39420. Sprite: {}
  39421. };
  39422. }
  39423. /**
  39424. * Updates the ray with a new origin and direction by copying the values from the arguments.
  39425. *
  39426. * @param {Vector3} origin - The origin vector where the ray casts from.
  39427. * @param {Vector3} direction - The (normalized) direction vector that gives direction to the ray.
  39428. */
  39429. set( origin, direction ) {
  39430. // direction is assumed to be normalized (for accurate distance calculations)
  39431. this.ray.set( origin, direction );
  39432. }
  39433. /**
  39434. * Uses the given coordinates and camera to compute a new origin and direction for the internal ray.
  39435. *
  39436. * @param {Vector2} coords - 2D coordinates of the mouse, in normalized device coordinates (NDC).
  39437. * X and Y components should be between `-1` and `1`.
  39438. * @param {Camera} camera - The camera from which the ray should originate.
  39439. */
  39440. setFromCamera( coords, camera ) {
  39441. if ( camera.isPerspectiveCamera ) {
  39442. this.ray.origin.setFromMatrixPosition( camera.matrixWorld );
  39443. this.ray.direction.set( coords.x, coords.y, 0.5 ).unproject( camera ).sub( this.ray.origin ).normalize();
  39444. this.camera = camera;
  39445. } else if ( camera.isOrthographicCamera ) {
  39446. this.ray.origin.set( coords.x, coords.y, ( camera.near + camera.far ) / ( camera.near - camera.far ) ).unproject( camera ); // set origin in plane of camera
  39447. this.ray.direction.set( 0, 0, -1 ).transformDirection( camera.matrixWorld );
  39448. this.camera = camera;
  39449. } else {
  39450. console.error( 'THREE.Raycaster: Unsupported camera type: ' + camera.type );
  39451. }
  39452. }
  39453. /**
  39454. * Uses the given WebXR controller to compute a new origin and direction for the internal ray.
  39455. *
  39456. * @param {WebXRController} controller - The controller to copy the position and direction from.
  39457. * @return {Raycaster} A reference to this raycaster.
  39458. */
  39459. setFromXRController( controller ) {
  39460. _matrix.identity().extractRotation( controller.matrixWorld );
  39461. this.ray.origin.setFromMatrixPosition( controller.matrixWorld );
  39462. this.ray.direction.set( 0, 0, -1 ).applyMatrix4( _matrix );
  39463. return this;
  39464. }
  39465. /**
  39466. * The intersection point of a raycaster intersection test.
  39467. * @typedef {Object} Raycaster~Intersection
  39468. * @property {number} distance - The distance from the ray's origin to the intersection point.
  39469. * @property {number} distanceToRay - Some 3D objects e.g. {@link Points} provide the distance of the
  39470. * intersection to the nearest point on the ray. For other objects it will be `undefined`.
  39471. * @property {Vector3} point - The intersection point, in world coordinates.
  39472. * @property {Object} face - The face that has been intersected.
  39473. * @property {number} faceIndex - The face index.
  39474. * @property {Object3D} object - The 3D object that has been intersected.
  39475. * @property {Vector2} uv - U,V coordinates at point of intersection.
  39476. * @property {Vector2} uv1 - Second set of U,V coordinates at point of intersection.
  39477. * @property {Vector3} uv1 - Interpolated normal vector at point of intersection.
  39478. * @property {number} instanceId - The index number of the instance where the ray
  39479. * intersects the {@link InstancedMesh}.
  39480. */
  39481. /**
  39482. * Checks all intersection between the ray and the object with or without the
  39483. * descendants. Intersections are returned sorted by distance, closest first.
  39484. *
  39485. * `Raycaster` delegates to the `raycast()` method of the passed 3D object, when
  39486. * evaluating whether the ray intersects the object or not. This allows meshes to respond
  39487. * differently to ray casting than lines or points.
  39488. *
  39489. * Note that for meshes, faces must be pointed towards the origin of the ray in order
  39490. * to be detected; intersections of the ray passing through the back of a face will not
  39491. * be detected. To raycast against both faces of an object, you'll want to set {@link Material#side}
  39492. * to `THREE.DoubleSide`.
  39493. *
  39494. * @param {Object3D} object - The 3D object to check for intersection with the ray.
  39495. * @param {boolean} [recursive=true] - If set to `true`, it also checks all descendants.
  39496. * Otherwise it only checks intersection with the object.
  39497. * @param {Array<Raycaster~Intersection>} [intersects=[]] The target array that holds the result of the method.
  39498. * @return {Array<Raycaster~Intersection>} An array holding the intersection points.
  39499. */
  39500. intersectObject( object, recursive = true, intersects = [] ) {
  39501. intersect( object, this, intersects, recursive );
  39502. intersects.sort( ascSort );
  39503. return intersects;
  39504. }
  39505. /**
  39506. * Checks all intersection between the ray and the objects with or without
  39507. * the descendants. Intersections are returned sorted by distance, closest first.
  39508. *
  39509. * @param {Array<Object3D>} objects - The 3D objects to check for intersection with the ray.
  39510. * @param {boolean} [recursive=true] - If set to `true`, it also checks all descendants.
  39511. * Otherwise it only checks intersection with the object.
  39512. * @param {Array<Raycaster~Intersection>} [intersects=[]] The target array that holds the result of the method.
  39513. * @return {Array<Raycaster~Intersection>} An array holding the intersection points.
  39514. */
  39515. intersectObjects( objects, recursive = true, intersects = [] ) {
  39516. for ( let i = 0, l = objects.length; i < l; i ++ ) {
  39517. intersect( objects[ i ], this, intersects, recursive );
  39518. }
  39519. intersects.sort( ascSort );
  39520. return intersects;
  39521. }
  39522. }
  39523. function ascSort( a, b ) {
  39524. return a.distance - b.distance;
  39525. }
  39526. function intersect( object, raycaster, intersects, recursive ) {
  39527. let propagate = true;
  39528. if ( object.layers.test( raycaster.layers ) ) {
  39529. const result = object.raycast( raycaster, intersects );
  39530. if ( result === false ) propagate = false;
  39531. }
  39532. if ( propagate === true && recursive === true ) {
  39533. const children = object.children;
  39534. for ( let i = 0, l = children.length; i < l; i ++ ) {
  39535. intersect( children[ i ], raycaster, intersects, true );
  39536. }
  39537. }
  39538. }
  39539. /**
  39540. * This class can be used to represent points in 3D space as
  39541. * [Spherical coordinates]{@link https://en.wikipedia.org/wiki/Spherical_coordinate_system}.
  39542. */
  39543. class Spherical {
  39544. /**
  39545. * Constructs a new spherical.
  39546. *
  39547. * @param {number} [radius=1] - The radius, or the Euclidean distance (straight-line distance) from the point to the origin.
  39548. * @param {number} [phi=0] - The polar angle in radians from the y (up) axis.
  39549. * @param {number} [theta=0] - The equator/azimuthal angle in radians around the y (up) axis.
  39550. */
  39551. constructor( radius = 1, phi = 0, theta = 0 ) {
  39552. /**
  39553. * The radius, or the Euclidean distance (straight-line distance) from the point to the origin.
  39554. *
  39555. * @type {number}
  39556. * @default 1
  39557. */
  39558. this.radius = radius;
  39559. /**
  39560. * The polar angle in radians from the y (up) axis.
  39561. *
  39562. * @type {number}
  39563. * @default 0
  39564. */
  39565. this.phi = phi;
  39566. /**
  39567. * The equator/azimuthal angle in radians around the y (up) axis.
  39568. *
  39569. * @type {number}
  39570. * @default 0
  39571. */
  39572. this.theta = theta;
  39573. }
  39574. /**
  39575. * Sets the spherical components by copying the given values.
  39576. *
  39577. * @param {number} radius - The radius.
  39578. * @param {number} phi - The polar angle.
  39579. * @param {number} theta - The azimuthal angle.
  39580. * @return {Spherical} A reference to this spherical.
  39581. */
  39582. set( radius, phi, theta ) {
  39583. this.radius = radius;
  39584. this.phi = phi;
  39585. this.theta = theta;
  39586. return this;
  39587. }
  39588. /**
  39589. * Copies the values of the given spherical to this instance.
  39590. *
  39591. * @param {Spherical} other - The spherical to copy.
  39592. * @return {Spherical} A reference to this spherical.
  39593. */
  39594. copy( other ) {
  39595. this.radius = other.radius;
  39596. this.phi = other.phi;
  39597. this.theta = other.theta;
  39598. return this;
  39599. }
  39600. /**
  39601. * Restricts the polar angle [page:.phi phi] to be between `0.000001` and pi -
  39602. * `0.000001`.
  39603. *
  39604. * @return {Spherical} A reference to this spherical.
  39605. */
  39606. makeSafe() {
  39607. const EPS = 0.000001;
  39608. this.phi = clamp( this.phi, EPS, Math.PI - EPS );
  39609. return this;
  39610. }
  39611. /**
  39612. * Sets the spherical components from the given vector which is assumed to hold
  39613. * Cartesian coordinates.
  39614. *
  39615. * @param {Vector3} v - The vector to set.
  39616. * @return {Spherical} A reference to this spherical.
  39617. */
  39618. setFromVector3( v ) {
  39619. return this.setFromCartesianCoords( v.x, v.y, v.z );
  39620. }
  39621. /**
  39622. * Sets the spherical components from the given Cartesian coordinates.
  39623. *
  39624. * @param {number} x - The x value.
  39625. * @param {number} y - The x value.
  39626. * @param {number} z - The x value.
  39627. * @return {Spherical} A reference to this spherical.
  39628. */
  39629. setFromCartesianCoords( x, y, z ) {
  39630. this.radius = Math.sqrt( x * x + y * y + z * z );
  39631. if ( this.radius === 0 ) {
  39632. this.theta = 0;
  39633. this.phi = 0;
  39634. } else {
  39635. this.theta = Math.atan2( x, z );
  39636. this.phi = Math.acos( clamp( y / this.radius, -1, 1 ) );
  39637. }
  39638. return this;
  39639. }
  39640. /**
  39641. * Returns a new spherical with copied values from this instance.
  39642. *
  39643. * @return {Spherical} A clone of this instance.
  39644. */
  39645. clone() {
  39646. return new this.constructor().copy( this );
  39647. }
  39648. }
  39649. /**
  39650. * This class can be used to represent points in 3D space as
  39651. * [Cylindrical coordinates]{@link https://en.wikipedia.org/wiki/Cylindrical_coordinate_system}.
  39652. */
  39653. class Cylindrical {
  39654. /**
  39655. * Constructs a new cylindrical.
  39656. *
  39657. * @param {number} [radius=1] - The distance from the origin to a point in the x-z plane.
  39658. * @param {number} [theta=0] - A counterclockwise angle in the x-z plane measured in radians from the positive z-axis.
  39659. * @param {number} [y=0] - The height above the x-z plane.
  39660. */
  39661. constructor( radius = 1, theta = 0, y = 0 ) {
  39662. /**
  39663. * The distance from the origin to a point in the x-z plane.
  39664. *
  39665. * @type {number}
  39666. * @default 1
  39667. */
  39668. this.radius = radius;
  39669. /**
  39670. * A counterclockwise angle in the x-z plane measured in radians from the positive z-axis.
  39671. *
  39672. * @type {number}
  39673. * @default 0
  39674. */
  39675. this.theta = theta;
  39676. /**
  39677. * The height above the x-z plane.
  39678. *
  39679. * @type {number}
  39680. * @default 0
  39681. */
  39682. this.y = y;
  39683. }
  39684. /**
  39685. * Sets the cylindrical components by copying the given values.
  39686. *
  39687. * @param {number} radius - The radius.
  39688. * @param {number} theta - The theta angle.
  39689. * @param {number} y - The height value.
  39690. * @return {Cylindrical} A reference to this cylindrical.
  39691. */
  39692. set( radius, theta, y ) {
  39693. this.radius = radius;
  39694. this.theta = theta;
  39695. this.y = y;
  39696. return this;
  39697. }
  39698. /**
  39699. * Copies the values of the given cylindrical to this instance.
  39700. *
  39701. * @param {Cylindrical} other - The cylindrical to copy.
  39702. * @return {Cylindrical} A reference to this cylindrical.
  39703. */
  39704. copy( other ) {
  39705. this.radius = other.radius;
  39706. this.theta = other.theta;
  39707. this.y = other.y;
  39708. return this;
  39709. }
  39710. /**
  39711. * Sets the cylindrical components from the given vector which is assumed to hold
  39712. * Cartesian coordinates.
  39713. *
  39714. * @param {Vector3} v - The vector to set.
  39715. * @return {Cylindrical} A reference to this cylindrical.
  39716. */
  39717. setFromVector3( v ) {
  39718. return this.setFromCartesianCoords( v.x, v.y, v.z );
  39719. }
  39720. /**
  39721. * Sets the cylindrical components from the given Cartesian coordinates.
  39722. *
  39723. * @param {number} x - The x value.
  39724. * @param {number} y - The x value.
  39725. * @param {number} z - The x value.
  39726. * @return {Cylindrical} A reference to this cylindrical.
  39727. */
  39728. setFromCartesianCoords( x, y, z ) {
  39729. this.radius = Math.sqrt( x * x + z * z );
  39730. this.theta = Math.atan2( x, z );
  39731. this.y = y;
  39732. return this;
  39733. }
  39734. /**
  39735. * Returns a new cylindrical with copied values from this instance.
  39736. *
  39737. * @return {Cylindrical} A clone of this instance.
  39738. */
  39739. clone() {
  39740. return new this.constructor().copy( this );
  39741. }
  39742. }
  39743. /**
  39744. * Represents a 2x2 matrix.
  39745. *
  39746. * A Note on Row-Major and Column-Major Ordering:
  39747. *
  39748. * The constructor and {@link Matrix2#set} method take arguments in
  39749. * [row-major]{@link https://en.wikipedia.org/wiki/Row-_and_column-major_order#Column-major_order}
  39750. * order, while internally they are stored in the {@link Matrix2#elements} array in column-major order.
  39751. * This means that calling:
  39752. * ```js
  39753. * const m = new THREE.Matrix2();
  39754. * m.set( 11, 12,
  39755. * 21, 22 );
  39756. * ```
  39757. * will result in the elements array containing:
  39758. * ```js
  39759. * m.elements = [ 11, 21,
  39760. * 12, 22 ];
  39761. * ```
  39762. * and internally all calculations are performed using column-major ordering.
  39763. * However, as the actual ordering makes no difference mathematically and
  39764. * most people are used to thinking about matrices in row-major order, the
  39765. * three.js documentation shows matrices in row-major order. Just bear in
  39766. * mind that if you are reading the source code, you'll have to take the
  39767. * transpose of any matrices outlined here to make sense of the calculations.
  39768. */
  39769. class Matrix2 {
  39770. /**
  39771. * Constructs a new 2x2 matrix. The arguments are supposed to be
  39772. * in row-major order. If no arguments are provided, the constructor
  39773. * initializes the matrix as an identity matrix.
  39774. *
  39775. * @param {number} [n11] - 1-1 matrix element.
  39776. * @param {number} [n12] - 1-2 matrix element.
  39777. * @param {number} [n21] - 2-1 matrix element.
  39778. * @param {number} [n22] - 2-2 matrix element.
  39779. */
  39780. constructor( n11, n12, n21, n22 ) {
  39781. /**
  39782. * This flag can be used for type testing.
  39783. *
  39784. * @type {boolean}
  39785. * @readonly
  39786. * @default true
  39787. */
  39788. Matrix2.prototype.isMatrix2 = true;
  39789. /**
  39790. * A column-major list of matrix values.
  39791. *
  39792. * @type {Array<number>}
  39793. */
  39794. this.elements = [
  39795. 1, 0,
  39796. 0, 1,
  39797. ];
  39798. if ( n11 !== undefined ) {
  39799. this.set( n11, n12, n21, n22 );
  39800. }
  39801. }
  39802. /**
  39803. * Sets this matrix to the 2x2 identity matrix.
  39804. *
  39805. * @return {Matrix2} A reference to this matrix.
  39806. */
  39807. identity() {
  39808. this.set(
  39809. 1, 0,
  39810. 0, 1,
  39811. );
  39812. return this;
  39813. }
  39814. /**
  39815. * Sets the elements of the matrix from the given array.
  39816. *
  39817. * @param {Array<number>} array - The matrix elements in column-major order.
  39818. * @param {number} [offset=0] - Index of the first element in the array.
  39819. * @return {Matrix2} A reference to this matrix.
  39820. */
  39821. fromArray( array, offset = 0 ) {
  39822. for ( let i = 0; i < 4; i ++ ) {
  39823. this.elements[ i ] = array[ i + offset ];
  39824. }
  39825. return this;
  39826. }
  39827. /**
  39828. * Sets the elements of the matrix.The arguments are supposed to be
  39829. * in row-major order.
  39830. *
  39831. * @param {number} n11 - 1-1 matrix element.
  39832. * @param {number} n12 - 1-2 matrix element.
  39833. * @param {number} n21 - 2-1 matrix element.
  39834. * @param {number} n22 - 2-2 matrix element.
  39835. * @return {Matrix2} A reference to this matrix.
  39836. */
  39837. set( n11, n12, n21, n22 ) {
  39838. const te = this.elements;
  39839. te[ 0 ] = n11; te[ 2 ] = n12;
  39840. te[ 1 ] = n21; te[ 3 ] = n22;
  39841. return this;
  39842. }
  39843. }
  39844. const _vector$4 = /*@__PURE__*/ new Vector2();
  39845. /**
  39846. * Represents an axis-aligned bounding box (AABB) in 2D space.
  39847. */
  39848. class Box2 {
  39849. /**
  39850. * Constructs a new bounding box.
  39851. *
  39852. * @param {Vector2} [min=(Infinity,Infinity)] - A vector representing the lower boundary of the box.
  39853. * @param {Vector2} [max=(-Infinity,-Infinity)] - A vector representing the upper boundary of the box.
  39854. */
  39855. constructor( min = new Vector2( + Infinity, + Infinity ), max = new Vector2( - Infinity, - Infinity ) ) {
  39856. /**
  39857. * This flag can be used for type testing.
  39858. *
  39859. * @type {boolean}
  39860. * @readonly
  39861. * @default true
  39862. */
  39863. this.isBox2 = true;
  39864. /**
  39865. * The lower boundary of the box.
  39866. *
  39867. * @type {Vector2}
  39868. */
  39869. this.min = min;
  39870. /**
  39871. * The upper boundary of the box.
  39872. *
  39873. * @type {Vector2}
  39874. */
  39875. this.max = max;
  39876. }
  39877. /**
  39878. * Sets the lower and upper boundaries of this box.
  39879. * Please note that this method only copies the values from the given objects.
  39880. *
  39881. * @param {Vector2} min - The lower boundary of the box.
  39882. * @param {Vector2} max - The upper boundary of the box.
  39883. * @return {Box2} A reference to this bounding box.
  39884. */
  39885. set( min, max ) {
  39886. this.min.copy( min );
  39887. this.max.copy( max );
  39888. return this;
  39889. }
  39890. /**
  39891. * Sets the upper and lower bounds of this box so it encloses the position data
  39892. * in the given array.
  39893. *
  39894. * @param {Array<Vector2>} points - An array holding 2D position data as instances of {@link Vector2}.
  39895. * @return {Box2} A reference to this bounding box.
  39896. */
  39897. setFromPoints( points ) {
  39898. this.makeEmpty();
  39899. for ( let i = 0, il = points.length; i < il; i ++ ) {
  39900. this.expandByPoint( points[ i ] );
  39901. }
  39902. return this;
  39903. }
  39904. /**
  39905. * Centers this box on the given center vector and sets this box's width, height and
  39906. * depth to the given size values.
  39907. *
  39908. * @param {Vector2} center - The center of the box.
  39909. * @param {Vector2} size - The x and y dimensions of the box.
  39910. * @return {Box2} A reference to this bounding box.
  39911. */
  39912. setFromCenterAndSize( center, size ) {
  39913. const halfSize = _vector$4.copy( size ).multiplyScalar( 0.5 );
  39914. this.min.copy( center ).sub( halfSize );
  39915. this.max.copy( center ).add( halfSize );
  39916. return this;
  39917. }
  39918. /**
  39919. * Returns a new box with copied values from this instance.
  39920. *
  39921. * @return {Box2} A clone of this instance.
  39922. */
  39923. clone() {
  39924. return new this.constructor().copy( this );
  39925. }
  39926. /**
  39927. * Copies the values of the given box to this instance.
  39928. *
  39929. * @param {Box2} box - The box to copy.
  39930. * @return {Box2} A reference to this bounding box.
  39931. */
  39932. copy( box ) {
  39933. this.min.copy( box.min );
  39934. this.max.copy( box.max );
  39935. return this;
  39936. }
  39937. /**
  39938. * Makes this box empty which means in encloses a zero space in 2D.
  39939. *
  39940. * @return {Box2} A reference to this bounding box.
  39941. */
  39942. makeEmpty() {
  39943. this.min.x = this.min.y = + Infinity;
  39944. this.max.x = this.max.y = - Infinity;
  39945. return this;
  39946. }
  39947. /**
  39948. * Returns true if this box includes zero points within its bounds.
  39949. * Note that a box with equal lower and upper bounds still includes one
  39950. * point, the one both bounds share.
  39951. *
  39952. * @return {boolean} Whether this box is empty or not.
  39953. */
  39954. isEmpty() {
  39955. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  39956. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y );
  39957. }
  39958. /**
  39959. * Returns the center point of this box.
  39960. *
  39961. * @param {Vector2} target - The target vector that is used to store the method's result.
  39962. * @return {Vector2} The center point.
  39963. */
  39964. getCenter( target ) {
  39965. return this.isEmpty() ? target.set( 0, 0 ) : target.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  39966. }
  39967. /**
  39968. * Returns the dimensions of this box.
  39969. *
  39970. * @param {Vector2} target - The target vector that is used to store the method's result.
  39971. * @return {Vector2} The size.
  39972. */
  39973. getSize( target ) {
  39974. return this.isEmpty() ? target.set( 0, 0 ) : target.subVectors( this.max, this.min );
  39975. }
  39976. /**
  39977. * Expands the boundaries of this box to include the given point.
  39978. *
  39979. * @param {Vector2} point - The point that should be included by the bounding box.
  39980. * @return {Box2} A reference to this bounding box.
  39981. */
  39982. expandByPoint( point ) {
  39983. this.min.min( point );
  39984. this.max.max( point );
  39985. return this;
  39986. }
  39987. /**
  39988. * Expands this box equilaterally by the given vector. The width of this
  39989. * box will be expanded by the x component of the vector in both
  39990. * directions. The height of this box will be expanded by the y component of
  39991. * the vector in both directions.
  39992. *
  39993. * @param {Vector2} vector - The vector that should expand the bounding box.
  39994. * @return {Box2} A reference to this bounding box.
  39995. */
  39996. expandByVector( vector ) {
  39997. this.min.sub( vector );
  39998. this.max.add( vector );
  39999. return this;
  40000. }
  40001. /**
  40002. * Expands each dimension of the box by the given scalar. If negative, the
  40003. * dimensions of the box will be contracted.
  40004. *
  40005. * @param {number} scalar - The scalar value that should expand the bounding box.
  40006. * @return {Box2} A reference to this bounding box.
  40007. */
  40008. expandByScalar( scalar ) {
  40009. this.min.addScalar( - scalar );
  40010. this.max.addScalar( scalar );
  40011. return this;
  40012. }
  40013. /**
  40014. * Returns `true` if the given point lies within or on the boundaries of this box.
  40015. *
  40016. * @param {Vector2} point - The point to test.
  40017. * @return {boolean} Whether the bounding box contains the given point or not.
  40018. */
  40019. containsPoint( point ) {
  40020. return point.x >= this.min.x && point.x <= this.max.x &&
  40021. point.y >= this.min.y && point.y <= this.max.y;
  40022. }
  40023. /**
  40024. * Returns `true` if this bounding box includes the entirety of the given bounding box.
  40025. * If this box and the given one are identical, this function also returns `true`.
  40026. *
  40027. * @param {Box2} box - The bounding box to test.
  40028. * @return {boolean} Whether the bounding box contains the given bounding box or not.
  40029. */
  40030. containsBox( box ) {
  40031. return this.min.x <= box.min.x && box.max.x <= this.max.x &&
  40032. this.min.y <= box.min.y && box.max.y <= this.max.y;
  40033. }
  40034. /**
  40035. * Returns a point as a proportion of this box's width and height.
  40036. *
  40037. * @param {Vector2} point - A point in 2D space.
  40038. * @param {Vector2} target - The target vector that is used to store the method's result.
  40039. * @return {Vector2} A point as a proportion of this box's width and height.
  40040. */
  40041. getParameter( point, target ) {
  40042. // This can potentially have a divide by zero if the box
  40043. // has a size dimension of 0.
  40044. return target.set(
  40045. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  40046. ( point.y - this.min.y ) / ( this.max.y - this.min.y )
  40047. );
  40048. }
  40049. /**
  40050. * Returns `true` if the given bounding box intersects with this bounding box.
  40051. *
  40052. * @param {Box2} box - The bounding box to test.
  40053. * @return {boolean} Whether the given bounding box intersects with this bounding box.
  40054. */
  40055. intersectsBox( box ) {
  40056. // using 4 splitting planes to rule out intersections
  40057. return box.max.x >= this.min.x && box.min.x <= this.max.x &&
  40058. box.max.y >= this.min.y && box.min.y <= this.max.y;
  40059. }
  40060. /**
  40061. * Clamps the given point within the bounds of this box.
  40062. *
  40063. * @param {Vector2} point - The point to clamp.
  40064. * @param {Vector2} target - The target vector that is used to store the method's result.
  40065. * @return {Vector2} The clamped point.
  40066. */
  40067. clampPoint( point, target ) {
  40068. return target.copy( point ).clamp( this.min, this.max );
  40069. }
  40070. /**
  40071. * Returns the euclidean distance from any edge of this box to the specified point. If
  40072. * the given point lies inside of this box, the distance will be `0`.
  40073. *
  40074. * @param {Vector2} point - The point to compute the distance to.
  40075. * @return {number} The euclidean distance.
  40076. */
  40077. distanceToPoint( point ) {
  40078. return this.clampPoint( point, _vector$4 ).distanceTo( point );
  40079. }
  40080. /**
  40081. * Computes the intersection of this bounding box and the given one, setting the upper
  40082. * bound of this box to the lesser of the two boxes' upper bounds and the
  40083. * lower bound of this box to the greater of the two boxes' lower bounds. If
  40084. * there's no overlap, makes this box empty.
  40085. *
  40086. * @param {Box2} box - The bounding box to intersect with.
  40087. * @return {Box2} A reference to this bounding box.
  40088. */
  40089. intersect( box ) {
  40090. this.min.max( box.min );
  40091. this.max.min( box.max );
  40092. if ( this.isEmpty() ) this.makeEmpty();
  40093. return this;
  40094. }
  40095. /**
  40096. * Computes the union of this box and another and the given one, setting the upper
  40097. * bound of this box to the greater of the two boxes' upper bounds and the
  40098. * lower bound of this box to the lesser of the two boxes' lower bounds.
  40099. *
  40100. * @param {Box2} box - The bounding box that will be unioned with this instance.
  40101. * @return {Box2} A reference to this bounding box.
  40102. */
  40103. union( box ) {
  40104. this.min.min( box.min );
  40105. this.max.max( box.max );
  40106. return this;
  40107. }
  40108. /**
  40109. * Adds the given offset to both the upper and lower bounds of this bounding box,
  40110. * effectively moving it in 2D space.
  40111. *
  40112. * @param {Vector2} offset - The offset that should be used to translate the bounding box.
  40113. * @return {Box2} A reference to this bounding box.
  40114. */
  40115. translate( offset ) {
  40116. this.min.add( offset );
  40117. this.max.add( offset );
  40118. return this;
  40119. }
  40120. /**
  40121. * Returns `true` if this bounding box is equal with the given one.
  40122. *
  40123. * @param {Box2} box - The box to test for equality.
  40124. * @return {boolean} Whether this bounding box is equal with the given one.
  40125. */
  40126. equals( box ) {
  40127. return box.min.equals( this.min ) && box.max.equals( this.max );
  40128. }
  40129. }
  40130. const _startP = /*@__PURE__*/ new Vector3();
  40131. const _startEnd = /*@__PURE__*/ new Vector3();
  40132. /**
  40133. * An analytical line segment in 3D space represented by a start and end point.
  40134. */
  40135. class Line3 {
  40136. /**
  40137. * Constructs a new line segment.
  40138. *
  40139. * @param {Vector3} [start=(0,0,0)] - Start of the line segment.
  40140. * @param {Vector3} [end=(0,0,0)] - End of the line segment.
  40141. */
  40142. constructor( start = new Vector3(), end = new Vector3() ) {
  40143. /**
  40144. * Start of the line segment.
  40145. *
  40146. * @type {Vector3}
  40147. */
  40148. this.start = start;
  40149. /**
  40150. * End of the line segment.
  40151. *
  40152. * @type {Vector3}
  40153. */
  40154. this.end = end;
  40155. }
  40156. /**
  40157. * Sets the start and end values by copying the given vectors.
  40158. *
  40159. * @param {Vector3} start - The start point.
  40160. * @param {Vector3} end - The end point.
  40161. * @return {Line3} A reference to this line segment.
  40162. */
  40163. set( start, end ) {
  40164. this.start.copy( start );
  40165. this.end.copy( end );
  40166. return this;
  40167. }
  40168. /**
  40169. * Copies the values of the given line segment to this instance.
  40170. *
  40171. * @param {Line3} line - The line segment to copy.
  40172. * @return {Line3} A reference to this line segment.
  40173. */
  40174. copy( line ) {
  40175. this.start.copy( line.start );
  40176. this.end.copy( line.end );
  40177. return this;
  40178. }
  40179. /**
  40180. * Returns the center of the line segment.
  40181. *
  40182. * @param {Vector3} target - The target vector that is used to store the method's result.
  40183. * @return {Vector3} The center point.
  40184. */
  40185. getCenter( target ) {
  40186. return target.addVectors( this.start, this.end ).multiplyScalar( 0.5 );
  40187. }
  40188. /**
  40189. * Returns the delta vector of the line segment's start and end point.
  40190. *
  40191. * @param {Vector3} target - The target vector that is used to store the method's result.
  40192. * @return {Vector3} The delta vector.
  40193. */
  40194. delta( target ) {
  40195. return target.subVectors( this.end, this.start );
  40196. }
  40197. /**
  40198. * Returns the squared Euclidean distance between the line' start and end point.
  40199. *
  40200. * @return {number} The squared Euclidean distance.
  40201. */
  40202. distanceSq() {
  40203. return this.start.distanceToSquared( this.end );
  40204. }
  40205. /**
  40206. * Returns the Euclidean distance between the line' start and end point.
  40207. *
  40208. * @return {number} The Euclidean distance.
  40209. */
  40210. distance() {
  40211. return this.start.distanceTo( this.end );
  40212. }
  40213. /**
  40214. * Returns a vector at a certain position along the line segment.
  40215. *
  40216. * @param {number} t - A value between `[0,1]` to represent a position along the line segment.
  40217. * @param {Vector3} target - The target vector that is used to store the method's result.
  40218. * @return {Vector3} The delta vector.
  40219. */
  40220. at( t, target ) {
  40221. return this.delta( target ).multiplyScalar( t ).add( this.start );
  40222. }
  40223. /**
  40224. * Returns a point parameter based on the closest point as projected on the line segment.
  40225. *
  40226. * @param {Vector3} point - The point for which to return a point parameter.
  40227. * @param {boolean} clampToLine - Whether to clamp the result to the range `[0,1]` or not.
  40228. * @return {number} The point parameter.
  40229. */
  40230. closestPointToPointParameter( point, clampToLine ) {
  40231. _startP.subVectors( point, this.start );
  40232. _startEnd.subVectors( this.end, this.start );
  40233. const startEnd2 = _startEnd.dot( _startEnd );
  40234. const startEnd_startP = _startEnd.dot( _startP );
  40235. let t = startEnd_startP / startEnd2;
  40236. if ( clampToLine ) {
  40237. t = clamp( t, 0, 1 );
  40238. }
  40239. return t;
  40240. }
  40241. /**
  40242. * Returns the closets point on the line for a given point.
  40243. *
  40244. * @param {Vector3} point - The point to compute the closest point on the line for.
  40245. * @param {boolean} clampToLine - Whether to clamp the result to the range `[0,1]` or not.
  40246. * @param {Vector3} target - The target vector that is used to store the method's result.
  40247. * @return {Vector3} The closest point on the line.
  40248. */
  40249. closestPointToPoint( point, clampToLine, target ) {
  40250. const t = this.closestPointToPointParameter( point, clampToLine );
  40251. return this.delta( target ).multiplyScalar( t ).add( this.start );
  40252. }
  40253. /**
  40254. * Applies a 4x4 transformation matrix to this line segment.
  40255. *
  40256. * @param {Matrix4} matrix - The transformation matrix.
  40257. * @return {Line3} A reference to this line segment.
  40258. */
  40259. applyMatrix4( matrix ) {
  40260. this.start.applyMatrix4( matrix );
  40261. this.end.applyMatrix4( matrix );
  40262. return this;
  40263. }
  40264. /**
  40265. * Returns `true` if this line segment is equal with the given one.
  40266. *
  40267. * @param {Line3} line - The line segment to test for equality.
  40268. * @return {boolean} Whether this line segment is equal with the given one.
  40269. */
  40270. equals( line ) {
  40271. return line.start.equals( this.start ) && line.end.equals( this.end );
  40272. }
  40273. /**
  40274. * Returns a new line segment with copied values from this instance.
  40275. *
  40276. * @return {Line3} A clone of this instance.
  40277. */
  40278. clone() {
  40279. return new this.constructor().copy( this );
  40280. }
  40281. }
  40282. const _vector$3 = /*@__PURE__*/ new Vector3();
  40283. /**
  40284. * This displays a cone shaped helper object for a {@link SpotLight}.
  40285. *
  40286. * ```js
  40287. * const spotLight = new THREE.SpotLight( 0xffffff );
  40288. * spotLight.position.set( 10, 10, 10 );
  40289. * scene.add( spotLight );
  40290. *
  40291. * const spotLightHelper = new THREE.SpotLightHelper( spotLight );
  40292. * scene.add( spotLightHelper );
  40293. * ```
  40294. *
  40295. * @augments Object3D
  40296. */
  40297. class SpotLightHelper extends Object3D {
  40298. /**
  40299. * Constructs a new spot light helper.
  40300. *
  40301. * @param {HemisphereLight} light - The light to be visualized.
  40302. * @param {number|Color|string} [color] - The helper's color. If not set, the helper will take
  40303. * the color of the light.
  40304. */
  40305. constructor( light, color ) {
  40306. super();
  40307. /**
  40308. * The light being visualized.
  40309. *
  40310. * @type {SpotLight}
  40311. */
  40312. this.light = light;
  40313. this.matrixAutoUpdate = false;
  40314. /**
  40315. * The color parameter passed in the constructor.
  40316. * If not set, the helper will take the color of the light.
  40317. *
  40318. * @type {number|Color|string}
  40319. */
  40320. this.color = color;
  40321. this.type = 'SpotLightHelper';
  40322. const geometry = new BufferGeometry();
  40323. const positions = [
  40324. 0, 0, 0, 0, 0, 1,
  40325. 0, 0, 0, 1, 0, 1,
  40326. 0, 0, 0, -1, 0, 1,
  40327. 0, 0, 0, 0, 1, 1,
  40328. 0, 0, 0, 0, -1, 1
  40329. ];
  40330. for ( let i = 0, j = 1, l = 32; i < l; i ++, j ++ ) {
  40331. const p1 = ( i / l ) * Math.PI * 2;
  40332. const p2 = ( j / l ) * Math.PI * 2;
  40333. positions.push(
  40334. Math.cos( p1 ), Math.sin( p1 ), 1,
  40335. Math.cos( p2 ), Math.sin( p2 ), 1
  40336. );
  40337. }
  40338. geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  40339. const material = new LineBasicMaterial( { fog: false, toneMapped: false } );
  40340. this.cone = new LineSegments( geometry, material );
  40341. this.add( this.cone );
  40342. this.update();
  40343. }
  40344. /**
  40345. * Frees the GPU-related resources allocated by this instance. Call this
  40346. * method whenever this instance is no longer used in your app.
  40347. */
  40348. dispose() {
  40349. this.cone.geometry.dispose();
  40350. this.cone.material.dispose();
  40351. }
  40352. /**
  40353. * Updates the helper to match the position and direction of the
  40354. * light being visualized.
  40355. */
  40356. update() {
  40357. this.light.updateWorldMatrix( true, false );
  40358. this.light.target.updateWorldMatrix( true, false );
  40359. // update the local matrix based on the parent and light target transforms
  40360. if ( this.parent ) {
  40361. this.parent.updateWorldMatrix( true );
  40362. this.matrix
  40363. .copy( this.parent.matrixWorld )
  40364. .invert()
  40365. .multiply( this.light.matrixWorld );
  40366. } else {
  40367. this.matrix.copy( this.light.matrixWorld );
  40368. }
  40369. this.matrixWorld.copy( this.light.matrixWorld );
  40370. const coneLength = this.light.distance ? this.light.distance : 1000;
  40371. const coneWidth = coneLength * Math.tan( this.light.angle );
  40372. this.cone.scale.set( coneWidth, coneWidth, coneLength );
  40373. _vector$3.setFromMatrixPosition( this.light.target.matrixWorld );
  40374. this.cone.lookAt( _vector$3 );
  40375. if ( this.color !== undefined ) {
  40376. this.cone.material.color.set( this.color );
  40377. } else {
  40378. this.cone.material.color.copy( this.light.color );
  40379. }
  40380. }
  40381. }
  40382. const _vector$2 = /*@__PURE__*/ new Vector3();
  40383. const _boneMatrix = /*@__PURE__*/ new Matrix4();
  40384. const _matrixWorldInv = /*@__PURE__*/ new Matrix4();
  40385. /**
  40386. * A helper object to assist with visualizing a {@link Skeleton}.
  40387. *
  40388. * ```js
  40389. * const helper = new THREE.SkeletonHelper( skinnedMesh );
  40390. * scene.add( helper );
  40391. * ```
  40392. *
  40393. * @augments LineSegments
  40394. */
  40395. class SkeletonHelper extends LineSegments {
  40396. /**
  40397. * Constructs a new hemisphere light helper.
  40398. *
  40399. * @param {Object3D} object - Usually an instance of {@link SkinnedMesh}. However, any 3D object
  40400. * can be used if it represents a hierarchy of bones (see {@link Bone}).
  40401. */
  40402. constructor( object ) {
  40403. const bones = getBoneList( object );
  40404. const geometry = new BufferGeometry();
  40405. const vertices = [];
  40406. const colors = [];
  40407. const color1 = new Color( 0, 0, 1 );
  40408. const color2 = new Color( 0, 1, 0 );
  40409. for ( let i = 0; i < bones.length; i ++ ) {
  40410. const bone = bones[ i ];
  40411. if ( bone.parent && bone.parent.isBone ) {
  40412. vertices.push( 0, 0, 0 );
  40413. vertices.push( 0, 0, 0 );
  40414. colors.push( color1.r, color1.g, color1.b );
  40415. colors.push( color2.r, color2.g, color2.b );
  40416. }
  40417. }
  40418. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  40419. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  40420. const material = new LineBasicMaterial( { vertexColors: true, depthTest: false, depthWrite: false, toneMapped: false, transparent: true } );
  40421. super( geometry, material );
  40422. /**
  40423. * This flag can be used for type testing.
  40424. *
  40425. * @type {boolean}
  40426. * @readonly
  40427. * @default true
  40428. */
  40429. this.isSkeletonHelper = true;
  40430. this.type = 'SkeletonHelper';
  40431. /**
  40432. * The object being visualized.
  40433. *
  40434. * @type {Object3D}
  40435. */
  40436. this.root = object;
  40437. /**
  40438. * The list of bones that the helper visualizes.
  40439. *
  40440. * @type {Array<Bone>}
  40441. */
  40442. this.bones = bones;
  40443. this.matrix = object.matrixWorld;
  40444. this.matrixAutoUpdate = false;
  40445. }
  40446. updateMatrixWorld( force ) {
  40447. const bones = this.bones;
  40448. const geometry = this.geometry;
  40449. const position = geometry.getAttribute( 'position' );
  40450. _matrixWorldInv.copy( this.root.matrixWorld ).invert();
  40451. for ( let i = 0, j = 0; i < bones.length; i ++ ) {
  40452. const bone = bones[ i ];
  40453. if ( bone.parent && bone.parent.isBone ) {
  40454. _boneMatrix.multiplyMatrices( _matrixWorldInv, bone.matrixWorld );
  40455. _vector$2.setFromMatrixPosition( _boneMatrix );
  40456. position.setXYZ( j, _vector$2.x, _vector$2.y, _vector$2.z );
  40457. _boneMatrix.multiplyMatrices( _matrixWorldInv, bone.parent.matrixWorld );
  40458. _vector$2.setFromMatrixPosition( _boneMatrix );
  40459. position.setXYZ( j + 1, _vector$2.x, _vector$2.y, _vector$2.z );
  40460. j += 2;
  40461. }
  40462. }
  40463. geometry.getAttribute( 'position' ).needsUpdate = true;
  40464. super.updateMatrixWorld( force );
  40465. }
  40466. /**
  40467. * Frees the GPU-related resources allocated by this instance. Call this
  40468. * method whenever this instance is no longer used in your app.
  40469. */
  40470. dispose() {
  40471. this.geometry.dispose();
  40472. this.material.dispose();
  40473. }
  40474. }
  40475. function getBoneList( object ) {
  40476. const boneList = [];
  40477. if ( object.isBone === true ) {
  40478. boneList.push( object );
  40479. }
  40480. for ( let i = 0; i < object.children.length; i ++ ) {
  40481. boneList.push( ...getBoneList( object.children[ i ] ) );
  40482. }
  40483. return boneList;
  40484. }
  40485. /**
  40486. * This displays a helper object consisting of a spherical mesh for
  40487. * visualizing an instance of {@link PointLight}.
  40488. *
  40489. * ```js
  40490. * const pointLight = new THREE.PointLight( 0xff0000, 1, 100 );
  40491. * pointLight.position.set( 10, 10, 10 );
  40492. * scene.add( pointLight );
  40493. *
  40494. * const sphereSize = 1;
  40495. * const pointLightHelper = new THREE.PointLightHelper( pointLight, sphereSize );
  40496. * scene.add( pointLightHelper );
  40497. * ```
  40498. *
  40499. * @augments Mesh
  40500. */
  40501. class PointLightHelper extends Mesh {
  40502. /**
  40503. * Constructs a new point light helper.
  40504. *
  40505. * @param {PointLight} light - The light to be visualized.
  40506. * @param {number} [sphereSize=1] - The size of the sphere helper.
  40507. * @param {number|Color|string} [color] - The helper's color. If not set, the helper will take
  40508. * the color of the light.
  40509. */
  40510. constructor( light, sphereSize, color ) {
  40511. const geometry = new SphereGeometry( sphereSize, 4, 2 );
  40512. const material = new MeshBasicMaterial( { wireframe: true, fog: false, toneMapped: false } );
  40513. super( geometry, material );
  40514. /**
  40515. * The light being visualized.
  40516. *
  40517. * @type {HemisphereLight}
  40518. */
  40519. this.light = light;
  40520. /**
  40521. * The color parameter passed in the constructor.
  40522. * If not set, the helper will take the color of the light.
  40523. *
  40524. * @type {number|Color|string}
  40525. */
  40526. this.color = color;
  40527. this.type = 'PointLightHelper';
  40528. this.matrix = this.light.matrixWorld;
  40529. this.matrixAutoUpdate = false;
  40530. this.update();
  40531. /*
  40532. // TODO: delete this comment?
  40533. const distanceGeometry = new THREE.IcosahedronGeometry( 1, 2 );
  40534. const distanceMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false, wireframe: true, opacity: 0.1, transparent: true } );
  40535. this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial );
  40536. this.lightDistance = new THREE.Mesh( distanceGeometry, distanceMaterial );
  40537. const d = light.distance;
  40538. if ( d === 0.0 ) {
  40539. this.lightDistance.visible = false;
  40540. } else {
  40541. this.lightDistance.scale.set( d, d, d );
  40542. }
  40543. this.add( this.lightDistance );
  40544. */
  40545. }
  40546. /**
  40547. * Frees the GPU-related resources allocated by this instance. Call this
  40548. * method whenever this instance is no longer used in your app.
  40549. */
  40550. dispose() {
  40551. this.geometry.dispose();
  40552. this.material.dispose();
  40553. }
  40554. /**
  40555. * Updates the helper to match the position of the
  40556. * light being visualized.
  40557. */
  40558. update() {
  40559. this.light.updateWorldMatrix( true, false );
  40560. if ( this.color !== undefined ) {
  40561. this.material.color.set( this.color );
  40562. } else {
  40563. this.material.color.copy( this.light.color );
  40564. }
  40565. /*
  40566. const d = this.light.distance;
  40567. if ( d === 0.0 ) {
  40568. this.lightDistance.visible = false;
  40569. } else {
  40570. this.lightDistance.visible = true;
  40571. this.lightDistance.scale.set( d, d, d );
  40572. }
  40573. */
  40574. }
  40575. }
  40576. const _vector$1 = /*@__PURE__*/ new Vector3();
  40577. const _color1 = /*@__PURE__*/ new Color();
  40578. const _color2 = /*@__PURE__*/ new Color();
  40579. /**
  40580. * Creates a visual aid consisting of a spherical mesh for a
  40581. * given {@link HemisphereLight}.
  40582. *
  40583. * ```js
  40584. * const light = new THREE.HemisphereLight( 0xffffbb, 0x080820, 1 );
  40585. * const helper = new THREE.HemisphereLightHelper( light, 5 );
  40586. * scene.add( helper );
  40587. * ```
  40588. *
  40589. * @augments Object3D
  40590. */
  40591. class HemisphereLightHelper extends Object3D {
  40592. /**
  40593. * Constructs a new hemisphere light helper.
  40594. *
  40595. * @param {HemisphereLight} light - The light to be visualized.
  40596. * @param {number} [size=1] - The size of the mesh used to visualize the light.
  40597. * @param {number|Color|string} [color] - The helper's color. If not set, the helper will take
  40598. * the color of the light.
  40599. */
  40600. constructor( light, size, color ) {
  40601. super();
  40602. /**
  40603. * The light being visualized.
  40604. *
  40605. * @type {HemisphereLight}
  40606. */
  40607. this.light = light;
  40608. this.matrix = light.matrixWorld;
  40609. this.matrixAutoUpdate = false;
  40610. /**
  40611. * The color parameter passed in the constructor.
  40612. * If not set, the helper will take the color of the light.
  40613. *
  40614. * @type {number|Color|string}
  40615. */
  40616. this.color = color;
  40617. this.type = 'HemisphereLightHelper';
  40618. const geometry = new OctahedronGeometry( size );
  40619. geometry.rotateY( Math.PI * 0.5 );
  40620. this.material = new MeshBasicMaterial( { wireframe: true, fog: false, toneMapped: false } );
  40621. if ( this.color === undefined ) this.material.vertexColors = true;
  40622. const position = geometry.getAttribute( 'position' );
  40623. const colors = new Float32Array( position.count * 3 );
  40624. geometry.setAttribute( 'color', new BufferAttribute( colors, 3 ) );
  40625. this.add( new Mesh( geometry, this.material ) );
  40626. this.update();
  40627. }
  40628. /**
  40629. * Frees the GPU-related resources allocated by this instance. Call this
  40630. * method whenever this instance is no longer used in your app.
  40631. */
  40632. dispose() {
  40633. this.children[ 0 ].geometry.dispose();
  40634. this.children[ 0 ].material.dispose();
  40635. }
  40636. /**
  40637. * Updates the helper to match the position and direction of the
  40638. * light being visualized.
  40639. */
  40640. update() {
  40641. const mesh = this.children[ 0 ];
  40642. if ( this.color !== undefined ) {
  40643. this.material.color.set( this.color );
  40644. } else {
  40645. const colors = mesh.geometry.getAttribute( 'color' );
  40646. _color1.copy( this.light.color );
  40647. _color2.copy( this.light.groundColor );
  40648. for ( let i = 0, l = colors.count; i < l; i ++ ) {
  40649. const color = ( i < ( l / 2 ) ) ? _color1 : _color2;
  40650. colors.setXYZ( i, color.r, color.g, color.b );
  40651. }
  40652. colors.needsUpdate = true;
  40653. }
  40654. this.light.updateWorldMatrix( true, false );
  40655. mesh.lookAt( _vector$1.setFromMatrixPosition( this.light.matrixWorld ).negate() );
  40656. }
  40657. }
  40658. /**
  40659. * The helper is an object to define grids. Grids are two-dimensional
  40660. * arrays of lines.
  40661. *
  40662. * ```js
  40663. * const size = 10;
  40664. * const divisions = 10;
  40665. *
  40666. * const gridHelper = new THREE.GridHelper( size, divisions );
  40667. * scene.add( gridHelper );
  40668. * ```
  40669. *
  40670. * @augments LineSegments
  40671. */
  40672. class GridHelper extends LineSegments {
  40673. /**
  40674. * Constructs a new grid helper.
  40675. *
  40676. * @param {number} [size=10] - The size of the grid.
  40677. * @param {number} [divisions=10] - The number of divisions across the grid.
  40678. * @param {number|Color|string} [color1=0x444444] - The color of the center line.
  40679. * @param {number|Color|string} [color2=0x888888] - The color of the lines of the grid.
  40680. */
  40681. constructor( size = 10, divisions = 10, color1 = 0x444444, color2 = 0x888888 ) {
  40682. color1 = new Color( color1 );
  40683. color2 = new Color( color2 );
  40684. const center = divisions / 2;
  40685. const step = size / divisions;
  40686. const halfSize = size / 2;
  40687. const vertices = [], colors = [];
  40688. for ( let i = 0, j = 0, k = - halfSize; i <= divisions; i ++, k += step ) {
  40689. vertices.push( - halfSize, 0, k, halfSize, 0, k );
  40690. vertices.push( k, 0, - halfSize, k, 0, halfSize );
  40691. const color = i === center ? color1 : color2;
  40692. color.toArray( colors, j ); j += 3;
  40693. color.toArray( colors, j ); j += 3;
  40694. color.toArray( colors, j ); j += 3;
  40695. color.toArray( colors, j ); j += 3;
  40696. }
  40697. const geometry = new BufferGeometry();
  40698. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  40699. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  40700. const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
  40701. super( geometry, material );
  40702. this.type = 'GridHelper';
  40703. }
  40704. /**
  40705. * Frees the GPU-related resources allocated by this instance. Call this
  40706. * method whenever this instance is no longer used in your app.
  40707. */
  40708. dispose() {
  40709. this.geometry.dispose();
  40710. this.material.dispose();
  40711. }
  40712. }
  40713. /**
  40714. * This helper is an object to define polar grids. Grids are
  40715. * two-dimensional arrays of lines.
  40716. *
  40717. * ```js
  40718. * const radius = 10;
  40719. * const sectors = 16;
  40720. * const rings = 8;
  40721. * const divisions = 64;
  40722. *
  40723. * const helper = new THREE.PolarGridHelper( radius, sectors, rings, divisions );
  40724. * scene.add( helper );
  40725. * ```
  40726. *
  40727. * @augments LineSegments
  40728. */
  40729. class PolarGridHelper extends LineSegments {
  40730. /**
  40731. * Constructs a new polar grid helper.
  40732. *
  40733. * @param {number} [radius=10] - The radius of the polar grid. This can be any positive number.
  40734. * @param {number} [sectors=16] - The number of sectors the grid will be divided into. This can be any positive integer.
  40735. * @param {number} [rings=16] - The number of rings. This can be any positive integer.
  40736. * @param {number} [divisions=64] - The number of line segments used for each circle. This can be any positive integer.
  40737. * @param {number|Color|string} [color1=0x444444] - The first color used for grid elements.
  40738. * @param {number|Color|string} [color2=0x888888] - The second color used for grid elements.
  40739. */
  40740. constructor( radius = 10, sectors = 16, rings = 8, divisions = 64, color1 = 0x444444, color2 = 0x888888 ) {
  40741. color1 = new Color( color1 );
  40742. color2 = new Color( color2 );
  40743. const vertices = [];
  40744. const colors = [];
  40745. // create the sectors
  40746. if ( sectors > 1 ) {
  40747. for ( let i = 0; i < sectors; i ++ ) {
  40748. const v = ( i / sectors ) * ( Math.PI * 2 );
  40749. const x = Math.sin( v ) * radius;
  40750. const z = Math.cos( v ) * radius;
  40751. vertices.push( 0, 0, 0 );
  40752. vertices.push( x, 0, z );
  40753. const color = ( i & 1 ) ? color1 : color2;
  40754. colors.push( color.r, color.g, color.b );
  40755. colors.push( color.r, color.g, color.b );
  40756. }
  40757. }
  40758. // create the rings
  40759. for ( let i = 0; i < rings; i ++ ) {
  40760. const color = ( i & 1 ) ? color1 : color2;
  40761. const r = radius - ( radius / rings * i );
  40762. for ( let j = 0; j < divisions; j ++ ) {
  40763. // first vertex
  40764. let v = ( j / divisions ) * ( Math.PI * 2 );
  40765. let x = Math.sin( v ) * r;
  40766. let z = Math.cos( v ) * r;
  40767. vertices.push( x, 0, z );
  40768. colors.push( color.r, color.g, color.b );
  40769. // second vertex
  40770. v = ( ( j + 1 ) / divisions ) * ( Math.PI * 2 );
  40771. x = Math.sin( v ) * r;
  40772. z = Math.cos( v ) * r;
  40773. vertices.push( x, 0, z );
  40774. colors.push( color.r, color.g, color.b );
  40775. }
  40776. }
  40777. const geometry = new BufferGeometry();
  40778. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  40779. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  40780. const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
  40781. super( geometry, material );
  40782. this.type = 'PolarGridHelper';
  40783. }
  40784. /**
  40785. * Frees the GPU-related resources allocated by this instance. Call this
  40786. * method whenever this instance is no longer used in your app.
  40787. */
  40788. dispose() {
  40789. this.geometry.dispose();
  40790. this.material.dispose();
  40791. }
  40792. }
  40793. const _v1 = /*@__PURE__*/ new Vector3();
  40794. const _v2 = /*@__PURE__*/ new Vector3();
  40795. const _v3 = /*@__PURE__*/ new Vector3();
  40796. /**
  40797. * Helper object to assist with visualizing a {@link DirectionalLight}'s
  40798. * effect on the scene. This consists of plane and a line representing the
  40799. * light's position and direction.
  40800. *
  40801. * ```js
  40802. * const light = new THREE.DirectionalLight( 0xFFFFFF );
  40803. * scene.add( light );
  40804. *
  40805. * const helper = new THREE.DirectionalLightHelper( light, 5 );
  40806. * scene.add( helper );
  40807. * ```
  40808. *
  40809. * @augments Object3D
  40810. */
  40811. class DirectionalLightHelper extends Object3D {
  40812. /**
  40813. * Constructs a new directional light helper.
  40814. *
  40815. * @param {DirectionalLight} light - The light to be visualized.
  40816. * @param {number} [size=1] - The dimensions of the plane.
  40817. * @param {number|Color|string} [color] - The helper's color. If not set, the helper will take
  40818. * the color of the light.
  40819. */
  40820. constructor( light, size, color ) {
  40821. super();
  40822. /**
  40823. * The light being visualized.
  40824. *
  40825. * @type {DirectionalLight}
  40826. */
  40827. this.light = light;
  40828. this.matrix = light.matrixWorld;
  40829. this.matrixAutoUpdate = false;
  40830. /**
  40831. * The color parameter passed in the constructor.
  40832. * If not set, the helper will take the color of the light.
  40833. *
  40834. * @type {number|Color|string}
  40835. */
  40836. this.color = color;
  40837. this.type = 'DirectionalLightHelper';
  40838. if ( size === undefined ) size = 1;
  40839. let geometry = new BufferGeometry();
  40840. geometry.setAttribute( 'position', new Float32BufferAttribute( [
  40841. - size, size, 0,
  40842. size, size, 0,
  40843. size, - size, 0,
  40844. - size, - size, 0,
  40845. - size, size, 0
  40846. ], 3 ) );
  40847. const material = new LineBasicMaterial( { fog: false, toneMapped: false } );
  40848. /**
  40849. * Contains the line showing the location of the directional light.
  40850. *
  40851. * @type {Line}
  40852. */
  40853. this.lightPlane = new Line( geometry, material );
  40854. this.add( this.lightPlane );
  40855. geometry = new BufferGeometry();
  40856. geometry.setAttribute( 'position', new Float32BufferAttribute( [ 0, 0, 0, 0, 0, 1 ], 3 ) );
  40857. /**
  40858. * Represents the target line of the directional light.
  40859. *
  40860. * @type {Line}
  40861. */
  40862. this.targetLine = new Line( geometry, material );
  40863. this.add( this.targetLine );
  40864. this.update();
  40865. }
  40866. /**
  40867. * Frees the GPU-related resources allocated by this instance. Call this
  40868. * method whenever this instance is no longer used in your app.
  40869. */
  40870. dispose() {
  40871. this.lightPlane.geometry.dispose();
  40872. this.lightPlane.material.dispose();
  40873. this.targetLine.geometry.dispose();
  40874. this.targetLine.material.dispose();
  40875. }
  40876. /**
  40877. * Updates the helper to match the position and direction of the
  40878. * light being visualized.
  40879. */
  40880. update() {
  40881. this.light.updateWorldMatrix( true, false );
  40882. this.light.target.updateWorldMatrix( true, false );
  40883. _v1.setFromMatrixPosition( this.light.matrixWorld );
  40884. _v2.setFromMatrixPosition( this.light.target.matrixWorld );
  40885. _v3.subVectors( _v2, _v1 );
  40886. this.lightPlane.lookAt( _v2 );
  40887. if ( this.color !== undefined ) {
  40888. this.lightPlane.material.color.set( this.color );
  40889. this.targetLine.material.color.set( this.color );
  40890. } else {
  40891. this.lightPlane.material.color.copy( this.light.color );
  40892. this.targetLine.material.color.copy( this.light.color );
  40893. }
  40894. this.targetLine.lookAt( _v2 );
  40895. this.targetLine.scale.z = _v3.length();
  40896. }
  40897. }
  40898. const _vector = /*@__PURE__*/ new Vector3();
  40899. const _camera = /*@__PURE__*/ new Camera();
  40900. /**
  40901. * This helps with visualizing what a camera contains in its frustum. It
  40902. * visualizes the frustum of a camera using a line segments.
  40903. *
  40904. * Based on frustum visualization in [lightgl.js shadowmap example]{@link https://github.com/evanw/lightgl.js/blob/master/tests/shadowmap.html}.
  40905. *
  40906. * `CameraHelper` must be a child of the scene.
  40907. *
  40908. * ```js
  40909. * const camera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 0.1, 1000 );
  40910. * const helper = new THREE.CameraHelper( camera );
  40911. * scene.add( helper );
  40912. * ```
  40913. *
  40914. * @augments LineSegments
  40915. */
  40916. class CameraHelper extends LineSegments {
  40917. /**
  40918. * Constructs a new arrow helper.
  40919. *
  40920. * @param {Camera} camera - The camera to visualize.
  40921. */
  40922. constructor( camera ) {
  40923. const geometry = new BufferGeometry();
  40924. const material = new LineBasicMaterial( { color: 0xffffff, vertexColors: true, toneMapped: false } );
  40925. const vertices = [];
  40926. const colors = [];
  40927. const pointMap = {};
  40928. // near
  40929. addLine( 'n1', 'n2' );
  40930. addLine( 'n2', 'n4' );
  40931. addLine( 'n4', 'n3' );
  40932. addLine( 'n3', 'n1' );
  40933. // far
  40934. addLine( 'f1', 'f2' );
  40935. addLine( 'f2', 'f4' );
  40936. addLine( 'f4', 'f3' );
  40937. addLine( 'f3', 'f1' );
  40938. // sides
  40939. addLine( 'n1', 'f1' );
  40940. addLine( 'n2', 'f2' );
  40941. addLine( 'n3', 'f3' );
  40942. addLine( 'n4', 'f4' );
  40943. // cone
  40944. addLine( 'p', 'n1' );
  40945. addLine( 'p', 'n2' );
  40946. addLine( 'p', 'n3' );
  40947. addLine( 'p', 'n4' );
  40948. // up
  40949. addLine( 'u1', 'u2' );
  40950. addLine( 'u2', 'u3' );
  40951. addLine( 'u3', 'u1' );
  40952. // target
  40953. addLine( 'c', 't' );
  40954. addLine( 'p', 'c' );
  40955. // cross
  40956. addLine( 'cn1', 'cn2' );
  40957. addLine( 'cn3', 'cn4' );
  40958. addLine( 'cf1', 'cf2' );
  40959. addLine( 'cf3', 'cf4' );
  40960. function addLine( a, b ) {
  40961. addPoint( a );
  40962. addPoint( b );
  40963. }
  40964. function addPoint( id ) {
  40965. vertices.push( 0, 0, 0 );
  40966. colors.push( 0, 0, 0 );
  40967. if ( pointMap[ id ] === undefined ) {
  40968. pointMap[ id ] = [];
  40969. }
  40970. pointMap[ id ].push( ( vertices.length / 3 ) - 1 );
  40971. }
  40972. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  40973. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  40974. super( geometry, material );
  40975. this.type = 'CameraHelper';
  40976. /**
  40977. * The camera being visualized.
  40978. *
  40979. * @type {Camera}
  40980. */
  40981. this.camera = camera;
  40982. if ( this.camera.updateProjectionMatrix ) this.camera.updateProjectionMatrix();
  40983. this.matrix = camera.matrixWorld;
  40984. this.matrixAutoUpdate = false;
  40985. /**
  40986. * This contains the points used to visualize the camera.
  40987. *
  40988. * @type {Object<string,Array<number>>}
  40989. */
  40990. this.pointMap = pointMap;
  40991. this.update();
  40992. // colors
  40993. const colorFrustum = new Color( 0xffaa00 );
  40994. const colorCone = new Color( 0xff0000 );
  40995. const colorUp = new Color( 0x00aaff );
  40996. const colorTarget = new Color( 0xffffff );
  40997. const colorCross = new Color( 0x333333 );
  40998. this.setColors( colorFrustum, colorCone, colorUp, colorTarget, colorCross );
  40999. }
  41000. /**
  41001. * Defines the colors of the helper.
  41002. *
  41003. * @param {Color} frustum - The frustum line color.
  41004. * @param {Color} cone - The cone line color.
  41005. * @param {Color} up - The up line color.
  41006. * @param {Color} target - The target line color.
  41007. * @param {Color} cross - The cross line color.
  41008. */
  41009. setColors( frustum, cone, up, target, cross ) {
  41010. const geometry = this.geometry;
  41011. const colorAttribute = geometry.getAttribute( 'color' );
  41012. // near
  41013. colorAttribute.setXYZ( 0, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 1, frustum.r, frustum.g, frustum.b ); // n1, n2
  41014. colorAttribute.setXYZ( 2, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 3, frustum.r, frustum.g, frustum.b ); // n2, n4
  41015. colorAttribute.setXYZ( 4, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 5, frustum.r, frustum.g, frustum.b ); // n4, n3
  41016. colorAttribute.setXYZ( 6, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 7, frustum.r, frustum.g, frustum.b ); // n3, n1
  41017. // far
  41018. colorAttribute.setXYZ( 8, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 9, frustum.r, frustum.g, frustum.b ); // f1, f2
  41019. colorAttribute.setXYZ( 10, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 11, frustum.r, frustum.g, frustum.b ); // f2, f4
  41020. colorAttribute.setXYZ( 12, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 13, frustum.r, frustum.g, frustum.b ); // f4, f3
  41021. colorAttribute.setXYZ( 14, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 15, frustum.r, frustum.g, frustum.b ); // f3, f1
  41022. // sides
  41023. colorAttribute.setXYZ( 16, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 17, frustum.r, frustum.g, frustum.b ); // n1, f1
  41024. colorAttribute.setXYZ( 18, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 19, frustum.r, frustum.g, frustum.b ); // n2, f2
  41025. colorAttribute.setXYZ( 20, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 21, frustum.r, frustum.g, frustum.b ); // n3, f3
  41026. colorAttribute.setXYZ( 22, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 23, frustum.r, frustum.g, frustum.b ); // n4, f4
  41027. // cone
  41028. colorAttribute.setXYZ( 24, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 25, cone.r, cone.g, cone.b ); // p, n1
  41029. colorAttribute.setXYZ( 26, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 27, cone.r, cone.g, cone.b ); // p, n2
  41030. colorAttribute.setXYZ( 28, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 29, cone.r, cone.g, cone.b ); // p, n3
  41031. colorAttribute.setXYZ( 30, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 31, cone.r, cone.g, cone.b ); // p, n4
  41032. // up
  41033. colorAttribute.setXYZ( 32, up.r, up.g, up.b ); colorAttribute.setXYZ( 33, up.r, up.g, up.b ); // u1, u2
  41034. colorAttribute.setXYZ( 34, up.r, up.g, up.b ); colorAttribute.setXYZ( 35, up.r, up.g, up.b ); // u2, u3
  41035. colorAttribute.setXYZ( 36, up.r, up.g, up.b ); colorAttribute.setXYZ( 37, up.r, up.g, up.b ); // u3, u1
  41036. // target
  41037. colorAttribute.setXYZ( 38, target.r, target.g, target.b ); colorAttribute.setXYZ( 39, target.r, target.g, target.b ); // c, t
  41038. colorAttribute.setXYZ( 40, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 41, cross.r, cross.g, cross.b ); // p, c
  41039. // cross
  41040. colorAttribute.setXYZ( 42, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 43, cross.r, cross.g, cross.b ); // cn1, cn2
  41041. colorAttribute.setXYZ( 44, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 45, cross.r, cross.g, cross.b ); // cn3, cn4
  41042. colorAttribute.setXYZ( 46, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 47, cross.r, cross.g, cross.b ); // cf1, cf2
  41043. colorAttribute.setXYZ( 48, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 49, cross.r, cross.g, cross.b ); // cf3, cf4
  41044. colorAttribute.needsUpdate = true;
  41045. }
  41046. /**
  41047. * Updates the helper based on the projection matrix of the camera.
  41048. */
  41049. update() {
  41050. const geometry = this.geometry;
  41051. const pointMap = this.pointMap;
  41052. const w = 1, h = 1;
  41053. // we need just camera projection matrix inverse
  41054. // world matrix must be identity
  41055. _camera.projectionMatrixInverse.copy( this.camera.projectionMatrixInverse );
  41056. // Adjust z values based on coordinate system
  41057. const nearZ = this.camera.coordinateSystem === WebGLCoordinateSystem ? -1 : 0;
  41058. // center / target
  41059. setPoint( 'c', pointMap, geometry, _camera, 0, 0, nearZ );
  41060. setPoint( 't', pointMap, geometry, _camera, 0, 0, 1 );
  41061. // near
  41062. setPoint( 'n1', pointMap, geometry, _camera, -1, -1, nearZ );
  41063. setPoint( 'n2', pointMap, geometry, _camera, w, -1, nearZ );
  41064. setPoint( 'n3', pointMap, geometry, _camera, -1, h, nearZ );
  41065. setPoint( 'n4', pointMap, geometry, _camera, w, h, nearZ );
  41066. // far
  41067. setPoint( 'f1', pointMap, geometry, _camera, -1, -1, 1 );
  41068. setPoint( 'f2', pointMap, geometry, _camera, w, -1, 1 );
  41069. setPoint( 'f3', pointMap, geometry, _camera, -1, h, 1 );
  41070. setPoint( 'f4', pointMap, geometry, _camera, w, h, 1 );
  41071. // up
  41072. setPoint( 'u1', pointMap, geometry, _camera, w * 0.7, h * 1.1, nearZ );
  41073. setPoint( 'u2', pointMap, geometry, _camera, -1 * 0.7, h * 1.1, nearZ );
  41074. setPoint( 'u3', pointMap, geometry, _camera, 0, h * 2, nearZ );
  41075. // cross
  41076. setPoint( 'cf1', pointMap, geometry, _camera, -1, 0, 1 );
  41077. setPoint( 'cf2', pointMap, geometry, _camera, w, 0, 1 );
  41078. setPoint( 'cf3', pointMap, geometry, _camera, 0, -1, 1 );
  41079. setPoint( 'cf4', pointMap, geometry, _camera, 0, h, 1 );
  41080. setPoint( 'cn1', pointMap, geometry, _camera, -1, 0, nearZ );
  41081. setPoint( 'cn2', pointMap, geometry, _camera, w, 0, nearZ );
  41082. setPoint( 'cn3', pointMap, geometry, _camera, 0, -1, nearZ );
  41083. setPoint( 'cn4', pointMap, geometry, _camera, 0, h, nearZ );
  41084. geometry.getAttribute( 'position' ).needsUpdate = true;
  41085. }
  41086. /**
  41087. * Frees the GPU-related resources allocated by this instance. Call this
  41088. * method whenever this instance is no longer used in your app.
  41089. */
  41090. dispose() {
  41091. this.geometry.dispose();
  41092. this.material.dispose();
  41093. }
  41094. }
  41095. function setPoint( point, pointMap, geometry, camera, x, y, z ) {
  41096. _vector.set( x, y, z ).unproject( camera );
  41097. const points = pointMap[ point ];
  41098. if ( points !== undefined ) {
  41099. const position = geometry.getAttribute( 'position' );
  41100. for ( let i = 0, l = points.length; i < l; i ++ ) {
  41101. position.setXYZ( points[ i ], _vector.x, _vector.y, _vector.z );
  41102. }
  41103. }
  41104. }
  41105. const _box = /*@__PURE__*/ new Box3();
  41106. /**
  41107. * Helper object to graphically show the world-axis-aligned bounding box
  41108. * around an object. The actual bounding box is handled with {@link Box3},
  41109. * this is just a visual helper for debugging. It can be automatically
  41110. * resized with {@link BoxHelper#update} when the object it's created from
  41111. * is transformed. Note that the object must have a geometry for this to work,
  41112. * so it won't work with sprites.
  41113. *
  41114. * ```js
  41115. * const sphere = new THREE.SphereGeometry();
  41116. * const object = new THREE.Mesh( sphere, new THREE.MeshBasicMaterial( 0xff0000 ) );
  41117. * const box = new THREE.BoxHelper( object, 0xffff00 );
  41118. * scene.add( box );
  41119. * ```
  41120. *
  41121. * @augments LineSegments
  41122. */
  41123. class BoxHelper extends LineSegments {
  41124. /**
  41125. * Constructs a new box helper.
  41126. *
  41127. * @param {Object3D} [object] - The 3D object to show the world-axis-aligned bounding box.
  41128. * @param {number|Color|string} [color=0xffff00] - The box's color.
  41129. */
  41130. constructor( object, color = 0xffff00 ) {
  41131. 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 ] );
  41132. const positions = new Float32Array( 8 * 3 );
  41133. const geometry = new BufferGeometry();
  41134. geometry.setIndex( new BufferAttribute( indices, 1 ) );
  41135. geometry.setAttribute( 'position', new BufferAttribute( positions, 3 ) );
  41136. super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  41137. /**
  41138. * The 3D object being visualized.
  41139. *
  41140. * @type {Object3D}
  41141. */
  41142. this.object = object;
  41143. this.type = 'BoxHelper';
  41144. this.matrixAutoUpdate = false;
  41145. this.update();
  41146. }
  41147. /**
  41148. * Updates the helper's geometry to match the dimensions of the object,
  41149. * including any children.
  41150. */
  41151. update() {
  41152. if ( this.object !== undefined ) {
  41153. _box.setFromObject( this.object );
  41154. }
  41155. if ( _box.isEmpty() ) return;
  41156. const min = _box.min;
  41157. const max = _box.max;
  41158. /*
  41159. 5____4
  41160. 1/___0/|
  41161. | 6__|_7
  41162. 2/___3/
  41163. 0: max.x, max.y, max.z
  41164. 1: min.x, max.y, max.z
  41165. 2: min.x, min.y, max.z
  41166. 3: max.x, min.y, max.z
  41167. 4: max.x, max.y, min.z
  41168. 5: min.x, max.y, min.z
  41169. 6: min.x, min.y, min.z
  41170. 7: max.x, min.y, min.z
  41171. */
  41172. const position = this.geometry.attributes.position;
  41173. const array = position.array;
  41174. array[ 0 ] = max.x; array[ 1 ] = max.y; array[ 2 ] = max.z;
  41175. array[ 3 ] = min.x; array[ 4 ] = max.y; array[ 5 ] = max.z;
  41176. array[ 6 ] = min.x; array[ 7 ] = min.y; array[ 8 ] = max.z;
  41177. array[ 9 ] = max.x; array[ 10 ] = min.y; array[ 11 ] = max.z;
  41178. array[ 12 ] = max.x; array[ 13 ] = max.y; array[ 14 ] = min.z;
  41179. array[ 15 ] = min.x; array[ 16 ] = max.y; array[ 17 ] = min.z;
  41180. array[ 18 ] = min.x; array[ 19 ] = min.y; array[ 20 ] = min.z;
  41181. array[ 21 ] = max.x; array[ 22 ] = min.y; array[ 23 ] = min.z;
  41182. position.needsUpdate = true;
  41183. this.geometry.computeBoundingSphere();
  41184. }
  41185. /**
  41186. * Updates the wireframe box for the passed object.
  41187. *
  41188. * @param {Object3D} object - The 3D object to create the helper for.
  41189. * @return {BoxHelper} A reference to this instance.
  41190. */
  41191. setFromObject( object ) {
  41192. this.object = object;
  41193. this.update();
  41194. return this;
  41195. }
  41196. copy( source, recursive ) {
  41197. super.copy( source, recursive );
  41198. this.object = source.object;
  41199. return this;
  41200. }
  41201. /**
  41202. * Frees the GPU-related resources allocated by this instance. Call this
  41203. * method whenever this instance is no longer used in your app.
  41204. */
  41205. dispose() {
  41206. this.geometry.dispose();
  41207. this.material.dispose();
  41208. }
  41209. }
  41210. /**
  41211. * A helper object to visualize an instance of {@link Box3}.
  41212. *
  41213. * ```js
  41214. * const box = new THREE.Box3();
  41215. * box.setFromCenterAndSize( new THREE.Vector3( 1, 1, 1 ), new THREE.Vector3( 2, 1, 3 ) );
  41216. *
  41217. * const helper = new THREE.Box3Helper( box, 0xffff00 );
  41218. * scene.add( helper )
  41219. * ```
  41220. *
  41221. * @augments LineSegments
  41222. */
  41223. class Box3Helper extends LineSegments {
  41224. /**
  41225. * Constructs a new box3 helper.
  41226. *
  41227. * @param {Box3} box - The box to visualize.
  41228. * @param {number|Color|string} [color=0xffff00] - The box's color.
  41229. */
  41230. constructor( box, color = 0xffff00 ) {
  41231. 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 ] );
  41232. 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 ];
  41233. const geometry = new BufferGeometry();
  41234. geometry.setIndex( new BufferAttribute( indices, 1 ) );
  41235. geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  41236. super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  41237. /**
  41238. * The box being visualized.
  41239. *
  41240. * @type {Box3}
  41241. */
  41242. this.box = box;
  41243. this.type = 'Box3Helper';
  41244. this.geometry.computeBoundingSphere();
  41245. }
  41246. updateMatrixWorld( force ) {
  41247. const box = this.box;
  41248. if ( box.isEmpty() ) return;
  41249. box.getCenter( this.position );
  41250. box.getSize( this.scale );
  41251. this.scale.multiplyScalar( 0.5 );
  41252. super.updateMatrixWorld( force );
  41253. }
  41254. /**
  41255. * Frees the GPU-related resources allocated by this instance. Call this
  41256. * method whenever this instance is no longer used in your app.
  41257. */
  41258. dispose() {
  41259. this.geometry.dispose();
  41260. this.material.dispose();
  41261. }
  41262. }
  41263. /**
  41264. * A helper object to visualize an instance of {@link Plane}.
  41265. *
  41266. * ```js
  41267. * const plane = new THREE.Plane( new THREE.Vector3( 1, 1, 0.2 ), 3 );
  41268. * const helper = new THREE.PlaneHelper( plane, 1, 0xffff00 );
  41269. * scene.add( helper );
  41270. * ```
  41271. *
  41272. * @augments Line
  41273. */
  41274. class PlaneHelper extends Line {
  41275. /**
  41276. * Constructs a new plane helper.
  41277. *
  41278. * @param {Plane} plane - The plane to be visualized.
  41279. * @param {number} [size=1] - The side length of plane helper.
  41280. * @param {number|Color|string} [hex=0xffff00] - The helper's color.
  41281. */
  41282. constructor( plane, size = 1, hex = 0xffff00 ) {
  41283. const color = hex;
  41284. 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 ];
  41285. const geometry = new BufferGeometry();
  41286. geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  41287. geometry.computeBoundingSphere();
  41288. super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  41289. this.type = 'PlaneHelper';
  41290. /**
  41291. * The plane being visualized.
  41292. *
  41293. * @type {Plane}
  41294. */
  41295. this.plane = plane;
  41296. /**
  41297. * The side length of plane helper.
  41298. *
  41299. * @type {number}
  41300. * @default 1
  41301. */
  41302. this.size = size;
  41303. const positions2 = [ 1, 1, 0, -1, 1, 0, -1, -1, 0, 1, 1, 0, -1, -1, 0, 1, -1, 0 ];
  41304. const geometry2 = new BufferGeometry();
  41305. geometry2.setAttribute( 'position', new Float32BufferAttribute( positions2, 3 ) );
  41306. geometry2.computeBoundingSphere();
  41307. this.add( new Mesh( geometry2, new MeshBasicMaterial( { color: color, opacity: 0.2, transparent: true, depthWrite: false, toneMapped: false } ) ) );
  41308. }
  41309. updateMatrixWorld( force ) {
  41310. this.position.set( 0, 0, 0 );
  41311. this.scale.set( 0.5 * this.size, 0.5 * this.size, 1 );
  41312. this.lookAt( this.plane.normal );
  41313. this.translateZ( - this.plane.constant );
  41314. super.updateMatrixWorld( force );
  41315. }
  41316. /**
  41317. * Updates the helper to match the position and direction of the
  41318. * light being visualized.
  41319. */
  41320. dispose() {
  41321. this.geometry.dispose();
  41322. this.material.dispose();
  41323. this.children[ 0 ].geometry.dispose();
  41324. this.children[ 0 ].material.dispose();
  41325. }
  41326. }
  41327. const _axis = /*@__PURE__*/ new Vector3();
  41328. let _lineGeometry, _coneGeometry;
  41329. /**
  41330. * An 3D arrow object for visualizing directions.
  41331. *
  41332. * ```js
  41333. * const dir = new THREE.Vector3( 1, 2, 0 );
  41334. *
  41335. * //normalize the direction vector (convert to vector of length 1)
  41336. * dir.normalize();
  41337. *
  41338. * const origin = new THREE.Vector3( 0, 0, 0 );
  41339. * const length = 1;
  41340. * const hex = 0xffff00;
  41341. *
  41342. * const arrowHelper = new THREE.ArrowHelper( dir, origin, length, hex );
  41343. * scene.add( arrowHelper );
  41344. * ```
  41345. *
  41346. * @augments Object3D
  41347. */
  41348. class ArrowHelper extends Object3D {
  41349. /**
  41350. * Constructs a new arrow helper.
  41351. *
  41352. * @param {Vector3} [dir=(0, 0, 1)] - The (normalized) direction vector.
  41353. * @param {Vector3} [origin=(0, 0, 0)] - Point at which the arrow starts.
  41354. * @param {number} [length=1] - Length of the arrow in world units.
  41355. * @param {(number|Color|string)} [color=0xffff00] - Color of the arrow.
  41356. * @param {number} [headLength=length*0.2] - The length of the head of the arrow.
  41357. * @param {number} [headWidth=headLength*0.2] - The width of the head of the arrow.
  41358. */
  41359. 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 ) {
  41360. super();
  41361. this.type = 'ArrowHelper';
  41362. if ( _lineGeometry === undefined ) {
  41363. _lineGeometry = new BufferGeometry();
  41364. _lineGeometry.setAttribute( 'position', new Float32BufferAttribute( [ 0, 0, 0, 0, 1, 0 ], 3 ) );
  41365. _coneGeometry = new ConeGeometry( 0.5, 1, 5, 1 );
  41366. _coneGeometry.translate( 0, -0.5, 0 );
  41367. }
  41368. this.position.copy( origin );
  41369. /**
  41370. * The line part of the arrow helper.
  41371. *
  41372. * @type {Line}
  41373. */
  41374. this.line = new Line( _lineGeometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  41375. this.line.matrixAutoUpdate = false;
  41376. this.add( this.line );
  41377. /**
  41378. * The cone part of the arrow helper.
  41379. *
  41380. * @type {Mesh}
  41381. */
  41382. this.cone = new Mesh( _coneGeometry, new MeshBasicMaterial( { color: color, toneMapped: false } ) );
  41383. this.cone.matrixAutoUpdate = false;
  41384. this.add( this.cone );
  41385. this.setDirection( dir );
  41386. this.setLength( length, headLength, headWidth );
  41387. }
  41388. /**
  41389. * Sets the direction of the helper.
  41390. *
  41391. * @param {Vector3} dir - The normalized direction vector.
  41392. */
  41393. setDirection( dir ) {
  41394. // dir is assumed to be normalized
  41395. if ( dir.y > 0.99999 ) {
  41396. this.quaternion.set( 0, 0, 0, 1 );
  41397. } else if ( dir.y < -0.99999 ) {
  41398. this.quaternion.set( 1, 0, 0, 0 );
  41399. } else {
  41400. _axis.set( dir.z, 0, - dir.x ).normalize();
  41401. const radians = Math.acos( dir.y );
  41402. this.quaternion.setFromAxisAngle( _axis, radians );
  41403. }
  41404. }
  41405. /**
  41406. * Sets the length of the helper.
  41407. *
  41408. * @param {number} length - Length of the arrow in world units.
  41409. * @param {number} [headLength=length*0.2] - The length of the head of the arrow.
  41410. * @param {number} [headWidth=headLength*0.2] - The width of the head of the arrow.
  41411. */
  41412. setLength( length, headLength = length * 0.2, headWidth = headLength * 0.2 ) {
  41413. this.line.scale.set( 1, Math.max( 0.0001, length - headLength ), 1 ); // see #17458
  41414. this.line.updateMatrix();
  41415. this.cone.scale.set( headWidth, headLength, headWidth );
  41416. this.cone.position.y = length;
  41417. this.cone.updateMatrix();
  41418. }
  41419. /**
  41420. * Sets the color of the helper.
  41421. *
  41422. * @param {number|Color|string} color - The color to set.
  41423. */
  41424. setColor( color ) {
  41425. this.line.material.color.set( color );
  41426. this.cone.material.color.set( color );
  41427. }
  41428. copy( source ) {
  41429. super.copy( source, false );
  41430. this.line.copy( source.line );
  41431. this.cone.copy( source.cone );
  41432. return this;
  41433. }
  41434. /**
  41435. * Frees the GPU-related resources allocated by this instance. Call this
  41436. * method whenever this instance is no longer used in your app.
  41437. */
  41438. dispose() {
  41439. this.line.geometry.dispose();
  41440. this.line.material.dispose();
  41441. this.cone.geometry.dispose();
  41442. this.cone.material.dispose();
  41443. }
  41444. }
  41445. /**
  41446. * An axis object to visualize the 3 axes in a simple way.
  41447. * The X axis is red. The Y axis is green. The Z axis is blue.
  41448. *
  41449. * ```js
  41450. * const axesHelper = new THREE.AxesHelper( 5 );
  41451. * scene.add( axesHelper );
  41452. * ```
  41453. *
  41454. * @augments LineSegments
  41455. */
  41456. class AxesHelper extends LineSegments {
  41457. /**
  41458. * Constructs a new axes helper.
  41459. *
  41460. * @param {number} [size=1] - Size of the lines representing the axes.
  41461. */
  41462. constructor( size = 1 ) {
  41463. const vertices = [
  41464. 0, 0, 0, size, 0, 0,
  41465. 0, 0, 0, 0, size, 0,
  41466. 0, 0, 0, 0, 0, size
  41467. ];
  41468. const colors = [
  41469. 1, 0, 0, 1, 0.6, 0,
  41470. 0, 1, 0, 0.6, 1, 0,
  41471. 0, 0, 1, 0, 0.6, 1
  41472. ];
  41473. const geometry = new BufferGeometry();
  41474. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  41475. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  41476. const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
  41477. super( geometry, material );
  41478. this.type = 'AxesHelper';
  41479. }
  41480. /**
  41481. * Defines the colors of the axes helper.
  41482. *
  41483. * @param {number|Color|string} xAxisColor - The color for the x axis.
  41484. * @param {number|Color|string} yAxisColor - The color for the y axis.
  41485. * @param {number|Color|string} zAxisColor - The color for the z axis.
  41486. * @return {AxesHelper} A reference to this axes helper.
  41487. */
  41488. setColors( xAxisColor, yAxisColor, zAxisColor ) {
  41489. const color = new Color();
  41490. const array = this.geometry.attributes.color.array;
  41491. color.set( xAxisColor );
  41492. color.toArray( array, 0 );
  41493. color.toArray( array, 3 );
  41494. color.set( yAxisColor );
  41495. color.toArray( array, 6 );
  41496. color.toArray( array, 9 );
  41497. color.set( zAxisColor );
  41498. color.toArray( array, 12 );
  41499. color.toArray( array, 15 );
  41500. this.geometry.attributes.color.needsUpdate = true;
  41501. return this;
  41502. }
  41503. /**
  41504. * Frees the GPU-related resources allocated by this instance. Call this
  41505. * method whenever this instance is no longer used in your app.
  41506. */
  41507. dispose() {
  41508. this.geometry.dispose();
  41509. this.material.dispose();
  41510. }
  41511. }
  41512. /**
  41513. * This class is used to convert a series of paths to an array of
  41514. * shapes. It is specifically used in context of fonts and SVG.
  41515. */
  41516. class ShapePath {
  41517. /**
  41518. * Constructs a new shape path.
  41519. */
  41520. constructor() {
  41521. this.type = 'ShapePath';
  41522. /**
  41523. * The color of the shape.
  41524. *
  41525. * @type {Color}
  41526. */
  41527. this.color = new Color();
  41528. /**
  41529. * The paths that have been generated for this shape.
  41530. *
  41531. * @type {Array<Path>}
  41532. * @default null
  41533. */
  41534. this.subPaths = [];
  41535. /**
  41536. * The current path that is being generated.
  41537. *
  41538. * @type {?Path}
  41539. * @default null
  41540. */
  41541. this.currentPath = null;
  41542. }
  41543. /**
  41544. * Creates a new path and moves it current point to the given one.
  41545. *
  41546. * @param {number} x - The x coordinate.
  41547. * @param {number} y - The y coordinate.
  41548. * @return {ShapePath} A reference to this shape path.
  41549. */
  41550. moveTo( x, y ) {
  41551. this.currentPath = new Path();
  41552. this.subPaths.push( this.currentPath );
  41553. this.currentPath.moveTo( x, y );
  41554. return this;
  41555. }
  41556. /**
  41557. * Adds an instance of {@link LineCurve} to the path by connecting
  41558. * the current point with the given one.
  41559. *
  41560. * @param {number} x - The x coordinate of the end point.
  41561. * @param {number} y - The y coordinate of the end point.
  41562. * @return {ShapePath} A reference to this shape path.
  41563. */
  41564. lineTo( x, y ) {
  41565. this.currentPath.lineTo( x, y );
  41566. return this;
  41567. }
  41568. /**
  41569. * Adds an instance of {@link QuadraticBezierCurve} to the path by connecting
  41570. * the current point with the given one.
  41571. *
  41572. * @param {number} aCPx - The x coordinate of the control point.
  41573. * @param {number} aCPy - The y coordinate of the control point.
  41574. * @param {number} aX - The x coordinate of the end point.
  41575. * @param {number} aY - The y coordinate of the end point.
  41576. * @return {ShapePath} A reference to this shape path.
  41577. */
  41578. quadraticCurveTo( aCPx, aCPy, aX, aY ) {
  41579. this.currentPath.quadraticCurveTo( aCPx, aCPy, aX, aY );
  41580. return this;
  41581. }
  41582. /**
  41583. * Adds an instance of {@link CubicBezierCurve} to the path by connecting
  41584. * the current point with the given one.
  41585. *
  41586. * @param {number} aCP1x - The x coordinate of the first control point.
  41587. * @param {number} aCP1y - The y coordinate of the first control point.
  41588. * @param {number} aCP2x - The x coordinate of the second control point.
  41589. * @param {number} aCP2y - The y coordinate of the second control point.
  41590. * @param {number} aX - The x coordinate of the end point.
  41591. * @param {number} aY - The y coordinate of the end point.
  41592. * @return {ShapePath} A reference to this shape path.
  41593. */
  41594. bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) {
  41595. this.currentPath.bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY );
  41596. return this;
  41597. }
  41598. /**
  41599. * Adds an instance of {@link SplineCurve} to the path by connecting
  41600. * the current point with the given list of points.
  41601. *
  41602. * @param {Array<Vector2>} pts - An array of points in 2D space.
  41603. * @return {ShapePath} A reference to this shape path.
  41604. */
  41605. splineThru( pts ) {
  41606. this.currentPath.splineThru( pts );
  41607. return this;
  41608. }
  41609. /**
  41610. * Converts the paths into an array of shapes.
  41611. *
  41612. * @param {boolean} isCCW - By default solid shapes are defined clockwise (CW) and holes are defined counterclockwise (CCW).
  41613. * If this flag is set to `true`, then those are flipped.
  41614. * @return {Array<Shape>} An array of shapes.
  41615. */
  41616. toShapes( isCCW ) {
  41617. function toShapesNoHoles( inSubpaths ) {
  41618. const shapes = [];
  41619. for ( let i = 0, l = inSubpaths.length; i < l; i ++ ) {
  41620. const tmpPath = inSubpaths[ i ];
  41621. const tmpShape = new Shape();
  41622. tmpShape.curves = tmpPath.curves;
  41623. shapes.push( tmpShape );
  41624. }
  41625. return shapes;
  41626. }
  41627. function isPointInsidePolygon( inPt, inPolygon ) {
  41628. const polyLen = inPolygon.length;
  41629. // inPt on polygon contour => immediate success or
  41630. // toggling of inside/outside at every single! intersection point of an edge
  41631. // with the horizontal line through inPt, left of inPt
  41632. // not counting lowerY endpoints of edges and whole edges on that line
  41633. let inside = false;
  41634. for ( let p = polyLen - 1, q = 0; q < polyLen; p = q ++ ) {
  41635. let edgeLowPt = inPolygon[ p ];
  41636. let edgeHighPt = inPolygon[ q ];
  41637. let edgeDx = edgeHighPt.x - edgeLowPt.x;
  41638. let edgeDy = edgeHighPt.y - edgeLowPt.y;
  41639. if ( Math.abs( edgeDy ) > Number.EPSILON ) {
  41640. // not parallel
  41641. if ( edgeDy < 0 ) {
  41642. edgeLowPt = inPolygon[ q ]; edgeDx = - edgeDx;
  41643. edgeHighPt = inPolygon[ p ]; edgeDy = - edgeDy;
  41644. }
  41645. if ( ( inPt.y < edgeLowPt.y ) || ( inPt.y > edgeHighPt.y ) ) continue;
  41646. if ( inPt.y === edgeLowPt.y ) {
  41647. if ( inPt.x === edgeLowPt.x ) return true; // inPt is on contour ?
  41648. // continue; // no intersection or edgeLowPt => doesn't count !!!
  41649. } else {
  41650. const perpEdge = edgeDy * ( inPt.x - edgeLowPt.x ) - edgeDx * ( inPt.y - edgeLowPt.y );
  41651. if ( perpEdge === 0 ) return true; // inPt is on contour ?
  41652. if ( perpEdge < 0 ) continue;
  41653. inside = ! inside; // true intersection left of inPt
  41654. }
  41655. } else {
  41656. // parallel or collinear
  41657. if ( inPt.y !== edgeLowPt.y ) continue; // parallel
  41658. // edge lies on the same horizontal line as inPt
  41659. if ( ( ( edgeHighPt.x <= inPt.x ) && ( inPt.x <= edgeLowPt.x ) ) ||
  41660. ( ( edgeLowPt.x <= inPt.x ) && ( inPt.x <= edgeHighPt.x ) ) ) return true; // inPt: Point on contour !
  41661. // continue;
  41662. }
  41663. }
  41664. return inside;
  41665. }
  41666. const isClockWise = ShapeUtils.isClockWise;
  41667. const subPaths = this.subPaths;
  41668. if ( subPaths.length === 0 ) return [];
  41669. let solid, tmpPath, tmpShape;
  41670. const shapes = [];
  41671. if ( subPaths.length === 1 ) {
  41672. tmpPath = subPaths[ 0 ];
  41673. tmpShape = new Shape();
  41674. tmpShape.curves = tmpPath.curves;
  41675. shapes.push( tmpShape );
  41676. return shapes;
  41677. }
  41678. let holesFirst = ! isClockWise( subPaths[ 0 ].getPoints() );
  41679. holesFirst = isCCW ? ! holesFirst : holesFirst;
  41680. // console.log("Holes first", holesFirst);
  41681. const betterShapeHoles = [];
  41682. const newShapes = [];
  41683. let newShapeHoles = [];
  41684. let mainIdx = 0;
  41685. let tmpPoints;
  41686. newShapes[ mainIdx ] = undefined;
  41687. newShapeHoles[ mainIdx ] = [];
  41688. for ( let i = 0, l = subPaths.length; i < l; i ++ ) {
  41689. tmpPath = subPaths[ i ];
  41690. tmpPoints = tmpPath.getPoints();
  41691. solid = isClockWise( tmpPoints );
  41692. solid = isCCW ? ! solid : solid;
  41693. if ( solid ) {
  41694. if ( ( ! holesFirst ) && ( newShapes[ mainIdx ] ) ) mainIdx ++;
  41695. newShapes[ mainIdx ] = { s: new Shape(), p: tmpPoints };
  41696. newShapes[ mainIdx ].s.curves = tmpPath.curves;
  41697. if ( holesFirst ) mainIdx ++;
  41698. newShapeHoles[ mainIdx ] = [];
  41699. //console.log('cw', i);
  41700. } else {
  41701. newShapeHoles[ mainIdx ].push( { h: tmpPath, p: tmpPoints[ 0 ] } );
  41702. //console.log('ccw', i);
  41703. }
  41704. }
  41705. // only Holes? -> probably all Shapes with wrong orientation
  41706. if ( ! newShapes[ 0 ] ) return toShapesNoHoles( subPaths );
  41707. if ( newShapes.length > 1 ) {
  41708. let ambiguous = false;
  41709. let toChange = 0;
  41710. for ( let sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) {
  41711. betterShapeHoles[ sIdx ] = [];
  41712. }
  41713. for ( let sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) {
  41714. const sho = newShapeHoles[ sIdx ];
  41715. for ( let hIdx = 0; hIdx < sho.length; hIdx ++ ) {
  41716. const ho = sho[ hIdx ];
  41717. let hole_unassigned = true;
  41718. for ( let s2Idx = 0; s2Idx < newShapes.length; s2Idx ++ ) {
  41719. if ( isPointInsidePolygon( ho.p, newShapes[ s2Idx ].p ) ) {
  41720. if ( sIdx !== s2Idx ) toChange ++;
  41721. if ( hole_unassigned ) {
  41722. hole_unassigned = false;
  41723. betterShapeHoles[ s2Idx ].push( ho );
  41724. } else {
  41725. ambiguous = true;
  41726. }
  41727. }
  41728. }
  41729. if ( hole_unassigned ) {
  41730. betterShapeHoles[ sIdx ].push( ho );
  41731. }
  41732. }
  41733. }
  41734. if ( toChange > 0 && ambiguous === false ) {
  41735. newShapeHoles = betterShapeHoles;
  41736. }
  41737. }
  41738. let tmpHoles;
  41739. for ( let i = 0, il = newShapes.length; i < il; i ++ ) {
  41740. tmpShape = newShapes[ i ].s;
  41741. shapes.push( tmpShape );
  41742. tmpHoles = newShapeHoles[ i ];
  41743. for ( let j = 0, jl = tmpHoles.length; j < jl; j ++ ) {
  41744. tmpShape.holes.push( tmpHoles[ j ].h );
  41745. }
  41746. }
  41747. //console.log("shape", shapes);
  41748. return shapes;
  41749. }
  41750. }
  41751. /**
  41752. * Abstract base class for controls.
  41753. *
  41754. * @abstract
  41755. * @augments EventDispatcher
  41756. */
  41757. class Controls extends EventDispatcher {
  41758. /**
  41759. * Constructs a new controls instance.
  41760. *
  41761. * @param {Object3D} object - The object that is managed by the controls.
  41762. * @param {?HTMLDOMElement} domElement - The HTML element used for event listeners.
  41763. */
  41764. constructor( object, domElement = null ) {
  41765. super();
  41766. /**
  41767. * The object that is managed by the controls.
  41768. *
  41769. * @type {Object3D}
  41770. */
  41771. this.object = object;
  41772. /**
  41773. * The HTML element used for event listeners.
  41774. *
  41775. * @type {?HTMLDOMElement}
  41776. * @default null
  41777. */
  41778. this.domElement = domElement;
  41779. /**
  41780. * Whether the controls responds to user input or not.
  41781. *
  41782. * @type {boolean}
  41783. * @default true
  41784. */
  41785. this.enabled = true;
  41786. /**
  41787. * The internal state of the controls.
  41788. *
  41789. * @type {number}
  41790. * @default -1
  41791. */
  41792. this.state = -1;
  41793. /**
  41794. * This object defines the keyboard input of the controls.
  41795. *
  41796. * @type {Object}
  41797. */
  41798. this.keys = {};
  41799. /**
  41800. * This object defines what type of actions are assigned to the available mouse buttons.
  41801. * It depends on the control implementation what kind of mouse buttons and actions are supported.
  41802. *
  41803. * @type {{LEFT: ?number, MIDDLE: ?number, RIGHT: ?number}}
  41804. */
  41805. this.mouseButtons = { LEFT: null, MIDDLE: null, RIGHT: null };
  41806. /**
  41807. * This object defines what type of actions are assigned to what kind of touch interaction.
  41808. * It depends on the control implementation what kind of touch interaction and actions are supported.
  41809. *
  41810. * @type {{ONE: ?number, TWO: ?number}}
  41811. */
  41812. this.touches = { ONE: null, TWO: null };
  41813. }
  41814. /**
  41815. * Connects the controls to the DOM. This method has so called "side effects" since
  41816. * it adds the module's event listeners to the DOM.
  41817. *
  41818. * @param {HTMLDOMElement} element - The DOM element to connect to.
  41819. */
  41820. connect( element ) {
  41821. if ( element === undefined ) {
  41822. console.warn( 'THREE.Controls: connect() now requires an element.' ); // @deprecated, the warning can be removed with r185
  41823. return;
  41824. }
  41825. if ( this.domElement !== null ) this.disconnect();
  41826. this.domElement = element;
  41827. }
  41828. /**
  41829. * Disconnects the controls from the DOM.
  41830. */
  41831. disconnect() {}
  41832. /**
  41833. * Call this method if you no longer want use to the controls. It frees all internal
  41834. * resources and removes all event listeners.
  41835. */
  41836. dispose() {}
  41837. /**
  41838. * Controls should implement this method if they have to update their internal state
  41839. * per simulation step.
  41840. *
  41841. * @param {number} [delta] - The time delta in seconds.
  41842. */
  41843. update( /* delta */ ) {}
  41844. }
  41845. /**
  41846. * Scales the texture as large as possible within its surface without cropping
  41847. * or stretching the texture. The method preserves the original aspect ratio of
  41848. * the texture. Akin to CSS `object-fit: contain`
  41849. *
  41850. * @param {Texture} texture - The texture.
  41851. * @param {number} aspect - The texture's aspect ratio.
  41852. * @return {Texture} The updated texture.
  41853. */
  41854. function contain( texture, aspect ) {
  41855. const imageAspect = ( texture.image && texture.image.width ) ? texture.image.width / texture.image.height : 1;
  41856. if ( imageAspect > aspect ) {
  41857. texture.repeat.x = 1;
  41858. texture.repeat.y = imageAspect / aspect;
  41859. texture.offset.x = 0;
  41860. texture.offset.y = ( 1 - texture.repeat.y ) / 2;
  41861. } else {
  41862. texture.repeat.x = aspect / imageAspect;
  41863. texture.repeat.y = 1;
  41864. texture.offset.x = ( 1 - texture.repeat.x ) / 2;
  41865. texture.offset.y = 0;
  41866. }
  41867. return texture;
  41868. }
  41869. /**
  41870. * Scales the texture to the smallest possible size to fill the surface, leaving
  41871. * no empty space. The method preserves the original aspect ratio of the texture.
  41872. * Akin to CSS `object-fit: cover`.
  41873. *
  41874. * @param {Texture} texture - The texture.
  41875. * @param {number} aspect - The texture's aspect ratio.
  41876. * @return {Texture} The updated texture.
  41877. */
  41878. function cover( texture, aspect ) {
  41879. const imageAspect = ( texture.image && texture.image.width ) ? texture.image.width / texture.image.height : 1;
  41880. if ( imageAspect > aspect ) {
  41881. texture.repeat.x = aspect / imageAspect;
  41882. texture.repeat.y = 1;
  41883. texture.offset.x = ( 1 - texture.repeat.x ) / 2;
  41884. texture.offset.y = 0;
  41885. } else {
  41886. texture.repeat.x = 1;
  41887. texture.repeat.y = imageAspect / aspect;
  41888. texture.offset.x = 0;
  41889. texture.offset.y = ( 1 - texture.repeat.y ) / 2;
  41890. }
  41891. return texture;
  41892. }
  41893. /**
  41894. * Configures the texture to the default transformation. Akin to CSS `object-fit: fill`.
  41895. *
  41896. * @param {Texture} texture - The texture.
  41897. * @return {Texture} The updated texture.
  41898. */
  41899. function fill( texture ) {
  41900. texture.repeat.x = 1;
  41901. texture.repeat.y = 1;
  41902. texture.offset.x = 0;
  41903. texture.offset.y = 0;
  41904. return texture;
  41905. }
  41906. /**
  41907. * Determines how many bytes must be used to represent the texture.
  41908. *
  41909. * @param {number} width - The width of the texture.
  41910. * @param {number} height - The height of the texture.
  41911. * @param {number} format - The texture's format.
  41912. * @param {number} type - The texture's type.
  41913. * @return {number} The byte length.
  41914. */
  41915. function getByteLength( width, height, format, type ) {
  41916. const typeByteLength = getTextureTypeByteLength( type );
  41917. switch ( format ) {
  41918. // https://registry.khronos.org/OpenGL-Refpages/es3.0/html/glTexImage2D.xhtml
  41919. case AlphaFormat:
  41920. return width * height;
  41921. case RedFormat:
  41922. return ( ( width * height ) / typeByteLength.components ) * typeByteLength.byteLength;
  41923. case RedIntegerFormat:
  41924. return ( ( width * height ) / typeByteLength.components ) * typeByteLength.byteLength;
  41925. case RGFormat:
  41926. return ( ( width * height * 2 ) / typeByteLength.components ) * typeByteLength.byteLength;
  41927. case RGIntegerFormat:
  41928. return ( ( width * height * 2 ) / typeByteLength.components ) * typeByteLength.byteLength;
  41929. case RGBFormat:
  41930. return ( ( width * height * 3 ) / typeByteLength.components ) * typeByteLength.byteLength;
  41931. case RGBAFormat:
  41932. return ( ( width * height * 4 ) / typeByteLength.components ) * typeByteLength.byteLength;
  41933. case RGBAIntegerFormat:
  41934. return ( ( width * height * 4 ) / typeByteLength.components ) * typeByteLength.byteLength;
  41935. // https://registry.khronos.org/webgl/extensions/WEBGL_compressed_texture_s3tc_srgb/
  41936. case RGB_S3TC_DXT1_Format:
  41937. case RGBA_S3TC_DXT1_Format:
  41938. return Math.floor( ( width + 3 ) / 4 ) * Math.floor( ( height + 3 ) / 4 ) * 8;
  41939. case RGBA_S3TC_DXT3_Format:
  41940. case RGBA_S3TC_DXT5_Format:
  41941. return Math.floor( ( width + 3 ) / 4 ) * Math.floor( ( height + 3 ) / 4 ) * 16;
  41942. // https://registry.khronos.org/webgl/extensions/WEBGL_compressed_texture_pvrtc/
  41943. case RGB_PVRTC_2BPPV1_Format:
  41944. case RGBA_PVRTC_2BPPV1_Format:
  41945. return ( Math.max( width, 16 ) * Math.max( height, 8 ) ) / 4;
  41946. case RGB_PVRTC_4BPPV1_Format:
  41947. case RGBA_PVRTC_4BPPV1_Format:
  41948. return ( Math.max( width, 8 ) * Math.max( height, 8 ) ) / 2;
  41949. // https://registry.khronos.org/webgl/extensions/WEBGL_compressed_texture_etc/
  41950. case RGB_ETC1_Format:
  41951. case RGB_ETC2_Format:
  41952. return Math.floor( ( width + 3 ) / 4 ) * Math.floor( ( height + 3 ) / 4 ) * 8;
  41953. case RGBA_ETC2_EAC_Format:
  41954. return Math.floor( ( width + 3 ) / 4 ) * Math.floor( ( height + 3 ) / 4 ) * 16;
  41955. // https://registry.khronos.org/webgl/extensions/WEBGL_compressed_texture_astc/
  41956. case RGBA_ASTC_4x4_Format:
  41957. return Math.floor( ( width + 3 ) / 4 ) * Math.floor( ( height + 3 ) / 4 ) * 16;
  41958. case RGBA_ASTC_5x4_Format:
  41959. return Math.floor( ( width + 4 ) / 5 ) * Math.floor( ( height + 3 ) / 4 ) * 16;
  41960. case RGBA_ASTC_5x5_Format:
  41961. return Math.floor( ( width + 4 ) / 5 ) * Math.floor( ( height + 4 ) / 5 ) * 16;
  41962. case RGBA_ASTC_6x5_Format:
  41963. return Math.floor( ( width + 5 ) / 6 ) * Math.floor( ( height + 4 ) / 5 ) * 16;
  41964. case RGBA_ASTC_6x6_Format:
  41965. return Math.floor( ( width + 5 ) / 6 ) * Math.floor( ( height + 5 ) / 6 ) * 16;
  41966. case RGBA_ASTC_8x5_Format:
  41967. return Math.floor( ( width + 7 ) / 8 ) * Math.floor( ( height + 4 ) / 5 ) * 16;
  41968. case RGBA_ASTC_8x6_Format:
  41969. return Math.floor( ( width + 7 ) / 8 ) * Math.floor( ( height + 5 ) / 6 ) * 16;
  41970. case RGBA_ASTC_8x8_Format:
  41971. return Math.floor( ( width + 7 ) / 8 ) * Math.floor( ( height + 7 ) / 8 ) * 16;
  41972. case RGBA_ASTC_10x5_Format:
  41973. return Math.floor( ( width + 9 ) / 10 ) * Math.floor( ( height + 4 ) / 5 ) * 16;
  41974. case RGBA_ASTC_10x6_Format:
  41975. return Math.floor( ( width + 9 ) / 10 ) * Math.floor( ( height + 5 ) / 6 ) * 16;
  41976. case RGBA_ASTC_10x8_Format:
  41977. return Math.floor( ( width + 9 ) / 10 ) * Math.floor( ( height + 7 ) / 8 ) * 16;
  41978. case RGBA_ASTC_10x10_Format:
  41979. return Math.floor( ( width + 9 ) / 10 ) * Math.floor( ( height + 9 ) / 10 ) * 16;
  41980. case RGBA_ASTC_12x10_Format:
  41981. return Math.floor( ( width + 11 ) / 12 ) * Math.floor( ( height + 9 ) / 10 ) * 16;
  41982. case RGBA_ASTC_12x12_Format:
  41983. return Math.floor( ( width + 11 ) / 12 ) * Math.floor( ( height + 11 ) / 12 ) * 16;
  41984. // https://registry.khronos.org/webgl/extensions/EXT_texture_compression_bptc/
  41985. case RGBA_BPTC_Format:
  41986. case RGB_BPTC_SIGNED_Format:
  41987. case RGB_BPTC_UNSIGNED_Format:
  41988. return Math.ceil( width / 4 ) * Math.ceil( height / 4 ) * 16;
  41989. // https://registry.khronos.org/webgl/extensions/EXT_texture_compression_rgtc/
  41990. case RED_RGTC1_Format:
  41991. case SIGNED_RED_RGTC1_Format:
  41992. return Math.ceil( width / 4 ) * Math.ceil( height / 4 ) * 8;
  41993. case RED_GREEN_RGTC2_Format:
  41994. case SIGNED_RED_GREEN_RGTC2_Format:
  41995. return Math.ceil( width / 4 ) * Math.ceil( height / 4 ) * 16;
  41996. }
  41997. throw new Error(
  41998. `Unable to determine texture byte length for ${format} format.`,
  41999. );
  42000. }
  42001. function getTextureTypeByteLength( type ) {
  42002. switch ( type ) {
  42003. case UnsignedByteType:
  42004. case ByteType:
  42005. return { byteLength: 1, components: 1 };
  42006. case UnsignedShortType:
  42007. case ShortType:
  42008. case HalfFloatType:
  42009. return { byteLength: 2, components: 1 };
  42010. case UnsignedShort4444Type:
  42011. case UnsignedShort5551Type:
  42012. return { byteLength: 2, components: 4 };
  42013. case UnsignedIntType:
  42014. case IntType:
  42015. case FloatType:
  42016. return { byteLength: 4, components: 1 };
  42017. case UnsignedInt5999Type:
  42018. return { byteLength: 4, components: 3 };
  42019. }
  42020. throw new Error( `Unknown texture type ${type}.` );
  42021. }
  42022. /**
  42023. * A class containing utility functions for textures.
  42024. *
  42025. * @hideconstructor
  42026. */
  42027. class TextureUtils {
  42028. /**
  42029. * Scales the texture as large as possible within its surface without cropping
  42030. * or stretching the texture. The method preserves the original aspect ratio of
  42031. * the texture. Akin to CSS `object-fit: contain`
  42032. *
  42033. * @param {Texture} texture - The texture.
  42034. * @param {number} aspect - The texture's aspect ratio.
  42035. * @return {Texture} The updated texture.
  42036. */
  42037. static contain( texture, aspect ) {
  42038. return contain( texture, aspect );
  42039. }
  42040. /**
  42041. * Scales the texture to the smallest possible size to fill the surface, leaving
  42042. * no empty space. The method preserves the original aspect ratio of the texture.
  42043. * Akin to CSS `object-fit: cover`.
  42044. *
  42045. * @param {Texture} texture - The texture.
  42046. * @param {number} aspect - The texture's aspect ratio.
  42047. * @return {Texture} The updated texture.
  42048. */
  42049. static cover( texture, aspect ) {
  42050. return cover( texture, aspect );
  42051. }
  42052. /**
  42053. * Configures the texture to the default transformation. Akin to CSS `object-fit: fill`.
  42054. *
  42055. * @param {Texture} texture - The texture.
  42056. * @return {Texture} The updated texture.
  42057. */
  42058. static fill( texture ) {
  42059. return fill( texture );
  42060. }
  42061. /**
  42062. * Determines how many bytes must be used to represent the texture.
  42063. *
  42064. * @param {number} width - The width of the texture.
  42065. * @param {number} height - The height of the texture.
  42066. * @param {number} format - The texture's format.
  42067. * @param {number} type - The texture's type.
  42068. * @return {number} The byte length.
  42069. */
  42070. static getByteLength( width, height, format, type ) {
  42071. return getByteLength( width, height, format, type );
  42072. }
  42073. }
  42074. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  42075. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'register', { detail: {
  42076. revision: REVISION,
  42077. } } ) );
  42078. }
  42079. if ( typeof window !== 'undefined' ) {
  42080. if ( window.__THREE__ ) {
  42081. console.warn( 'WARNING: Multiple instances of Three.js being imported.' );
  42082. } else {
  42083. window.__THREE__ = REVISION;
  42084. }
  42085. }
  42086. 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, FrustumArray, GLBufferAttribute, GLSL1, GLSL3, GreaterCompare, GreaterDepth, GreaterEqualCompare, GreaterEqualDepth, GreaterEqualStencilFunc, GreaterStencilFunc, GridHelper, Group, HalfFloatType, HemisphereLight, HemisphereLightHelper, IcosahedronGeometry, ImageBitmapLoader, ImageLoader, ImageUtils, IncrementStencilOp, IncrementWrapStencilOp, InstancedBufferAttribute, InstancedBufferGeometry, InstancedInterleavedBuffer, InstancedMesh, Int16BufferAttribute, Int32BufferAttribute, Int8BufferAttribute, IntType, InterleavedBuffer, InterleavedBufferAttribute, Interpolant, InterpolateDiscrete, InterpolateLinear, InterpolateSmooth, InterpolationSamplingMode, InterpolationSamplingType, InvertStencilOp, KeepStencilOp, KeyframeTrack, LOD, LatheGeometry, Layers, LessCompare, LessDepth, LessEqualCompare, LessEqualDepth, LessEqualStencilFunc, LessStencilFunc, Light, LightProbe, Line, Line3, LineBasicMaterial, LineCurve, LineCurve3, LineDashedMaterial, LineLoop, LineSegments, LinearFilter, LinearInterpolant, LinearMipMapLinearFilter, LinearMipMapNearestFilter, LinearMipmapLinearFilter, LinearMipmapNearestFilter, LinearSRGBColorSpace, LinearToneMapping, LinearTransfer, Loader, LoaderUtils, LoadingManager, LoopOnce, LoopPingPong, LoopRepeat, MOUSE, Material, MaterialLoader, MathUtils, Matrix2, Matrix3, Matrix4, MaxEquation, Mesh, MeshBasicMaterial, MeshDepthMaterial, MeshDistanceMaterial, MeshLambertMaterial, MeshMatcapMaterial, MeshNormalMaterial, MeshPhongMaterial, MeshPhysicalMaterial, MeshStandardMaterial, MeshToonMaterial, MinEquation, MirroredRepeatWrapping, MixOperation, MultiplyBlending, MultiplyOperation, NearestFilter, NearestMipMapLinearFilter, NearestMipMapNearestFilter, NearestMipmapLinearFilter, NearestMipmapNearestFilter, NeutralToneMapping, NeverCompare, NeverDepth, NeverStencilFunc, NoBlending, NoColorSpace, NoToneMapping, NormalAnimationBlendMode, NormalBlending, NotEqualCompare, NotEqualDepth, NotEqualStencilFunc, NumberKeyframeTrack, Object3D, ObjectLoader, ObjectSpaceNormalMap, OctahedronGeometry, OneFactor, OneMinusConstantAlphaFactor, OneMinusConstantColorFactor, OneMinusDstAlphaFactor, OneMinusDstColorFactor, OneMinusSrcAlphaFactor, OneMinusSrcColorFactor, OrthographicCamera, PCFShadowMap, PCFSoftShadowMap, Path, PerspectiveCamera, Plane, PlaneGeometry, PlaneHelper, PointLight, PointLightHelper, Points, PointsMaterial, PolarGridHelper, PolyhedronGeometry, PositionalAudio, PropertyBinding, PropertyMixer, QuadraticBezierCurve, QuadraticBezierCurve3, Quaternion, QuaternionKeyframeTrack, QuaternionLinearInterpolant, RAD2DEG, RED_GREEN_RGTC2_Format, RED_RGTC1_Format, REVISION, RGBADepthPacking, RGBAFormat, RGBAIntegerFormat, RGBA_ASTC_10x10_Format, RGBA_ASTC_10x5_Format, RGBA_ASTC_10x6_Format, RGBA_ASTC_10x8_Format, RGBA_ASTC_12x10_Format, RGBA_ASTC_12x12_Format, RGBA_ASTC_4x4_Format, RGBA_ASTC_5x4_Format, RGBA_ASTC_5x5_Format, RGBA_ASTC_6x5_Format, RGBA_ASTC_6x6_Format, RGBA_ASTC_8x5_Format, RGBA_ASTC_8x6_Format, RGBA_ASTC_8x8_Format, RGBA_BPTC_Format, RGBA_ETC2_EAC_Format, RGBA_PVRTC_2BPPV1_Format, RGBA_PVRTC_4BPPV1_Format, RGBA_S3TC_DXT1_Format, RGBA_S3TC_DXT3_Format, RGBA_S3TC_DXT5_Format, RGBDepthPacking, RGBFormat, RGBIntegerFormat, RGB_BPTC_SIGNED_Format, RGB_BPTC_UNSIGNED_Format, RGB_ETC1_Format, RGB_ETC2_Format, RGB_PVRTC_2BPPV1_Format, RGB_PVRTC_4BPPV1_Format, RGB_S3TC_DXT1_Format, RGDepthPacking, RGFormat, RGIntegerFormat, RawShaderMaterial, Ray, Raycaster, RectAreaLight, RedFormat, RedIntegerFormat, ReinhardToneMapping, RenderTarget, RenderTarget3D, RepeatWrapping, ReplaceStencilOp, ReverseSubtractEquation, RingGeometry, SIGNED_RED_GREEN_RGTC2_Format, SIGNED_RED_RGTC1_Format, SRGBColorSpace, SRGBTransfer, Scene, ShaderMaterial, ShadowMaterial, Shape, ShapeGeometry, ShapePath, ShapeUtils, ShortType, Skeleton, SkeletonHelper, SkinnedMesh, Source, Sphere, SphereGeometry, Spherical, SphericalHarmonics3, SplineCurve, SpotLight, SpotLightHelper, Sprite, SpriteMaterial, SrcAlphaFactor, SrcAlphaSaturateFactor, SrcColorFactor, StaticCopyUsage, StaticDrawUsage, StaticReadUsage, StereoCamera, StreamCopyUsage, StreamDrawUsage, StreamReadUsage, StringKeyframeTrack, SubtractEquation, SubtractiveBlending, TOUCH, TangentSpaceNormalMap, TetrahedronGeometry, Texture, TextureLoader, TextureUtils, 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号