three.core.js 1.3 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748317493175031751317523175331754317553175631757317583175931760317613176231763317643176531766317673176831769317703177131772317733177431775317763177731778317793178031781317823178331784317853178631787317883178931790317913179231793317943179531796317973179831799318003180131802318033180431805318063180731808318093181031811318123181331814318153181631817318183181931820318213182231823318243182531826318273182831829318303183131832318333183431835318363183731838318393184031841318423184331844318453184631847318483184931850318513185231853318543185531856318573185831859318603186131862318633186431865318663186731868318693187031871318723187331874318753187631877318783187931880318813188231883318843188531886318873188831889318903189131892318933189431895318963189731898318993190031901319023190331904319053190631907319083190931910319113191231913319143191531916319173191831919319203192131922319233192431925319263192731928319293193031931319323193331934319353193631937319383193931940319413194231943319443194531946319473194831949319503195131952319533195431955319563195731958319593196031961319623196331964319653196631967319683196931970319713197231973319743197531976319773197831979319803198131982319833198431985319863198731988319893199031991319923199331994319953199631997319983199932000320013200232003320043200532006320073200832009320103201132012320133201432015320163201732018320193202032021320223202332024320253202632027320283202932030320313203232033320343203532036320373203832039320403204132042320433204432045320463204732048320493205032051320523205332054320553205632057320583205932060320613206232063320643206532066320673206832069320703207132072320733207432075320763207732078320793208032081320823208332084320853208632087320883208932090320913209232093320943209532096320973209832099321003210132102321033210432105321063210732108321093211032111321123211332114321153211632117321183211932120321213212232123321243212532126321273212832129321303213132132321333213432135321363213732138321393214032141321423214332144321453214632147321483214932150321513215232153321543215532156321573215832159321603216132162321633216432165321663216732168321693217032171321723217332174321753217632177321783217932180321813218232183321843218532186321873218832189321903219132192321933219432195321963219732198321993220032201322023220332204322053220632207322083220932210322113221232213322143221532216322173221832219322203222132222322233222432225322263222732228322293223032231322323223332234322353223632237322383223932240322413224232243322443224532246322473224832249322503225132252322533225432255322563225732258322593226032261322623226332264322653226632267322683226932270322713227232273322743227532276322773227832279322803228132282322833228432285322863228732288322893229032291322923229332294322953229632297322983229932300323013230232303323043230532306323073230832309323103231132312323133231432315323163231732318323193232032321323223232332324323253232632327323283232932330323313233232333323343233532336323373233832339323403234132342323433234432345323463234732348323493235032351323523235332354323553235632357323583235932360323613236232363323643236532366323673236832369323703237132372323733237432375323763237732378323793238032381323823238332384323853238632387323883238932390323913239232393323943239532396323973239832399324003240132402324033240432405324063240732408324093241032411324123241332414324153241632417324183241932420324213242232423324243242532426324273242832429324303243132432324333243432435324363243732438324393244032441324423244332444324453244632447324483244932450324513245232453324543245532456324573245832459324603246132462324633246432465324663246732468324693247032471324723247332474324753247632477324783247932480324813248232483324843248532486324873248832489324903249132492324933249432495324963249732498324993250032501325023250332504325053250632507325083250932510325113251232513325143251532516325173251832519325203252132522325233252432525325263252732528325293253032531325323253332534325353253632537325383253932540325413254232543325443254532546325473254832549325503255132552325533255432555325563255732558325593256032561325623256332564325653256632567325683256932570325713257232573325743257532576325773257832579325803258132582325833258432585325863258732588325893259032591325923259332594325953259632597325983259932600326013260232603326043260532606326073260832609326103261132612326133261432615326163261732618326193262032621326223262332624326253262632627326283262932630326313263232633326343263532636326373263832639326403264132642326433264432645326463264732648326493265032651326523265332654326553265632657326583265932660326613266232663326643266532666326673266832669326703267132672326733267432675326763267732678326793268032681326823268332684326853268632687326883268932690326913269232693326943269532696326973269832699327003270132702327033270432705327063270732708327093271032711327123271332714327153271632717327183271932720327213272232723327243272532726327273272832729327303273132732327333273432735327363273732738327393274032741327423274332744327453274632747327483274932750327513275232753327543275532756327573275832759327603276132762327633276432765327663276732768327693277032771327723277332774327753277632777327783277932780327813278232783327843278532786327873278832789327903279132792327933279432795327963279732798327993280032801328023280332804328053280632807328083280932810328113281232813328143281532816328173281832819328203282132822328233282432825328263282732828328293283032831328323283332834328353283632837328383283932840328413284232843328443284532846328473284832849328503285132852328533285432855328563285732858328593286032861328623286332864328653286632867328683286932870328713287232873328743287532876328773287832879328803288132882328833288432885328863288732888328893289032891328923289332894328953289632897328983289932900329013290232903329043290532906329073290832909329103291132912329133291432915329163291732918329193292032921329223292332924329253292632927329283292932930329313293232933329343293532936329373293832939329403294132942329433294432945329463294732948329493295032951329523295332954329553295632957329583295932960329613296232963329643296532966329673296832969329703297132972329733297432975329763297732978329793298032981329823298332984329853298632987329883298932990329913299232993329943299532996329973299832999330003300133002330033300433005330063300733008330093301033011330123301333014330153301633017330183301933020330213302233023330243302533026330273302833029330303303133032330333303433035330363303733038330393304033041330423304333044330453304633047330483304933050330513305233053330543305533056330573305833059330603306133062330633306433065330663306733068330693307033071330723307333074330753307633077330783307933080330813308233083330843308533086330873308833089330903309133092330933309433095330963309733098330993310033101331023310333104331053310633107331083310933110331113311233113331143311533116331173311833119331203312133122331233312433125331263312733128331293313033131331323313333134331353313633137331383313933140331413314233143331443314533146331473314833149331503315133152331533315433155331563315733158331593316033161331623316333164331653316633167331683316933170331713317233173331743317533176331773317833179331803318133182331833318433185331863318733188331893319033191331923319333194331953319633197331983319933200332013320233203332043320533206332073320833209332103321133212332133321433215332163321733218332193322033221332223322333224332253322633227332283322933230332313323233233332343323533236332373323833239332403324133242332433324433245332463324733248332493325033251332523325333254332553325633257332583325933260332613326233263332643326533266332673326833269332703327133272332733327433275332763327733278332793328033281332823328333284332853328633287332883328933290332913329233293332943329533296332973329833299333003330133302333033330433305333063330733308333093331033311333123331333314333153331633317333183331933320333213332233323333243332533326333273332833329333303333133332333333333433335333363333733338333393334033341333423334333344333453334633347333483334933350333513335233353333543335533356333573335833359333603336133362333633336433365333663336733368333693337033371333723337333374333753337633377333783337933380333813338233383333843338533386333873338833389333903339133392333933339433395333963339733398333993340033401334023340333404334053340633407334083340933410334113341233413334143341533416334173341833419334203342133422334233342433425334263342733428334293343033431334323343333434334353343633437334383343933440334413344233443334443344533446334473344833449334503345133452334533345433455334563345733458334593346033461334623346333464334653346633467334683346933470334713347233473334743347533476334773347833479334803348133482334833348433485334863348733488334893349033491334923349333494334953349633497334983349933500335013350233503335043350533506335073350833509335103351133512335133351433515335163351733518335193352033521335223352333524335253352633527335283352933530335313353233533335343353533536335373353833539335403354133542335433354433545335463354733548335493355033551335523355333554335553355633557335583355933560335613356233563335643356533566335673356833569335703357133572335733357433575335763357733578335793358033581335823358333584335853358633587335883358933590335913359233593335943359533596335973359833599336003360133602336033360433605336063360733608336093361033611336123361333614336153361633617336183361933620336213362233623336243362533626336273362833629336303363133632336333363433635336363363733638336393364033641336423364333644336453364633647336483364933650336513365233653336543365533656336573365833659336603366133662336633366433665336663366733668336693367033671336723367333674336753367633677336783367933680336813368233683336843368533686336873368833689336903369133692336933369433695336963369733698336993370033701337023370333704337053370633707337083370933710337113371233713337143371533716337173371833719337203372133722337233372433725337263372733728337293373033731337323373333734337353373633737337383373933740337413374233743337443374533746337473374833749337503375133752337533375433755337563375733758337593376033761337623376333764337653376633767337683376933770337713377233773337743377533776337773377833779337803378133782337833378433785337863378733788337893379033791337923379333794337953379633797337983379933800338013380233803338043380533806338073380833809338103381133812338133381433815338163381733818338193382033821338223382333824338253382633827338283382933830338313383233833338343383533836338373383833839338403384133842338433384433845338463384733848338493385033851338523385333854338553385633857338583385933860338613386233863338643386533866338673386833869338703387133872338733387433875338763387733878338793388033881338823388333884338853388633887338883388933890338913389233893338943389533896338973389833899339003390133902339033390433905339063390733908339093391033911339123391333914339153391633917339183391933920339213392233923339243392533926339273392833929339303393133932339333393433935339363393733938339393394033941339423394333944339453394633947339483394933950339513395233953339543395533956339573395833959339603396133962339633396433965339663396733968339693397033971339723397333974339753397633977339783397933980339813398233983339843398533986339873398833989339903399133992339933399433995339963399733998339993400034001340023400334004340053400634007340083400934010340113401234013340143401534016340173401834019340203402134022340233402434025340263402734028340293403034031340323403334034340353403634037340383403934040340413404234043340443404534046340473404834049340503405134052340533405434055340563405734058340593406034061340623406334064340653406634067340683406934070340713407234073340743407534076340773407834079340803408134082340833408434085340863408734088340893409034091340923409334094340953409634097340983409934100341013410234103341043410534106341073410834109341103411134112341133411434115341163411734118341193412034121341223412334124341253412634127341283412934130341313413234133341343413534136341373413834139341403414134142341433414434145341463414734148341493415034151341523415334154341553415634157341583415934160341613416234163341643416534166341673416834169341703417134172341733417434175341763417734178341793418034181341823418334184341853418634187341883418934190341913419234193341943419534196341973419834199342003420134202342033420434205342063420734208342093421034211342123421334214342153421634217342183421934220342213422234223342243422534226342273422834229342303423134232342333423434235342363423734238342393424034241342423424334244342453424634247342483424934250342513425234253342543425534256342573425834259342603426134262342633426434265342663426734268342693427034271342723427334274342753427634277342783427934280342813428234283342843428534286342873428834289342903429134292342933429434295342963429734298342993430034301343023430334304343053430634307343083430934310343113431234313343143431534316343173431834319343203432134322343233432434325343263432734328343293433034331343323433334334343353433634337343383433934340343413434234343343443434534346343473434834349343503435134352343533435434355343563435734358343593436034361343623436334364343653436634367343683436934370343713437234373343743437534376343773437834379343803438134382343833438434385343863438734388343893439034391343923439334394343953439634397343983439934400344013440234403344043440534406344073440834409344103441134412344133441434415344163441734418344193442034421344223442334424344253442634427344283442934430344313443234433344343443534436344373443834439344403444134442344433444434445344463444734448344493445034451344523445334454344553445634457344583445934460344613446234463344643446534466344673446834469344703447134472344733447434475344763447734478344793448034481344823448334484344853448634487344883448934490344913449234493344943449534496344973449834499345003450134502345033450434505345063450734508345093451034511345123451334514345153451634517345183451934520345213452234523345243452534526345273452834529345303453134532345333453434535345363453734538345393454034541345423454334544345453454634547345483454934550345513455234553345543455534556345573455834559345603456134562345633456434565345663456734568345693457034571345723457334574345753457634577345783457934580345813458234583345843458534586345873458834589345903459134592345933459434595345963459734598345993460034601346023460334604346053460634607346083460934610346113461234613346143461534616346173461834619346203462134622346233462434625346263462734628346293463034631346323463334634346353463634637346383463934640346413464234643346443464534646346473464834649346503465134652346533465434655346563465734658346593466034661346623466334664346653466634667346683466934670346713467234673346743467534676346773467834679346803468134682346833468434685346863468734688346893469034691346923469334694346953469634697346983469934700347013470234703347043470534706347073470834709347103471134712347133471434715347163471734718347193472034721347223472334724347253472634727347283472934730347313473234733347343473534736347373473834739347403474134742347433474434745347463474734748347493475034751347523475334754347553475634757347583475934760347613476234763347643476534766347673476834769347703477134772347733477434775347763477734778347793478034781347823478334784347853478634787347883478934790347913479234793347943479534796347973479834799348003480134802348033480434805348063480734808348093481034811348123481334814348153481634817348183481934820348213482234823348243482534826348273482834829348303483134832348333483434835348363483734838348393484034841348423484334844348453484634847348483484934850348513485234853348543485534856348573485834859348603486134862348633486434865348663486734868348693487034871348723487334874348753487634877348783487934880348813488234883348843488534886348873488834889348903489134892348933489434895348963489734898348993490034901349023490334904349053490634907349083490934910349113491234913349143491534916349173491834919349203492134922349233492434925349263492734928349293493034931349323493334934349353493634937349383493934940349413494234943349443494534946349473494834949349503495134952349533495434955349563495734958349593496034961349623496334964349653496634967349683496934970349713497234973349743497534976349773497834979349803498134982349833498434985349863498734988349893499034991349923499334994349953499634997349983499935000350013500235003350043500535006350073500835009350103501135012350133501435015350163501735018350193502035021350223502335024350253502635027350283502935030350313503235033350343503535036350373503835039350403504135042350433504435045350463504735048350493505035051350523505335054350553505635057350583505935060350613506235063350643506535066350673506835069350703507135072350733507435075350763507735078350793508035081350823508335084350853508635087350883508935090350913509235093350943509535096350973509835099351003510135102351033510435105351063510735108351093511035111351123511335114351153511635117351183511935120351213512235123351243512535126351273512835129351303513135132351333513435135351363513735138351393514035141351423514335144351453514635147351483514935150351513515235153351543515535156351573515835159351603516135162351633516435165351663516735168351693517035171351723517335174351753517635177351783517935180351813518235183351843518535186351873518835189351903519135192351933519435195351963519735198351993520035201352023520335204352053520635207352083520935210352113521235213352143521535216352173521835219352203522135222352233522435225352263522735228352293523035231352323523335234352353523635237352383523935240352413524235243352443524535246352473524835249352503525135252352533525435255352563525735258352593526035261352623526335264352653526635267352683526935270352713527235273352743527535276352773527835279352803528135282352833528435285352863528735288352893529035291352923529335294352953529635297352983529935300353013530235303353043530535306353073530835309353103531135312353133531435315353163531735318353193532035321353223532335324353253532635327353283532935330353313533235333353343533535336353373533835339353403534135342353433534435345353463534735348353493535035351353523535335354353553535635357353583535935360353613536235363353643536535366353673536835369353703537135372353733537435375353763537735378353793538035381353823538335384353853538635387353883538935390353913539235393353943539535396353973539835399354003540135402354033540435405354063540735408354093541035411354123541335414354153541635417354183541935420354213542235423354243542535426354273542835429354303543135432354333543435435354363543735438354393544035441354423544335444354453544635447354483544935450354513545235453354543545535456354573545835459354603546135462354633546435465354663546735468354693547035471354723547335474354753547635477354783547935480354813548235483354843548535486354873548835489354903549135492354933549435495354963549735498354993550035501355023550335504355053550635507355083550935510355113551235513355143551535516355173551835519355203552135522355233552435525355263552735528355293553035531355323553335534355353553635537355383553935540355413554235543355443554535546355473554835549355503555135552355533555435555355563555735558355593556035561355623556335564355653556635567355683556935570355713557235573355743557535576355773557835579355803558135582355833558435585355863558735588355893559035591355923559335594355953559635597355983559935600356013560235603356043560535606356073560835609356103561135612356133561435615356163561735618356193562035621356223562335624356253562635627356283562935630356313563235633356343563535636356373563835639356403564135642356433564435645356463564735648356493565035651356523565335654356553565635657356583565935660356613566235663356643566535666356673566835669356703567135672356733567435675356763567735678356793568035681356823568335684356853568635687356883568935690356913569235693356943569535696356973569835699357003570135702357033570435705357063570735708357093571035711357123571335714357153571635717357183571935720357213572235723357243572535726357273572835729357303573135732357333573435735357363573735738357393574035741357423574335744357453574635747357483574935750357513575235753357543575535756357573575835759357603576135762357633576435765357663576735768357693577035771357723577335774357753577635777357783577935780357813578235783357843578535786357873578835789357903579135792357933579435795357963579735798357993580035801358023580335804358053580635807358083580935810358113581235813358143581535816358173581835819358203582135822358233582435825358263582735828358293583035831358323583335834358353583635837358383583935840358413584235843358443584535846358473584835849358503585135852358533585435855358563585735858358593586035861358623586335864358653586635867358683586935870358713587235873358743587535876358773587835879358803588135882358833588435885358863588735888358893589035891358923589335894358953589635897358983589935900359013590235903359043590535906359073590835909359103591135912359133591435915359163591735918359193592035921359223592335924359253592635927359283592935930359313593235933359343593535936359373593835939359403594135942359433594435945359463594735948359493595035951359523595335954359553595635957359583595935960359613596235963359643596535966359673596835969359703597135972359733597435975359763597735978359793598035981359823598335984359853598635987359883598935990359913599235993359943599535996359973599835999360003600136002360033600436005360063600736008360093601036011360123601336014360153601636017360183601936020360213602236023360243602536026360273602836029360303603136032360333603436035360363603736038360393604036041360423604336044360453604636047360483604936050360513605236053360543605536056360573605836059360603606136062360633606436065360663606736068360693607036071360723607336074360753607636077360783607936080360813608236083360843608536086360873608836089360903609136092360933609436095360963609736098360993610036101361023610336104361053610636107361083610936110361113611236113361143611536116361173611836119361203612136122361233612436125361263612736128361293613036131361323613336134361353613636137361383613936140361413614236143361443614536146361473614836149361503615136152361533615436155361563615736158361593616036161361623616336164361653616636167361683616936170361713617236173361743617536176361773617836179361803618136182361833618436185361863618736188361893619036191361923619336194361953619636197361983619936200362013620236203362043620536206362073620836209362103621136212362133621436215362163621736218362193622036221362223622336224362253622636227362283622936230362313623236233362343623536236362373623836239362403624136242362433624436245362463624736248362493625036251362523625336254362553625636257362583625936260362613626236263362643626536266362673626836269362703627136272362733627436275362763627736278362793628036281362823628336284362853628636287362883628936290362913629236293362943629536296362973629836299363003630136302363033630436305363063630736308363093631036311363123631336314363153631636317363183631936320363213632236323363243632536326363273632836329363303633136332363333633436335363363633736338363393634036341363423634336344363453634636347363483634936350363513635236353363543635536356363573635836359363603636136362363633636436365363663636736368363693637036371363723637336374363753637636377363783637936380363813638236383363843638536386363873638836389363903639136392363933639436395363963639736398363993640036401364023640336404364053640636407364083640936410364113641236413364143641536416364173641836419364203642136422364233642436425364263642736428364293643036431364323643336434364353643636437364383643936440364413644236443364443644536446364473644836449364503645136452364533645436455364563645736458364593646036461364623646336464364653646636467364683646936470364713647236473364743647536476364773647836479364803648136482364833648436485364863648736488364893649036491364923649336494364953649636497364983649936500365013650236503365043650536506365073650836509365103651136512365133651436515365163651736518365193652036521365223652336524365253652636527365283652936530365313653236533365343653536536365373653836539365403654136542365433654436545365463654736548365493655036551365523655336554365553655636557365583655936560365613656236563365643656536566365673656836569365703657136572365733657436575365763657736578365793658036581365823658336584365853658636587365883658936590365913659236593365943659536596365973659836599366003660136602366033660436605366063660736608366093661036611366123661336614366153661636617366183661936620366213662236623366243662536626366273662836629366303663136632366333663436635366363663736638366393664036641366423664336644366453664636647366483664936650366513665236653366543665536656366573665836659366603666136662366633666436665366663666736668366693667036671366723667336674366753667636677366783667936680366813668236683366843668536686366873668836689366903669136692366933669436695366963669736698366993670036701367023670336704367053670636707367083670936710367113671236713367143671536716367173671836719367203672136722367233672436725367263672736728367293673036731367323673336734367353673636737367383673936740367413674236743367443674536746367473674836749367503675136752367533675436755367563675736758367593676036761367623676336764367653676636767367683676936770367713677236773367743677536776367773677836779367803678136782367833678436785367863678736788367893679036791367923679336794367953679636797367983679936800368013680236803368043680536806368073680836809368103681136812368133681436815368163681736818368193682036821368223682336824368253682636827368283682936830368313683236833368343683536836368373683836839368403684136842368433684436845368463684736848368493685036851368523685336854368553685636857368583685936860368613686236863368643686536866368673686836869368703687136872368733687436875368763687736878368793688036881368823688336884368853688636887368883688936890368913689236893368943689536896368973689836899369003690136902369033690436905369063690736908369093691036911369123691336914369153691636917369183691936920369213692236923369243692536926369273692836929369303693136932369333693436935369363693736938369393694036941369423694336944369453694636947369483694936950369513695236953369543695536956369573695836959369603696136962369633696436965369663696736968369693697036971369723697336974369753697636977369783697936980369813698236983369843698536986369873698836989369903699136992369933699436995369963699736998369993700037001370023700337004370053700637007370083700937010370113701237013370143701537016370173701837019370203702137022370233702437025370263702737028370293703037031370323703337034370353703637037370383703937040370413704237043370443704537046370473704837049370503705137052370533705437055370563705737058370593706037061370623706337064370653706637067370683706937070370713707237073370743707537076370773707837079370803708137082370833708437085370863708737088370893709037091370923709337094370953709637097370983709937100371013710237103371043710537106371073710837109371103711137112371133711437115371163711737118371193712037121371223712337124371253712637127371283712937130371313713237133371343713537136371373713837139371403714137142371433714437145371463714737148371493715037151371523715337154371553715637157371583715937160371613716237163371643716537166371673716837169371703717137172371733717437175371763717737178371793718037181371823718337184371853718637187371883718937190371913719237193371943719537196371973719837199372003720137202372033720437205372063720737208372093721037211372123721337214372153721637217372183721937220372213722237223372243722537226372273722837229372303723137232372333723437235372363723737238372393724037241372423724337244372453724637247372483724937250372513725237253372543725537256372573725837259372603726137262372633726437265372663726737268372693727037271372723727337274372753727637277372783727937280372813728237283372843728537286372873728837289372903729137292372933729437295372963729737298372993730037301373023730337304373053730637307373083730937310373113731237313373143731537316373173731837319373203732137322373233732437325373263732737328373293733037331373323733337334373353733637337373383733937340373413734237343373443734537346373473734837349373503735137352373533735437355373563735737358373593736037361373623736337364373653736637367373683736937370373713737237373373743737537376373773737837379373803738137382373833738437385373863738737388373893739037391373923739337394373953739637397373983739937400374013740237403374043740537406374073740837409374103741137412374133741437415374163741737418374193742037421374223742337424374253742637427374283742937430374313743237433374343743537436374373743837439374403744137442374433744437445374463744737448374493745037451374523745337454374553745637457374583745937460374613746237463374643746537466374673746837469374703747137472374733747437475374763747737478374793748037481374823748337484374853748637487374883748937490374913749237493374943749537496374973749837499375003750137502375033750437505375063750737508375093751037511375123751337514375153751637517375183751937520375213752237523375243752537526375273752837529375303753137532375333753437535375363753737538375393754037541375423754337544375453754637547375483754937550375513755237553375543755537556375573755837559375603756137562375633756437565375663756737568375693757037571375723757337574375753757637577375783757937580375813758237583375843758537586375873758837589375903759137592375933759437595375963759737598375993760037601376023760337604376053760637607376083760937610376113761237613376143761537616376173761837619376203762137622376233762437625376263762737628376293763037631376323763337634376353763637637376383763937640376413764237643376443764537646376473764837649376503765137652376533765437655376563765737658376593766037661376623766337664376653766637667376683766937670376713767237673376743767537676376773767837679376803768137682376833768437685376863768737688376893769037691376923769337694376953769637697376983769937700377013770237703377043770537706377073770837709377103771137712377133771437715377163771737718377193772037721377223772337724377253772637727377283772937730377313773237733377343773537736377373773837739377403774137742377433774437745377463774737748377493775037751377523775337754377553775637757377583775937760377613776237763377643776537766377673776837769377703777137772377733777437775377763777737778377793778037781377823778337784377853778637787377883778937790377913779237793377943779537796377973779837799378003780137802378033780437805378063780737808378093781037811378123781337814378153781637817378183781937820378213782237823378243782537826378273782837829378303783137832378333783437835378363783737838378393784037841378423784337844378453784637847378483784937850378513785237853378543785537856378573785837859378603786137862378633786437865378663786737868378693787037871378723787337874378753787637877378783787937880378813788237883378843788537886378873788837889378903789137892378933789437895378963789737898378993790037901379023790337904379053790637907379083790937910379113791237913379143791537916379173791837919379203792137922379233792437925379263792737928379293793037931379323793337934379353793637937379383793937940379413794237943379443794537946379473794837949379503795137952379533795437955379563795737958379593796037961379623796337964379653796637967379683796937970379713797237973379743797537976379773797837979379803798137982379833798437985379863798737988379893799037991379923799337994379953799637997379983799938000380013800238003380043800538006380073800838009380103801138012380133801438015380163801738018380193802038021380223802338024380253802638027380283802938030380313803238033380343803538036380373803838039380403804138042380433804438045380463804738048380493805038051380523805338054380553805638057380583805938060380613806238063380643806538066380673806838069380703807138072380733807438075380763807738078380793808038081380823808338084380853808638087380883808938090380913809238093380943809538096380973809838099381003810138102381033810438105381063810738108381093811038111381123811338114381153811638117381183811938120381213812238123381243812538126381273812838129381303813138132381333813438135381363813738138381393814038141381423814338144381453814638147381483814938150381513815238153381543815538156381573815838159381603816138162381633816438165381663816738168381693817038171381723817338174381753817638177381783817938180381813818238183381843818538186381873818838189381903819138192381933819438195381963819738198381993820038201382023820338204382053820638207382083820938210382113821238213382143821538216382173821838219382203822138222382233822438225382263822738228382293823038231382323823338234382353823638237382383823938240382413824238243382443824538246382473824838249382503825138252382533825438255382563825738258382593826038261382623826338264382653826638267382683826938270382713827238273382743827538276382773827838279382803828138282382833828438285382863828738288382893829038291382923829338294382953829638297382983829938300383013830238303383043830538306383073830838309383103831138312383133831438315383163831738318383193832038321383223832338324383253832638327383283832938330383313833238333383343833538336383373833838339383403834138342383433834438345383463834738348383493835038351383523835338354383553835638357383583835938360383613836238363383643836538366383673836838369383703837138372383733837438375383763837738378383793838038381383823838338384383853838638387383883838938390383913839238393383943839538396383973839838399384003840138402384033840438405384063840738408384093841038411384123841338414384153841638417384183841938420384213842238423384243842538426384273842838429384303843138432384333843438435384363843738438384393844038441384423844338444384453844638447384483844938450384513845238453384543845538456384573845838459384603846138462384633846438465384663846738468384693847038471384723847338474384753847638477384783847938480384813848238483384843848538486384873848838489384903849138492384933849438495384963849738498384993850038501385023850338504385053850638507385083850938510385113851238513385143851538516385173851838519385203852138522385233852438525385263852738528385293853038531385323853338534385353853638537385383853938540385413854238543385443854538546385473854838549385503855138552385533855438555385563855738558385593856038561385623856338564385653856638567385683856938570385713857238573385743857538576385773857838579385803858138582385833858438585385863858738588385893859038591385923859338594385953859638597385983859938600386013860238603386043860538606386073860838609386103861138612386133861438615386163861738618386193862038621386223862338624386253862638627386283862938630386313863238633386343863538636386373863838639386403864138642386433864438645386463864738648386493865038651386523865338654386553865638657386583865938660386613866238663386643866538666386673866838669386703867138672386733867438675386763867738678386793868038681386823868338684386853868638687386883868938690386913869238693386943869538696386973869838699387003870138702387033870438705387063870738708387093871038711387123871338714387153871638717387183871938720387213872238723387243872538726387273872838729387303873138732387333873438735387363873738738387393874038741387423874338744387453874638747387483874938750387513875238753387543875538756387573875838759387603876138762387633876438765387663876738768387693877038771387723877338774387753877638777387783877938780387813878238783387843878538786387873878838789387903879138792387933879438795387963879738798387993880038801388023880338804388053880638807388083880938810388113881238813388143881538816388173881838819388203882138822388233882438825388263882738828388293883038831388323883338834388353883638837388383883938840388413884238843388443884538846388473884838849388503885138852388533885438855388563885738858388593886038861388623886338864388653886638867388683886938870388713887238873388743887538876388773887838879388803888138882388833888438885388863888738888388893889038891388923889338894388953889638897388983889938900389013890238903389043890538906389073890838909389103891138912389133891438915389163891738918389193892038921389223892338924389253892638927389283892938930389313893238933389343893538936389373893838939389403894138942389433894438945389463894738948389493895038951389523895338954389553895638957389583895938960389613896238963389643896538966389673896838969389703897138972389733897438975389763897738978389793898038981389823898338984389853898638987389883898938990389913899238993389943899538996389973899838999390003900139002390033900439005390063900739008390093901039011390123901339014390153901639017390183901939020390213902239023390243902539026390273902839029390303903139032390333903439035390363903739038390393904039041390423904339044390453904639047390483904939050390513905239053390543905539056390573905839059390603906139062390633906439065390663906739068390693907039071390723907339074390753907639077390783907939080390813908239083390843908539086390873908839089390903909139092390933909439095390963909739098390993910039101391023910339104391053910639107391083910939110391113911239113391143911539116391173911839119391203912139122391233912439125391263912739128391293913039131391323913339134391353913639137391383913939140391413914239143391443914539146391473914839149391503915139152391533915439155391563915739158391593916039161391623916339164391653916639167391683916939170391713917239173391743917539176391773917839179391803918139182391833918439185391863918739188391893919039191391923919339194391953919639197391983919939200392013920239203392043920539206392073920839209392103921139212392133921439215392163921739218392193922039221392223922339224392253922639227392283922939230392313923239233392343923539236392373923839239392403924139242392433924439245392463924739248392493925039251392523925339254392553925639257392583925939260392613926239263392643926539266392673926839269392703927139272392733927439275392763927739278392793928039281392823928339284392853928639287392883928939290392913929239293392943929539296392973929839299393003930139302393033930439305393063930739308393093931039311393123931339314393153931639317393183931939320393213932239323393243932539326393273932839329393303933139332393333933439335393363933739338393393934039341393423934339344393453934639347393483934939350393513935239353393543935539356393573935839359393603936139362393633936439365393663936739368393693937039371393723937339374393753937639377393783937939380393813938239383393843938539386393873938839389393903939139392393933939439395393963939739398393993940039401394023940339404394053940639407394083940939410394113941239413394143941539416394173941839419394203942139422394233942439425394263942739428394293943039431394323943339434394353943639437394383943939440394413944239443394443944539446394473944839449394503945139452394533945439455394563945739458394593946039461394623946339464394653946639467394683946939470394713947239473394743947539476394773947839479394803948139482394833948439485394863948739488394893949039491394923949339494394953949639497394983949939500395013950239503395043950539506395073950839509395103951139512395133951439515395163951739518395193952039521395223952339524395253952639527395283952939530395313953239533395343953539536395373953839539395403954139542395433954439545395463954739548395493955039551395523955339554395553955639557395583955939560395613956239563395643956539566395673956839569395703957139572395733957439575395763957739578395793958039581395823958339584395853958639587395883958939590395913959239593395943959539596395973959839599396003960139602396033960439605396063960739608396093961039611396123961339614396153961639617396183961939620396213962239623396243962539626396273962839629396303963139632396333963439635396363963739638396393964039641396423964339644396453964639647396483964939650396513965239653396543965539656396573965839659396603966139662396633966439665396663966739668396693967039671396723967339674396753967639677396783967939680396813968239683396843968539686396873968839689396903969139692396933969439695396963969739698396993970039701397023970339704397053970639707397083970939710397113971239713397143971539716397173971839719397203972139722397233972439725397263972739728397293973039731397323973339734397353973639737397383973939740397413974239743397443974539746397473974839749397503975139752397533975439755397563975739758397593976039761397623976339764397653976639767397683976939770397713977239773397743977539776397773977839779397803978139782397833978439785397863978739788397893979039791397923979339794397953979639797397983979939800398013980239803398043980539806398073980839809398103981139812398133981439815398163981739818398193982039821398223982339824398253982639827398283982939830398313983239833398343983539836398373983839839398403984139842398433984439845398463984739848398493985039851398523985339854398553985639857398583985939860398613986239863398643986539866398673986839869398703987139872398733987439875398763987739878398793988039881398823988339884398853988639887398883988939890398913989239893398943989539896398973989839899399003990139902399033990439905399063990739908399093991039911399123991339914399153991639917399183991939920399213992239923399243992539926399273992839929399303993139932399333993439935399363993739938399393994039941399423994339944399453994639947399483994939950399513995239953399543995539956399573995839959399603996139962399633996439965399663996739968399693997039971399723997339974399753997639977399783997939980399813998239983399843998539986399873998839989399903999139992399933999439995399963999739998399994000040001400024000340004400054000640007400084000940010400114001240013400144001540016400174001840019400204002140022400234002440025400264002740028400294003040031400324003340034400354003640037400384003940040400414004240043400444004540046400474004840049400504005140052400534005440055400564005740058400594006040061400624006340064400654006640067400684006940070400714007240073400744007540076400774007840079400804008140082400834008440085400864008740088400894009040091400924009340094400954009640097400984009940100401014010240103401044010540106401074010840109401104011140112401134011440115401164011740118401194012040121401224012340124401254012640127401284012940130401314013240133401344013540136401374013840139401404014140142401434014440145401464014740148401494015040151401524015340154401554015640157401584015940160401614016240163401644016540166401674016840169401704017140172401734017440175401764017740178401794018040181401824018340184401854018640187401884018940190401914019240193401944019540196401974019840199402004020140202402034020440205402064020740208402094021040211402124021340214402154021640217402184021940220402214022240223402244022540226402274022840229402304023140232402334023440235402364023740238402394024040241402424024340244402454024640247402484024940250402514025240253402544025540256402574025840259402604026140262402634026440265402664026740268402694027040271402724027340274402754027640277402784027940280402814028240283402844028540286402874028840289402904029140292402934029440295402964029740298402994030040301403024030340304403054030640307403084030940310403114031240313403144031540316403174031840319403204032140322403234032440325403264032740328403294033040331403324033340334403354033640337403384033940340403414034240343403444034540346403474034840349403504035140352403534035440355403564035740358403594036040361403624036340364403654036640367403684036940370403714037240373403744037540376403774037840379403804038140382403834038440385403864038740388403894039040391403924039340394403954039640397403984039940400404014040240403404044040540406404074040840409404104041140412404134041440415404164041740418404194042040421404224042340424404254042640427404284042940430404314043240433404344043540436404374043840439404404044140442404434044440445404464044740448404494045040451404524045340454404554045640457404584045940460404614046240463404644046540466404674046840469404704047140472404734047440475404764047740478404794048040481404824048340484404854048640487404884048940490404914049240493404944049540496404974049840499405004050140502405034050440505405064050740508405094051040511405124051340514405154051640517405184051940520405214052240523405244052540526405274052840529405304053140532405334053440535405364053740538405394054040541405424054340544405454054640547405484054940550405514055240553405544055540556405574055840559405604056140562405634056440565405664056740568405694057040571405724057340574405754057640577405784057940580405814058240583405844058540586405874058840589405904059140592405934059440595405964059740598405994060040601406024060340604406054060640607406084060940610406114061240613406144061540616406174061840619406204062140622406234062440625406264062740628406294063040631406324063340634406354063640637406384063940640406414064240643406444064540646406474064840649406504065140652406534065440655406564065740658406594066040661406624066340664406654066640667406684066940670406714067240673406744067540676406774067840679406804068140682406834068440685406864068740688406894069040691406924069340694406954069640697406984069940700407014070240703407044070540706407074070840709407104071140712407134071440715407164071740718407194072040721407224072340724407254072640727407284072940730407314073240733407344073540736407374073840739407404074140742407434074440745407464074740748407494075040751407524075340754407554075640757407584075940760407614076240763407644076540766407674076840769407704077140772407734077440775407764077740778407794078040781407824078340784407854078640787407884078940790407914079240793407944079540796407974079840799408004080140802408034080440805408064080740808408094081040811408124081340814408154081640817408184081940820408214082240823408244082540826408274082840829408304083140832408334083440835408364083740838408394084040841408424084340844408454084640847408484084940850408514085240853408544085540856408574085840859408604086140862408634086440865408664086740868408694087040871408724087340874408754087640877408784087940880408814088240883408844088540886408874088840889408904089140892408934089440895408964089740898408994090040901409024090340904409054090640907409084090940910409114091240913409144091540916409174091840919409204092140922409234092440925409264092740928409294093040931409324093340934409354093640937409384093940940409414094240943409444094540946409474094840949409504095140952409534095440955409564095740958409594096040961409624096340964409654096640967409684096940970409714097240973409744097540976409774097840979409804098140982409834098440985409864098740988409894099040991409924099340994409954099640997409984099941000410014100241003410044100541006410074100841009410104101141012410134101441015410164101741018410194102041021410224102341024410254102641027410284102941030410314103241033410344103541036410374103841039410404104141042410434104441045410464104741048410494105041051410524105341054410554105641057410584105941060410614106241063410644106541066410674106841069410704107141072410734107441075410764107741078410794108041081410824108341084410854108641087410884108941090410914109241093410944109541096410974109841099411004110141102411034110441105411064110741108411094111041111411124111341114411154111641117411184111941120411214112241123411244112541126411274112841129411304113141132411334113441135411364113741138411394114041141411424114341144411454114641147411484114941150411514115241153411544115541156411574115841159411604116141162411634116441165411664116741168411694117041171411724117341174411754117641177411784117941180411814118241183411844118541186411874118841189411904119141192411934119441195411964119741198411994120041201412024120341204412054120641207412084120941210412114121241213412144121541216412174121841219412204122141222412234122441225412264122741228412294123041231412324123341234412354123641237412384123941240412414124241243412444124541246412474124841249412504125141252412534125441255412564125741258412594126041261412624126341264412654126641267412684126941270412714127241273412744127541276412774127841279412804128141282412834128441285412864128741288412894129041291412924129341294412954129641297412984129941300413014130241303413044130541306413074130841309413104131141312413134131441315413164131741318413194132041321413224132341324413254132641327413284132941330413314133241333413344133541336413374133841339413404134141342413434134441345413464134741348413494135041351413524135341354413554135641357413584135941360413614136241363413644136541366413674136841369413704137141372413734137441375413764137741378413794138041381413824138341384413854138641387413884138941390413914139241393413944139541396413974139841399414004140141402414034140441405414064140741408414094141041411414124141341414414154141641417414184141941420414214142241423414244142541426414274142841429414304143141432414334143441435414364143741438414394144041441414424144341444414454144641447414484144941450414514145241453414544145541456414574145841459414604146141462414634146441465414664146741468414694147041471414724147341474414754147641477414784147941480414814148241483414844148541486414874148841489414904149141492414934149441495414964149741498414994150041501415024150341504415054150641507415084150941510415114151241513415144151541516415174151841519415204152141522415234152441525415264152741528415294153041531415324153341534415354153641537415384153941540415414154241543415444154541546415474154841549415504155141552415534155441555415564155741558415594156041561415624156341564415654156641567415684156941570415714157241573415744157541576415774157841579415804158141582415834158441585415864158741588415894159041591415924159341594415954159641597415984159941600416014160241603416044160541606416074160841609416104161141612416134161441615416164161741618416194162041621416224162341624416254162641627416284162941630416314163241633416344163541636416374163841639416404164141642416434164441645416464164741648416494165041651416524165341654416554165641657416584165941660416614166241663416644166541666416674166841669416704167141672416734167441675416764167741678416794168041681416824168341684416854168641687416884168941690416914169241693416944169541696416974169841699417004170141702417034170441705417064170741708417094171041711417124171341714417154171641717417184171941720417214172241723417244172541726417274172841729417304173141732417334173441735417364173741738417394174041741417424174341744417454174641747417484174941750417514175241753417544175541756417574175841759417604176141762417634176441765417664176741768417694177041771417724177341774417754177641777417784177941780417814178241783417844178541786417874178841789417904179141792417934179441795417964179741798417994180041801418024180341804418054180641807418084180941810418114181241813418144181541816418174181841819418204182141822418234182441825418264182741828418294183041831418324183341834418354183641837418384183941840418414184241843418444184541846418474184841849418504185141852418534185441855418564185741858418594186041861418624186341864418654186641867418684186941870418714187241873418744187541876418774187841879418804188141882418834188441885418864188741888418894189041891418924189341894418954189641897418984189941900419014190241903419044190541906419074190841909419104191141912419134191441915419164191741918419194192041921419224192341924419254192641927419284192941930419314193241933419344193541936419374193841939419404194141942419434194441945419464194741948419494195041951419524195341954419554195641957419584195941960419614196241963419644196541966419674196841969419704197141972419734197441975419764197741978419794198041981419824198341984419854198641987419884198941990419914199241993419944199541996419974199841999420004200142002420034200442005420064200742008420094201042011420124201342014420154201642017420184201942020420214202242023420244202542026420274202842029420304203142032420334203442035420364203742038420394204042041420424204342044420454204642047420484204942050420514205242053420544205542056420574205842059420604206142062420634206442065420664206742068420694207042071420724207342074420754207642077420784207942080420814208242083420844208542086420874208842089420904209142092420934209442095420964209742098420994210042101421024210342104421054210642107421084210942110421114211242113421144211542116421174211842119421204212142122421234212442125421264212742128421294213042131421324213342134421354213642137421384213942140421414214242143421444214542146421474214842149421504215142152421534215442155421564215742158421594216042161421624216342164421654216642167421684216942170421714217242173421744217542176421774217842179421804218142182421834218442185421864218742188421894219042191421924219342194421954219642197421984219942200422014220242203422044220542206422074220842209422104221142212422134221442215422164221742218422194222042221422224222342224422254222642227422284222942230422314223242233422344223542236422374223842239422404224142242422434224442245422464224742248422494225042251422524225342254422554225642257422584225942260422614226242263422644226542266422674226842269422704227142272422734227442275422764227742278422794228042281422824228342284422854228642287422884228942290422914229242293422944229542296422974229842299423004230142302423034230442305423064230742308423094231042311423124231342314423154231642317423184231942320423214232242323423244232542326423274232842329423304233142332423334233442335423364233742338423394234042341423424234342344423454234642347423484234942350423514235242353423544235542356423574235842359423604236142362423634236442365423664236742368423694237042371423724237342374423754237642377423784237942380423814238242383423844238542386423874238842389423904239142392423934239442395423964239742398423994240042401424024240342404424054240642407424084240942410424114241242413424144241542416424174241842419424204242142422424234242442425424264242742428424294243042431424324243342434424354243642437424384243942440424414244242443424444244542446424474244842449424504245142452424534245442455424564245742458424594246042461424624246342464424654246642467424684246942470424714247242473424744247542476424774247842479424804248142482424834248442485424864248742488424894249042491424924249342494424954249642497424984249942500425014250242503425044250542506425074250842509425104251142512425134251442515425164251742518425194252042521425224252342524425254252642527425284252942530425314253242533425344253542536425374253842539425404254142542425434254442545425464254742548425494255042551425524255342554425554255642557425584255942560425614256242563425644256542566425674256842569425704257142572425734257442575425764257742578425794258042581425824258342584425854258642587425884258942590425914259242593425944259542596425974259842599426004260142602426034260442605426064260742608426094261042611426124261342614426154261642617426184261942620426214262242623426244262542626426274262842629426304263142632426334263442635426364263742638426394264042641426424264342644426454264642647426484264942650426514265242653426544265542656426574265842659426604266142662426634266442665426664266742668426694267042671426724267342674426754267642677426784267942680426814268242683426844268542686426874268842689426904269142692426934269442695426964269742698426994270042701427024270342704427054270642707427084270942710427114271242713427144271542716427174271842719427204272142722427234272442725427264272742728427294273042731427324273342734427354273642737427384273942740427414274242743427444274542746427474274842749427504275142752427534275442755427564275742758427594276042761427624276342764427654276642767427684276942770427714277242773427744277542776427774277842779427804278142782427834278442785427864278742788427894279042791427924279342794427954279642797427984279942800428014280242803428044280542806428074280842809428104281142812428134281442815428164281742818428194282042821428224282342824428254282642827428284282942830428314283242833428344283542836428374283842839428404284142842428434284442845428464284742848428494285042851428524285342854428554285642857428584285942860428614286242863428644286542866428674286842869428704287142872428734287442875428764287742878428794288042881428824288342884428854288642887428884288942890428914289242893428944289542896428974289842899429004290142902429034290442905429064290742908429094291042911429124291342914429154291642917429184291942920429214292242923429244292542926429274292842929429304293142932429334293442935429364293742938429394294042941429424294342944429454294642947429484294942950429514295242953429544295542956429574295842959429604296142962429634296442965429664296742968429694297042971429724297342974429754297642977429784297942980429814298242983429844298542986429874298842989429904299142992429934299442995429964299742998429994300043001430024300343004430054300643007430084300943010430114301243013430144301543016430174301843019430204302143022430234302443025430264302743028430294303043031430324303343034430354303643037430384303943040430414304243043430444304543046430474304843049430504305143052430534305443055430564305743058430594306043061430624306343064430654306643067430684306943070430714307243073430744307543076430774307843079430804308143082430834308443085430864308743088430894309043091430924309343094430954309643097430984309943100431014310243103431044310543106431074310843109431104311143112431134311443115431164311743118431194312043121431224312343124431254312643127431284312943130431314313243133431344313543136431374313843139431404314143142431434314443145431464314743148431494315043151431524315343154431554315643157431584315943160431614316243163431644316543166431674316843169431704317143172431734317443175431764317743178431794318043181431824318343184431854318643187431884318943190431914319243193431944319543196431974319843199432004320143202432034320443205432064320743208432094321043211432124321343214432154321643217432184321943220432214322243223432244322543226432274322843229432304323143232432334323443235432364323743238432394324043241432424324343244432454324643247432484324943250432514325243253432544325543256432574325843259432604326143262432634326443265432664326743268432694327043271432724327343274432754327643277432784327943280432814328243283432844328543286432874328843289432904329143292432934329443295432964329743298432994330043301433024330343304433054330643307433084330943310433114331243313433144331543316433174331843319433204332143322433234332443325433264332743328433294333043331433324333343334433354333643337433384333943340433414334243343433444334543346433474334843349433504335143352433534335443355433564335743358433594336043361433624336343364433654336643367433684336943370433714337243373433744337543376433774337843379433804338143382433834338443385433864338743388433894339043391433924339343394433954339643397433984339943400434014340243403434044340543406434074340843409434104341143412434134341443415434164341743418434194342043421434224342343424434254342643427434284342943430434314343243433434344343543436434374343843439434404344143442434434344443445434464344743448434494345043451434524345343454434554345643457434584345943460434614346243463434644346543466434674346843469434704347143472434734347443475434764347743478434794348043481434824348343484434854348643487434884348943490434914349243493434944349543496434974349843499435004350143502435034350443505435064350743508435094351043511435124351343514435154351643517435184351943520435214352243523435244352543526435274352843529435304353143532435334353443535435364353743538435394354043541435424354343544435454354643547435484354943550435514355243553435544355543556435574355843559435604356143562435634356443565435664356743568435694357043571435724357343574435754357643577435784357943580435814358243583435844358543586435874358843589435904359143592435934359443595435964359743598435994360043601436024360343604436054360643607436084360943610436114361243613436144361543616436174361843619436204362143622436234362443625436264362743628436294363043631436324363343634436354363643637436384363943640436414364243643436444364543646436474364843649436504365143652436534365443655436564365743658436594366043661436624366343664436654366643667436684366943670436714367243673436744367543676436774367843679436804368143682436834368443685436864368743688436894369043691436924369343694436954369643697436984369943700437014370243703437044370543706437074370843709437104371143712437134371443715437164371743718437194372043721437224372343724437254372643727437284372943730437314373243733437344373543736437374373843739437404374143742437434374443745437464374743748437494375043751437524375343754437554375643757437584375943760437614376243763437644376543766437674376843769437704377143772437734377443775437764377743778437794378043781437824378343784437854378643787437884378943790437914379243793437944379543796437974379843799438004380143802438034380443805438064380743808438094381043811438124381343814438154381643817438184381943820438214382243823438244382543826438274382843829438304383143832438334383443835438364383743838438394384043841438424384343844438454384643847438484384943850438514385243853438544385543856438574385843859438604386143862438634386443865438664386743868438694387043871438724387343874438754387643877438784387943880438814388243883438844388543886438874388843889438904389143892438934389443895438964389743898438994390043901439024390343904439054390643907439084390943910439114391243913439144391543916439174391843919439204392143922439234392443925439264392743928439294393043931439324393343934439354393643937439384393943940439414394243943439444394543946439474394843949439504395143952439534395443955439564395743958439594396043961439624396343964439654396643967439684396943970439714397243973439744397543976439774397843979439804398143982439834398443985439864398743988439894399043991439924399343994439954399643997439984399944000440014400244003440044400544006440074400844009440104401144012440134401444015440164401744018440194402044021440224402344024440254402644027440284402944030440314403244033440344403544036440374403844039440404404144042440434404444045440464404744048440494405044051440524405344054440554405644057440584405944060440614406244063440644406544066440674406844069440704407144072440734407444075440764407744078440794408044081440824408344084440854408644087440884408944090440914409244093440944409544096440974409844099441004410144102441034410444105441064410744108441094411044111441124411344114441154411644117441184411944120441214412244123441244412544126441274412844129441304413144132441334413444135441364413744138441394414044141441424414344144441454414644147441484414944150441514415244153441544415544156441574415844159441604416144162441634416444165441664416744168441694417044171441724417344174441754417644177441784417944180441814418244183441844418544186441874418844189441904419144192441934419444195441964419744198441994420044201442024420344204442054420644207442084420944210442114421244213442144421544216442174421844219442204422144222442234422444225442264422744228442294423044231442324423344234442354423644237442384423944240442414424244243442444424544246442474424844249442504425144252442534425444255442564425744258442594426044261442624426344264442654426644267442684426944270442714427244273442744427544276442774427844279442804428144282442834428444285442864428744288442894429044291442924429344294442954429644297442984429944300443014430244303443044430544306443074430844309443104431144312443134431444315443164431744318443194432044321443224432344324443254432644327443284432944330443314433244333443344433544336443374433844339443404434144342443434434444345443464434744348443494435044351443524435344354443554435644357443584435944360443614436244363443644436544366443674436844369443704437144372443734437444375443764437744378443794438044381443824438344384443854438644387443884438944390443914439244393443944439544396443974439844399444004440144402444034440444405444064440744408444094441044411444124441344414444154441644417444184441944420444214442244423444244442544426444274442844429444304443144432444334443444435444364443744438444394444044441444424444344444444454444644447444484444944450444514445244453444544445544456444574445844459444604446144462444634446444465444664446744468444694447044471444724447344474444754447644477444784447944480444814448244483444844448544486444874448844489444904449144492444934449444495444964449744498444994450044501445024450344504445054450644507445084450944510445114451244513445144451544516445174451844519445204452144522445234452444525445264452744528445294453044531445324453344534445354453644537445384453944540445414454244543445444454544546445474454844549445504455144552445534455444555445564455744558445594456044561445624456344564445654456644567445684456944570445714457244573445744457544576445774457844579445804458144582445834458444585445864458744588445894459044591445924459344594445954459644597445984459944600446014460244603446044460544606446074460844609446104461144612446134461444615446164461744618446194462044621446224462344624446254462644627446284462944630446314463244633446344463544636446374463844639446404464144642446434464444645446464464744648446494465044651446524465344654446554465644657446584465944660446614466244663446644466544666446674466844669446704467144672446734467444675446764467744678446794468044681446824468344684446854468644687446884468944690446914469244693446944469544696446974469844699447004470144702447034470444705447064470744708447094471044711447124471344714447154471644717447184471944720447214472244723447244472544726447274472844729447304473144732447334473444735447364473744738447394474044741447424474344744447454474644747447484474944750447514475244753447544475544756447574475844759447604476144762447634476444765447664476744768447694477044771447724477344774447754477644777447784477944780447814478244783447844478544786447874478844789447904479144792447934479444795447964479744798447994480044801448024480344804448054480644807448084480944810448114481244813448144481544816448174481844819448204482144822448234482444825448264482744828448294483044831448324483344834448354483644837448384483944840448414484244843448444484544846448474484844849448504485144852448534485444855448564485744858448594486044861448624486344864448654486644867448684486944870448714487244873448744487544876448774487844879448804488144882448834488444885448864488744888448894489044891448924489344894448954489644897448984489944900449014490244903449044490544906449074490844909449104491144912449134491444915449164491744918449194492044921449224492344924449254492644927449284492944930449314493244933449344493544936449374493844939449404494144942449434494444945449464494744948449494495044951449524495344954449554495644957449584495944960449614496244963449644496544966449674496844969449704497144972449734497444975449764497744978449794498044981449824498344984449854498644987449884498944990449914499244993449944499544996449974499844999450004500145002450034500445005450064500745008450094501045011450124501345014450154501645017450184501945020450214502245023450244502545026450274502845029450304503145032450334503445035450364503745038450394504045041450424504345044450454504645047450484504945050450514505245053450544505545056450574505845059450604506145062450634506445065450664506745068450694507045071450724507345074450754507645077450784507945080450814508245083450844508545086450874508845089450904509145092450934509445095450964509745098450994510045101451024510345104451054510645107451084510945110451114511245113451144511545116451174511845119451204512145122451234512445125451264512745128451294513045131451324513345134451354513645137451384513945140451414514245143451444514545146451474514845149451504515145152451534515445155451564515745158451594516045161451624516345164451654516645167451684516945170451714517245173451744517545176451774517845179451804518145182451834518445185451864518745188451894519045191451924519345194451954519645197451984519945200452014520245203452044520545206452074520845209452104521145212452134521445215452164521745218452194522045221452224522345224452254522645227452284522945230452314523245233452344523545236452374523845239452404524145242452434524445245452464524745248452494525045251452524525345254452554525645257452584525945260452614526245263452644526545266452674526845269452704527145272452734527445275452764527745278452794528045281452824528345284452854528645287452884528945290452914529245293452944529545296452974529845299453004530145302453034530445305453064530745308453094531045311453124531345314453154531645317453184531945320453214532245323453244532545326453274532845329453304533145332453334533445335453364533745338453394534045341453424534345344453454534645347453484534945350453514535245353453544535545356453574535845359453604536145362453634536445365453664536745368453694537045371453724537345374453754537645377453784537945380453814538245383453844538545386453874538845389453904539145392453934539445395453964539745398453994540045401454024540345404454054540645407454084540945410454114541245413454144541545416454174541845419454204542145422454234542445425454264542745428454294543045431454324543345434454354543645437454384543945440454414544245443454444544545446454474544845449454504545145452454534545445455454564545745458454594546045461454624546345464454654546645467454684546945470454714547245473454744547545476454774547845479454804548145482454834548445485454864548745488454894549045491454924549345494454954549645497454984549945500455014550245503455044550545506455074550845509455104551145512455134551445515455164551745518455194552045521455224552345524455254552645527455284552945530455314553245533455344553545536455374553845539455404554145542455434554445545455464554745548455494555045551455524555345554455554555645557455584555945560455614556245563455644556545566455674556845569455704557145572455734557445575455764557745578455794558045581455824558345584455854558645587455884558945590455914559245593455944559545596455974559845599456004560145602456034560445605456064560745608456094561045611456124561345614456154561645617456184561945620456214562245623456244562545626456274562845629456304563145632456334563445635456364563745638456394564045641456424564345644456454564645647456484564945650456514565245653456544565545656456574565845659456604566145662456634566445665456664566745668456694567045671456724567345674456754567645677456784567945680456814568245683456844568545686456874568845689456904569145692456934569445695456964569745698456994570045701457024570345704457054570645707457084570945710457114571245713457144571545716457174571845719457204572145722457234572445725457264572745728457294573045731457324573345734457354573645737457384573945740457414574245743457444574545746457474574845749457504575145752457534575445755457564575745758457594576045761457624576345764457654576645767457684576945770457714577245773457744577545776457774577845779457804578145782457834578445785457864578745788457894579045791457924579345794457954579645797457984579945800458014580245803458044580545806458074580845809458104581145812458134581445815458164581745818458194582045821458224582345824458254582645827458284582945830458314583245833458344583545836458374583845839458404584145842458434584445845458464584745848458494585045851458524585345854458554585645857458584585945860458614586245863458644586545866458674586845869458704587145872458734587445875458764587745878458794588045881458824588345884458854588645887458884588945890458914589245893458944589545896458974589845899459004590145902459034590445905459064590745908459094591045911459124591345914459154591645917459184591945920459214592245923459244592545926459274592845929459304593145932459334593445935459364593745938459394594045941459424594345944459454594645947459484594945950459514595245953459544595545956459574595845959459604596145962459634596445965459664596745968459694597045971459724597345974459754597645977459784597945980459814598245983459844598545986459874598845989459904599145992459934599445995459964599745998459994600046001460024600346004460054600646007460084600946010460114601246013460144601546016460174601846019460204602146022460234602446025460264602746028460294603046031460324603346034460354603646037460384603946040460414604246043460444604546046460474604846049460504605146052460534605446055460564605746058460594606046061460624606346064460654606646067460684606946070460714607246073460744607546076460774607846079460804608146082460834608446085460864608746088460894609046091460924609346094460954609646097460984609946100461014610246103461044610546106461074610846109461104611146112461134611446115461164611746118461194612046121461224612346124461254612646127461284612946130461314613246133461344613546136461374613846139461404614146142461434614446145461464614746148461494615046151461524615346154461554615646157461584615946160461614616246163461644616546166461674616846169461704617146172461734617446175461764617746178461794618046181461824618346184461854618646187461884618946190461914619246193461944619546196461974619846199462004620146202462034620446205462064620746208462094621046211462124621346214462154621646217462184621946220462214622246223462244622546226462274622846229462304623146232462334623446235462364623746238462394624046241462424624346244462454624646247462484624946250462514625246253462544625546256462574625846259462604626146262462634626446265462664626746268462694627046271462724627346274462754627646277462784627946280462814628246283462844628546286462874628846289462904629146292462934629446295462964629746298462994630046301463024630346304463054630646307463084630946310463114631246313463144631546316463174631846319463204632146322463234632446325463264632746328463294633046331463324633346334463354633646337463384633946340463414634246343463444634546346463474634846349463504635146352463534635446355463564635746358463594636046361463624636346364463654636646367463684636946370463714637246373463744637546376463774637846379463804638146382463834638446385463864638746388463894639046391463924639346394463954639646397463984639946400464014640246403464044640546406464074640846409464104641146412464134641446415464164641746418464194642046421464224642346424464254642646427464284642946430464314643246433464344643546436464374643846439464404644146442464434644446445464464644746448464494645046451464524645346454464554645646457464584645946460464614646246463464644646546466464674646846469464704647146472464734647446475464764647746478464794648046481464824648346484464854648646487464884648946490464914649246493464944649546496464974649846499465004650146502465034650446505465064650746508465094651046511465124651346514465154651646517465184651946520465214652246523465244652546526465274652846529465304653146532465334653446535465364653746538465394654046541465424654346544465454654646547465484654946550465514655246553465544655546556465574655846559465604656146562465634656446565465664656746568465694657046571465724657346574465754657646577465784657946580465814658246583465844658546586465874658846589465904659146592465934659446595465964659746598465994660046601466024660346604466054660646607466084660946610466114661246613466144661546616466174661846619466204662146622466234662446625466264662746628466294663046631466324663346634466354663646637466384663946640466414664246643466444664546646466474664846649466504665146652466534665446655466564665746658466594666046661466624666346664466654666646667466684666946670466714667246673466744667546676466774667846679466804668146682466834668446685466864668746688466894669046691466924669346694466954669646697466984669946700467014670246703467044670546706467074670846709467104671146712467134671446715467164671746718467194672046721467224672346724467254672646727467284672946730467314673246733467344673546736467374673846739467404674146742467434674446745467464674746748467494675046751467524675346754467554675646757467584675946760467614676246763467644676546766467674676846769467704677146772467734677446775467764677746778467794678046781467824678346784467854678646787467884678946790467914679246793467944679546796467974679846799468004680146802468034680446805468064680746808468094681046811468124681346814468154681646817468184681946820468214682246823468244682546826468274682846829468304683146832468334683446835468364683746838468394684046841468424684346844468454684646847468484684946850468514685246853468544685546856468574685846859468604686146862468634686446865468664686746868468694687046871468724687346874468754687646877468784687946880468814688246883468844688546886468874688846889468904689146892468934689446895468964689746898468994690046901469024690346904469054690646907469084690946910469114691246913469144691546916469174691846919469204692146922469234692446925469264692746928469294693046931469324693346934469354693646937469384693946940469414694246943469444694546946469474694846949469504695146952469534695446955469564695746958469594696046961469624696346964469654696646967469684696946970469714697246973469744697546976469774697846979469804698146982469834698446985469864698746988469894699046991469924699346994469954699646997469984699947000470014700247003470044700547006470074700847009470104701147012470134701447015470164701747018470194702047021470224702347024470254702647027470284702947030470314703247033470344703547036470374703847039470404704147042470434704447045470464704747048470494705047051470524705347054470554705647057470584705947060470614706247063470644706547066470674706847069470704707147072470734707447075470764707747078470794708047081470824708347084470854708647087470884708947090470914709247093470944709547096470974709847099471004710147102471034710447105471064710747108471094711047111471124711347114471154711647117471184711947120471214712247123471244712547126471274712847129471304713147132471334713447135471364713747138471394714047141471424714347144471454714647147471484714947150471514715247153471544715547156471574715847159471604716147162471634716447165471664716747168471694717047171471724717347174471754717647177471784717947180471814718247183471844718547186471874718847189471904719147192471934719447195471964719747198471994720047201472024720347204472054720647207472084720947210472114721247213472144721547216472174721847219472204722147222472234722447225472264722747228472294723047231472324723347234472354723647237472384723947240472414724247243472444724547246472474724847249472504725147252472534725447255472564725747258472594726047261472624726347264472654726647267472684726947270472714727247273472744727547276472774727847279472804728147282472834728447285472864728747288472894729047291472924729347294472954729647297472984729947300473014730247303473044730547306473074730847309473104731147312473134731447315473164731747318473194732047321473224732347324473254732647327473284732947330473314733247333473344733547336473374733847339473404734147342473434734447345473464734747348473494735047351473524735347354473554735647357473584735947360473614736247363473644736547366473674736847369473704737147372473734737447375473764737747378473794738047381473824738347384473854738647387473884738947390473914739247393473944739547396473974739847399474004740147402474034740447405474064740747408474094741047411474124741347414474154741647417474184741947420474214742247423474244742547426474274742847429474304743147432474334743447435474364743747438474394744047441474424744347444474454744647447474484744947450474514745247453474544745547456474574745847459474604746147462474634746447465474664746747468474694747047471474724747347474474754747647477474784747947480474814748247483474844748547486474874748847489474904749147492474934749447495474964749747498474994750047501475024750347504475054750647507475084750947510475114751247513475144751547516475174751847519475204752147522475234752447525475264752747528475294753047531475324753347534475354753647537475384753947540475414754247543475444754547546475474754847549475504755147552475534755447555475564755747558475594756047561475624756347564475654756647567475684756947570475714757247573475744757547576475774757847579475804758147582475834758447585475864758747588475894759047591475924759347594475954759647597475984759947600476014760247603476044760547606476074760847609476104761147612476134761447615476164761747618476194762047621476224762347624476254762647627476284762947630476314763247633476344763547636476374763847639476404764147642476434764447645476464764747648476494765047651476524765347654476554765647657476584765947660476614766247663476644766547666476674766847669476704767147672476734767447675476764767747678476794768047681476824768347684476854768647687476884768947690476914769247693476944769547696476974769847699477004770147702477034770447705477064770747708477094771047711477124771347714477154771647717477184771947720477214772247723477244772547726477274772847729477304773147732477334773447735477364773747738477394774047741477424774347744477454774647747477484774947750477514775247753477544775547756477574775847759477604776147762477634776447765477664776747768477694777047771477724777347774477754777647777477784777947780477814778247783477844778547786477874778847789477904779147792477934779447795477964779747798477994780047801478024780347804478054780647807478084780947810478114781247813478144781547816478174781847819478204782147822478234782447825478264782747828478294783047831478324783347834478354783647837478384783947840478414784247843478444784547846478474784847849478504785147852478534785447855478564785747858478594786047861478624786347864478654786647867478684786947870478714787247873478744787547876478774787847879478804788147882478834788447885478864788747888478894789047891478924789347894478954789647897478984789947900479014790247903479044790547906479074790847909479104791147912479134791447915479164791747918479194792047921479224792347924479254792647927479284792947930479314793247933479344793547936479374793847939479404794147942479434794447945479464794747948479494795047951479524795347954479554795647957479584795947960479614796247963479644796547966479674796847969479704797147972479734797447975479764797747978479794798047981479824798347984479854798647987479884798947990479914799247993479944799547996479974799847999480004800148002480034800448005480064800748008480094801048011480124801348014480154801648017480184801948020480214802248023480244802548026480274802848029480304803148032480334803448035480364803748038480394804048041480424804348044480454804648047480484804948050480514805248053480544805548056480574805848059480604806148062480634806448065480664806748068480694807048071480724807348074480754807648077480784807948080480814808248083480844808548086480874808848089480904809148092480934809448095480964809748098480994810048101481024810348104481054810648107481084810948110481114811248113481144811548116481174811848119481204812148122481234812448125481264812748128481294813048131481324813348134481354813648137481384813948140481414814248143481444814548146481474814848149481504815148152481534815448155481564815748158481594816048161481624816348164481654816648167481684816948170481714817248173481744817548176481774817848179481804818148182481834818448185481864818748188481894819048191481924819348194481954819648197481984819948200482014820248203482044820548206482074820848209482104821148212482134821448215482164821748218482194822048221482224822348224482254822648227482284822948230482314823248233482344823548236482374823848239482404824148242482434824448245482464824748248482494825048251482524825348254482554825648257482584825948260482614826248263482644826548266482674826848269482704827148272482734827448275482764827748278482794828048281482824828348284482854828648287482884828948290482914829248293482944829548296482974829848299483004830148302483034830448305483064830748308483094831048311483124831348314483154831648317483184831948320483214832248323483244832548326483274832848329483304833148332483334833448335483364833748338483394834048341483424834348344483454834648347483484834948350483514835248353483544835548356483574835848359483604836148362483634836448365483664836748368483694837048371483724837348374483754837648377483784837948380483814838248383483844838548386483874838848389483904839148392483934839448395483964839748398483994840048401484024840348404484054840648407484084840948410484114841248413484144841548416484174841848419484204842148422484234842448425484264842748428484294843048431484324843348434484354843648437484384843948440484414844248443484444844548446484474844848449484504845148452484534845448455484564845748458484594846048461484624846348464484654846648467484684846948470484714847248473484744847548476484774847848479484804848148482484834848448485484864848748488484894849048491484924849348494484954849648497484984849948500485014850248503485044850548506485074850848509485104851148512485134851448515485164851748518485194852048521485224852348524485254852648527485284852948530485314853248533485344853548536485374853848539485404854148542485434854448545485464854748548485494855048551485524855348554485554855648557485584855948560485614856248563485644856548566485674856848569485704857148572485734857448575485764857748578485794858048581485824858348584485854858648587485884858948590485914859248593485944859548596485974859848599486004860148602486034860448605486064860748608486094861048611486124861348614486154861648617486184861948620486214862248623486244862548626486274862848629486304863148632486334863448635486364863748638486394864048641486424864348644486454864648647486484864948650486514865248653486544865548656486574865848659486604866148662486634866448665486664866748668486694867048671486724867348674486754867648677486784867948680486814868248683486844868548686486874868848689486904869148692486934869448695486964869748698486994870048701487024870348704487054870648707487084870948710487114871248713487144871548716487174871848719487204872148722487234872448725487264872748728487294873048731487324873348734487354873648737487384873948740487414874248743487444874548746487474874848749487504875148752487534875448755487564875748758487594876048761487624876348764487654876648767487684876948770487714877248773487744877548776487774877848779487804878148782487834878448785487864878748788487894879048791487924879348794487954879648797487984879948800488014880248803488044880548806488074880848809488104881148812488134881448815488164881748818488194882048821488224882348824488254882648827488284882948830488314883248833488344883548836488374883848839488404884148842488434884448845488464884748848488494885048851488524885348854488554885648857488584885948860488614886248863488644886548866488674886848869488704887148872488734887448875488764887748878488794888048881488824888348884488854888648887488884888948890488914889248893488944889548896488974889848899489004890148902489034890448905489064890748908489094891048911489124891348914489154891648917489184891948920489214892248923489244892548926489274892848929489304893148932489334893448935489364893748938489394894048941489424894348944489454894648947489484894948950489514895248953489544895548956489574895848959489604896148962489634896448965489664896748968489694897048971489724897348974489754897648977489784897948980489814898248983489844898548986489874898848989489904899148992489934899448995489964899748998489994900049001490024900349004490054900649007490084900949010490114901249013490144901549016490174901849019490204902149022490234902449025490264902749028490294903049031490324903349034490354903649037490384903949040490414904249043490444904549046490474904849049490504905149052490534905449055490564905749058490594906049061490624906349064490654906649067490684906949070490714907249073490744907549076490774907849079490804908149082490834908449085490864908749088490894909049091490924909349094490954909649097490984909949100491014910249103491044910549106491074910849109491104911149112491134911449115491164911749118491194912049121491224912349124491254912649127491284912949130491314913249133491344913549136491374913849139491404914149142491434914449145491464914749148491494915049151491524915349154491554915649157491584915949160491614916249163491644916549166491674916849169491704917149172491734917449175491764917749178491794918049181491824918349184491854918649187491884918949190491914919249193491944919549196491974919849199492004920149202492034920449205492064920749208492094921049211492124921349214492154921649217492184921949220492214922249223492244922549226492274922849229492304923149232492334923449235492364923749238492394924049241492424924349244492454924649247492484924949250492514925249253492544925549256492574925849259492604926149262492634926449265492664926749268492694927049271492724927349274492754927649277492784927949280492814928249283492844928549286492874928849289492904929149292492934929449295492964929749298492994930049301493024930349304493054930649307493084930949310493114931249313493144931549316493174931849319493204932149322493234932449325493264932749328493294933049331493324933349334493354933649337493384933949340493414934249343493444934549346493474934849349493504935149352493534935449355493564935749358493594936049361493624936349364493654936649367493684936949370493714937249373493744937549376493774937849379493804938149382493834938449385493864938749388493894939049391493924939349394493954939649397493984939949400494014940249403494044940549406494074940849409494104941149412494134941449415494164941749418494194942049421494224942349424494254942649427494284942949430494314943249433494344943549436494374943849439494404944149442494434944449445494464944749448494494945049451494524945349454494554945649457494584945949460494614946249463494644946549466494674946849469494704947149472494734947449475494764947749478494794948049481494824948349484494854948649487494884948949490494914949249493494944949549496494974949849499495004950149502495034950449505495064950749508495094951049511495124951349514495154951649517495184951949520495214952249523495244952549526495274952849529495304953149532495334953449535495364953749538495394954049541495424954349544495454954649547495484954949550495514955249553495544955549556495574955849559495604956149562495634956449565495664956749568495694957049571495724957349574495754957649577495784957949580495814958249583495844958549586495874958849589495904959149592495934959449595495964959749598495994960049601496024960349604496054960649607496084960949610496114961249613496144961549616496174961849619496204962149622496234962449625496264962749628496294963049631496324963349634496354963649637496384963949640496414964249643496444964549646496474964849649496504965149652496534965449655496564965749658496594966049661496624966349664496654966649667496684966949670496714967249673496744967549676496774967849679496804968149682496834968449685496864968749688496894969049691496924969349694496954969649697496984969949700497014970249703497044970549706497074970849709497104971149712497134971449715497164971749718497194972049721497224972349724497254972649727497284972949730497314973249733497344973549736497374973849739497404974149742497434974449745497464974749748497494975049751497524975349754497554975649757497584975949760497614976249763497644976549766497674976849769497704977149772497734977449775497764977749778497794978049781497824978349784497854978649787497884978949790497914979249793497944979549796497974979849799498004980149802498034980449805498064980749808498094981049811498124981349814498154981649817498184981949820498214982249823498244982549826498274982849829498304983149832498334983449835498364983749838498394984049841498424984349844498454984649847498484984949850498514985249853498544985549856498574985849859498604986149862498634986449865498664986749868498694987049871498724987349874498754987649877498784987949880498814988249883498844988549886498874988849889498904989149892498934989449895498964989749898498994990049901499024990349904499054990649907499084990949910499114991249913499144991549916499174991849919499204992149922499234992449925499264992749928499294993049931499324993349934499354993649937499384993949940499414994249943499444994549946499474994849949499504995149952499534995449955499564995749958499594996049961499624996349964499654996649967499684996949970499714997249973499744997549976499774997849979499804998149982499834998449985499864998749988499894999049991499924999349994499954999649997499984999950000500015000250003500045000550006500075000850009500105001150012500135001450015500165001750018500195002050021500225002350024500255002650027500285002950030500315003250033500345003550036500375003850039500405004150042500435004450045500465004750048500495005050051500525005350054500555005650057500585005950060500615006250063500645006550066500675006850069500705007150072500735007450075500765007750078500795008050081500825008350084500855008650087500885008950090500915009250093500945009550096500975009850099501005010150102501035010450105501065010750108501095011050111501125011350114501155011650117501185011950120501215012250123501245012550126501275012850129501305013150132501335013450135501365013750138501395014050141501425014350144501455014650147501485014950150501515015250153501545015550156501575015850159501605016150162501635016450165501665016750168501695017050171501725017350174501755017650177501785017950180501815018250183501845018550186501875018850189501905019150192501935019450195501965019750198501995020050201502025020350204502055020650207502085020950210502115021250213502145021550216502175021850219502205022150222502235022450225502265022750228502295023050231502325023350234502355023650237502385023950240502415024250243502445024550246502475024850249502505025150252502535025450255502565025750258502595026050261502625026350264502655026650267502685026950270502715027250273502745027550276502775027850279502805028150282502835028450285502865028750288502895029050291502925029350294502955029650297502985029950300503015030250303503045030550306503075030850309503105031150312503135031450315503165031750318503195032050321503225032350324503255032650327503285032950330503315033250333503345033550336503375033850339503405034150342503435034450345503465034750348503495035050351503525035350354503555035650357503585035950360503615036250363503645036550366503675036850369503705037150372503735037450375503765037750378503795038050381503825038350384503855038650387503885038950390503915039250393503945039550396503975039850399504005040150402504035040450405504065040750408504095041050411504125041350414504155041650417504185041950420504215042250423504245042550426504275042850429504305043150432504335043450435504365043750438504395044050441504425044350444504455044650447504485044950450504515045250453504545045550456504575045850459504605046150462504635046450465504665046750468504695047050471504725047350474504755047650477504785047950480504815048250483504845048550486504875048850489504905049150492504935049450495504965049750498504995050050501505025050350504505055050650507505085050950510505115051250513505145051550516505175051850519505205052150522505235052450525505265052750528505295053050531505325053350534505355053650537505385053950540505415054250543505445054550546505475054850549505505055150552505535055450555505565055750558505595056050561505625056350564505655056650567505685056950570505715057250573505745057550576505775057850579505805058150582505835058450585505865058750588505895059050591505925059350594505955059650597505985059950600506015060250603506045060550606506075060850609506105061150612506135061450615506165061750618506195062050621506225062350624506255062650627506285062950630506315063250633506345063550636506375063850639506405064150642506435064450645506465064750648506495065050651506525065350654506555065650657506585065950660506615066250663506645066550666506675066850669506705067150672506735067450675506765067750678506795068050681506825068350684506855068650687506885068950690506915069250693506945069550696506975069850699507005070150702507035070450705507065070750708507095071050711507125071350714507155071650717507185071950720507215072250723507245072550726507275072850729507305073150732507335073450735507365073750738507395074050741507425074350744507455074650747507485074950750507515075250753507545075550756507575075850759507605076150762507635076450765507665076750768507695077050771507725077350774507755077650777507785077950780507815078250783507845078550786507875078850789507905079150792507935079450795507965079750798507995080050801508025080350804508055080650807508085080950810508115081250813508145081550816508175081850819508205082150822508235082450825508265082750828508295083050831508325083350834508355083650837508385083950840508415084250843508445084550846508475084850849508505085150852508535085450855508565085750858508595086050861508625086350864508655086650867508685086950870508715087250873508745087550876508775087850879508805088150882508835088450885508865088750888508895089050891508925089350894508955089650897508985089950900509015090250903509045090550906509075090850909509105091150912509135091450915509165091750918509195092050921509225092350924509255092650927509285092950930509315093250933509345093550936509375093850939509405094150942509435094450945509465094750948509495095050951509525095350954509555095650957509585095950960509615096250963509645096550966509675096850969509705097150972509735097450975509765097750978509795098050981509825098350984509855098650987509885098950990509915099250993509945099550996509975099850999510005100151002510035100451005510065100751008510095101051011510125101351014510155101651017510185101951020510215102251023510245102551026510275102851029510305103151032510335103451035510365103751038510395104051041510425104351044510455104651047510485104951050510515105251053510545105551056510575105851059510605106151062510635106451065510665106751068510695107051071510725107351074510755107651077510785107951080510815108251083510845108551086510875108851089510905109151092510935109451095510965109751098510995110051101511025110351104511055110651107511085110951110511115111251113511145111551116511175111851119511205112151122511235112451125511265112751128511295113051131511325113351134511355113651137511385113951140511415114251143511445114551146511475114851149511505115151152511535115451155511565115751158511595116051161511625116351164511655116651167511685116951170511715117251173511745117551176511775117851179511805118151182511835118451185511865118751188511895119051191511925119351194511955119651197511985119951200512015120251203512045120551206512075120851209512105121151212512135121451215512165121751218512195122051221512225122351224512255122651227512285122951230512315123251233512345123551236512375123851239512405124151242512435124451245512465124751248512495125051251512525125351254512555125651257512585125951260512615126251263512645126551266512675126851269512705127151272512735127451275512765127751278512795128051281512825128351284512855128651287512885128951290512915129251293512945129551296512975129851299513005130151302513035130451305513065130751308513095131051311513125131351314513155131651317513185131951320513215132251323513245132551326513275132851329513305133151332513335133451335513365133751338513395134051341513425134351344513455134651347513485134951350513515135251353513545135551356513575135851359513605136151362513635136451365513665136751368513695137051371513725137351374513755137651377513785137951380513815138251383513845138551386513875138851389513905139151392513935139451395513965139751398513995140051401514025140351404514055140651407514085140951410514115141251413514145141551416514175141851419514205142151422514235142451425514265142751428514295143051431514325143351434514355143651437514385143951440514415144251443514445144551446514475144851449514505145151452514535145451455514565145751458514595146051461514625146351464514655146651467514685146951470514715147251473514745147551476514775147851479514805148151482514835148451485514865148751488514895149051491514925149351494514955149651497514985149951500515015150251503515045150551506515075150851509515105151151512515135151451515515165151751518515195152051521515225152351524515255152651527515285152951530515315153251533515345153551536515375153851539515405154151542515435154451545515465154751548515495155051551515525155351554515555155651557515585155951560515615156251563515645156551566515675156851569515705157151572515735157451575515765157751578515795158051581515825158351584515855158651587515885158951590515915159251593515945159551596515975159851599516005160151602516035160451605516065160751608516095161051611516125161351614516155161651617516185161951620516215162251623516245162551626516275162851629516305163151632516335163451635516365163751638516395164051641516425164351644516455164651647516485164951650516515165251653516545165551656516575165851659516605166151662516635166451665516665166751668516695167051671516725167351674516755167651677516785167951680516815168251683516845168551686516875168851689516905169151692516935169451695516965169751698516995170051701517025170351704517055170651707517085170951710517115171251713517145171551716517175171851719517205172151722517235172451725517265172751728517295173051731517325173351734517355173651737517385173951740517415174251743517445174551746517475174851749517505175151752517535175451755517565175751758517595176051761517625176351764517655176651767517685176951770517715177251773517745177551776517775177851779517805178151782517835178451785517865178751788517895179051791517925179351794517955179651797517985179951800518015180251803518045180551806518075180851809518105181151812518135181451815518165181751818518195182051821518225182351824518255182651827518285182951830518315183251833518345183551836518375183851839518405184151842518435184451845518465184751848518495185051851518525185351854518555185651857518585185951860518615186251863518645186551866518675186851869518705187151872518735187451875518765187751878518795188051881518825188351884518855188651887518885188951890518915189251893518945189551896518975189851899519005190151902519035190451905519065190751908519095191051911519125191351914519155191651917519185191951920519215192251923519245192551926519275192851929519305193151932519335193451935519365193751938519395194051941519425194351944519455194651947519485194951950519515195251953519545195551956519575195851959519605196151962519635196451965519665196751968519695197051971519725197351974519755197651977519785197951980519815198251983519845198551986519875198851989519905199151992519935199451995519965199751998519995200052001520025200352004520055200652007520085200952010520115201252013520145201552016520175201852019520205202152022520235202452025520265202752028520295203052031520325203352034520355203652037520385203952040520415204252043520445204552046520475204852049520505205152052520535205452055520565205752058520595206052061520625206352064520655206652067520685206952070520715207252073520745207552076520775207852079520805208152082520835208452085520865208752088520895209052091520925209352094520955209652097520985209952100521015210252103521045210552106521075210852109521105211152112521135211452115521165211752118521195212052121521225212352124521255212652127521285212952130521315213252133521345213552136521375213852139521405214152142521435214452145521465214752148521495215052151521525215352154521555215652157521585215952160521615216252163521645216552166521675216852169521705217152172521735217452175521765217752178521795218052181521825218352184521855218652187521885218952190521915219252193521945219552196521975219852199522005220152202522035220452205522065220752208522095221052211522125221352214522155221652217522185221952220522215222252223522245222552226522275222852229522305223152232522335223452235522365223752238522395224052241522425224352244522455224652247522485224952250522515225252253522545225552256522575225852259522605226152262522635226452265522665226752268522695227052271522725227352274522755227652277522785227952280522815228252283522845228552286522875228852289522905229152292522935229452295522965229752298522995230052301523025230352304523055230652307523085230952310523115231252313523145231552316523175231852319523205232152322523235232452325523265232752328523295233052331523325233352334523355233652337523385233952340523415234252343523445234552346523475234852349523505235152352523535235452355523565235752358523595236052361523625236352364523655236652367523685236952370523715237252373523745237552376523775237852379523805238152382523835238452385523865238752388523895239052391523925239352394523955239652397523985239952400524015240252403524045240552406524075240852409524105241152412524135241452415524165241752418524195242052421524225242352424524255242652427524285242952430524315243252433524345243552436524375243852439524405244152442524435244452445524465244752448524495245052451524525245352454524555245652457524585245952460524615246252463524645246552466524675246852469524705247152472524735247452475524765247752478524795248052481524825248352484524855248652487524885248952490524915249252493524945249552496524975249852499525005250152502525035250452505525065250752508525095251052511525125251352514525155251652517525185251952520525215252252523525245252552526525275252852529525305253152532525335253452535525365253752538525395254052541525425254352544525455254652547525485254952550525515255252553525545255552556525575255852559525605256152562525635256452565525665256752568525695257052571525725257352574525755257652577525785257952580525815258252583525845258552586525875258852589525905259152592525935259452595525965259752598525995260052601526025260352604526055260652607526085260952610526115261252613526145261552616526175261852619526205262152622526235262452625526265262752628526295263052631526325263352634526355263652637526385263952640526415264252643526445264552646526475264852649526505265152652526535265452655526565265752658526595266052661526625266352664526655266652667526685266952670526715267252673526745267552676526775267852679526805268152682526835268452685526865268752688526895269052691526925269352694526955269652697526985269952700527015270252703527045270552706527075270852709527105271152712527135271452715527165271752718527195272052721527225272352724527255272652727527285272952730527315273252733527345273552736527375273852739527405274152742527435274452745527465274752748527495275052751527525275352754527555275652757527585275952760527615276252763527645276552766527675276852769527705277152772527735277452775527765277752778527795278052781527825278352784527855278652787527885278952790527915279252793527945279552796527975279852799528005280152802528035280452805528065280752808528095281052811528125281352814528155281652817528185281952820528215282252823528245282552826528275282852829528305283152832528335283452835528365283752838528395284052841528425284352844528455284652847528485284952850528515285252853528545285552856528575285852859528605286152862528635286452865528665286752868528695287052871528725287352874528755287652877528785287952880528815288252883528845288552886528875288852889528905289152892528935289452895528965289752898528995290052901529025290352904529055290652907529085290952910529115291252913529145291552916529175291852919529205292152922529235292452925529265292752928529295293052931529325293352934529355293652937529385293952940529415294252943529445294552946529475294852949529505295152952529535295452955529565295752958529595296052961529625296352964529655296652967529685296952970529715297252973529745297552976529775297852979529805298152982529835298452985529865298752988529895299052991529925299352994529955299652997529985299953000530015300253003530045300553006530075300853009530105301153012530135301453015530165301753018530195302053021530225302353024530255302653027530285302953030530315303253033530345303553036530375303853039530405304153042530435304453045530465304753048530495305053051530525305353054530555305653057530585305953060530615306253063530645306553066530675306853069530705307153072530735307453075530765307753078530795308053081530825308353084530855308653087530885308953090530915309253093530945309553096530975309853099531005310153102531035310453105531065310753108531095311053111531125311353114531155311653117531185311953120531215312253123531245312553126531275312853129531305313153132531335313453135531365313753138531395314053141531425314353144531455314653147531485314953150531515315253153531545315553156531575315853159531605316153162531635316453165531665316753168531695317053171531725317353174531755317653177531785317953180531815318253183531845318553186531875318853189531905319153192531935319453195531965319753198531995320053201532025320353204532055320653207532085320953210532115321253213532145321553216532175321853219532205322153222532235322453225532265322753228532295323053231532325323353234532355323653237532385323953240532415324253243532445324553246532475324853249532505325153252532535325453255532565325753258532595326053261532625326353264532655326653267532685326953270532715327253273532745327553276532775327853279532805328153282532835328453285532865328753288532895329053291532925329353294532955329653297532985329953300533015330253303533045330553306533075330853309533105331153312533135331453315533165331753318533195332053321533225332353324533255332653327533285332953330533315333253333533345333553336533375333853339533405334153342533435334453345533465334753348533495335053351533525335353354533555335653357533585335953360533615336253363533645336553366533675336853369533705337153372533735337453375533765337753378533795338053381533825338353384533855338653387533885338953390533915339253393533945339553396533975339853399534005340153402534035340453405534065340753408534095341053411534125341353414534155341653417534185341953420534215342253423534245342553426534275342853429534305343153432534335343453435534365343753438534395344053441534425344353444534455344653447534485344953450534515345253453534545345553456534575345853459534605346153462534635346453465534665346753468534695347053471534725347353474534755347653477534785347953480534815348253483534845348553486534875348853489534905349153492534935349453495534965349753498534995350053501535025350353504535055350653507535085350953510535115351253513535145351553516535175351853519535205352153522535235352453525535265352753528535295353053531535325353353534535355353653537535385353953540535415354253543535445354553546535475354853549535505355153552535535355453555535565355753558535595356053561535625356353564535655356653567535685356953570535715357253573535745357553576535775357853579535805358153582535835358453585535865358753588535895359053591535925359353594535955359653597535985359953600536015360253603536045360553606536075360853609536105361153612536135361453615536165361753618536195362053621536225362353624536255362653627536285362953630536315363253633536345363553636536375363853639536405364153642536435364453645536465364753648536495365053651536525365353654536555365653657536585365953660536615366253663536645366553666536675366853669536705367153672536735367453675536765367753678536795368053681536825368353684536855368653687536885368953690536915369253693536945369553696536975369853699537005370153702537035370453705537065370753708537095371053711537125371353714537155371653717537185371953720537215372253723537245372553726537275372853729537305373153732537335373453735537365373753738537395374053741537425374353744537455374653747537485374953750537515375253753537545375553756537575375853759537605376153762537635376453765537665376753768537695377053771537725377353774537755377653777537785377953780537815378253783537845378553786537875378853789537905379153792537935379453795537965379753798537995380053801538025380353804538055380653807538085380953810538115381253813538145381553816538175381853819538205382153822538235382453825538265382753828538295383053831538325383353834538355383653837538385383953840538415384253843538445384553846538475384853849538505385153852538535385453855538565385753858538595386053861538625386353864538655386653867538685386953870538715387253873538745387553876538775387853879538805388153882538835388453885538865388753888538895389053891538925389353894538955389653897538985389953900539015390253903539045390553906539075390853909539105391153912539135391453915539165391753918539195392053921539225392353924539255392653927539285392953930539315393253933539345393553936539375393853939539405394153942539435394453945539465394753948539495395053951539525395353954539555395653957539585395953960539615396253963539645396553966539675396853969539705397153972539735397453975539765397753978539795398053981539825398353984539855398653987539885398953990539915399253993539945399553996539975399853999540005400154002540035400454005540065400754008540095401054011540125401354014540155401654017540185401954020540215402254023540245402554026540275402854029540305403154032540335403454035540365403754038540395404054041540425404354044540455404654047540485404954050540515405254053540545405554056540575405854059540605406154062540635406454065540665406754068540695407054071540725407354074540755407654077540785407954080540815408254083540845408554086540875408854089540905409154092540935409454095540965409754098540995410054101541025410354104541055410654107541085410954110541115411254113541145411554116541175411854119541205412154122541235412454125541265412754128541295413054131541325413354134541355413654137541385413954140541415414254143541445414554146541475414854149541505415154152541535415454155541565415754158541595416054161541625416354164541655416654167541685416954170541715417254173541745417554176541775417854179541805418154182541835418454185541865418754188541895419054191541925419354194541955419654197541985419954200542015420254203542045420554206542075420854209542105421154212542135421454215542165421754218542195422054221542225422354224542255422654227542285422954230542315423254233542345423554236542375423854239542405424154242542435424454245542465424754248542495425054251542525425354254542555425654257542585425954260542615426254263542645426554266542675426854269542705427154272542735427454275542765427754278542795428054281542825428354284542855428654287542885428954290542915429254293542945429554296542975429854299543005430154302543035430454305543065430754308543095431054311543125431354314543155431654317543185431954320543215432254323543245432554326543275432854329543305433154332543335433454335543365433754338543395434054341543425434354344543455434654347543485434954350543515435254353543545435554356543575435854359543605436154362543635436454365543665436754368543695437054371543725437354374543755437654377543785437954380543815438254383543845438554386543875438854389543905439154392543935439454395543965439754398543995440054401544025440354404544055440654407544085440954410544115441254413544145441554416544175441854419544205442154422544235442454425544265442754428544295443054431544325443354434544355443654437544385443954440544415444254443544445444554446544475444854449544505445154452544535445454455544565445754458544595446054461544625446354464544655446654467544685446954470544715447254473544745447554476544775447854479544805448154482544835448454485544865448754488544895449054491544925449354494544955449654497544985449954500545015450254503545045450554506545075450854509545105451154512545135451454515545165451754518545195452054521545225452354524545255452654527545285452954530545315453254533545345453554536545375453854539545405454154542545435454454545545465454754548545495455054551545525455354554545555455654557545585455954560545615456254563545645456554566545675456854569545705457154572545735457454575545765457754578545795458054581545825458354584545855458654587545885458954590545915459254593545945459554596545975459854599546005460154602546035460454605546065460754608546095461054611546125461354614546155461654617546185461954620546215462254623546245462554626546275462854629546305463154632546335463454635546365463754638546395464054641546425464354644546455464654647546485464954650546515465254653546545465554656546575465854659546605466154662546635466454665546665466754668546695467054671546725467354674546755467654677546785467954680546815468254683546845468554686546875468854689546905469154692546935469454695546965469754698546995470054701547025470354704547055470654707547085470954710547115471254713547145471554716547175471854719547205472154722547235472454725547265472754728547295473054731547325473354734547355473654737547385473954740547415474254743547445474554746547475474854749547505475154752547535475454755547565475754758547595476054761547625476354764547655476654767547685476954770547715477254773547745477554776547775477854779547805478154782547835478454785547865478754788547895479054791547925479354794547955479654797547985479954800548015480254803548045480554806548075480854809548105481154812548135481454815548165481754818548195482054821548225482354824548255482654827548285482954830548315483254833548345483554836548375483854839548405484154842548435484454845548465484754848548495485054851548525485354854548555485654857548585485954860548615486254863548645486554866548675486854869548705487154872548735487454875548765487754878548795488054881548825488354884548855488654887548885488954890548915489254893548945489554896548975489854899549005490154902549035490454905549065490754908549095491054911549125491354914549155491654917549185491954920549215492254923549245492554926549275492854929549305493154932549335493454935549365493754938549395494054941549425494354944549455494654947549485494954950549515495254953549545495554956549575495854959549605496154962549635496454965549665496754968549695497054971549725497354974549755497654977549785497954980549815498254983549845498554986549875498854989549905499154992549935499454995549965499754998549995500055001550025500355004550055500655007550085500955010550115501255013550145501555016550175501855019550205502155022550235502455025550265502755028550295503055031550325503355034550355503655037550385503955040550415504255043550445504555046550475504855049550505505155052550535505455055550565505755058550595506055061550625506355064550655506655067550685506955070550715507255073550745507555076550775507855079550805508155082550835508455085550865508755088550895509055091550925509355094550955509655097550985509955100551015510255103551045510555106551075510855109551105511155112551135511455115551165511755118551195512055121551225512355124551255512655127551285512955130551315513255133551345513555136551375513855139551405514155142551435514455145551465514755148551495515055151551525515355154551555515655157551585515955160551615516255163551645516555166551675516855169551705517155172551735517455175551765517755178551795518055181551825518355184551855518655187551885518955190551915519255193551945519555196551975519855199552005520155202552035520455205552065520755208552095521055211552125521355214552155521655217552185521955220552215522255223552245522555226552275522855229552305523155232552335523455235552365523755238552395524055241552425524355244552455524655247552485524955250552515525255253552545525555256552575525855259552605526155262552635526455265552665526755268552695527055271552725527355274552755527655277552785527955280552815528255283552845528555286552875528855289552905529155292552935529455295552965529755298552995530055301553025530355304553055530655307553085530955310553115531255313553145531555316553175531855319553205532155322553235532455325553265532755328553295533055331553325533355334553355533655337553385533955340553415534255343553445534555346553475534855349553505535155352553535535455355553565535755358553595536055361553625536355364553655536655367553685536955370553715537255373553745537555376553775537855379553805538155382553835538455385553865538755388553895539055391553925539355394553955539655397553985539955400554015540255403554045540555406554075540855409554105541155412554135541455415554165541755418554195542055421554225542355424554255542655427554285542955430554315543255433554345543555436554375543855439554405544155442554435544455445554465544755448554495545055451554525545355454554555545655457554585545955460554615546255463554645546555466554675546855469554705547155472554735547455475554765547755478554795548055481554825548355484554855548655487554885548955490554915549255493554945549555496554975549855499555005550155502555035550455505555065550755508555095551055511555125551355514555155551655517555185551955520555215552255523555245552555526555275552855529555305553155532555335553455535555365553755538555395554055541555425554355544555455554655547555485554955550555515555255553555545555555556555575555855559555605556155562555635556455565555665556755568555695557055571555725557355574555755557655577555785557955580555815558255583555845558555586555875558855589555905559155592555935559455595555965559755598555995560055601556025560355604556055560655607556085560955610556115561255613556145561555616556175561855619556205562155622556235562455625556265562755628556295563055631556325563355634556355563655637556385563955640556415564255643556445564555646556475564855649556505565155652556535565455655556565565755658556595566055661556625566355664556655566655667556685566955670556715567255673556745567555676556775567855679556805568155682556835568455685556865568755688556895569055691556925569355694556955569655697556985569955700557015570255703557045570555706557075570855709557105571155712557135571455715557165571755718557195572055721557225572355724557255572655727557285572955730557315573255733557345573555736557375573855739557405574155742557435574455745557465574755748557495575055751557525575355754557555575655757557585575955760557615576255763557645576555766557675576855769557705577155772557735577455775557765577755778557795578055781557825578355784557855578655787557885578955790557915579255793557945579555796557975579855799558005580155802558035580455805558065580755808558095581055811558125581355814558155581655817558185581955820558215582255823558245582555826558275582855829558305583155832558335583455835558365583755838558395584055841558425584355844558455584655847558485584955850558515585255853558545585555856558575585855859558605586155862558635586455865558665586755868558695587055871558725587355874558755587655877558785587955880558815588255883558845588555886558875588855889558905589155892558935589455895558965589755898558995590055901559025590355904559055590655907559085590955910559115591255913559145591555916559175591855919559205592155922559235592455925559265592755928559295593055931559325593355934559355593655937559385593955940559415594255943559445594555946559475594855949559505595155952559535595455955559565595755958559595596055961559625596355964559655596655967559685596955970559715597255973559745597555976559775597855979559805598155982559835598455985559865598755988559895599055991559925599355994559955599655997559985599956000560015600256003560045600556006560075600856009560105601156012560135601456015560165601756018560195602056021560225602356024560255602656027560285602956030560315603256033560345603556036560375603856039560405604156042560435604456045560465604756048560495605056051560525605356054560555605656057560585605956060560615606256063560645606556066560675606856069560705607156072560735607456075560765607756078560795608056081560825608356084560855608656087560885608956090560915609256093560945609556096560975609856099561005610156102561035610456105561065610756108561095611056111561125611356114561155611656117561185611956120561215612256123561245612556126561275612856129561305613156132561335613456135561365613756138561395614056141561425614356144561455614656147561485614956150561515615256153561545615556156561575615856159561605616156162561635616456165561665616756168561695617056171561725617356174561755617656177561785617956180561815618256183561845618556186561875618856189561905619156192561935619456195561965619756198561995620056201562025620356204562055620656207562085620956210562115621256213562145621556216562175621856219562205622156222562235622456225562265622756228562295623056231562325623356234562355623656237562385623956240562415624256243562445624556246562475624856249562505625156252562535625456255562565625756258562595626056261562625626356264562655626656267562685626956270562715627256273562745627556276562775627856279562805628156282562835628456285562865628756288562895629056291562925629356294562955629656297562985629956300563015630256303563045630556306563075630856309563105631156312563135631456315563165631756318563195632056321563225632356324563255632656327563285632956330563315633256333563345633556336563375633856339563405634156342563435634456345563465634756348563495635056351563525635356354563555635656357563585635956360563615636256363563645636556366563675636856369563705637156372563735637456375563765637756378563795638056381563825638356384563855638656387563885638956390563915639256393563945639556396563975639856399564005640156402564035640456405564065640756408564095641056411564125641356414564155641656417564185641956420564215642256423564245642556426564275642856429564305643156432564335643456435564365643756438564395644056441564425644356444564455644656447564485644956450564515645256453564545645556456564575645856459564605646156462564635646456465564665646756468564695647056471564725647356474564755647656477564785647956480564815648256483564845648556486564875648856489564905649156492564935649456495564965649756498564995650056501565025650356504565055650656507565085650956510565115651256513565145651556516565175651856519565205652156522565235652456525565265652756528565295653056531565325653356534565355653656537565385653956540565415654256543565445654556546565475654856549565505655156552565535655456555565565655756558565595656056561565625656356564565655656656567565685656956570565715657256573565745657556576565775657856579565805658156582565835658456585565865658756588565895659056591565925659356594565955659656597565985659956600566015660256603566045660556606566075660856609566105661156612566135661456615566165661756618566195662056621566225662356624566255662656627566285662956630566315663256633566345663556636566375663856639566405664156642566435664456645566465664756648566495665056651566525665356654566555665656657566585665956660566615666256663566645666556666566675666856669566705667156672566735667456675566765667756678566795668056681566825668356684566855668656687566885668956690566915669256693566945669556696566975669856699567005670156702567035670456705567065670756708567095671056711567125671356714567155671656717567185671956720567215672256723567245672556726567275672856729567305673156732567335673456735567365673756738567395674056741567425674356744567455674656747567485674956750567515675256753567545675556756567575675856759567605676156762567635676456765567665676756768567695677056771567725677356774567755677656777567785677956780567815678256783567845678556786567875678856789567905679156792567935679456795567965679756798567995680056801568025680356804568055680656807568085680956810568115681256813568145681556816568175681856819568205682156822568235682456825568265682756828568295683056831568325683356834568355683656837568385683956840568415684256843568445684556846568475684856849568505685156852568535685456855568565685756858568595686056861568625686356864568655686656867568685686956870568715687256873568745687556876568775687856879568805688156882568835688456885568865688756888568895689056891568925689356894568955689656897568985689956900569015690256903569045690556906569075690856909569105691156912569135691456915569165691756918569195692056921569225692356924569255692656927569285692956930569315693256933569345693556936569375693856939569405694156942569435694456945569465694756948569495695056951569525695356954569555695656957569585695956960569615696256963569645696556966569675696856969569705697156972569735697456975569765697756978569795698056981569825698356984569855698656987569885698956990569915699256993569945699556996569975699856999570005700157002570035700457005570065700757008570095701057011570125701357014570155701657017570185701957020570215702257023570245702557026570275702857029570305703157032570335703457035570365703757038570395704057041570425704357044570455704657047570485704957050570515705257053570545705557056570575705857059570605706157062570635706457065570665706757068570695707057071570725707357074570755707657077570785707957080570815708257083570845708557086570875708857089570905709157092570935709457095570965709757098570995710057101571025710357104571055710657107571085710957110571115711257113571145711557116571175711857119571205712157122571235712457125571265712757128571295713057131571325713357134571355713657137571385713957140571415714257143571445714557146571475714857149571505715157152571535715457155571565715757158571595716057161571625716357164571655716657167571685716957170571715717257173571745717557176571775717857179571805718157182571835718457185571865718757188571895719057191571925719357194571955719657197571985719957200572015720257203572045720557206572075720857209572105721157212572135721457215572165721757218572195722057221572225722357224572255722657227572285722957230572315723257233572345723557236572375723857239572405724157242572435724457245572465724757248572495725057251572525725357254572555725657257572585725957260572615726257263572645726557266572675726857269572705727157272572735727457275572765727757278572795728057281572825728357284572855728657287572885728957290572915729257293572945729557296572975729857299573005730157302573035730457305573065730757308573095731057311573125731357314573155731657317573185731957320573215732257323573245732557326573275732857329573305733157332573335733457335573365733757338573395734057341573425734357344573455734657347573485734957350573515735257353573545735557356573575735857359573605736157362573635736457365573665736757368573695737057371573725737357374573755737657377573785737957380573815738257383573845738557386573875738857389573905739157392573935739457395573965739757398573995740057401574025740357404574055740657407574085740957410574115741257413574145741557416574175741857419574205742157422574235742457425574265742757428574295743057431574325743357434574355743657437574385743957440574415744257443574445744557446574475744857449574505745157452574535745457455574565745757458574595746057461574625746357464574655746657467574685746957470574715747257473574745747557476574775747857479574805748157482574835748457485574865748757488574895749057491574925749357494574955749657497574985749957500575015750257503575045750557506575075750857509575105751157512575135751457515575165751757518575195752057521575225752357524575255752657527575285752957530575315753257533575345753557536575375753857539575405754157542575435754457545575465754757548575495755057551575525755357554575555755657557575585755957560575615756257563575645756557566575675756857569575705757157572575735757457575575765757757578575795758057581575825758357584575855758657587575885758957590575915759257593575945759557596575975759857599576005760157602576035760457605576065760757608576095761057611576125761357614576155761657617576185761957620576215762257623576245762557626576275762857629576305763157632576335763457635576365763757638576395764057641576425764357644576455764657647576485764957650576515765257653576545765557656576575765857659576605766157662576635766457665576665766757668576695767057671576725767357674576755767657677576785767957680576815768257683576845768557686576875768857689576905769157692576935769457695576965769757698576995770057701577025770357704577055770657707577085770957710577115771257713577145771557716577175771857719577205772157722577235772457725577265772757728577295773057731577325773357734577355773657737577385773957740577415774257743577445774557746577475774857749577505775157752577535775457755577565775757758577595776057761577625776357764577655776657767577685776957770577715777257773577745777557776577775777857779577805778157782577835778457785577865778757788577895779057791577925779357794577955779657797577985779957800578015780257803578045780557806578075780857809578105781157812578135781457815578165781757818578195782057821578225782357824578255782657827578285782957830578315783257833578345783557836578375783857839578405784157842578435784457845578465784757848578495785057851578525785357854578555785657857578585785957860578615786257863578645786557866578675786857869578705787157872578735787457875578765787757878578795788057881578825788357884578855788657887578885788957890578915789257893578945789557896578975789857899579005790157902579035790457905579065790757908579095791057911579125791357914579155791657917579185791957920579215792257923579245792557926579275792857929579305793157932579335793457935579365793757938579395794057941579425794357944579455794657947579485794957950579515795257953579545795557956579575795857959579605796157962579635796457965579665796757968579695797057971579725797357974579755797657977579785797957980579815798257983579845798557986579875798857989579905799157992579935799457995579965799757998579995800058001580025800358004580055800658007580085800958010580115801258013580145801558016580175801858019580205802158022580235802458025580265802758028580295803058031580325803358034580355803658037580385803958040580415804258043580445804558046580475804858049580505805158052580535805458055580565805758058580595806058061580625806358064580655806658067580685806958070580715807258073580745807558076580775807858079580805808158082580835808458085580865808758088580895809058091580925809358094580955809658097580985809958100581015810258103581045810558106581075810858109581105811158112581135811458115581165811758118581195812058121581225812358124581255812658127581285812958130581315813258133581345813558136581375813858139581405814158142581435814458145581465814758148581495815058151581525815358154581555815658157581585815958160581615816258163581645816558166581675816858169581705817158172581735817458175581765817758178581795818058181581825818358184581855818658187581885818958190581915819258193581945819558196581975819858199582005820158202582035820458205582065820758208582095821058211582125821358214582155821658217582185821958220582215822258223582245822558226582275822858229582305823158232582335823458235582365823758238582395824058241582425824358244582455824658247582485824958250582515825258253582545825558256582575825858259582605826158262582635826458265582665826758268582695827058271582725827358274582755827658277582785827958280582815828258283582845828558286582875828858289582905829158292582935829458295582965829758298582995830058301583025830358304583055830658307583085830958310583115831258313583145831558316583175831858319583205832158322583235832458325583265832758328583295833058331583325833358334583355833658337583385833958340583415834258343583445834558346583475834858349583505835158352583535835458355583565835758358583595836058361583625836358364583655836658367583685836958370583715837258373583745837558376583775837858379583805838158382583835838458385583865838758388583895839058391583925839358394583955839658397583985839958400584015840258403584045840558406584075840858409584105841158412584135841458415584165841758418584195842058421584225842358424584255842658427584285842958430584315843258433584345843558436584375843858439584405844158442584435844458445584465844758448584495845058451584525845358454584555845658457584585845958460584615846258463584645846558466584675846858469584705847158472584735847458475584765847758478584795848058481584825848358484584855848658487584885848958490584915849258493584945849558496584975849858499585005850158502585035850458505585065850758508585095851058511585125851358514585155851658517585185851958520585215852258523585245852558526585275852858529585305853158532585335853458535585365853758538585395854058541585425854358544585455854658547585485854958550585515855258553585545855558556585575855858559585605856158562585635856458565585665856758568585695857058571585725857358574585755857658577585785857958580585815858258583585845858558586585875858858589585905859158592585935859458595585965859758598585995860058601586025860358604586055860658607586085860958610586115861258613586145861558616586175861858619586205862158622586235862458625586265862758628586295863058631586325863358634586355863658637586385863958640586415864258643586445864558646586475864858649586505865158652586535865458655586565865758658586595866058661586625866358664586655866658667586685866958670586715867258673586745867558676586775867858679586805868158682586835868458685586865868758688586895869058691586925869358694586955869658697586985869958700587015870258703587045870558706587075870858709587105871158712587135871458715587165871758718587195872058721587225872358724587255872658727587285872958730587315873258733587345873558736587375873858739587405874158742587435874458745587465874758748587495875058751587525875358754587555875658757587585875958760587615876258763587645876558766587675876858769587705877158772587735877458775587765877758778587795878058781587825878358784587855878658787587885878958790587915879258793587945879558796587975879858799588005880158802588035880458805588065880758808588095881058811588125881358814588155881658817588185881958820588215882258823588245882558826588275882858829588305883158832588335883458835588365883758838588395884058841588425884358844588455884658847588485884958850588515885258853588545885558856588575885858859588605886158862588635886458865588665886758868588695887058871588725887358874588755887658877588785887958880588815888258883588845888558886588875888858889588905889158892588935889458895588965889758898588995890058901589025890358904589055890658907589085890958910589115891258913589145891558916589175891858919589205892158922589235892458925589265892758928589295893058931589325893358934589355893658937589385893958940589415894258943589445894558946589475894858949589505895158952589535895458955589565895758958589595896058961589625896358964589655896658967589685896958970589715897258973589745897558976589775897858979589805898158982589835898458985589865898758988589895899058991589925899358994589955899658997589985899959000590015900259003590045900559006590075900859009590105901159012590135901459015590165901759018590195902059021590225902359024590255902659027590285902959030590315903259033590345903559036590375903859039590405904159042590435904459045590465904759048590495905059051590525905359054590555905659057590585905959060590615906259063590645906559066590675906859069590705907159072590735907459075590765907759078590795908059081590825908359084590855908659087590885908959090
  1. /**
  2. * @license
  3. * Copyright 2010-2025 Three.js Authors
  4. * SPDX-License-Identifier: MIT
  5. */
  6. const REVISION = '183dev';
  7. /**
  8. * Represents mouse buttons and interaction types in context of controls.
  9. *
  10. * @type {ConstantsMouse}
  11. * @constant
  12. */
  13. const MOUSE = { LEFT: 0, MIDDLE: 1, RIGHT: 2, ROTATE: 0, DOLLY: 1, PAN: 2 };
  14. /**
  15. * Represents touch interaction types in context of controls.
  16. *
  17. * @type {ConstantsTouch}
  18. * @constant
  19. */
  20. const TOUCH = { ROTATE: 0, PAN: 1, DOLLY_PAN: 2, DOLLY_ROTATE: 3 };
  21. /**
  22. * Disables face culling.
  23. *
  24. * @type {number}
  25. * @constant
  26. */
  27. const CullFaceNone = 0;
  28. /**
  29. * Culls back faces.
  30. *
  31. * @type {number}
  32. * @constant
  33. */
  34. const CullFaceBack = 1;
  35. /**
  36. * Culls front faces.
  37. *
  38. * @type {number}
  39. * @constant
  40. */
  41. const CullFaceFront = 2;
  42. /**
  43. * Culls both front and back faces.
  44. *
  45. * @type {number}
  46. * @constant
  47. */
  48. const CullFaceFrontBack = 3;
  49. /**
  50. * Gives unfiltered shadow maps - fastest, but lowest quality.
  51. *
  52. * @type {number}
  53. * @constant
  54. */
  55. const BasicShadowMap = 0;
  56. /**
  57. * Filters shadow maps using the Percentage-Closer Filtering (PCF) algorithm.
  58. *
  59. * @type {number}
  60. * @constant
  61. */
  62. const PCFShadowMap = 1;
  63. /**
  64. * Filters shadow maps using the Percentage-Closer Filtering (PCF) algorithm with
  65. * better soft shadows especially when using low-resolution shadow maps.
  66. *
  67. * @type {number}
  68. * @constant
  69. */
  70. const PCFSoftShadowMap = 2;
  71. /**
  72. * Filters shadow maps using the Variance Shadow Map (VSM) algorithm.
  73. * When using VSMShadowMap all shadow receivers will also cast shadows.
  74. *
  75. * @type {number}
  76. * @constant
  77. */
  78. const VSMShadowMap = 3;
  79. /**
  80. * Only front faces are rendered.
  81. *
  82. * @type {number}
  83. * @constant
  84. */
  85. const FrontSide = 0;
  86. /**
  87. * Only back faces are rendered.
  88. *
  89. * @type {number}
  90. * @constant
  91. */
  92. const BackSide = 1;
  93. /**
  94. * Both front and back faces are rendered.
  95. *
  96. * @type {number}
  97. * @constant
  98. */
  99. const DoubleSide = 2;
  100. /**
  101. * No blending is performed which effectively disables
  102. * alpha transparency.
  103. *
  104. * @type {number}
  105. * @constant
  106. */
  107. const NoBlending = 0;
  108. /**
  109. * The default blending.
  110. *
  111. * @type {number}
  112. * @constant
  113. */
  114. const NormalBlending = 1;
  115. /**
  116. * Represents additive blending.
  117. *
  118. * @type {number}
  119. * @constant
  120. */
  121. const AdditiveBlending = 2;
  122. /**
  123. * Represents subtractive blending.
  124. *
  125. * @type {number}
  126. * @constant
  127. */
  128. const SubtractiveBlending = 3;
  129. /**
  130. * Represents multiply blending.
  131. *
  132. * @type {number}
  133. * @constant
  134. */
  135. const MultiplyBlending = 4;
  136. /**
  137. * Represents custom blending.
  138. *
  139. * @type {number}
  140. * @constant
  141. */
  142. const CustomBlending = 5;
  143. /**
  144. * A `source + destination` blending equation.
  145. *
  146. * @type {number}
  147. * @constant
  148. */
  149. const AddEquation = 100;
  150. /**
  151. * A `source - destination` blending equation.
  152. *
  153. * @type {number}
  154. * @constant
  155. */
  156. const SubtractEquation = 101;
  157. /**
  158. * A `destination - source` blending equation.
  159. *
  160. * @type {number}
  161. * @constant
  162. */
  163. const ReverseSubtractEquation = 102;
  164. /**
  165. * A blend equation that uses the minimum of source and destination.
  166. *
  167. * @type {number}
  168. * @constant
  169. */
  170. const MinEquation = 103;
  171. /**
  172. * A blend equation that uses the maximum of source and destination.
  173. *
  174. * @type {number}
  175. * @constant
  176. */
  177. const MaxEquation = 104;
  178. /**
  179. * Multiplies all colors by `0`.
  180. *
  181. * @type {number}
  182. * @constant
  183. */
  184. const ZeroFactor = 200;
  185. /**
  186. * Multiplies all colors by `1`.
  187. *
  188. * @type {number}
  189. * @constant
  190. */
  191. const OneFactor = 201;
  192. /**
  193. * Multiplies all colors by the source colors.
  194. *
  195. * @type {number}
  196. * @constant
  197. */
  198. const SrcColorFactor = 202;
  199. /**
  200. * Multiplies all colors by `1` minus each source color.
  201. *
  202. * @type {number}
  203. * @constant
  204. */
  205. const OneMinusSrcColorFactor = 203;
  206. /**
  207. * Multiplies all colors by the source alpha value.
  208. *
  209. * @type {number}
  210. * @constant
  211. */
  212. const SrcAlphaFactor = 204;
  213. /**
  214. * Multiplies all colors by 1 minus the source alpha value.
  215. *
  216. * @type {number}
  217. * @constant
  218. */
  219. const OneMinusSrcAlphaFactor = 205;
  220. /**
  221. * Multiplies all colors by the destination alpha value.
  222. *
  223. * @type {number}
  224. * @constant
  225. */
  226. const DstAlphaFactor = 206;
  227. /**
  228. * Multiplies all colors by `1` minus the destination alpha value.
  229. *
  230. * @type {number}
  231. * @constant
  232. */
  233. const OneMinusDstAlphaFactor = 207;
  234. /**
  235. * Multiplies all colors by the destination color.
  236. *
  237. * @type {number}
  238. * @constant
  239. */
  240. const DstColorFactor = 208;
  241. /**
  242. * Multiplies all colors by `1` minus each destination color.
  243. *
  244. * @type {number}
  245. * @constant
  246. */
  247. const OneMinusDstColorFactor = 209;
  248. /**
  249. * Multiplies the RGB colors by the smaller of either the source alpha
  250. * value or the value of `1` minus the destination alpha value. The alpha
  251. * value is multiplied by `1`.
  252. *
  253. * @type {number}
  254. * @constant
  255. */
  256. const SrcAlphaSaturateFactor = 210;
  257. /**
  258. * Multiplies all colors by a constant color.
  259. *
  260. * @type {number}
  261. * @constant
  262. */
  263. const ConstantColorFactor = 211;
  264. /**
  265. * Multiplies all colors by `1` minus a constant color.
  266. *
  267. * @type {number}
  268. * @constant
  269. */
  270. const OneMinusConstantColorFactor = 212;
  271. /**
  272. * Multiplies all colors by a constant alpha value.
  273. *
  274. * @type {number}
  275. * @constant
  276. */
  277. const ConstantAlphaFactor = 213;
  278. /**
  279. * Multiplies all colors by 1 minus a constant alpha value.
  280. *
  281. * @type {number}
  282. * @constant
  283. */
  284. const OneMinusConstantAlphaFactor = 214;
  285. /**
  286. * Never pass.
  287. *
  288. * @type {number}
  289. * @constant
  290. */
  291. const NeverDepth = 0;
  292. /**
  293. * Always pass.
  294. *
  295. * @type {number}
  296. * @constant
  297. */
  298. const AlwaysDepth = 1;
  299. /**
  300. * Pass if the incoming value is less than the depth buffer value.
  301. *
  302. * @type {number}
  303. * @constant
  304. */
  305. const LessDepth = 2;
  306. /**
  307. * Pass if the incoming value is less than or equal to the depth buffer value.
  308. *
  309. * @type {number}
  310. * @constant
  311. */
  312. const LessEqualDepth = 3;
  313. /**
  314. * Pass if the incoming value equals the depth buffer value.
  315. *
  316. * @type {number}
  317. * @constant
  318. */
  319. const EqualDepth = 4;
  320. /**
  321. * Pass if the incoming value is greater than or equal to the depth buffer value.
  322. *
  323. * @type {number}
  324. * @constant
  325. */
  326. const GreaterEqualDepth = 5;
  327. /**
  328. * Pass if the incoming value is greater than the depth buffer value.
  329. *
  330. * @type {number}
  331. * @constant
  332. */
  333. const GreaterDepth = 6;
  334. /**
  335. * Pass if the incoming value is not equal to the depth buffer value.
  336. *
  337. * @type {number}
  338. * @constant
  339. */
  340. const NotEqualDepth = 7;
  341. /**
  342. * Multiplies the environment map color with the surface color.
  343. *
  344. * @type {number}
  345. * @constant
  346. */
  347. const MultiplyOperation = 0;
  348. /**
  349. * Uses reflectivity to blend between the two colors.
  350. *
  351. * @type {number}
  352. * @constant
  353. */
  354. const MixOperation = 1;
  355. /**
  356. * Adds the two colors.
  357. *
  358. * @type {number}
  359. * @constant
  360. */
  361. const AddOperation = 2;
  362. /**
  363. * No tone mapping is applied.
  364. *
  365. * @type {number}
  366. * @constant
  367. */
  368. const NoToneMapping = 0;
  369. /**
  370. * Linear tone mapping.
  371. *
  372. * @type {number}
  373. * @constant
  374. */
  375. const LinearToneMapping = 1;
  376. /**
  377. * Reinhard tone mapping.
  378. *
  379. * @type {number}
  380. * @constant
  381. */
  382. const ReinhardToneMapping = 2;
  383. /**
  384. * Cineon tone mapping.
  385. *
  386. * @type {number}
  387. * @constant
  388. */
  389. const CineonToneMapping = 3;
  390. /**
  391. * ACES Filmic tone mapping.
  392. *
  393. * @type {number}
  394. * @constant
  395. */
  396. const ACESFilmicToneMapping = 4;
  397. /**
  398. * Custom tone mapping.
  399. *
  400. * Expects a custom implementation by modifying shader code of the material's fragment shader.
  401. *
  402. * @type {number}
  403. * @constant
  404. */
  405. const CustomToneMapping = 5;
  406. /**
  407. * AgX tone mapping.
  408. *
  409. * @type {number}
  410. * @constant
  411. */
  412. const AgXToneMapping = 6;
  413. /**
  414. * Neutral tone mapping.
  415. *
  416. * Implementation based on the Khronos 3D Commerce Group standard tone mapping.
  417. *
  418. * @type {number}
  419. * @constant
  420. */
  421. const NeutralToneMapping = 7;
  422. /**
  423. * The skinned mesh shares the same world space as the skeleton.
  424. *
  425. * @type {string}
  426. * @constant
  427. */
  428. const AttachedBindMode = 'attached';
  429. /**
  430. * The skinned mesh does not share the same world space as the skeleton.
  431. * This is useful when a skeleton is shared across multiple skinned meshes.
  432. *
  433. * @type {string}
  434. * @constant
  435. */
  436. const DetachedBindMode = 'detached';
  437. /**
  438. * Maps textures using the geometry's UV coordinates.
  439. *
  440. * @type {number}
  441. * @constant
  442. */
  443. const UVMapping = 300;
  444. /**
  445. * Reflection mapping for cube textures.
  446. *
  447. * @type {number}
  448. * @constant
  449. */
  450. const CubeReflectionMapping = 301;
  451. /**
  452. * Refraction mapping for cube textures.
  453. *
  454. * @type {number}
  455. * @constant
  456. */
  457. const CubeRefractionMapping = 302;
  458. /**
  459. * Reflection mapping for equirectangular textures.
  460. *
  461. * @type {number}
  462. * @constant
  463. */
  464. const EquirectangularReflectionMapping = 303;
  465. /**
  466. * Refraction mapping for equirectangular textures.
  467. *
  468. * @type {number}
  469. * @constant
  470. */
  471. const EquirectangularRefractionMapping = 304;
  472. /**
  473. * Reflection mapping for PMREM textures.
  474. *
  475. * @type {number}
  476. * @constant
  477. */
  478. const CubeUVReflectionMapping = 306;
  479. /**
  480. * The texture will simply repeat to infinity.
  481. *
  482. * @type {number}
  483. * @constant
  484. */
  485. const RepeatWrapping = 1000;
  486. /**
  487. * The last pixel of the texture stretches to the edge of the mesh.
  488. *
  489. * @type {number}
  490. * @constant
  491. */
  492. const ClampToEdgeWrapping = 1001;
  493. /**
  494. * The texture will repeats to infinity, mirroring on each repeat.
  495. *
  496. * @type {number}
  497. * @constant
  498. */
  499. const MirroredRepeatWrapping = 1002;
  500. /**
  501. * Returns the value of the texture element that is nearest (in Manhattan distance)
  502. * to the specified texture coordinates.
  503. *
  504. * @type {number}
  505. * @constant
  506. */
  507. const NearestFilter = 1003;
  508. /**
  509. * Chooses the mipmap that most closely matches the size of the pixel being textured
  510. * and uses the `NearestFilter` criterion (the texel nearest to the center of the pixel)
  511. * to produce a texture value.
  512. *
  513. * @type {number}
  514. * @constant
  515. */
  516. const NearestMipmapNearestFilter = 1004;
  517. const NearestMipMapNearestFilter = 1004; // legacy
  518. /**
  519. * Chooses the two mipmaps that most closely match the size of the pixel being textured and
  520. * uses the `NearestFilter` criterion to produce a texture value from each mipmap.
  521. * The final texture value is a weighted average of those two values.
  522. *
  523. * @type {number}
  524. * @constant
  525. */
  526. const NearestMipmapLinearFilter = 1005;
  527. const NearestMipMapLinearFilter = 1005; // legacy
  528. /**
  529. * Returns the weighted average of the four texture elements that are closest to the specified
  530. * texture coordinates, and can include items wrapped or repeated from other parts of a texture,
  531. * depending on the values of `wrapS` and `wrapT`, and on the exact mapping.
  532. *
  533. * @type {number}
  534. * @constant
  535. */
  536. const LinearFilter = 1006;
  537. /**
  538. * Chooses the mipmap that most closely matches the size of the pixel being textured and uses
  539. * the `LinearFilter` criterion (a weighted average of the four texels that are closest to the
  540. * center of the pixel) to produce a texture value.
  541. *
  542. * @type {number}
  543. * @constant
  544. */
  545. const LinearMipmapNearestFilter = 1007;
  546. const LinearMipMapNearestFilter = 1007; // legacy
  547. /**
  548. * Chooses the two mipmaps that most closely match the size of the pixel being textured and uses
  549. * the `LinearFilter` criterion to produce a texture value from each mipmap. The final texture value
  550. * is a weighted average of those two values.
  551. *
  552. * @type {number}
  553. * @constant
  554. */
  555. const LinearMipmapLinearFilter = 1008;
  556. const LinearMipMapLinearFilter = 1008; // legacy
  557. /**
  558. * An unsigned byte data type for textures.
  559. *
  560. * @type {number}
  561. * @constant
  562. */
  563. const UnsignedByteType = 1009;
  564. /**
  565. * A byte data type for textures.
  566. *
  567. * @type {number}
  568. * @constant
  569. */
  570. const ByteType = 1010;
  571. /**
  572. * A short data type for textures.
  573. *
  574. * @type {number}
  575. * @constant
  576. */
  577. const ShortType = 1011;
  578. /**
  579. * An unsigned short data type for textures.
  580. *
  581. * @type {number}
  582. * @constant
  583. */
  584. const UnsignedShortType = 1012;
  585. /**
  586. * An int data type for textures.
  587. *
  588. * @type {number}
  589. * @constant
  590. */
  591. const IntType = 1013;
  592. /**
  593. * An unsigned int data type for textures.
  594. *
  595. * @type {number}
  596. * @constant
  597. */
  598. const UnsignedIntType = 1014;
  599. /**
  600. * A float data type for textures.
  601. *
  602. * @type {number}
  603. * @constant
  604. */
  605. const FloatType = 1015;
  606. /**
  607. * A half float data type for textures.
  608. *
  609. * @type {number}
  610. * @constant
  611. */
  612. const HalfFloatType = 1016;
  613. /**
  614. * An unsigned short 4_4_4_4 (packed) data type for textures.
  615. *
  616. * @type {number}
  617. * @constant
  618. */
  619. const UnsignedShort4444Type = 1017;
  620. /**
  621. * An unsigned short 5_5_5_1 (packed) data type for textures.
  622. *
  623. * @type {number}
  624. * @constant
  625. */
  626. const UnsignedShort5551Type = 1018;
  627. /**
  628. * An unsigned int 24_8 data type for textures.
  629. *
  630. * @type {number}
  631. * @constant
  632. */
  633. const UnsignedInt248Type = 1020;
  634. /**
  635. * An unsigned int 5_9_9_9 (packed) data type for textures.
  636. *
  637. * @type {number}
  638. * @constant
  639. */
  640. const UnsignedInt5999Type = 35902;
  641. /**
  642. * An unsigned int 10_11_11 (packed) data type for textures.
  643. *
  644. * @type {number}
  645. * @constant
  646. */
  647. const UnsignedInt101111Type = 35899;
  648. /**
  649. * Discards the red, green and blue components and reads just the alpha component.
  650. *
  651. * @type {number}
  652. * @constant
  653. */
  654. const AlphaFormat = 1021;
  655. /**
  656. * Discards the alpha component and reads the red, green and blue component.
  657. *
  658. * @type {number}
  659. * @constant
  660. */
  661. const RGBFormat = 1022;
  662. /**
  663. * Reads the red, green, blue and alpha components.
  664. *
  665. * @type {number}
  666. * @constant
  667. */
  668. const RGBAFormat = 1023;
  669. /**
  670. * Reads each element as a single depth value, converts it to floating point, and clamps to the range `[0,1]`.
  671. *
  672. * @type {number}
  673. * @constant
  674. */
  675. const DepthFormat = 1026;
  676. /**
  677. * Reads each element is a pair of depth and stencil values. The depth component of the pair is interpreted as
  678. * in `DepthFormat`. The stencil component is interpreted based on the depth + stencil internal format.
  679. *
  680. * @type {number}
  681. * @constant
  682. */
  683. const DepthStencilFormat = 1027;
  684. /**
  685. * Discards the green, blue and alpha components and reads just the red component.
  686. *
  687. * @type {number}
  688. * @constant
  689. */
  690. const RedFormat = 1028;
  691. /**
  692. * Discards the green, blue and alpha components and reads just the red component. The texels are read as integers instead of floating point.
  693. *
  694. * @type {number}
  695. * @constant
  696. */
  697. const RedIntegerFormat = 1029;
  698. /**
  699. * Discards the alpha, and blue components and reads the red, and green components.
  700. *
  701. * @type {number}
  702. * @constant
  703. */
  704. const RGFormat = 1030;
  705. /**
  706. * Discards the alpha, and blue components and reads the red, and green components. The texels are read as integers instead of floating point.
  707. *
  708. * @type {number}
  709. * @constant
  710. */
  711. const RGIntegerFormat = 1031;
  712. /**
  713. * Discards the alpha component and reads the red, green and blue component. The texels are read as integers instead of floating point.
  714. *
  715. * @type {number}
  716. * @constant
  717. */
  718. const RGBIntegerFormat = 1032;
  719. /**
  720. * Reads the red, green, blue and alpha components. The texels are read as integers instead of floating point.
  721. *
  722. * @type {number}
  723. * @constant
  724. */
  725. const RGBAIntegerFormat = 1033;
  726. /**
  727. * A DXT1-compressed image in an RGB image format.
  728. *
  729. * @type {number}
  730. * @constant
  731. */
  732. const RGB_S3TC_DXT1_Format = 33776;
  733. /**
  734. * A DXT1-compressed image in an RGB image format with a simple on/off alpha value.
  735. *
  736. * @type {number}
  737. * @constant
  738. */
  739. const RGBA_S3TC_DXT1_Format = 33777;
  740. /**
  741. * A DXT3-compressed image in an RGBA image format. Compared to a 32-bit RGBA texture, it offers 4:1 compression.
  742. *
  743. * @type {number}
  744. * @constant
  745. */
  746. const RGBA_S3TC_DXT3_Format = 33778;
  747. /**
  748. * A DXT5-compressed image in an RGBA image format. It also provides a 4:1 compression, but differs to the DXT3
  749. * compression in how the alpha compression is done.
  750. *
  751. * @type {number}
  752. * @constant
  753. */
  754. const RGBA_S3TC_DXT5_Format = 33779;
  755. /**
  756. * PVRTC RGB compression in 4-bit mode. One block for each 4×4 pixels.
  757. *
  758. * @type {number}
  759. * @constant
  760. */
  761. const RGB_PVRTC_4BPPV1_Format = 35840;
  762. /**
  763. * PVRTC RGB compression in 2-bit mode. One block for each 8×4 pixels.
  764. *
  765. * @type {number}
  766. * @constant
  767. */
  768. const RGB_PVRTC_2BPPV1_Format = 35841;
  769. /**
  770. * PVRTC RGBA compression in 4-bit mode. One block for each 4×4 pixels.
  771. *
  772. * @type {number}
  773. * @constant
  774. */
  775. const RGBA_PVRTC_4BPPV1_Format = 35842;
  776. /**
  777. * PVRTC RGBA compression in 2-bit mode. One block for each 8×4 pixels.
  778. *
  779. * @type {number}
  780. * @constant
  781. */
  782. const RGBA_PVRTC_2BPPV1_Format = 35843;
  783. /**
  784. * ETC1 RGB format.
  785. *
  786. * @type {number}
  787. * @constant
  788. */
  789. const RGB_ETC1_Format = 36196;
  790. /**
  791. * ETC2 RGB format.
  792. *
  793. * @type {number}
  794. * @constant
  795. */
  796. const RGB_ETC2_Format = 37492;
  797. /**
  798. * ETC2 RGBA format.
  799. *
  800. * @type {number}
  801. * @constant
  802. */
  803. const RGBA_ETC2_EAC_Format = 37496;
  804. /**
  805. * EAC R11 UNORM format.
  806. *
  807. * @type {number}
  808. * @constant
  809. */
  810. const R11_EAC_Format = 37488; // 0x9270
  811. /**
  812. * EAC R11 SNORM format.
  813. *
  814. * @type {number}
  815. * @constant
  816. */
  817. const SIGNED_R11_EAC_Format = 37489; // 0x9271
  818. /**
  819. * EAC RG11 UNORM format.
  820. *
  821. * @type {number}
  822. * @constant
  823. */
  824. const RG11_EAC_Format = 37490; // 0x9272
  825. /**
  826. * EAC RG11 SNORM format.
  827. *
  828. * @type {number}
  829. * @constant
  830. */
  831. const SIGNED_RG11_EAC_Format = 37491; // 0x9273
  832. /**
  833. * ASTC RGBA 4x4 format.
  834. *
  835. * @type {number}
  836. * @constant
  837. */
  838. const RGBA_ASTC_4x4_Format = 37808;
  839. /**
  840. * ASTC RGBA 5x4 format.
  841. *
  842. * @type {number}
  843. * @constant
  844. */
  845. const RGBA_ASTC_5x4_Format = 37809;
  846. /**
  847. * ASTC RGBA 5x5 format.
  848. *
  849. * @type {number}
  850. * @constant
  851. */
  852. const RGBA_ASTC_5x5_Format = 37810;
  853. /**
  854. * ASTC RGBA 6x5 format.
  855. *
  856. * @type {number}
  857. * @constant
  858. */
  859. const RGBA_ASTC_6x5_Format = 37811;
  860. /**
  861. * ASTC RGBA 6x6 format.
  862. *
  863. * @type {number}
  864. * @constant
  865. */
  866. const RGBA_ASTC_6x6_Format = 37812;
  867. /**
  868. * ASTC RGBA 8x5 format.
  869. *
  870. * @type {number}
  871. * @constant
  872. */
  873. const RGBA_ASTC_8x5_Format = 37813;
  874. /**
  875. * ASTC RGBA 8x6 format.
  876. *
  877. * @type {number}
  878. * @constant
  879. */
  880. const RGBA_ASTC_8x6_Format = 37814;
  881. /**
  882. * ASTC RGBA 8x8 format.
  883. *
  884. * @type {number}
  885. * @constant
  886. */
  887. const RGBA_ASTC_8x8_Format = 37815;
  888. /**
  889. * ASTC RGBA 10x5 format.
  890. *
  891. * @type {number}
  892. * @constant
  893. */
  894. const RGBA_ASTC_10x5_Format = 37816;
  895. /**
  896. * ASTC RGBA 10x6 format.
  897. *
  898. * @type {number}
  899. * @constant
  900. */
  901. const RGBA_ASTC_10x6_Format = 37817;
  902. /**
  903. * ASTC RGBA 10x8 format.
  904. *
  905. * @type {number}
  906. * @constant
  907. */
  908. const RGBA_ASTC_10x8_Format = 37818;
  909. /**
  910. * ASTC RGBA 10x10 format.
  911. *
  912. * @type {number}
  913. * @constant
  914. */
  915. const RGBA_ASTC_10x10_Format = 37819;
  916. /**
  917. * ASTC RGBA 12x10 format.
  918. *
  919. * @type {number}
  920. * @constant
  921. */
  922. const RGBA_ASTC_12x10_Format = 37820;
  923. /**
  924. * ASTC RGBA 12x12 format.
  925. *
  926. * @type {number}
  927. * @constant
  928. */
  929. const RGBA_ASTC_12x12_Format = 37821;
  930. /**
  931. * BPTC RGBA format.
  932. *
  933. * @type {number}
  934. * @constant
  935. */
  936. const RGBA_BPTC_Format = 36492;
  937. /**
  938. * BPTC Signed RGB format.
  939. *
  940. * @type {number}
  941. * @constant
  942. */
  943. const RGB_BPTC_SIGNED_Format = 36494;
  944. /**
  945. * BPTC Unsigned RGB format.
  946. *
  947. * @type {number}
  948. * @constant
  949. */
  950. const RGB_BPTC_UNSIGNED_Format = 36495;
  951. /**
  952. * RGTC1 Red format.
  953. *
  954. * @type {number}
  955. * @constant
  956. */
  957. const RED_RGTC1_Format = 36283;
  958. /**
  959. * RGTC1 Signed Red format.
  960. *
  961. * @type {number}
  962. * @constant
  963. */
  964. const SIGNED_RED_RGTC1_Format = 36284;
  965. /**
  966. * RGTC2 Red Green format.
  967. *
  968. * @type {number}
  969. * @constant
  970. */
  971. const RED_GREEN_RGTC2_Format = 36285;
  972. /**
  973. * RGTC2 Signed Red Green format.
  974. *
  975. * @type {number}
  976. * @constant
  977. */
  978. const SIGNED_RED_GREEN_RGTC2_Format = 36286;
  979. /**
  980. * Animations are played once.
  981. *
  982. * @type {number}
  983. * @constant
  984. */
  985. const LoopOnce = 2200;
  986. /**
  987. * Animations are played with a chosen number of repetitions, each time jumping from
  988. * the end of the clip directly to its beginning.
  989. *
  990. * @type {number}
  991. * @constant
  992. */
  993. const LoopRepeat = 2201;
  994. /**
  995. * Animations are played with a chosen number of repetitions, alternately playing forward
  996. * and backward.
  997. *
  998. * @type {number}
  999. * @constant
  1000. */
  1001. const LoopPingPong = 2202;
  1002. /**
  1003. * Discrete interpolation mode for keyframe tracks.
  1004. *
  1005. * @type {number}
  1006. * @constant
  1007. */
  1008. const InterpolateDiscrete = 2300;
  1009. /**
  1010. * Linear interpolation mode for keyframe tracks.
  1011. *
  1012. * @type {number}
  1013. * @constant
  1014. */
  1015. const InterpolateLinear = 2301;
  1016. /**
  1017. * Smooth interpolation mode for keyframe tracks.
  1018. *
  1019. * @type {number}
  1020. * @constant
  1021. */
  1022. const InterpolateSmooth = 2302;
  1023. /**
  1024. * Zero curvature ending for animations.
  1025. *
  1026. * @type {number}
  1027. * @constant
  1028. */
  1029. const ZeroCurvatureEnding = 2400;
  1030. /**
  1031. * Zero slope ending for animations.
  1032. *
  1033. * @type {number}
  1034. * @constant
  1035. */
  1036. const ZeroSlopeEnding = 2401;
  1037. /**
  1038. * Wrap around ending for animations.
  1039. *
  1040. * @type {number}
  1041. * @constant
  1042. */
  1043. const WrapAroundEnding = 2402;
  1044. /**
  1045. * Default animation blend mode.
  1046. *
  1047. * @type {number}
  1048. * @constant
  1049. */
  1050. const NormalAnimationBlendMode = 2500;
  1051. /**
  1052. * Additive animation blend mode. Can be used to layer motions on top of
  1053. * each other to build complex performances from smaller re-usable assets.
  1054. *
  1055. * @type {number}
  1056. * @constant
  1057. */
  1058. const AdditiveAnimationBlendMode = 2501;
  1059. /**
  1060. * For every three vertices draw a single triangle.
  1061. *
  1062. * @type {number}
  1063. * @constant
  1064. */
  1065. const TrianglesDrawMode = 0;
  1066. /**
  1067. * For each vertex draw a triangle from the last three vertices.
  1068. *
  1069. * @type {number}
  1070. * @constant
  1071. */
  1072. const TriangleStripDrawMode = 1;
  1073. /**
  1074. * For each vertex draw a triangle from the first vertex and the last two vertices.
  1075. *
  1076. * @type {number}
  1077. * @constant
  1078. */
  1079. const TriangleFanDrawMode = 2;
  1080. /**
  1081. * The depth value is inverted (1.0 - z) for visualization purposes.
  1082. *
  1083. * @type {number}
  1084. * @constant
  1085. */
  1086. const BasicDepthPacking = 3200;
  1087. /**
  1088. * The depth value is packed into 32 bit RGBA.
  1089. *
  1090. * @type {number}
  1091. * @constant
  1092. */
  1093. const RGBADepthPacking = 3201;
  1094. /**
  1095. * The depth value is packed into 24 bit RGB.
  1096. *
  1097. * @type {number}
  1098. * @constant
  1099. */
  1100. const RGBDepthPacking = 3202;
  1101. /**
  1102. * The depth value is packed into 16 bit RG.
  1103. *
  1104. * @type {number}
  1105. * @constant
  1106. */
  1107. const RGDepthPacking = 3203;
  1108. /**
  1109. * Normal information is relative to the underlying surface.
  1110. *
  1111. * @type {number}
  1112. * @constant
  1113. */
  1114. const TangentSpaceNormalMap = 0;
  1115. /**
  1116. * Normal information is relative to the object orientation.
  1117. *
  1118. * @type {number}
  1119. * @constant
  1120. */
  1121. const ObjectSpaceNormalMap = 1;
  1122. // Color space string identifiers, matching CSS Color Module Level 4 and WebGPU names where available.
  1123. /**
  1124. * No color space.
  1125. *
  1126. * @type {string}
  1127. * @constant
  1128. */
  1129. const NoColorSpace = '';
  1130. /**
  1131. * sRGB color space.
  1132. *
  1133. * @type {string}
  1134. * @constant
  1135. */
  1136. const SRGBColorSpace = 'srgb';
  1137. /**
  1138. * sRGB-linear color space.
  1139. *
  1140. * @type {string}
  1141. * @constant
  1142. */
  1143. const LinearSRGBColorSpace = 'srgb-linear';
  1144. /**
  1145. * Linear transfer function.
  1146. *
  1147. * @type {string}
  1148. * @constant
  1149. */
  1150. const LinearTransfer = 'linear';
  1151. /**
  1152. * sRGB transfer function.
  1153. *
  1154. * @type {string}
  1155. * @constant
  1156. */
  1157. const SRGBTransfer = 'srgb';
  1158. /**
  1159. * No normal map packing.
  1160. *
  1161. * @type {string}
  1162. * @constant
  1163. */
  1164. const NoNormalPacking = '';
  1165. /**
  1166. * Normal RG packing.
  1167. *
  1168. * @type {string}
  1169. * @constant
  1170. */
  1171. const NormalRGPacking = 'rg';
  1172. /**
  1173. * Normal GA packing.
  1174. *
  1175. * @type {string}
  1176. * @constant
  1177. */
  1178. const NormalGAPacking = 'ga';
  1179. /**
  1180. * Sets the stencil buffer value to `0`.
  1181. *
  1182. * @type {number}
  1183. * @constant
  1184. */
  1185. const ZeroStencilOp = 0;
  1186. /**
  1187. * Keeps the current value.
  1188. *
  1189. * @type {number}
  1190. * @constant
  1191. */
  1192. const KeepStencilOp = 7680;
  1193. /**
  1194. * Sets the stencil buffer value to the specified reference value.
  1195. *
  1196. * @type {number}
  1197. * @constant
  1198. */
  1199. const ReplaceStencilOp = 7681;
  1200. /**
  1201. * Increments the current stencil buffer value. Clamps to the maximum representable unsigned value.
  1202. *
  1203. * @type {number}
  1204. * @constant
  1205. */
  1206. const IncrementStencilOp = 7682;
  1207. /**
  1208. * Decrements the current stencil buffer value. Clamps to `0`.
  1209. *
  1210. * @type {number}
  1211. * @constant
  1212. */
  1213. const DecrementStencilOp = 7683;
  1214. /**
  1215. * Increments the current stencil buffer value. Wraps stencil buffer value to zero when incrementing
  1216. * the maximum representable unsigned value.
  1217. *
  1218. * @type {number}
  1219. * @constant
  1220. */
  1221. const IncrementWrapStencilOp = 34055;
  1222. /**
  1223. * Decrements the current stencil buffer value. Wraps stencil buffer value to the maximum representable
  1224. * unsigned value when decrementing a stencil buffer value of `0`.
  1225. *
  1226. * @type {number}
  1227. * @constant
  1228. */
  1229. const DecrementWrapStencilOp = 34056;
  1230. /**
  1231. * Inverts the current stencil buffer value bitwise.
  1232. *
  1233. * @type {number}
  1234. * @constant
  1235. */
  1236. const InvertStencilOp = 5386;
  1237. /**
  1238. * Will never return true.
  1239. *
  1240. * @type {number}
  1241. * @constant
  1242. */
  1243. const NeverStencilFunc = 512;
  1244. /**
  1245. * Will return true if the stencil reference value is less than the current stencil value.
  1246. *
  1247. * @type {number}
  1248. * @constant
  1249. */
  1250. const LessStencilFunc = 513;
  1251. /**
  1252. * Will return true if the stencil reference value is equal to the current stencil value.
  1253. *
  1254. * @type {number}
  1255. * @constant
  1256. */
  1257. const EqualStencilFunc = 514;
  1258. /**
  1259. * Will return true if the stencil reference value is less than or equal to the current stencil value.
  1260. *
  1261. * @type {number}
  1262. * @constant
  1263. */
  1264. const LessEqualStencilFunc = 515;
  1265. /**
  1266. * Will return true if the stencil reference value is greater than the current stencil value.
  1267. *
  1268. * @type {number}
  1269. * @constant
  1270. */
  1271. const GreaterStencilFunc = 516;
  1272. /**
  1273. * Will return true if the stencil reference value is not equal to the current stencil value.
  1274. *
  1275. * @type {number}
  1276. * @constant
  1277. */
  1278. const NotEqualStencilFunc = 517;
  1279. /**
  1280. * Will return true if the stencil reference value is greater than or equal to the current stencil value.
  1281. *
  1282. * @type {number}
  1283. * @constant
  1284. */
  1285. const GreaterEqualStencilFunc = 518;
  1286. /**
  1287. * Will always return true.
  1288. *
  1289. * @type {number}
  1290. * @constant
  1291. */
  1292. const AlwaysStencilFunc = 519;
  1293. /**
  1294. * Never pass.
  1295. *
  1296. * @type {number}
  1297. * @constant
  1298. */
  1299. const NeverCompare = 512;
  1300. /**
  1301. * Pass if the incoming value is less than the texture value.
  1302. *
  1303. * @type {number}
  1304. * @constant
  1305. */
  1306. const LessCompare = 513;
  1307. /**
  1308. * Pass if the incoming value equals the texture value.
  1309. *
  1310. * @type {number}
  1311. * @constant
  1312. */
  1313. const EqualCompare = 514;
  1314. /**
  1315. * Pass if the incoming value is less than or equal to the texture value.
  1316. *
  1317. * @type {number}
  1318. * @constant
  1319. */
  1320. const LessEqualCompare = 515;
  1321. /**
  1322. * Pass if the incoming value is greater than the texture value.
  1323. *
  1324. * @type {number}
  1325. * @constant
  1326. */
  1327. const GreaterCompare = 516;
  1328. /**
  1329. * Pass if the incoming value is not equal to the texture value.
  1330. *
  1331. * @type {number}
  1332. * @constant
  1333. */
  1334. const NotEqualCompare = 517;
  1335. /**
  1336. * Pass if the incoming value is greater than or equal to the texture value.
  1337. *
  1338. * @type {number}
  1339. * @constant
  1340. */
  1341. const GreaterEqualCompare = 518;
  1342. /**
  1343. * Always pass.
  1344. *
  1345. * @type {number}
  1346. * @constant
  1347. */
  1348. const AlwaysCompare = 519;
  1349. /**
  1350. * The contents are intended to be specified once by the application, and used many
  1351. * times as the source for drawing and image specification commands.
  1352. *
  1353. * @type {number}
  1354. * @constant
  1355. */
  1356. const StaticDrawUsage = 35044;
  1357. /**
  1358. * The contents are intended to be respecified repeatedly by the application, and
  1359. * used many times as the source for drawing and image specification commands.
  1360. *
  1361. * @type {number}
  1362. * @constant
  1363. */
  1364. const DynamicDrawUsage = 35048;
  1365. /**
  1366. * The contents are intended to be specified once by the application, and used at most
  1367. * a few times as the source for drawing and image specification commands.
  1368. *
  1369. * @type {number}
  1370. * @constant
  1371. */
  1372. const StreamDrawUsage = 35040;
  1373. /**
  1374. * The contents are intended to be specified once by reading data from the 3D API, and queried
  1375. * many times by the application.
  1376. *
  1377. * @type {number}
  1378. * @constant
  1379. */
  1380. const StaticReadUsage = 35045;
  1381. /**
  1382. * The contents are intended to be respecified repeatedly by reading data from the 3D API, and queried
  1383. * many times by the application.
  1384. *
  1385. * @type {number}
  1386. * @constant
  1387. */
  1388. const DynamicReadUsage = 35049;
  1389. /**
  1390. * The contents are intended to be specified once by reading data from the 3D API, and queried at most
  1391. * a few times by the application
  1392. *
  1393. * @type {number}
  1394. * @constant
  1395. */
  1396. const StreamReadUsage = 35041;
  1397. /**
  1398. * The contents are intended to be specified once by reading data from the 3D API, and used many times as
  1399. * the source for WebGL drawing and image specification commands.
  1400. *
  1401. * @type {number}
  1402. * @constant
  1403. */
  1404. const StaticCopyUsage = 35046;
  1405. /**
  1406. * The contents are intended to be respecified repeatedly by reading data from the 3D API, and used many times
  1407. * as the source for WebGL drawing and image specification commands.
  1408. *
  1409. * @type {number}
  1410. * @constant
  1411. */
  1412. const DynamicCopyUsage = 35050;
  1413. /**
  1414. * The contents are intended to be specified once by reading data from the 3D API, and used at most a few times
  1415. * as the source for WebGL drawing and image specification commands.
  1416. *
  1417. * @type {number}
  1418. * @constant
  1419. */
  1420. const StreamCopyUsage = 35042;
  1421. /**
  1422. * GLSL 1 shader code.
  1423. *
  1424. * @type {string}
  1425. * @constant
  1426. */
  1427. const GLSL1 = '100';
  1428. /**
  1429. * GLSL 3 shader code.
  1430. *
  1431. * @type {string}
  1432. * @constant
  1433. */
  1434. const GLSL3 = '300 es';
  1435. /**
  1436. * WebGL coordinate system.
  1437. *
  1438. * @type {number}
  1439. * @constant
  1440. */
  1441. const WebGLCoordinateSystem = 2000;
  1442. /**
  1443. * WebGPU coordinate system.
  1444. *
  1445. * @type {number}
  1446. * @constant
  1447. */
  1448. const WebGPUCoordinateSystem = 2001;
  1449. /**
  1450. * Represents the different timestamp query types.
  1451. *
  1452. * @type {ConstantsTimestampQuery}
  1453. * @constant
  1454. */
  1455. const TimestampQuery = {
  1456. COMPUTE: 'compute',
  1457. RENDER: 'render'
  1458. };
  1459. /**
  1460. * Represents mouse buttons and interaction types in context of controls.
  1461. *
  1462. * @type {ConstantsInterpolationSamplingType}
  1463. * @constant
  1464. */
  1465. const InterpolationSamplingType = {
  1466. PERSPECTIVE: 'perspective',
  1467. LINEAR: 'linear',
  1468. FLAT: 'flat'
  1469. };
  1470. /**
  1471. * Represents the different interpolation sampling modes.
  1472. *
  1473. * @type {ConstantsInterpolationSamplingMode}
  1474. * @constant
  1475. */
  1476. const InterpolationSamplingMode = {
  1477. NORMAL: 'normal',
  1478. CENTROID: 'centroid',
  1479. SAMPLE: 'sample',
  1480. FIRST: 'first',
  1481. EITHER: 'either'
  1482. };
  1483. /**
  1484. * Compatibility flags for features that may not be supported across all platforms.
  1485. *
  1486. * @type {Object}
  1487. * @constant
  1488. */
  1489. const Compatibility = {
  1490. TEXTURE_COMPARE: 'depthTextureCompare'
  1491. };
  1492. /**
  1493. * This type represents mouse buttons and interaction types in context of controls.
  1494. *
  1495. * @typedef {Object} ConstantsMouse
  1496. * @property {number} MIDDLE - The left mouse button.
  1497. * @property {number} LEFT - The middle mouse button.
  1498. * @property {number} RIGHT - The right mouse button.
  1499. * @property {number} ROTATE - A rotate interaction.
  1500. * @property {number} DOLLY - A dolly interaction.
  1501. * @property {number} PAN - A pan interaction.
  1502. **/
  1503. /**
  1504. * This type represents touch interaction types in context of controls.
  1505. *
  1506. * @typedef {Object} ConstantsTouch
  1507. * @property {number} ROTATE - A rotate interaction.
  1508. * @property {number} PAN - A pan interaction.
  1509. * @property {number} DOLLY_PAN - The dolly-pan interaction.
  1510. * @property {number} DOLLY_ROTATE - A dolly-rotate interaction.
  1511. **/
  1512. /**
  1513. * This type represents the different timestamp query types.
  1514. *
  1515. * @typedef {Object} ConstantsTimestampQuery
  1516. * @property {string} COMPUTE - A `compute` timestamp query.
  1517. * @property {string} RENDER - A `render` timestamp query.
  1518. **/
  1519. /**
  1520. * Represents the different interpolation sampling types.
  1521. *
  1522. * @typedef {Object} ConstantsInterpolationSamplingType
  1523. * @property {string} PERSPECTIVE - Perspective-correct interpolation.
  1524. * @property {string} LINEAR - Linear interpolation.
  1525. * @property {string} FLAT - Flat interpolation.
  1526. */
  1527. /**
  1528. * Represents the different interpolation sampling modes.
  1529. *
  1530. * @typedef {Object} ConstantsInterpolationSamplingMode
  1531. * @property {string} NORMAL - Normal sampling mode.
  1532. * @property {string} CENTROID - Centroid sampling mode.
  1533. * @property {string} SAMPLE - Sample-specific sampling mode.
  1534. * @property {string} FIRST - Flat interpolation using the first vertex.
  1535. * @property {string} EITHER - Flat interpolation using either vertex.
  1536. */
  1537. function arrayNeedsUint32( array ) {
  1538. // assumes larger values usually on last
  1539. for ( let i = array.length - 1; i >= 0; -- i ) {
  1540. if ( array[ i ] >= 65535 ) return true; // account for PRIMITIVE_RESTART_FIXED_INDEX, #24565
  1541. }
  1542. return false;
  1543. }
  1544. const TYPED_ARRAYS = {
  1545. Int8Array: Int8Array,
  1546. Uint8Array: Uint8Array,
  1547. Uint8ClampedArray: Uint8ClampedArray,
  1548. Int16Array: Int16Array,
  1549. Uint16Array: Uint16Array,
  1550. Int32Array: Int32Array,
  1551. Uint32Array: Uint32Array,
  1552. Float32Array: Float32Array,
  1553. Float64Array: Float64Array
  1554. };
  1555. function getTypedArray( type, buffer ) {
  1556. return new TYPED_ARRAYS[ type ]( buffer );
  1557. }
  1558. /**
  1559. * Returns `true` if the given object is a typed array.
  1560. *
  1561. * @param {any} array - The object to check.
  1562. * @return {boolean} Whether the given object is a typed array.
  1563. */
  1564. function isTypedArray( array ) {
  1565. return ArrayBuffer.isView( array ) && ! ( array instanceof DataView );
  1566. }
  1567. function createElementNS( name ) {
  1568. return document.createElementNS( 'http://www.w3.org/1999/xhtml', name );
  1569. }
  1570. function createCanvasElement() {
  1571. const canvas = createElementNS( 'canvas' );
  1572. canvas.style.display = 'block';
  1573. return canvas;
  1574. }
  1575. const _cache = {};
  1576. let _setConsoleFunction = null;
  1577. function setConsoleFunction( fn ) {
  1578. _setConsoleFunction = fn;
  1579. }
  1580. function getConsoleFunction() {
  1581. return _setConsoleFunction;
  1582. }
  1583. function log( ...params ) {
  1584. const message = 'THREE.' + params.shift();
  1585. if ( _setConsoleFunction ) {
  1586. _setConsoleFunction( 'log', message, ...params );
  1587. } else {
  1588. console.log( message, ...params );
  1589. }
  1590. }
  1591. function warn( ...params ) {
  1592. const message = 'THREE.' + params.shift();
  1593. if ( _setConsoleFunction ) {
  1594. _setConsoleFunction( 'warn', message, ...params );
  1595. } else {
  1596. console.warn( message, ...params );
  1597. }
  1598. }
  1599. function error( ...params ) {
  1600. const message = 'THREE.' + params.shift();
  1601. if ( _setConsoleFunction ) {
  1602. _setConsoleFunction( 'error', message, ...params );
  1603. } else {
  1604. console.error( message, ...params );
  1605. }
  1606. }
  1607. function warnOnce( ...params ) {
  1608. const message = params.join( ' ' );
  1609. if ( message in _cache ) return;
  1610. _cache[ message ] = true;
  1611. warn( ...params );
  1612. }
  1613. function probeAsync( gl, sync, interval ) {
  1614. return new Promise( function ( resolve, reject ) {
  1615. function probe() {
  1616. switch ( gl.clientWaitSync( sync, gl.SYNC_FLUSH_COMMANDS_BIT, 0 ) ) {
  1617. case gl.WAIT_FAILED:
  1618. reject();
  1619. break;
  1620. case gl.TIMEOUT_EXPIRED:
  1621. setTimeout( probe, interval );
  1622. break;
  1623. default:
  1624. resolve();
  1625. }
  1626. }
  1627. setTimeout( probe, interval );
  1628. } );
  1629. }
  1630. /**
  1631. * This modules allows to dispatch event objects on custom JavaScript objects.
  1632. *
  1633. * Main repository: [eventdispatcher.js](https://github.com/mrdoob/eventdispatcher.js/)
  1634. *
  1635. * Code Example:
  1636. * ```js
  1637. * class Car extends EventDispatcher {
  1638. * start() {
  1639. * this.dispatchEvent( { type: 'start', message: 'vroom vroom!' } );
  1640. * }
  1641. *};
  1642. *
  1643. * // Using events with the custom object
  1644. * const car = new Car();
  1645. * car.addEventListener( 'start', function ( event ) {
  1646. * alert( event.message );
  1647. * } );
  1648. *
  1649. * car.start();
  1650. * ```
  1651. */
  1652. class EventDispatcher {
  1653. /**
  1654. * Adds the given event listener to the given event type.
  1655. *
  1656. * @param {string} type - The type of event to listen to.
  1657. * @param {Function} listener - The function that gets called when the event is fired.
  1658. */
  1659. addEventListener( type, listener ) {
  1660. if ( this._listeners === undefined ) this._listeners = {};
  1661. const listeners = this._listeners;
  1662. if ( listeners[ type ] === undefined ) {
  1663. listeners[ type ] = [];
  1664. }
  1665. if ( listeners[ type ].indexOf( listener ) === -1 ) {
  1666. listeners[ type ].push( listener );
  1667. }
  1668. }
  1669. /**
  1670. * Returns `true` if the given event listener has been added to the given event type.
  1671. *
  1672. * @param {string} type - The type of event.
  1673. * @param {Function} listener - The listener to check.
  1674. * @return {boolean} Whether the given event listener has been added to the given event type.
  1675. */
  1676. hasEventListener( type, listener ) {
  1677. const listeners = this._listeners;
  1678. if ( listeners === undefined ) return false;
  1679. return listeners[ type ] !== undefined && listeners[ type ].indexOf( listener ) !== -1;
  1680. }
  1681. /**
  1682. * Removes the given event listener from the given event type.
  1683. *
  1684. * @param {string} type - The type of event.
  1685. * @param {Function} listener - The listener to remove.
  1686. */
  1687. removeEventListener( type, listener ) {
  1688. const listeners = this._listeners;
  1689. if ( listeners === undefined ) return;
  1690. const listenerArray = listeners[ type ];
  1691. if ( listenerArray !== undefined ) {
  1692. const index = listenerArray.indexOf( listener );
  1693. if ( index !== -1 ) {
  1694. listenerArray.splice( index, 1 );
  1695. }
  1696. }
  1697. }
  1698. /**
  1699. * Dispatches an event object.
  1700. *
  1701. * @param {Object} event - The event that gets fired.
  1702. */
  1703. dispatchEvent( event ) {
  1704. const listeners = this._listeners;
  1705. if ( listeners === undefined ) return;
  1706. const listenerArray = listeners[ event.type ];
  1707. if ( listenerArray !== undefined ) {
  1708. event.target = this;
  1709. // Make a copy, in case listeners are removed while iterating.
  1710. const array = listenerArray.slice( 0 );
  1711. for ( let i = 0, l = array.length; i < l; i ++ ) {
  1712. array[ i ].call( this, event );
  1713. }
  1714. event.target = null;
  1715. }
  1716. }
  1717. }
  1718. 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' ];
  1719. let _seed = 1234567;
  1720. const DEG2RAD = Math.PI / 180;
  1721. const RAD2DEG = 180 / Math.PI;
  1722. /**
  1723. * Generate a [UUID](https://en.wikipedia.org/wiki/Universally_unique_identifier)
  1724. * (universally unique identifier).
  1725. *
  1726. * @return {string} The UUID.
  1727. */
  1728. function generateUUID() {
  1729. // http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/21963136#21963136
  1730. const d0 = Math.random() * 0xffffffff | 0;
  1731. const d1 = Math.random() * 0xffffffff | 0;
  1732. const d2 = Math.random() * 0xffffffff | 0;
  1733. const d3 = Math.random() * 0xffffffff | 0;
  1734. const uuid = _lut[ d0 & 0xff ] + _lut[ d0 >> 8 & 0xff ] + _lut[ d0 >> 16 & 0xff ] + _lut[ d0 >> 24 & 0xff ] + '-' +
  1735. _lut[ d1 & 0xff ] + _lut[ d1 >> 8 & 0xff ] + '-' + _lut[ d1 >> 16 & 0x0f | 0x40 ] + _lut[ d1 >> 24 & 0xff ] + '-' +
  1736. _lut[ d2 & 0x3f | 0x80 ] + _lut[ d2 >> 8 & 0xff ] + '-' + _lut[ d2 >> 16 & 0xff ] + _lut[ d2 >> 24 & 0xff ] +
  1737. _lut[ d3 & 0xff ] + _lut[ d3 >> 8 & 0xff ] + _lut[ d3 >> 16 & 0xff ] + _lut[ d3 >> 24 & 0xff ];
  1738. // .toLowerCase() here flattens concatenated strings to save heap memory space.
  1739. return uuid.toLowerCase();
  1740. }
  1741. /**
  1742. * Clamps the given value between min and max.
  1743. *
  1744. * @param {number} value - The value to clamp.
  1745. * @param {number} min - The min value.
  1746. * @param {number} max - The max value.
  1747. * @return {number} The clamped value.
  1748. */
  1749. function clamp( value, min, max ) {
  1750. return Math.max( min, Math.min( max, value ) );
  1751. }
  1752. /**
  1753. * Computes the Euclidean modulo of the given parameters that
  1754. * is `( ( n % m ) + m ) % m`.
  1755. *
  1756. * @param {number} n - The first parameter.
  1757. * @param {number} m - The second parameter.
  1758. * @return {number} The Euclidean modulo.
  1759. */
  1760. function euclideanModulo( n, m ) {
  1761. // https://en.wikipedia.org/wiki/Modulo_operation
  1762. return ( ( n % m ) + m ) % m;
  1763. }
  1764. /**
  1765. * Performs a linear mapping from range `<a1, a2>` to range `<b1, b2>`
  1766. * for the given value.
  1767. *
  1768. * @param {number} x - The value to be mapped.
  1769. * @param {number} a1 - Minimum value for range A.
  1770. * @param {number} a2 - Maximum value for range A.
  1771. * @param {number} b1 - Minimum value for range B.
  1772. * @param {number} b2 - Maximum value for range B.
  1773. * @return {number} The mapped value.
  1774. */
  1775. function mapLinear( x, a1, a2, b1, b2 ) {
  1776. return b1 + ( x - a1 ) * ( b2 - b1 ) / ( a2 - a1 );
  1777. }
  1778. /**
  1779. * Returns the percentage in the closed interval `[0, 1]` of the given value
  1780. * between the start and end point.
  1781. *
  1782. * @param {number} x - The start point
  1783. * @param {number} y - The end point.
  1784. * @param {number} value - A value between start and end.
  1785. * @return {number} The interpolation factor.
  1786. */
  1787. function inverseLerp( x, y, value ) {
  1788. // https://www.gamedev.net/tutorials/programming/general-and-gameplay-programming/inverse-lerp-a-super-useful-yet-often-overlooked-function-r5230/
  1789. if ( x !== y ) {
  1790. return ( value - x ) / ( y - x );
  1791. } else {
  1792. return 0;
  1793. }
  1794. }
  1795. /**
  1796. * Returns a value linearly interpolated from two known points based on the given interval -
  1797. * `t = 0` will return `x` and `t = 1` will return `y`.
  1798. *
  1799. * @param {number} x - The start point
  1800. * @param {number} y - The end point.
  1801. * @param {number} t - The interpolation factor in the closed interval `[0, 1]`.
  1802. * @return {number} The interpolated value.
  1803. */
  1804. function lerp( x, y, t ) {
  1805. return ( 1 - t ) * x + t * y;
  1806. }
  1807. /**
  1808. * Smoothly interpolate a number from `x` to `y` in a spring-like manner using a delta
  1809. * time to maintain frame rate independent movement. For details, see
  1810. * [Frame rate independent damping using lerp](http://www.rorydriscoll.com/2016/03/07/frame-rate-independent-damping-using-lerp/).
  1811. *
  1812. * @param {number} x - The current point.
  1813. * @param {number} y - The target point.
  1814. * @param {number} lambda - A higher lambda value will make the movement more sudden,
  1815. * and a lower value will make the movement more gradual.
  1816. * @param {number} dt - Delta time in seconds.
  1817. * @return {number} The interpolated value.
  1818. */
  1819. function damp( x, y, lambda, dt ) {
  1820. return lerp( x, y, 1 - Math.exp( - lambda * dt ) );
  1821. }
  1822. /**
  1823. * Returns a value that alternates between `0` and the given `length` parameter.
  1824. *
  1825. * @param {number} x - The value to pingpong.
  1826. * @param {number} [length=1] - The positive value the function will pingpong to.
  1827. * @return {number} The alternated value.
  1828. */
  1829. function pingpong( x, length = 1 ) {
  1830. // https://www.desmos.com/calculator/vcsjnyz7x4
  1831. return length - Math.abs( euclideanModulo( x, length * 2 ) - length );
  1832. }
  1833. /**
  1834. * Returns a value in the range `[0,1]` that represents the percentage that `x` has
  1835. * moved between `min` and `max`, but smoothed or slowed down the closer `x` is to
  1836. * the `min` and `max`.
  1837. *
  1838. * See [Smoothstep](http://en.wikipedia.org/wiki/Smoothstep) for more details.
  1839. *
  1840. * @param {number} x - The value to evaluate based on its position between min and max.
  1841. * @param {number} min - The min value. Any x value below min will be `0`.
  1842. * @param {number} max - The max value. Any x value above max will be `1`.
  1843. * @return {number} The alternated value.
  1844. */
  1845. function smoothstep( x, min, max ) {
  1846. if ( x <= min ) return 0;
  1847. if ( x >= max ) return 1;
  1848. x = ( x - min ) / ( max - min );
  1849. return x * x * ( 3 - 2 * x );
  1850. }
  1851. /**
  1852. * A [variation on smoothstep](https://en.wikipedia.org/wiki/Smoothstep#Variations)
  1853. * that has zero 1st and 2nd order derivatives at x=0 and x=1.
  1854. *
  1855. * @param {number} x - The value to evaluate based on its position between min and max.
  1856. * @param {number} min - The min value. Any x value below min will be `0`.
  1857. * @param {number} max - The max value. Any x value above max will be `1`.
  1858. * @return {number} The alternated value.
  1859. */
  1860. function smootherstep( x, min, max ) {
  1861. if ( x <= min ) return 0;
  1862. if ( x >= max ) return 1;
  1863. x = ( x - min ) / ( max - min );
  1864. return x * x * x * ( x * ( x * 6 - 15 ) + 10 );
  1865. }
  1866. /**
  1867. * Returns a random integer from `<low, high>` interval.
  1868. *
  1869. * @param {number} low - The lower value boundary.
  1870. * @param {number} high - The upper value boundary
  1871. * @return {number} A random integer.
  1872. */
  1873. function randInt( low, high ) {
  1874. return low + Math.floor( Math.random() * ( high - low + 1 ) );
  1875. }
  1876. /**
  1877. * Returns a random float from `<low, high>` interval.
  1878. *
  1879. * @param {number} low - The lower value boundary.
  1880. * @param {number} high - The upper value boundary
  1881. * @return {number} A random float.
  1882. */
  1883. function randFloat( low, high ) {
  1884. return low + Math.random() * ( high - low );
  1885. }
  1886. /**
  1887. * Returns a random integer from `<-range/2, range/2>` interval.
  1888. *
  1889. * @param {number} range - Defines the value range.
  1890. * @return {number} A random float.
  1891. */
  1892. function randFloatSpread( range ) {
  1893. return range * ( 0.5 - Math.random() );
  1894. }
  1895. /**
  1896. * Returns a deterministic pseudo-random float in the interval `[0, 1]`.
  1897. *
  1898. * @param {number} [s] - The integer seed.
  1899. * @return {number} A random float.
  1900. */
  1901. function seededRandom( s ) {
  1902. if ( s !== undefined ) _seed = s;
  1903. // Mulberry32 generator
  1904. let t = _seed += 0x6D2B79F5;
  1905. t = Math.imul( t ^ t >>> 15, t | 1 );
  1906. t ^= t + Math.imul( t ^ t >>> 7, t | 61 );
  1907. return ( ( t ^ t >>> 14 ) >>> 0 ) / 4294967296;
  1908. }
  1909. /**
  1910. * Converts degrees to radians.
  1911. *
  1912. * @param {number} degrees - A value in degrees.
  1913. * @return {number} The converted value in radians.
  1914. */
  1915. function degToRad( degrees ) {
  1916. return degrees * DEG2RAD;
  1917. }
  1918. /**
  1919. * Converts radians to degrees.
  1920. *
  1921. * @param {number} radians - A value in radians.
  1922. * @return {number} The converted value in degrees.
  1923. */
  1924. function radToDeg( radians ) {
  1925. return radians * RAD2DEG;
  1926. }
  1927. /**
  1928. * Returns `true` if the given number is a power of two.
  1929. *
  1930. * @param {number} value - The value to check.
  1931. * @return {boolean} Whether the given number is a power of two or not.
  1932. */
  1933. function isPowerOfTwo( value ) {
  1934. return ( value & ( value - 1 ) ) === 0 && value !== 0;
  1935. }
  1936. /**
  1937. * Returns the smallest power of two that is greater than or equal to the given number.
  1938. *
  1939. * @param {number} value - The value to find a POT for.
  1940. * @return {number} The smallest power of two that is greater than or equal to the given number.
  1941. */
  1942. function ceilPowerOfTwo( value ) {
  1943. return Math.pow( 2, Math.ceil( Math.log( value ) / Math.LN2 ) );
  1944. }
  1945. /**
  1946. * Returns the largest power of two that is less than or equal to the given number.
  1947. *
  1948. * @param {number} value - The value to find a POT for.
  1949. * @return {number} The largest power of two that is less than or equal to the given number.
  1950. */
  1951. function floorPowerOfTwo( value ) {
  1952. return Math.pow( 2, Math.floor( Math.log( value ) / Math.LN2 ) );
  1953. }
  1954. /**
  1955. * Sets the given quaternion from the [Intrinsic Proper Euler Angles](https://en.wikipedia.org/wiki/Euler_angles)
  1956. * defined by the given angles and order.
  1957. *
  1958. * Rotations are applied to the axes in the order specified by order:
  1959. * rotation by angle `a` is applied first, then by angle `b`, then by angle `c`.
  1960. *
  1961. * @param {Quaternion} q - The quaternion to set.
  1962. * @param {number} a - The rotation applied to the first axis, in radians.
  1963. * @param {number} b - The rotation applied to the second axis, in radians.
  1964. * @param {number} c - The rotation applied to the third axis, in radians.
  1965. * @param {('XYX'|'XZX'|'YXY'|'YZY'|'ZXZ'|'ZYZ')} order - A string specifying the axes order.
  1966. */
  1967. function setQuaternionFromProperEuler( q, a, b, c, order ) {
  1968. const cos = Math.cos;
  1969. const sin = Math.sin;
  1970. const c2 = cos( b / 2 );
  1971. const s2 = sin( b / 2 );
  1972. const c13 = cos( ( a + c ) / 2 );
  1973. const s13 = sin( ( a + c ) / 2 );
  1974. const c1_3 = cos( ( a - c ) / 2 );
  1975. const s1_3 = sin( ( a - c ) / 2 );
  1976. const c3_1 = cos( ( c - a ) / 2 );
  1977. const s3_1 = sin( ( c - a ) / 2 );
  1978. switch ( order ) {
  1979. case 'XYX':
  1980. q.set( c2 * s13, s2 * c1_3, s2 * s1_3, c2 * c13 );
  1981. break;
  1982. case 'YZY':
  1983. q.set( s2 * s1_3, c2 * s13, s2 * c1_3, c2 * c13 );
  1984. break;
  1985. case 'ZXZ':
  1986. q.set( s2 * c1_3, s2 * s1_3, c2 * s13, c2 * c13 );
  1987. break;
  1988. case 'XZX':
  1989. q.set( c2 * s13, s2 * s3_1, s2 * c3_1, c2 * c13 );
  1990. break;
  1991. case 'YXY':
  1992. q.set( s2 * c3_1, c2 * s13, s2 * s3_1, c2 * c13 );
  1993. break;
  1994. case 'ZYZ':
  1995. q.set( s2 * s3_1, s2 * c3_1, c2 * s13, c2 * c13 );
  1996. break;
  1997. default:
  1998. warn( 'MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: ' + order );
  1999. }
  2000. }
  2001. /**
  2002. * Denormalizes the given value according to the given typed array.
  2003. *
  2004. * @param {number} value - The value to denormalize.
  2005. * @param {TypedArray} array - The typed array that defines the data type of the value.
  2006. * @return {number} The denormalize (float) value in the range `[0,1]`.
  2007. */
  2008. function denormalize( value, array ) {
  2009. switch ( array.constructor ) {
  2010. case Float32Array:
  2011. return value;
  2012. case Uint32Array:
  2013. return value / 4294967295.0;
  2014. case Uint16Array:
  2015. return value / 65535.0;
  2016. case Uint8Array:
  2017. return value / 255.0;
  2018. case Int32Array:
  2019. return Math.max( value / 2147483647.0, -1 );
  2020. case Int16Array:
  2021. return Math.max( value / 32767.0, -1 );
  2022. case Int8Array:
  2023. return Math.max( value / 127.0, -1 );
  2024. default:
  2025. throw new Error( 'Invalid component type.' );
  2026. }
  2027. }
  2028. /**
  2029. * Normalizes the given value according to the given typed array.
  2030. *
  2031. * @param {number} value - The float value in the range `[0,1]` to normalize.
  2032. * @param {TypedArray} array - The typed array that defines the data type of the value.
  2033. * @return {number} The normalize value.
  2034. */
  2035. function normalize( value, array ) {
  2036. switch ( array.constructor ) {
  2037. case Float32Array:
  2038. return value;
  2039. case Uint32Array:
  2040. return Math.round( value * 4294967295.0 );
  2041. case Uint16Array:
  2042. return Math.round( value * 65535.0 );
  2043. case Uint8Array:
  2044. return Math.round( value * 255.0 );
  2045. case Int32Array:
  2046. return Math.round( value * 2147483647.0 );
  2047. case Int16Array:
  2048. return Math.round( value * 32767.0 );
  2049. case Int8Array:
  2050. return Math.round( value * 127.0 );
  2051. default:
  2052. throw new Error( 'Invalid component type.' );
  2053. }
  2054. }
  2055. /**
  2056. * @class
  2057. * @classdesc A collection of math utility functions.
  2058. * @hideconstructor
  2059. */
  2060. const MathUtils = {
  2061. DEG2RAD: DEG2RAD,
  2062. RAD2DEG: RAD2DEG,
  2063. /**
  2064. * Generate a [UUID](https://en.wikipedia.org/wiki/Universally_unique_identifier)
  2065. * (universally unique identifier).
  2066. *
  2067. * @static
  2068. * @method
  2069. * @return {string} The UUID.
  2070. */
  2071. generateUUID: generateUUID,
  2072. /**
  2073. * Clamps the given value between min and max.
  2074. *
  2075. * @static
  2076. * @method
  2077. * @param {number} value - The value to clamp.
  2078. * @param {number} min - The min value.
  2079. * @param {number} max - The max value.
  2080. * @return {number} The clamped value.
  2081. */
  2082. clamp: clamp,
  2083. /**
  2084. * Computes the Euclidean modulo of the given parameters that
  2085. * is `( ( n % m ) + m ) % m`.
  2086. *
  2087. * @static
  2088. * @method
  2089. * @param {number} n - The first parameter.
  2090. * @param {number} m - The second parameter.
  2091. * @return {number} The Euclidean modulo.
  2092. */
  2093. euclideanModulo: euclideanModulo,
  2094. /**
  2095. * Performs a linear mapping from range `<a1, a2>` to range `<b1, b2>`
  2096. * for the given value.
  2097. *
  2098. * @static
  2099. * @method
  2100. * @param {number} x - The value to be mapped.
  2101. * @param {number} a1 - Minimum value for range A.
  2102. * @param {number} a2 - Maximum value for range A.
  2103. * @param {number} b1 - Minimum value for range B.
  2104. * @param {number} b2 - Maximum value for range B.
  2105. * @return {number} The mapped value.
  2106. */
  2107. mapLinear: mapLinear,
  2108. /**
  2109. * Returns the percentage in the closed interval `[0, 1]` of the given value
  2110. * between the start and end point.
  2111. *
  2112. * @static
  2113. * @method
  2114. * @param {number} x - The start point
  2115. * @param {number} y - The end point.
  2116. * @param {number} value - A value between start and end.
  2117. * @return {number} The interpolation factor.
  2118. */
  2119. inverseLerp: inverseLerp,
  2120. /**
  2121. * Returns a value linearly interpolated from two known points based on the given interval -
  2122. * `t = 0` will return `x` and `t = 1` will return `y`.
  2123. *
  2124. * @static
  2125. * @method
  2126. * @param {number} x - The start point
  2127. * @param {number} y - The end point.
  2128. * @param {number} t - The interpolation factor in the closed interval `[0, 1]`.
  2129. * @return {number} The interpolated value.
  2130. */
  2131. lerp: lerp,
  2132. /**
  2133. * Smoothly interpolate a number from `x` to `y` in a spring-like manner using a delta
  2134. * time to maintain frame rate independent movement. For details, see
  2135. * [Frame rate independent damping using lerp](http://www.rorydriscoll.com/2016/03/07/frame-rate-independent-damping-using-lerp/).
  2136. *
  2137. * @static
  2138. * @method
  2139. * @param {number} x - The current point.
  2140. * @param {number} y - The target point.
  2141. * @param {number} lambda - A higher lambda value will make the movement more sudden,
  2142. * and a lower value will make the movement more gradual.
  2143. * @param {number} dt - Delta time in seconds.
  2144. * @return {number} The interpolated value.
  2145. */
  2146. damp: damp,
  2147. /**
  2148. * Returns a value that alternates between `0` and the given `length` parameter.
  2149. *
  2150. * @static
  2151. * @method
  2152. * @param {number} x - The value to pingpong.
  2153. * @param {number} [length=1] - The positive value the function will pingpong to.
  2154. * @return {number} The alternated value.
  2155. */
  2156. pingpong: pingpong,
  2157. /**
  2158. * Returns a value in the range `[0,1]` that represents the percentage that `x` has
  2159. * moved between `min` and `max`, but smoothed or slowed down the closer `x` is to
  2160. * the `min` and `max`.
  2161. *
  2162. * See [Smoothstep](http://en.wikipedia.org/wiki/Smoothstep) for more details.
  2163. *
  2164. * @static
  2165. * @method
  2166. * @param {number} x - The value to evaluate based on its position between min and max.
  2167. * @param {number} min - The min value. Any x value below min will be `0`.
  2168. * @param {number} max - The max value. Any x value above max will be `1`.
  2169. * @return {number} The alternated value.
  2170. */
  2171. smoothstep: smoothstep,
  2172. /**
  2173. * A [variation on smoothstep](https://en.wikipedia.org/wiki/Smoothstep#Variations)
  2174. * that has zero 1st and 2nd order derivatives at x=0 and x=1.
  2175. *
  2176. * @static
  2177. * @method
  2178. * @param {number} x - The value to evaluate based on its position between min and max.
  2179. * @param {number} min - The min value. Any x value below min will be `0`.
  2180. * @param {number} max - The max value. Any x value above max will be `1`.
  2181. * @return {number} The alternated value.
  2182. */
  2183. smootherstep: smootherstep,
  2184. /**
  2185. * Returns a random integer from `<low, high>` interval.
  2186. *
  2187. * @static
  2188. * @method
  2189. * @param {number} low - The lower value boundary.
  2190. * @param {number} high - The upper value boundary
  2191. * @return {number} A random integer.
  2192. */
  2193. randInt: randInt,
  2194. /**
  2195. * Returns a random float from `<low, high>` interval.
  2196. *
  2197. * @static
  2198. * @method
  2199. * @param {number} low - The lower value boundary.
  2200. * @param {number} high - The upper value boundary
  2201. * @return {number} A random float.
  2202. */
  2203. randFloat: randFloat,
  2204. /**
  2205. * Returns a random integer from `<-range/2, range/2>` interval.
  2206. *
  2207. * @static
  2208. * @method
  2209. * @param {number} range - Defines the value range.
  2210. * @return {number} A random float.
  2211. */
  2212. randFloatSpread: randFloatSpread,
  2213. /**
  2214. * Returns a deterministic pseudo-random float in the interval `[0, 1]`.
  2215. *
  2216. * @static
  2217. * @method
  2218. * @param {number} [s] - The integer seed.
  2219. * @return {number} A random float.
  2220. */
  2221. seededRandom: seededRandom,
  2222. /**
  2223. * Converts degrees to radians.
  2224. *
  2225. * @static
  2226. * @method
  2227. * @param {number} degrees - A value in degrees.
  2228. * @return {number} The converted value in radians.
  2229. */
  2230. degToRad: degToRad,
  2231. /**
  2232. * Converts radians to degrees.
  2233. *
  2234. * @static
  2235. * @method
  2236. * @param {number} radians - A value in radians.
  2237. * @return {number} The converted value in degrees.
  2238. */
  2239. radToDeg: radToDeg,
  2240. /**
  2241. * Returns `true` if the given number is a power of two.
  2242. *
  2243. * @static
  2244. * @method
  2245. * @param {number} value - The value to check.
  2246. * @return {boolean} Whether the given number is a power of two or not.
  2247. */
  2248. isPowerOfTwo: isPowerOfTwo,
  2249. /**
  2250. * Returns the smallest power of two that is greater than or equal to the given number.
  2251. *
  2252. * @static
  2253. * @method
  2254. * @param {number} value - The value to find a POT for.
  2255. * @return {number} The smallest power of two that is greater than or equal to the given number.
  2256. */
  2257. ceilPowerOfTwo: ceilPowerOfTwo,
  2258. /**
  2259. * Returns the largest power of two that is less than or equal to the given number.
  2260. *
  2261. * @static
  2262. * @method
  2263. * @param {number} value - The value to find a POT for.
  2264. * @return {number} The largest power of two that is less than or equal to the given number.
  2265. */
  2266. floorPowerOfTwo: floorPowerOfTwo,
  2267. /**
  2268. * Sets the given quaternion from the [Intrinsic Proper Euler Angles](https://en.wikipedia.org/wiki/Euler_angles)
  2269. * defined by the given angles and order.
  2270. *
  2271. * Rotations are applied to the axes in the order specified by order:
  2272. * rotation by angle `a` is applied first, then by angle `b`, then by angle `c`.
  2273. *
  2274. * @static
  2275. * @method
  2276. * @param {Quaternion} q - The quaternion to set.
  2277. * @param {number} a - The rotation applied to the first axis, in radians.
  2278. * @param {number} b - The rotation applied to the second axis, in radians.
  2279. * @param {number} c - The rotation applied to the third axis, in radians.
  2280. * @param {('XYX'|'XZX'|'YXY'|'YZY'|'ZXZ'|'ZYZ')} order - A string specifying the axes order.
  2281. */
  2282. setQuaternionFromProperEuler: setQuaternionFromProperEuler,
  2283. /**
  2284. * Normalizes the given value according to the given typed array.
  2285. *
  2286. * @static
  2287. * @method
  2288. * @param {number} value - The float value in the range `[0,1]` to normalize.
  2289. * @param {TypedArray} array - The typed array that defines the data type of the value.
  2290. * @return {number} The normalize value.
  2291. */
  2292. normalize: normalize,
  2293. /**
  2294. * Denormalizes the given value according to the given typed array.
  2295. *
  2296. * @static
  2297. * @method
  2298. * @param {number} value - The value to denormalize.
  2299. * @param {TypedArray} array - The typed array that defines the data type of the value.
  2300. * @return {number} The denormalize (float) value in the range `[0,1]`.
  2301. */
  2302. denormalize: denormalize
  2303. };
  2304. /**
  2305. * Class representing a 2D vector. A 2D vector is an ordered pair of numbers
  2306. * (labeled x and y), which can be used to represent a number of things, such as:
  2307. *
  2308. * - A point in 2D space (i.e. a position on a plane).
  2309. * - A direction and length across a plane. In three.js the length will
  2310. * always be the Euclidean distance(straight-line distance) from `(0, 0)` to `(x, y)`
  2311. * and the direction is also measured from `(0, 0)` towards `(x, y)`.
  2312. * - Any arbitrary ordered pair of numbers.
  2313. *
  2314. * There are other things a 2D vector can be used to represent, such as
  2315. * momentum vectors, complex numbers and so on, however these are the most
  2316. * common uses in three.js.
  2317. *
  2318. * Iterating through a vector instance will yield its components `(x, y)` in
  2319. * the corresponding order.
  2320. * ```js
  2321. * const a = new THREE.Vector2( 0, 1 );
  2322. *
  2323. * //no arguments; will be initialised to (0, 0)
  2324. * const b = new THREE.Vector2( );
  2325. *
  2326. * const d = a.distanceTo( b );
  2327. * ```
  2328. */
  2329. class Vector2 {
  2330. /**
  2331. * Constructs a new 2D vector.
  2332. *
  2333. * @param {number} [x=0] - The x value of this vector.
  2334. * @param {number} [y=0] - The y value of this vector.
  2335. */
  2336. constructor( x = 0, y = 0 ) {
  2337. /**
  2338. * This flag can be used for type testing.
  2339. *
  2340. * @type {boolean}
  2341. * @readonly
  2342. * @default true
  2343. */
  2344. Vector2.prototype.isVector2 = true;
  2345. /**
  2346. * The x value of this vector.
  2347. *
  2348. * @type {number}
  2349. */
  2350. this.x = x;
  2351. /**
  2352. * The y value of this vector.
  2353. *
  2354. * @type {number}
  2355. */
  2356. this.y = y;
  2357. }
  2358. /**
  2359. * Alias for {@link Vector2#x}.
  2360. *
  2361. * @type {number}
  2362. */
  2363. get width() {
  2364. return this.x;
  2365. }
  2366. set width( value ) {
  2367. this.x = value;
  2368. }
  2369. /**
  2370. * Alias for {@link Vector2#y}.
  2371. *
  2372. * @type {number}
  2373. */
  2374. get height() {
  2375. return this.y;
  2376. }
  2377. set height( value ) {
  2378. this.y = value;
  2379. }
  2380. /**
  2381. * Sets the vector components.
  2382. *
  2383. * @param {number} x - The value of the x component.
  2384. * @param {number} y - The value of the y component.
  2385. * @return {Vector2} A reference to this vector.
  2386. */
  2387. set( x, y ) {
  2388. this.x = x;
  2389. this.y = y;
  2390. return this;
  2391. }
  2392. /**
  2393. * Sets the vector components to the same value.
  2394. *
  2395. * @param {number} scalar - The value to set for all vector components.
  2396. * @return {Vector2} A reference to this vector.
  2397. */
  2398. setScalar( scalar ) {
  2399. this.x = scalar;
  2400. this.y = scalar;
  2401. return this;
  2402. }
  2403. /**
  2404. * Sets the vector's x component to the given value
  2405. *
  2406. * @param {number} x - The value to set.
  2407. * @return {Vector2} A reference to this vector.
  2408. */
  2409. setX( x ) {
  2410. this.x = x;
  2411. return this;
  2412. }
  2413. /**
  2414. * Sets the vector's y component to the given value
  2415. *
  2416. * @param {number} y - The value to set.
  2417. * @return {Vector2} A reference to this vector.
  2418. */
  2419. setY( y ) {
  2420. this.y = y;
  2421. return this;
  2422. }
  2423. /**
  2424. * Allows to set a vector component with an index.
  2425. *
  2426. * @param {number} index - The component index. `0` equals to x, `1` equals to y.
  2427. * @param {number} value - The value to set.
  2428. * @return {Vector2} A reference to this vector.
  2429. */
  2430. setComponent( index, value ) {
  2431. switch ( index ) {
  2432. case 0: this.x = value; break;
  2433. case 1: this.y = value; break;
  2434. default: throw new Error( 'index is out of range: ' + index );
  2435. }
  2436. return this;
  2437. }
  2438. /**
  2439. * Returns the value of the vector component which matches the given index.
  2440. *
  2441. * @param {number} index - The component index. `0` equals to x, `1` equals to y.
  2442. * @return {number} A vector component value.
  2443. */
  2444. getComponent( index ) {
  2445. switch ( index ) {
  2446. case 0: return this.x;
  2447. case 1: return this.y;
  2448. default: throw new Error( 'index is out of range: ' + index );
  2449. }
  2450. }
  2451. /**
  2452. * Returns a new vector with copied values from this instance.
  2453. *
  2454. * @return {Vector2} A clone of this instance.
  2455. */
  2456. clone() {
  2457. return new this.constructor( this.x, this.y );
  2458. }
  2459. /**
  2460. * Copies the values of the given vector to this instance.
  2461. *
  2462. * @param {Vector2} v - The vector to copy.
  2463. * @return {Vector2} A reference to this vector.
  2464. */
  2465. copy( v ) {
  2466. this.x = v.x;
  2467. this.y = v.y;
  2468. return this;
  2469. }
  2470. /**
  2471. * Adds the given vector to this instance.
  2472. *
  2473. * @param {Vector2} v - The vector to add.
  2474. * @return {Vector2} A reference to this vector.
  2475. */
  2476. add( v ) {
  2477. this.x += v.x;
  2478. this.y += v.y;
  2479. return this;
  2480. }
  2481. /**
  2482. * Adds the given scalar value to all components of this instance.
  2483. *
  2484. * @param {number} s - The scalar to add.
  2485. * @return {Vector2} A reference to this vector.
  2486. */
  2487. addScalar( s ) {
  2488. this.x += s;
  2489. this.y += s;
  2490. return this;
  2491. }
  2492. /**
  2493. * Adds the given vectors and stores the result in this instance.
  2494. *
  2495. * @param {Vector2} a - The first vector.
  2496. * @param {Vector2} b - The second vector.
  2497. * @return {Vector2} A reference to this vector.
  2498. */
  2499. addVectors( a, b ) {
  2500. this.x = a.x + b.x;
  2501. this.y = a.y + b.y;
  2502. return this;
  2503. }
  2504. /**
  2505. * Adds the given vector scaled by the given factor to this instance.
  2506. *
  2507. * @param {Vector2} v - The vector.
  2508. * @param {number} s - The factor that scales `v`.
  2509. * @return {Vector2} A reference to this vector.
  2510. */
  2511. addScaledVector( v, s ) {
  2512. this.x += v.x * s;
  2513. this.y += v.y * s;
  2514. return this;
  2515. }
  2516. /**
  2517. * Subtracts the given vector from this instance.
  2518. *
  2519. * @param {Vector2} v - The vector to subtract.
  2520. * @return {Vector2} A reference to this vector.
  2521. */
  2522. sub( v ) {
  2523. this.x -= v.x;
  2524. this.y -= v.y;
  2525. return this;
  2526. }
  2527. /**
  2528. * Subtracts the given scalar value from all components of this instance.
  2529. *
  2530. * @param {number} s - The scalar to subtract.
  2531. * @return {Vector2} A reference to this vector.
  2532. */
  2533. subScalar( s ) {
  2534. this.x -= s;
  2535. this.y -= s;
  2536. return this;
  2537. }
  2538. /**
  2539. * Subtracts the given vectors and stores the result in this instance.
  2540. *
  2541. * @param {Vector2} a - The first vector.
  2542. * @param {Vector2} b - The second vector.
  2543. * @return {Vector2} A reference to this vector.
  2544. */
  2545. subVectors( a, b ) {
  2546. this.x = a.x - b.x;
  2547. this.y = a.y - b.y;
  2548. return this;
  2549. }
  2550. /**
  2551. * Multiplies the given vector with this instance.
  2552. *
  2553. * @param {Vector2} v - The vector to multiply.
  2554. * @return {Vector2} A reference to this vector.
  2555. */
  2556. multiply( v ) {
  2557. this.x *= v.x;
  2558. this.y *= v.y;
  2559. return this;
  2560. }
  2561. /**
  2562. * Multiplies the given scalar value with all components of this instance.
  2563. *
  2564. * @param {number} scalar - The scalar to multiply.
  2565. * @return {Vector2} A reference to this vector.
  2566. */
  2567. multiplyScalar( scalar ) {
  2568. this.x *= scalar;
  2569. this.y *= scalar;
  2570. return this;
  2571. }
  2572. /**
  2573. * Divides this instance by the given vector.
  2574. *
  2575. * @param {Vector2} v - The vector to divide.
  2576. * @return {Vector2} A reference to this vector.
  2577. */
  2578. divide( v ) {
  2579. this.x /= v.x;
  2580. this.y /= v.y;
  2581. return this;
  2582. }
  2583. /**
  2584. * Divides this vector by the given scalar.
  2585. *
  2586. * @param {number} scalar - The scalar to divide.
  2587. * @return {Vector2} A reference to this vector.
  2588. */
  2589. divideScalar( scalar ) {
  2590. return this.multiplyScalar( 1 / scalar );
  2591. }
  2592. /**
  2593. * Multiplies this vector (with an implicit 1 as the 3rd component) by
  2594. * the given 3x3 matrix.
  2595. *
  2596. * @param {Matrix3} m - The matrix to apply.
  2597. * @return {Vector2} A reference to this vector.
  2598. */
  2599. applyMatrix3( m ) {
  2600. const x = this.x, y = this.y;
  2601. const e = m.elements;
  2602. this.x = e[ 0 ] * x + e[ 3 ] * y + e[ 6 ];
  2603. this.y = e[ 1 ] * x + e[ 4 ] * y + e[ 7 ];
  2604. return this;
  2605. }
  2606. /**
  2607. * If this vector's x or y value is greater than the given vector's x or y
  2608. * value, replace that value with the corresponding min value.
  2609. *
  2610. * @param {Vector2} v - The vector.
  2611. * @return {Vector2} A reference to this vector.
  2612. */
  2613. min( v ) {
  2614. this.x = Math.min( this.x, v.x );
  2615. this.y = Math.min( this.y, v.y );
  2616. return this;
  2617. }
  2618. /**
  2619. * If this vector's x or y value is less than the given vector's x or y
  2620. * value, replace that value with the corresponding max value.
  2621. *
  2622. * @param {Vector2} v - The vector.
  2623. * @return {Vector2} A reference to this vector.
  2624. */
  2625. max( v ) {
  2626. this.x = Math.max( this.x, v.x );
  2627. this.y = Math.max( this.y, v.y );
  2628. return this;
  2629. }
  2630. /**
  2631. * If this vector's x or y value is greater than the max vector's x or y
  2632. * value, it is replaced by the corresponding value.
  2633. * If this vector's x or y value is less than the min vector's x or y value,
  2634. * it is replaced by the corresponding value.
  2635. *
  2636. * @param {Vector2} min - The minimum x and y values.
  2637. * @param {Vector2} max - The maximum x and y values in the desired range.
  2638. * @return {Vector2} A reference to this vector.
  2639. */
  2640. clamp( min, max ) {
  2641. // assumes min < max, componentwise
  2642. this.x = clamp( this.x, min.x, max.x );
  2643. this.y = clamp( this.y, min.y, max.y );
  2644. return this;
  2645. }
  2646. /**
  2647. * If this vector's x or y values are greater than the max value, they are
  2648. * replaced by the max value.
  2649. * If this vector's x or y values are less than the min value, they are
  2650. * replaced by the min value.
  2651. *
  2652. * @param {number} minVal - The minimum value the components will be clamped to.
  2653. * @param {number} maxVal - The maximum value the components will be clamped to.
  2654. * @return {Vector2} A reference to this vector.
  2655. */
  2656. clampScalar( minVal, maxVal ) {
  2657. this.x = clamp( this.x, minVal, maxVal );
  2658. this.y = clamp( this.y, minVal, maxVal );
  2659. return this;
  2660. }
  2661. /**
  2662. * If this vector's length is greater than the max value, it is replaced by
  2663. * the max value.
  2664. * If this vector's length is less than the min value, it is replaced by the
  2665. * min value.
  2666. *
  2667. * @param {number} min - The minimum value the vector length will be clamped to.
  2668. * @param {number} max - The maximum value the vector length will be clamped to.
  2669. * @return {Vector2} A reference to this vector.
  2670. */
  2671. clampLength( min, max ) {
  2672. const length = this.length();
  2673. return this.divideScalar( length || 1 ).multiplyScalar( clamp( length, min, max ) );
  2674. }
  2675. /**
  2676. * The components of this vector are rounded down to the nearest integer value.
  2677. *
  2678. * @return {Vector2} A reference to this vector.
  2679. */
  2680. floor() {
  2681. this.x = Math.floor( this.x );
  2682. this.y = Math.floor( this.y );
  2683. return this;
  2684. }
  2685. /**
  2686. * The components of this vector are rounded up to the nearest integer value.
  2687. *
  2688. * @return {Vector2} A reference to this vector.
  2689. */
  2690. ceil() {
  2691. this.x = Math.ceil( this.x );
  2692. this.y = Math.ceil( this.y );
  2693. return this;
  2694. }
  2695. /**
  2696. * The components of this vector are rounded to the nearest integer value
  2697. *
  2698. * @return {Vector2} A reference to this vector.
  2699. */
  2700. round() {
  2701. this.x = Math.round( this.x );
  2702. this.y = Math.round( this.y );
  2703. return this;
  2704. }
  2705. /**
  2706. * The components of this vector are rounded towards zero (up if negative,
  2707. * down if positive) to an integer value.
  2708. *
  2709. * @return {Vector2} A reference to this vector.
  2710. */
  2711. roundToZero() {
  2712. this.x = Math.trunc( this.x );
  2713. this.y = Math.trunc( this.y );
  2714. return this;
  2715. }
  2716. /**
  2717. * Inverts this vector - i.e. sets x = -x and y = -y.
  2718. *
  2719. * @return {Vector2} A reference to this vector.
  2720. */
  2721. negate() {
  2722. this.x = - this.x;
  2723. this.y = - this.y;
  2724. return this;
  2725. }
  2726. /**
  2727. * Calculates the dot product of the given vector with this instance.
  2728. *
  2729. * @param {Vector2} v - The vector to compute the dot product with.
  2730. * @return {number} The result of the dot product.
  2731. */
  2732. dot( v ) {
  2733. return this.x * v.x + this.y * v.y;
  2734. }
  2735. /**
  2736. * Calculates the cross product of the given vector with this instance.
  2737. *
  2738. * @param {Vector2} v - The vector to compute the cross product with.
  2739. * @return {number} The result of the cross product.
  2740. */
  2741. cross( v ) {
  2742. return this.x * v.y - this.y * v.x;
  2743. }
  2744. /**
  2745. * Computes the square of the Euclidean length (straight-line length) from
  2746. * (0, 0) to (x, y). If you are comparing the lengths of vectors, you should
  2747. * compare the length squared instead as it is slightly more efficient to calculate.
  2748. *
  2749. * @return {number} The square length of this vector.
  2750. */
  2751. lengthSq() {
  2752. return this.x * this.x + this.y * this.y;
  2753. }
  2754. /**
  2755. * Computes the Euclidean length (straight-line length) from (0, 0) to (x, y).
  2756. *
  2757. * @return {number} The length of this vector.
  2758. */
  2759. length() {
  2760. return Math.sqrt( this.x * this.x + this.y * this.y );
  2761. }
  2762. /**
  2763. * Computes the Manhattan length of this vector.
  2764. *
  2765. * @return {number} The length of this vector.
  2766. */
  2767. manhattanLength() {
  2768. return Math.abs( this.x ) + Math.abs( this.y );
  2769. }
  2770. /**
  2771. * Converts this vector to a unit vector - that is, sets it equal to a vector
  2772. * with the same direction as this one, but with a vector length of `1`.
  2773. *
  2774. * @return {Vector2} A reference to this vector.
  2775. */
  2776. normalize() {
  2777. return this.divideScalar( this.length() || 1 );
  2778. }
  2779. /**
  2780. * Computes the angle in radians of this vector with respect to the positive x-axis.
  2781. *
  2782. * @return {number} The angle in radians.
  2783. */
  2784. angle() {
  2785. const angle = Math.atan2( - this.y, - this.x ) + Math.PI;
  2786. return angle;
  2787. }
  2788. /**
  2789. * Returns the angle between the given vector and this instance in radians.
  2790. *
  2791. * @param {Vector2} v - The vector to compute the angle with.
  2792. * @return {number} The angle in radians.
  2793. */
  2794. angleTo( v ) {
  2795. const denominator = Math.sqrt( this.lengthSq() * v.lengthSq() );
  2796. if ( denominator === 0 ) return Math.PI / 2;
  2797. const theta = this.dot( v ) / denominator;
  2798. // clamp, to handle numerical problems
  2799. return Math.acos( clamp( theta, -1, 1 ) );
  2800. }
  2801. /**
  2802. * Computes the distance from the given vector to this instance.
  2803. *
  2804. * @param {Vector2} v - The vector to compute the distance to.
  2805. * @return {number} The distance.
  2806. */
  2807. distanceTo( v ) {
  2808. return Math.sqrt( this.distanceToSquared( v ) );
  2809. }
  2810. /**
  2811. * Computes the squared distance from the given vector to this instance.
  2812. * If you are just comparing the distance with another distance, you should compare
  2813. * the distance squared instead as it is slightly more efficient to calculate.
  2814. *
  2815. * @param {Vector2} v - The vector to compute the squared distance to.
  2816. * @return {number} The squared distance.
  2817. */
  2818. distanceToSquared( v ) {
  2819. const dx = this.x - v.x, dy = this.y - v.y;
  2820. return dx * dx + dy * dy;
  2821. }
  2822. /**
  2823. * Computes the Manhattan distance from the given vector to this instance.
  2824. *
  2825. * @param {Vector2} v - The vector to compute the Manhattan distance to.
  2826. * @return {number} The Manhattan distance.
  2827. */
  2828. manhattanDistanceTo( v ) {
  2829. return Math.abs( this.x - v.x ) + Math.abs( this.y - v.y );
  2830. }
  2831. /**
  2832. * Sets this vector to a vector with the same direction as this one, but
  2833. * with the specified length.
  2834. *
  2835. * @param {number} length - The new length of this vector.
  2836. * @return {Vector2} A reference to this vector.
  2837. */
  2838. setLength( length ) {
  2839. return this.normalize().multiplyScalar( length );
  2840. }
  2841. /**
  2842. * Linearly interpolates between the given vector and this instance, where
  2843. * alpha is the percent distance along the line - alpha = 0 will be this
  2844. * vector, and alpha = 1 will be the given one.
  2845. *
  2846. * @param {Vector2} v - The vector to interpolate towards.
  2847. * @param {number} alpha - The interpolation factor, typically in the closed interval `[0, 1]`.
  2848. * @return {Vector2} A reference to this vector.
  2849. */
  2850. lerp( v, alpha ) {
  2851. this.x += ( v.x - this.x ) * alpha;
  2852. this.y += ( v.y - this.y ) * alpha;
  2853. return this;
  2854. }
  2855. /**
  2856. * Linearly interpolates between the given vectors, where alpha is the percent
  2857. * distance along the line - alpha = 0 will be first vector, and alpha = 1 will
  2858. * be the second one. The result is stored in this instance.
  2859. *
  2860. * @param {Vector2} v1 - The first vector.
  2861. * @param {Vector2} v2 - The second vector.
  2862. * @param {number} alpha - The interpolation factor, typically in the closed interval `[0, 1]`.
  2863. * @return {Vector2} A reference to this vector.
  2864. */
  2865. lerpVectors( v1, v2, alpha ) {
  2866. this.x = v1.x + ( v2.x - v1.x ) * alpha;
  2867. this.y = v1.y + ( v2.y - v1.y ) * alpha;
  2868. return this;
  2869. }
  2870. /**
  2871. * Returns `true` if this vector is equal with the given one.
  2872. *
  2873. * @param {Vector2} v - The vector to test for equality.
  2874. * @return {boolean} Whether this vector is equal with the given one.
  2875. */
  2876. equals( v ) {
  2877. return ( ( v.x === this.x ) && ( v.y === this.y ) );
  2878. }
  2879. /**
  2880. * Sets this vector's x value to be `array[ offset ]` and y
  2881. * value to be `array[ offset + 1 ]`.
  2882. *
  2883. * @param {Array<number>} array - An array holding the vector component values.
  2884. * @param {number} [offset=0] - The offset into the array.
  2885. * @return {Vector2} A reference to this vector.
  2886. */
  2887. fromArray( array, offset = 0 ) {
  2888. this.x = array[ offset ];
  2889. this.y = array[ offset + 1 ];
  2890. return this;
  2891. }
  2892. /**
  2893. * Writes the components of this vector to the given array. If no array is provided,
  2894. * the method returns a new instance.
  2895. *
  2896. * @param {Array<number>} [array=[]] - The target array holding the vector components.
  2897. * @param {number} [offset=0] - Index of the first element in the array.
  2898. * @return {Array<number>} The vector components.
  2899. */
  2900. toArray( array = [], offset = 0 ) {
  2901. array[ offset ] = this.x;
  2902. array[ offset + 1 ] = this.y;
  2903. return array;
  2904. }
  2905. /**
  2906. * Sets the components of this vector from the given buffer attribute.
  2907. *
  2908. * @param {BufferAttribute} attribute - The buffer attribute holding vector data.
  2909. * @param {number} index - The index into the attribute.
  2910. * @return {Vector2} A reference to this vector.
  2911. */
  2912. fromBufferAttribute( attribute, index ) {
  2913. this.x = attribute.getX( index );
  2914. this.y = attribute.getY( index );
  2915. return this;
  2916. }
  2917. /**
  2918. * Rotates this vector around the given center by the given angle.
  2919. *
  2920. * @param {Vector2} center - The point around which to rotate.
  2921. * @param {number} angle - The angle to rotate, in radians.
  2922. * @return {Vector2} A reference to this vector.
  2923. */
  2924. rotateAround( center, angle ) {
  2925. const c = Math.cos( angle ), s = Math.sin( angle );
  2926. const x = this.x - center.x;
  2927. const y = this.y - center.y;
  2928. this.x = x * c - y * s + center.x;
  2929. this.y = x * s + y * c + center.y;
  2930. return this;
  2931. }
  2932. /**
  2933. * Sets each component of this vector to a pseudo-random value between `0` and
  2934. * `1`, excluding `1`.
  2935. *
  2936. * @return {Vector2} A reference to this vector.
  2937. */
  2938. random() {
  2939. this.x = Math.random();
  2940. this.y = Math.random();
  2941. return this;
  2942. }
  2943. *[ Symbol.iterator ]() {
  2944. yield this.x;
  2945. yield this.y;
  2946. }
  2947. }
  2948. /**
  2949. * Class for representing a Quaternion. Quaternions are used in three.js to represent rotations.
  2950. *
  2951. * Iterating through a vector instance will yield its components `(x, y, z, w)` in
  2952. * the corresponding order.
  2953. *
  2954. * Note that three.js expects Quaternions to be normalized.
  2955. * ```js
  2956. * const quaternion = new THREE.Quaternion();
  2957. * quaternion.setFromAxisAngle( new THREE.Vector3( 0, 1, 0 ), Math.PI / 2 );
  2958. *
  2959. * const vector = new THREE.Vector3( 1, 0, 0 );
  2960. * vector.applyQuaternion( quaternion );
  2961. * ```
  2962. */
  2963. class Quaternion {
  2964. /**
  2965. * Constructs a new quaternion.
  2966. *
  2967. * @param {number} [x=0] - The x value of this quaternion.
  2968. * @param {number} [y=0] - The y value of this quaternion.
  2969. * @param {number} [z=0] - The z value of this quaternion.
  2970. * @param {number} [w=1] - The w value of this quaternion.
  2971. */
  2972. constructor( x = 0, y = 0, z = 0, w = 1 ) {
  2973. /**
  2974. * This flag can be used for type testing.
  2975. *
  2976. * @type {boolean}
  2977. * @readonly
  2978. * @default true
  2979. */
  2980. this.isQuaternion = true;
  2981. this._x = x;
  2982. this._y = y;
  2983. this._z = z;
  2984. this._w = w;
  2985. }
  2986. /**
  2987. * Interpolates between two quaternions via SLERP. This implementation assumes the
  2988. * quaternion data are managed in flat arrays.
  2989. *
  2990. * @param {Array<number>} dst - The destination array.
  2991. * @param {number} dstOffset - An offset into the destination array.
  2992. * @param {Array<number>} src0 - The source array of the first quaternion.
  2993. * @param {number} srcOffset0 - An offset into the first source array.
  2994. * @param {Array<number>} src1 - The source array of the second quaternion.
  2995. * @param {number} srcOffset1 - An offset into the second source array.
  2996. * @param {number} t - The interpolation factor. A value in the range `[0,1]` will interpolate. A value outside the range `[0,1]` will extrapolate.
  2997. * @see {@link Quaternion#slerp}
  2998. */
  2999. static slerpFlat( dst, dstOffset, src0, srcOffset0, src1, srcOffset1, t ) {
  3000. let x0 = src0[ srcOffset0 + 0 ],
  3001. y0 = src0[ srcOffset0 + 1 ],
  3002. z0 = src0[ srcOffset0 + 2 ],
  3003. w0 = src0[ srcOffset0 + 3 ];
  3004. let x1 = src1[ srcOffset1 + 0 ],
  3005. y1 = src1[ srcOffset1 + 1 ],
  3006. z1 = src1[ srcOffset1 + 2 ],
  3007. w1 = src1[ srcOffset1 + 3 ];
  3008. if ( w0 !== w1 || x0 !== x1 || y0 !== y1 || z0 !== z1 ) {
  3009. let dot = x0 * x1 + y0 * y1 + z0 * z1 + w0 * w1;
  3010. if ( dot < 0 ) {
  3011. x1 = - x1;
  3012. y1 = - y1;
  3013. z1 = - z1;
  3014. w1 = - w1;
  3015. dot = - dot;
  3016. }
  3017. let s = 1 - t;
  3018. if ( dot < 0.9995 ) {
  3019. // slerp
  3020. const theta = Math.acos( dot );
  3021. const sin = Math.sin( theta );
  3022. s = Math.sin( s * theta ) / sin;
  3023. t = Math.sin( t * theta ) / sin;
  3024. x0 = x0 * s + x1 * t;
  3025. y0 = y0 * s + y1 * t;
  3026. z0 = z0 * s + z1 * t;
  3027. w0 = w0 * s + w1 * t;
  3028. } else {
  3029. // for small angles, lerp then normalize
  3030. x0 = x0 * s + x1 * t;
  3031. y0 = y0 * s + y1 * t;
  3032. z0 = z0 * s + z1 * t;
  3033. w0 = w0 * s + w1 * t;
  3034. const f = 1 / Math.sqrt( x0 * x0 + y0 * y0 + z0 * z0 + w0 * w0 );
  3035. x0 *= f;
  3036. y0 *= f;
  3037. z0 *= f;
  3038. w0 *= f;
  3039. }
  3040. }
  3041. dst[ dstOffset ] = x0;
  3042. dst[ dstOffset + 1 ] = y0;
  3043. dst[ dstOffset + 2 ] = z0;
  3044. dst[ dstOffset + 3 ] = w0;
  3045. }
  3046. /**
  3047. * Multiplies two quaternions. This implementation assumes the quaternion data are managed
  3048. * in flat arrays.
  3049. *
  3050. * @param {Array<number>} dst - The destination array.
  3051. * @param {number} dstOffset - An offset into the destination array.
  3052. * @param {Array<number>} src0 - The source array of the first quaternion.
  3053. * @param {number} srcOffset0 - An offset into the first source array.
  3054. * @param {Array<number>} src1 - The source array of the second quaternion.
  3055. * @param {number} srcOffset1 - An offset into the second source array.
  3056. * @return {Array<number>} The destination array.
  3057. * @see {@link Quaternion#multiplyQuaternions}.
  3058. */
  3059. static multiplyQuaternionsFlat( dst, dstOffset, src0, srcOffset0, src1, srcOffset1 ) {
  3060. const x0 = src0[ srcOffset0 ];
  3061. const y0 = src0[ srcOffset0 + 1 ];
  3062. const z0 = src0[ srcOffset0 + 2 ];
  3063. const w0 = src0[ srcOffset0 + 3 ];
  3064. const x1 = src1[ srcOffset1 ];
  3065. const y1 = src1[ srcOffset1 + 1 ];
  3066. const z1 = src1[ srcOffset1 + 2 ];
  3067. const w1 = src1[ srcOffset1 + 3 ];
  3068. dst[ dstOffset ] = x0 * w1 + w0 * x1 + y0 * z1 - z0 * y1;
  3069. dst[ dstOffset + 1 ] = y0 * w1 + w0 * y1 + z0 * x1 - x0 * z1;
  3070. dst[ dstOffset + 2 ] = z0 * w1 + w0 * z1 + x0 * y1 - y0 * x1;
  3071. dst[ dstOffset + 3 ] = w0 * w1 - x0 * x1 - y0 * y1 - z0 * z1;
  3072. return dst;
  3073. }
  3074. /**
  3075. * The x value of this quaternion.
  3076. *
  3077. * @type {number}
  3078. * @default 0
  3079. */
  3080. get x() {
  3081. return this._x;
  3082. }
  3083. set x( value ) {
  3084. this._x = value;
  3085. this._onChangeCallback();
  3086. }
  3087. /**
  3088. * The y value of this quaternion.
  3089. *
  3090. * @type {number}
  3091. * @default 0
  3092. */
  3093. get y() {
  3094. return this._y;
  3095. }
  3096. set y( value ) {
  3097. this._y = value;
  3098. this._onChangeCallback();
  3099. }
  3100. /**
  3101. * The z value of this quaternion.
  3102. *
  3103. * @type {number}
  3104. * @default 0
  3105. */
  3106. get z() {
  3107. return this._z;
  3108. }
  3109. set z( value ) {
  3110. this._z = value;
  3111. this._onChangeCallback();
  3112. }
  3113. /**
  3114. * The w value of this quaternion.
  3115. *
  3116. * @type {number}
  3117. * @default 1
  3118. */
  3119. get w() {
  3120. return this._w;
  3121. }
  3122. set w( value ) {
  3123. this._w = value;
  3124. this._onChangeCallback();
  3125. }
  3126. /**
  3127. * Sets the quaternion components.
  3128. *
  3129. * @param {number} x - The x value of this quaternion.
  3130. * @param {number} y - The y value of this quaternion.
  3131. * @param {number} z - The z value of this quaternion.
  3132. * @param {number} w - The w value of this quaternion.
  3133. * @return {Quaternion} A reference to this quaternion.
  3134. */
  3135. set( x, y, z, w ) {
  3136. this._x = x;
  3137. this._y = y;
  3138. this._z = z;
  3139. this._w = w;
  3140. this._onChangeCallback();
  3141. return this;
  3142. }
  3143. /**
  3144. * Returns a new quaternion with copied values from this instance.
  3145. *
  3146. * @return {Quaternion} A clone of this instance.
  3147. */
  3148. clone() {
  3149. return new this.constructor( this._x, this._y, this._z, this._w );
  3150. }
  3151. /**
  3152. * Copies the values of the given quaternion to this instance.
  3153. *
  3154. * @param {Quaternion} quaternion - The quaternion to copy.
  3155. * @return {Quaternion} A reference to this quaternion.
  3156. */
  3157. copy( quaternion ) {
  3158. this._x = quaternion.x;
  3159. this._y = quaternion.y;
  3160. this._z = quaternion.z;
  3161. this._w = quaternion.w;
  3162. this._onChangeCallback();
  3163. return this;
  3164. }
  3165. /**
  3166. * Sets this quaternion from the rotation specified by the given
  3167. * Euler angles.
  3168. *
  3169. * @param {Euler} euler - The Euler angles.
  3170. * @param {boolean} [update=true] - Whether the internal `onChange` callback should be executed or not.
  3171. * @return {Quaternion} A reference to this quaternion.
  3172. */
  3173. setFromEuler( euler, update = true ) {
  3174. const x = euler._x, y = euler._y, z = euler._z, order = euler._order;
  3175. // http://www.mathworks.com/matlabcentral/fileexchange/
  3176. // 20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/
  3177. // content/SpinCalc.m
  3178. const cos = Math.cos;
  3179. const sin = Math.sin;
  3180. const c1 = cos( x / 2 );
  3181. const c2 = cos( y / 2 );
  3182. const c3 = cos( z / 2 );
  3183. const s1 = sin( x / 2 );
  3184. const s2 = sin( y / 2 );
  3185. const s3 = sin( z / 2 );
  3186. switch ( order ) {
  3187. case 'XYZ':
  3188. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  3189. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  3190. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  3191. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  3192. break;
  3193. case 'YXZ':
  3194. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  3195. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  3196. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  3197. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  3198. break;
  3199. case 'ZXY':
  3200. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  3201. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  3202. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  3203. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  3204. break;
  3205. case 'ZYX':
  3206. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  3207. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  3208. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  3209. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  3210. break;
  3211. case 'YZX':
  3212. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  3213. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  3214. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  3215. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  3216. break;
  3217. case 'XZY':
  3218. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  3219. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  3220. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  3221. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  3222. break;
  3223. default:
  3224. warn( 'Quaternion: .setFromEuler() encountered an unknown order: ' + order );
  3225. }
  3226. if ( update === true ) this._onChangeCallback();
  3227. return this;
  3228. }
  3229. /**
  3230. * Sets this quaternion from the given axis and angle.
  3231. *
  3232. * @param {Vector3} axis - The normalized axis.
  3233. * @param {number} angle - The angle in radians.
  3234. * @return {Quaternion} A reference to this quaternion.
  3235. */
  3236. setFromAxisAngle( axis, angle ) {
  3237. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm
  3238. const halfAngle = angle / 2, s = Math.sin( halfAngle );
  3239. this._x = axis.x * s;
  3240. this._y = axis.y * s;
  3241. this._z = axis.z * s;
  3242. this._w = Math.cos( halfAngle );
  3243. this._onChangeCallback();
  3244. return this;
  3245. }
  3246. /**
  3247. * Sets this quaternion from the given rotation matrix.
  3248. *
  3249. * @param {Matrix4} m - A 4x4 matrix of which the upper 3x3 of matrix is a pure rotation matrix (i.e. unscaled).
  3250. * @return {Quaternion} A reference to this quaternion.
  3251. */
  3252. setFromRotationMatrix( m ) {
  3253. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm
  3254. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  3255. const te = m.elements,
  3256. m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ],
  3257. m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ],
  3258. m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ],
  3259. trace = m11 + m22 + m33;
  3260. if ( trace > 0 ) {
  3261. const s = 0.5 / Math.sqrt( trace + 1.0 );
  3262. this._w = 0.25 / s;
  3263. this._x = ( m32 - m23 ) * s;
  3264. this._y = ( m13 - m31 ) * s;
  3265. this._z = ( m21 - m12 ) * s;
  3266. } else if ( m11 > m22 && m11 > m33 ) {
  3267. const s = 2.0 * Math.sqrt( 1.0 + m11 - m22 - m33 );
  3268. this._w = ( m32 - m23 ) / s;
  3269. this._x = 0.25 * s;
  3270. this._y = ( m12 + m21 ) / s;
  3271. this._z = ( m13 + m31 ) / s;
  3272. } else if ( m22 > m33 ) {
  3273. const s = 2.0 * Math.sqrt( 1.0 + m22 - m11 - m33 );
  3274. this._w = ( m13 - m31 ) / s;
  3275. this._x = ( m12 + m21 ) / s;
  3276. this._y = 0.25 * s;
  3277. this._z = ( m23 + m32 ) / s;
  3278. } else {
  3279. const s = 2.0 * Math.sqrt( 1.0 + m33 - m11 - m22 );
  3280. this._w = ( m21 - m12 ) / s;
  3281. this._x = ( m13 + m31 ) / s;
  3282. this._y = ( m23 + m32 ) / s;
  3283. this._z = 0.25 * s;
  3284. }
  3285. this._onChangeCallback();
  3286. return this;
  3287. }
  3288. /**
  3289. * Sets this quaternion to the rotation required to rotate the direction vector
  3290. * `vFrom` to the direction vector `vTo`.
  3291. *
  3292. * @param {Vector3} vFrom - The first (normalized) direction vector.
  3293. * @param {Vector3} vTo - The second (normalized) direction vector.
  3294. * @return {Quaternion} A reference to this quaternion.
  3295. */
  3296. setFromUnitVectors( vFrom, vTo ) {
  3297. // assumes direction vectors vFrom and vTo are normalized
  3298. let r = vFrom.dot( vTo ) + 1;
  3299. if ( r < 1e-8 ) { // the epsilon value has been discussed in #31286
  3300. // vFrom and vTo point in opposite directions
  3301. r = 0;
  3302. if ( Math.abs( vFrom.x ) > Math.abs( vFrom.z ) ) {
  3303. this._x = - vFrom.y;
  3304. this._y = vFrom.x;
  3305. this._z = 0;
  3306. this._w = r;
  3307. } else {
  3308. this._x = 0;
  3309. this._y = - vFrom.z;
  3310. this._z = vFrom.y;
  3311. this._w = r;
  3312. }
  3313. } else {
  3314. // crossVectors( vFrom, vTo ); // inlined to avoid cyclic dependency on Vector3
  3315. this._x = vFrom.y * vTo.z - vFrom.z * vTo.y;
  3316. this._y = vFrom.z * vTo.x - vFrom.x * vTo.z;
  3317. this._z = vFrom.x * vTo.y - vFrom.y * vTo.x;
  3318. this._w = r;
  3319. }
  3320. return this.normalize();
  3321. }
  3322. /**
  3323. * Returns the angle between this quaternion and the given one in radians.
  3324. *
  3325. * @param {Quaternion} q - The quaternion to compute the angle with.
  3326. * @return {number} The angle in radians.
  3327. */
  3328. angleTo( q ) {
  3329. return 2 * Math.acos( Math.abs( clamp( this.dot( q ), -1, 1 ) ) );
  3330. }
  3331. /**
  3332. * Rotates this quaternion by a given angular step to the given quaternion.
  3333. * The method ensures that the final quaternion will not overshoot `q`.
  3334. *
  3335. * @param {Quaternion} q - The target quaternion.
  3336. * @param {number} step - The angular step in radians.
  3337. * @return {Quaternion} A reference to this quaternion.
  3338. */
  3339. rotateTowards( q, step ) {
  3340. const angle = this.angleTo( q );
  3341. if ( angle === 0 ) return this;
  3342. const t = Math.min( 1, step / angle );
  3343. this.slerp( q, t );
  3344. return this;
  3345. }
  3346. /**
  3347. * Sets this quaternion to the identity quaternion; that is, to the
  3348. * quaternion that represents "no rotation".
  3349. *
  3350. * @return {Quaternion} A reference to this quaternion.
  3351. */
  3352. identity() {
  3353. return this.set( 0, 0, 0, 1 );
  3354. }
  3355. /**
  3356. * Inverts this quaternion via {@link Quaternion#conjugate}. The
  3357. * quaternion is assumed to have unit length.
  3358. *
  3359. * @return {Quaternion} A reference to this quaternion.
  3360. */
  3361. invert() {
  3362. return this.conjugate();
  3363. }
  3364. /**
  3365. * Returns the rotational conjugate of this quaternion. The conjugate of a
  3366. * quaternion represents the same rotation in the opposite direction about
  3367. * the rotational axis.
  3368. *
  3369. * @return {Quaternion} A reference to this quaternion.
  3370. */
  3371. conjugate() {
  3372. this._x *= -1;
  3373. this._y *= -1;
  3374. this._z *= -1;
  3375. this._onChangeCallback();
  3376. return this;
  3377. }
  3378. /**
  3379. * Calculates the dot product of this quaternion and the given one.
  3380. *
  3381. * @param {Quaternion} v - The quaternion to compute the dot product with.
  3382. * @return {number} The result of the dot product.
  3383. */
  3384. dot( v ) {
  3385. return this._x * v._x + this._y * v._y + this._z * v._z + this._w * v._w;
  3386. }
  3387. /**
  3388. * Computes the squared Euclidean length (straight-line length) of this quaternion,
  3389. * considered as a 4 dimensional vector. This can be useful if you are comparing the
  3390. * lengths of two quaternions, as this is a slightly more efficient calculation than
  3391. * {@link Quaternion#length}.
  3392. *
  3393. * @return {number} The squared Euclidean length.
  3394. */
  3395. lengthSq() {
  3396. return this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w;
  3397. }
  3398. /**
  3399. * Computes the Euclidean length (straight-line length) of this quaternion,
  3400. * considered as a 4 dimensional vector.
  3401. *
  3402. * @return {number} The Euclidean length.
  3403. */
  3404. length() {
  3405. return Math.sqrt( this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w );
  3406. }
  3407. /**
  3408. * Normalizes this quaternion - that is, calculated the quaternion that performs
  3409. * the same rotation as this one, but has a length equal to `1`.
  3410. *
  3411. * @return {Quaternion} A reference to this quaternion.
  3412. */
  3413. normalize() {
  3414. let l = this.length();
  3415. if ( l === 0 ) {
  3416. this._x = 0;
  3417. this._y = 0;
  3418. this._z = 0;
  3419. this._w = 1;
  3420. } else {
  3421. l = 1 / l;
  3422. this._x = this._x * l;
  3423. this._y = this._y * l;
  3424. this._z = this._z * l;
  3425. this._w = this._w * l;
  3426. }
  3427. this._onChangeCallback();
  3428. return this;
  3429. }
  3430. /**
  3431. * Multiplies this quaternion by the given one.
  3432. *
  3433. * @param {Quaternion} q - The quaternion.
  3434. * @return {Quaternion} A reference to this quaternion.
  3435. */
  3436. multiply( q ) {
  3437. return this.multiplyQuaternions( this, q );
  3438. }
  3439. /**
  3440. * Pre-multiplies this quaternion by the given one.
  3441. *
  3442. * @param {Quaternion} q - The quaternion.
  3443. * @return {Quaternion} A reference to this quaternion.
  3444. */
  3445. premultiply( q ) {
  3446. return this.multiplyQuaternions( q, this );
  3447. }
  3448. /**
  3449. * Multiplies the given quaternions and stores the result in this instance.
  3450. *
  3451. * @param {Quaternion} a - The first quaternion.
  3452. * @param {Quaternion} b - The second quaternion.
  3453. * @return {Quaternion} A reference to this quaternion.
  3454. */
  3455. multiplyQuaternions( a, b ) {
  3456. // from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm
  3457. const qax = a._x, qay = a._y, qaz = a._z, qaw = a._w;
  3458. const qbx = b._x, qby = b._y, qbz = b._z, qbw = b._w;
  3459. this._x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby;
  3460. this._y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz;
  3461. this._z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx;
  3462. this._w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz;
  3463. this._onChangeCallback();
  3464. return this;
  3465. }
  3466. /**
  3467. * Performs a spherical linear interpolation between this quaternion and the target quaternion.
  3468. *
  3469. * @param {Quaternion} qb - The target quaternion.
  3470. * @param {number} t - The interpolation factor. A value in the range `[0,1]` will interpolate. A value outside the range `[0,1]` will extrapolate.
  3471. * @return {Quaternion} A reference to this quaternion.
  3472. */
  3473. slerp( qb, t ) {
  3474. let x = qb._x, y = qb._y, z = qb._z, w = qb._w;
  3475. let dot = this.dot( qb );
  3476. if ( dot < 0 ) {
  3477. x = - x;
  3478. y = - y;
  3479. z = - z;
  3480. w = - w;
  3481. dot = - dot;
  3482. }
  3483. let s = 1 - t;
  3484. if ( dot < 0.9995 ) {
  3485. // slerp
  3486. const theta = Math.acos( dot );
  3487. const sin = Math.sin( theta );
  3488. s = Math.sin( s * theta ) / sin;
  3489. t = Math.sin( t * theta ) / sin;
  3490. this._x = this._x * s + x * t;
  3491. this._y = this._y * s + y * t;
  3492. this._z = this._z * s + z * t;
  3493. this._w = this._w * s + w * t;
  3494. this._onChangeCallback();
  3495. } else {
  3496. // for small angles, lerp then normalize
  3497. this._x = this._x * s + x * t;
  3498. this._y = this._y * s + y * t;
  3499. this._z = this._z * s + z * t;
  3500. this._w = this._w * s + w * t;
  3501. this.normalize(); // normalize calls _onChangeCallback()
  3502. }
  3503. return this;
  3504. }
  3505. /**
  3506. * Performs a spherical linear interpolation between the given quaternions
  3507. * and stores the result in this quaternion.
  3508. *
  3509. * @param {Quaternion} qa - The source quaternion.
  3510. * @param {Quaternion} qb - The target quaternion.
  3511. * @param {number} t - The interpolation factor in the closed interval `[0, 1]`.
  3512. * @return {Quaternion} A reference to this quaternion.
  3513. */
  3514. slerpQuaternions( qa, qb, t ) {
  3515. return this.copy( qa ).slerp( qb, t );
  3516. }
  3517. /**
  3518. * Sets this quaternion to a uniformly random, normalized quaternion.
  3519. *
  3520. * @return {Quaternion} A reference to this quaternion.
  3521. */
  3522. random() {
  3523. // Ken Shoemake
  3524. // Uniform random rotations
  3525. // D. Kirk, editor, Graphics Gems III, pages 124-132. Academic Press, New York, 1992.
  3526. const theta1 = 2 * Math.PI * Math.random();
  3527. const theta2 = 2 * Math.PI * Math.random();
  3528. const x0 = Math.random();
  3529. const r1 = Math.sqrt( 1 - x0 );
  3530. const r2 = Math.sqrt( x0 );
  3531. return this.set(
  3532. r1 * Math.sin( theta1 ),
  3533. r1 * Math.cos( theta1 ),
  3534. r2 * Math.sin( theta2 ),
  3535. r2 * Math.cos( theta2 ),
  3536. );
  3537. }
  3538. /**
  3539. * Returns `true` if this quaternion is equal with the given one.
  3540. *
  3541. * @param {Quaternion} quaternion - The quaternion to test for equality.
  3542. * @return {boolean} Whether this quaternion is equal with the given one.
  3543. */
  3544. equals( quaternion ) {
  3545. return ( quaternion._x === this._x ) && ( quaternion._y === this._y ) && ( quaternion._z === this._z ) && ( quaternion._w === this._w );
  3546. }
  3547. /**
  3548. * Sets this quaternion's components from the given array.
  3549. *
  3550. * @param {Array<number>} array - An array holding the quaternion component values.
  3551. * @param {number} [offset=0] - The offset into the array.
  3552. * @return {Quaternion} A reference to this quaternion.
  3553. */
  3554. fromArray( array, offset = 0 ) {
  3555. this._x = array[ offset ];
  3556. this._y = array[ offset + 1 ];
  3557. this._z = array[ offset + 2 ];
  3558. this._w = array[ offset + 3 ];
  3559. this._onChangeCallback();
  3560. return this;
  3561. }
  3562. /**
  3563. * Writes the components of this quaternion to the given array. If no array is provided,
  3564. * the method returns a new instance.
  3565. *
  3566. * @param {Array<number>} [array=[]] - The target array holding the quaternion components.
  3567. * @param {number} [offset=0] - Index of the first element in the array.
  3568. * @return {Array<number>} The quaternion components.
  3569. */
  3570. toArray( array = [], offset = 0 ) {
  3571. array[ offset ] = this._x;
  3572. array[ offset + 1 ] = this._y;
  3573. array[ offset + 2 ] = this._z;
  3574. array[ offset + 3 ] = this._w;
  3575. return array;
  3576. }
  3577. /**
  3578. * Sets the components of this quaternion from the given buffer attribute.
  3579. *
  3580. * @param {BufferAttribute} attribute - The buffer attribute holding quaternion data.
  3581. * @param {number} index - The index into the attribute.
  3582. * @return {Quaternion} A reference to this quaternion.
  3583. */
  3584. fromBufferAttribute( attribute, index ) {
  3585. this._x = attribute.getX( index );
  3586. this._y = attribute.getY( index );
  3587. this._z = attribute.getZ( index );
  3588. this._w = attribute.getW( index );
  3589. this._onChangeCallback();
  3590. return this;
  3591. }
  3592. /**
  3593. * This methods defines the serialization result of this class. Returns the
  3594. * numerical elements of this quaternion in an array of format `[x, y, z, w]`.
  3595. *
  3596. * @return {Array<number>} The serialized quaternion.
  3597. */
  3598. toJSON() {
  3599. return this.toArray();
  3600. }
  3601. _onChange( callback ) {
  3602. this._onChangeCallback = callback;
  3603. return this;
  3604. }
  3605. _onChangeCallback() {}
  3606. *[ Symbol.iterator ]() {
  3607. yield this._x;
  3608. yield this._y;
  3609. yield this._z;
  3610. yield this._w;
  3611. }
  3612. }
  3613. /**
  3614. * Class representing a 3D vector. A 3D vector is an ordered triplet of numbers
  3615. * (labeled x, y and z), which can be used to represent a number of things, such as:
  3616. *
  3617. * - A point in 3D space.
  3618. * - A direction and length in 3D space. In three.js the length will
  3619. * always be the Euclidean distance(straight-line distance) from `(0, 0, 0)` to `(x, y, z)`
  3620. * and the direction is also measured from `(0, 0, 0)` towards `(x, y, z)`.
  3621. * - Any arbitrary ordered triplet of numbers.
  3622. *
  3623. * There are other things a 3D vector can be used to represent, such as
  3624. * momentum vectors and so on, however these are the most
  3625. * common uses in three.js.
  3626. *
  3627. * Iterating through a vector instance will yield its components `(x, y, z)` in
  3628. * the corresponding order.
  3629. * ```js
  3630. * const a = new THREE.Vector3( 0, 1, 0 );
  3631. *
  3632. * //no arguments; will be initialised to (0, 0, 0)
  3633. * const b = new THREE.Vector3( );
  3634. *
  3635. * const d = a.distanceTo( b );
  3636. * ```
  3637. */
  3638. class Vector3 {
  3639. /**
  3640. * Constructs a new 3D vector.
  3641. *
  3642. * @param {number} [x=0] - The x value of this vector.
  3643. * @param {number} [y=0] - The y value of this vector.
  3644. * @param {number} [z=0] - The z value of this vector.
  3645. */
  3646. constructor( x = 0, y = 0, z = 0 ) {
  3647. /**
  3648. * This flag can be used for type testing.
  3649. *
  3650. * @type {boolean}
  3651. * @readonly
  3652. * @default true
  3653. */
  3654. Vector3.prototype.isVector3 = true;
  3655. /**
  3656. * The x value of this vector.
  3657. *
  3658. * @type {number}
  3659. */
  3660. this.x = x;
  3661. /**
  3662. * The y value of this vector.
  3663. *
  3664. * @type {number}
  3665. */
  3666. this.y = y;
  3667. /**
  3668. * The z value of this vector.
  3669. *
  3670. * @type {number}
  3671. */
  3672. this.z = z;
  3673. }
  3674. /**
  3675. * Sets the vector components.
  3676. *
  3677. * @param {number} x - The value of the x component.
  3678. * @param {number} y - The value of the y component.
  3679. * @param {number} z - The value of the z component.
  3680. * @return {Vector3} A reference to this vector.
  3681. */
  3682. set( x, y, z ) {
  3683. if ( z === undefined ) z = this.z; // sprite.scale.set(x,y)
  3684. this.x = x;
  3685. this.y = y;
  3686. this.z = z;
  3687. return this;
  3688. }
  3689. /**
  3690. * Sets the vector components to the same value.
  3691. *
  3692. * @param {number} scalar - The value to set for all vector components.
  3693. * @return {Vector3} A reference to this vector.
  3694. */
  3695. setScalar( scalar ) {
  3696. this.x = scalar;
  3697. this.y = scalar;
  3698. this.z = scalar;
  3699. return this;
  3700. }
  3701. /**
  3702. * Sets the vector's x component to the given value
  3703. *
  3704. * @param {number} x - The value to set.
  3705. * @return {Vector3} A reference to this vector.
  3706. */
  3707. setX( x ) {
  3708. this.x = x;
  3709. return this;
  3710. }
  3711. /**
  3712. * Sets the vector's y component to the given value
  3713. *
  3714. * @param {number} y - The value to set.
  3715. * @return {Vector3} A reference to this vector.
  3716. */
  3717. setY( y ) {
  3718. this.y = y;
  3719. return this;
  3720. }
  3721. /**
  3722. * Sets the vector's z component to the given value
  3723. *
  3724. * @param {number} z - The value to set.
  3725. * @return {Vector3} A reference to this vector.
  3726. */
  3727. setZ( z ) {
  3728. this.z = z;
  3729. return this;
  3730. }
  3731. /**
  3732. * Allows to set a vector component with an index.
  3733. *
  3734. * @param {number} index - The component index. `0` equals to x, `1` equals to y, `2` equals to z.
  3735. * @param {number} value - The value to set.
  3736. * @return {Vector3} A reference to this vector.
  3737. */
  3738. setComponent( index, value ) {
  3739. switch ( index ) {
  3740. case 0: this.x = value; break;
  3741. case 1: this.y = value; break;
  3742. case 2: this.z = value; break;
  3743. default: throw new Error( 'index is out of range: ' + index );
  3744. }
  3745. return this;
  3746. }
  3747. /**
  3748. * Returns the value of the vector component which matches the given index.
  3749. *
  3750. * @param {number} index - The component index. `0` equals to x, `1` equals to y, `2` equals to z.
  3751. * @return {number} A vector component value.
  3752. */
  3753. getComponent( index ) {
  3754. switch ( index ) {
  3755. case 0: return this.x;
  3756. case 1: return this.y;
  3757. case 2: return this.z;
  3758. default: throw new Error( 'index is out of range: ' + index );
  3759. }
  3760. }
  3761. /**
  3762. * Returns a new vector with copied values from this instance.
  3763. *
  3764. * @return {Vector3} A clone of this instance.
  3765. */
  3766. clone() {
  3767. return new this.constructor( this.x, this.y, this.z );
  3768. }
  3769. /**
  3770. * Copies the values of the given vector to this instance.
  3771. *
  3772. * @param {Vector3} v - The vector to copy.
  3773. * @return {Vector3} A reference to this vector.
  3774. */
  3775. copy( v ) {
  3776. this.x = v.x;
  3777. this.y = v.y;
  3778. this.z = v.z;
  3779. return this;
  3780. }
  3781. /**
  3782. * Adds the given vector to this instance.
  3783. *
  3784. * @param {Vector3} v - The vector to add.
  3785. * @return {Vector3} A reference to this vector.
  3786. */
  3787. add( v ) {
  3788. this.x += v.x;
  3789. this.y += v.y;
  3790. this.z += v.z;
  3791. return this;
  3792. }
  3793. /**
  3794. * Adds the given scalar value to all components of this instance.
  3795. *
  3796. * @param {number} s - The scalar to add.
  3797. * @return {Vector3} A reference to this vector.
  3798. */
  3799. addScalar( s ) {
  3800. this.x += s;
  3801. this.y += s;
  3802. this.z += s;
  3803. return this;
  3804. }
  3805. /**
  3806. * Adds the given vectors and stores the result in this instance.
  3807. *
  3808. * @param {Vector3} a - The first vector.
  3809. * @param {Vector3} b - The second vector.
  3810. * @return {Vector3} A reference to this vector.
  3811. */
  3812. addVectors( a, b ) {
  3813. this.x = a.x + b.x;
  3814. this.y = a.y + b.y;
  3815. this.z = a.z + b.z;
  3816. return this;
  3817. }
  3818. /**
  3819. * Adds the given vector scaled by the given factor to this instance.
  3820. *
  3821. * @param {Vector3|Vector4} v - The vector.
  3822. * @param {number} s - The factor that scales `v`.
  3823. * @return {Vector3} A reference to this vector.
  3824. */
  3825. addScaledVector( v, s ) {
  3826. this.x += v.x * s;
  3827. this.y += v.y * s;
  3828. this.z += v.z * s;
  3829. return this;
  3830. }
  3831. /**
  3832. * Subtracts the given vector from this instance.
  3833. *
  3834. * @param {Vector3} v - The vector to subtract.
  3835. * @return {Vector3} A reference to this vector.
  3836. */
  3837. sub( v ) {
  3838. this.x -= v.x;
  3839. this.y -= v.y;
  3840. this.z -= v.z;
  3841. return this;
  3842. }
  3843. /**
  3844. * Subtracts the given scalar value from all components of this instance.
  3845. *
  3846. * @param {number} s - The scalar to subtract.
  3847. * @return {Vector3} A reference to this vector.
  3848. */
  3849. subScalar( s ) {
  3850. this.x -= s;
  3851. this.y -= s;
  3852. this.z -= s;
  3853. return this;
  3854. }
  3855. /**
  3856. * Subtracts the given vectors and stores the result in this instance.
  3857. *
  3858. * @param {Vector3} a - The first vector.
  3859. * @param {Vector3} b - The second vector.
  3860. * @return {Vector3} A reference to this vector.
  3861. */
  3862. subVectors( a, b ) {
  3863. this.x = a.x - b.x;
  3864. this.y = a.y - b.y;
  3865. this.z = a.z - b.z;
  3866. return this;
  3867. }
  3868. /**
  3869. * Multiplies the given vector with this instance.
  3870. *
  3871. * @param {Vector3} v - The vector to multiply.
  3872. * @return {Vector3} A reference to this vector.
  3873. */
  3874. multiply( v ) {
  3875. this.x *= v.x;
  3876. this.y *= v.y;
  3877. this.z *= v.z;
  3878. return this;
  3879. }
  3880. /**
  3881. * Multiplies the given scalar value with all components of this instance.
  3882. *
  3883. * @param {number} scalar - The scalar to multiply.
  3884. * @return {Vector3} A reference to this vector.
  3885. */
  3886. multiplyScalar( scalar ) {
  3887. this.x *= scalar;
  3888. this.y *= scalar;
  3889. this.z *= scalar;
  3890. return this;
  3891. }
  3892. /**
  3893. * Multiplies the given vectors and stores the result in this instance.
  3894. *
  3895. * @param {Vector3} a - The first vector.
  3896. * @param {Vector3} b - The second vector.
  3897. * @return {Vector3} A reference to this vector.
  3898. */
  3899. multiplyVectors( a, b ) {
  3900. this.x = a.x * b.x;
  3901. this.y = a.y * b.y;
  3902. this.z = a.z * b.z;
  3903. return this;
  3904. }
  3905. /**
  3906. * Applies the given Euler rotation to this vector.
  3907. *
  3908. * @param {Euler} euler - The Euler angles.
  3909. * @return {Vector3} A reference to this vector.
  3910. */
  3911. applyEuler( euler ) {
  3912. return this.applyQuaternion( _quaternion$4.setFromEuler( euler ) );
  3913. }
  3914. /**
  3915. * Applies a rotation specified by an axis and an angle to this vector.
  3916. *
  3917. * @param {Vector3} axis - A normalized vector representing the rotation axis.
  3918. * @param {number} angle - The angle in radians.
  3919. * @return {Vector3} A reference to this vector.
  3920. */
  3921. applyAxisAngle( axis, angle ) {
  3922. return this.applyQuaternion( _quaternion$4.setFromAxisAngle( axis, angle ) );
  3923. }
  3924. /**
  3925. * Multiplies this vector with the given 3x3 matrix.
  3926. *
  3927. * @param {Matrix3} m - The 3x3 matrix.
  3928. * @return {Vector3} A reference to this vector.
  3929. */
  3930. applyMatrix3( m ) {
  3931. const x = this.x, y = this.y, z = this.z;
  3932. const e = m.elements;
  3933. this.x = e[ 0 ] * x + e[ 3 ] * y + e[ 6 ] * z;
  3934. this.y = e[ 1 ] * x + e[ 4 ] * y + e[ 7 ] * z;
  3935. this.z = e[ 2 ] * x + e[ 5 ] * y + e[ 8 ] * z;
  3936. return this;
  3937. }
  3938. /**
  3939. * Multiplies this vector by the given normal matrix and normalizes
  3940. * the result.
  3941. *
  3942. * @param {Matrix3} m - The normal matrix.
  3943. * @return {Vector3} A reference to this vector.
  3944. */
  3945. applyNormalMatrix( m ) {
  3946. return this.applyMatrix3( m ).normalize();
  3947. }
  3948. /**
  3949. * Multiplies this vector (with an implicit 1 in the 4th dimension) by m, and
  3950. * divides by perspective.
  3951. *
  3952. * @param {Matrix4} m - The matrix to apply.
  3953. * @return {Vector3} A reference to this vector.
  3954. */
  3955. applyMatrix4( m ) {
  3956. const x = this.x, y = this.y, z = this.z;
  3957. const e = m.elements;
  3958. const w = 1 / ( e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] );
  3959. this.x = ( e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] ) * w;
  3960. this.y = ( e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] ) * w;
  3961. this.z = ( e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] ) * w;
  3962. return this;
  3963. }
  3964. /**
  3965. * Applies the given Quaternion to this vector.
  3966. *
  3967. * @param {Quaternion} q - The Quaternion.
  3968. * @return {Vector3} A reference to this vector.
  3969. */
  3970. applyQuaternion( q ) {
  3971. // quaternion q is assumed to have unit length
  3972. const vx = this.x, vy = this.y, vz = this.z;
  3973. const qx = q.x, qy = q.y, qz = q.z, qw = q.w;
  3974. // t = 2 * cross( q.xyz, v );
  3975. const tx = 2 * ( qy * vz - qz * vy );
  3976. const ty = 2 * ( qz * vx - qx * vz );
  3977. const tz = 2 * ( qx * vy - qy * vx );
  3978. // v + q.w * t + cross( q.xyz, t );
  3979. this.x = vx + qw * tx + qy * tz - qz * ty;
  3980. this.y = vy + qw * ty + qz * tx - qx * tz;
  3981. this.z = vz + qw * tz + qx * ty - qy * tx;
  3982. return this;
  3983. }
  3984. /**
  3985. * Projects this vector from world space into the camera's normalized
  3986. * device coordinate (NDC) space.
  3987. *
  3988. * @param {Camera} camera - The camera.
  3989. * @return {Vector3} A reference to this vector.
  3990. */
  3991. project( camera ) {
  3992. return this.applyMatrix4( camera.matrixWorldInverse ).applyMatrix4( camera.projectionMatrix );
  3993. }
  3994. /**
  3995. * Unprojects this vector from the camera's normalized device coordinate (NDC)
  3996. * space into world space.
  3997. *
  3998. * @param {Camera} camera - The camera.
  3999. * @return {Vector3} A reference to this vector.
  4000. */
  4001. unproject( camera ) {
  4002. return this.applyMatrix4( camera.projectionMatrixInverse ).applyMatrix4( camera.matrixWorld );
  4003. }
  4004. /**
  4005. * Transforms the direction of this vector by a matrix (the upper left 3 x 3
  4006. * subset of the given 4x4 matrix and then normalizes the result.
  4007. *
  4008. * @param {Matrix4} m - The matrix.
  4009. * @return {Vector3} A reference to this vector.
  4010. */
  4011. transformDirection( m ) {
  4012. // input: THREE.Matrix4 affine matrix
  4013. // vector interpreted as a direction
  4014. const x = this.x, y = this.y, z = this.z;
  4015. const e = m.elements;
  4016. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z;
  4017. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z;
  4018. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z;
  4019. return this.normalize();
  4020. }
  4021. /**
  4022. * Divides this instance by the given vector.
  4023. *
  4024. * @param {Vector3} v - The vector to divide.
  4025. * @return {Vector3} A reference to this vector.
  4026. */
  4027. divide( v ) {
  4028. this.x /= v.x;
  4029. this.y /= v.y;
  4030. this.z /= v.z;
  4031. return this;
  4032. }
  4033. /**
  4034. * Divides this vector by the given scalar.
  4035. *
  4036. * @param {number} scalar - The scalar to divide.
  4037. * @return {Vector3} A reference to this vector.
  4038. */
  4039. divideScalar( scalar ) {
  4040. return this.multiplyScalar( 1 / scalar );
  4041. }
  4042. /**
  4043. * If this vector's x, y or z value is greater than the given vector's x, y or z
  4044. * value, replace that value with the corresponding min value.
  4045. *
  4046. * @param {Vector3} v - The vector.
  4047. * @return {Vector3} A reference to this vector.
  4048. */
  4049. min( v ) {
  4050. this.x = Math.min( this.x, v.x );
  4051. this.y = Math.min( this.y, v.y );
  4052. this.z = Math.min( this.z, v.z );
  4053. return this;
  4054. }
  4055. /**
  4056. * If this vector's x, y or z value is less than the given vector's x, y or z
  4057. * value, replace that value with the corresponding max value.
  4058. *
  4059. * @param {Vector3} v - The vector.
  4060. * @return {Vector3} A reference to this vector.
  4061. */
  4062. max( v ) {
  4063. this.x = Math.max( this.x, v.x );
  4064. this.y = Math.max( this.y, v.y );
  4065. this.z = Math.max( this.z, v.z );
  4066. return this;
  4067. }
  4068. /**
  4069. * If this vector's x, y or z value is greater than the max vector's x, y or z
  4070. * value, it is replaced by the corresponding value.
  4071. * If this vector's x, y or z value is less than the min vector's x, y or z value,
  4072. * it is replaced by the corresponding value.
  4073. *
  4074. * @param {Vector3} min - The minimum x, y and z values.
  4075. * @param {Vector3} max - The maximum x, y and z values in the desired range.
  4076. * @return {Vector3} A reference to this vector.
  4077. */
  4078. clamp( min, max ) {
  4079. // assumes min < max, componentwise
  4080. this.x = clamp( this.x, min.x, max.x );
  4081. this.y = clamp( this.y, min.y, max.y );
  4082. this.z = clamp( this.z, min.z, max.z );
  4083. return this;
  4084. }
  4085. /**
  4086. * If this vector's x, y or z values are greater than the max value, they are
  4087. * replaced by the max value.
  4088. * If this vector's x, y or z values are less than the min value, they are
  4089. * replaced by the min value.
  4090. *
  4091. * @param {number} minVal - The minimum value the components will be clamped to.
  4092. * @param {number} maxVal - The maximum value the components will be clamped to.
  4093. * @return {Vector3} A reference to this vector.
  4094. */
  4095. clampScalar( minVal, maxVal ) {
  4096. this.x = clamp( this.x, minVal, maxVal );
  4097. this.y = clamp( this.y, minVal, maxVal );
  4098. this.z = clamp( this.z, minVal, maxVal );
  4099. return this;
  4100. }
  4101. /**
  4102. * If this vector's length is greater than the max value, it is replaced by
  4103. * the max value.
  4104. * If this vector's length is less than the min value, it is replaced by the
  4105. * min value.
  4106. *
  4107. * @param {number} min - The minimum value the vector length will be clamped to.
  4108. * @param {number} max - The maximum value the vector length will be clamped to.
  4109. * @return {Vector3} A reference to this vector.
  4110. */
  4111. clampLength( min, max ) {
  4112. const length = this.length();
  4113. return this.divideScalar( length || 1 ).multiplyScalar( clamp( length, min, max ) );
  4114. }
  4115. /**
  4116. * The components of this vector are rounded down to the nearest integer value.
  4117. *
  4118. * @return {Vector3} A reference to this vector.
  4119. */
  4120. floor() {
  4121. this.x = Math.floor( this.x );
  4122. this.y = Math.floor( this.y );
  4123. this.z = Math.floor( this.z );
  4124. return this;
  4125. }
  4126. /**
  4127. * The components of this vector are rounded up to the nearest integer value.
  4128. *
  4129. * @return {Vector3} A reference to this vector.
  4130. */
  4131. ceil() {
  4132. this.x = Math.ceil( this.x );
  4133. this.y = Math.ceil( this.y );
  4134. this.z = Math.ceil( this.z );
  4135. return this;
  4136. }
  4137. /**
  4138. * The components of this vector are rounded to the nearest integer value
  4139. *
  4140. * @return {Vector3} A reference to this vector.
  4141. */
  4142. round() {
  4143. this.x = Math.round( this.x );
  4144. this.y = Math.round( this.y );
  4145. this.z = Math.round( this.z );
  4146. return this;
  4147. }
  4148. /**
  4149. * The components of this vector are rounded towards zero (up if negative,
  4150. * down if positive) to an integer value.
  4151. *
  4152. * @return {Vector3} A reference to this vector.
  4153. */
  4154. roundToZero() {
  4155. this.x = Math.trunc( this.x );
  4156. this.y = Math.trunc( this.y );
  4157. this.z = Math.trunc( this.z );
  4158. return this;
  4159. }
  4160. /**
  4161. * Inverts this vector - i.e. sets x = -x, y = -y and z = -z.
  4162. *
  4163. * @return {Vector3} A reference to this vector.
  4164. */
  4165. negate() {
  4166. this.x = - this.x;
  4167. this.y = - this.y;
  4168. this.z = - this.z;
  4169. return this;
  4170. }
  4171. /**
  4172. * Calculates the dot product of the given vector with this instance.
  4173. *
  4174. * @param {Vector3} v - The vector to compute the dot product with.
  4175. * @return {number} The result of the dot product.
  4176. */
  4177. dot( v ) {
  4178. return this.x * v.x + this.y * v.y + this.z * v.z;
  4179. }
  4180. /**
  4181. * Computes the square of the Euclidean length (straight-line length) from
  4182. * (0, 0, 0) to (x, y, z). If you are comparing the lengths of vectors, you should
  4183. * compare the length squared instead as it is slightly more efficient to calculate.
  4184. *
  4185. * @return {number} The square length of this vector.
  4186. */
  4187. lengthSq() {
  4188. return this.x * this.x + this.y * this.y + this.z * this.z;
  4189. }
  4190. /**
  4191. * Computes the Euclidean length (straight-line length) from (0, 0, 0) to (x, y, z).
  4192. *
  4193. * @return {number} The length of this vector.
  4194. */
  4195. length() {
  4196. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z );
  4197. }
  4198. /**
  4199. * Computes the Manhattan length of this vector.
  4200. *
  4201. * @return {number} The length of this vector.
  4202. */
  4203. manhattanLength() {
  4204. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z );
  4205. }
  4206. /**
  4207. * Converts this vector to a unit vector - that is, sets it equal to a vector
  4208. * with the same direction as this one, but with a vector length of `1`.
  4209. *
  4210. * @return {Vector3} A reference to this vector.
  4211. */
  4212. normalize() {
  4213. return this.divideScalar( this.length() || 1 );
  4214. }
  4215. /**
  4216. * Sets this vector to a vector with the same direction as this one, but
  4217. * with the specified length.
  4218. *
  4219. * @param {number} length - The new length of this vector.
  4220. * @return {Vector3} A reference to this vector.
  4221. */
  4222. setLength( length ) {
  4223. return this.normalize().multiplyScalar( length );
  4224. }
  4225. /**
  4226. * Linearly interpolates between the given vector and this instance, where
  4227. * alpha is the percent distance along the line - alpha = 0 will be this
  4228. * vector, and alpha = 1 will be the given one.
  4229. *
  4230. * @param {Vector3} v - The vector to interpolate towards.
  4231. * @param {number} alpha - The interpolation factor, typically in the closed interval `[0, 1]`.
  4232. * @return {Vector3} A reference to this vector.
  4233. */
  4234. lerp( v, alpha ) {
  4235. this.x += ( v.x - this.x ) * alpha;
  4236. this.y += ( v.y - this.y ) * alpha;
  4237. this.z += ( v.z - this.z ) * alpha;
  4238. return this;
  4239. }
  4240. /**
  4241. * Linearly interpolates between the given vectors, where alpha is the percent
  4242. * distance along the line - alpha = 0 will be first vector, and alpha = 1 will
  4243. * be the second one. The result is stored in this instance.
  4244. *
  4245. * @param {Vector3} v1 - The first vector.
  4246. * @param {Vector3} v2 - The second vector.
  4247. * @param {number} alpha - The interpolation factor, typically in the closed interval `[0, 1]`.
  4248. * @return {Vector3} A reference to this vector.
  4249. */
  4250. lerpVectors( v1, v2, alpha ) {
  4251. this.x = v1.x + ( v2.x - v1.x ) * alpha;
  4252. this.y = v1.y + ( v2.y - v1.y ) * alpha;
  4253. this.z = v1.z + ( v2.z - v1.z ) * alpha;
  4254. return this;
  4255. }
  4256. /**
  4257. * Calculates the cross product of the given vector with this instance.
  4258. *
  4259. * @param {Vector3} v - The vector to compute the cross product with.
  4260. * @return {Vector3} The result of the cross product.
  4261. */
  4262. cross( v ) {
  4263. return this.crossVectors( this, v );
  4264. }
  4265. /**
  4266. * Calculates the cross product of the given vectors and stores the result
  4267. * in this instance.
  4268. *
  4269. * @param {Vector3} a - The first vector.
  4270. * @param {Vector3} b - The second vector.
  4271. * @return {Vector3} A reference to this vector.
  4272. */
  4273. crossVectors( a, b ) {
  4274. const ax = a.x, ay = a.y, az = a.z;
  4275. const bx = b.x, by = b.y, bz = b.z;
  4276. this.x = ay * bz - az * by;
  4277. this.y = az * bx - ax * bz;
  4278. this.z = ax * by - ay * bx;
  4279. return this;
  4280. }
  4281. /**
  4282. * Projects this vector onto the given one.
  4283. *
  4284. * @param {Vector3} v - The vector to project to.
  4285. * @return {Vector3} A reference to this vector.
  4286. */
  4287. projectOnVector( v ) {
  4288. const denominator = v.lengthSq();
  4289. if ( denominator === 0 ) return this.set( 0, 0, 0 );
  4290. const scalar = v.dot( this ) / denominator;
  4291. return this.copy( v ).multiplyScalar( scalar );
  4292. }
  4293. /**
  4294. * Projects this vector onto a plane by subtracting this
  4295. * vector projected onto the plane's normal from this vector.
  4296. *
  4297. * @param {Vector3} planeNormal - The plane normal.
  4298. * @return {Vector3} A reference to this vector.
  4299. */
  4300. projectOnPlane( planeNormal ) {
  4301. _vector$c.copy( this ).projectOnVector( planeNormal );
  4302. return this.sub( _vector$c );
  4303. }
  4304. /**
  4305. * Reflects this vector off a plane orthogonal to the given normal vector.
  4306. *
  4307. * @param {Vector3} normal - The (normalized) normal vector.
  4308. * @return {Vector3} A reference to this vector.
  4309. */
  4310. reflect( normal ) {
  4311. return this.sub( _vector$c.copy( normal ).multiplyScalar( 2 * this.dot( normal ) ) );
  4312. }
  4313. /**
  4314. * Returns the angle between the given vector and this instance in radians.
  4315. *
  4316. * @param {Vector3} v - The vector to compute the angle with.
  4317. * @return {number} The angle in radians.
  4318. */
  4319. angleTo( v ) {
  4320. const denominator = Math.sqrt( this.lengthSq() * v.lengthSq() );
  4321. if ( denominator === 0 ) return Math.PI / 2;
  4322. const theta = this.dot( v ) / denominator;
  4323. // clamp, to handle numerical problems
  4324. return Math.acos( clamp( theta, -1, 1 ) );
  4325. }
  4326. /**
  4327. * Computes the distance from the given vector to this instance.
  4328. *
  4329. * @param {Vector3} v - The vector to compute the distance to.
  4330. * @return {number} The distance.
  4331. */
  4332. distanceTo( v ) {
  4333. return Math.sqrt( this.distanceToSquared( v ) );
  4334. }
  4335. /**
  4336. * Computes the squared distance from the given vector to this instance.
  4337. * If you are just comparing the distance with another distance, you should compare
  4338. * the distance squared instead as it is slightly more efficient to calculate.
  4339. *
  4340. * @param {Vector3} v - The vector to compute the squared distance to.
  4341. * @return {number} The squared distance.
  4342. */
  4343. distanceToSquared( v ) {
  4344. const dx = this.x - v.x, dy = this.y - v.y, dz = this.z - v.z;
  4345. return dx * dx + dy * dy + dz * dz;
  4346. }
  4347. /**
  4348. * Computes the Manhattan distance from the given vector to this instance.
  4349. *
  4350. * @param {Vector3} v - The vector to compute the Manhattan distance to.
  4351. * @return {number} The Manhattan distance.
  4352. */
  4353. manhattanDistanceTo( v ) {
  4354. return Math.abs( this.x - v.x ) + Math.abs( this.y - v.y ) + Math.abs( this.z - v.z );
  4355. }
  4356. /**
  4357. * Sets the vector components from the given spherical coordinates.
  4358. *
  4359. * @param {Spherical} s - The spherical coordinates.
  4360. * @return {Vector3} A reference to this vector.
  4361. */
  4362. setFromSpherical( s ) {
  4363. return this.setFromSphericalCoords( s.radius, s.phi, s.theta );
  4364. }
  4365. /**
  4366. * Sets the vector components from the given spherical coordinates.
  4367. *
  4368. * @param {number} radius - The radius.
  4369. * @param {number} phi - The phi angle in radians.
  4370. * @param {number} theta - The theta angle in radians.
  4371. * @return {Vector3} A reference to this vector.
  4372. */
  4373. setFromSphericalCoords( radius, phi, theta ) {
  4374. const sinPhiRadius = Math.sin( phi ) * radius;
  4375. this.x = sinPhiRadius * Math.sin( theta );
  4376. this.y = Math.cos( phi ) * radius;
  4377. this.z = sinPhiRadius * Math.cos( theta );
  4378. return this;
  4379. }
  4380. /**
  4381. * Sets the vector components from the given cylindrical coordinates.
  4382. *
  4383. * @param {Cylindrical} c - The cylindrical coordinates.
  4384. * @return {Vector3} A reference to this vector.
  4385. */
  4386. setFromCylindrical( c ) {
  4387. return this.setFromCylindricalCoords( c.radius, c.theta, c.y );
  4388. }
  4389. /**
  4390. * Sets the vector components from the given cylindrical coordinates.
  4391. *
  4392. * @param {number} radius - The radius.
  4393. * @param {number} theta - The theta angle in radians.
  4394. * @param {number} y - The y value.
  4395. * @return {Vector3} A reference to this vector.
  4396. */
  4397. setFromCylindricalCoords( radius, theta, y ) {
  4398. this.x = radius * Math.sin( theta );
  4399. this.y = y;
  4400. this.z = radius * Math.cos( theta );
  4401. return this;
  4402. }
  4403. /**
  4404. * Sets the vector components to the position elements of the
  4405. * given transformation matrix.
  4406. *
  4407. * @param {Matrix4} m - The 4x4 matrix.
  4408. * @return {Vector3} A reference to this vector.
  4409. */
  4410. setFromMatrixPosition( m ) {
  4411. const e = m.elements;
  4412. this.x = e[ 12 ];
  4413. this.y = e[ 13 ];
  4414. this.z = e[ 14 ];
  4415. return this;
  4416. }
  4417. /**
  4418. * Sets the vector components to the scale elements of the
  4419. * given transformation matrix.
  4420. *
  4421. * @param {Matrix4} m - The 4x4 matrix.
  4422. * @return {Vector3} A reference to this vector.
  4423. */
  4424. setFromMatrixScale( m ) {
  4425. const sx = this.setFromMatrixColumn( m, 0 ).length();
  4426. const sy = this.setFromMatrixColumn( m, 1 ).length();
  4427. const sz = this.setFromMatrixColumn( m, 2 ).length();
  4428. this.x = sx;
  4429. this.y = sy;
  4430. this.z = sz;
  4431. return this;
  4432. }
  4433. /**
  4434. * Sets the vector components from the specified matrix column.
  4435. *
  4436. * @param {Matrix4} m - The 4x4 matrix.
  4437. * @param {number} index - The column index.
  4438. * @return {Vector3} A reference to this vector.
  4439. */
  4440. setFromMatrixColumn( m, index ) {
  4441. return this.fromArray( m.elements, index * 4 );
  4442. }
  4443. /**
  4444. * Sets the vector components from the specified matrix column.
  4445. *
  4446. * @param {Matrix3} m - The 3x3 matrix.
  4447. * @param {number} index - The column index.
  4448. * @return {Vector3} A reference to this vector.
  4449. */
  4450. setFromMatrix3Column( m, index ) {
  4451. return this.fromArray( m.elements, index * 3 );
  4452. }
  4453. /**
  4454. * Sets the vector components from the given Euler angles.
  4455. *
  4456. * @param {Euler} e - The Euler angles to set.
  4457. * @return {Vector3} A reference to this vector.
  4458. */
  4459. setFromEuler( e ) {
  4460. this.x = e._x;
  4461. this.y = e._y;
  4462. this.z = e._z;
  4463. return this;
  4464. }
  4465. /**
  4466. * Sets the vector components from the RGB components of the
  4467. * given color.
  4468. *
  4469. * @param {Color} c - The color to set.
  4470. * @return {Vector3} A reference to this vector.
  4471. */
  4472. setFromColor( c ) {
  4473. this.x = c.r;
  4474. this.y = c.g;
  4475. this.z = c.b;
  4476. return this;
  4477. }
  4478. /**
  4479. * Returns `true` if this vector is equal with the given one.
  4480. *
  4481. * @param {Vector3} v - The vector to test for equality.
  4482. * @return {boolean} Whether this vector is equal with the given one.
  4483. */
  4484. equals( v ) {
  4485. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) );
  4486. }
  4487. /**
  4488. * Sets this vector's x value to be `array[ offset ]`, y value to be `array[ offset + 1 ]`
  4489. * and z value to be `array[ offset + 2 ]`.
  4490. *
  4491. * @param {Array<number>} array - An array holding the vector component values.
  4492. * @param {number} [offset=0] - The offset into the array.
  4493. * @return {Vector3} A reference to this vector.
  4494. */
  4495. fromArray( array, offset = 0 ) {
  4496. this.x = array[ offset ];
  4497. this.y = array[ offset + 1 ];
  4498. this.z = array[ offset + 2 ];
  4499. return this;
  4500. }
  4501. /**
  4502. * Writes the components of this vector to the given array. If no array is provided,
  4503. * the method returns a new instance.
  4504. *
  4505. * @param {Array<number>} [array=[]] - The target array holding the vector components.
  4506. * @param {number} [offset=0] - Index of the first element in the array.
  4507. * @return {Array<number>} The vector components.
  4508. */
  4509. toArray( array = [], offset = 0 ) {
  4510. array[ offset ] = this.x;
  4511. array[ offset + 1 ] = this.y;
  4512. array[ offset + 2 ] = this.z;
  4513. return array;
  4514. }
  4515. /**
  4516. * Sets the components of this vector from the given buffer attribute.
  4517. *
  4518. * @param {BufferAttribute} attribute - The buffer attribute holding vector data.
  4519. * @param {number} index - The index into the attribute.
  4520. * @return {Vector3} A reference to this vector.
  4521. */
  4522. fromBufferAttribute( attribute, index ) {
  4523. this.x = attribute.getX( index );
  4524. this.y = attribute.getY( index );
  4525. this.z = attribute.getZ( index );
  4526. return this;
  4527. }
  4528. /**
  4529. * Sets each component of this vector to a pseudo-random value between `0` and
  4530. * `1`, excluding `1`.
  4531. *
  4532. * @return {Vector3} A reference to this vector.
  4533. */
  4534. random() {
  4535. this.x = Math.random();
  4536. this.y = Math.random();
  4537. this.z = Math.random();
  4538. return this;
  4539. }
  4540. /**
  4541. * Sets this vector to a uniformly random point on a unit sphere.
  4542. *
  4543. * @return {Vector3} A reference to this vector.
  4544. */
  4545. randomDirection() {
  4546. // https://mathworld.wolfram.com/SpherePointPicking.html
  4547. const theta = Math.random() * Math.PI * 2;
  4548. const u = Math.random() * 2 - 1;
  4549. const c = Math.sqrt( 1 - u * u );
  4550. this.x = c * Math.cos( theta );
  4551. this.y = u;
  4552. this.z = c * Math.sin( theta );
  4553. return this;
  4554. }
  4555. *[ Symbol.iterator ]() {
  4556. yield this.x;
  4557. yield this.y;
  4558. yield this.z;
  4559. }
  4560. }
  4561. const _vector$c = /*@__PURE__*/ new Vector3();
  4562. const _quaternion$4 = /*@__PURE__*/ new Quaternion();
  4563. /**
  4564. * Represents a 3x3 matrix.
  4565. *
  4566. * A Note on Row-Major and Column-Major Ordering:
  4567. *
  4568. * The constructor and {@link Matrix3#set} method take arguments in
  4569. * [row-major](https://en.wikipedia.org/wiki/Row-_and_column-major_order#Column-major_order)
  4570. * order, while internally they are stored in the {@link Matrix3#elements} array in column-major order.
  4571. * This means that calling:
  4572. * ```js
  4573. * const m = new THREE.Matrix();
  4574. * m.set( 11, 12, 13,
  4575. * 21, 22, 23,
  4576. * 31, 32, 33 );
  4577. * ```
  4578. * will result in the elements array containing:
  4579. * ```js
  4580. * m.elements = [ 11, 21, 31,
  4581. * 12, 22, 32,
  4582. * 13, 23, 33 ];
  4583. * ```
  4584. * and internally all calculations are performed using column-major ordering.
  4585. * However, as the actual ordering makes no difference mathematically and
  4586. * most people are used to thinking about matrices in row-major order, the
  4587. * three.js documentation shows matrices in row-major order. Just bear in
  4588. * mind that if you are reading the source code, you'll have to take the
  4589. * transpose of any matrices outlined here to make sense of the calculations.
  4590. */
  4591. class Matrix3 {
  4592. /**
  4593. * Constructs a new 3x3 matrix. The arguments are supposed to be
  4594. * in row-major order. If no arguments are provided, the constructor
  4595. * initializes the matrix as an identity matrix.
  4596. *
  4597. * @param {number} [n11] - 1-1 matrix element.
  4598. * @param {number} [n12] - 1-2 matrix element.
  4599. * @param {number} [n13] - 1-3 matrix element.
  4600. * @param {number} [n21] - 2-1 matrix element.
  4601. * @param {number} [n22] - 2-2 matrix element.
  4602. * @param {number} [n23] - 2-3 matrix element.
  4603. * @param {number} [n31] - 3-1 matrix element.
  4604. * @param {number} [n32] - 3-2 matrix element.
  4605. * @param {number} [n33] - 3-3 matrix element.
  4606. */
  4607. constructor( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) {
  4608. /**
  4609. * This flag can be used for type testing.
  4610. *
  4611. * @type {boolean}
  4612. * @readonly
  4613. * @default true
  4614. */
  4615. Matrix3.prototype.isMatrix3 = true;
  4616. /**
  4617. * A column-major list of matrix values.
  4618. *
  4619. * @type {Array<number>}
  4620. */
  4621. this.elements = [
  4622. 1, 0, 0,
  4623. 0, 1, 0,
  4624. 0, 0, 1
  4625. ];
  4626. if ( n11 !== undefined ) {
  4627. this.set( n11, n12, n13, n21, n22, n23, n31, n32, n33 );
  4628. }
  4629. }
  4630. /**
  4631. * Sets the elements of the matrix.The arguments are supposed to be
  4632. * in row-major order.
  4633. *
  4634. * @param {number} [n11] - 1-1 matrix element.
  4635. * @param {number} [n12] - 1-2 matrix element.
  4636. * @param {number} [n13] - 1-3 matrix element.
  4637. * @param {number} [n21] - 2-1 matrix element.
  4638. * @param {number} [n22] - 2-2 matrix element.
  4639. * @param {number} [n23] - 2-3 matrix element.
  4640. * @param {number} [n31] - 3-1 matrix element.
  4641. * @param {number} [n32] - 3-2 matrix element.
  4642. * @param {number} [n33] - 3-3 matrix element.
  4643. * @return {Matrix3} A reference to this matrix.
  4644. */
  4645. set( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) {
  4646. const te = this.elements;
  4647. te[ 0 ] = n11; te[ 1 ] = n21; te[ 2 ] = n31;
  4648. te[ 3 ] = n12; te[ 4 ] = n22; te[ 5 ] = n32;
  4649. te[ 6 ] = n13; te[ 7 ] = n23; te[ 8 ] = n33;
  4650. return this;
  4651. }
  4652. /**
  4653. * Sets this matrix to the 3x3 identity matrix.
  4654. *
  4655. * @return {Matrix3} A reference to this matrix.
  4656. */
  4657. identity() {
  4658. this.set(
  4659. 1, 0, 0,
  4660. 0, 1, 0,
  4661. 0, 0, 1
  4662. );
  4663. return this;
  4664. }
  4665. /**
  4666. * Copies the values of the given matrix to this instance.
  4667. *
  4668. * @param {Matrix3} m - The matrix to copy.
  4669. * @return {Matrix3} A reference to this matrix.
  4670. */
  4671. copy( m ) {
  4672. const te = this.elements;
  4673. const me = m.elements;
  4674. te[ 0 ] = me[ 0 ]; te[ 1 ] = me[ 1 ]; te[ 2 ] = me[ 2 ];
  4675. te[ 3 ] = me[ 3 ]; te[ 4 ] = me[ 4 ]; te[ 5 ] = me[ 5 ];
  4676. te[ 6 ] = me[ 6 ]; te[ 7 ] = me[ 7 ]; te[ 8 ] = me[ 8 ];
  4677. return this;
  4678. }
  4679. /**
  4680. * Extracts the basis of this matrix into the three axis vectors provided.
  4681. *
  4682. * @param {Vector3} xAxis - The basis's x axis.
  4683. * @param {Vector3} yAxis - The basis's y axis.
  4684. * @param {Vector3} zAxis - The basis's z axis.
  4685. * @return {Matrix3} A reference to this matrix.
  4686. */
  4687. extractBasis( xAxis, yAxis, zAxis ) {
  4688. xAxis.setFromMatrix3Column( this, 0 );
  4689. yAxis.setFromMatrix3Column( this, 1 );
  4690. zAxis.setFromMatrix3Column( this, 2 );
  4691. return this;
  4692. }
  4693. /**
  4694. * Set this matrix to the upper 3x3 matrix of the given 4x4 matrix.
  4695. *
  4696. * @param {Matrix4} m - The 4x4 matrix.
  4697. * @return {Matrix3} A reference to this matrix.
  4698. */
  4699. setFromMatrix4( m ) {
  4700. const me = m.elements;
  4701. this.set(
  4702. me[ 0 ], me[ 4 ], me[ 8 ],
  4703. me[ 1 ], me[ 5 ], me[ 9 ],
  4704. me[ 2 ], me[ 6 ], me[ 10 ]
  4705. );
  4706. return this;
  4707. }
  4708. /**
  4709. * Post-multiplies this matrix by the given 3x3 matrix.
  4710. *
  4711. * @param {Matrix3} m - The matrix to multiply with.
  4712. * @return {Matrix3} A reference to this matrix.
  4713. */
  4714. multiply( m ) {
  4715. return this.multiplyMatrices( this, m );
  4716. }
  4717. /**
  4718. * Pre-multiplies this matrix by the given 3x3 matrix.
  4719. *
  4720. * @param {Matrix3} m - The matrix to multiply with.
  4721. * @return {Matrix3} A reference to this matrix.
  4722. */
  4723. premultiply( m ) {
  4724. return this.multiplyMatrices( m, this );
  4725. }
  4726. /**
  4727. * Multiples the given 3x3 matrices and stores the result
  4728. * in this matrix.
  4729. *
  4730. * @param {Matrix3} a - The first matrix.
  4731. * @param {Matrix3} b - The second matrix.
  4732. * @return {Matrix3} A reference to this matrix.
  4733. */
  4734. multiplyMatrices( a, b ) {
  4735. const ae = a.elements;
  4736. const be = b.elements;
  4737. const te = this.elements;
  4738. const a11 = ae[ 0 ], a12 = ae[ 3 ], a13 = ae[ 6 ];
  4739. const a21 = ae[ 1 ], a22 = ae[ 4 ], a23 = ae[ 7 ];
  4740. const a31 = ae[ 2 ], a32 = ae[ 5 ], a33 = ae[ 8 ];
  4741. const b11 = be[ 0 ], b12 = be[ 3 ], b13 = be[ 6 ];
  4742. const b21 = be[ 1 ], b22 = be[ 4 ], b23 = be[ 7 ];
  4743. const b31 = be[ 2 ], b32 = be[ 5 ], b33 = be[ 8 ];
  4744. te[ 0 ] = a11 * b11 + a12 * b21 + a13 * b31;
  4745. te[ 3 ] = a11 * b12 + a12 * b22 + a13 * b32;
  4746. te[ 6 ] = a11 * b13 + a12 * b23 + a13 * b33;
  4747. te[ 1 ] = a21 * b11 + a22 * b21 + a23 * b31;
  4748. te[ 4 ] = a21 * b12 + a22 * b22 + a23 * b32;
  4749. te[ 7 ] = a21 * b13 + a22 * b23 + a23 * b33;
  4750. te[ 2 ] = a31 * b11 + a32 * b21 + a33 * b31;
  4751. te[ 5 ] = a31 * b12 + a32 * b22 + a33 * b32;
  4752. te[ 8 ] = a31 * b13 + a32 * b23 + a33 * b33;
  4753. return this;
  4754. }
  4755. /**
  4756. * Multiplies every component of the matrix by the given scalar.
  4757. *
  4758. * @param {number} s - The scalar.
  4759. * @return {Matrix3} A reference to this matrix.
  4760. */
  4761. multiplyScalar( s ) {
  4762. const te = this.elements;
  4763. te[ 0 ] *= s; te[ 3 ] *= s; te[ 6 ] *= s;
  4764. te[ 1 ] *= s; te[ 4 ] *= s; te[ 7 ] *= s;
  4765. te[ 2 ] *= s; te[ 5 ] *= s; te[ 8 ] *= s;
  4766. return this;
  4767. }
  4768. /**
  4769. * Computes and returns the determinant of this matrix.
  4770. *
  4771. * @return {number} The determinant.
  4772. */
  4773. determinant() {
  4774. const te = this.elements;
  4775. const a = te[ 0 ], b = te[ 1 ], c = te[ 2 ],
  4776. d = te[ 3 ], e = te[ 4 ], f = te[ 5 ],
  4777. g = te[ 6 ], h = te[ 7 ], i = te[ 8 ];
  4778. return a * e * i - a * f * h - b * d * i + b * f * g + c * d * h - c * e * g;
  4779. }
  4780. /**
  4781. * Inverts this matrix, using the [analytic method](https://en.wikipedia.org/wiki/Invertible_matrix#Analytic_solution).
  4782. * You can not invert with a determinant of zero. If you attempt this, the method produces
  4783. * a zero matrix instead.
  4784. *
  4785. * @return {Matrix3} A reference to this matrix.
  4786. */
  4787. invert() {
  4788. const te = this.elements,
  4789. n11 = te[ 0 ], n21 = te[ 1 ], n31 = te[ 2 ],
  4790. n12 = te[ 3 ], n22 = te[ 4 ], n32 = te[ 5 ],
  4791. n13 = te[ 6 ], n23 = te[ 7 ], n33 = te[ 8 ],
  4792. t11 = n33 * n22 - n32 * n23,
  4793. t12 = n32 * n13 - n33 * n12,
  4794. t13 = n23 * n12 - n22 * n13,
  4795. det = n11 * t11 + n21 * t12 + n31 * t13;
  4796. if ( det === 0 ) return this.set( 0, 0, 0, 0, 0, 0, 0, 0, 0 );
  4797. const detInv = 1 / det;
  4798. te[ 0 ] = t11 * detInv;
  4799. te[ 1 ] = ( n31 * n23 - n33 * n21 ) * detInv;
  4800. te[ 2 ] = ( n32 * n21 - n31 * n22 ) * detInv;
  4801. te[ 3 ] = t12 * detInv;
  4802. te[ 4 ] = ( n33 * n11 - n31 * n13 ) * detInv;
  4803. te[ 5 ] = ( n31 * n12 - n32 * n11 ) * detInv;
  4804. te[ 6 ] = t13 * detInv;
  4805. te[ 7 ] = ( n21 * n13 - n23 * n11 ) * detInv;
  4806. te[ 8 ] = ( n22 * n11 - n21 * n12 ) * detInv;
  4807. return this;
  4808. }
  4809. /**
  4810. * Transposes this matrix in place.
  4811. *
  4812. * @return {Matrix3} A reference to this matrix.
  4813. */
  4814. transpose() {
  4815. let tmp;
  4816. const m = this.elements;
  4817. tmp = m[ 1 ]; m[ 1 ] = m[ 3 ]; m[ 3 ] = tmp;
  4818. tmp = m[ 2 ]; m[ 2 ] = m[ 6 ]; m[ 6 ] = tmp;
  4819. tmp = m[ 5 ]; m[ 5 ] = m[ 7 ]; m[ 7 ] = tmp;
  4820. return this;
  4821. }
  4822. /**
  4823. * Computes the normal matrix which is the inverse transpose of the upper
  4824. * left 3x3 portion of the given 4x4 matrix.
  4825. *
  4826. * @param {Matrix4} matrix4 - The 4x4 matrix.
  4827. * @return {Matrix3} A reference to this matrix.
  4828. */
  4829. getNormalMatrix( matrix4 ) {
  4830. return this.setFromMatrix4( matrix4 ).invert().transpose();
  4831. }
  4832. /**
  4833. * Transposes this matrix into the supplied array, and returns itself unchanged.
  4834. *
  4835. * @param {Array<number>} r - An array to store the transposed matrix elements.
  4836. * @return {Matrix3} A reference to this matrix.
  4837. */
  4838. transposeIntoArray( r ) {
  4839. const m = this.elements;
  4840. r[ 0 ] = m[ 0 ];
  4841. r[ 1 ] = m[ 3 ];
  4842. r[ 2 ] = m[ 6 ];
  4843. r[ 3 ] = m[ 1 ];
  4844. r[ 4 ] = m[ 4 ];
  4845. r[ 5 ] = m[ 7 ];
  4846. r[ 6 ] = m[ 2 ];
  4847. r[ 7 ] = m[ 5 ];
  4848. r[ 8 ] = m[ 8 ];
  4849. return this;
  4850. }
  4851. /**
  4852. * Sets the UV transform matrix from offset, repeat, rotation, and center.
  4853. *
  4854. * @param {number} tx - Offset x.
  4855. * @param {number} ty - Offset y.
  4856. * @param {number} sx - Repeat x.
  4857. * @param {number} sy - Repeat y.
  4858. * @param {number} rotation - Rotation, in radians. Positive values rotate counterclockwise.
  4859. * @param {number} cx - Center x of rotation.
  4860. * @param {number} cy - Center y of rotation
  4861. * @return {Matrix3} A reference to this matrix.
  4862. */
  4863. setUvTransform( tx, ty, sx, sy, rotation, cx, cy ) {
  4864. const c = Math.cos( rotation );
  4865. const s = Math.sin( rotation );
  4866. this.set(
  4867. sx * c, sx * s, - sx * ( c * cx + s * cy ) + cx + tx,
  4868. - sy * s, sy * c, - sy * ( - s * cx + c * cy ) + cy + ty,
  4869. 0, 0, 1
  4870. );
  4871. return this;
  4872. }
  4873. /**
  4874. * Scales this matrix with the given scalar values.
  4875. *
  4876. * @param {number} sx - The amount to scale in the X axis.
  4877. * @param {number} sy - The amount to scale in the Y axis.
  4878. * @return {Matrix3} A reference to this matrix.
  4879. */
  4880. scale( sx, sy ) {
  4881. this.premultiply( _m3.makeScale( sx, sy ) );
  4882. return this;
  4883. }
  4884. /**
  4885. * Rotates this matrix by the given angle.
  4886. *
  4887. * @param {number} theta - The rotation in radians.
  4888. * @return {Matrix3} A reference to this matrix.
  4889. */
  4890. rotate( theta ) {
  4891. this.premultiply( _m3.makeRotation( - theta ) );
  4892. return this;
  4893. }
  4894. /**
  4895. * Translates this matrix by the given scalar values.
  4896. *
  4897. * @param {number} tx - The amount to translate in the X axis.
  4898. * @param {number} ty - The amount to translate in the Y axis.
  4899. * @return {Matrix3} A reference to this matrix.
  4900. */
  4901. translate( tx, ty ) {
  4902. this.premultiply( _m3.makeTranslation( tx, ty ) );
  4903. return this;
  4904. }
  4905. // for 2D Transforms
  4906. /**
  4907. * Sets this matrix as a 2D translation transform.
  4908. *
  4909. * @param {number|Vector2} x - The amount to translate in the X axis or alternatively a translation vector.
  4910. * @param {number} y - The amount to translate in the Y axis.
  4911. * @return {Matrix3} A reference to this matrix.
  4912. */
  4913. makeTranslation( x, y ) {
  4914. if ( x.isVector2 ) {
  4915. this.set(
  4916. 1, 0, x.x,
  4917. 0, 1, x.y,
  4918. 0, 0, 1
  4919. );
  4920. } else {
  4921. this.set(
  4922. 1, 0, x,
  4923. 0, 1, y,
  4924. 0, 0, 1
  4925. );
  4926. }
  4927. return this;
  4928. }
  4929. /**
  4930. * Sets this matrix as a 2D rotational transformation.
  4931. *
  4932. * @param {number} theta - The rotation in radians.
  4933. * @return {Matrix3} A reference to this matrix.
  4934. */
  4935. makeRotation( theta ) {
  4936. // counterclockwise
  4937. const c = Math.cos( theta );
  4938. const s = Math.sin( theta );
  4939. this.set(
  4940. c, - s, 0,
  4941. s, c, 0,
  4942. 0, 0, 1
  4943. );
  4944. return this;
  4945. }
  4946. /**
  4947. * Sets this matrix as a 2D scale transform.
  4948. *
  4949. * @param {number} x - The amount to scale in the X axis.
  4950. * @param {number} y - The amount to scale in the Y axis.
  4951. * @return {Matrix3} A reference to this matrix.
  4952. */
  4953. makeScale( x, y ) {
  4954. this.set(
  4955. x, 0, 0,
  4956. 0, y, 0,
  4957. 0, 0, 1
  4958. );
  4959. return this;
  4960. }
  4961. /**
  4962. * Returns `true` if this matrix is equal with the given one.
  4963. *
  4964. * @param {Matrix3} matrix - The matrix to test for equality.
  4965. * @return {boolean} Whether this matrix is equal with the given one.
  4966. */
  4967. equals( matrix ) {
  4968. const te = this.elements;
  4969. const me = matrix.elements;
  4970. for ( let i = 0; i < 9; i ++ ) {
  4971. if ( te[ i ] !== me[ i ] ) return false;
  4972. }
  4973. return true;
  4974. }
  4975. /**
  4976. * Sets the elements of the matrix from the given array.
  4977. *
  4978. * @param {Array<number>} array - The matrix elements in column-major order.
  4979. * @param {number} [offset=0] - Index of the first element in the array.
  4980. * @return {Matrix3} A reference to this matrix.
  4981. */
  4982. fromArray( array, offset = 0 ) {
  4983. for ( let i = 0; i < 9; i ++ ) {
  4984. this.elements[ i ] = array[ i + offset ];
  4985. }
  4986. return this;
  4987. }
  4988. /**
  4989. * Writes the elements of this matrix to the given array. If no array is provided,
  4990. * the method returns a new instance.
  4991. *
  4992. * @param {Array<number>} [array=[]] - The target array holding the matrix elements in column-major order.
  4993. * @param {number} [offset=0] - Index of the first element in the array.
  4994. * @return {Array<number>} The matrix elements in column-major order.
  4995. */
  4996. toArray( array = [], offset = 0 ) {
  4997. const te = this.elements;
  4998. array[ offset ] = te[ 0 ];
  4999. array[ offset + 1 ] = te[ 1 ];
  5000. array[ offset + 2 ] = te[ 2 ];
  5001. array[ offset + 3 ] = te[ 3 ];
  5002. array[ offset + 4 ] = te[ 4 ];
  5003. array[ offset + 5 ] = te[ 5 ];
  5004. array[ offset + 6 ] = te[ 6 ];
  5005. array[ offset + 7 ] = te[ 7 ];
  5006. array[ offset + 8 ] = te[ 8 ];
  5007. return array;
  5008. }
  5009. /**
  5010. * Returns a matrix with copied values from this instance.
  5011. *
  5012. * @return {Matrix3} A clone of this instance.
  5013. */
  5014. clone() {
  5015. return new this.constructor().fromArray( this.elements );
  5016. }
  5017. }
  5018. const _m3 = /*@__PURE__*/ new Matrix3();
  5019. const LINEAR_REC709_TO_XYZ = /*@__PURE__*/ new Matrix3().set(
  5020. 0.4123908, 0.3575843, 0.1804808,
  5021. 0.2126390, 0.7151687, 0.0721923,
  5022. 0.0193308, 0.1191948, 0.9505322
  5023. );
  5024. const XYZ_TO_LINEAR_REC709 = /*@__PURE__*/ new Matrix3().set(
  5025. 3.2409699, -1.5373832, -0.4986108,
  5026. -0.9692436, 1.8759675, 0.0415551,
  5027. 0.0556301, -0.203977, 1.0569715
  5028. );
  5029. function createColorManagement() {
  5030. const ColorManagement = {
  5031. enabled: true,
  5032. workingColorSpace: LinearSRGBColorSpace,
  5033. /**
  5034. * Implementations of supported color spaces.
  5035. *
  5036. * Required:
  5037. * - primaries: chromaticity coordinates [ rx ry gx gy bx by ]
  5038. * - whitePoint: reference white [ x y ]
  5039. * - transfer: transfer function (pre-defined)
  5040. * - toXYZ: Matrix3 RGB to XYZ transform
  5041. * - fromXYZ: Matrix3 XYZ to RGB transform
  5042. * - luminanceCoefficients: RGB luminance coefficients
  5043. *
  5044. * Optional:
  5045. * - outputColorSpaceConfig: { drawingBufferColorSpace: ColorSpace, toneMappingMode: 'extended' | 'standard' }
  5046. * - workingColorSpaceConfig: { unpackColorSpace: ColorSpace }
  5047. *
  5048. * Reference:
  5049. * - https://www.russellcottrell.com/photo/matrixCalculator.htm
  5050. */
  5051. spaces: {},
  5052. convert: function ( color, sourceColorSpace, targetColorSpace ) {
  5053. if ( this.enabled === false || sourceColorSpace === targetColorSpace || ! sourceColorSpace || ! targetColorSpace ) {
  5054. return color;
  5055. }
  5056. if ( this.spaces[ sourceColorSpace ].transfer === SRGBTransfer ) {
  5057. color.r = SRGBToLinear( color.r );
  5058. color.g = SRGBToLinear( color.g );
  5059. color.b = SRGBToLinear( color.b );
  5060. }
  5061. if ( this.spaces[ sourceColorSpace ].primaries !== this.spaces[ targetColorSpace ].primaries ) {
  5062. color.applyMatrix3( this.spaces[ sourceColorSpace ].toXYZ );
  5063. color.applyMatrix3( this.spaces[ targetColorSpace ].fromXYZ );
  5064. }
  5065. if ( this.spaces[ targetColorSpace ].transfer === SRGBTransfer ) {
  5066. color.r = LinearToSRGB( color.r );
  5067. color.g = LinearToSRGB( color.g );
  5068. color.b = LinearToSRGB( color.b );
  5069. }
  5070. return color;
  5071. },
  5072. workingToColorSpace: function ( color, targetColorSpace ) {
  5073. return this.convert( color, this.workingColorSpace, targetColorSpace );
  5074. },
  5075. colorSpaceToWorking: function ( color, sourceColorSpace ) {
  5076. return this.convert( color, sourceColorSpace, this.workingColorSpace );
  5077. },
  5078. getPrimaries: function ( colorSpace ) {
  5079. return this.spaces[ colorSpace ].primaries;
  5080. },
  5081. getTransfer: function ( colorSpace ) {
  5082. if ( colorSpace === NoColorSpace ) return LinearTransfer;
  5083. return this.spaces[ colorSpace ].transfer;
  5084. },
  5085. getToneMappingMode: function ( colorSpace ) {
  5086. return this.spaces[ colorSpace ].outputColorSpaceConfig.toneMappingMode || 'standard';
  5087. },
  5088. getLuminanceCoefficients: function ( target, colorSpace = this.workingColorSpace ) {
  5089. return target.fromArray( this.spaces[ colorSpace ].luminanceCoefficients );
  5090. },
  5091. define: function ( colorSpaces ) {
  5092. Object.assign( this.spaces, colorSpaces );
  5093. },
  5094. // Internal APIs
  5095. _getMatrix: function ( targetMatrix, sourceColorSpace, targetColorSpace ) {
  5096. return targetMatrix
  5097. .copy( this.spaces[ sourceColorSpace ].toXYZ )
  5098. .multiply( this.spaces[ targetColorSpace ].fromXYZ );
  5099. },
  5100. _getDrawingBufferColorSpace: function ( colorSpace ) {
  5101. return this.spaces[ colorSpace ].outputColorSpaceConfig.drawingBufferColorSpace;
  5102. },
  5103. _getUnpackColorSpace: function ( colorSpace = this.workingColorSpace ) {
  5104. return this.spaces[ colorSpace ].workingColorSpaceConfig.unpackColorSpace;
  5105. },
  5106. // Deprecated
  5107. fromWorkingColorSpace: function ( color, targetColorSpace ) {
  5108. warnOnce( 'ColorManagement: .fromWorkingColorSpace() has been renamed to .workingToColorSpace().' ); // @deprecated, r177
  5109. return ColorManagement.workingToColorSpace( color, targetColorSpace );
  5110. },
  5111. toWorkingColorSpace: function ( color, sourceColorSpace ) {
  5112. warnOnce( 'ColorManagement: .toWorkingColorSpace() has been renamed to .colorSpaceToWorking().' ); // @deprecated, r177
  5113. return ColorManagement.colorSpaceToWorking( color, sourceColorSpace );
  5114. },
  5115. };
  5116. /******************************************************************************
  5117. * sRGB definitions
  5118. */
  5119. const REC709_PRIMARIES = [ 0.640, 0.330, 0.300, 0.600, 0.150, 0.060 ];
  5120. const REC709_LUMINANCE_COEFFICIENTS = [ 0.2126, 0.7152, 0.0722 ];
  5121. const D65 = [ 0.3127, 0.3290 ];
  5122. ColorManagement.define( {
  5123. [ LinearSRGBColorSpace ]: {
  5124. primaries: REC709_PRIMARIES,
  5125. whitePoint: D65,
  5126. transfer: LinearTransfer,
  5127. toXYZ: LINEAR_REC709_TO_XYZ,
  5128. fromXYZ: XYZ_TO_LINEAR_REC709,
  5129. luminanceCoefficients: REC709_LUMINANCE_COEFFICIENTS,
  5130. workingColorSpaceConfig: { unpackColorSpace: SRGBColorSpace },
  5131. outputColorSpaceConfig: { drawingBufferColorSpace: SRGBColorSpace }
  5132. },
  5133. [ SRGBColorSpace ]: {
  5134. primaries: REC709_PRIMARIES,
  5135. whitePoint: D65,
  5136. transfer: SRGBTransfer,
  5137. toXYZ: LINEAR_REC709_TO_XYZ,
  5138. fromXYZ: XYZ_TO_LINEAR_REC709,
  5139. luminanceCoefficients: REC709_LUMINANCE_COEFFICIENTS,
  5140. outputColorSpaceConfig: { drawingBufferColorSpace: SRGBColorSpace }
  5141. },
  5142. } );
  5143. return ColorManagement;
  5144. }
  5145. const ColorManagement = /*@__PURE__*/ createColorManagement();
  5146. function SRGBToLinear( c ) {
  5147. return ( c < 0.04045 ) ? c * 0.0773993808 : Math.pow( c * 0.9478672986 + 0.0521327014, 2.4 );
  5148. }
  5149. function LinearToSRGB( c ) {
  5150. return ( c < 0.0031308 ) ? c * 12.92 : 1.055 * ( Math.pow( c, 0.41666 ) ) - 0.055;
  5151. }
  5152. let _canvas;
  5153. /**
  5154. * A class containing utility functions for images.
  5155. *
  5156. * @hideconstructor
  5157. */
  5158. class ImageUtils {
  5159. /**
  5160. * Returns a data URI containing a representation of the given image.
  5161. *
  5162. * @param {(HTMLImageElement|HTMLCanvasElement)} image - The image object.
  5163. * @param {string} [type='image/png'] - Indicates the image format.
  5164. * @return {string} The data URI.
  5165. */
  5166. static getDataURL( image, type = 'image/png' ) {
  5167. if ( /^data:/i.test( image.src ) ) {
  5168. return image.src;
  5169. }
  5170. if ( typeof HTMLCanvasElement === 'undefined' ) {
  5171. return image.src;
  5172. }
  5173. let canvas;
  5174. if ( image instanceof HTMLCanvasElement ) {
  5175. canvas = image;
  5176. } else {
  5177. if ( _canvas === undefined ) _canvas = createElementNS( 'canvas' );
  5178. _canvas.width = image.width;
  5179. _canvas.height = image.height;
  5180. const context = _canvas.getContext( '2d' );
  5181. if ( image instanceof ImageData ) {
  5182. context.putImageData( image, 0, 0 );
  5183. } else {
  5184. context.drawImage( image, 0, 0, image.width, image.height );
  5185. }
  5186. canvas = _canvas;
  5187. }
  5188. return canvas.toDataURL( type );
  5189. }
  5190. /**
  5191. * Converts the given sRGB image data to linear color space.
  5192. *
  5193. * @param {(HTMLImageElement|HTMLCanvasElement|ImageBitmap|Object)} image - The image object.
  5194. * @return {HTMLCanvasElement|Object} The converted image.
  5195. */
  5196. static sRGBToLinear( image ) {
  5197. if ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) ||
  5198. ( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) ||
  5199. ( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) ) {
  5200. const canvas = createElementNS( 'canvas' );
  5201. canvas.width = image.width;
  5202. canvas.height = image.height;
  5203. const context = canvas.getContext( '2d' );
  5204. context.drawImage( image, 0, 0, image.width, image.height );
  5205. const imageData = context.getImageData( 0, 0, image.width, image.height );
  5206. const data = imageData.data;
  5207. for ( let i = 0; i < data.length; i ++ ) {
  5208. data[ i ] = SRGBToLinear( data[ i ] / 255 ) * 255;
  5209. }
  5210. context.putImageData( imageData, 0, 0 );
  5211. return canvas;
  5212. } else if ( image.data ) {
  5213. const data = image.data.slice( 0 );
  5214. for ( let i = 0; i < data.length; i ++ ) {
  5215. if ( data instanceof Uint8Array || data instanceof Uint8ClampedArray ) {
  5216. data[ i ] = Math.floor( SRGBToLinear( data[ i ] / 255 ) * 255 );
  5217. } else {
  5218. // assuming float
  5219. data[ i ] = SRGBToLinear( data[ i ] );
  5220. }
  5221. }
  5222. return {
  5223. data: data,
  5224. width: image.width,
  5225. height: image.height
  5226. };
  5227. } else {
  5228. warn( 'ImageUtils.sRGBToLinear(): Unsupported image type. No color space conversion applied.' );
  5229. return image;
  5230. }
  5231. }
  5232. }
  5233. let _sourceId = 0;
  5234. /**
  5235. * Represents the data source of a texture.
  5236. *
  5237. * The main purpose of this class is to decouple the data definition from the texture
  5238. * definition so the same data can be used with multiple texture instances.
  5239. */
  5240. class Source {
  5241. /**
  5242. * Constructs a new video texture.
  5243. *
  5244. * @param {any} [data=null] - The data definition of a texture.
  5245. */
  5246. constructor( data = null ) {
  5247. /**
  5248. * This flag can be used for type testing.
  5249. *
  5250. * @type {boolean}
  5251. * @readonly
  5252. * @default true
  5253. */
  5254. this.isSource = true;
  5255. /**
  5256. * The ID of the source.
  5257. *
  5258. * @name Source#id
  5259. * @type {number}
  5260. * @readonly
  5261. */
  5262. Object.defineProperty( this, 'id', { value: _sourceId ++ } );
  5263. /**
  5264. * The UUID of the source.
  5265. *
  5266. * @type {string}
  5267. * @readonly
  5268. */
  5269. this.uuid = generateUUID();
  5270. /**
  5271. * The data definition of a texture.
  5272. *
  5273. * @type {any}
  5274. */
  5275. this.data = data;
  5276. /**
  5277. * This property is only relevant when {@link Source#needsUpdate} is set to `true` and
  5278. * provides more control on how texture data should be processed. When `dataReady` is set
  5279. * to `false`, the engine performs the memory allocation (if necessary) but does not transfer
  5280. * the data into the GPU memory.
  5281. *
  5282. * @type {boolean}
  5283. * @default true
  5284. */
  5285. this.dataReady = true;
  5286. /**
  5287. * This starts at `0` and counts how many times {@link Source#needsUpdate} is set to `true`.
  5288. *
  5289. * @type {number}
  5290. * @readonly
  5291. * @default 0
  5292. */
  5293. this.version = 0;
  5294. }
  5295. /**
  5296. * Returns the dimensions of the source into the given target vector.
  5297. *
  5298. * @param {(Vector2|Vector3)} target - The target object the result is written into.
  5299. * @return {(Vector2|Vector3)} The dimensions of the source.
  5300. */
  5301. getSize( target ) {
  5302. const data = this.data;
  5303. if ( ( typeof HTMLVideoElement !== 'undefined' ) && ( data instanceof HTMLVideoElement ) ) {
  5304. target.set( data.videoWidth, data.videoHeight, 0 );
  5305. } else if ( ( typeof VideoFrame !== 'undefined' ) && ( data instanceof VideoFrame ) ) {
  5306. target.set( data.displayHeight, data.displayWidth, 0 );
  5307. } else if ( data !== null ) {
  5308. target.set( data.width, data.height, data.depth || 0 );
  5309. } else {
  5310. target.set( 0, 0, 0 );
  5311. }
  5312. return target;
  5313. }
  5314. /**
  5315. * When the property is set to `true`, the engine allocates the memory
  5316. * for the texture (if necessary) and triggers the actual texture upload
  5317. * to the GPU next time the source is used.
  5318. *
  5319. * @type {boolean}
  5320. * @default false
  5321. * @param {boolean} value
  5322. */
  5323. set needsUpdate( value ) {
  5324. if ( value === true ) this.version ++;
  5325. }
  5326. /**
  5327. * Serializes the source into JSON.
  5328. *
  5329. * @param {?(Object|string)} meta - An optional value holding meta information about the serialization.
  5330. * @return {Object} A JSON object representing the serialized source.
  5331. * @see {@link ObjectLoader#parse}
  5332. */
  5333. toJSON( meta ) {
  5334. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  5335. if ( ! isRootObject && meta.images[ this.uuid ] !== undefined ) {
  5336. return meta.images[ this.uuid ];
  5337. }
  5338. const output = {
  5339. uuid: this.uuid,
  5340. url: ''
  5341. };
  5342. const data = this.data;
  5343. if ( data !== null ) {
  5344. let url;
  5345. if ( Array.isArray( data ) ) {
  5346. // cube texture
  5347. url = [];
  5348. for ( let i = 0, l = data.length; i < l; i ++ ) {
  5349. if ( data[ i ].isDataTexture ) {
  5350. url.push( serializeImage( data[ i ].image ) );
  5351. } else {
  5352. url.push( serializeImage( data[ i ] ) );
  5353. }
  5354. }
  5355. } else {
  5356. // texture
  5357. url = serializeImage( data );
  5358. }
  5359. output.url = url;
  5360. }
  5361. if ( ! isRootObject ) {
  5362. meta.images[ this.uuid ] = output;
  5363. }
  5364. return output;
  5365. }
  5366. }
  5367. function serializeImage( image ) {
  5368. if ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) ||
  5369. ( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) ||
  5370. ( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) ) {
  5371. // default images
  5372. return ImageUtils.getDataURL( image );
  5373. } else {
  5374. if ( image.data ) {
  5375. // images of DataTexture
  5376. return {
  5377. data: Array.from( image.data ),
  5378. width: image.width,
  5379. height: image.height,
  5380. type: image.data.constructor.name
  5381. };
  5382. } else {
  5383. warn( 'Texture: Unable to serialize Texture.' );
  5384. return {};
  5385. }
  5386. }
  5387. }
  5388. let _textureId = 0;
  5389. const _tempVec3 = /*@__PURE__*/ new Vector3();
  5390. /**
  5391. * Base class for all textures.
  5392. *
  5393. * Note: After the initial use of a texture, its dimensions, format, and type
  5394. * cannot be changed. Instead, call {@link Texture#dispose} on the texture and instantiate a new one.
  5395. *
  5396. * @augments EventDispatcher
  5397. */
  5398. class Texture extends EventDispatcher {
  5399. /**
  5400. * Constructs a new texture.
  5401. *
  5402. * @param {?Object} [image=Texture.DEFAULT_IMAGE] - The image holding the texture data.
  5403. * @param {number} [mapping=Texture.DEFAULT_MAPPING] - The texture mapping.
  5404. * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value.
  5405. * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value.
  5406. * @param {number} [magFilter=LinearFilter] - The mag filter value.
  5407. * @param {number} [minFilter=LinearMipmapLinearFilter] - The min filter value.
  5408. * @param {number} [format=RGBAFormat] - The texture format.
  5409. * @param {number} [type=UnsignedByteType] - The texture type.
  5410. * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value.
  5411. * @param {string} [colorSpace=NoColorSpace] - The color space.
  5412. */
  5413. 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 ) {
  5414. super();
  5415. /**
  5416. * This flag can be used for type testing.
  5417. *
  5418. * @type {boolean}
  5419. * @readonly
  5420. * @default true
  5421. */
  5422. this.isTexture = true;
  5423. /**
  5424. * The ID of the texture.
  5425. *
  5426. * @name Texture#id
  5427. * @type {number}
  5428. * @readonly
  5429. */
  5430. Object.defineProperty( this, 'id', { value: _textureId ++ } );
  5431. /**
  5432. * The UUID of the material.
  5433. *
  5434. * @type {string}
  5435. * @readonly
  5436. */
  5437. this.uuid = generateUUID();
  5438. /**
  5439. * The name of the material.
  5440. *
  5441. * @type {string}
  5442. */
  5443. this.name = '';
  5444. /**
  5445. * The data definition of a texture. A reference to the data source can be
  5446. * shared across textures. This is often useful in context of spritesheets
  5447. * where multiple textures render the same data but with different texture
  5448. * transformations.
  5449. *
  5450. * @type {Source}
  5451. */
  5452. this.source = new Source( image );
  5453. /**
  5454. * An array holding user-defined mipmaps.
  5455. *
  5456. * @type {Array<Object>}
  5457. */
  5458. this.mipmaps = [];
  5459. /**
  5460. * How the texture is applied to the object. The value `UVMapping`
  5461. * is the default, where texture or uv coordinates are used to apply the map.
  5462. *
  5463. * @type {(UVMapping|CubeReflectionMapping|CubeRefractionMapping|EquirectangularReflectionMapping|EquirectangularRefractionMapping|CubeUVReflectionMapping)}
  5464. * @default UVMapping
  5465. */
  5466. this.mapping = mapping;
  5467. /**
  5468. * Lets you select the uv attribute to map the texture to. `0` for `uv`,
  5469. * `1` for `uv1`, `2` for `uv2` and `3` for `uv3`.
  5470. *
  5471. * @type {number}
  5472. * @default 0
  5473. */
  5474. this.channel = 0;
  5475. /**
  5476. * This defines how the texture is wrapped horizontally and corresponds to
  5477. * *U* in UV mapping.
  5478. *
  5479. * @type {(RepeatWrapping|ClampToEdgeWrapping|MirroredRepeatWrapping)}
  5480. * @default ClampToEdgeWrapping
  5481. */
  5482. this.wrapS = wrapS;
  5483. /**
  5484. * This defines how the texture is wrapped horizontally and corresponds to
  5485. * *V* in UV mapping.
  5486. *
  5487. * @type {(RepeatWrapping|ClampToEdgeWrapping|MirroredRepeatWrapping)}
  5488. * @default ClampToEdgeWrapping
  5489. */
  5490. this.wrapT = wrapT;
  5491. /**
  5492. * How the texture is sampled when a texel covers more than one pixel.
  5493. *
  5494. * @type {(NearestFilter|NearestMipmapNearestFilter|NearestMipmapLinearFilter|LinearFilter|LinearMipmapNearestFilter|LinearMipmapLinearFilter)}
  5495. * @default LinearFilter
  5496. */
  5497. this.magFilter = magFilter;
  5498. /**
  5499. * How the texture is sampled when a texel covers less than one pixel.
  5500. *
  5501. * @type {(NearestFilter|NearestMipmapNearestFilter|NearestMipmapLinearFilter|LinearFilter|LinearMipmapNearestFilter|LinearMipmapLinearFilter)}
  5502. * @default LinearMipmapLinearFilter
  5503. */
  5504. this.minFilter = minFilter;
  5505. /**
  5506. * The number of samples taken along the axis through the pixel that has the
  5507. * highest density of texels. By default, this value is `1`. A higher value
  5508. * gives a less blurry result than a basic mipmap, at the cost of more
  5509. * texture samples being used.
  5510. *
  5511. * @type {number}
  5512. * @default Texture.DEFAULT_ANISOTROPY
  5513. */
  5514. this.anisotropy = anisotropy;
  5515. /**
  5516. * The format of the texture.
  5517. *
  5518. * @type {number}
  5519. * @default RGBAFormat
  5520. */
  5521. this.format = format;
  5522. /**
  5523. * The default internal format is derived from {@link Texture#format} and {@link Texture#type} and
  5524. * defines how the texture data is going to be stored on the GPU.
  5525. *
  5526. * This property allows to overwrite the default format.
  5527. *
  5528. * @type {?string}
  5529. * @default null
  5530. */
  5531. this.internalFormat = null;
  5532. /**
  5533. * The data type of the texture.
  5534. *
  5535. * @type {number}
  5536. * @default UnsignedByteType
  5537. */
  5538. this.type = type;
  5539. /**
  5540. * How much a single repetition of the texture is offset from the beginning,
  5541. * in each direction U and V. Typical range is `0.0` to `1.0`.
  5542. *
  5543. * @type {Vector2}
  5544. * @default (0,0)
  5545. */
  5546. this.offset = new Vector2( 0, 0 );
  5547. /**
  5548. * How many times the texture is repeated across the surface, in each
  5549. * direction U and V. If repeat is set greater than `1` in either direction,
  5550. * the corresponding wrap parameter should also be set to `RepeatWrapping`
  5551. * or `MirroredRepeatWrapping` to achieve the desired tiling effect.
  5552. *
  5553. * @type {Vector2}
  5554. * @default (1,1)
  5555. */
  5556. this.repeat = new Vector2( 1, 1 );
  5557. /**
  5558. * The point around which rotation occurs. A value of `(0.5, 0.5)` corresponds
  5559. * to the center of the texture. Default is `(0, 0)`, the lower left.
  5560. *
  5561. * @type {Vector2}
  5562. * @default (0,0)
  5563. */
  5564. this.center = new Vector2( 0, 0 );
  5565. /**
  5566. * How much the texture is rotated around the center point, in radians.
  5567. * Positive values are counter-clockwise.
  5568. *
  5569. * @type {number}
  5570. * @default 0
  5571. */
  5572. this.rotation = 0;
  5573. /**
  5574. * Whether to update the texture's uv-transformation {@link Texture#matrix}
  5575. * from the properties {@link Texture#offset}, {@link Texture#repeat},
  5576. * {@link Texture#rotation}, and {@link Texture#center}.
  5577. *
  5578. * Set this to `false` if you are specifying the uv-transform matrix directly.
  5579. *
  5580. * @type {boolean}
  5581. * @default true
  5582. */
  5583. this.matrixAutoUpdate = true;
  5584. /**
  5585. * The uv-transformation matrix of the texture.
  5586. *
  5587. * @type {Matrix3}
  5588. */
  5589. this.matrix = new Matrix3();
  5590. /**
  5591. * Whether to generate mipmaps (if possible) for a texture.
  5592. *
  5593. * Set this to `false` if you are creating mipmaps manually.
  5594. *
  5595. * @type {boolean}
  5596. * @default true
  5597. */
  5598. this.generateMipmaps = true;
  5599. /**
  5600. * If set to `true`, the alpha channel, if present, is multiplied into the
  5601. * color channels when the texture is uploaded to the GPU.
  5602. *
  5603. * Note that this property has no effect when using `ImageBitmap`. You need to
  5604. * configure premultiply alpha on bitmap creation instead.
  5605. *
  5606. * @type {boolean}
  5607. * @default false
  5608. */
  5609. this.premultiplyAlpha = false;
  5610. /**
  5611. * If set to `true`, the texture is flipped along the vertical axis when
  5612. * uploaded to the GPU.
  5613. *
  5614. * Note that this property has no effect when using `ImageBitmap`. You need to
  5615. * configure the flip on bitmap creation instead.
  5616. *
  5617. * @type {boolean}
  5618. * @default true
  5619. */
  5620. this.flipY = true;
  5621. /**
  5622. * Specifies the alignment requirements for the start of each pixel row in memory.
  5623. * The allowable values are `1` (byte-alignment), `2` (rows aligned to even-numbered bytes),
  5624. * `4` (word-alignment), and `8` (rows start on double-word boundaries).
  5625. *
  5626. * @type {number}
  5627. * @default 4
  5628. */
  5629. this.unpackAlignment = 4; // valid values: 1, 2, 4, 8 (see http://www.khronos.org/opengles/sdk/docs/man/xhtml/glPixelStorei.xml)
  5630. /**
  5631. * Textures containing color data should be annotated with `SRGBColorSpace` or `LinearSRGBColorSpace`.
  5632. *
  5633. * @type {string}
  5634. * @default NoColorSpace
  5635. */
  5636. this.colorSpace = colorSpace;
  5637. /**
  5638. * An object that can be used to store custom data about the texture. It
  5639. * should not hold references to functions as these will not be cloned.
  5640. *
  5641. * @type {Object}
  5642. */
  5643. this.userData = {};
  5644. /**
  5645. * This can be used to only update a subregion or specific rows of the texture (for example, just the
  5646. * first 3 rows). Use the `addUpdateRange()` function to add ranges to this array.
  5647. *
  5648. * @type {Array<Object>}
  5649. */
  5650. this.updateRanges = [];
  5651. /**
  5652. * This starts at `0` and counts how many times {@link Texture#needsUpdate} is set to `true`.
  5653. *
  5654. * @type {number}
  5655. * @readonly
  5656. * @default 0
  5657. */
  5658. this.version = 0;
  5659. /**
  5660. * A callback function, called when the texture is updated (e.g., when
  5661. * {@link Texture#needsUpdate} has been set to true and then the texture is used).
  5662. *
  5663. * @type {?Function}
  5664. * @default null
  5665. */
  5666. this.onUpdate = null;
  5667. /**
  5668. * An optional back reference to the textures render target.
  5669. *
  5670. * @type {?(RenderTarget|WebGLRenderTarget)}
  5671. * @default null
  5672. */
  5673. this.renderTarget = null;
  5674. /**
  5675. * Indicates whether a texture belongs to a render target or not.
  5676. *
  5677. * @type {boolean}
  5678. * @readonly
  5679. * @default false
  5680. */
  5681. this.isRenderTargetTexture = false;
  5682. /**
  5683. * Indicates if a texture should be handled like a texture array.
  5684. *
  5685. * @type {boolean}
  5686. * @readonly
  5687. * @default false
  5688. */
  5689. this.isArrayTexture = image && image.depth && image.depth > 1 ? true : false;
  5690. /**
  5691. * Indicates whether this texture should be processed by `PMREMGenerator` or not
  5692. * (only relevant for render target textures).
  5693. *
  5694. * @type {number}
  5695. * @readonly
  5696. * @default 0
  5697. */
  5698. this.pmremVersion = 0;
  5699. }
  5700. /**
  5701. * The width of the texture in pixels.
  5702. */
  5703. get width() {
  5704. return this.source.getSize( _tempVec3 ).x;
  5705. }
  5706. /**
  5707. * The height of the texture in pixels.
  5708. */
  5709. get height() {
  5710. return this.source.getSize( _tempVec3 ).y;
  5711. }
  5712. /**
  5713. * The depth of the texture in pixels.
  5714. */
  5715. get depth() {
  5716. return this.source.getSize( _tempVec3 ).z;
  5717. }
  5718. /**
  5719. * The image object holding the texture data.
  5720. *
  5721. * @type {?Object}
  5722. */
  5723. get image() {
  5724. return this.source.data;
  5725. }
  5726. set image( value = null ) {
  5727. this.source.data = value;
  5728. }
  5729. /**
  5730. * Updates the texture transformation matrix from the from the properties {@link Texture#offset},
  5731. * {@link Texture#repeat}, {@link Texture#rotation}, and {@link Texture#center}.
  5732. */
  5733. updateMatrix() {
  5734. this.matrix.setUvTransform( this.offset.x, this.offset.y, this.repeat.x, this.repeat.y, this.rotation, this.center.x, this.center.y );
  5735. }
  5736. /**
  5737. * Adds a range of data in the data texture to be updated on the GPU.
  5738. *
  5739. * @param {number} start - Position at which to start update.
  5740. * @param {number} count - The number of components to update.
  5741. */
  5742. addUpdateRange( start, count ) {
  5743. this.updateRanges.push( { start, count } );
  5744. }
  5745. /**
  5746. * Clears the update ranges.
  5747. */
  5748. clearUpdateRanges() {
  5749. this.updateRanges.length = 0;
  5750. }
  5751. /**
  5752. * Returns a new texture with copied values from this instance.
  5753. *
  5754. * @return {Texture} A clone of this instance.
  5755. */
  5756. clone() {
  5757. return new this.constructor().copy( this );
  5758. }
  5759. /**
  5760. * Copies the values of the given texture to this instance.
  5761. *
  5762. * @param {Texture} source - The texture to copy.
  5763. * @return {Texture} A reference to this instance.
  5764. */
  5765. copy( source ) {
  5766. this.name = source.name;
  5767. this.source = source.source;
  5768. this.mipmaps = source.mipmaps.slice( 0 );
  5769. this.mapping = source.mapping;
  5770. this.channel = source.channel;
  5771. this.wrapS = source.wrapS;
  5772. this.wrapT = source.wrapT;
  5773. this.magFilter = source.magFilter;
  5774. this.minFilter = source.minFilter;
  5775. this.anisotropy = source.anisotropy;
  5776. this.format = source.format;
  5777. this.internalFormat = source.internalFormat;
  5778. this.type = source.type;
  5779. this.offset.copy( source.offset );
  5780. this.repeat.copy( source.repeat );
  5781. this.center.copy( source.center );
  5782. this.rotation = source.rotation;
  5783. this.matrixAutoUpdate = source.matrixAutoUpdate;
  5784. this.matrix.copy( source.matrix );
  5785. this.generateMipmaps = source.generateMipmaps;
  5786. this.premultiplyAlpha = source.premultiplyAlpha;
  5787. this.flipY = source.flipY;
  5788. this.unpackAlignment = source.unpackAlignment;
  5789. this.colorSpace = source.colorSpace;
  5790. this.renderTarget = source.renderTarget;
  5791. this.isRenderTargetTexture = source.isRenderTargetTexture;
  5792. this.isArrayTexture = source.isArrayTexture;
  5793. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  5794. this.needsUpdate = true;
  5795. return this;
  5796. }
  5797. /**
  5798. * Sets this texture's properties based on `values`.
  5799. * @param {Object} values - A container with texture parameters.
  5800. */
  5801. setValues( values ) {
  5802. for ( const key in values ) {
  5803. const newValue = values[ key ];
  5804. if ( newValue === undefined ) {
  5805. warn( `Texture.setValues(): parameter '${ key }' has value of undefined.` );
  5806. continue;
  5807. }
  5808. const currentValue = this[ key ];
  5809. if ( currentValue === undefined ) {
  5810. warn( `Texture.setValues(): property '${ key }' does not exist.` );
  5811. continue;
  5812. }
  5813. if ( ( currentValue && newValue ) && ( currentValue.isVector2 && newValue.isVector2 ) ) {
  5814. currentValue.copy( newValue );
  5815. } else if ( ( currentValue && newValue ) && ( currentValue.isVector3 && newValue.isVector3 ) ) {
  5816. currentValue.copy( newValue );
  5817. } else if ( ( currentValue && newValue ) && ( currentValue.isMatrix3 && newValue.isMatrix3 ) ) {
  5818. currentValue.copy( newValue );
  5819. } else {
  5820. this[ key ] = newValue;
  5821. }
  5822. }
  5823. }
  5824. /**
  5825. * Serializes the texture into JSON.
  5826. *
  5827. * @param {?(Object|string)} meta - An optional value holding meta information about the serialization.
  5828. * @return {Object} A JSON object representing the serialized texture.
  5829. * @see {@link ObjectLoader#parse}
  5830. */
  5831. toJSON( meta ) {
  5832. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  5833. if ( ! isRootObject && meta.textures[ this.uuid ] !== undefined ) {
  5834. return meta.textures[ this.uuid ];
  5835. }
  5836. const output = {
  5837. metadata: {
  5838. version: 4.7,
  5839. type: 'Texture',
  5840. generator: 'Texture.toJSON'
  5841. },
  5842. uuid: this.uuid,
  5843. name: this.name,
  5844. image: this.source.toJSON( meta ).uuid,
  5845. mapping: this.mapping,
  5846. channel: this.channel,
  5847. repeat: [ this.repeat.x, this.repeat.y ],
  5848. offset: [ this.offset.x, this.offset.y ],
  5849. center: [ this.center.x, this.center.y ],
  5850. rotation: this.rotation,
  5851. wrap: [ this.wrapS, this.wrapT ],
  5852. format: this.format,
  5853. internalFormat: this.internalFormat,
  5854. type: this.type,
  5855. colorSpace: this.colorSpace,
  5856. minFilter: this.minFilter,
  5857. magFilter: this.magFilter,
  5858. anisotropy: this.anisotropy,
  5859. flipY: this.flipY,
  5860. generateMipmaps: this.generateMipmaps,
  5861. premultiplyAlpha: this.premultiplyAlpha,
  5862. unpackAlignment: this.unpackAlignment
  5863. };
  5864. if ( Object.keys( this.userData ).length > 0 ) output.userData = this.userData;
  5865. if ( ! isRootObject ) {
  5866. meta.textures[ this.uuid ] = output;
  5867. }
  5868. return output;
  5869. }
  5870. /**
  5871. * Frees the GPU-related resources allocated by this instance. Call this
  5872. * method whenever this instance is no longer used in your app.
  5873. *
  5874. * @fires Texture#dispose
  5875. */
  5876. dispose() {
  5877. /**
  5878. * Fires when the texture has been disposed of.
  5879. *
  5880. * @event Texture#dispose
  5881. * @type {Object}
  5882. */
  5883. this.dispatchEvent( { type: 'dispose' } );
  5884. }
  5885. /**
  5886. * Transforms the given uv vector with the textures uv transformation matrix.
  5887. *
  5888. * @param {Vector2} uv - The uv vector.
  5889. * @return {Vector2} The transformed uv vector.
  5890. */
  5891. transformUv( uv ) {
  5892. if ( this.mapping !== UVMapping ) return uv;
  5893. uv.applyMatrix3( this.matrix );
  5894. if ( uv.x < 0 || uv.x > 1 ) {
  5895. switch ( this.wrapS ) {
  5896. case RepeatWrapping:
  5897. uv.x = uv.x - Math.floor( uv.x );
  5898. break;
  5899. case ClampToEdgeWrapping:
  5900. uv.x = uv.x < 0 ? 0 : 1;
  5901. break;
  5902. case MirroredRepeatWrapping:
  5903. if ( Math.abs( Math.floor( uv.x ) % 2 ) === 1 ) {
  5904. uv.x = Math.ceil( uv.x ) - uv.x;
  5905. } else {
  5906. uv.x = uv.x - Math.floor( uv.x );
  5907. }
  5908. break;
  5909. }
  5910. }
  5911. if ( uv.y < 0 || uv.y > 1 ) {
  5912. switch ( this.wrapT ) {
  5913. case RepeatWrapping:
  5914. uv.y = uv.y - Math.floor( uv.y );
  5915. break;
  5916. case ClampToEdgeWrapping:
  5917. uv.y = uv.y < 0 ? 0 : 1;
  5918. break;
  5919. case MirroredRepeatWrapping:
  5920. if ( Math.abs( Math.floor( uv.y ) % 2 ) === 1 ) {
  5921. uv.y = Math.ceil( uv.y ) - uv.y;
  5922. } else {
  5923. uv.y = uv.y - Math.floor( uv.y );
  5924. }
  5925. break;
  5926. }
  5927. }
  5928. if ( this.flipY ) {
  5929. uv.y = 1 - uv.y;
  5930. }
  5931. return uv;
  5932. }
  5933. /**
  5934. * Setting this property to `true` indicates the engine the texture
  5935. * must be updated in the next render. This triggers a texture upload
  5936. * to the GPU and ensures correct texture parameter configuration.
  5937. *
  5938. * @type {boolean}
  5939. * @default false
  5940. * @param {boolean} value
  5941. */
  5942. set needsUpdate( value ) {
  5943. if ( value === true ) {
  5944. this.version ++;
  5945. this.source.needsUpdate = true;
  5946. }
  5947. }
  5948. /**
  5949. * Setting this property to `true` indicates the engine the PMREM
  5950. * must be regenerated.
  5951. *
  5952. * @type {boolean}
  5953. * @default false
  5954. * @param {boolean} value
  5955. */
  5956. set needsPMREMUpdate( value ) {
  5957. if ( value === true ) {
  5958. this.pmremVersion ++;
  5959. }
  5960. }
  5961. }
  5962. /**
  5963. * The default image for all textures.
  5964. *
  5965. * @static
  5966. * @type {?Image}
  5967. * @default null
  5968. */
  5969. Texture.DEFAULT_IMAGE = null;
  5970. /**
  5971. * The default mapping for all textures.
  5972. *
  5973. * @static
  5974. * @type {number}
  5975. * @default UVMapping
  5976. */
  5977. Texture.DEFAULT_MAPPING = UVMapping;
  5978. /**
  5979. * The default anisotropy value for all textures.
  5980. *
  5981. * @static
  5982. * @type {number}
  5983. * @default 1
  5984. */
  5985. Texture.DEFAULT_ANISOTROPY = 1;
  5986. /**
  5987. * Class representing a 4D vector. A 4D vector is an ordered quadruplet of numbers
  5988. * (labeled x, y, z and w), which can be used to represent a number of things, such as:
  5989. *
  5990. * - A point in 4D space.
  5991. * - A direction and length in 4D space. In three.js the length will
  5992. * always be the Euclidean distance(straight-line distance) from `(0, 0, 0, 0)` to `(x, y, z, w)`
  5993. * and the direction is also measured from `(0, 0, 0, 0)` towards `(x, y, z, w)`.
  5994. * - Any arbitrary ordered quadruplet of numbers.
  5995. *
  5996. * There are other things a 4D vector can be used to represent, however these
  5997. * are the most common uses in *three.js*.
  5998. *
  5999. * Iterating through a vector instance will yield its components `(x, y, z, w)` in
  6000. * the corresponding order.
  6001. * ```js
  6002. * const a = new THREE.Vector4( 0, 1, 0, 0 );
  6003. *
  6004. * //no arguments; will be initialised to (0, 0, 0, 1)
  6005. * const b = new THREE.Vector4( );
  6006. *
  6007. * const d = a.dot( b );
  6008. * ```
  6009. */
  6010. class Vector4 {
  6011. /**
  6012. * Constructs a new 4D vector.
  6013. *
  6014. * @param {number} [x=0] - The x value of this vector.
  6015. * @param {number} [y=0] - The y value of this vector.
  6016. * @param {number} [z=0] - The z value of this vector.
  6017. * @param {number} [w=1] - The w value of this vector.
  6018. */
  6019. constructor( x = 0, y = 0, z = 0, w = 1 ) {
  6020. /**
  6021. * This flag can be used for type testing.
  6022. *
  6023. * @type {boolean}
  6024. * @readonly
  6025. * @default true
  6026. */
  6027. Vector4.prototype.isVector4 = true;
  6028. /**
  6029. * The x value of this vector.
  6030. *
  6031. * @type {number}
  6032. */
  6033. this.x = x;
  6034. /**
  6035. * The y value of this vector.
  6036. *
  6037. * @type {number}
  6038. */
  6039. this.y = y;
  6040. /**
  6041. * The z value of this vector.
  6042. *
  6043. * @type {number}
  6044. */
  6045. this.z = z;
  6046. /**
  6047. * The w value of this vector.
  6048. *
  6049. * @type {number}
  6050. */
  6051. this.w = w;
  6052. }
  6053. /**
  6054. * Alias for {@link Vector4#z}.
  6055. *
  6056. * @type {number}
  6057. */
  6058. get width() {
  6059. return this.z;
  6060. }
  6061. set width( value ) {
  6062. this.z = value;
  6063. }
  6064. /**
  6065. * Alias for {@link Vector4#w}.
  6066. *
  6067. * @type {number}
  6068. */
  6069. get height() {
  6070. return this.w;
  6071. }
  6072. set height( value ) {
  6073. this.w = value;
  6074. }
  6075. /**
  6076. * Sets the vector components.
  6077. *
  6078. * @param {number} x - The value of the x component.
  6079. * @param {number} y - The value of the y component.
  6080. * @param {number} z - The value of the z component.
  6081. * @param {number} w - The value of the w component.
  6082. * @return {Vector4} A reference to this vector.
  6083. */
  6084. set( x, y, z, w ) {
  6085. this.x = x;
  6086. this.y = y;
  6087. this.z = z;
  6088. this.w = w;
  6089. return this;
  6090. }
  6091. /**
  6092. * Sets the vector components to the same value.
  6093. *
  6094. * @param {number} scalar - The value to set for all vector components.
  6095. * @return {Vector4} A reference to this vector.
  6096. */
  6097. setScalar( scalar ) {
  6098. this.x = scalar;
  6099. this.y = scalar;
  6100. this.z = scalar;
  6101. this.w = scalar;
  6102. return this;
  6103. }
  6104. /**
  6105. * Sets the vector's x component to the given value
  6106. *
  6107. * @param {number} x - The value to set.
  6108. * @return {Vector4} A reference to this vector.
  6109. */
  6110. setX( x ) {
  6111. this.x = x;
  6112. return this;
  6113. }
  6114. /**
  6115. * Sets the vector's y component to the given value
  6116. *
  6117. * @param {number} y - The value to set.
  6118. * @return {Vector4} A reference to this vector.
  6119. */
  6120. setY( y ) {
  6121. this.y = y;
  6122. return this;
  6123. }
  6124. /**
  6125. * Sets the vector's z component to the given value
  6126. *
  6127. * @param {number} z - The value to set.
  6128. * @return {Vector4} A reference to this vector.
  6129. */
  6130. setZ( z ) {
  6131. this.z = z;
  6132. return this;
  6133. }
  6134. /**
  6135. * Sets the vector's w component to the given value
  6136. *
  6137. * @param {number} w - The value to set.
  6138. * @return {Vector4} A reference to this vector.
  6139. */
  6140. setW( w ) {
  6141. this.w = w;
  6142. return this;
  6143. }
  6144. /**
  6145. * Allows to set a vector component with an index.
  6146. *
  6147. * @param {number} index - The component index. `0` equals to x, `1` equals to y,
  6148. * `2` equals to z, `3` equals to w.
  6149. * @param {number} value - The value to set.
  6150. * @return {Vector4} A reference to this vector.
  6151. */
  6152. setComponent( index, value ) {
  6153. switch ( index ) {
  6154. case 0: this.x = value; break;
  6155. case 1: this.y = value; break;
  6156. case 2: this.z = value; break;
  6157. case 3: this.w = value; break;
  6158. default: throw new Error( 'index is out of range: ' + index );
  6159. }
  6160. return this;
  6161. }
  6162. /**
  6163. * Returns the value of the vector component which matches the given index.
  6164. *
  6165. * @param {number} index - The component index. `0` equals to x, `1` equals to y,
  6166. * `2` equals to z, `3` equals to w.
  6167. * @return {number} A vector component value.
  6168. */
  6169. getComponent( index ) {
  6170. switch ( index ) {
  6171. case 0: return this.x;
  6172. case 1: return this.y;
  6173. case 2: return this.z;
  6174. case 3: return this.w;
  6175. default: throw new Error( 'index is out of range: ' + index );
  6176. }
  6177. }
  6178. /**
  6179. * Returns a new vector with copied values from this instance.
  6180. *
  6181. * @return {Vector4} A clone of this instance.
  6182. */
  6183. clone() {
  6184. return new this.constructor( this.x, this.y, this.z, this.w );
  6185. }
  6186. /**
  6187. * Copies the values of the given vector to this instance.
  6188. *
  6189. * @param {Vector3|Vector4} v - The vector to copy.
  6190. * @return {Vector4} A reference to this vector.
  6191. */
  6192. copy( v ) {
  6193. this.x = v.x;
  6194. this.y = v.y;
  6195. this.z = v.z;
  6196. this.w = ( v.w !== undefined ) ? v.w : 1;
  6197. return this;
  6198. }
  6199. /**
  6200. * Adds the given vector to this instance.
  6201. *
  6202. * @param {Vector4} v - The vector to add.
  6203. * @return {Vector4} A reference to this vector.
  6204. */
  6205. add( v ) {
  6206. this.x += v.x;
  6207. this.y += v.y;
  6208. this.z += v.z;
  6209. this.w += v.w;
  6210. return this;
  6211. }
  6212. /**
  6213. * Adds the given scalar value to all components of this instance.
  6214. *
  6215. * @param {number} s - The scalar to add.
  6216. * @return {Vector4} A reference to this vector.
  6217. */
  6218. addScalar( s ) {
  6219. this.x += s;
  6220. this.y += s;
  6221. this.z += s;
  6222. this.w += s;
  6223. return this;
  6224. }
  6225. /**
  6226. * Adds the given vectors and stores the result in this instance.
  6227. *
  6228. * @param {Vector4} a - The first vector.
  6229. * @param {Vector4} b - The second vector.
  6230. * @return {Vector4} A reference to this vector.
  6231. */
  6232. addVectors( a, b ) {
  6233. this.x = a.x + b.x;
  6234. this.y = a.y + b.y;
  6235. this.z = a.z + b.z;
  6236. this.w = a.w + b.w;
  6237. return this;
  6238. }
  6239. /**
  6240. * Adds the given vector scaled by the given factor to this instance.
  6241. *
  6242. * @param {Vector4} v - The vector.
  6243. * @param {number} s - The factor that scales `v`.
  6244. * @return {Vector4} A reference to this vector.
  6245. */
  6246. addScaledVector( v, s ) {
  6247. this.x += v.x * s;
  6248. this.y += v.y * s;
  6249. this.z += v.z * s;
  6250. this.w += v.w * s;
  6251. return this;
  6252. }
  6253. /**
  6254. * Subtracts the given vector from this instance.
  6255. *
  6256. * @param {Vector4} v - The vector to subtract.
  6257. * @return {Vector4} A reference to this vector.
  6258. */
  6259. sub( v ) {
  6260. this.x -= v.x;
  6261. this.y -= v.y;
  6262. this.z -= v.z;
  6263. this.w -= v.w;
  6264. return this;
  6265. }
  6266. /**
  6267. * Subtracts the given scalar value from all components of this instance.
  6268. *
  6269. * @param {number} s - The scalar to subtract.
  6270. * @return {Vector4} A reference to this vector.
  6271. */
  6272. subScalar( s ) {
  6273. this.x -= s;
  6274. this.y -= s;
  6275. this.z -= s;
  6276. this.w -= s;
  6277. return this;
  6278. }
  6279. /**
  6280. * Subtracts the given vectors and stores the result in this instance.
  6281. *
  6282. * @param {Vector4} a - The first vector.
  6283. * @param {Vector4} b - The second vector.
  6284. * @return {Vector4} A reference to this vector.
  6285. */
  6286. subVectors( a, b ) {
  6287. this.x = a.x - b.x;
  6288. this.y = a.y - b.y;
  6289. this.z = a.z - b.z;
  6290. this.w = a.w - b.w;
  6291. return this;
  6292. }
  6293. /**
  6294. * Multiplies the given vector with this instance.
  6295. *
  6296. * @param {Vector4} v - The vector to multiply.
  6297. * @return {Vector4} A reference to this vector.
  6298. */
  6299. multiply( v ) {
  6300. this.x *= v.x;
  6301. this.y *= v.y;
  6302. this.z *= v.z;
  6303. this.w *= v.w;
  6304. return this;
  6305. }
  6306. /**
  6307. * Multiplies the given scalar value with all components of this instance.
  6308. *
  6309. * @param {number} scalar - The scalar to multiply.
  6310. * @return {Vector4} A reference to this vector.
  6311. */
  6312. multiplyScalar( scalar ) {
  6313. this.x *= scalar;
  6314. this.y *= scalar;
  6315. this.z *= scalar;
  6316. this.w *= scalar;
  6317. return this;
  6318. }
  6319. /**
  6320. * Multiplies this vector with the given 4x4 matrix.
  6321. *
  6322. * @param {Matrix4} m - The 4x4 matrix.
  6323. * @return {Vector4} A reference to this vector.
  6324. */
  6325. applyMatrix4( m ) {
  6326. const x = this.x, y = this.y, z = this.z, w = this.w;
  6327. const e = m.elements;
  6328. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] * w;
  6329. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] * w;
  6330. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] * w;
  6331. this.w = e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] * w;
  6332. return this;
  6333. }
  6334. /**
  6335. * Divides this instance by the given vector.
  6336. *
  6337. * @param {Vector4} v - The vector to divide.
  6338. * @return {Vector4} A reference to this vector.
  6339. */
  6340. divide( v ) {
  6341. this.x /= v.x;
  6342. this.y /= v.y;
  6343. this.z /= v.z;
  6344. this.w /= v.w;
  6345. return this;
  6346. }
  6347. /**
  6348. * Divides this vector by the given scalar.
  6349. *
  6350. * @param {number} scalar - The scalar to divide.
  6351. * @return {Vector4} A reference to this vector.
  6352. */
  6353. divideScalar( scalar ) {
  6354. return this.multiplyScalar( 1 / scalar );
  6355. }
  6356. /**
  6357. * Sets the x, y and z components of this
  6358. * vector to the quaternion's axis and w to the angle.
  6359. *
  6360. * @param {Quaternion} q - The Quaternion to set.
  6361. * @return {Vector4} A reference to this vector.
  6362. */
  6363. setAxisAngleFromQuaternion( q ) {
  6364. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToAngle/index.htm
  6365. // q is assumed to be normalized
  6366. this.w = 2 * Math.acos( q.w );
  6367. const s = Math.sqrt( 1 - q.w * q.w );
  6368. if ( s < 0.0001 ) {
  6369. this.x = 1;
  6370. this.y = 0;
  6371. this.z = 0;
  6372. } else {
  6373. this.x = q.x / s;
  6374. this.y = q.y / s;
  6375. this.z = q.z / s;
  6376. }
  6377. return this;
  6378. }
  6379. /**
  6380. * Sets the x, y and z components of this
  6381. * vector to the axis of rotation and w to the angle.
  6382. *
  6383. * @param {Matrix4} m - A 4x4 matrix of which the upper left 3x3 matrix is a pure rotation matrix.
  6384. * @return {Vector4} A reference to this vector.
  6385. */
  6386. setAxisAngleFromRotationMatrix( m ) {
  6387. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToAngle/index.htm
  6388. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  6389. let angle, x, y, z; // variables for result
  6390. const epsilon = 0.01, // margin to allow for rounding errors
  6391. epsilon2 = 0.1, // margin to distinguish between 0 and 180 degrees
  6392. te = m.elements,
  6393. m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ],
  6394. m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ],
  6395. m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];
  6396. if ( ( Math.abs( m12 - m21 ) < epsilon ) &&
  6397. ( Math.abs( m13 - m31 ) < epsilon ) &&
  6398. ( Math.abs( m23 - m32 ) < epsilon ) ) {
  6399. // singularity found
  6400. // first check for identity matrix which must have +1 for all terms
  6401. // in leading diagonal and zero in other terms
  6402. if ( ( Math.abs( m12 + m21 ) < epsilon2 ) &&
  6403. ( Math.abs( m13 + m31 ) < epsilon2 ) &&
  6404. ( Math.abs( m23 + m32 ) < epsilon2 ) &&
  6405. ( Math.abs( m11 + m22 + m33 - 3 ) < epsilon2 ) ) {
  6406. // this singularity is identity matrix so angle = 0
  6407. this.set( 1, 0, 0, 0 );
  6408. return this; // zero angle, arbitrary axis
  6409. }
  6410. // otherwise this singularity is angle = 180
  6411. angle = Math.PI;
  6412. const xx = ( m11 + 1 ) / 2;
  6413. const yy = ( m22 + 1 ) / 2;
  6414. const zz = ( m33 + 1 ) / 2;
  6415. const xy = ( m12 + m21 ) / 4;
  6416. const xz = ( m13 + m31 ) / 4;
  6417. const yz = ( m23 + m32 ) / 4;
  6418. if ( ( xx > yy ) && ( xx > zz ) ) {
  6419. // m11 is the largest diagonal term
  6420. if ( xx < epsilon ) {
  6421. x = 0;
  6422. y = 0.707106781;
  6423. z = 0.707106781;
  6424. } else {
  6425. x = Math.sqrt( xx );
  6426. y = xy / x;
  6427. z = xz / x;
  6428. }
  6429. } else if ( yy > zz ) {
  6430. // m22 is the largest diagonal term
  6431. if ( yy < epsilon ) {
  6432. x = 0.707106781;
  6433. y = 0;
  6434. z = 0.707106781;
  6435. } else {
  6436. y = Math.sqrt( yy );
  6437. x = xy / y;
  6438. z = yz / y;
  6439. }
  6440. } else {
  6441. // m33 is the largest diagonal term so base result on this
  6442. if ( zz < epsilon ) {
  6443. x = 0.707106781;
  6444. y = 0.707106781;
  6445. z = 0;
  6446. } else {
  6447. z = Math.sqrt( zz );
  6448. x = xz / z;
  6449. y = yz / z;
  6450. }
  6451. }
  6452. this.set( x, y, z, angle );
  6453. return this; // return 180 deg rotation
  6454. }
  6455. // as we have reached here there are no singularities so we can handle normally
  6456. let s = Math.sqrt( ( m32 - m23 ) * ( m32 - m23 ) +
  6457. ( m13 - m31 ) * ( m13 - m31 ) +
  6458. ( m21 - m12 ) * ( m21 - m12 ) ); // used to normalize
  6459. if ( Math.abs( s ) < 0.001 ) s = 1;
  6460. // prevent divide by zero, should not happen if matrix is orthogonal and should be
  6461. // caught by singularity test above, but I've left it in just in case
  6462. this.x = ( m32 - m23 ) / s;
  6463. this.y = ( m13 - m31 ) / s;
  6464. this.z = ( m21 - m12 ) / s;
  6465. this.w = Math.acos( ( m11 + m22 + m33 - 1 ) / 2 );
  6466. return this;
  6467. }
  6468. /**
  6469. * Sets the vector components to the position elements of the
  6470. * given transformation matrix.
  6471. *
  6472. * @param {Matrix4} m - The 4x4 matrix.
  6473. * @return {Vector4} A reference to this vector.
  6474. */
  6475. setFromMatrixPosition( m ) {
  6476. const e = m.elements;
  6477. this.x = e[ 12 ];
  6478. this.y = e[ 13 ];
  6479. this.z = e[ 14 ];
  6480. this.w = e[ 15 ];
  6481. return this;
  6482. }
  6483. /**
  6484. * If this vector's x, y, z or w value is greater than the given vector's x, y, z or w
  6485. * value, replace that value with the corresponding min value.
  6486. *
  6487. * @param {Vector4} v - The vector.
  6488. * @return {Vector4} A reference to this vector.
  6489. */
  6490. min( v ) {
  6491. this.x = Math.min( this.x, v.x );
  6492. this.y = Math.min( this.y, v.y );
  6493. this.z = Math.min( this.z, v.z );
  6494. this.w = Math.min( this.w, v.w );
  6495. return this;
  6496. }
  6497. /**
  6498. * If this vector's x, y, z or w value is less than the given vector's x, y, z or w
  6499. * value, replace that value with the corresponding max value.
  6500. *
  6501. * @param {Vector4} v - The vector.
  6502. * @return {Vector4} A reference to this vector.
  6503. */
  6504. max( v ) {
  6505. this.x = Math.max( this.x, v.x );
  6506. this.y = Math.max( this.y, v.y );
  6507. this.z = Math.max( this.z, v.z );
  6508. this.w = Math.max( this.w, v.w );
  6509. return this;
  6510. }
  6511. /**
  6512. * If this vector's x, y, z or w value is greater than the max vector's x, y, z or w
  6513. * value, it is replaced by the corresponding value.
  6514. * If this vector's x, y, z or w value is less than the min vector's x, y, z or w value,
  6515. * it is replaced by the corresponding value.
  6516. *
  6517. * @param {Vector4} min - The minimum x, y and z values.
  6518. * @param {Vector4} max - The maximum x, y and z values in the desired range.
  6519. * @return {Vector4} A reference to this vector.
  6520. */
  6521. clamp( min, max ) {
  6522. // assumes min < max, componentwise
  6523. this.x = clamp( this.x, min.x, max.x );
  6524. this.y = clamp( this.y, min.y, max.y );
  6525. this.z = clamp( this.z, min.z, max.z );
  6526. this.w = clamp( this.w, min.w, max.w );
  6527. return this;
  6528. }
  6529. /**
  6530. * If this vector's x, y, z or w values are greater than the max value, they are
  6531. * replaced by the max value.
  6532. * If this vector's x, y, z or w values are less than the min value, they are
  6533. * replaced by the min value.
  6534. *
  6535. * @param {number} minVal - The minimum value the components will be clamped to.
  6536. * @param {number} maxVal - The maximum value the components will be clamped to.
  6537. * @return {Vector4} A reference to this vector.
  6538. */
  6539. clampScalar( minVal, maxVal ) {
  6540. this.x = clamp( this.x, minVal, maxVal );
  6541. this.y = clamp( this.y, minVal, maxVal );
  6542. this.z = clamp( this.z, minVal, maxVal );
  6543. this.w = clamp( this.w, minVal, maxVal );
  6544. return this;
  6545. }
  6546. /**
  6547. * If this vector's length is greater than the max value, it is replaced by
  6548. * the max value.
  6549. * If this vector's length is less than the min value, it is replaced by the
  6550. * min value.
  6551. *
  6552. * @param {number} min - The minimum value the vector length will be clamped to.
  6553. * @param {number} max - The maximum value the vector length will be clamped to.
  6554. * @return {Vector4} A reference to this vector.
  6555. */
  6556. clampLength( min, max ) {
  6557. const length = this.length();
  6558. return this.divideScalar( length || 1 ).multiplyScalar( clamp( length, min, max ) );
  6559. }
  6560. /**
  6561. * The components of this vector are rounded down to the nearest integer value.
  6562. *
  6563. * @return {Vector4} A reference to this vector.
  6564. */
  6565. floor() {
  6566. this.x = Math.floor( this.x );
  6567. this.y = Math.floor( this.y );
  6568. this.z = Math.floor( this.z );
  6569. this.w = Math.floor( this.w );
  6570. return this;
  6571. }
  6572. /**
  6573. * The components of this vector are rounded up to the nearest integer value.
  6574. *
  6575. * @return {Vector4} A reference to this vector.
  6576. */
  6577. ceil() {
  6578. this.x = Math.ceil( this.x );
  6579. this.y = Math.ceil( this.y );
  6580. this.z = Math.ceil( this.z );
  6581. this.w = Math.ceil( this.w );
  6582. return this;
  6583. }
  6584. /**
  6585. * The components of this vector are rounded to the nearest integer value
  6586. *
  6587. * @return {Vector4} A reference to this vector.
  6588. */
  6589. round() {
  6590. this.x = Math.round( this.x );
  6591. this.y = Math.round( this.y );
  6592. this.z = Math.round( this.z );
  6593. this.w = Math.round( this.w );
  6594. return this;
  6595. }
  6596. /**
  6597. * The components of this vector are rounded towards zero (up if negative,
  6598. * down if positive) to an integer value.
  6599. *
  6600. * @return {Vector4} A reference to this vector.
  6601. */
  6602. roundToZero() {
  6603. this.x = Math.trunc( this.x );
  6604. this.y = Math.trunc( this.y );
  6605. this.z = Math.trunc( this.z );
  6606. this.w = Math.trunc( this.w );
  6607. return this;
  6608. }
  6609. /**
  6610. * Inverts this vector - i.e. sets x = -x, y = -y, z = -z, w = -w.
  6611. *
  6612. * @return {Vector4} A reference to this vector.
  6613. */
  6614. negate() {
  6615. this.x = - this.x;
  6616. this.y = - this.y;
  6617. this.z = - this.z;
  6618. this.w = - this.w;
  6619. return this;
  6620. }
  6621. /**
  6622. * Calculates the dot product of the given vector with this instance.
  6623. *
  6624. * @param {Vector4} v - The vector to compute the dot product with.
  6625. * @return {number} The result of the dot product.
  6626. */
  6627. dot( v ) {
  6628. return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w;
  6629. }
  6630. /**
  6631. * Computes the square of the Euclidean length (straight-line length) from
  6632. * (0, 0, 0, 0) to (x, y, z, w). If you are comparing the lengths of vectors, you should
  6633. * compare the length squared instead as it is slightly more efficient to calculate.
  6634. *
  6635. * @return {number} The square length of this vector.
  6636. */
  6637. lengthSq() {
  6638. return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w;
  6639. }
  6640. /**
  6641. * Computes the Euclidean length (straight-line length) from (0, 0, 0, 0) to (x, y, z, w).
  6642. *
  6643. * @return {number} The length of this vector.
  6644. */
  6645. length() {
  6646. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w );
  6647. }
  6648. /**
  6649. * Computes the Manhattan length of this vector.
  6650. *
  6651. * @return {number} The length of this vector.
  6652. */
  6653. manhattanLength() {
  6654. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z ) + Math.abs( this.w );
  6655. }
  6656. /**
  6657. * Converts this vector to a unit vector - that is, sets it equal to a vector
  6658. * with the same direction as this one, but with a vector length of `1`.
  6659. *
  6660. * @return {Vector4} A reference to this vector.
  6661. */
  6662. normalize() {
  6663. return this.divideScalar( this.length() || 1 );
  6664. }
  6665. /**
  6666. * Sets this vector to a vector with the same direction as this one, but
  6667. * with the specified length.
  6668. *
  6669. * @param {number} length - The new length of this vector.
  6670. * @return {Vector4} A reference to this vector.
  6671. */
  6672. setLength( length ) {
  6673. return this.normalize().multiplyScalar( length );
  6674. }
  6675. /**
  6676. * Linearly interpolates between the given vector and this instance, where
  6677. * alpha is the percent distance along the line - alpha = 0 will be this
  6678. * vector, and alpha = 1 will be the given one.
  6679. *
  6680. * @param {Vector4} v - The vector to interpolate towards.
  6681. * @param {number} alpha - The interpolation factor, typically in the closed interval `[0, 1]`.
  6682. * @return {Vector4} A reference to this vector.
  6683. */
  6684. lerp( v, alpha ) {
  6685. this.x += ( v.x - this.x ) * alpha;
  6686. this.y += ( v.y - this.y ) * alpha;
  6687. this.z += ( v.z - this.z ) * alpha;
  6688. this.w += ( v.w - this.w ) * alpha;
  6689. return this;
  6690. }
  6691. /**
  6692. * Linearly interpolates between the given vectors, where alpha is the percent
  6693. * distance along the line - alpha = 0 will be first vector, and alpha = 1 will
  6694. * be the second one. The result is stored in this instance.
  6695. *
  6696. * @param {Vector4} v1 - The first vector.
  6697. * @param {Vector4} v2 - The second vector.
  6698. * @param {number} alpha - The interpolation factor, typically in the closed interval `[0, 1]`.
  6699. * @return {Vector4} A reference to this vector.
  6700. */
  6701. lerpVectors( v1, v2, alpha ) {
  6702. this.x = v1.x + ( v2.x - v1.x ) * alpha;
  6703. this.y = v1.y + ( v2.y - v1.y ) * alpha;
  6704. this.z = v1.z + ( v2.z - v1.z ) * alpha;
  6705. this.w = v1.w + ( v2.w - v1.w ) * alpha;
  6706. return this;
  6707. }
  6708. /**
  6709. * Returns `true` if this vector is equal with the given one.
  6710. *
  6711. * @param {Vector4} v - The vector to test for equality.
  6712. * @return {boolean} Whether this vector is equal with the given one.
  6713. */
  6714. equals( v ) {
  6715. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) && ( v.w === this.w ) );
  6716. }
  6717. /**
  6718. * Sets this vector's x value to be `array[ offset ]`, y value to be `array[ offset + 1 ]`,
  6719. * z value to be `array[ offset + 2 ]`, w value to be `array[ offset + 3 ]`.
  6720. *
  6721. * @param {Array<number>} array - An array holding the vector component values.
  6722. * @param {number} [offset=0] - The offset into the array.
  6723. * @return {Vector4} A reference to this vector.
  6724. */
  6725. fromArray( array, offset = 0 ) {
  6726. this.x = array[ offset ];
  6727. this.y = array[ offset + 1 ];
  6728. this.z = array[ offset + 2 ];
  6729. this.w = array[ offset + 3 ];
  6730. return this;
  6731. }
  6732. /**
  6733. * Writes the components of this vector to the given array. If no array is provided,
  6734. * the method returns a new instance.
  6735. *
  6736. * @param {Array<number>} [array=[]] - The target array holding the vector components.
  6737. * @param {number} [offset=0] - Index of the first element in the array.
  6738. * @return {Array<number>} The vector components.
  6739. */
  6740. toArray( array = [], offset = 0 ) {
  6741. array[ offset ] = this.x;
  6742. array[ offset + 1 ] = this.y;
  6743. array[ offset + 2 ] = this.z;
  6744. array[ offset + 3 ] = this.w;
  6745. return array;
  6746. }
  6747. /**
  6748. * Sets the components of this vector from the given buffer attribute.
  6749. *
  6750. * @param {BufferAttribute} attribute - The buffer attribute holding vector data.
  6751. * @param {number} index - The index into the attribute.
  6752. * @return {Vector4} A reference to this vector.
  6753. */
  6754. fromBufferAttribute( attribute, index ) {
  6755. this.x = attribute.getX( index );
  6756. this.y = attribute.getY( index );
  6757. this.z = attribute.getZ( index );
  6758. this.w = attribute.getW( index );
  6759. return this;
  6760. }
  6761. /**
  6762. * Sets each component of this vector to a pseudo-random value between `0` and
  6763. * `1`, excluding `1`.
  6764. *
  6765. * @return {Vector4} A reference to this vector.
  6766. */
  6767. random() {
  6768. this.x = Math.random();
  6769. this.y = Math.random();
  6770. this.z = Math.random();
  6771. this.w = Math.random();
  6772. return this;
  6773. }
  6774. *[ Symbol.iterator ]() {
  6775. yield this.x;
  6776. yield this.y;
  6777. yield this.z;
  6778. yield this.w;
  6779. }
  6780. }
  6781. /**
  6782. * A render target is a buffer where the video card draws pixels for a scene
  6783. * that is being rendered in the background. It is used in different effects,
  6784. * such as applying postprocessing to a rendered image before displaying it
  6785. * on the screen.
  6786. *
  6787. * @augments EventDispatcher
  6788. */
  6789. class RenderTarget extends EventDispatcher {
  6790. /**
  6791. * Render target options.
  6792. *
  6793. * @typedef {Object} RenderTarget~Options
  6794. * @property {boolean} [generateMipmaps=false] - Whether to generate mipmaps or not.
  6795. * @property {number} [magFilter=LinearFilter] - The mag filter.
  6796. * @property {number} [minFilter=LinearFilter] - The min filter.
  6797. * @property {number} [format=RGBAFormat] - The texture format.
  6798. * @property {number} [type=UnsignedByteType] - The texture type.
  6799. * @property {?string} [internalFormat=null] - The texture's internal format.
  6800. * @property {number} [wrapS=ClampToEdgeWrapping] - The texture's uv wrapping mode.
  6801. * @property {number} [wrapT=ClampToEdgeWrapping] - The texture's uv wrapping mode.
  6802. * @property {number} [anisotropy=1] - The texture's anisotropy value.
  6803. * @property {string} [colorSpace=NoColorSpace] - The texture's color space.
  6804. * @property {boolean} [depthBuffer=true] - Whether to allocate a depth buffer or not.
  6805. * @property {boolean} [stencilBuffer=false] - Whether to allocate a stencil buffer or not.
  6806. * @property {boolean} [resolveDepthBuffer=true] - Whether to resolve the depth buffer or not.
  6807. * @property {boolean} [resolveStencilBuffer=true] - Whether to resolve the stencil buffer or not.
  6808. * @property {?Texture} [depthTexture=null] - Reference to a depth texture.
  6809. * @property {number} [samples=0] - The MSAA samples count.
  6810. * @property {number} [count=1] - Defines the number of color attachments . Must be at least `1`.
  6811. * @property {number} [depth=1] - The texture depth.
  6812. * @property {boolean} [multiview=false] - Whether this target is used for multiview rendering.
  6813. */
  6814. /**
  6815. * Constructs a new render target.
  6816. *
  6817. * @param {number} [width=1] - The width of the render target.
  6818. * @param {number} [height=1] - The height of the render target.
  6819. * @param {RenderTarget~Options} [options] - The configuration object.
  6820. */
  6821. constructor( width = 1, height = 1, options = {} ) {
  6822. super();
  6823. options = Object.assign( {
  6824. generateMipmaps: false,
  6825. internalFormat: null,
  6826. minFilter: LinearFilter,
  6827. depthBuffer: true,
  6828. stencilBuffer: false,
  6829. resolveDepthBuffer: true,
  6830. resolveStencilBuffer: true,
  6831. depthTexture: null,
  6832. samples: 0,
  6833. count: 1,
  6834. depth: 1,
  6835. multiview: false
  6836. }, options );
  6837. /**
  6838. * This flag can be used for type testing.
  6839. *
  6840. * @type {boolean}
  6841. * @readonly
  6842. * @default true
  6843. */
  6844. this.isRenderTarget = true;
  6845. /**
  6846. * The width of the render target.
  6847. *
  6848. * @type {number}
  6849. * @default 1
  6850. */
  6851. this.width = width;
  6852. /**
  6853. * The height of the render target.
  6854. *
  6855. * @type {number}
  6856. * @default 1
  6857. */
  6858. this.height = height;
  6859. /**
  6860. * The depth of the render target.
  6861. *
  6862. * @type {number}
  6863. * @default 1
  6864. */
  6865. this.depth = options.depth;
  6866. /**
  6867. * A rectangular area inside the render target's viewport. Fragments that are
  6868. * outside the area will be discarded.
  6869. *
  6870. * @type {Vector4}
  6871. * @default (0,0,width,height)
  6872. */
  6873. this.scissor = new Vector4( 0, 0, width, height );
  6874. /**
  6875. * Indicates whether the scissor test should be enabled when rendering into
  6876. * this render target or not.
  6877. *
  6878. * @type {boolean}
  6879. * @default false
  6880. */
  6881. this.scissorTest = false;
  6882. /**
  6883. * A rectangular area representing the render target's viewport.
  6884. *
  6885. * @type {Vector4}
  6886. * @default (0,0,width,height)
  6887. */
  6888. this.viewport = new Vector4( 0, 0, width, height );
  6889. const image = { width: width, height: height, depth: options.depth };
  6890. const texture = new Texture( image );
  6891. /**
  6892. * An array of textures. Each color attachment is represented as a separate texture.
  6893. * Has at least a single entry for the default color attachment.
  6894. *
  6895. * @type {Array<Texture>}
  6896. */
  6897. this.textures = [];
  6898. const count = options.count;
  6899. for ( let i = 0; i < count; i ++ ) {
  6900. this.textures[ i ] = texture.clone();
  6901. this.textures[ i ].isRenderTargetTexture = true;
  6902. this.textures[ i ].renderTarget = this;
  6903. }
  6904. this._setTextureOptions( options );
  6905. /**
  6906. * Whether to allocate a depth buffer or not.
  6907. *
  6908. * @type {boolean}
  6909. * @default true
  6910. */
  6911. this.depthBuffer = options.depthBuffer;
  6912. /**
  6913. * Whether to allocate a stencil buffer or not.
  6914. *
  6915. * @type {boolean}
  6916. * @default false
  6917. */
  6918. this.stencilBuffer = options.stencilBuffer;
  6919. /**
  6920. * Whether to resolve the depth buffer or not.
  6921. *
  6922. * @type {boolean}
  6923. * @default true
  6924. */
  6925. this.resolveDepthBuffer = options.resolveDepthBuffer;
  6926. /**
  6927. * Whether to resolve the stencil buffer or not.
  6928. *
  6929. * @type {boolean}
  6930. * @default true
  6931. */
  6932. this.resolveStencilBuffer = options.resolveStencilBuffer;
  6933. this._depthTexture = null;
  6934. this.depthTexture = options.depthTexture;
  6935. /**
  6936. * The number of MSAA samples.
  6937. *
  6938. * A value of `0` disables MSAA.
  6939. *
  6940. * @type {number}
  6941. * @default 0
  6942. */
  6943. this.samples = options.samples;
  6944. /**
  6945. * Whether to this target is used in multiview rendering.
  6946. *
  6947. * @type {boolean}
  6948. * @default false
  6949. */
  6950. this.multiview = options.multiview;
  6951. }
  6952. _setTextureOptions( options = {} ) {
  6953. const values = {
  6954. minFilter: LinearFilter,
  6955. generateMipmaps: false,
  6956. flipY: false,
  6957. internalFormat: null
  6958. };
  6959. if ( options.mapping !== undefined ) values.mapping = options.mapping;
  6960. if ( options.wrapS !== undefined ) values.wrapS = options.wrapS;
  6961. if ( options.wrapT !== undefined ) values.wrapT = options.wrapT;
  6962. if ( options.wrapR !== undefined ) values.wrapR = options.wrapR;
  6963. if ( options.magFilter !== undefined ) values.magFilter = options.magFilter;
  6964. if ( options.minFilter !== undefined ) values.minFilter = options.minFilter;
  6965. if ( options.format !== undefined ) values.format = options.format;
  6966. if ( options.type !== undefined ) values.type = options.type;
  6967. if ( options.anisotropy !== undefined ) values.anisotropy = options.anisotropy;
  6968. if ( options.colorSpace !== undefined ) values.colorSpace = options.colorSpace;
  6969. if ( options.flipY !== undefined ) values.flipY = options.flipY;
  6970. if ( options.generateMipmaps !== undefined ) values.generateMipmaps = options.generateMipmaps;
  6971. if ( options.internalFormat !== undefined ) values.internalFormat = options.internalFormat;
  6972. for ( let i = 0; i < this.textures.length; i ++ ) {
  6973. const texture = this.textures[ i ];
  6974. texture.setValues( values );
  6975. }
  6976. }
  6977. /**
  6978. * The texture representing the default color attachment.
  6979. *
  6980. * @type {Texture}
  6981. */
  6982. get texture() {
  6983. return this.textures[ 0 ];
  6984. }
  6985. set texture( value ) {
  6986. this.textures[ 0 ] = value;
  6987. }
  6988. set depthTexture( current ) {
  6989. if ( this._depthTexture !== null ) this._depthTexture.renderTarget = null;
  6990. if ( current !== null ) current.renderTarget = this;
  6991. this._depthTexture = current;
  6992. }
  6993. /**
  6994. * Instead of saving the depth in a renderbuffer, a texture
  6995. * can be used instead which is useful for further processing
  6996. * e.g. in context of post-processing.
  6997. *
  6998. * @type {?DepthTexture}
  6999. * @default null
  7000. */
  7001. get depthTexture() {
  7002. return this._depthTexture;
  7003. }
  7004. /**
  7005. * Sets the size of this render target.
  7006. *
  7007. * @param {number} width - The width.
  7008. * @param {number} height - The height.
  7009. * @param {number} [depth=1] - The depth.
  7010. */
  7011. setSize( width, height, depth = 1 ) {
  7012. if ( this.width !== width || this.height !== height || this.depth !== depth ) {
  7013. this.width = width;
  7014. this.height = height;
  7015. this.depth = depth;
  7016. for ( let i = 0, il = this.textures.length; i < il; i ++ ) {
  7017. this.textures[ i ].image.width = width;
  7018. this.textures[ i ].image.height = height;
  7019. this.textures[ i ].image.depth = depth;
  7020. if ( this.textures[ i ].isData3DTexture !== true ) { // Fix for #31693
  7021. // TODO: Reconsider setting isArrayTexture flag here and in the ctor of Texture.
  7022. // Maybe a method `isArrayTexture()` or just a getter could replace a flag since
  7023. // both are evaluated on each call?
  7024. this.textures[ i ].isArrayTexture = this.textures[ i ].image.depth > 1;
  7025. }
  7026. }
  7027. this.dispose();
  7028. }
  7029. this.viewport.set( 0, 0, width, height );
  7030. this.scissor.set( 0, 0, width, height );
  7031. }
  7032. /**
  7033. * Returns a new render target with copied values from this instance.
  7034. *
  7035. * @return {RenderTarget} A clone of this instance.
  7036. */
  7037. clone() {
  7038. return new this.constructor().copy( this );
  7039. }
  7040. /**
  7041. * Copies the settings of the given render target. This is a structural copy so
  7042. * no resources are shared between render targets after the copy. That includes
  7043. * all MRT textures and the depth texture.
  7044. *
  7045. * @param {RenderTarget} source - The render target to copy.
  7046. * @return {RenderTarget} A reference to this instance.
  7047. */
  7048. copy( source ) {
  7049. this.width = source.width;
  7050. this.height = source.height;
  7051. this.depth = source.depth;
  7052. this.scissor.copy( source.scissor );
  7053. this.scissorTest = source.scissorTest;
  7054. this.viewport.copy( source.viewport );
  7055. this.textures.length = 0;
  7056. for ( let i = 0, il = source.textures.length; i < il; i ++ ) {
  7057. this.textures[ i ] = source.textures[ i ].clone();
  7058. this.textures[ i ].isRenderTargetTexture = true;
  7059. this.textures[ i ].renderTarget = this;
  7060. // ensure image object is not shared, see #20328
  7061. const image = Object.assign( {}, source.textures[ i ].image );
  7062. this.textures[ i ].source = new Source( image );
  7063. }
  7064. this.depthBuffer = source.depthBuffer;
  7065. this.stencilBuffer = source.stencilBuffer;
  7066. this.resolveDepthBuffer = source.resolveDepthBuffer;
  7067. this.resolveStencilBuffer = source.resolveStencilBuffer;
  7068. if ( source.depthTexture !== null ) this.depthTexture = source.depthTexture.clone();
  7069. this.samples = source.samples;
  7070. return this;
  7071. }
  7072. /**
  7073. * Frees the GPU-related resources allocated by this instance. Call this
  7074. * method whenever this instance is no longer used in your app.
  7075. *
  7076. * @fires RenderTarget#dispose
  7077. */
  7078. dispose() {
  7079. this.dispatchEvent( { type: 'dispose' } );
  7080. }
  7081. }
  7082. /**
  7083. * A render target used in context of {@link WebGLRenderer}.
  7084. *
  7085. * @augments RenderTarget
  7086. */
  7087. class WebGLRenderTarget extends RenderTarget {
  7088. /**
  7089. * Constructs a new 3D render target.
  7090. *
  7091. * @param {number} [width=1] - The width of the render target.
  7092. * @param {number} [height=1] - The height of the render target.
  7093. * @param {RenderTarget~Options} [options] - The configuration object.
  7094. */
  7095. constructor( width = 1, height = 1, options = {} ) {
  7096. super( width, height, options );
  7097. /**
  7098. * This flag can be used for type testing.
  7099. *
  7100. * @type {boolean}
  7101. * @readonly
  7102. * @default true
  7103. */
  7104. this.isWebGLRenderTarget = true;
  7105. }
  7106. }
  7107. /**
  7108. * Creates an array of textures directly from raw buffer data.
  7109. *
  7110. * @augments Texture
  7111. */
  7112. class DataArrayTexture extends Texture {
  7113. /**
  7114. * Constructs a new data array texture.
  7115. *
  7116. * @param {?TypedArray} [data=null] - The buffer data.
  7117. * @param {number} [width=1] - The width of the texture.
  7118. * @param {number} [height=1] - The height of the texture.
  7119. * @param {number} [depth=1] - The depth of the texture.
  7120. */
  7121. constructor( data = null, width = 1, height = 1, depth = 1 ) {
  7122. super( null );
  7123. /**
  7124. * This flag can be used for type testing.
  7125. *
  7126. * @type {boolean}
  7127. * @readonly
  7128. * @default true
  7129. */
  7130. this.isDataArrayTexture = true;
  7131. /**
  7132. * The image definition of a data texture.
  7133. *
  7134. * @type {{data:TypedArray,width:number,height:number,depth:number}}
  7135. */
  7136. this.image = { data, width, height, depth };
  7137. /**
  7138. * How the texture is sampled when a texel covers more than one pixel.
  7139. *
  7140. * Overwritten and set to `NearestFilter` by default.
  7141. *
  7142. * @type {(NearestFilter|NearestMipmapNearestFilter|NearestMipmapLinearFilter|LinearFilter|LinearMipmapNearestFilter|LinearMipmapLinearFilter)}
  7143. * @default NearestFilter
  7144. */
  7145. this.magFilter = NearestFilter;
  7146. /**
  7147. * How the texture is sampled when a texel covers less than one pixel.
  7148. *
  7149. * Overwritten and set to `NearestFilter` by default.
  7150. *
  7151. * @type {(NearestFilter|NearestMipmapNearestFilter|NearestMipmapLinearFilter|LinearFilter|LinearMipmapNearestFilter|LinearMipmapLinearFilter)}
  7152. * @default NearestFilter
  7153. */
  7154. this.minFilter = NearestFilter;
  7155. /**
  7156. * This defines how the texture is wrapped in the depth and corresponds to
  7157. * *W* in UVW mapping.
  7158. *
  7159. * @type {(RepeatWrapping|ClampToEdgeWrapping|MirroredRepeatWrapping)}
  7160. * @default ClampToEdgeWrapping
  7161. */
  7162. this.wrapR = ClampToEdgeWrapping;
  7163. /**
  7164. * Whether to generate mipmaps (if possible) for a texture.
  7165. *
  7166. * Overwritten and set to `false` by default.
  7167. *
  7168. * @type {boolean}
  7169. * @default false
  7170. */
  7171. this.generateMipmaps = false;
  7172. /**
  7173. * If set to `true`, the texture is flipped along the vertical axis when
  7174. * uploaded to the GPU.
  7175. *
  7176. * Overwritten and set to `false` by default.
  7177. *
  7178. * @type {boolean}
  7179. * @default false
  7180. */
  7181. this.flipY = false;
  7182. /**
  7183. * Specifies the alignment requirements for the start of each pixel row in memory.
  7184. *
  7185. * Overwritten and set to `1` by default.
  7186. *
  7187. * @type {boolean}
  7188. * @default 1
  7189. */
  7190. this.unpackAlignment = 1;
  7191. /**
  7192. * A set of all layers which need to be updated in the texture.
  7193. *
  7194. * @type {Set<number>}
  7195. */
  7196. this.layerUpdates = new Set();
  7197. }
  7198. /**
  7199. * Describes that a specific layer of the texture needs to be updated.
  7200. * Normally when {@link Texture#needsUpdate} is set to `true`, the
  7201. * entire data texture array is sent to the GPU. Marking specific
  7202. * layers will only transmit subsets of all mipmaps associated with a
  7203. * specific depth in the array which is often much more performant.
  7204. *
  7205. * @param {number} layerIndex - The layer index that should be updated.
  7206. */
  7207. addLayerUpdate( layerIndex ) {
  7208. this.layerUpdates.add( layerIndex );
  7209. }
  7210. /**
  7211. * Resets the layer updates registry.
  7212. */
  7213. clearLayerUpdates() {
  7214. this.layerUpdates.clear();
  7215. }
  7216. }
  7217. /**
  7218. * An array render target used in context of {@link WebGLRenderer}.
  7219. *
  7220. * @augments WebGLRenderTarget
  7221. */
  7222. class WebGLArrayRenderTarget extends WebGLRenderTarget {
  7223. /**
  7224. * Constructs a new array render target.
  7225. *
  7226. * @param {number} [width=1] - The width of the render target.
  7227. * @param {number} [height=1] - The height of the render target.
  7228. * @param {number} [depth=1] - The height of the render target.
  7229. * @param {RenderTarget~Options} [options] - The configuration object.
  7230. */
  7231. constructor( width = 1, height = 1, depth = 1, options = {} ) {
  7232. super( width, height, options );
  7233. /**
  7234. * This flag can be used for type testing.
  7235. *
  7236. * @type {boolean}
  7237. * @readonly
  7238. * @default true
  7239. */
  7240. this.isWebGLArrayRenderTarget = true;
  7241. this.depth = depth;
  7242. /**
  7243. * Overwritten with a different texture type.
  7244. *
  7245. * @type {DataArrayTexture}
  7246. */
  7247. this.texture = new DataArrayTexture( null, width, height, depth );
  7248. this._setTextureOptions( options );
  7249. this.texture.isRenderTargetTexture = true;
  7250. }
  7251. }
  7252. /**
  7253. * Creates a three-dimensional texture from raw data, with parameters to
  7254. * divide it into width, height, and depth.
  7255. *
  7256. * @augments Texture
  7257. */
  7258. class Data3DTexture extends Texture {
  7259. /**
  7260. * Constructs a new data array texture.
  7261. *
  7262. * @param {?TypedArray} [data=null] - The buffer data.
  7263. * @param {number} [width=1] - The width of the texture.
  7264. * @param {number} [height=1] - The height of the texture.
  7265. * @param {number} [depth=1] - The depth of the texture.
  7266. */
  7267. constructor( data = null, width = 1, height = 1, depth = 1 ) {
  7268. // We're going to add .setXXX() methods for setting properties later.
  7269. // Users can still set in Data3DTexture directly.
  7270. //
  7271. // const texture = new THREE.Data3DTexture( data, width, height, depth );
  7272. // texture.anisotropy = 16;
  7273. //
  7274. // See #14839
  7275. super( null );
  7276. /**
  7277. * This flag can be used for type testing.
  7278. *
  7279. * @type {boolean}
  7280. * @readonly
  7281. * @default true
  7282. */
  7283. this.isData3DTexture = true;
  7284. /**
  7285. * The image definition of a data texture.
  7286. *
  7287. * @type {{data:TypedArray,width:number,height:number,depth:number}}
  7288. */
  7289. this.image = { data, width, height, depth };
  7290. /**
  7291. * How the texture is sampled when a texel covers more than one pixel.
  7292. *
  7293. * Overwritten and set to `NearestFilter` by default.
  7294. *
  7295. * @type {(NearestFilter|NearestMipmapNearestFilter|NearestMipmapLinearFilter|LinearFilter|LinearMipmapNearestFilter|LinearMipmapLinearFilter)}
  7296. * @default NearestFilter
  7297. */
  7298. this.magFilter = NearestFilter;
  7299. /**
  7300. * How the texture is sampled when a texel covers less than one pixel.
  7301. *
  7302. * Overwritten and set to `NearestFilter` by default.
  7303. *
  7304. * @type {(NearestFilter|NearestMipmapNearestFilter|NearestMipmapLinearFilter|LinearFilter|LinearMipmapNearestFilter|LinearMipmapLinearFilter)}
  7305. * @default NearestFilter
  7306. */
  7307. this.minFilter = NearestFilter;
  7308. /**
  7309. * This defines how the texture is wrapped in the depth and corresponds to
  7310. * *W* in UVW mapping.
  7311. *
  7312. * @type {(RepeatWrapping|ClampToEdgeWrapping|MirroredRepeatWrapping)}
  7313. * @default ClampToEdgeWrapping
  7314. */
  7315. this.wrapR = ClampToEdgeWrapping;
  7316. /**
  7317. * Whether to generate mipmaps (if possible) for a texture.
  7318. *
  7319. * Overwritten and set to `false` by default.
  7320. *
  7321. * @type {boolean}
  7322. * @default false
  7323. */
  7324. this.generateMipmaps = false;
  7325. /**
  7326. * If set to `true`, the texture is flipped along the vertical axis when
  7327. * uploaded to the GPU.
  7328. *
  7329. * Overwritten and set to `false` by default.
  7330. *
  7331. * @type {boolean}
  7332. * @default false
  7333. */
  7334. this.flipY = false;
  7335. /**
  7336. * Specifies the alignment requirements for the start of each pixel row in memory.
  7337. *
  7338. * Overwritten and set to `1` by default.
  7339. *
  7340. * @type {boolean}
  7341. * @default 1
  7342. */
  7343. this.unpackAlignment = 1;
  7344. }
  7345. }
  7346. /**
  7347. * A 3D render target used in context of {@link WebGLRenderer}.
  7348. *
  7349. * @augments WebGLRenderTarget
  7350. */
  7351. class WebGL3DRenderTarget extends WebGLRenderTarget {
  7352. /**
  7353. * Constructs a new 3D render target.
  7354. *
  7355. * @param {number} [width=1] - The width of the render target.
  7356. * @param {number} [height=1] - The height of the render target.
  7357. * @param {number} [depth=1] - The height of the render target.
  7358. * @param {RenderTarget~Options} [options] - The configuration object.
  7359. */
  7360. constructor( width = 1, height = 1, depth = 1, options = {} ) {
  7361. super( width, height, options );
  7362. /**
  7363. * This flag can be used for type testing.
  7364. *
  7365. * @type {boolean}
  7366. * @readonly
  7367. * @default true
  7368. */
  7369. this.isWebGL3DRenderTarget = true;
  7370. this.depth = depth;
  7371. /**
  7372. * Overwritten with a different texture type.
  7373. *
  7374. * @type {Data3DTexture}
  7375. */
  7376. this.texture = new Data3DTexture( null, width, height, depth );
  7377. this._setTextureOptions( options );
  7378. this.texture.isRenderTargetTexture = true;
  7379. }
  7380. }
  7381. /**
  7382. * Represents an axis-aligned bounding box (AABB) in 3D space.
  7383. */
  7384. class Box3 {
  7385. /**
  7386. * Constructs a new bounding box.
  7387. *
  7388. * @param {Vector3} [min=(Infinity,Infinity,Infinity)] - A vector representing the lower boundary of the box.
  7389. * @param {Vector3} [max=(-Infinity,-Infinity,-Infinity)] - A vector representing the upper boundary of the box.
  7390. */
  7391. constructor( min = new Vector3( + Infinity, + Infinity, + Infinity ), max = new Vector3( - Infinity, - Infinity, - Infinity ) ) {
  7392. /**
  7393. * This flag can be used for type testing.
  7394. *
  7395. * @type {boolean}
  7396. * @readonly
  7397. * @default true
  7398. */
  7399. this.isBox3 = true;
  7400. /**
  7401. * The lower boundary of the box.
  7402. *
  7403. * @type {Vector3}
  7404. */
  7405. this.min = min;
  7406. /**
  7407. * The upper boundary of the box.
  7408. *
  7409. * @type {Vector3}
  7410. */
  7411. this.max = max;
  7412. }
  7413. /**
  7414. * Sets the lower and upper boundaries of this box.
  7415. * Please note that this method only copies the values from the given objects.
  7416. *
  7417. * @param {Vector3} min - The lower boundary of the box.
  7418. * @param {Vector3} max - The upper boundary of the box.
  7419. * @return {Box3} A reference to this bounding box.
  7420. */
  7421. set( min, max ) {
  7422. this.min.copy( min );
  7423. this.max.copy( max );
  7424. return this;
  7425. }
  7426. /**
  7427. * Sets the upper and lower bounds of this box so it encloses the position data
  7428. * in the given array.
  7429. *
  7430. * @param {Array<number>} array - An array holding 3D position data.
  7431. * @return {Box3} A reference to this bounding box.
  7432. */
  7433. setFromArray( array ) {
  7434. this.makeEmpty();
  7435. for ( let i = 0, il = array.length; i < il; i += 3 ) {
  7436. this.expandByPoint( _vector$b.fromArray( array, i ) );
  7437. }
  7438. return this;
  7439. }
  7440. /**
  7441. * Sets the upper and lower bounds of this box so it encloses the position data
  7442. * in the given buffer attribute.
  7443. *
  7444. * @param {BufferAttribute} attribute - A buffer attribute holding 3D position data.
  7445. * @return {Box3} A reference to this bounding box.
  7446. */
  7447. setFromBufferAttribute( attribute ) {
  7448. this.makeEmpty();
  7449. for ( let i = 0, il = attribute.count; i < il; i ++ ) {
  7450. this.expandByPoint( _vector$b.fromBufferAttribute( attribute, i ) );
  7451. }
  7452. return this;
  7453. }
  7454. /**
  7455. * Sets the upper and lower bounds of this box so it encloses the position data
  7456. * in the given array.
  7457. *
  7458. * @param {Array<Vector3>} points - An array holding 3D position data as instances of {@link Vector3}.
  7459. * @return {Box3} A reference to this bounding box.
  7460. */
  7461. setFromPoints( points ) {
  7462. this.makeEmpty();
  7463. for ( let i = 0, il = points.length; i < il; i ++ ) {
  7464. this.expandByPoint( points[ i ] );
  7465. }
  7466. return this;
  7467. }
  7468. /**
  7469. * Centers this box on the given center vector and sets this box's width, height and
  7470. * depth to the given size values.
  7471. *
  7472. * @param {Vector3} center - The center of the box.
  7473. * @param {Vector3} size - The x, y and z dimensions of the box.
  7474. * @return {Box3} A reference to this bounding box.
  7475. */
  7476. setFromCenterAndSize( center, size ) {
  7477. const halfSize = _vector$b.copy( size ).multiplyScalar( 0.5 );
  7478. this.min.copy( center ).sub( halfSize );
  7479. this.max.copy( center ).add( halfSize );
  7480. return this;
  7481. }
  7482. /**
  7483. * Computes the world-axis-aligned bounding box for the given 3D object
  7484. * (including its children), accounting for the object's, and children's,
  7485. * world transforms. The function may result in a larger box than strictly necessary.
  7486. *
  7487. * @param {Object3D} object - The 3D object to compute the bounding box for.
  7488. * @param {boolean} [precise=false] - If set to `true`, the method computes the smallest
  7489. * world-axis-aligned bounding box at the expense of more computation.
  7490. * @return {Box3} A reference to this bounding box.
  7491. */
  7492. setFromObject( object, precise = false ) {
  7493. this.makeEmpty();
  7494. return this.expandByObject( object, precise );
  7495. }
  7496. /**
  7497. * Returns a new box with copied values from this instance.
  7498. *
  7499. * @return {Box3} A clone of this instance.
  7500. */
  7501. clone() {
  7502. return new this.constructor().copy( this );
  7503. }
  7504. /**
  7505. * Copies the values of the given box to this instance.
  7506. *
  7507. * @param {Box3} box - The box to copy.
  7508. * @return {Box3} A reference to this bounding box.
  7509. */
  7510. copy( box ) {
  7511. this.min.copy( box.min );
  7512. this.max.copy( box.max );
  7513. return this;
  7514. }
  7515. /**
  7516. * Makes this box empty which means in encloses a zero space in 3D.
  7517. *
  7518. * @return {Box3} A reference to this bounding box.
  7519. */
  7520. makeEmpty() {
  7521. this.min.x = this.min.y = this.min.z = + Infinity;
  7522. this.max.x = this.max.y = this.max.z = - Infinity;
  7523. return this;
  7524. }
  7525. /**
  7526. * Returns true if this box includes zero points within its bounds.
  7527. * Note that a box with equal lower and upper bounds still includes one
  7528. * point, the one both bounds share.
  7529. *
  7530. * @return {boolean} Whether this box is empty or not.
  7531. */
  7532. isEmpty() {
  7533. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  7534. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y ) || ( this.max.z < this.min.z );
  7535. }
  7536. /**
  7537. * Returns the center point of this box.
  7538. *
  7539. * @param {Vector3} target - The target vector that is used to store the method's result.
  7540. * @return {Vector3} The center point.
  7541. */
  7542. getCenter( target ) {
  7543. return this.isEmpty() ? target.set( 0, 0, 0 ) : target.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  7544. }
  7545. /**
  7546. * Returns the dimensions of this box.
  7547. *
  7548. * @param {Vector3} target - The target vector that is used to store the method's result.
  7549. * @return {Vector3} The size.
  7550. */
  7551. getSize( target ) {
  7552. return this.isEmpty() ? target.set( 0, 0, 0 ) : target.subVectors( this.max, this.min );
  7553. }
  7554. /**
  7555. * Expands the boundaries of this box to include the given point.
  7556. *
  7557. * @param {Vector3} point - The point that should be included by the bounding box.
  7558. * @return {Box3} A reference to this bounding box.
  7559. */
  7560. expandByPoint( point ) {
  7561. this.min.min( point );
  7562. this.max.max( point );
  7563. return this;
  7564. }
  7565. /**
  7566. * Expands this box equilaterally by the given vector. The width of this
  7567. * box will be expanded by the x component of the vector in both
  7568. * directions. The height of this box will be expanded by the y component of
  7569. * the vector in both directions. The depth of this box will be
  7570. * expanded by the z component of the vector in both directions.
  7571. *
  7572. * @param {Vector3} vector - The vector that should expand the bounding box.
  7573. * @return {Box3} A reference to this bounding box.
  7574. */
  7575. expandByVector( vector ) {
  7576. this.min.sub( vector );
  7577. this.max.add( vector );
  7578. return this;
  7579. }
  7580. /**
  7581. * Expands each dimension of the box by the given scalar. If negative, the
  7582. * dimensions of the box will be contracted.
  7583. *
  7584. * @param {number} scalar - The scalar value that should expand the bounding box.
  7585. * @return {Box3} A reference to this bounding box.
  7586. */
  7587. expandByScalar( scalar ) {
  7588. this.min.addScalar( - scalar );
  7589. this.max.addScalar( scalar );
  7590. return this;
  7591. }
  7592. /**
  7593. * Expands the boundaries of this box to include the given 3D object and
  7594. * its children, accounting for the object's, and children's, world
  7595. * transforms. The function may result in a larger box than strictly
  7596. * necessary (unless the precise parameter is set to true).
  7597. *
  7598. * @param {Object3D} object - The 3D object that should expand the bounding box.
  7599. * @param {boolean} precise - If set to `true`, the method expands the bounding box
  7600. * as little as necessary at the expense of more computation.
  7601. * @return {Box3} A reference to this bounding box.
  7602. */
  7603. expandByObject( object, precise = false ) {
  7604. // Computes the world-axis-aligned bounding box of an object (including its children),
  7605. // accounting for both the object's, and children's, world transforms
  7606. object.updateWorldMatrix( false, false );
  7607. const geometry = object.geometry;
  7608. if ( geometry !== undefined ) {
  7609. const positionAttribute = geometry.getAttribute( 'position' );
  7610. // precise AABB computation based on vertex data requires at least a position attribute.
  7611. // instancing isn't supported so far and uses the normal (conservative) code path.
  7612. if ( precise === true && positionAttribute !== undefined && object.isInstancedMesh !== true ) {
  7613. for ( let i = 0, l = positionAttribute.count; i < l; i ++ ) {
  7614. if ( object.isMesh === true ) {
  7615. object.getVertexPosition( i, _vector$b );
  7616. } else {
  7617. _vector$b.fromBufferAttribute( positionAttribute, i );
  7618. }
  7619. _vector$b.applyMatrix4( object.matrixWorld );
  7620. this.expandByPoint( _vector$b );
  7621. }
  7622. } else {
  7623. if ( object.boundingBox !== undefined ) {
  7624. // object-level bounding box
  7625. if ( object.boundingBox === null ) {
  7626. object.computeBoundingBox();
  7627. }
  7628. _box$4.copy( object.boundingBox );
  7629. } else {
  7630. // geometry-level bounding box
  7631. if ( geometry.boundingBox === null ) {
  7632. geometry.computeBoundingBox();
  7633. }
  7634. _box$4.copy( geometry.boundingBox );
  7635. }
  7636. _box$4.applyMatrix4( object.matrixWorld );
  7637. this.union( _box$4 );
  7638. }
  7639. }
  7640. const children = object.children;
  7641. for ( let i = 0, l = children.length; i < l; i ++ ) {
  7642. this.expandByObject( children[ i ], precise );
  7643. }
  7644. return this;
  7645. }
  7646. /**
  7647. * Returns `true` if the given point lies within or on the boundaries of this box.
  7648. *
  7649. * @param {Vector3} point - The point to test.
  7650. * @return {boolean} Whether the bounding box contains the given point or not.
  7651. */
  7652. containsPoint( point ) {
  7653. return point.x >= this.min.x && point.x <= this.max.x &&
  7654. point.y >= this.min.y && point.y <= this.max.y &&
  7655. point.z >= this.min.z && point.z <= this.max.z;
  7656. }
  7657. /**
  7658. * Returns `true` if this bounding box includes the entirety of the given bounding box.
  7659. * If this box and the given one are identical, this function also returns `true`.
  7660. *
  7661. * @param {Box3} box - The bounding box to test.
  7662. * @return {boolean} Whether the bounding box contains the given bounding box or not.
  7663. */
  7664. containsBox( box ) {
  7665. return this.min.x <= box.min.x && box.max.x <= this.max.x &&
  7666. this.min.y <= box.min.y && box.max.y <= this.max.y &&
  7667. this.min.z <= box.min.z && box.max.z <= this.max.z;
  7668. }
  7669. /**
  7670. * Returns a point as a proportion of this box's width, height and depth.
  7671. *
  7672. * @param {Vector3} point - A point in 3D space.
  7673. * @param {Vector3} target - The target vector that is used to store the method's result.
  7674. * @return {Vector3} A point as a proportion of this box's width, height and depth.
  7675. */
  7676. getParameter( point, target ) {
  7677. // This can potentially have a divide by zero if the box
  7678. // has a size dimension of 0.
  7679. return target.set(
  7680. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  7681. ( point.y - this.min.y ) / ( this.max.y - this.min.y ),
  7682. ( point.z - this.min.z ) / ( this.max.z - this.min.z )
  7683. );
  7684. }
  7685. /**
  7686. * Returns `true` if the given bounding box intersects with this bounding box.
  7687. *
  7688. * @param {Box3} box - The bounding box to test.
  7689. * @return {boolean} Whether the given bounding box intersects with this bounding box.
  7690. */
  7691. intersectsBox( box ) {
  7692. // using 6 splitting planes to rule out intersections.
  7693. return box.max.x >= this.min.x && box.min.x <= this.max.x &&
  7694. box.max.y >= this.min.y && box.min.y <= this.max.y &&
  7695. box.max.z >= this.min.z && box.min.z <= this.max.z;
  7696. }
  7697. /**
  7698. * Returns `true` if the given bounding sphere intersects with this bounding box.
  7699. *
  7700. * @param {Sphere} sphere - The bounding sphere to test.
  7701. * @return {boolean} Whether the given bounding sphere intersects with this bounding box.
  7702. */
  7703. intersectsSphere( sphere ) {
  7704. // Find the point on the AABB closest to the sphere center.
  7705. this.clampPoint( sphere.center, _vector$b );
  7706. // If that point is inside the sphere, the AABB and sphere intersect.
  7707. return _vector$b.distanceToSquared( sphere.center ) <= ( sphere.radius * sphere.radius );
  7708. }
  7709. /**
  7710. * Returns `true` if the given plane intersects with this bounding box.
  7711. *
  7712. * @param {Plane} plane - The plane to test.
  7713. * @return {boolean} Whether the given plane intersects with this bounding box.
  7714. */
  7715. intersectsPlane( plane ) {
  7716. // We compute the minimum and maximum dot product values. If those values
  7717. // are on the same side (back or front) of the plane, then there is no intersection.
  7718. let min, max;
  7719. if ( plane.normal.x > 0 ) {
  7720. min = plane.normal.x * this.min.x;
  7721. max = plane.normal.x * this.max.x;
  7722. } else {
  7723. min = plane.normal.x * this.max.x;
  7724. max = plane.normal.x * this.min.x;
  7725. }
  7726. if ( plane.normal.y > 0 ) {
  7727. min += plane.normal.y * this.min.y;
  7728. max += plane.normal.y * this.max.y;
  7729. } else {
  7730. min += plane.normal.y * this.max.y;
  7731. max += plane.normal.y * this.min.y;
  7732. }
  7733. if ( plane.normal.z > 0 ) {
  7734. min += plane.normal.z * this.min.z;
  7735. max += plane.normal.z * this.max.z;
  7736. } else {
  7737. min += plane.normal.z * this.max.z;
  7738. max += plane.normal.z * this.min.z;
  7739. }
  7740. return ( min <= - plane.constant && max >= - plane.constant );
  7741. }
  7742. /**
  7743. * Returns `true` if the given triangle intersects with this bounding box.
  7744. *
  7745. * @param {Triangle} triangle - The triangle to test.
  7746. * @return {boolean} Whether the given triangle intersects with this bounding box.
  7747. */
  7748. intersectsTriangle( triangle ) {
  7749. if ( this.isEmpty() ) {
  7750. return false;
  7751. }
  7752. // compute box center and extents
  7753. this.getCenter( _center );
  7754. _extents.subVectors( this.max, _center );
  7755. // translate triangle to aabb origin
  7756. _v0$2.subVectors( triangle.a, _center );
  7757. _v1$7.subVectors( triangle.b, _center );
  7758. _v2$4.subVectors( triangle.c, _center );
  7759. // compute edge vectors for triangle
  7760. _f0.subVectors( _v1$7, _v0$2 );
  7761. _f1.subVectors( _v2$4, _v1$7 );
  7762. _f2.subVectors( _v0$2, _v2$4 );
  7763. // test against axes that are given by cross product combinations of the edges of the triangle and the edges of the aabb
  7764. // 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
  7765. // axis_ij = u_i x f_j (u0, u1, u2 = face normals of aabb = x,y,z axes vectors since aabb is axis aligned)
  7766. let axes = [
  7767. 0, - _f0.z, _f0.y, 0, - _f1.z, _f1.y, 0, - _f2.z, _f2.y,
  7768. _f0.z, 0, - _f0.x, _f1.z, 0, - _f1.x, _f2.z, 0, - _f2.x,
  7769. - _f0.y, _f0.x, 0, - _f1.y, _f1.x, 0, - _f2.y, _f2.x, 0
  7770. ];
  7771. if ( ! satForAxes( axes, _v0$2, _v1$7, _v2$4, _extents ) ) {
  7772. return false;
  7773. }
  7774. // test 3 face normals from the aabb
  7775. axes = [ 1, 0, 0, 0, 1, 0, 0, 0, 1 ];
  7776. if ( ! satForAxes( axes, _v0$2, _v1$7, _v2$4, _extents ) ) {
  7777. return false;
  7778. }
  7779. // finally testing the face normal of the triangle
  7780. // use already existing triangle edge vectors here
  7781. _triangleNormal.crossVectors( _f0, _f1 );
  7782. axes = [ _triangleNormal.x, _triangleNormal.y, _triangleNormal.z ];
  7783. return satForAxes( axes, _v0$2, _v1$7, _v2$4, _extents );
  7784. }
  7785. /**
  7786. * Clamps the given point within the bounds of this box.
  7787. *
  7788. * @param {Vector3} point - The point to clamp.
  7789. * @param {Vector3} target - The target vector that is used to store the method's result.
  7790. * @return {Vector3} The clamped point.
  7791. */
  7792. clampPoint( point, target ) {
  7793. return target.copy( point ).clamp( this.min, this.max );
  7794. }
  7795. /**
  7796. * Returns the euclidean distance from any edge of this box to the specified point. If
  7797. * the given point lies inside of this box, the distance will be `0`.
  7798. *
  7799. * @param {Vector3} point - The point to compute the distance to.
  7800. * @return {number} The euclidean distance.
  7801. */
  7802. distanceToPoint( point ) {
  7803. return this.clampPoint( point, _vector$b ).distanceTo( point );
  7804. }
  7805. /**
  7806. * Returns a bounding sphere that encloses this bounding box.
  7807. *
  7808. * @param {Sphere} target - The target sphere that is used to store the method's result.
  7809. * @return {Sphere} The bounding sphere that encloses this bounding box.
  7810. */
  7811. getBoundingSphere( target ) {
  7812. if ( this.isEmpty() ) {
  7813. target.makeEmpty();
  7814. } else {
  7815. this.getCenter( target.center );
  7816. target.radius = this.getSize( _vector$b ).length() * 0.5;
  7817. }
  7818. return target;
  7819. }
  7820. /**
  7821. * Computes the intersection of this bounding box and the given one, setting the upper
  7822. * bound of this box to the lesser of the two boxes' upper bounds and the
  7823. * lower bound of this box to the greater of the two boxes' lower bounds. If
  7824. * there's no overlap, makes this box empty.
  7825. *
  7826. * @param {Box3} box - The bounding box to intersect with.
  7827. * @return {Box3} A reference to this bounding box.
  7828. */
  7829. intersect( box ) {
  7830. this.min.max( box.min );
  7831. this.max.min( box.max );
  7832. // 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.
  7833. if ( this.isEmpty() ) this.makeEmpty();
  7834. return this;
  7835. }
  7836. /**
  7837. * Computes the union of this box and another and the given one, setting the upper
  7838. * bound of this box to the greater of the two boxes' upper bounds and the
  7839. * lower bound of this box to the lesser of the two boxes' lower bounds.
  7840. *
  7841. * @param {Box3} box - The bounding box that will be unioned with this instance.
  7842. * @return {Box3} A reference to this bounding box.
  7843. */
  7844. union( box ) {
  7845. this.min.min( box.min );
  7846. this.max.max( box.max );
  7847. return this;
  7848. }
  7849. /**
  7850. * Transforms this bounding box by the given 4x4 transformation matrix.
  7851. *
  7852. * @param {Matrix4} matrix - The transformation matrix.
  7853. * @return {Box3} A reference to this bounding box.
  7854. */
  7855. applyMatrix4( matrix ) {
  7856. // transform of empty box is an empty box.
  7857. if ( this.isEmpty() ) return this;
  7858. // NOTE: I am using a binary pattern to specify all 2^3 combinations below
  7859. _points[ 0 ].set( this.min.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 000
  7860. _points[ 1 ].set( this.min.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 001
  7861. _points[ 2 ].set( this.min.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 010
  7862. _points[ 3 ].set( this.min.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 011
  7863. _points[ 4 ].set( this.max.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 100
  7864. _points[ 5 ].set( this.max.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 101
  7865. _points[ 6 ].set( this.max.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 110
  7866. _points[ 7 ].set( this.max.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 111
  7867. this.setFromPoints( _points );
  7868. return this;
  7869. }
  7870. /**
  7871. * Adds the given offset to both the upper and lower bounds of this bounding box,
  7872. * effectively moving it in 3D space.
  7873. *
  7874. * @param {Vector3} offset - The offset that should be used to translate the bounding box.
  7875. * @return {Box3} A reference to this bounding box.
  7876. */
  7877. translate( offset ) {
  7878. this.min.add( offset );
  7879. this.max.add( offset );
  7880. return this;
  7881. }
  7882. /**
  7883. * Returns `true` if this bounding box is equal with the given one.
  7884. *
  7885. * @param {Box3} box - The box to test for equality.
  7886. * @return {boolean} Whether this bounding box is equal with the given one.
  7887. */
  7888. equals( box ) {
  7889. return box.min.equals( this.min ) && box.max.equals( this.max );
  7890. }
  7891. /**
  7892. * Returns a serialized structure of the bounding box.
  7893. *
  7894. * @return {Object} Serialized structure with fields representing the object state.
  7895. */
  7896. toJSON() {
  7897. return {
  7898. min: this.min.toArray(),
  7899. max: this.max.toArray()
  7900. };
  7901. }
  7902. /**
  7903. * Returns a serialized structure of the bounding box.
  7904. *
  7905. * @param {Object} json - The serialized json to set the box from.
  7906. * @return {Box3} A reference to this bounding box.
  7907. */
  7908. fromJSON( json ) {
  7909. this.min.fromArray( json.min );
  7910. this.max.fromArray( json.max );
  7911. return this;
  7912. }
  7913. }
  7914. const _points = [
  7915. /*@__PURE__*/ new Vector3(),
  7916. /*@__PURE__*/ new Vector3(),
  7917. /*@__PURE__*/ new Vector3(),
  7918. /*@__PURE__*/ new Vector3(),
  7919. /*@__PURE__*/ new Vector3(),
  7920. /*@__PURE__*/ new Vector3(),
  7921. /*@__PURE__*/ new Vector3(),
  7922. /*@__PURE__*/ new Vector3()
  7923. ];
  7924. const _vector$b = /*@__PURE__*/ new Vector3();
  7925. const _box$4 = /*@__PURE__*/ new Box3();
  7926. // triangle centered vertices
  7927. const _v0$2 = /*@__PURE__*/ new Vector3();
  7928. const _v1$7 = /*@__PURE__*/ new Vector3();
  7929. const _v2$4 = /*@__PURE__*/ new Vector3();
  7930. // triangle edge vectors
  7931. const _f0 = /*@__PURE__*/ new Vector3();
  7932. const _f1 = /*@__PURE__*/ new Vector3();
  7933. const _f2 = /*@__PURE__*/ new Vector3();
  7934. const _center = /*@__PURE__*/ new Vector3();
  7935. const _extents = /*@__PURE__*/ new Vector3();
  7936. const _triangleNormal = /*@__PURE__*/ new Vector3();
  7937. const _testAxis = /*@__PURE__*/ new Vector3();
  7938. function satForAxes( axes, v0, v1, v2, extents ) {
  7939. for ( let i = 0, j = axes.length - 3; i <= j; i += 3 ) {
  7940. _testAxis.fromArray( axes, i );
  7941. // project the aabb onto the separating axis
  7942. const r = extents.x * Math.abs( _testAxis.x ) + extents.y * Math.abs( _testAxis.y ) + extents.z * Math.abs( _testAxis.z );
  7943. // project all 3 vertices of the triangle onto the separating axis
  7944. const p0 = v0.dot( _testAxis );
  7945. const p1 = v1.dot( _testAxis );
  7946. const p2 = v2.dot( _testAxis );
  7947. // actual test, basically see if either of the most extreme of the triangle points intersects r
  7948. if ( Math.max( - Math.max( p0, p1, p2 ), Math.min( p0, p1, p2 ) ) > r ) {
  7949. // points of the projected triangle are outside the projected half-length of the aabb
  7950. // the axis is separating and we can exit
  7951. return false;
  7952. }
  7953. }
  7954. return true;
  7955. }
  7956. const _box$3 = /*@__PURE__*/ new Box3();
  7957. const _v1$6 = /*@__PURE__*/ new Vector3();
  7958. const _v2$3 = /*@__PURE__*/ new Vector3();
  7959. /**
  7960. * An analytical 3D sphere defined by a center and radius. This class is mainly
  7961. * used as a Bounding Sphere for 3D objects.
  7962. */
  7963. class Sphere {
  7964. /**
  7965. * Constructs a new sphere.
  7966. *
  7967. * @param {Vector3} [center=(0,0,0)] - The center of the sphere
  7968. * @param {number} [radius=-1] - The radius of the sphere.
  7969. */
  7970. constructor( center = new Vector3(), radius = -1 ) {
  7971. /**
  7972. * This flag can be used for type testing.
  7973. *
  7974. * @type {boolean}
  7975. * @readonly
  7976. * @default true
  7977. */
  7978. this.isSphere = true;
  7979. /**
  7980. * The center of the sphere
  7981. *
  7982. * @type {Vector3}
  7983. */
  7984. this.center = center;
  7985. /**
  7986. * The radius of the sphere.
  7987. *
  7988. * @type {number}
  7989. */
  7990. this.radius = radius;
  7991. }
  7992. /**
  7993. * Sets the sphere's components by copying the given values.
  7994. *
  7995. * @param {Vector3} center - The center.
  7996. * @param {number} radius - The radius.
  7997. * @return {Sphere} A reference to this sphere.
  7998. */
  7999. set( center, radius ) {
  8000. this.center.copy( center );
  8001. this.radius = radius;
  8002. return this;
  8003. }
  8004. /**
  8005. * Computes the minimum bounding sphere for list of points.
  8006. * If the optional center point is given, it is used as the sphere's
  8007. * center. Otherwise, the center of the axis-aligned bounding box
  8008. * encompassing the points is calculated.
  8009. *
  8010. * @param {Array<Vector3>} points - A list of points in 3D space.
  8011. * @param {Vector3} [optionalCenter] - The center of the sphere.
  8012. * @return {Sphere} A reference to this sphere.
  8013. */
  8014. setFromPoints( points, optionalCenter ) {
  8015. const center = this.center;
  8016. if ( optionalCenter !== undefined ) {
  8017. center.copy( optionalCenter );
  8018. } else {
  8019. _box$3.setFromPoints( points ).getCenter( center );
  8020. }
  8021. let maxRadiusSq = 0;
  8022. for ( let i = 0, il = points.length; i < il; i ++ ) {
  8023. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( points[ i ] ) );
  8024. }
  8025. this.radius = Math.sqrt( maxRadiusSq );
  8026. return this;
  8027. }
  8028. /**
  8029. * Copies the values of the given sphere to this instance.
  8030. *
  8031. * @param {Sphere} sphere - The sphere to copy.
  8032. * @return {Sphere} A reference to this sphere.
  8033. */
  8034. copy( sphere ) {
  8035. this.center.copy( sphere.center );
  8036. this.radius = sphere.radius;
  8037. return this;
  8038. }
  8039. /**
  8040. * Returns `true` if the sphere is empty (the radius set to a negative number).
  8041. *
  8042. * Spheres with a radius of `0` contain only their center point and are not
  8043. * considered to be empty.
  8044. *
  8045. * @return {boolean} Whether this sphere is empty or not.
  8046. */
  8047. isEmpty() {
  8048. return ( this.radius < 0 );
  8049. }
  8050. /**
  8051. * Makes this sphere empty which means in encloses a zero space in 3D.
  8052. *
  8053. * @return {Sphere} A reference to this sphere.
  8054. */
  8055. makeEmpty() {
  8056. this.center.set( 0, 0, 0 );
  8057. this.radius = -1;
  8058. return this;
  8059. }
  8060. /**
  8061. * Returns `true` if this sphere contains the given point inclusive of
  8062. * the surface of the sphere.
  8063. *
  8064. * @param {Vector3} point - The point to check.
  8065. * @return {boolean} Whether this sphere contains the given point or not.
  8066. */
  8067. containsPoint( point ) {
  8068. return ( point.distanceToSquared( this.center ) <= ( this.radius * this.radius ) );
  8069. }
  8070. /**
  8071. * Returns the closest distance from the boundary of the sphere to the
  8072. * given point. If the sphere contains the point, the distance will
  8073. * be negative.
  8074. *
  8075. * @param {Vector3} point - The point to compute the distance to.
  8076. * @return {number} The distance to the point.
  8077. */
  8078. distanceToPoint( point ) {
  8079. return ( point.distanceTo( this.center ) - this.radius );
  8080. }
  8081. /**
  8082. * Returns `true` if this sphere intersects with the given one.
  8083. *
  8084. * @param {Sphere} sphere - The sphere to test.
  8085. * @return {boolean} Whether this sphere intersects with the given one or not.
  8086. */
  8087. intersectsSphere( sphere ) {
  8088. const radiusSum = this.radius + sphere.radius;
  8089. return sphere.center.distanceToSquared( this.center ) <= ( radiusSum * radiusSum );
  8090. }
  8091. /**
  8092. * Returns `true` if this sphere intersects with the given box.
  8093. *
  8094. * @param {Box3} box - The box to test.
  8095. * @return {boolean} Whether this sphere intersects with the given box or not.
  8096. */
  8097. intersectsBox( box ) {
  8098. return box.intersectsSphere( this );
  8099. }
  8100. /**
  8101. * Returns `true` if this sphere intersects with the given plane.
  8102. *
  8103. * @param {Plane} plane - The plane to test.
  8104. * @return {boolean} Whether this sphere intersects with the given plane or not.
  8105. */
  8106. intersectsPlane( plane ) {
  8107. return Math.abs( plane.distanceToPoint( this.center ) ) <= this.radius;
  8108. }
  8109. /**
  8110. * Clamps a point within the sphere. If the point is outside the sphere, it
  8111. * will clamp it to the closest point on the edge of the sphere. Points
  8112. * already inside the sphere will not be affected.
  8113. *
  8114. * @param {Vector3} point - The plane to clamp.
  8115. * @param {Vector3} target - The target vector that is used to store the method's result.
  8116. * @return {Vector3} The clamped point.
  8117. */
  8118. clampPoint( point, target ) {
  8119. const deltaLengthSq = this.center.distanceToSquared( point );
  8120. target.copy( point );
  8121. if ( deltaLengthSq > ( this.radius * this.radius ) ) {
  8122. target.sub( this.center ).normalize();
  8123. target.multiplyScalar( this.radius ).add( this.center );
  8124. }
  8125. return target;
  8126. }
  8127. /**
  8128. * Returns a bounding box that encloses this sphere.
  8129. *
  8130. * @param {Box3} target - The target box that is used to store the method's result.
  8131. * @return {Box3} The bounding box that encloses this sphere.
  8132. */
  8133. getBoundingBox( target ) {
  8134. if ( this.isEmpty() ) {
  8135. // Empty sphere produces empty bounding box
  8136. target.makeEmpty();
  8137. return target;
  8138. }
  8139. target.set( this.center, this.center );
  8140. target.expandByScalar( this.radius );
  8141. return target;
  8142. }
  8143. /**
  8144. * Transforms this sphere with the given 4x4 transformation matrix.
  8145. *
  8146. * @param {Matrix4} matrix - The transformation matrix.
  8147. * @return {Sphere} A reference to this sphere.
  8148. */
  8149. applyMatrix4( matrix ) {
  8150. this.center.applyMatrix4( matrix );
  8151. this.radius = this.radius * matrix.getMaxScaleOnAxis();
  8152. return this;
  8153. }
  8154. /**
  8155. * Translates the sphere's center by the given offset.
  8156. *
  8157. * @param {Vector3} offset - The offset.
  8158. * @return {Sphere} A reference to this sphere.
  8159. */
  8160. translate( offset ) {
  8161. this.center.add( offset );
  8162. return this;
  8163. }
  8164. /**
  8165. * Expands the boundaries of this sphere to include the given point.
  8166. *
  8167. * @param {Vector3} point - The point to include.
  8168. * @return {Sphere} A reference to this sphere.
  8169. */
  8170. expandByPoint( point ) {
  8171. if ( this.isEmpty() ) {
  8172. this.center.copy( point );
  8173. this.radius = 0;
  8174. return this;
  8175. }
  8176. _v1$6.subVectors( point, this.center );
  8177. const lengthSq = _v1$6.lengthSq();
  8178. if ( lengthSq > ( this.radius * this.radius ) ) {
  8179. // calculate the minimal sphere
  8180. const length = Math.sqrt( lengthSq );
  8181. const delta = ( length - this.radius ) * 0.5;
  8182. this.center.addScaledVector( _v1$6, delta / length );
  8183. this.radius += delta;
  8184. }
  8185. return this;
  8186. }
  8187. /**
  8188. * Expands this sphere to enclose both the original sphere and the given sphere.
  8189. *
  8190. * @param {Sphere} sphere - The sphere to include.
  8191. * @return {Sphere} A reference to this sphere.
  8192. */
  8193. union( sphere ) {
  8194. if ( sphere.isEmpty() ) {
  8195. return this;
  8196. }
  8197. if ( this.isEmpty() ) {
  8198. this.copy( sphere );
  8199. return this;
  8200. }
  8201. if ( this.center.equals( sphere.center ) === true ) {
  8202. this.radius = Math.max( this.radius, sphere.radius );
  8203. } else {
  8204. _v2$3.subVectors( sphere.center, this.center ).setLength( sphere.radius );
  8205. this.expandByPoint( _v1$6.copy( sphere.center ).add( _v2$3 ) );
  8206. this.expandByPoint( _v1$6.copy( sphere.center ).sub( _v2$3 ) );
  8207. }
  8208. return this;
  8209. }
  8210. /**
  8211. * Returns `true` if this sphere is equal with the given one.
  8212. *
  8213. * @param {Sphere} sphere - The sphere to test for equality.
  8214. * @return {boolean} Whether this bounding sphere is equal with the given one.
  8215. */
  8216. equals( sphere ) {
  8217. return sphere.center.equals( this.center ) && ( sphere.radius === this.radius );
  8218. }
  8219. /**
  8220. * Returns a new sphere with copied values from this instance.
  8221. *
  8222. * @return {Sphere} A clone of this instance.
  8223. */
  8224. clone() {
  8225. return new this.constructor().copy( this );
  8226. }
  8227. /**
  8228. * Returns a serialized structure of the bounding sphere.
  8229. *
  8230. * @return {Object} Serialized structure with fields representing the object state.
  8231. */
  8232. toJSON() {
  8233. return {
  8234. radius: this.radius,
  8235. center: this.center.toArray()
  8236. };
  8237. }
  8238. /**
  8239. * Returns a serialized structure of the bounding sphere.
  8240. *
  8241. * @param {Object} json - The serialized json to set the sphere from.
  8242. * @return {Sphere} A reference to this bounding sphere.
  8243. */
  8244. fromJSON( json ) {
  8245. this.radius = json.radius;
  8246. this.center.fromArray( json.center );
  8247. return this;
  8248. }
  8249. }
  8250. const _vector$a = /*@__PURE__*/ new Vector3();
  8251. const _segCenter = /*@__PURE__*/ new Vector3();
  8252. const _segDir = /*@__PURE__*/ new Vector3();
  8253. const _diff = /*@__PURE__*/ new Vector3();
  8254. const _edge1 = /*@__PURE__*/ new Vector3();
  8255. const _edge2 = /*@__PURE__*/ new Vector3();
  8256. const _normal$1 = /*@__PURE__*/ new Vector3();
  8257. /**
  8258. * A ray that emits from an origin in a certain direction. The class is used by
  8259. * {@link Raycaster} to assist with raycasting. Raycasting is used for
  8260. * mouse picking (working out what objects in the 3D space the mouse is over)
  8261. * amongst other things.
  8262. */
  8263. class Ray {
  8264. /**
  8265. * Constructs a new ray.
  8266. *
  8267. * @param {Vector3} [origin=(0,0,0)] - The origin of the ray.
  8268. * @param {Vector3} [direction=(0,0,-1)] - The (normalized) direction of the ray.
  8269. */
  8270. constructor( origin = new Vector3(), direction = new Vector3( 0, 0, -1 ) ) {
  8271. /**
  8272. * The origin of the ray.
  8273. *
  8274. * @type {Vector3}
  8275. */
  8276. this.origin = origin;
  8277. /**
  8278. * The (normalized) direction of the ray.
  8279. *
  8280. * @type {Vector3}
  8281. */
  8282. this.direction = direction;
  8283. }
  8284. /**
  8285. * Sets the ray's components by copying the given values.
  8286. *
  8287. * @param {Vector3} origin - The origin.
  8288. * @param {Vector3} direction - The direction.
  8289. * @return {Ray} A reference to this ray.
  8290. */
  8291. set( origin, direction ) {
  8292. this.origin.copy( origin );
  8293. this.direction.copy( direction );
  8294. return this;
  8295. }
  8296. /**
  8297. * Copies the values of the given ray to this instance.
  8298. *
  8299. * @param {Ray} ray - The ray to copy.
  8300. * @return {Ray} A reference to this ray.
  8301. */
  8302. copy( ray ) {
  8303. this.origin.copy( ray.origin );
  8304. this.direction.copy( ray.direction );
  8305. return this;
  8306. }
  8307. /**
  8308. * Returns a vector that is located at a given distance along this ray.
  8309. *
  8310. * @param {number} t - The distance along the ray to retrieve a position for.
  8311. * @param {Vector3} target - The target vector that is used to store the method's result.
  8312. * @return {Vector3} A position on the ray.
  8313. */
  8314. at( t, target ) {
  8315. return target.copy( this.origin ).addScaledVector( this.direction, t );
  8316. }
  8317. /**
  8318. * Adjusts the direction of the ray to point at the given vector in world space.
  8319. *
  8320. * @param {Vector3} v - The target position.
  8321. * @return {Ray} A reference to this ray.
  8322. */
  8323. lookAt( v ) {
  8324. this.direction.copy( v ).sub( this.origin ).normalize();
  8325. return this;
  8326. }
  8327. /**
  8328. * Shift the origin of this ray along its direction by the given distance.
  8329. *
  8330. * @param {number} t - The distance along the ray to interpolate.
  8331. * @return {Ray} A reference to this ray.
  8332. */
  8333. recast( t ) {
  8334. this.origin.copy( this.at( t, _vector$a ) );
  8335. return this;
  8336. }
  8337. /**
  8338. * Returns the point along this ray that is closest to the given point.
  8339. *
  8340. * @param {Vector3} point - A point in 3D space to get the closet location on the ray for.
  8341. * @param {Vector3} target - The target vector that is used to store the method's result.
  8342. * @return {Vector3} The closest point on this ray.
  8343. */
  8344. closestPointToPoint( point, target ) {
  8345. target.subVectors( point, this.origin );
  8346. const directionDistance = target.dot( this.direction );
  8347. if ( directionDistance < 0 ) {
  8348. return target.copy( this.origin );
  8349. }
  8350. return target.copy( this.origin ).addScaledVector( this.direction, directionDistance );
  8351. }
  8352. /**
  8353. * Returns the distance of the closest approach between this ray and the given point.
  8354. *
  8355. * @param {Vector3} point - A point in 3D space to compute the distance to.
  8356. * @return {number} The distance.
  8357. */
  8358. distanceToPoint( point ) {
  8359. return Math.sqrt( this.distanceSqToPoint( point ) );
  8360. }
  8361. /**
  8362. * Returns the squared distance of the closest approach between this ray and the given point.
  8363. *
  8364. * @param {Vector3} point - A point in 3D space to compute the distance to.
  8365. * @return {number} The squared distance.
  8366. */
  8367. distanceSqToPoint( point ) {
  8368. const directionDistance = _vector$a.subVectors( point, this.origin ).dot( this.direction );
  8369. // point behind the ray
  8370. if ( directionDistance < 0 ) {
  8371. return this.origin.distanceToSquared( point );
  8372. }
  8373. _vector$a.copy( this.origin ).addScaledVector( this.direction, directionDistance );
  8374. return _vector$a.distanceToSquared( point );
  8375. }
  8376. /**
  8377. * Returns the squared distance between this ray and the given line segment.
  8378. *
  8379. * @param {Vector3} v0 - The start point of the line segment.
  8380. * @param {Vector3} v1 - The end point of the line segment.
  8381. * @param {Vector3} [optionalPointOnRay] - When provided, it receives the point on this ray that is closest to the segment.
  8382. * @param {Vector3} [optionalPointOnSegment] - When provided, it receives the point on the line segment that is closest to this ray.
  8383. * @return {number} The squared distance.
  8384. */
  8385. distanceSqToSegment( v0, v1, optionalPointOnRay, optionalPointOnSegment ) {
  8386. // from https://github.com/pmjoniak/GeometricTools/blob/master/GTEngine/Include/Mathematics/GteDistRaySegment.h
  8387. // It returns the min distance between the ray and the segment
  8388. // defined by v0 and v1
  8389. // It can also set two optional targets :
  8390. // - The closest point on the ray
  8391. // - The closest point on the segment
  8392. _segCenter.copy( v0 ).add( v1 ).multiplyScalar( 0.5 );
  8393. _segDir.copy( v1 ).sub( v0 ).normalize();
  8394. _diff.copy( this.origin ).sub( _segCenter );
  8395. const segExtent = v0.distanceTo( v1 ) * 0.5;
  8396. const a01 = - this.direction.dot( _segDir );
  8397. const b0 = _diff.dot( this.direction );
  8398. const b1 = - _diff.dot( _segDir );
  8399. const c = _diff.lengthSq();
  8400. const det = Math.abs( 1 - a01 * a01 );
  8401. let s0, s1, sqrDist, extDet;
  8402. if ( det > 0 ) {
  8403. // The ray and segment are not parallel.
  8404. s0 = a01 * b1 - b0;
  8405. s1 = a01 * b0 - b1;
  8406. extDet = segExtent * det;
  8407. if ( s0 >= 0 ) {
  8408. if ( s1 >= - extDet ) {
  8409. if ( s1 <= extDet ) {
  8410. // region 0
  8411. // Minimum at interior points of ray and segment.
  8412. const invDet = 1 / det;
  8413. s0 *= invDet;
  8414. s1 *= invDet;
  8415. sqrDist = s0 * ( s0 + a01 * s1 + 2 * b0 ) + s1 * ( a01 * s0 + s1 + 2 * b1 ) + c;
  8416. } else {
  8417. // region 1
  8418. s1 = segExtent;
  8419. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  8420. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  8421. }
  8422. } else {
  8423. // region 5
  8424. s1 = - segExtent;
  8425. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  8426. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  8427. }
  8428. } else {
  8429. if ( s1 <= - extDet ) {
  8430. // region 4
  8431. s0 = Math.max( 0, - ( - a01 * segExtent + b0 ) );
  8432. s1 = ( s0 > 0 ) ? - segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  8433. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  8434. } else if ( s1 <= extDet ) {
  8435. // region 3
  8436. s0 = 0;
  8437. s1 = Math.min( Math.max( - segExtent, - b1 ), segExtent );
  8438. sqrDist = s1 * ( s1 + 2 * b1 ) + c;
  8439. } else {
  8440. // region 2
  8441. s0 = Math.max( 0, - ( a01 * segExtent + b0 ) );
  8442. s1 = ( s0 > 0 ) ? segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  8443. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  8444. }
  8445. }
  8446. } else {
  8447. // Ray and segment are parallel.
  8448. s1 = ( a01 > 0 ) ? - segExtent : segExtent;
  8449. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  8450. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  8451. }
  8452. if ( optionalPointOnRay ) {
  8453. optionalPointOnRay.copy( this.origin ).addScaledVector( this.direction, s0 );
  8454. }
  8455. if ( optionalPointOnSegment ) {
  8456. optionalPointOnSegment.copy( _segCenter ).addScaledVector( _segDir, s1 );
  8457. }
  8458. return sqrDist;
  8459. }
  8460. /**
  8461. * Intersects this ray with the given sphere, returning the intersection
  8462. * point or `null` if there is no intersection.
  8463. *
  8464. * @param {Sphere} sphere - The sphere to intersect.
  8465. * @param {Vector3} target - The target vector that is used to store the method's result.
  8466. * @return {?Vector3} The intersection point.
  8467. */
  8468. intersectSphere( sphere, target ) {
  8469. _vector$a.subVectors( sphere.center, this.origin );
  8470. const tca = _vector$a.dot( this.direction );
  8471. const d2 = _vector$a.dot( _vector$a ) - tca * tca;
  8472. const radius2 = sphere.radius * sphere.radius;
  8473. if ( d2 > radius2 ) return null;
  8474. const thc = Math.sqrt( radius2 - d2 );
  8475. // t0 = first intersect point - entrance on front of sphere
  8476. const t0 = tca - thc;
  8477. // t1 = second intersect point - exit point on back of sphere
  8478. const t1 = tca + thc;
  8479. // test to see if t1 is behind the ray - if so, return null
  8480. if ( t1 < 0 ) return null;
  8481. // test to see if t0 is behind the ray:
  8482. // if it is, the ray is inside the sphere, so return the second exit point scaled by t1,
  8483. // in order to always return an intersect point that is in front of the ray.
  8484. if ( t0 < 0 ) return this.at( t1, target );
  8485. // else t0 is in front of the ray, so return the first collision point scaled by t0
  8486. return this.at( t0, target );
  8487. }
  8488. /**
  8489. * Returns `true` if this ray intersects with the given sphere.
  8490. *
  8491. * @param {Sphere} sphere - The sphere to intersect.
  8492. * @return {boolean} Whether this ray intersects with the given sphere or not.
  8493. */
  8494. intersectsSphere( sphere ) {
  8495. if ( sphere.radius < 0 ) return false; // handle empty spheres, see #31187
  8496. return this.distanceSqToPoint( sphere.center ) <= ( sphere.radius * sphere.radius );
  8497. }
  8498. /**
  8499. * Computes the distance from the ray's origin to the given plane. Returns `null` if the ray
  8500. * does not intersect with the plane.
  8501. *
  8502. * @param {Plane} plane - The plane to compute the distance to.
  8503. * @return {?number} Whether this ray intersects with the given sphere or not.
  8504. */
  8505. distanceToPlane( plane ) {
  8506. const denominator = plane.normal.dot( this.direction );
  8507. if ( denominator === 0 ) {
  8508. // line is coplanar, return origin
  8509. if ( plane.distanceToPoint( this.origin ) === 0 ) {
  8510. return 0;
  8511. }
  8512. // Null is preferable to undefined since undefined means.... it is undefined
  8513. return null;
  8514. }
  8515. const t = - ( this.origin.dot( plane.normal ) + plane.constant ) / denominator;
  8516. // Return if the ray never intersects the plane
  8517. return t >= 0 ? t : null;
  8518. }
  8519. /**
  8520. * Intersects this ray with the given plane, returning the intersection
  8521. * point or `null` if there is no intersection.
  8522. *
  8523. * @param {Plane} plane - The plane to intersect.
  8524. * @param {Vector3} target - The target vector that is used to store the method's result.
  8525. * @return {?Vector3} The intersection point.
  8526. */
  8527. intersectPlane( plane, target ) {
  8528. const t = this.distanceToPlane( plane );
  8529. if ( t === null ) {
  8530. return null;
  8531. }
  8532. return this.at( t, target );
  8533. }
  8534. /**
  8535. * Returns `true` if this ray intersects with the given plane.
  8536. *
  8537. * @param {Plane} plane - The plane to intersect.
  8538. * @return {boolean} Whether this ray intersects with the given plane or not.
  8539. */
  8540. intersectsPlane( plane ) {
  8541. // check if the ray lies on the plane first
  8542. const distToPoint = plane.distanceToPoint( this.origin );
  8543. if ( distToPoint === 0 ) {
  8544. return true;
  8545. }
  8546. const denominator = plane.normal.dot( this.direction );
  8547. if ( denominator * distToPoint < 0 ) {
  8548. return true;
  8549. }
  8550. // ray origin is behind the plane (and is pointing behind it)
  8551. return false;
  8552. }
  8553. /**
  8554. * Intersects this ray with the given bounding box, returning the intersection
  8555. * point or `null` if there is no intersection.
  8556. *
  8557. * @param {Box3} box - The box to intersect.
  8558. * @param {Vector3} target - The target vector that is used to store the method's result.
  8559. * @return {?Vector3} The intersection point.
  8560. */
  8561. intersectBox( box, target ) {
  8562. let tmin, tmax, tymin, tymax, tzmin, tzmax;
  8563. const invdirx = 1 / this.direction.x,
  8564. invdiry = 1 / this.direction.y,
  8565. invdirz = 1 / this.direction.z;
  8566. const origin = this.origin;
  8567. if ( invdirx >= 0 ) {
  8568. tmin = ( box.min.x - origin.x ) * invdirx;
  8569. tmax = ( box.max.x - origin.x ) * invdirx;
  8570. } else {
  8571. tmin = ( box.max.x - origin.x ) * invdirx;
  8572. tmax = ( box.min.x - origin.x ) * invdirx;
  8573. }
  8574. if ( invdiry >= 0 ) {
  8575. tymin = ( box.min.y - origin.y ) * invdiry;
  8576. tymax = ( box.max.y - origin.y ) * invdiry;
  8577. } else {
  8578. tymin = ( box.max.y - origin.y ) * invdiry;
  8579. tymax = ( box.min.y - origin.y ) * invdiry;
  8580. }
  8581. if ( ( tmin > tymax ) || ( tymin > tmax ) ) return null;
  8582. if ( tymin > tmin || isNaN( tmin ) ) tmin = tymin;
  8583. if ( tymax < tmax || isNaN( tmax ) ) tmax = tymax;
  8584. if ( invdirz >= 0 ) {
  8585. tzmin = ( box.min.z - origin.z ) * invdirz;
  8586. tzmax = ( box.max.z - origin.z ) * invdirz;
  8587. } else {
  8588. tzmin = ( box.max.z - origin.z ) * invdirz;
  8589. tzmax = ( box.min.z - origin.z ) * invdirz;
  8590. }
  8591. if ( ( tmin > tzmax ) || ( tzmin > tmax ) ) return null;
  8592. if ( tzmin > tmin || tmin !== tmin ) tmin = tzmin;
  8593. if ( tzmax < tmax || tmax !== tmax ) tmax = tzmax;
  8594. //return point closest to the ray (positive side)
  8595. if ( tmax < 0 ) return null;
  8596. return this.at( tmin >= 0 ? tmin : tmax, target );
  8597. }
  8598. /**
  8599. * Returns `true` if this ray intersects with the given box.
  8600. *
  8601. * @param {Box3} box - The box to intersect.
  8602. * @return {boolean} Whether this ray intersects with the given box or not.
  8603. */
  8604. intersectsBox( box ) {
  8605. return this.intersectBox( box, _vector$a ) !== null;
  8606. }
  8607. /**
  8608. * Intersects this ray with the given triangle, returning the intersection
  8609. * point or `null` if there is no intersection.
  8610. *
  8611. * @param {Vector3} a - The first vertex of the triangle.
  8612. * @param {Vector3} b - The second vertex of the triangle.
  8613. * @param {Vector3} c - The third vertex of the triangle.
  8614. * @param {boolean} backfaceCulling - Whether to use backface culling or not.
  8615. * @param {Vector3} target - The target vector that is used to store the method's result.
  8616. * @return {?Vector3} The intersection point.
  8617. */
  8618. intersectTriangle( a, b, c, backfaceCulling, target ) {
  8619. // Compute the offset origin, edges, and normal.
  8620. // from https://github.com/pmjoniak/GeometricTools/blob/master/GTEngine/Include/Mathematics/GteIntrRay3Triangle3.h
  8621. _edge1.subVectors( b, a );
  8622. _edge2.subVectors( c, a );
  8623. _normal$1.crossVectors( _edge1, _edge2 );
  8624. // Solve Q + t*D = b1*E1 + b2*E2 (Q = kDiff, D = ray direction,
  8625. // E1 = kEdge1, E2 = kEdge2, N = Cross(E1,E2)) by
  8626. // |Dot(D,N)|*b1 = sign(Dot(D,N))*Dot(D,Cross(Q,E2))
  8627. // |Dot(D,N)|*b2 = sign(Dot(D,N))*Dot(D,Cross(E1,Q))
  8628. // |Dot(D,N)|*t = -sign(Dot(D,N))*Dot(Q,N)
  8629. let DdN = this.direction.dot( _normal$1 );
  8630. let sign;
  8631. if ( DdN > 0 ) {
  8632. if ( backfaceCulling ) return null;
  8633. sign = 1;
  8634. } else if ( DdN < 0 ) {
  8635. sign = -1;
  8636. DdN = - DdN;
  8637. } else {
  8638. return null;
  8639. }
  8640. _diff.subVectors( this.origin, a );
  8641. const DdQxE2 = sign * this.direction.dot( _edge2.crossVectors( _diff, _edge2 ) );
  8642. // b1 < 0, no intersection
  8643. if ( DdQxE2 < 0 ) {
  8644. return null;
  8645. }
  8646. const DdE1xQ = sign * this.direction.dot( _edge1.cross( _diff ) );
  8647. // b2 < 0, no intersection
  8648. if ( DdE1xQ < 0 ) {
  8649. return null;
  8650. }
  8651. // b1+b2 > 1, no intersection
  8652. if ( DdQxE2 + DdE1xQ > DdN ) {
  8653. return null;
  8654. }
  8655. // Line intersects triangle, check if ray does.
  8656. const QdN = - sign * _diff.dot( _normal$1 );
  8657. // t < 0, no intersection
  8658. if ( QdN < 0 ) {
  8659. return null;
  8660. }
  8661. // Ray intersects triangle.
  8662. return this.at( QdN / DdN, target );
  8663. }
  8664. /**
  8665. * Transforms this ray with the given 4x4 transformation matrix.
  8666. *
  8667. * @param {Matrix4} matrix4 - The transformation matrix.
  8668. * @return {Ray} A reference to this ray.
  8669. */
  8670. applyMatrix4( matrix4 ) {
  8671. this.origin.applyMatrix4( matrix4 );
  8672. this.direction.transformDirection( matrix4 );
  8673. return this;
  8674. }
  8675. /**
  8676. * Returns `true` if this ray is equal with the given one.
  8677. *
  8678. * @param {Ray} ray - The ray to test for equality.
  8679. * @return {boolean} Whether this ray is equal with the given one.
  8680. */
  8681. equals( ray ) {
  8682. return ray.origin.equals( this.origin ) && ray.direction.equals( this.direction );
  8683. }
  8684. /**
  8685. * Returns a new ray with copied values from this instance.
  8686. *
  8687. * @return {Ray} A clone of this instance.
  8688. */
  8689. clone() {
  8690. return new this.constructor().copy( this );
  8691. }
  8692. }
  8693. /**
  8694. * Represents a 4x4 matrix.
  8695. *
  8696. * The most common use of a 4x4 matrix in 3D computer graphics is as a transformation matrix.
  8697. * For an introduction to transformation matrices as used in WebGL, check out [this tutorial](https://www.opengl-tutorial.org/beginners-tutorials/tutorial-3-matrices)
  8698. *
  8699. * This allows a 3D vector representing a point in 3D space to undergo
  8700. * transformations such as translation, rotation, shear, scale, reflection,
  8701. * orthogonal or perspective projection and so on, by being multiplied by the
  8702. * matrix. This is known as `applying` the matrix to the vector.
  8703. *
  8704. * A Note on Row-Major and Column-Major Ordering:
  8705. *
  8706. * The constructor and {@link Matrix3#set} method take arguments in
  8707. * [row-major](https://en.wikipedia.org/wiki/Row-_and_column-major_order#Column-major_order)
  8708. * order, while internally they are stored in the {@link Matrix3#elements} array in column-major order.
  8709. * This means that calling:
  8710. * ```js
  8711. * const m = new THREE.Matrix4();
  8712. * m.set( 11, 12, 13, 14,
  8713. * 21, 22, 23, 24,
  8714. * 31, 32, 33, 34,
  8715. * 41, 42, 43, 44 );
  8716. * ```
  8717. * will result in the elements array containing:
  8718. * ```js
  8719. * m.elements = [ 11, 21, 31, 41,
  8720. * 12, 22, 32, 42,
  8721. * 13, 23, 33, 43,
  8722. * 14, 24, 34, 44 ];
  8723. * ```
  8724. * and internally all calculations are performed using column-major ordering.
  8725. * However, as the actual ordering makes no difference mathematically and
  8726. * most people are used to thinking about matrices in row-major order, the
  8727. * three.js documentation shows matrices in row-major order. Just bear in
  8728. * mind that if you are reading the source code, you'll have to take the
  8729. * transpose of any matrices outlined here to make sense of the calculations.
  8730. */
  8731. class Matrix4 {
  8732. /**
  8733. * Constructs a new 4x4 matrix. The arguments are supposed to be
  8734. * in row-major order. If no arguments are provided, the constructor
  8735. * initializes the matrix as an identity matrix.
  8736. *
  8737. * @param {number} [n11] - 1-1 matrix element.
  8738. * @param {number} [n12] - 1-2 matrix element.
  8739. * @param {number} [n13] - 1-3 matrix element.
  8740. * @param {number} [n14] - 1-4 matrix element.
  8741. * @param {number} [n21] - 2-1 matrix element.
  8742. * @param {number} [n22] - 2-2 matrix element.
  8743. * @param {number} [n23] - 2-3 matrix element.
  8744. * @param {number} [n24] - 2-4 matrix element.
  8745. * @param {number} [n31] - 3-1 matrix element.
  8746. * @param {number} [n32] - 3-2 matrix element.
  8747. * @param {number} [n33] - 3-3 matrix element.
  8748. * @param {number} [n34] - 3-4 matrix element.
  8749. * @param {number} [n41] - 4-1 matrix element.
  8750. * @param {number} [n42] - 4-2 matrix element.
  8751. * @param {number} [n43] - 4-3 matrix element.
  8752. * @param {number} [n44] - 4-4 matrix element.
  8753. */
  8754. constructor( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  8755. /**
  8756. * This flag can be used for type testing.
  8757. *
  8758. * @type {boolean}
  8759. * @readonly
  8760. * @default true
  8761. */
  8762. Matrix4.prototype.isMatrix4 = true;
  8763. /**
  8764. * A column-major list of matrix values.
  8765. *
  8766. * @type {Array<number>}
  8767. */
  8768. this.elements = [
  8769. 1, 0, 0, 0,
  8770. 0, 1, 0, 0,
  8771. 0, 0, 1, 0,
  8772. 0, 0, 0, 1
  8773. ];
  8774. if ( n11 !== undefined ) {
  8775. this.set( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 );
  8776. }
  8777. }
  8778. /**
  8779. * Sets the elements of the matrix.The arguments are supposed to be
  8780. * in row-major order.
  8781. *
  8782. * @param {number} [n11] - 1-1 matrix element.
  8783. * @param {number} [n12] - 1-2 matrix element.
  8784. * @param {number} [n13] - 1-3 matrix element.
  8785. * @param {number} [n14] - 1-4 matrix element.
  8786. * @param {number} [n21] - 2-1 matrix element.
  8787. * @param {number} [n22] - 2-2 matrix element.
  8788. * @param {number} [n23] - 2-3 matrix element.
  8789. * @param {number} [n24] - 2-4 matrix element.
  8790. * @param {number} [n31] - 3-1 matrix element.
  8791. * @param {number} [n32] - 3-2 matrix element.
  8792. * @param {number} [n33] - 3-3 matrix element.
  8793. * @param {number} [n34] - 3-4 matrix element.
  8794. * @param {number} [n41] - 4-1 matrix element.
  8795. * @param {number} [n42] - 4-2 matrix element.
  8796. * @param {number} [n43] - 4-3 matrix element.
  8797. * @param {number} [n44] - 4-4 matrix element.
  8798. * @return {Matrix4} A reference to this matrix.
  8799. */
  8800. set( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  8801. const te = this.elements;
  8802. te[ 0 ] = n11; te[ 4 ] = n12; te[ 8 ] = n13; te[ 12 ] = n14;
  8803. te[ 1 ] = n21; te[ 5 ] = n22; te[ 9 ] = n23; te[ 13 ] = n24;
  8804. te[ 2 ] = n31; te[ 6 ] = n32; te[ 10 ] = n33; te[ 14 ] = n34;
  8805. te[ 3 ] = n41; te[ 7 ] = n42; te[ 11 ] = n43; te[ 15 ] = n44;
  8806. return this;
  8807. }
  8808. /**
  8809. * Sets this matrix to the 4x4 identity matrix.
  8810. *
  8811. * @return {Matrix4} A reference to this matrix.
  8812. */
  8813. identity() {
  8814. this.set(
  8815. 1, 0, 0, 0,
  8816. 0, 1, 0, 0,
  8817. 0, 0, 1, 0,
  8818. 0, 0, 0, 1
  8819. );
  8820. return this;
  8821. }
  8822. /**
  8823. * Returns a matrix with copied values from this instance.
  8824. *
  8825. * @return {Matrix4} A clone of this instance.
  8826. */
  8827. clone() {
  8828. return new Matrix4().fromArray( this.elements );
  8829. }
  8830. /**
  8831. * Copies the values of the given matrix to this instance.
  8832. *
  8833. * @param {Matrix4} m - The matrix to copy.
  8834. * @return {Matrix4} A reference to this matrix.
  8835. */
  8836. copy( m ) {
  8837. const te = this.elements;
  8838. const me = m.elements;
  8839. te[ 0 ] = me[ 0 ]; te[ 1 ] = me[ 1 ]; te[ 2 ] = me[ 2 ]; te[ 3 ] = me[ 3 ];
  8840. te[ 4 ] = me[ 4 ]; te[ 5 ] = me[ 5 ]; te[ 6 ] = me[ 6 ]; te[ 7 ] = me[ 7 ];
  8841. te[ 8 ] = me[ 8 ]; te[ 9 ] = me[ 9 ]; te[ 10 ] = me[ 10 ]; te[ 11 ] = me[ 11 ];
  8842. te[ 12 ] = me[ 12 ]; te[ 13 ] = me[ 13 ]; te[ 14 ] = me[ 14 ]; te[ 15 ] = me[ 15 ];
  8843. return this;
  8844. }
  8845. /**
  8846. * Copies the translation component of the given matrix
  8847. * into this matrix's translation component.
  8848. *
  8849. * @param {Matrix4} m - The matrix to copy the translation component.
  8850. * @return {Matrix4} A reference to this matrix.
  8851. */
  8852. copyPosition( m ) {
  8853. const te = this.elements, me = m.elements;
  8854. te[ 12 ] = me[ 12 ];
  8855. te[ 13 ] = me[ 13 ];
  8856. te[ 14 ] = me[ 14 ];
  8857. return this;
  8858. }
  8859. /**
  8860. * Set the upper 3x3 elements of this matrix to the values of given 3x3 matrix.
  8861. *
  8862. * @param {Matrix3} m - The 3x3 matrix.
  8863. * @return {Matrix4} A reference to this matrix.
  8864. */
  8865. setFromMatrix3( m ) {
  8866. const me = m.elements;
  8867. this.set(
  8868. me[ 0 ], me[ 3 ], me[ 6 ], 0,
  8869. me[ 1 ], me[ 4 ], me[ 7 ], 0,
  8870. me[ 2 ], me[ 5 ], me[ 8 ], 0,
  8871. 0, 0, 0, 1
  8872. );
  8873. return this;
  8874. }
  8875. /**
  8876. * Extracts the basis of this matrix into the three axis vectors provided.
  8877. *
  8878. * @param {Vector3} xAxis - The basis's x axis.
  8879. * @param {Vector3} yAxis - The basis's y axis.
  8880. * @param {Vector3} zAxis - The basis's z axis.
  8881. * @return {Matrix4} A reference to this matrix.
  8882. */
  8883. extractBasis( xAxis, yAxis, zAxis ) {
  8884. if ( this.determinant() === 0 ) {
  8885. xAxis.set( 1, 0, 0 );
  8886. yAxis.set( 0, 1, 0 );
  8887. zAxis.set( 0, 0, 1 );
  8888. return this;
  8889. }
  8890. xAxis.setFromMatrixColumn( this, 0 );
  8891. yAxis.setFromMatrixColumn( this, 1 );
  8892. zAxis.setFromMatrixColumn( this, 2 );
  8893. return this;
  8894. }
  8895. /**
  8896. * Sets the given basis vectors to this matrix.
  8897. *
  8898. * @param {Vector3} xAxis - The basis's x axis.
  8899. * @param {Vector3} yAxis - The basis's y axis.
  8900. * @param {Vector3} zAxis - The basis's z axis.
  8901. * @return {Matrix4} A reference to this matrix.
  8902. */
  8903. makeBasis( xAxis, yAxis, zAxis ) {
  8904. this.set(
  8905. xAxis.x, yAxis.x, zAxis.x, 0,
  8906. xAxis.y, yAxis.y, zAxis.y, 0,
  8907. xAxis.z, yAxis.z, zAxis.z, 0,
  8908. 0, 0, 0, 1
  8909. );
  8910. return this;
  8911. }
  8912. /**
  8913. * Extracts the rotation component of the given matrix
  8914. * into this matrix's rotation component.
  8915. *
  8916. * Note: This method does not support reflection matrices.
  8917. *
  8918. * @param {Matrix4} m - The matrix.
  8919. * @return {Matrix4} A reference to this matrix.
  8920. */
  8921. extractRotation( m ) {
  8922. if ( m.determinant() === 0 ) {
  8923. return this.identity();
  8924. }
  8925. const te = this.elements;
  8926. const me = m.elements;
  8927. const scaleX = 1 / _v1$5.setFromMatrixColumn( m, 0 ).length();
  8928. const scaleY = 1 / _v1$5.setFromMatrixColumn( m, 1 ).length();
  8929. const scaleZ = 1 / _v1$5.setFromMatrixColumn( m, 2 ).length();
  8930. te[ 0 ] = me[ 0 ] * scaleX;
  8931. te[ 1 ] = me[ 1 ] * scaleX;
  8932. te[ 2 ] = me[ 2 ] * scaleX;
  8933. te[ 3 ] = 0;
  8934. te[ 4 ] = me[ 4 ] * scaleY;
  8935. te[ 5 ] = me[ 5 ] * scaleY;
  8936. te[ 6 ] = me[ 6 ] * scaleY;
  8937. te[ 7 ] = 0;
  8938. te[ 8 ] = me[ 8 ] * scaleZ;
  8939. te[ 9 ] = me[ 9 ] * scaleZ;
  8940. te[ 10 ] = me[ 10 ] * scaleZ;
  8941. te[ 11 ] = 0;
  8942. te[ 12 ] = 0;
  8943. te[ 13 ] = 0;
  8944. te[ 14 ] = 0;
  8945. te[ 15 ] = 1;
  8946. return this;
  8947. }
  8948. /**
  8949. * Sets the rotation component (the upper left 3x3 matrix) of this matrix to
  8950. * the rotation specified by the given Euler angles. The rest of
  8951. * the matrix is set to the identity. Depending on the {@link Euler#order},
  8952. * there are six possible outcomes. See [this page](https://en.wikipedia.org/wiki/Euler_angles#Rotation_matrix)
  8953. * for a complete list.
  8954. *
  8955. * @param {Euler} euler - The Euler angles.
  8956. * @return {Matrix4} A reference to this matrix.
  8957. */
  8958. makeRotationFromEuler( euler ) {
  8959. const te = this.elements;
  8960. const x = euler.x, y = euler.y, z = euler.z;
  8961. const a = Math.cos( x ), b = Math.sin( x );
  8962. const c = Math.cos( y ), d = Math.sin( y );
  8963. const e = Math.cos( z ), f = Math.sin( z );
  8964. if ( euler.order === 'XYZ' ) {
  8965. const ae = a * e, af = a * f, be = b * e, bf = b * f;
  8966. te[ 0 ] = c * e;
  8967. te[ 4 ] = - c * f;
  8968. te[ 8 ] = d;
  8969. te[ 1 ] = af + be * d;
  8970. te[ 5 ] = ae - bf * d;
  8971. te[ 9 ] = - b * c;
  8972. te[ 2 ] = bf - ae * d;
  8973. te[ 6 ] = be + af * d;
  8974. te[ 10 ] = a * c;
  8975. } else if ( euler.order === 'YXZ' ) {
  8976. const ce = c * e, cf = c * f, de = d * e, df = d * f;
  8977. te[ 0 ] = ce + df * b;
  8978. te[ 4 ] = de * b - cf;
  8979. te[ 8 ] = a * d;
  8980. te[ 1 ] = a * f;
  8981. te[ 5 ] = a * e;
  8982. te[ 9 ] = - b;
  8983. te[ 2 ] = cf * b - de;
  8984. te[ 6 ] = df + ce * b;
  8985. te[ 10 ] = a * c;
  8986. } else if ( euler.order === 'ZXY' ) {
  8987. const ce = c * e, cf = c * f, de = d * e, df = d * f;
  8988. te[ 0 ] = ce - df * b;
  8989. te[ 4 ] = - a * f;
  8990. te[ 8 ] = de + cf * b;
  8991. te[ 1 ] = cf + de * b;
  8992. te[ 5 ] = a * e;
  8993. te[ 9 ] = df - ce * b;
  8994. te[ 2 ] = - a * d;
  8995. te[ 6 ] = b;
  8996. te[ 10 ] = a * c;
  8997. } else if ( euler.order === 'ZYX' ) {
  8998. const ae = a * e, af = a * f, be = b * e, bf = b * f;
  8999. te[ 0 ] = c * e;
  9000. te[ 4 ] = be * d - af;
  9001. te[ 8 ] = ae * d + bf;
  9002. te[ 1 ] = c * f;
  9003. te[ 5 ] = bf * d + ae;
  9004. te[ 9 ] = af * d - be;
  9005. te[ 2 ] = - d;
  9006. te[ 6 ] = b * c;
  9007. te[ 10 ] = a * c;
  9008. } else if ( euler.order === 'YZX' ) {
  9009. const ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  9010. te[ 0 ] = c * e;
  9011. te[ 4 ] = bd - ac * f;
  9012. te[ 8 ] = bc * f + ad;
  9013. te[ 1 ] = f;
  9014. te[ 5 ] = a * e;
  9015. te[ 9 ] = - b * e;
  9016. te[ 2 ] = - d * e;
  9017. te[ 6 ] = ad * f + bc;
  9018. te[ 10 ] = ac - bd * f;
  9019. } else if ( euler.order === 'XZY' ) {
  9020. const ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  9021. te[ 0 ] = c * e;
  9022. te[ 4 ] = - f;
  9023. te[ 8 ] = d * e;
  9024. te[ 1 ] = ac * f + bd;
  9025. te[ 5 ] = a * e;
  9026. te[ 9 ] = ad * f - bc;
  9027. te[ 2 ] = bc * f - ad;
  9028. te[ 6 ] = b * e;
  9029. te[ 10 ] = bd * f + ac;
  9030. }
  9031. // bottom row
  9032. te[ 3 ] = 0;
  9033. te[ 7 ] = 0;
  9034. te[ 11 ] = 0;
  9035. // last column
  9036. te[ 12 ] = 0;
  9037. te[ 13 ] = 0;
  9038. te[ 14 ] = 0;
  9039. te[ 15 ] = 1;
  9040. return this;
  9041. }
  9042. /**
  9043. * Sets the rotation component of this matrix to the rotation specified by
  9044. * the given Quaternion as outlined [here](https://en.wikipedia.org/wiki/Rotation_matrix#Quaternion)
  9045. * The rest of the matrix is set to the identity.
  9046. *
  9047. * @param {Quaternion} q - The Quaternion.
  9048. * @return {Matrix4} A reference to this matrix.
  9049. */
  9050. makeRotationFromQuaternion( q ) {
  9051. return this.compose( _zero, q, _one );
  9052. }
  9053. /**
  9054. * Sets the rotation component of the transformation matrix, looking from `eye` towards
  9055. * `target`, and oriented by the up-direction.
  9056. *
  9057. * @param {Vector3} eye - The eye vector.
  9058. * @param {Vector3} target - The target vector.
  9059. * @param {Vector3} up - The up vector.
  9060. * @return {Matrix4} A reference to this matrix.
  9061. */
  9062. lookAt( eye, target, up ) {
  9063. const te = this.elements;
  9064. _z.subVectors( eye, target );
  9065. if ( _z.lengthSq() === 0 ) {
  9066. // eye and target are in the same position
  9067. _z.z = 1;
  9068. }
  9069. _z.normalize();
  9070. _x.crossVectors( up, _z );
  9071. if ( _x.lengthSq() === 0 ) {
  9072. // up and z are parallel
  9073. if ( Math.abs( up.z ) === 1 ) {
  9074. _z.x += 0.0001;
  9075. } else {
  9076. _z.z += 0.0001;
  9077. }
  9078. _z.normalize();
  9079. _x.crossVectors( up, _z );
  9080. }
  9081. _x.normalize();
  9082. _y.crossVectors( _z, _x );
  9083. te[ 0 ] = _x.x; te[ 4 ] = _y.x; te[ 8 ] = _z.x;
  9084. te[ 1 ] = _x.y; te[ 5 ] = _y.y; te[ 9 ] = _z.y;
  9085. te[ 2 ] = _x.z; te[ 6 ] = _y.z; te[ 10 ] = _z.z;
  9086. return this;
  9087. }
  9088. /**
  9089. * Post-multiplies this matrix by the given 4x4 matrix.
  9090. *
  9091. * @param {Matrix4} m - The matrix to multiply with.
  9092. * @return {Matrix4} A reference to this matrix.
  9093. */
  9094. multiply( m ) {
  9095. return this.multiplyMatrices( this, m );
  9096. }
  9097. /**
  9098. * Pre-multiplies this matrix by the given 4x4 matrix.
  9099. *
  9100. * @param {Matrix4} m - The matrix to multiply with.
  9101. * @return {Matrix4} A reference to this matrix.
  9102. */
  9103. premultiply( m ) {
  9104. return this.multiplyMatrices( m, this );
  9105. }
  9106. /**
  9107. * Multiples the given 4x4 matrices and stores the result
  9108. * in this matrix.
  9109. *
  9110. * @param {Matrix4} a - The first matrix.
  9111. * @param {Matrix4} b - The second matrix.
  9112. * @return {Matrix4} A reference to this matrix.
  9113. */
  9114. multiplyMatrices( a, b ) {
  9115. const ae = a.elements;
  9116. const be = b.elements;
  9117. const te = this.elements;
  9118. const a11 = ae[ 0 ], a12 = ae[ 4 ], a13 = ae[ 8 ], a14 = ae[ 12 ];
  9119. const a21 = ae[ 1 ], a22 = ae[ 5 ], a23 = ae[ 9 ], a24 = ae[ 13 ];
  9120. const a31 = ae[ 2 ], a32 = ae[ 6 ], a33 = ae[ 10 ], a34 = ae[ 14 ];
  9121. const a41 = ae[ 3 ], a42 = ae[ 7 ], a43 = ae[ 11 ], a44 = ae[ 15 ];
  9122. const b11 = be[ 0 ], b12 = be[ 4 ], b13 = be[ 8 ], b14 = be[ 12 ];
  9123. const b21 = be[ 1 ], b22 = be[ 5 ], b23 = be[ 9 ], b24 = be[ 13 ];
  9124. const b31 = be[ 2 ], b32 = be[ 6 ], b33 = be[ 10 ], b34 = be[ 14 ];
  9125. const b41 = be[ 3 ], b42 = be[ 7 ], b43 = be[ 11 ], b44 = be[ 15 ];
  9126. te[ 0 ] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41;
  9127. te[ 4 ] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42;
  9128. te[ 8 ] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43;
  9129. te[ 12 ] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44;
  9130. te[ 1 ] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41;
  9131. te[ 5 ] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42;
  9132. te[ 9 ] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43;
  9133. te[ 13 ] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44;
  9134. te[ 2 ] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41;
  9135. te[ 6 ] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42;
  9136. te[ 10 ] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43;
  9137. te[ 14 ] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44;
  9138. te[ 3 ] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41;
  9139. te[ 7 ] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42;
  9140. te[ 11 ] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43;
  9141. te[ 15 ] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44;
  9142. return this;
  9143. }
  9144. /**
  9145. * Multiplies every component of the matrix by the given scalar.
  9146. *
  9147. * @param {number} s - The scalar.
  9148. * @return {Matrix4} A reference to this matrix.
  9149. */
  9150. multiplyScalar( s ) {
  9151. const te = this.elements;
  9152. te[ 0 ] *= s; te[ 4 ] *= s; te[ 8 ] *= s; te[ 12 ] *= s;
  9153. te[ 1 ] *= s; te[ 5 ] *= s; te[ 9 ] *= s; te[ 13 ] *= s;
  9154. te[ 2 ] *= s; te[ 6 ] *= s; te[ 10 ] *= s; te[ 14 ] *= s;
  9155. te[ 3 ] *= s; te[ 7 ] *= s; te[ 11 ] *= s; te[ 15 ] *= s;
  9156. return this;
  9157. }
  9158. /**
  9159. * Computes and returns the determinant of this matrix.
  9160. *
  9161. * Based on the method outlined [here](http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.html).
  9162. *
  9163. * @return {number} The determinant.
  9164. */
  9165. determinant() {
  9166. const te = this.elements;
  9167. const n11 = te[ 0 ], n12 = te[ 4 ], n13 = te[ 8 ], n14 = te[ 12 ];
  9168. const n21 = te[ 1 ], n22 = te[ 5 ], n23 = te[ 9 ], n24 = te[ 13 ];
  9169. const n31 = te[ 2 ], n32 = te[ 6 ], n33 = te[ 10 ], n34 = te[ 14 ];
  9170. const n41 = te[ 3 ], n42 = te[ 7 ], n43 = te[ 11 ], n44 = te[ 15 ];
  9171. const t11 = n23 * n34 - n24 * n33;
  9172. const t12 = n22 * n34 - n24 * n32;
  9173. const t13 = n22 * n33 - n23 * n32;
  9174. const t21 = n21 * n34 - n24 * n31;
  9175. const t22 = n21 * n33 - n23 * n31;
  9176. const t23 = n21 * n32 - n22 * n31;
  9177. return n11 * ( n42 * t11 - n43 * t12 + n44 * t13 ) -
  9178. n12 * ( n41 * t11 - n43 * t21 + n44 * t22 ) +
  9179. n13 * ( n41 * t12 - n42 * t21 + n44 * t23 ) -
  9180. n14 * ( n41 * t13 - n42 * t22 + n43 * t23 );
  9181. }
  9182. /**
  9183. * Transposes this matrix in place.
  9184. *
  9185. * @return {Matrix4} A reference to this matrix.
  9186. */
  9187. transpose() {
  9188. const te = this.elements;
  9189. let tmp;
  9190. tmp = te[ 1 ]; te[ 1 ] = te[ 4 ]; te[ 4 ] = tmp;
  9191. tmp = te[ 2 ]; te[ 2 ] = te[ 8 ]; te[ 8 ] = tmp;
  9192. tmp = te[ 6 ]; te[ 6 ] = te[ 9 ]; te[ 9 ] = tmp;
  9193. tmp = te[ 3 ]; te[ 3 ] = te[ 12 ]; te[ 12 ] = tmp;
  9194. tmp = te[ 7 ]; te[ 7 ] = te[ 13 ]; te[ 13 ] = tmp;
  9195. tmp = te[ 11 ]; te[ 11 ] = te[ 14 ]; te[ 14 ] = tmp;
  9196. return this;
  9197. }
  9198. /**
  9199. * Sets the position component for this matrix from the given vector,
  9200. * without affecting the rest of the matrix.
  9201. *
  9202. * @param {number|Vector3} x - The x component of the vector or alternatively the vector object.
  9203. * @param {number} y - The y component of the vector.
  9204. * @param {number} z - The z component of the vector.
  9205. * @return {Matrix4} A reference to this matrix.
  9206. */
  9207. setPosition( x, y, z ) {
  9208. const te = this.elements;
  9209. if ( x.isVector3 ) {
  9210. te[ 12 ] = x.x;
  9211. te[ 13 ] = x.y;
  9212. te[ 14 ] = x.z;
  9213. } else {
  9214. te[ 12 ] = x;
  9215. te[ 13 ] = y;
  9216. te[ 14 ] = z;
  9217. }
  9218. return this;
  9219. }
  9220. /**
  9221. * Inverts this matrix, using the [analytic method](https://en.wikipedia.org/wiki/Invertible_matrix#Analytic_solution).
  9222. * You can not invert with a determinant of zero. If you attempt this, the method produces
  9223. * a zero matrix instead.
  9224. *
  9225. * @return {Matrix4} A reference to this matrix.
  9226. */
  9227. invert() {
  9228. // based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm
  9229. const te = this.elements,
  9230. n11 = te[ 0 ], n21 = te[ 1 ], n31 = te[ 2 ], n41 = te[ 3 ],
  9231. n12 = te[ 4 ], n22 = te[ 5 ], n32 = te[ 6 ], n42 = te[ 7 ],
  9232. n13 = te[ 8 ], n23 = te[ 9 ], n33 = te[ 10 ], n43 = te[ 11 ],
  9233. n14 = te[ 12 ], n24 = te[ 13 ], n34 = te[ 14 ], n44 = te[ 15 ],
  9234. t11 = n23 * n34 * n42 - n24 * n33 * n42 + n24 * n32 * n43 - n22 * n34 * n43 - n23 * n32 * n44 + n22 * n33 * n44,
  9235. t12 = n14 * n33 * n42 - n13 * n34 * n42 - n14 * n32 * n43 + n12 * n34 * n43 + n13 * n32 * n44 - n12 * n33 * n44,
  9236. t13 = n13 * n24 * n42 - n14 * n23 * n42 + n14 * n22 * n43 - n12 * n24 * n43 - n13 * n22 * n44 + n12 * n23 * n44,
  9237. t14 = n14 * n23 * n32 - n13 * n24 * n32 - n14 * n22 * n33 + n12 * n24 * n33 + n13 * n22 * n34 - n12 * n23 * n34;
  9238. const det = n11 * t11 + n21 * t12 + n31 * t13 + n41 * t14;
  9239. if ( det === 0 ) return this.set( 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 );
  9240. const detInv = 1 / det;
  9241. te[ 0 ] = t11 * detInv;
  9242. te[ 1 ] = ( n24 * n33 * n41 - n23 * n34 * n41 - n24 * n31 * n43 + n21 * n34 * n43 + n23 * n31 * n44 - n21 * n33 * n44 ) * detInv;
  9243. te[ 2 ] = ( n22 * n34 * n41 - n24 * n32 * n41 + n24 * n31 * n42 - n21 * n34 * n42 - n22 * n31 * n44 + n21 * n32 * n44 ) * detInv;
  9244. te[ 3 ] = ( n23 * n32 * n41 - n22 * n33 * n41 - n23 * n31 * n42 + n21 * n33 * n42 + n22 * n31 * n43 - n21 * n32 * n43 ) * detInv;
  9245. te[ 4 ] = t12 * detInv;
  9246. te[ 5 ] = ( n13 * n34 * n41 - n14 * n33 * n41 + n14 * n31 * n43 - n11 * n34 * n43 - n13 * n31 * n44 + n11 * n33 * n44 ) * detInv;
  9247. te[ 6 ] = ( n14 * n32 * n41 - n12 * n34 * n41 - n14 * n31 * n42 + n11 * n34 * n42 + n12 * n31 * n44 - n11 * n32 * n44 ) * detInv;
  9248. te[ 7 ] = ( n12 * n33 * n41 - n13 * n32 * n41 + n13 * n31 * n42 - n11 * n33 * n42 - n12 * n31 * n43 + n11 * n32 * n43 ) * detInv;
  9249. te[ 8 ] = t13 * detInv;
  9250. te[ 9 ] = ( n14 * n23 * n41 - n13 * n24 * n41 - n14 * n21 * n43 + n11 * n24 * n43 + n13 * n21 * n44 - n11 * n23 * n44 ) * detInv;
  9251. te[ 10 ] = ( n12 * n24 * n41 - n14 * n22 * n41 + n14 * n21 * n42 - n11 * n24 * n42 - n12 * n21 * n44 + n11 * n22 * n44 ) * detInv;
  9252. te[ 11 ] = ( n13 * n22 * n41 - n12 * n23 * n41 - n13 * n21 * n42 + n11 * n23 * n42 + n12 * n21 * n43 - n11 * n22 * n43 ) * detInv;
  9253. te[ 12 ] = t14 * detInv;
  9254. te[ 13 ] = ( n13 * n24 * n31 - n14 * n23 * n31 + n14 * n21 * n33 - n11 * n24 * n33 - n13 * n21 * n34 + n11 * n23 * n34 ) * detInv;
  9255. te[ 14 ] = ( n14 * n22 * n31 - n12 * n24 * n31 - n14 * n21 * n32 + n11 * n24 * n32 + n12 * n21 * n34 - n11 * n22 * n34 ) * detInv;
  9256. te[ 15 ] = ( n12 * n23 * n31 - n13 * n22 * n31 + n13 * n21 * n32 - n11 * n23 * n32 - n12 * n21 * n33 + n11 * n22 * n33 ) * detInv;
  9257. return this;
  9258. }
  9259. /**
  9260. * Multiplies the columns of this matrix by the given vector.
  9261. *
  9262. * @param {Vector3} v - The scale vector.
  9263. * @return {Matrix4} A reference to this matrix.
  9264. */
  9265. scale( v ) {
  9266. const te = this.elements;
  9267. const x = v.x, y = v.y, z = v.z;
  9268. te[ 0 ] *= x; te[ 4 ] *= y; te[ 8 ] *= z;
  9269. te[ 1 ] *= x; te[ 5 ] *= y; te[ 9 ] *= z;
  9270. te[ 2 ] *= x; te[ 6 ] *= y; te[ 10 ] *= z;
  9271. te[ 3 ] *= x; te[ 7 ] *= y; te[ 11 ] *= z;
  9272. return this;
  9273. }
  9274. /**
  9275. * Gets the maximum scale value of the three axes.
  9276. *
  9277. * @return {number} The maximum scale.
  9278. */
  9279. getMaxScaleOnAxis() {
  9280. const te = this.elements;
  9281. const scaleXSq = te[ 0 ] * te[ 0 ] + te[ 1 ] * te[ 1 ] + te[ 2 ] * te[ 2 ];
  9282. const scaleYSq = te[ 4 ] * te[ 4 ] + te[ 5 ] * te[ 5 ] + te[ 6 ] * te[ 6 ];
  9283. const scaleZSq = te[ 8 ] * te[ 8 ] + te[ 9 ] * te[ 9 ] + te[ 10 ] * te[ 10 ];
  9284. return Math.sqrt( Math.max( scaleXSq, scaleYSq, scaleZSq ) );
  9285. }
  9286. /**
  9287. * Sets this matrix as a translation transform from the given vector.
  9288. *
  9289. * @param {number|Vector3} x - The amount to translate in the X axis or alternatively a translation vector.
  9290. * @param {number} y - The amount to translate in the Y axis.
  9291. * @param {number} z - The amount to translate in the z axis.
  9292. * @return {Matrix4} A reference to this matrix.
  9293. */
  9294. makeTranslation( x, y, z ) {
  9295. if ( x.isVector3 ) {
  9296. this.set(
  9297. 1, 0, 0, x.x,
  9298. 0, 1, 0, x.y,
  9299. 0, 0, 1, x.z,
  9300. 0, 0, 0, 1
  9301. );
  9302. } else {
  9303. this.set(
  9304. 1, 0, 0, x,
  9305. 0, 1, 0, y,
  9306. 0, 0, 1, z,
  9307. 0, 0, 0, 1
  9308. );
  9309. }
  9310. return this;
  9311. }
  9312. /**
  9313. * Sets this matrix as a rotational transformation around the X axis by
  9314. * the given angle.
  9315. *
  9316. * @param {number} theta - The rotation in radians.
  9317. * @return {Matrix4} A reference to this matrix.
  9318. */
  9319. makeRotationX( theta ) {
  9320. const c = Math.cos( theta ), s = Math.sin( theta );
  9321. this.set(
  9322. 1, 0, 0, 0,
  9323. 0, c, - s, 0,
  9324. 0, s, c, 0,
  9325. 0, 0, 0, 1
  9326. );
  9327. return this;
  9328. }
  9329. /**
  9330. * Sets this matrix as a rotational transformation around the Y axis by
  9331. * the given angle.
  9332. *
  9333. * @param {number} theta - The rotation in radians.
  9334. * @return {Matrix4} A reference to this matrix.
  9335. */
  9336. makeRotationY( theta ) {
  9337. const c = Math.cos( theta ), s = Math.sin( theta );
  9338. this.set(
  9339. c, 0, s, 0,
  9340. 0, 1, 0, 0,
  9341. - s, 0, c, 0,
  9342. 0, 0, 0, 1
  9343. );
  9344. return this;
  9345. }
  9346. /**
  9347. * Sets this matrix as a rotational transformation around the Z axis by
  9348. * the given angle.
  9349. *
  9350. * @param {number} theta - The rotation in radians.
  9351. * @return {Matrix4} A reference to this matrix.
  9352. */
  9353. makeRotationZ( theta ) {
  9354. const c = Math.cos( theta ), s = Math.sin( theta );
  9355. this.set(
  9356. c, - s, 0, 0,
  9357. s, c, 0, 0,
  9358. 0, 0, 1, 0,
  9359. 0, 0, 0, 1
  9360. );
  9361. return this;
  9362. }
  9363. /**
  9364. * Sets this matrix as a rotational transformation around the given axis by
  9365. * the given angle.
  9366. *
  9367. * This is a somewhat controversial but mathematically sound alternative to
  9368. * rotating via Quaternions. See the discussion [here](https://www.gamedev.net/articles/programming/math-and-physics/do-we-really-need-quaternions-r1199).
  9369. *
  9370. * @param {Vector3} axis - The normalized rotation axis.
  9371. * @param {number} angle - The rotation in radians.
  9372. * @return {Matrix4} A reference to this matrix.
  9373. */
  9374. makeRotationAxis( axis, angle ) {
  9375. // Based on http://www.gamedev.net/reference/articles/article1199.asp
  9376. const c = Math.cos( angle );
  9377. const s = Math.sin( angle );
  9378. const t = 1 - c;
  9379. const x = axis.x, y = axis.y, z = axis.z;
  9380. const tx = t * x, ty = t * y;
  9381. this.set(
  9382. tx * x + c, tx * y - s * z, tx * z + s * y, 0,
  9383. tx * y + s * z, ty * y + c, ty * z - s * x, 0,
  9384. tx * z - s * y, ty * z + s * x, t * z * z + c, 0,
  9385. 0, 0, 0, 1
  9386. );
  9387. return this;
  9388. }
  9389. /**
  9390. * Sets this matrix as a scale transformation.
  9391. *
  9392. * @param {number} x - The amount to scale in the X axis.
  9393. * @param {number} y - The amount to scale in the Y axis.
  9394. * @param {number} z - The amount to scale in the Z axis.
  9395. * @return {Matrix4} A reference to this matrix.
  9396. */
  9397. makeScale( x, y, z ) {
  9398. this.set(
  9399. x, 0, 0, 0,
  9400. 0, y, 0, 0,
  9401. 0, 0, z, 0,
  9402. 0, 0, 0, 1
  9403. );
  9404. return this;
  9405. }
  9406. /**
  9407. * Sets this matrix as a shear transformation.
  9408. *
  9409. * @param {number} xy - The amount to shear X by Y.
  9410. * @param {number} xz - The amount to shear X by Z.
  9411. * @param {number} yx - The amount to shear Y by X.
  9412. * @param {number} yz - The amount to shear Y by Z.
  9413. * @param {number} zx - The amount to shear Z by X.
  9414. * @param {number} zy - The amount to shear Z by Y.
  9415. * @return {Matrix4} A reference to this matrix.
  9416. */
  9417. makeShear( xy, xz, yx, yz, zx, zy ) {
  9418. this.set(
  9419. 1, yx, zx, 0,
  9420. xy, 1, zy, 0,
  9421. xz, yz, 1, 0,
  9422. 0, 0, 0, 1
  9423. );
  9424. return this;
  9425. }
  9426. /**
  9427. * Sets this matrix to the transformation composed of the given position,
  9428. * rotation (Quaternion) and scale.
  9429. *
  9430. * @param {Vector3} position - The position vector.
  9431. * @param {Quaternion} quaternion - The rotation as a Quaternion.
  9432. * @param {Vector3} scale - The scale vector.
  9433. * @return {Matrix4} A reference to this matrix.
  9434. */
  9435. compose( position, quaternion, scale ) {
  9436. const te = this.elements;
  9437. const x = quaternion._x, y = quaternion._y, z = quaternion._z, w = quaternion._w;
  9438. const x2 = x + x, y2 = y + y, z2 = z + z;
  9439. const xx = x * x2, xy = x * y2, xz = x * z2;
  9440. const yy = y * y2, yz = y * z2, zz = z * z2;
  9441. const wx = w * x2, wy = w * y2, wz = w * z2;
  9442. const sx = scale.x, sy = scale.y, sz = scale.z;
  9443. te[ 0 ] = ( 1 - ( yy + zz ) ) * sx;
  9444. te[ 1 ] = ( xy + wz ) * sx;
  9445. te[ 2 ] = ( xz - wy ) * sx;
  9446. te[ 3 ] = 0;
  9447. te[ 4 ] = ( xy - wz ) * sy;
  9448. te[ 5 ] = ( 1 - ( xx + zz ) ) * sy;
  9449. te[ 6 ] = ( yz + wx ) * sy;
  9450. te[ 7 ] = 0;
  9451. te[ 8 ] = ( xz + wy ) * sz;
  9452. te[ 9 ] = ( yz - wx ) * sz;
  9453. te[ 10 ] = ( 1 - ( xx + yy ) ) * sz;
  9454. te[ 11 ] = 0;
  9455. te[ 12 ] = position.x;
  9456. te[ 13 ] = position.y;
  9457. te[ 14 ] = position.z;
  9458. te[ 15 ] = 1;
  9459. return this;
  9460. }
  9461. /**
  9462. * Decomposes this matrix into its position, rotation and scale components
  9463. * and provides the result in the given objects.
  9464. *
  9465. * Note: Not all matrices are decomposable in this way. For example, if an
  9466. * object has a non-uniformly scaled parent, then the object's world matrix
  9467. * may not be decomposable, and this method may not be appropriate.
  9468. *
  9469. * @param {Vector3} position - The position vector.
  9470. * @param {Quaternion} quaternion - The rotation as a Quaternion.
  9471. * @param {Vector3} scale - The scale vector.
  9472. * @return {Matrix4} A reference to this matrix.
  9473. */
  9474. decompose( position, quaternion, scale ) {
  9475. const te = this.elements;
  9476. position.x = te[ 12 ];
  9477. position.y = te[ 13 ];
  9478. position.z = te[ 14 ];
  9479. if ( this.determinant() === 0 ) {
  9480. scale.set( 1, 1, 1 );
  9481. quaternion.identity();
  9482. return this;
  9483. }
  9484. let sx = _v1$5.set( te[ 0 ], te[ 1 ], te[ 2 ] ).length();
  9485. const sy = _v1$5.set( te[ 4 ], te[ 5 ], te[ 6 ] ).length();
  9486. const sz = _v1$5.set( te[ 8 ], te[ 9 ], te[ 10 ] ).length();
  9487. // if determine is negative, we need to invert one scale
  9488. const det = this.determinant();
  9489. if ( det < 0 ) sx = - sx;
  9490. // scale the rotation part
  9491. _m1$2.copy( this );
  9492. const invSX = 1 / sx;
  9493. const invSY = 1 / sy;
  9494. const invSZ = 1 / sz;
  9495. _m1$2.elements[ 0 ] *= invSX;
  9496. _m1$2.elements[ 1 ] *= invSX;
  9497. _m1$2.elements[ 2 ] *= invSX;
  9498. _m1$2.elements[ 4 ] *= invSY;
  9499. _m1$2.elements[ 5 ] *= invSY;
  9500. _m1$2.elements[ 6 ] *= invSY;
  9501. _m1$2.elements[ 8 ] *= invSZ;
  9502. _m1$2.elements[ 9 ] *= invSZ;
  9503. _m1$2.elements[ 10 ] *= invSZ;
  9504. quaternion.setFromRotationMatrix( _m1$2 );
  9505. scale.x = sx;
  9506. scale.y = sy;
  9507. scale.z = sz;
  9508. return this;
  9509. }
  9510. /**
  9511. * Creates a perspective projection matrix. This is used internally by
  9512. * {@link PerspectiveCamera#updateProjectionMatrix}.
  9513. * @param {number} left - Left boundary of the viewing frustum at the near plane.
  9514. * @param {number} right - Right boundary of the viewing frustum at the near plane.
  9515. * @param {number} top - Top boundary of the viewing frustum at the near plane.
  9516. * @param {number} bottom - Bottom boundary of the viewing frustum at the near plane.
  9517. * @param {number} near - The distance from the camera to the near plane.
  9518. * @param {number} far - The distance from the camera to the far plane.
  9519. * @param {(WebGLCoordinateSystem|WebGPUCoordinateSystem)} [coordinateSystem=WebGLCoordinateSystem] - The coordinate system.
  9520. * @param {boolean} [reversedDepth=false] - Whether to use a reversed depth.
  9521. * @return {Matrix4} A reference to this matrix.
  9522. */
  9523. makePerspective( left, right, top, bottom, near, far, coordinateSystem = WebGLCoordinateSystem, reversedDepth = false ) {
  9524. const te = this.elements;
  9525. const x = 2 * near / ( right - left );
  9526. const y = 2 * near / ( top - bottom );
  9527. const a = ( right + left ) / ( right - left );
  9528. const b = ( top + bottom ) / ( top - bottom );
  9529. let c, d;
  9530. if ( reversedDepth ) {
  9531. c = near / ( far - near );
  9532. d = ( far * near ) / ( far - near );
  9533. } else {
  9534. if ( coordinateSystem === WebGLCoordinateSystem ) {
  9535. c = - ( far + near ) / ( far - near );
  9536. d = ( -2 * far * near ) / ( far - near );
  9537. } else if ( coordinateSystem === WebGPUCoordinateSystem ) {
  9538. c = - far / ( far - near );
  9539. d = ( - far * near ) / ( far - near );
  9540. } else {
  9541. throw new Error( 'THREE.Matrix4.makePerspective(): Invalid coordinate system: ' + coordinateSystem );
  9542. }
  9543. }
  9544. te[ 0 ] = x; te[ 4 ] = 0; te[ 8 ] = a; te[ 12 ] = 0;
  9545. te[ 1 ] = 0; te[ 5 ] = y; te[ 9 ] = b; te[ 13 ] = 0;
  9546. te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = c; te[ 14 ] = d;
  9547. te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = -1; te[ 15 ] = 0;
  9548. return this;
  9549. }
  9550. /**
  9551. * Creates a orthographic projection matrix. This is used internally by
  9552. * {@link OrthographicCamera#updateProjectionMatrix}.
  9553. * @param {number} left - Left boundary of the viewing frustum at the near plane.
  9554. * @param {number} right - Right boundary of the viewing frustum at the near plane.
  9555. * @param {number} top - Top boundary of the viewing frustum at the near plane.
  9556. * @param {number} bottom - Bottom boundary of the viewing frustum at the near plane.
  9557. * @param {number} near - The distance from the camera to the near plane.
  9558. * @param {number} far - The distance from the camera to the far plane.
  9559. * @param {(WebGLCoordinateSystem|WebGPUCoordinateSystem)} [coordinateSystem=WebGLCoordinateSystem] - The coordinate system.
  9560. * @param {boolean} [reversedDepth=false] - Whether to use a reversed depth.
  9561. * @return {Matrix4} A reference to this matrix.
  9562. */
  9563. makeOrthographic( left, right, top, bottom, near, far, coordinateSystem = WebGLCoordinateSystem, reversedDepth = false ) {
  9564. const te = this.elements;
  9565. const x = 2 / ( right - left );
  9566. const y = 2 / ( top - bottom );
  9567. const a = - ( right + left ) / ( right - left );
  9568. const b = - ( top + bottom ) / ( top - bottom );
  9569. let c, d;
  9570. if ( reversedDepth ) {
  9571. c = 1 / ( far - near );
  9572. d = far / ( far - near );
  9573. } else {
  9574. if ( coordinateSystem === WebGLCoordinateSystem ) {
  9575. c = -2 / ( far - near );
  9576. d = - ( far + near ) / ( far - near );
  9577. } else if ( coordinateSystem === WebGPUCoordinateSystem ) {
  9578. c = -1 / ( far - near );
  9579. d = - near / ( far - near );
  9580. } else {
  9581. throw new Error( 'THREE.Matrix4.makeOrthographic(): Invalid coordinate system: ' + coordinateSystem );
  9582. }
  9583. }
  9584. te[ 0 ] = x; te[ 4 ] = 0; te[ 8 ] = 0; te[ 12 ] = a;
  9585. te[ 1 ] = 0; te[ 5 ] = y; te[ 9 ] = 0; te[ 13 ] = b;
  9586. te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = c; te[ 14 ] = d;
  9587. te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = 0; te[ 15 ] = 1;
  9588. return this;
  9589. }
  9590. /**
  9591. * Returns `true` if this matrix is equal with the given one.
  9592. *
  9593. * @param {Matrix4} matrix - The matrix to test for equality.
  9594. * @return {boolean} Whether this matrix is equal with the given one.
  9595. */
  9596. equals( matrix ) {
  9597. const te = this.elements;
  9598. const me = matrix.elements;
  9599. for ( let i = 0; i < 16; i ++ ) {
  9600. if ( te[ i ] !== me[ i ] ) return false;
  9601. }
  9602. return true;
  9603. }
  9604. /**
  9605. * Sets the elements of the matrix from the given array.
  9606. *
  9607. * @param {Array<number>} array - The matrix elements in column-major order.
  9608. * @param {number} [offset=0] - Index of the first element in the array.
  9609. * @return {Matrix4} A reference to this matrix.
  9610. */
  9611. fromArray( array, offset = 0 ) {
  9612. for ( let i = 0; i < 16; i ++ ) {
  9613. this.elements[ i ] = array[ i + offset ];
  9614. }
  9615. return this;
  9616. }
  9617. /**
  9618. * Writes the elements of this matrix to the given array. If no array is provided,
  9619. * the method returns a new instance.
  9620. *
  9621. * @param {Array<number>} [array=[]] - The target array holding the matrix elements in column-major order.
  9622. * @param {number} [offset=0] - Index of the first element in the array.
  9623. * @return {Array<number>} The matrix elements in column-major order.
  9624. */
  9625. toArray( array = [], offset = 0 ) {
  9626. const te = this.elements;
  9627. array[ offset ] = te[ 0 ];
  9628. array[ offset + 1 ] = te[ 1 ];
  9629. array[ offset + 2 ] = te[ 2 ];
  9630. array[ offset + 3 ] = te[ 3 ];
  9631. array[ offset + 4 ] = te[ 4 ];
  9632. array[ offset + 5 ] = te[ 5 ];
  9633. array[ offset + 6 ] = te[ 6 ];
  9634. array[ offset + 7 ] = te[ 7 ];
  9635. array[ offset + 8 ] = te[ 8 ];
  9636. array[ offset + 9 ] = te[ 9 ];
  9637. array[ offset + 10 ] = te[ 10 ];
  9638. array[ offset + 11 ] = te[ 11 ];
  9639. array[ offset + 12 ] = te[ 12 ];
  9640. array[ offset + 13 ] = te[ 13 ];
  9641. array[ offset + 14 ] = te[ 14 ];
  9642. array[ offset + 15 ] = te[ 15 ];
  9643. return array;
  9644. }
  9645. }
  9646. const _v1$5 = /*@__PURE__*/ new Vector3();
  9647. const _m1$2 = /*@__PURE__*/ new Matrix4();
  9648. const _zero = /*@__PURE__*/ new Vector3( 0, 0, 0 );
  9649. const _one = /*@__PURE__*/ new Vector3( 1, 1, 1 );
  9650. const _x = /*@__PURE__*/ new Vector3();
  9651. const _y = /*@__PURE__*/ new Vector3();
  9652. const _z = /*@__PURE__*/ new Vector3();
  9653. const _matrix$2 = /*@__PURE__*/ new Matrix4();
  9654. const _quaternion$3 = /*@__PURE__*/ new Quaternion();
  9655. /**
  9656. * A class representing Euler angles.
  9657. *
  9658. * Euler angles describe a rotational transformation by rotating an object on
  9659. * its various axes in specified amounts per axis, and a specified axis
  9660. * order.
  9661. *
  9662. * Iterating through an instance will yield its components (x, y, z,
  9663. * order) in the corresponding order.
  9664. *
  9665. * ```js
  9666. * const a = new THREE.Euler( 0, 1, 1.57, 'XYZ' );
  9667. * const b = new THREE.Vector3( 1, 0, 1 );
  9668. * b.applyEuler(a);
  9669. * ```
  9670. */
  9671. class Euler {
  9672. /**
  9673. * Constructs a new euler instance.
  9674. *
  9675. * @param {number} [x=0] - The angle of the x axis in radians.
  9676. * @param {number} [y=0] - The angle of the y axis in radians.
  9677. * @param {number} [z=0] - The angle of the z axis in radians.
  9678. * @param {string} [order=Euler.DEFAULT_ORDER] - A string representing the order that the rotations are applied.
  9679. */
  9680. constructor( x = 0, y = 0, z = 0, order = Euler.DEFAULT_ORDER ) {
  9681. /**
  9682. * This flag can be used for type testing.
  9683. *
  9684. * @type {boolean}
  9685. * @readonly
  9686. * @default true
  9687. */
  9688. this.isEuler = true;
  9689. this._x = x;
  9690. this._y = y;
  9691. this._z = z;
  9692. this._order = order;
  9693. }
  9694. /**
  9695. * The angle of the x axis in radians.
  9696. *
  9697. * @type {number}
  9698. * @default 0
  9699. */
  9700. get x() {
  9701. return this._x;
  9702. }
  9703. set x( value ) {
  9704. this._x = value;
  9705. this._onChangeCallback();
  9706. }
  9707. /**
  9708. * The angle of the y axis in radians.
  9709. *
  9710. * @type {number}
  9711. * @default 0
  9712. */
  9713. get y() {
  9714. return this._y;
  9715. }
  9716. set y( value ) {
  9717. this._y = value;
  9718. this._onChangeCallback();
  9719. }
  9720. /**
  9721. * The angle of the z axis in radians.
  9722. *
  9723. * @type {number}
  9724. * @default 0
  9725. */
  9726. get z() {
  9727. return this._z;
  9728. }
  9729. set z( value ) {
  9730. this._z = value;
  9731. this._onChangeCallback();
  9732. }
  9733. /**
  9734. * A string representing the order that the rotations are applied.
  9735. *
  9736. * @type {string}
  9737. * @default 'XYZ'
  9738. */
  9739. get order() {
  9740. return this._order;
  9741. }
  9742. set order( value ) {
  9743. this._order = value;
  9744. this._onChangeCallback();
  9745. }
  9746. /**
  9747. * Sets the Euler components.
  9748. *
  9749. * @param {number} x - The angle of the x axis in radians.
  9750. * @param {number} y - The angle of the y axis in radians.
  9751. * @param {number} z - The angle of the z axis in radians.
  9752. * @param {string} [order] - A string representing the order that the rotations are applied.
  9753. * @return {Euler} A reference to this Euler instance.
  9754. */
  9755. set( x, y, z, order = this._order ) {
  9756. this._x = x;
  9757. this._y = y;
  9758. this._z = z;
  9759. this._order = order;
  9760. this._onChangeCallback();
  9761. return this;
  9762. }
  9763. /**
  9764. * Returns a new Euler instance with copied values from this instance.
  9765. *
  9766. * @return {Euler} A clone of this instance.
  9767. */
  9768. clone() {
  9769. return new this.constructor( this._x, this._y, this._z, this._order );
  9770. }
  9771. /**
  9772. * Copies the values of the given Euler instance to this instance.
  9773. *
  9774. * @param {Euler} euler - The Euler instance to copy.
  9775. * @return {Euler} A reference to this Euler instance.
  9776. */
  9777. copy( euler ) {
  9778. this._x = euler._x;
  9779. this._y = euler._y;
  9780. this._z = euler._z;
  9781. this._order = euler._order;
  9782. this._onChangeCallback();
  9783. return this;
  9784. }
  9785. /**
  9786. * Sets the angles of this Euler instance from a pure rotation matrix.
  9787. *
  9788. * @param {Matrix4} m - A 4x4 matrix of which the upper 3x3 of matrix is a pure rotation matrix (i.e. unscaled).
  9789. * @param {string} [order] - A string representing the order that the rotations are applied.
  9790. * @param {boolean} [update=true] - Whether the internal `onChange` callback should be executed or not.
  9791. * @return {Euler} A reference to this Euler instance.
  9792. */
  9793. setFromRotationMatrix( m, order = this._order, update = true ) {
  9794. const te = m.elements;
  9795. const m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ];
  9796. const m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ];
  9797. const m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];
  9798. switch ( order ) {
  9799. case 'XYZ':
  9800. this._y = Math.asin( clamp( m13, -1, 1 ) );
  9801. if ( Math.abs( m13 ) < 0.9999999 ) {
  9802. this._x = Math.atan2( - m23, m33 );
  9803. this._z = Math.atan2( - m12, m11 );
  9804. } else {
  9805. this._x = Math.atan2( m32, m22 );
  9806. this._z = 0;
  9807. }
  9808. break;
  9809. case 'YXZ':
  9810. this._x = Math.asin( - clamp( m23, -1, 1 ) );
  9811. if ( Math.abs( m23 ) < 0.9999999 ) {
  9812. this._y = Math.atan2( m13, m33 );
  9813. this._z = Math.atan2( m21, m22 );
  9814. } else {
  9815. this._y = Math.atan2( - m31, m11 );
  9816. this._z = 0;
  9817. }
  9818. break;
  9819. case 'ZXY':
  9820. this._x = Math.asin( clamp( m32, -1, 1 ) );
  9821. if ( Math.abs( m32 ) < 0.9999999 ) {
  9822. this._y = Math.atan2( - m31, m33 );
  9823. this._z = Math.atan2( - m12, m22 );
  9824. } else {
  9825. this._y = 0;
  9826. this._z = Math.atan2( m21, m11 );
  9827. }
  9828. break;
  9829. case 'ZYX':
  9830. this._y = Math.asin( - clamp( m31, -1, 1 ) );
  9831. if ( Math.abs( m31 ) < 0.9999999 ) {
  9832. this._x = Math.atan2( m32, m33 );
  9833. this._z = Math.atan2( m21, m11 );
  9834. } else {
  9835. this._x = 0;
  9836. this._z = Math.atan2( - m12, m22 );
  9837. }
  9838. break;
  9839. case 'YZX':
  9840. this._z = Math.asin( clamp( m21, -1, 1 ) );
  9841. if ( Math.abs( m21 ) < 0.9999999 ) {
  9842. this._x = Math.atan2( - m23, m22 );
  9843. this._y = Math.atan2( - m31, m11 );
  9844. } else {
  9845. this._x = 0;
  9846. this._y = Math.atan2( m13, m33 );
  9847. }
  9848. break;
  9849. case 'XZY':
  9850. this._z = Math.asin( - clamp( m12, -1, 1 ) );
  9851. if ( Math.abs( m12 ) < 0.9999999 ) {
  9852. this._x = Math.atan2( m32, m22 );
  9853. this._y = Math.atan2( m13, m11 );
  9854. } else {
  9855. this._x = Math.atan2( - m23, m33 );
  9856. this._y = 0;
  9857. }
  9858. break;
  9859. default:
  9860. warn( 'Euler: .setFromRotationMatrix() encountered an unknown order: ' + order );
  9861. }
  9862. this._order = order;
  9863. if ( update === true ) this._onChangeCallback();
  9864. return this;
  9865. }
  9866. /**
  9867. * Sets the angles of this Euler instance from a normalized quaternion.
  9868. *
  9869. * @param {Quaternion} q - A normalized Quaternion.
  9870. * @param {string} [order] - A string representing the order that the rotations are applied.
  9871. * @param {boolean} [update=true] - Whether the internal `onChange` callback should be executed or not.
  9872. * @return {Euler} A reference to this Euler instance.
  9873. */
  9874. setFromQuaternion( q, order, update ) {
  9875. _matrix$2.makeRotationFromQuaternion( q );
  9876. return this.setFromRotationMatrix( _matrix$2, order, update );
  9877. }
  9878. /**
  9879. * Sets the angles of this Euler instance from the given vector.
  9880. *
  9881. * @param {Vector3} v - The vector.
  9882. * @param {string} [order] - A string representing the order that the rotations are applied.
  9883. * @return {Euler} A reference to this Euler instance.
  9884. */
  9885. setFromVector3( v, order = this._order ) {
  9886. return this.set( v.x, v.y, v.z, order );
  9887. }
  9888. /**
  9889. * Resets the euler angle with a new order by creating a quaternion from this
  9890. * euler angle and then setting this euler angle with the quaternion and the
  9891. * new order.
  9892. *
  9893. * Warning: This discards revolution information.
  9894. *
  9895. * @param {string} [newOrder] - A string representing the new order that the rotations are applied.
  9896. * @return {Euler} A reference to this Euler instance.
  9897. */
  9898. reorder( newOrder ) {
  9899. _quaternion$3.setFromEuler( this );
  9900. return this.setFromQuaternion( _quaternion$3, newOrder );
  9901. }
  9902. /**
  9903. * Returns `true` if this Euler instance is equal with the given one.
  9904. *
  9905. * @param {Euler} euler - The Euler instance to test for equality.
  9906. * @return {boolean} Whether this Euler instance is equal with the given one.
  9907. */
  9908. equals( euler ) {
  9909. return ( euler._x === this._x ) && ( euler._y === this._y ) && ( euler._z === this._z ) && ( euler._order === this._order );
  9910. }
  9911. /**
  9912. * Sets this Euler instance's components to values from the given array. The first three
  9913. * entries of the array are assign to the x,y and z components. An optional fourth entry
  9914. * defines the Euler order.
  9915. *
  9916. * @param {Array<number,number,number,?string>} array - An array holding the Euler component values.
  9917. * @return {Euler} A reference to this Euler instance.
  9918. */
  9919. fromArray( array ) {
  9920. this._x = array[ 0 ];
  9921. this._y = array[ 1 ];
  9922. this._z = array[ 2 ];
  9923. if ( array[ 3 ] !== undefined ) this._order = array[ 3 ];
  9924. this._onChangeCallback();
  9925. return this;
  9926. }
  9927. /**
  9928. * Writes the components of this Euler instance to the given array. If no array is provided,
  9929. * the method returns a new instance.
  9930. *
  9931. * @param {Array<number,number,number,string>} [array=[]] - The target array holding the Euler components.
  9932. * @param {number} [offset=0] - Index of the first element in the array.
  9933. * @return {Array<number,number,number,string>} The Euler components.
  9934. */
  9935. toArray( array = [], offset = 0 ) {
  9936. array[ offset ] = this._x;
  9937. array[ offset + 1 ] = this._y;
  9938. array[ offset + 2 ] = this._z;
  9939. array[ offset + 3 ] = this._order;
  9940. return array;
  9941. }
  9942. _onChange( callback ) {
  9943. this._onChangeCallback = callback;
  9944. return this;
  9945. }
  9946. _onChangeCallback() {}
  9947. *[ Symbol.iterator ]() {
  9948. yield this._x;
  9949. yield this._y;
  9950. yield this._z;
  9951. yield this._order;
  9952. }
  9953. }
  9954. /**
  9955. * The default Euler angle order.
  9956. *
  9957. * @static
  9958. * @type {string}
  9959. * @default 'XYZ'
  9960. */
  9961. Euler.DEFAULT_ORDER = 'XYZ';
  9962. /**
  9963. * A layers object assigns an 3D object to 1 or more of 32
  9964. * layers numbered `0` to `31` - internally the layers are stored as a
  9965. * bit mask], and by default all 3D objects are a member of layer `0`.
  9966. *
  9967. * This can be used to control visibility - an object must share a layer with
  9968. * a camera to be visible when that camera's view is
  9969. * rendered.
  9970. *
  9971. * All classes that inherit from {@link Object3D} have an `layers` property which
  9972. * is an instance of this class.
  9973. */
  9974. class Layers {
  9975. /**
  9976. * Constructs a new layers instance, with membership
  9977. * initially set to layer `0`.
  9978. */
  9979. constructor() {
  9980. /**
  9981. * A bit mask storing which of the 32 layers this layers object is currently
  9982. * a member of.
  9983. *
  9984. * @type {number}
  9985. */
  9986. this.mask = 1 | 0;
  9987. }
  9988. /**
  9989. * Sets membership to the given layer, and remove membership all other layers.
  9990. *
  9991. * @param {number} layer - The layer to set.
  9992. */
  9993. set( layer ) {
  9994. this.mask = ( 1 << layer | 0 ) >>> 0;
  9995. }
  9996. /**
  9997. * Adds membership of the given layer.
  9998. *
  9999. * @param {number} layer - The layer to enable.
  10000. */
  10001. enable( layer ) {
  10002. this.mask |= 1 << layer | 0;
  10003. }
  10004. /**
  10005. * Adds membership to all layers.
  10006. */
  10007. enableAll() {
  10008. this.mask = 0xffffffff | 0;
  10009. }
  10010. /**
  10011. * Toggles the membership of the given layer.
  10012. *
  10013. * @param {number} layer - The layer to toggle.
  10014. */
  10015. toggle( layer ) {
  10016. this.mask ^= 1 << layer | 0;
  10017. }
  10018. /**
  10019. * Removes membership of the given layer.
  10020. *
  10021. * @param {number} layer - The layer to enable.
  10022. */
  10023. disable( layer ) {
  10024. this.mask &= ~ ( 1 << layer | 0 );
  10025. }
  10026. /**
  10027. * Removes the membership from all layers.
  10028. */
  10029. disableAll() {
  10030. this.mask = 0;
  10031. }
  10032. /**
  10033. * Returns `true` if this and the given layers object have at least one
  10034. * layer in common.
  10035. *
  10036. * @param {Layers} layers - The layers to test.
  10037. * @return {boolean } Whether this and the given layers object have at least one layer in common or not.
  10038. */
  10039. test( layers ) {
  10040. return ( this.mask & layers.mask ) !== 0;
  10041. }
  10042. /**
  10043. * Returns `true` if the given layer is enabled.
  10044. *
  10045. * @param {number} layer - The layer to test.
  10046. * @return {boolean } Whether the given layer is enabled or not.
  10047. */
  10048. isEnabled( layer ) {
  10049. return ( this.mask & ( 1 << layer | 0 ) ) !== 0;
  10050. }
  10051. }
  10052. let _object3DId = 0;
  10053. const _v1$4 = /*@__PURE__*/ new Vector3();
  10054. const _q1 = /*@__PURE__*/ new Quaternion();
  10055. const _m1$1 = /*@__PURE__*/ new Matrix4();
  10056. const _target = /*@__PURE__*/ new Vector3();
  10057. const _position$3 = /*@__PURE__*/ new Vector3();
  10058. const _scale$2 = /*@__PURE__*/ new Vector3();
  10059. const _quaternion$2 = /*@__PURE__*/ new Quaternion();
  10060. const _xAxis = /*@__PURE__*/ new Vector3( 1, 0, 0 );
  10061. const _yAxis = /*@__PURE__*/ new Vector3( 0, 1, 0 );
  10062. const _zAxis = /*@__PURE__*/ new Vector3( 0, 0, 1 );
  10063. /**
  10064. * Fires when the object has been added to its parent object.
  10065. *
  10066. * @event Object3D#added
  10067. * @type {Object}
  10068. */
  10069. const _addedEvent = { type: 'added' };
  10070. /**
  10071. * Fires when the object has been removed from its parent object.
  10072. *
  10073. * @event Object3D#removed
  10074. * @type {Object}
  10075. */
  10076. const _removedEvent = { type: 'removed' };
  10077. /**
  10078. * Fires when a new child object has been added.
  10079. *
  10080. * @event Object3D#childadded
  10081. * @type {Object}
  10082. */
  10083. const _childaddedEvent = { type: 'childadded', child: null };
  10084. /**
  10085. * Fires when a child object has been removed.
  10086. *
  10087. * @event Object3D#childremoved
  10088. * @type {Object}
  10089. */
  10090. const _childremovedEvent = { type: 'childremoved', child: null };
  10091. /**
  10092. * This is the base class for most objects in three.js and provides a set of
  10093. * properties and methods for manipulating objects in 3D space.
  10094. *
  10095. * @augments EventDispatcher
  10096. */
  10097. class Object3D extends EventDispatcher {
  10098. /**
  10099. * Constructs a new 3D object.
  10100. */
  10101. constructor() {
  10102. super();
  10103. /**
  10104. * This flag can be used for type testing.
  10105. *
  10106. * @type {boolean}
  10107. * @readonly
  10108. * @default true
  10109. */
  10110. this.isObject3D = true;
  10111. /**
  10112. * The ID of the 3D object.
  10113. *
  10114. * @name Object3D#id
  10115. * @type {number}
  10116. * @readonly
  10117. */
  10118. Object.defineProperty( this, 'id', { value: _object3DId ++ } );
  10119. /**
  10120. * The UUID of the 3D object.
  10121. *
  10122. * @type {string}
  10123. * @readonly
  10124. */
  10125. this.uuid = generateUUID();
  10126. /**
  10127. * The name of the 3D object.
  10128. *
  10129. * @type {string}
  10130. */
  10131. this.name = '';
  10132. /**
  10133. * The type property is used for detecting the object type
  10134. * in context of serialization/deserialization.
  10135. *
  10136. * @type {string}
  10137. * @readonly
  10138. */
  10139. this.type = 'Object3D';
  10140. /**
  10141. * A reference to the parent object.
  10142. *
  10143. * @type {?Object3D}
  10144. * @default null
  10145. */
  10146. this.parent = null;
  10147. /**
  10148. * An array holding the child 3D objects of this instance.
  10149. *
  10150. * @type {Array<Object3D>}
  10151. */
  10152. this.children = [];
  10153. /**
  10154. * Defines the `up` direction of the 3D object which influences
  10155. * the orientation via methods like {@link Object3D#lookAt}.
  10156. *
  10157. * The default values for all 3D objects is defined by `Object3D.DEFAULT_UP`.
  10158. *
  10159. * @type {Vector3}
  10160. */
  10161. this.up = Object3D.DEFAULT_UP.clone();
  10162. const position = new Vector3();
  10163. const rotation = new Euler();
  10164. const quaternion = new Quaternion();
  10165. const scale = new Vector3( 1, 1, 1 );
  10166. function onRotationChange() {
  10167. quaternion.setFromEuler( rotation, false );
  10168. }
  10169. function onQuaternionChange() {
  10170. rotation.setFromQuaternion( quaternion, undefined, false );
  10171. }
  10172. rotation._onChange( onRotationChange );
  10173. quaternion._onChange( onQuaternionChange );
  10174. Object.defineProperties( this, {
  10175. /**
  10176. * Represents the object's local position.
  10177. *
  10178. * @name Object3D#position
  10179. * @type {Vector3}
  10180. * @default (0,0,0)
  10181. */
  10182. position: {
  10183. configurable: true,
  10184. enumerable: true,
  10185. value: position
  10186. },
  10187. /**
  10188. * Represents the object's local rotation as Euler angles, in radians.
  10189. *
  10190. * @name Object3D#rotation
  10191. * @type {Euler}
  10192. * @default (0,0,0)
  10193. */
  10194. rotation: {
  10195. configurable: true,
  10196. enumerable: true,
  10197. value: rotation
  10198. },
  10199. /**
  10200. * Represents the object's local rotation as Quaternions.
  10201. *
  10202. * @name Object3D#quaternion
  10203. * @type {Quaternion}
  10204. */
  10205. quaternion: {
  10206. configurable: true,
  10207. enumerable: true,
  10208. value: quaternion
  10209. },
  10210. /**
  10211. * Represents the object's local scale.
  10212. *
  10213. * @name Object3D#scale
  10214. * @type {Vector3}
  10215. * @default (1,1,1)
  10216. */
  10217. scale: {
  10218. configurable: true,
  10219. enumerable: true,
  10220. value: scale
  10221. },
  10222. /**
  10223. * Represents the object's model-view matrix.
  10224. *
  10225. * @name Object3D#modelViewMatrix
  10226. * @type {Matrix4}
  10227. */
  10228. modelViewMatrix: {
  10229. value: new Matrix4()
  10230. },
  10231. /**
  10232. * Represents the object's normal matrix.
  10233. *
  10234. * @name Object3D#normalMatrix
  10235. * @type {Matrix3}
  10236. */
  10237. normalMatrix: {
  10238. value: new Matrix3()
  10239. }
  10240. } );
  10241. /**
  10242. * Represents the object's transformation matrix in local space.
  10243. *
  10244. * @type {Matrix4}
  10245. */
  10246. this.matrix = new Matrix4();
  10247. /**
  10248. * Represents the object's transformation matrix in world space.
  10249. * If the 3D object has no parent, then it's identical to the local transformation matrix
  10250. *
  10251. * @type {Matrix4}
  10252. */
  10253. this.matrixWorld = new Matrix4();
  10254. /**
  10255. * When set to `true`, the engine automatically computes the local matrix from position,
  10256. * rotation and scale every frame.
  10257. *
  10258. * The default values for all 3D objects is defined by `Object3D.DEFAULT_MATRIX_AUTO_UPDATE`.
  10259. *
  10260. * @type {boolean}
  10261. * @default true
  10262. */
  10263. this.matrixAutoUpdate = Object3D.DEFAULT_MATRIX_AUTO_UPDATE;
  10264. /**
  10265. * When set to `true`, the engine automatically computes the world matrix from the current local
  10266. * matrix and the object's transformation hierarchy.
  10267. *
  10268. * The default values for all 3D objects is defined by `Object3D.DEFAULT_MATRIX_WORLD_AUTO_UPDATE`.
  10269. *
  10270. * @type {boolean}
  10271. * @default true
  10272. */
  10273. this.matrixWorldAutoUpdate = Object3D.DEFAULT_MATRIX_WORLD_AUTO_UPDATE; // checked by the renderer
  10274. /**
  10275. * When set to `true`, it calculates the world matrix in that frame and resets this property
  10276. * to `false`.
  10277. *
  10278. * @type {boolean}
  10279. * @default false
  10280. */
  10281. this.matrixWorldNeedsUpdate = false;
  10282. /**
  10283. * The layer membership of the 3D object. The 3D object is only visible if it has
  10284. * at least one layer in common with the camera in use. This property can also be
  10285. * used to filter out unwanted objects in ray-intersection tests when using {@link Raycaster}.
  10286. *
  10287. * @type {Layers}
  10288. */
  10289. this.layers = new Layers();
  10290. /**
  10291. * When set to `true`, the 3D object gets rendered.
  10292. *
  10293. * @type {boolean}
  10294. * @default true
  10295. */
  10296. this.visible = true;
  10297. /**
  10298. * When set to `true`, the 3D object gets rendered into shadow maps.
  10299. *
  10300. * @type {boolean}
  10301. * @default false
  10302. */
  10303. this.castShadow = false;
  10304. /**
  10305. * When set to `true`, the 3D object is affected by shadows in the scene.
  10306. *
  10307. * @type {boolean}
  10308. * @default false
  10309. */
  10310. this.receiveShadow = false;
  10311. /**
  10312. * When set to `true`, the 3D object is honored by view frustum culling.
  10313. *
  10314. * @type {boolean}
  10315. * @default true
  10316. */
  10317. this.frustumCulled = true;
  10318. /**
  10319. * This value allows the default rendering order of scene graph objects to be
  10320. * overridden although opaque and transparent objects remain sorted independently.
  10321. * When this property is set for an instance of {@link Group},all descendants
  10322. * objects will be sorted and rendered together. Sorting is from lowest to highest
  10323. * render order.
  10324. *
  10325. * @type {number}
  10326. * @default 0
  10327. */
  10328. this.renderOrder = 0;
  10329. /**
  10330. * An array holding the animation clips of the 3D object.
  10331. *
  10332. * @type {Array<AnimationClip>}
  10333. */
  10334. this.animations = [];
  10335. /**
  10336. * Custom depth material to be used when rendering to the depth map. Can only be used
  10337. * in context of meshes. When shadow-casting with a {@link DirectionalLight} or {@link SpotLight},
  10338. * if you are modifying vertex positions in the vertex shader you must specify a custom depth
  10339. * material for proper shadows.
  10340. *
  10341. * Only relevant in context of {@link WebGLRenderer}.
  10342. *
  10343. * @type {(Material|undefined)}
  10344. * @default undefined
  10345. */
  10346. this.customDepthMaterial = undefined;
  10347. /**
  10348. * Same as {@link Object3D#customDepthMaterial}, but used with {@link PointLight}.
  10349. *
  10350. * Only relevant in context of {@link WebGLRenderer}.
  10351. *
  10352. * @type {(Material|undefined)}
  10353. * @default undefined
  10354. */
  10355. this.customDistanceMaterial = undefined;
  10356. /**
  10357. * An object that can be used to store custom data about the 3D object. It
  10358. * should not hold references to functions as these will not be cloned.
  10359. *
  10360. * @type {Object}
  10361. */
  10362. this.userData = {};
  10363. }
  10364. /**
  10365. * A callback that is executed immediately before a 3D object is rendered to a shadow map.
  10366. *
  10367. * @param {Renderer|WebGLRenderer} renderer - The renderer.
  10368. * @param {Object3D} object - The 3D object.
  10369. * @param {Camera} camera - The camera that is used to render the scene.
  10370. * @param {Camera} shadowCamera - The shadow camera.
  10371. * @param {BufferGeometry} geometry - The 3D object's geometry.
  10372. * @param {Material} depthMaterial - The depth material.
  10373. * @param {Object} group - The geometry group data.
  10374. */
  10375. onBeforeShadow( /* renderer, object, camera, shadowCamera, geometry, depthMaterial, group */ ) {}
  10376. /**
  10377. * A callback that is executed immediately after a 3D object is rendered to a shadow map.
  10378. *
  10379. * @param {Renderer|WebGLRenderer} renderer - The renderer.
  10380. * @param {Object3D} object - The 3D object.
  10381. * @param {Camera} camera - The camera that is used to render the scene.
  10382. * @param {Camera} shadowCamera - The shadow camera.
  10383. * @param {BufferGeometry} geometry - The 3D object's geometry.
  10384. * @param {Material} depthMaterial - The depth material.
  10385. * @param {Object} group - The geometry group data.
  10386. */
  10387. onAfterShadow( /* renderer, object, camera, shadowCamera, geometry, depthMaterial, group */ ) {}
  10388. /**
  10389. * A callback that is executed immediately before a 3D object is rendered.
  10390. *
  10391. * @param {Renderer|WebGLRenderer} renderer - The renderer.
  10392. * @param {Object3D} object - The 3D object.
  10393. * @param {Camera} camera - The camera that is used to render the scene.
  10394. * @param {BufferGeometry} geometry - The 3D object's geometry.
  10395. * @param {Material} material - The 3D object's material.
  10396. * @param {Object} group - The geometry group data.
  10397. */
  10398. onBeforeRender( /* renderer, scene, camera, geometry, material, group */ ) {}
  10399. /**
  10400. * A callback that is executed immediately after a 3D object is rendered.
  10401. *
  10402. * @param {Renderer|WebGLRenderer} renderer - The renderer.
  10403. * @param {Object3D} object - The 3D object.
  10404. * @param {Camera} camera - The camera that is used to render the scene.
  10405. * @param {BufferGeometry} geometry - The 3D object's geometry.
  10406. * @param {Material} material - The 3D object's material.
  10407. * @param {Object} group - The geometry group data.
  10408. */
  10409. onAfterRender( /* renderer, scene, camera, geometry, material, group */ ) {}
  10410. /**
  10411. * Applies the given transformation matrix to the object and updates the object's position,
  10412. * rotation and scale.
  10413. *
  10414. * @param {Matrix4} matrix - The transformation matrix.
  10415. */
  10416. applyMatrix4( matrix ) {
  10417. if ( this.matrixAutoUpdate ) this.updateMatrix();
  10418. this.matrix.premultiply( matrix );
  10419. this.matrix.decompose( this.position, this.quaternion, this.scale );
  10420. }
  10421. /**
  10422. * Applies a rotation represented by given the quaternion to the 3D object.
  10423. *
  10424. * @param {Quaternion} q - The quaternion.
  10425. * @return {Object3D} A reference to this instance.
  10426. */
  10427. applyQuaternion( q ) {
  10428. this.quaternion.premultiply( q );
  10429. return this;
  10430. }
  10431. /**
  10432. * Sets the given rotation represented as an axis/angle couple to the 3D object.
  10433. *
  10434. * @param {Vector3} axis - The (normalized) axis vector.
  10435. * @param {number} angle - The angle in radians.
  10436. */
  10437. setRotationFromAxisAngle( axis, angle ) {
  10438. // assumes axis is normalized
  10439. this.quaternion.setFromAxisAngle( axis, angle );
  10440. }
  10441. /**
  10442. * Sets the given rotation represented as Euler angles to the 3D object.
  10443. *
  10444. * @param {Euler} euler - The Euler angles.
  10445. */
  10446. setRotationFromEuler( euler ) {
  10447. this.quaternion.setFromEuler( euler, true );
  10448. }
  10449. /**
  10450. * Sets the given rotation represented as rotation matrix to the 3D object.
  10451. *
  10452. * @param {Matrix4} m - Although a 4x4 matrix is expected, the upper 3x3 portion must be
  10453. * a pure rotation matrix (i.e, unscaled).
  10454. */
  10455. setRotationFromMatrix( m ) {
  10456. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  10457. this.quaternion.setFromRotationMatrix( m );
  10458. }
  10459. /**
  10460. * Sets the given rotation represented as a Quaternion to the 3D object.
  10461. *
  10462. * @param {Quaternion} q - The Quaternion
  10463. */
  10464. setRotationFromQuaternion( q ) {
  10465. // assumes q is normalized
  10466. this.quaternion.copy( q );
  10467. }
  10468. /**
  10469. * Rotates the 3D object along an axis in local space.
  10470. *
  10471. * @param {Vector3} axis - The (normalized) axis vector.
  10472. * @param {number} angle - The angle in radians.
  10473. * @return {Object3D} A reference to this instance.
  10474. */
  10475. rotateOnAxis( axis, angle ) {
  10476. // rotate object on axis in object space
  10477. // axis is assumed to be normalized
  10478. _q1.setFromAxisAngle( axis, angle );
  10479. this.quaternion.multiply( _q1 );
  10480. return this;
  10481. }
  10482. /**
  10483. * Rotates the 3D object along an axis in world space.
  10484. *
  10485. * @param {Vector3} axis - The (normalized) axis vector.
  10486. * @param {number} angle - The angle in radians.
  10487. * @return {Object3D} A reference to this instance.
  10488. */
  10489. rotateOnWorldAxis( axis, angle ) {
  10490. // rotate object on axis in world space
  10491. // axis is assumed to be normalized
  10492. // method assumes no rotated parent
  10493. _q1.setFromAxisAngle( axis, angle );
  10494. this.quaternion.premultiply( _q1 );
  10495. return this;
  10496. }
  10497. /**
  10498. * Rotates the 3D object around its X axis in local space.
  10499. *
  10500. * @param {number} angle - The angle in radians.
  10501. * @return {Object3D} A reference to this instance.
  10502. */
  10503. rotateX( angle ) {
  10504. return this.rotateOnAxis( _xAxis, angle );
  10505. }
  10506. /**
  10507. * Rotates the 3D object around its Y axis in local space.
  10508. *
  10509. * @param {number} angle - The angle in radians.
  10510. * @return {Object3D} A reference to this instance.
  10511. */
  10512. rotateY( angle ) {
  10513. return this.rotateOnAxis( _yAxis, angle );
  10514. }
  10515. /**
  10516. * Rotates the 3D object around its Z axis in local space.
  10517. *
  10518. * @param {number} angle - The angle in radians.
  10519. * @return {Object3D} A reference to this instance.
  10520. */
  10521. rotateZ( angle ) {
  10522. return this.rotateOnAxis( _zAxis, angle );
  10523. }
  10524. /**
  10525. * Translate the 3D object by a distance along the given axis in local space.
  10526. *
  10527. * @param {Vector3} axis - The (normalized) axis vector.
  10528. * @param {number} distance - The distance in world units.
  10529. * @return {Object3D} A reference to this instance.
  10530. */
  10531. translateOnAxis( axis, distance ) {
  10532. // translate object by distance along axis in object space
  10533. // axis is assumed to be normalized
  10534. _v1$4.copy( axis ).applyQuaternion( this.quaternion );
  10535. this.position.add( _v1$4.multiplyScalar( distance ) );
  10536. return this;
  10537. }
  10538. /**
  10539. * Translate the 3D object by a distance along its X-axis in local space.
  10540. *
  10541. * @param {number} distance - The distance in world units.
  10542. * @return {Object3D} A reference to this instance.
  10543. */
  10544. translateX( distance ) {
  10545. return this.translateOnAxis( _xAxis, distance );
  10546. }
  10547. /**
  10548. * Translate the 3D object by a distance along its Y-axis in local space.
  10549. *
  10550. * @param {number} distance - The distance in world units.
  10551. * @return {Object3D} A reference to this instance.
  10552. */
  10553. translateY( distance ) {
  10554. return this.translateOnAxis( _yAxis, distance );
  10555. }
  10556. /**
  10557. * Translate the 3D object by a distance along its Z-axis in local space.
  10558. *
  10559. * @param {number} distance - The distance in world units.
  10560. * @return {Object3D} A reference to this instance.
  10561. */
  10562. translateZ( distance ) {
  10563. return this.translateOnAxis( _zAxis, distance );
  10564. }
  10565. /**
  10566. * Converts the given vector from this 3D object's local space to world space.
  10567. *
  10568. * @param {Vector3} vector - The vector to convert.
  10569. * @return {Vector3} The converted vector.
  10570. */
  10571. localToWorld( vector ) {
  10572. this.updateWorldMatrix( true, false );
  10573. return vector.applyMatrix4( this.matrixWorld );
  10574. }
  10575. /**
  10576. * Converts the given vector from this 3D object's word space to local space.
  10577. *
  10578. * @param {Vector3} vector - The vector to convert.
  10579. * @return {Vector3} The converted vector.
  10580. */
  10581. worldToLocal( vector ) {
  10582. this.updateWorldMatrix( true, false );
  10583. return vector.applyMatrix4( _m1$1.copy( this.matrixWorld ).invert() );
  10584. }
  10585. /**
  10586. * Rotates the object to face a point in world space.
  10587. *
  10588. * This method does not support objects having non-uniformly-scaled parent(s).
  10589. *
  10590. * @param {number|Vector3} x - The x coordinate in world space. Alternatively, a vector representing a position in world space
  10591. * @param {number} [y] - The y coordinate in world space.
  10592. * @param {number} [z] - The z coordinate in world space.
  10593. */
  10594. lookAt( x, y, z ) {
  10595. // This method does not support objects having non-uniformly-scaled parent(s)
  10596. if ( x.isVector3 ) {
  10597. _target.copy( x );
  10598. } else {
  10599. _target.set( x, y, z );
  10600. }
  10601. const parent = this.parent;
  10602. this.updateWorldMatrix( true, false );
  10603. _position$3.setFromMatrixPosition( this.matrixWorld );
  10604. if ( this.isCamera || this.isLight ) {
  10605. _m1$1.lookAt( _position$3, _target, this.up );
  10606. } else {
  10607. _m1$1.lookAt( _target, _position$3, this.up );
  10608. }
  10609. this.quaternion.setFromRotationMatrix( _m1$1 );
  10610. if ( parent ) {
  10611. _m1$1.extractRotation( parent.matrixWorld );
  10612. _q1.setFromRotationMatrix( _m1$1 );
  10613. this.quaternion.premultiply( _q1.invert() );
  10614. }
  10615. }
  10616. /**
  10617. * Adds the given 3D object as a child to this 3D object. An arbitrary number of
  10618. * objects may be added. Any current parent on an object passed in here will be
  10619. * removed, since an object can have at most one parent.
  10620. *
  10621. * @fires Object3D#added
  10622. * @fires Object3D#childadded
  10623. * @param {Object3D} object - The 3D object to add.
  10624. * @return {Object3D} A reference to this instance.
  10625. */
  10626. add( object ) {
  10627. if ( arguments.length > 1 ) {
  10628. for ( let i = 0; i < arguments.length; i ++ ) {
  10629. this.add( arguments[ i ] );
  10630. }
  10631. return this;
  10632. }
  10633. if ( object === this ) {
  10634. error( 'Object3D.add: object can\'t be added as a child of itself.', object );
  10635. return this;
  10636. }
  10637. if ( object && object.isObject3D ) {
  10638. object.removeFromParent();
  10639. object.parent = this;
  10640. this.children.push( object );
  10641. object.dispatchEvent( _addedEvent );
  10642. _childaddedEvent.child = object;
  10643. this.dispatchEvent( _childaddedEvent );
  10644. _childaddedEvent.child = null;
  10645. } else {
  10646. error( 'Object3D.add: object not an instance of THREE.Object3D.', object );
  10647. }
  10648. return this;
  10649. }
  10650. /**
  10651. * Removes the given 3D object as child from this 3D object.
  10652. * An arbitrary number of objects may be removed.
  10653. *
  10654. * @fires Object3D#removed
  10655. * @fires Object3D#childremoved
  10656. * @param {Object3D} object - The 3D object to remove.
  10657. * @return {Object3D} A reference to this instance.
  10658. */
  10659. remove( object ) {
  10660. if ( arguments.length > 1 ) {
  10661. for ( let i = 0; i < arguments.length; i ++ ) {
  10662. this.remove( arguments[ i ] );
  10663. }
  10664. return this;
  10665. }
  10666. const index = this.children.indexOf( object );
  10667. if ( index !== -1 ) {
  10668. object.parent = null;
  10669. this.children.splice( index, 1 );
  10670. object.dispatchEvent( _removedEvent );
  10671. _childremovedEvent.child = object;
  10672. this.dispatchEvent( _childremovedEvent );
  10673. _childremovedEvent.child = null;
  10674. }
  10675. return this;
  10676. }
  10677. /**
  10678. * Removes this 3D object from its current parent.
  10679. *
  10680. * @fires Object3D#removed
  10681. * @fires Object3D#childremoved
  10682. * @return {Object3D} A reference to this instance.
  10683. */
  10684. removeFromParent() {
  10685. const parent = this.parent;
  10686. if ( parent !== null ) {
  10687. parent.remove( this );
  10688. }
  10689. return this;
  10690. }
  10691. /**
  10692. * Removes all child objects.
  10693. *
  10694. * @fires Object3D#removed
  10695. * @fires Object3D#childremoved
  10696. * @return {Object3D} A reference to this instance.
  10697. */
  10698. clear() {
  10699. return this.remove( ... this.children );
  10700. }
  10701. /**
  10702. * Adds the given 3D object as a child of this 3D object, while maintaining the object's world
  10703. * transform. This method does not support scene graphs having non-uniformly-scaled nodes(s).
  10704. *
  10705. * @fires Object3D#added
  10706. * @fires Object3D#childadded
  10707. * @param {Object3D} object - The 3D object to attach.
  10708. * @return {Object3D} A reference to this instance.
  10709. */
  10710. attach( object ) {
  10711. // adds object as a child of this, while maintaining the object's world transform
  10712. // Note: This method does not support scene graphs having non-uniformly-scaled nodes(s)
  10713. this.updateWorldMatrix( true, false );
  10714. _m1$1.copy( this.matrixWorld ).invert();
  10715. if ( object.parent !== null ) {
  10716. object.parent.updateWorldMatrix( true, false );
  10717. _m1$1.multiply( object.parent.matrixWorld );
  10718. }
  10719. object.applyMatrix4( _m1$1 );
  10720. object.removeFromParent();
  10721. object.parent = this;
  10722. this.children.push( object );
  10723. object.updateWorldMatrix( false, true );
  10724. object.dispatchEvent( _addedEvent );
  10725. _childaddedEvent.child = object;
  10726. this.dispatchEvent( _childaddedEvent );
  10727. _childaddedEvent.child = null;
  10728. return this;
  10729. }
  10730. /**
  10731. * Searches through the 3D object and its children, starting with the 3D object
  10732. * itself, and returns the first with a matching ID.
  10733. *
  10734. * @param {number} id - The id.
  10735. * @return {Object3D|undefined} The found 3D object. Returns `undefined` if no 3D object has been found.
  10736. */
  10737. getObjectById( id ) {
  10738. return this.getObjectByProperty( 'id', id );
  10739. }
  10740. /**
  10741. * Searches through the 3D object and its children, starting with the 3D object
  10742. * itself, and returns the first with a matching name.
  10743. *
  10744. * @param {string} name - The name.
  10745. * @return {Object3D|undefined} The found 3D object. Returns `undefined` if no 3D object has been found.
  10746. */
  10747. getObjectByName( name ) {
  10748. return this.getObjectByProperty( 'name', name );
  10749. }
  10750. /**
  10751. * Searches through the 3D object and its children, starting with the 3D object
  10752. * itself, and returns the first with a matching property value.
  10753. *
  10754. * @param {string} name - The name of the property.
  10755. * @param {any} value - The value.
  10756. * @return {Object3D|undefined} The found 3D object. Returns `undefined` if no 3D object has been found.
  10757. */
  10758. getObjectByProperty( name, value ) {
  10759. if ( this[ name ] === value ) return this;
  10760. for ( let i = 0, l = this.children.length; i < l; i ++ ) {
  10761. const child = this.children[ i ];
  10762. const object = child.getObjectByProperty( name, value );
  10763. if ( object !== undefined ) {
  10764. return object;
  10765. }
  10766. }
  10767. return undefined;
  10768. }
  10769. /**
  10770. * Searches through the 3D object and its children, starting with the 3D object
  10771. * itself, and returns all 3D objects with a matching property value.
  10772. *
  10773. * @param {string} name - The name of the property.
  10774. * @param {any} value - The value.
  10775. * @param {Array<Object3D>} result - The method stores the result in this array.
  10776. * @return {Array<Object3D>} The found 3D objects.
  10777. */
  10778. getObjectsByProperty( name, value, result = [] ) {
  10779. if ( this[ name ] === value ) result.push( this );
  10780. const children = this.children;
  10781. for ( let i = 0, l = children.length; i < l; i ++ ) {
  10782. children[ i ].getObjectsByProperty( name, value, result );
  10783. }
  10784. return result;
  10785. }
  10786. /**
  10787. * Returns a vector representing the position of the 3D object in world space.
  10788. *
  10789. * @param {Vector3} target - The target vector the result is stored to.
  10790. * @return {Vector3} The 3D object's position in world space.
  10791. */
  10792. getWorldPosition( target ) {
  10793. this.updateWorldMatrix( true, false );
  10794. return target.setFromMatrixPosition( this.matrixWorld );
  10795. }
  10796. /**
  10797. * Returns a Quaternion representing the position of the 3D object in world space.
  10798. *
  10799. * @param {Quaternion} target - The target Quaternion the result is stored to.
  10800. * @return {Quaternion} The 3D object's rotation in world space.
  10801. */
  10802. getWorldQuaternion( target ) {
  10803. this.updateWorldMatrix( true, false );
  10804. this.matrixWorld.decompose( _position$3, target, _scale$2 );
  10805. return target;
  10806. }
  10807. /**
  10808. * Returns a vector representing the scale of the 3D object in world space.
  10809. *
  10810. * @param {Vector3} target - The target vector the result is stored to.
  10811. * @return {Vector3} The 3D object's scale in world space.
  10812. */
  10813. getWorldScale( target ) {
  10814. this.updateWorldMatrix( true, false );
  10815. this.matrixWorld.decompose( _position$3, _quaternion$2, target );
  10816. return target;
  10817. }
  10818. /**
  10819. * Returns a vector representing the ("look") direction of the 3D object in world space.
  10820. *
  10821. * @param {Vector3} target - The target vector the result is stored to.
  10822. * @return {Vector3} The 3D object's direction in world space.
  10823. */
  10824. getWorldDirection( target ) {
  10825. this.updateWorldMatrix( true, false );
  10826. const e = this.matrixWorld.elements;
  10827. return target.set( e[ 8 ], e[ 9 ], e[ 10 ] ).normalize();
  10828. }
  10829. /**
  10830. * Abstract method to get intersections between a casted ray and this
  10831. * 3D object. Renderable 3D objects such as {@link Mesh}, {@link Line} or {@link Points}
  10832. * implement this method in order to use raycasting.
  10833. *
  10834. * @abstract
  10835. * @param {Raycaster} raycaster - The raycaster.
  10836. * @param {Array<Object>} intersects - An array holding the result of the method.
  10837. */
  10838. raycast( /* raycaster, intersects */ ) {}
  10839. /**
  10840. * Executes the callback on this 3D object and all descendants.
  10841. *
  10842. * Note: Modifying the scene graph inside the callback is discouraged.
  10843. *
  10844. * @param {Function} callback - A callback function that allows to process the current 3D object.
  10845. */
  10846. traverse( callback ) {
  10847. callback( this );
  10848. const children = this.children;
  10849. for ( let i = 0, l = children.length; i < l; i ++ ) {
  10850. children[ i ].traverse( callback );
  10851. }
  10852. }
  10853. /**
  10854. * Like {@link Object3D#traverse}, but the callback will only be executed for visible 3D objects.
  10855. * Descendants of invisible 3D objects are not traversed.
  10856. *
  10857. * Note: Modifying the scene graph inside the callback is discouraged.
  10858. *
  10859. * @param {Function} callback - A callback function that allows to process the current 3D object.
  10860. */
  10861. traverseVisible( callback ) {
  10862. if ( this.visible === false ) return;
  10863. callback( this );
  10864. const children = this.children;
  10865. for ( let i = 0, l = children.length; i < l; i ++ ) {
  10866. children[ i ].traverseVisible( callback );
  10867. }
  10868. }
  10869. /**
  10870. * Like {@link Object3D#traverse}, but the callback will only be executed for all ancestors.
  10871. *
  10872. * Note: Modifying the scene graph inside the callback is discouraged.
  10873. *
  10874. * @param {Function} callback - A callback function that allows to process the current 3D object.
  10875. */
  10876. traverseAncestors( callback ) {
  10877. const parent = this.parent;
  10878. if ( parent !== null ) {
  10879. callback( parent );
  10880. parent.traverseAncestors( callback );
  10881. }
  10882. }
  10883. /**
  10884. * Updates the transformation matrix in local space by computing it from the current
  10885. * position, rotation and scale values.
  10886. */
  10887. updateMatrix() {
  10888. this.matrix.compose( this.position, this.quaternion, this.scale );
  10889. this.matrixWorldNeedsUpdate = true;
  10890. }
  10891. /**
  10892. * Updates the transformation matrix in world space of this 3D objects and its descendants.
  10893. *
  10894. * To ensure correct results, this method also recomputes the 3D object's transformation matrix in
  10895. * local space. The computation of the local and world matrix can be controlled with the
  10896. * {@link Object3D#matrixAutoUpdate} and {@link Object3D#matrixWorldAutoUpdate} flags which are both
  10897. * `true` by default. Set these flags to `false` if you need more control over the update matrix process.
  10898. *
  10899. * @param {boolean} [force=false] - When set to `true`, a recomputation of world matrices is forced even
  10900. * when {@link Object3D#matrixWorldAutoUpdate} is set to `false`.
  10901. */
  10902. updateMatrixWorld( force ) {
  10903. if ( this.matrixAutoUpdate ) this.updateMatrix();
  10904. if ( this.matrixWorldNeedsUpdate || force ) {
  10905. if ( this.matrixWorldAutoUpdate === true ) {
  10906. if ( this.parent === null ) {
  10907. this.matrixWorld.copy( this.matrix );
  10908. } else {
  10909. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  10910. }
  10911. }
  10912. this.matrixWorldNeedsUpdate = false;
  10913. force = true;
  10914. }
  10915. // make sure descendants are updated if required
  10916. const children = this.children;
  10917. for ( let i = 0, l = children.length; i < l; i ++ ) {
  10918. const child = children[ i ];
  10919. child.updateMatrixWorld( force );
  10920. }
  10921. }
  10922. /**
  10923. * An alternative version of {@link Object3D#updateMatrixWorld} with more control over the
  10924. * update of ancestor and descendant nodes.
  10925. *
  10926. * @param {boolean} [updateParents=false] Whether ancestor nodes should be updated or not.
  10927. * @param {boolean} [updateChildren=false] Whether descendant nodes should be updated or not.
  10928. */
  10929. updateWorldMatrix( updateParents, updateChildren ) {
  10930. const parent = this.parent;
  10931. if ( updateParents === true && parent !== null ) {
  10932. parent.updateWorldMatrix( true, false );
  10933. }
  10934. if ( this.matrixAutoUpdate ) this.updateMatrix();
  10935. if ( this.matrixWorldAutoUpdate === true ) {
  10936. if ( this.parent === null ) {
  10937. this.matrixWorld.copy( this.matrix );
  10938. } else {
  10939. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  10940. }
  10941. }
  10942. // make sure descendants are updated
  10943. if ( updateChildren === true ) {
  10944. const children = this.children;
  10945. for ( let i = 0, l = children.length; i < l; i ++ ) {
  10946. const child = children[ i ];
  10947. child.updateWorldMatrix( false, true );
  10948. }
  10949. }
  10950. }
  10951. /**
  10952. * Serializes the 3D object into JSON.
  10953. *
  10954. * @param {?(Object|string)} meta - An optional value holding meta information about the serialization.
  10955. * @return {Object} A JSON object representing the serialized 3D object.
  10956. * @see {@link ObjectLoader#parse}
  10957. */
  10958. toJSON( meta ) {
  10959. // meta is a string when called from JSON.stringify
  10960. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  10961. const output = {};
  10962. // meta is a hash used to collect geometries, materials.
  10963. // not providing it implies that this is the root object
  10964. // being serialized.
  10965. if ( isRootObject ) {
  10966. // initialize meta obj
  10967. meta = {
  10968. geometries: {},
  10969. materials: {},
  10970. textures: {},
  10971. images: {},
  10972. shapes: {},
  10973. skeletons: {},
  10974. animations: {},
  10975. nodes: {}
  10976. };
  10977. output.metadata = {
  10978. version: 4.7,
  10979. type: 'Object',
  10980. generator: 'Object3D.toJSON'
  10981. };
  10982. }
  10983. // standard Object3D serialization
  10984. const object = {};
  10985. object.uuid = this.uuid;
  10986. object.type = this.type;
  10987. if ( this.name !== '' ) object.name = this.name;
  10988. if ( this.castShadow === true ) object.castShadow = true;
  10989. if ( this.receiveShadow === true ) object.receiveShadow = true;
  10990. if ( this.visible === false ) object.visible = false;
  10991. if ( this.frustumCulled === false ) object.frustumCulled = false;
  10992. if ( this.renderOrder !== 0 ) object.renderOrder = this.renderOrder;
  10993. if ( Object.keys( this.userData ).length > 0 ) object.userData = this.userData;
  10994. object.layers = this.layers.mask;
  10995. object.matrix = this.matrix.toArray();
  10996. object.up = this.up.toArray();
  10997. if ( this.matrixAutoUpdate === false ) object.matrixAutoUpdate = false;
  10998. // object specific properties
  10999. if ( this.isInstancedMesh ) {
  11000. object.type = 'InstancedMesh';
  11001. object.count = this.count;
  11002. object.instanceMatrix = this.instanceMatrix.toJSON();
  11003. if ( this.instanceColor !== null ) object.instanceColor = this.instanceColor.toJSON();
  11004. }
  11005. if ( this.isBatchedMesh ) {
  11006. object.type = 'BatchedMesh';
  11007. object.perObjectFrustumCulled = this.perObjectFrustumCulled;
  11008. object.sortObjects = this.sortObjects;
  11009. object.drawRanges = this._drawRanges;
  11010. object.reservedRanges = this._reservedRanges;
  11011. object.geometryInfo = this._geometryInfo.map( info => ( {
  11012. ...info,
  11013. boundingBox: info.boundingBox ? info.boundingBox.toJSON() : undefined,
  11014. boundingSphere: info.boundingSphere ? info.boundingSphere.toJSON() : undefined
  11015. } ) );
  11016. object.instanceInfo = this._instanceInfo.map( info => ( { ...info } ) );
  11017. object.availableInstanceIds = this._availableInstanceIds.slice();
  11018. object.availableGeometryIds = this._availableGeometryIds.slice();
  11019. object.nextIndexStart = this._nextIndexStart;
  11020. object.nextVertexStart = this._nextVertexStart;
  11021. object.geometryCount = this._geometryCount;
  11022. object.maxInstanceCount = this._maxInstanceCount;
  11023. object.maxVertexCount = this._maxVertexCount;
  11024. object.maxIndexCount = this._maxIndexCount;
  11025. object.geometryInitialized = this._geometryInitialized;
  11026. object.matricesTexture = this._matricesTexture.toJSON( meta );
  11027. object.indirectTexture = this._indirectTexture.toJSON( meta );
  11028. if ( this._colorsTexture !== null ) {
  11029. object.colorsTexture = this._colorsTexture.toJSON( meta );
  11030. }
  11031. if ( this.boundingSphere !== null ) {
  11032. object.boundingSphere = this.boundingSphere.toJSON();
  11033. }
  11034. if ( this.boundingBox !== null ) {
  11035. object.boundingBox = this.boundingBox.toJSON();
  11036. }
  11037. }
  11038. //
  11039. function serialize( library, element ) {
  11040. if ( library[ element.uuid ] === undefined ) {
  11041. library[ element.uuid ] = element.toJSON( meta );
  11042. }
  11043. return element.uuid;
  11044. }
  11045. if ( this.isScene ) {
  11046. if ( this.background ) {
  11047. if ( this.background.isColor ) {
  11048. object.background = this.background.toJSON();
  11049. } else if ( this.background.isTexture ) {
  11050. object.background = this.background.toJSON( meta ).uuid;
  11051. }
  11052. }
  11053. if ( this.environment && this.environment.isTexture && this.environment.isRenderTargetTexture !== true ) {
  11054. object.environment = this.environment.toJSON( meta ).uuid;
  11055. }
  11056. } else if ( this.isMesh || this.isLine || this.isPoints ) {
  11057. object.geometry = serialize( meta.geometries, this.geometry );
  11058. const parameters = this.geometry.parameters;
  11059. if ( parameters !== undefined && parameters.shapes !== undefined ) {
  11060. const shapes = parameters.shapes;
  11061. if ( Array.isArray( shapes ) ) {
  11062. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  11063. const shape = shapes[ i ];
  11064. serialize( meta.shapes, shape );
  11065. }
  11066. } else {
  11067. serialize( meta.shapes, shapes );
  11068. }
  11069. }
  11070. }
  11071. if ( this.isSkinnedMesh ) {
  11072. object.bindMode = this.bindMode;
  11073. object.bindMatrix = this.bindMatrix.toArray();
  11074. if ( this.skeleton !== undefined ) {
  11075. serialize( meta.skeletons, this.skeleton );
  11076. object.skeleton = this.skeleton.uuid;
  11077. }
  11078. }
  11079. if ( this.material !== undefined ) {
  11080. if ( Array.isArray( this.material ) ) {
  11081. const uuids = [];
  11082. for ( let i = 0, l = this.material.length; i < l; i ++ ) {
  11083. uuids.push( serialize( meta.materials, this.material[ i ] ) );
  11084. }
  11085. object.material = uuids;
  11086. } else {
  11087. object.material = serialize( meta.materials, this.material );
  11088. }
  11089. }
  11090. //
  11091. if ( this.children.length > 0 ) {
  11092. object.children = [];
  11093. for ( let i = 0; i < this.children.length; i ++ ) {
  11094. object.children.push( this.children[ i ].toJSON( meta ).object );
  11095. }
  11096. }
  11097. //
  11098. if ( this.animations.length > 0 ) {
  11099. object.animations = [];
  11100. for ( let i = 0; i < this.animations.length; i ++ ) {
  11101. const animation = this.animations[ i ];
  11102. object.animations.push( serialize( meta.animations, animation ) );
  11103. }
  11104. }
  11105. if ( isRootObject ) {
  11106. const geometries = extractFromCache( meta.geometries );
  11107. const materials = extractFromCache( meta.materials );
  11108. const textures = extractFromCache( meta.textures );
  11109. const images = extractFromCache( meta.images );
  11110. const shapes = extractFromCache( meta.shapes );
  11111. const skeletons = extractFromCache( meta.skeletons );
  11112. const animations = extractFromCache( meta.animations );
  11113. const nodes = extractFromCache( meta.nodes );
  11114. if ( geometries.length > 0 ) output.geometries = geometries;
  11115. if ( materials.length > 0 ) output.materials = materials;
  11116. if ( textures.length > 0 ) output.textures = textures;
  11117. if ( images.length > 0 ) output.images = images;
  11118. if ( shapes.length > 0 ) output.shapes = shapes;
  11119. if ( skeletons.length > 0 ) output.skeletons = skeletons;
  11120. if ( animations.length > 0 ) output.animations = animations;
  11121. if ( nodes.length > 0 ) output.nodes = nodes;
  11122. }
  11123. output.object = object;
  11124. return output;
  11125. // extract data from the cache hash
  11126. // remove metadata on each item
  11127. // and return as array
  11128. function extractFromCache( cache ) {
  11129. const values = [];
  11130. for ( const key in cache ) {
  11131. const data = cache[ key ];
  11132. delete data.metadata;
  11133. values.push( data );
  11134. }
  11135. return values;
  11136. }
  11137. }
  11138. /**
  11139. * Returns a new 3D object with copied values from this instance.
  11140. *
  11141. * @param {boolean} [recursive=true] - When set to `true`, descendants of the 3D object are also cloned.
  11142. * @return {Object3D} A clone of this instance.
  11143. */
  11144. clone( recursive ) {
  11145. return new this.constructor().copy( this, recursive );
  11146. }
  11147. /**
  11148. * Copies the values of the given 3D object to this instance.
  11149. *
  11150. * @param {Object3D} source - The 3D object to copy.
  11151. * @param {boolean} [recursive=true] - When set to `true`, descendants of the 3D object are cloned.
  11152. * @return {Object3D} A reference to this instance.
  11153. */
  11154. copy( source, recursive = true ) {
  11155. this.name = source.name;
  11156. this.up.copy( source.up );
  11157. this.position.copy( source.position );
  11158. this.rotation.order = source.rotation.order;
  11159. this.quaternion.copy( source.quaternion );
  11160. this.scale.copy( source.scale );
  11161. this.matrix.copy( source.matrix );
  11162. this.matrixWorld.copy( source.matrixWorld );
  11163. this.matrixAutoUpdate = source.matrixAutoUpdate;
  11164. this.matrixWorldAutoUpdate = source.matrixWorldAutoUpdate;
  11165. this.matrixWorldNeedsUpdate = source.matrixWorldNeedsUpdate;
  11166. this.layers.mask = source.layers.mask;
  11167. this.visible = source.visible;
  11168. this.castShadow = source.castShadow;
  11169. this.receiveShadow = source.receiveShadow;
  11170. this.frustumCulled = source.frustumCulled;
  11171. this.renderOrder = source.renderOrder;
  11172. this.animations = source.animations.slice();
  11173. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  11174. if ( recursive === true ) {
  11175. for ( let i = 0; i < source.children.length; i ++ ) {
  11176. const child = source.children[ i ];
  11177. this.add( child.clone() );
  11178. }
  11179. }
  11180. return this;
  11181. }
  11182. }
  11183. /**
  11184. * The default up direction for objects, also used as the default
  11185. * position for {@link DirectionalLight} and {@link HemisphereLight}.
  11186. *
  11187. * @static
  11188. * @type {Vector3}
  11189. * @default (0,1,0)
  11190. */
  11191. Object3D.DEFAULT_UP = /*@__PURE__*/ new Vector3( 0, 1, 0 );
  11192. /**
  11193. * The default setting for {@link Object3D#matrixAutoUpdate} for
  11194. * newly created 3D objects.
  11195. *
  11196. * @static
  11197. * @type {boolean}
  11198. * @default true
  11199. */
  11200. Object3D.DEFAULT_MATRIX_AUTO_UPDATE = true;
  11201. /**
  11202. * The default setting for {@link Object3D#matrixWorldAutoUpdate} for
  11203. * newly created 3D objects.
  11204. *
  11205. * @static
  11206. * @type {boolean}
  11207. * @default true
  11208. */
  11209. Object3D.DEFAULT_MATRIX_WORLD_AUTO_UPDATE = true;
  11210. const _v0$1 = /*@__PURE__*/ new Vector3();
  11211. const _v1$3 = /*@__PURE__*/ new Vector3();
  11212. const _v2$2 = /*@__PURE__*/ new Vector3();
  11213. const _v3$2 = /*@__PURE__*/ new Vector3();
  11214. const _vab = /*@__PURE__*/ new Vector3();
  11215. const _vac = /*@__PURE__*/ new Vector3();
  11216. const _vbc = /*@__PURE__*/ new Vector3();
  11217. const _vap = /*@__PURE__*/ new Vector3();
  11218. const _vbp = /*@__PURE__*/ new Vector3();
  11219. const _vcp = /*@__PURE__*/ new Vector3();
  11220. const _v40 = /*@__PURE__*/ new Vector4();
  11221. const _v41 = /*@__PURE__*/ new Vector4();
  11222. const _v42 = /*@__PURE__*/ new Vector4();
  11223. /**
  11224. * A geometric triangle as defined by three vectors representing its three corners.
  11225. */
  11226. class Triangle {
  11227. /**
  11228. * Constructs a new triangle.
  11229. *
  11230. * @param {Vector3} [a=(0,0,0)] - The first corner of the triangle.
  11231. * @param {Vector3} [b=(0,0,0)] - The second corner of the triangle.
  11232. * @param {Vector3} [c=(0,0,0)] - The third corner of the triangle.
  11233. */
  11234. constructor( a = new Vector3(), b = new Vector3(), c = new Vector3() ) {
  11235. /**
  11236. * The first corner of the triangle.
  11237. *
  11238. * @type {Vector3}
  11239. */
  11240. this.a = a;
  11241. /**
  11242. * The second corner of the triangle.
  11243. *
  11244. * @type {Vector3}
  11245. */
  11246. this.b = b;
  11247. /**
  11248. * The third corner of the triangle.
  11249. *
  11250. * @type {Vector3}
  11251. */
  11252. this.c = c;
  11253. }
  11254. /**
  11255. * Computes the normal vector of a triangle.
  11256. *
  11257. * @param {Vector3} a - The first corner of the triangle.
  11258. * @param {Vector3} b - The second corner of the triangle.
  11259. * @param {Vector3} c - The third corner of the triangle.
  11260. * @param {Vector3} target - The target vector that is used to store the method's result.
  11261. * @return {Vector3} The triangle's normal.
  11262. */
  11263. static getNormal( a, b, c, target ) {
  11264. target.subVectors( c, b );
  11265. _v0$1.subVectors( a, b );
  11266. target.cross( _v0$1 );
  11267. const targetLengthSq = target.lengthSq();
  11268. if ( targetLengthSq > 0 ) {
  11269. return target.multiplyScalar( 1 / Math.sqrt( targetLengthSq ) );
  11270. }
  11271. return target.set( 0, 0, 0 );
  11272. }
  11273. /**
  11274. * Computes a barycentric coordinates from the given vector.
  11275. * Returns `null` if the triangle is degenerate.
  11276. *
  11277. * @param {Vector3} point - A point in 3D space.
  11278. * @param {Vector3} a - The first corner of the triangle.
  11279. * @param {Vector3} b - The second corner of the triangle.
  11280. * @param {Vector3} c - The third corner of the triangle.
  11281. * @param {Vector3} target - The target vector that is used to store the method's result.
  11282. * @return {?Vector3} The barycentric coordinates for the given point
  11283. */
  11284. static getBarycoord( point, a, b, c, target ) {
  11285. // based on: http://www.blackpawn.com/texts/pointinpoly/default.html
  11286. _v0$1.subVectors( c, a );
  11287. _v1$3.subVectors( b, a );
  11288. _v2$2.subVectors( point, a );
  11289. const dot00 = _v0$1.dot( _v0$1 );
  11290. const dot01 = _v0$1.dot( _v1$3 );
  11291. const dot02 = _v0$1.dot( _v2$2 );
  11292. const dot11 = _v1$3.dot( _v1$3 );
  11293. const dot12 = _v1$3.dot( _v2$2 );
  11294. const denom = ( dot00 * dot11 - dot01 * dot01 );
  11295. // collinear or singular triangle
  11296. if ( denom === 0 ) {
  11297. target.set( 0, 0, 0 );
  11298. return null;
  11299. }
  11300. const invDenom = 1 / denom;
  11301. const u = ( dot11 * dot02 - dot01 * dot12 ) * invDenom;
  11302. const v = ( dot00 * dot12 - dot01 * dot02 ) * invDenom;
  11303. // barycentric coordinates must always sum to 1
  11304. return target.set( 1 - u - v, v, u );
  11305. }
  11306. /**
  11307. * Returns `true` if the given point, when projected onto the plane of the
  11308. * triangle, lies within the triangle.
  11309. *
  11310. * @param {Vector3} point - The point in 3D space to test.
  11311. * @param {Vector3} a - The first corner of the triangle.
  11312. * @param {Vector3} b - The second corner of the triangle.
  11313. * @param {Vector3} c - The third corner of the triangle.
  11314. * @return {boolean} Whether the given point, when projected onto the plane of the
  11315. * triangle, lies within the triangle or not.
  11316. */
  11317. static containsPoint( point, a, b, c ) {
  11318. // if the triangle is degenerate then we can't contain a point
  11319. if ( this.getBarycoord( point, a, b, c, _v3$2 ) === null ) {
  11320. return false;
  11321. }
  11322. return ( _v3$2.x >= 0 ) && ( _v3$2.y >= 0 ) && ( ( _v3$2.x + _v3$2.y ) <= 1 );
  11323. }
  11324. /**
  11325. * Computes the value barycentrically interpolated for the given point on the
  11326. * triangle. Returns `null` if the triangle is degenerate.
  11327. *
  11328. * @param {Vector3} point - Position of interpolated point.
  11329. * @param {Vector3} p1 - The first corner of the triangle.
  11330. * @param {Vector3} p2 - The second corner of the triangle.
  11331. * @param {Vector3} p3 - The third corner of the triangle.
  11332. * @param {Vector3} v1 - Value to interpolate of first vertex.
  11333. * @param {Vector3} v2 - Value to interpolate of second vertex.
  11334. * @param {Vector3} v3 - Value to interpolate of third vertex.
  11335. * @param {Vector3} target - The target vector that is used to store the method's result.
  11336. * @return {?Vector3} The interpolated value.
  11337. */
  11338. static getInterpolation( point, p1, p2, p3, v1, v2, v3, target ) {
  11339. if ( this.getBarycoord( point, p1, p2, p3, _v3$2 ) === null ) {
  11340. target.x = 0;
  11341. target.y = 0;
  11342. if ( 'z' in target ) target.z = 0;
  11343. if ( 'w' in target ) target.w = 0;
  11344. return null;
  11345. }
  11346. target.setScalar( 0 );
  11347. target.addScaledVector( v1, _v3$2.x );
  11348. target.addScaledVector( v2, _v3$2.y );
  11349. target.addScaledVector( v3, _v3$2.z );
  11350. return target;
  11351. }
  11352. /**
  11353. * Computes the value barycentrically interpolated for the given attribute and indices.
  11354. *
  11355. * @param {BufferAttribute} attr - The attribute to interpolate.
  11356. * @param {number} i1 - Index of first vertex.
  11357. * @param {number} i2 - Index of second vertex.
  11358. * @param {number} i3 - Index of third vertex.
  11359. * @param {Vector3} barycoord - The barycoordinate value to use to interpolate.
  11360. * @param {Vector3} target - The target vector that is used to store the method's result.
  11361. * @return {Vector3} The interpolated attribute value.
  11362. */
  11363. static getInterpolatedAttribute( attr, i1, i2, i3, barycoord, target ) {
  11364. _v40.setScalar( 0 );
  11365. _v41.setScalar( 0 );
  11366. _v42.setScalar( 0 );
  11367. _v40.fromBufferAttribute( attr, i1 );
  11368. _v41.fromBufferAttribute( attr, i2 );
  11369. _v42.fromBufferAttribute( attr, i3 );
  11370. target.setScalar( 0 );
  11371. target.addScaledVector( _v40, barycoord.x );
  11372. target.addScaledVector( _v41, barycoord.y );
  11373. target.addScaledVector( _v42, barycoord.z );
  11374. return target;
  11375. }
  11376. /**
  11377. * Returns `true` if the triangle is oriented towards the given direction.
  11378. *
  11379. * @param {Vector3} a - The first corner of the triangle.
  11380. * @param {Vector3} b - The second corner of the triangle.
  11381. * @param {Vector3} c - The third corner of the triangle.
  11382. * @param {Vector3} direction - The (normalized) direction vector.
  11383. * @return {boolean} Whether the triangle is oriented towards the given direction or not.
  11384. */
  11385. static isFrontFacing( a, b, c, direction ) {
  11386. _v0$1.subVectors( c, b );
  11387. _v1$3.subVectors( a, b );
  11388. // strictly front facing
  11389. return ( _v0$1.cross( _v1$3 ).dot( direction ) < 0 ) ? true : false;
  11390. }
  11391. /**
  11392. * Sets the triangle's vertices by copying the given values.
  11393. *
  11394. * @param {Vector3} a - The first corner of the triangle.
  11395. * @param {Vector3} b - The second corner of the triangle.
  11396. * @param {Vector3} c - The third corner of the triangle.
  11397. * @return {Triangle} A reference to this triangle.
  11398. */
  11399. set( a, b, c ) {
  11400. this.a.copy( a );
  11401. this.b.copy( b );
  11402. this.c.copy( c );
  11403. return this;
  11404. }
  11405. /**
  11406. * Sets the triangle's vertices by copying the given array values.
  11407. *
  11408. * @param {Array<Vector3>} points - An array with 3D points.
  11409. * @param {number} i0 - The array index representing the first corner of the triangle.
  11410. * @param {number} i1 - The array index representing the second corner of the triangle.
  11411. * @param {number} i2 - The array index representing the third corner of the triangle.
  11412. * @return {Triangle} A reference to this triangle.
  11413. */
  11414. setFromPointsAndIndices( points, i0, i1, i2 ) {
  11415. this.a.copy( points[ i0 ] );
  11416. this.b.copy( points[ i1 ] );
  11417. this.c.copy( points[ i2 ] );
  11418. return this;
  11419. }
  11420. /**
  11421. * Sets the triangle's vertices by copying the given attribute values.
  11422. *
  11423. * @param {BufferAttribute} attribute - A buffer attribute with 3D points data.
  11424. * @param {number} i0 - The attribute index representing the first corner of the triangle.
  11425. * @param {number} i1 - The attribute index representing the second corner of the triangle.
  11426. * @param {number} i2 - The attribute index representing the third corner of the triangle.
  11427. * @return {Triangle} A reference to this triangle.
  11428. */
  11429. setFromAttributeAndIndices( attribute, i0, i1, i2 ) {
  11430. this.a.fromBufferAttribute( attribute, i0 );
  11431. this.b.fromBufferAttribute( attribute, i1 );
  11432. this.c.fromBufferAttribute( attribute, i2 );
  11433. return this;
  11434. }
  11435. /**
  11436. * Returns a new triangle with copied values from this instance.
  11437. *
  11438. * @return {Triangle} A clone of this instance.
  11439. */
  11440. clone() {
  11441. return new this.constructor().copy( this );
  11442. }
  11443. /**
  11444. * Copies the values of the given triangle to this instance.
  11445. *
  11446. * @param {Triangle} triangle - The triangle to copy.
  11447. * @return {Triangle} A reference to this triangle.
  11448. */
  11449. copy( triangle ) {
  11450. this.a.copy( triangle.a );
  11451. this.b.copy( triangle.b );
  11452. this.c.copy( triangle.c );
  11453. return this;
  11454. }
  11455. /**
  11456. * Computes the area of the triangle.
  11457. *
  11458. * @return {number} The triangle's area.
  11459. */
  11460. getArea() {
  11461. _v0$1.subVectors( this.c, this.b );
  11462. _v1$3.subVectors( this.a, this.b );
  11463. return _v0$1.cross( _v1$3 ).length() * 0.5;
  11464. }
  11465. /**
  11466. * Computes the midpoint of the triangle.
  11467. *
  11468. * @param {Vector3} target - The target vector that is used to store the method's result.
  11469. * @return {Vector3} The triangle's midpoint.
  11470. */
  11471. getMidpoint( target ) {
  11472. return target.addVectors( this.a, this.b ).add( this.c ).multiplyScalar( 1 / 3 );
  11473. }
  11474. /**
  11475. * Computes the normal of the triangle.
  11476. *
  11477. * @param {Vector3} target - The target vector that is used to store the method's result.
  11478. * @return {Vector3} The triangle's normal.
  11479. */
  11480. getNormal( target ) {
  11481. return Triangle.getNormal( this.a, this.b, this.c, target );
  11482. }
  11483. /**
  11484. * Computes a plane the triangle lies within.
  11485. *
  11486. * @param {Plane} target - The target vector that is used to store the method's result.
  11487. * @return {Plane} The plane the triangle lies within.
  11488. */
  11489. getPlane( target ) {
  11490. return target.setFromCoplanarPoints( this.a, this.b, this.c );
  11491. }
  11492. /**
  11493. * Computes a barycentric coordinates from the given vector.
  11494. * Returns `null` if the triangle is degenerate.
  11495. *
  11496. * @param {Vector3} point - A point in 3D space.
  11497. * @param {Vector3} target - The target vector that is used to store the method's result.
  11498. * @return {?Vector3} The barycentric coordinates for the given point
  11499. */
  11500. getBarycoord( point, target ) {
  11501. return Triangle.getBarycoord( point, this.a, this.b, this.c, target );
  11502. }
  11503. /**
  11504. * Computes the value barycentrically interpolated for the given point on the
  11505. * triangle. Returns `null` if the triangle is degenerate.
  11506. *
  11507. * @param {Vector3} point - Position of interpolated point.
  11508. * @param {Vector3} v1 - Value to interpolate of first vertex.
  11509. * @param {Vector3} v2 - Value to interpolate of second vertex.
  11510. * @param {Vector3} v3 - Value to interpolate of third vertex.
  11511. * @param {Vector3} target - The target vector that is used to store the method's result.
  11512. * @return {?Vector3} The interpolated value.
  11513. */
  11514. getInterpolation( point, v1, v2, v3, target ) {
  11515. return Triangle.getInterpolation( point, this.a, this.b, this.c, v1, v2, v3, target );
  11516. }
  11517. /**
  11518. * Returns `true` if the given point, when projected onto the plane of the
  11519. * triangle, lies within the triangle.
  11520. *
  11521. * @param {Vector3} point - The point in 3D space to test.
  11522. * @return {boolean} Whether the given point, when projected onto the plane of the
  11523. * triangle, lies within the triangle or not.
  11524. */
  11525. containsPoint( point ) {
  11526. return Triangle.containsPoint( point, this.a, this.b, this.c );
  11527. }
  11528. /**
  11529. * Returns `true` if the triangle is oriented towards the given direction.
  11530. *
  11531. * @param {Vector3} direction - The (normalized) direction vector.
  11532. * @return {boolean} Whether the triangle is oriented towards the given direction or not.
  11533. */
  11534. isFrontFacing( direction ) {
  11535. return Triangle.isFrontFacing( this.a, this.b, this.c, direction );
  11536. }
  11537. /**
  11538. * Returns `true` if this triangle intersects with the given box.
  11539. *
  11540. * @param {Box3} box - The box to intersect.
  11541. * @return {boolean} Whether this triangle intersects with the given box or not.
  11542. */
  11543. intersectsBox( box ) {
  11544. return box.intersectsTriangle( this );
  11545. }
  11546. /**
  11547. * Returns the closest point on the triangle to the given point.
  11548. *
  11549. * @param {Vector3} p - The point to compute the closest point for.
  11550. * @param {Vector3} target - The target vector that is used to store the method's result.
  11551. * @return {Vector3} The closest point on the triangle.
  11552. */
  11553. closestPointToPoint( p, target ) {
  11554. const a = this.a, b = this.b, c = this.c;
  11555. let v, w;
  11556. // algorithm thanks to Real-Time Collision Detection by Christer Ericson,
  11557. // published by Morgan Kaufmann Publishers, (c) 2005 Elsevier Inc.,
  11558. // under the accompanying license; see chapter 5.1.5 for detailed explanation.
  11559. // basically, we're distinguishing which of the voronoi regions of the triangle
  11560. // the point lies in with the minimum amount of redundant computation.
  11561. _vab.subVectors( b, a );
  11562. _vac.subVectors( c, a );
  11563. _vap.subVectors( p, a );
  11564. const d1 = _vab.dot( _vap );
  11565. const d2 = _vac.dot( _vap );
  11566. if ( d1 <= 0 && d2 <= 0 ) {
  11567. // vertex region of A; barycentric coords (1, 0, 0)
  11568. return target.copy( a );
  11569. }
  11570. _vbp.subVectors( p, b );
  11571. const d3 = _vab.dot( _vbp );
  11572. const d4 = _vac.dot( _vbp );
  11573. if ( d3 >= 0 && d4 <= d3 ) {
  11574. // vertex region of B; barycentric coords (0, 1, 0)
  11575. return target.copy( b );
  11576. }
  11577. const vc = d1 * d4 - d3 * d2;
  11578. if ( vc <= 0 && d1 >= 0 && d3 <= 0 ) {
  11579. v = d1 / ( d1 - d3 );
  11580. // edge region of AB; barycentric coords (1-v, v, 0)
  11581. return target.copy( a ).addScaledVector( _vab, v );
  11582. }
  11583. _vcp.subVectors( p, c );
  11584. const d5 = _vab.dot( _vcp );
  11585. const d6 = _vac.dot( _vcp );
  11586. if ( d6 >= 0 && d5 <= d6 ) {
  11587. // vertex region of C; barycentric coords (0, 0, 1)
  11588. return target.copy( c );
  11589. }
  11590. const vb = d5 * d2 - d1 * d6;
  11591. if ( vb <= 0 && d2 >= 0 && d6 <= 0 ) {
  11592. w = d2 / ( d2 - d6 );
  11593. // edge region of AC; barycentric coords (1-w, 0, w)
  11594. return target.copy( a ).addScaledVector( _vac, w );
  11595. }
  11596. const va = d3 * d6 - d5 * d4;
  11597. if ( va <= 0 && ( d4 - d3 ) >= 0 && ( d5 - d6 ) >= 0 ) {
  11598. _vbc.subVectors( c, b );
  11599. w = ( d4 - d3 ) / ( ( d4 - d3 ) + ( d5 - d6 ) );
  11600. // edge region of BC; barycentric coords (0, 1-w, w)
  11601. return target.copy( b ).addScaledVector( _vbc, w ); // edge region of BC
  11602. }
  11603. // face region
  11604. const denom = 1 / ( va + vb + vc );
  11605. // u = va * denom
  11606. v = vb * denom;
  11607. w = vc * denom;
  11608. return target.copy( a ).addScaledVector( _vab, v ).addScaledVector( _vac, w );
  11609. }
  11610. /**
  11611. * Returns `true` if this triangle is equal with the given one.
  11612. *
  11613. * @param {Triangle} triangle - The triangle to test for equality.
  11614. * @return {boolean} Whether this triangle is equal with the given one.
  11615. */
  11616. equals( triangle ) {
  11617. return triangle.a.equals( this.a ) && triangle.b.equals( this.b ) && triangle.c.equals( this.c );
  11618. }
  11619. }
  11620. const _colorKeywords = { 'aliceblue': 0xF0F8FF, 'antiquewhite': 0xFAEBD7, 'aqua': 0x00FFFF, 'aquamarine': 0x7FFFD4, 'azure': 0xF0FFFF,
  11621. 'beige': 0xF5F5DC, 'bisque': 0xFFE4C4, 'black': 0x000000, 'blanchedalmond': 0xFFEBCD, 'blue': 0x0000FF, 'blueviolet': 0x8A2BE2,
  11622. 'brown': 0xA52A2A, 'burlywood': 0xDEB887, 'cadetblue': 0x5F9EA0, 'chartreuse': 0x7FFF00, 'chocolate': 0xD2691E, 'coral': 0xFF7F50,
  11623. 'cornflowerblue': 0x6495ED, 'cornsilk': 0xFFF8DC, 'crimson': 0xDC143C, 'cyan': 0x00FFFF, 'darkblue': 0x00008B, 'darkcyan': 0x008B8B,
  11624. 'darkgoldenrod': 0xB8860B, 'darkgray': 0xA9A9A9, 'darkgreen': 0x006400, 'darkgrey': 0xA9A9A9, 'darkkhaki': 0xBDB76B, 'darkmagenta': 0x8B008B,
  11625. 'darkolivegreen': 0x556B2F, 'darkorange': 0xFF8C00, 'darkorchid': 0x9932CC, 'darkred': 0x8B0000, 'darksalmon': 0xE9967A, 'darkseagreen': 0x8FBC8F,
  11626. 'darkslateblue': 0x483D8B, 'darkslategray': 0x2F4F4F, 'darkslategrey': 0x2F4F4F, 'darkturquoise': 0x00CED1, 'darkviolet': 0x9400D3,
  11627. 'deeppink': 0xFF1493, 'deepskyblue': 0x00BFFF, 'dimgray': 0x696969, 'dimgrey': 0x696969, 'dodgerblue': 0x1E90FF, 'firebrick': 0xB22222,
  11628. 'floralwhite': 0xFFFAF0, 'forestgreen': 0x228B22, 'fuchsia': 0xFF00FF, 'gainsboro': 0xDCDCDC, 'ghostwhite': 0xF8F8FF, 'gold': 0xFFD700,
  11629. 'goldenrod': 0xDAA520, 'gray': 0x808080, 'green': 0x008000, 'greenyellow': 0xADFF2F, 'grey': 0x808080, 'honeydew': 0xF0FFF0, 'hotpink': 0xFF69B4,
  11630. 'indianred': 0xCD5C5C, 'indigo': 0x4B0082, 'ivory': 0xFFFFF0, 'khaki': 0xF0E68C, 'lavender': 0xE6E6FA, 'lavenderblush': 0xFFF0F5, 'lawngreen': 0x7CFC00,
  11631. 'lemonchiffon': 0xFFFACD, 'lightblue': 0xADD8E6, 'lightcoral': 0xF08080, 'lightcyan': 0xE0FFFF, 'lightgoldenrodyellow': 0xFAFAD2, 'lightgray': 0xD3D3D3,
  11632. 'lightgreen': 0x90EE90, 'lightgrey': 0xD3D3D3, 'lightpink': 0xFFB6C1, 'lightsalmon': 0xFFA07A, 'lightseagreen': 0x20B2AA, 'lightskyblue': 0x87CEFA,
  11633. 'lightslategray': 0x778899, 'lightslategrey': 0x778899, 'lightsteelblue': 0xB0C4DE, 'lightyellow': 0xFFFFE0, 'lime': 0x00FF00, 'limegreen': 0x32CD32,
  11634. 'linen': 0xFAF0E6, 'magenta': 0xFF00FF, 'maroon': 0x800000, 'mediumaquamarine': 0x66CDAA, 'mediumblue': 0x0000CD, 'mediumorchid': 0xBA55D3,
  11635. 'mediumpurple': 0x9370DB, 'mediumseagreen': 0x3CB371, 'mediumslateblue': 0x7B68EE, 'mediumspringgreen': 0x00FA9A, 'mediumturquoise': 0x48D1CC,
  11636. 'mediumvioletred': 0xC71585, 'midnightblue': 0x191970, 'mintcream': 0xF5FFFA, 'mistyrose': 0xFFE4E1, 'moccasin': 0xFFE4B5, 'navajowhite': 0xFFDEAD,
  11637. 'navy': 0x000080, 'oldlace': 0xFDF5E6, 'olive': 0x808000, 'olivedrab': 0x6B8E23, 'orange': 0xFFA500, 'orangered': 0xFF4500, 'orchid': 0xDA70D6,
  11638. 'palegoldenrod': 0xEEE8AA, 'palegreen': 0x98FB98, 'paleturquoise': 0xAFEEEE, 'palevioletred': 0xDB7093, 'papayawhip': 0xFFEFD5, 'peachpuff': 0xFFDAB9,
  11639. 'peru': 0xCD853F, 'pink': 0xFFC0CB, 'plum': 0xDDA0DD, 'powderblue': 0xB0E0E6, 'purple': 0x800080, 'rebeccapurple': 0x663399, 'red': 0xFF0000, 'rosybrown': 0xBC8F8F,
  11640. 'royalblue': 0x4169E1, 'saddlebrown': 0x8B4513, 'salmon': 0xFA8072, 'sandybrown': 0xF4A460, 'seagreen': 0x2E8B57, 'seashell': 0xFFF5EE,
  11641. 'sienna': 0xA0522D, 'silver': 0xC0C0C0, 'skyblue': 0x87CEEB, 'slateblue': 0x6A5ACD, 'slategray': 0x708090, 'slategrey': 0x708090, 'snow': 0xFFFAFA,
  11642. 'springgreen': 0x00FF7F, 'steelblue': 0x4682B4, 'tan': 0xD2B48C, 'teal': 0x008080, 'thistle': 0xD8BFD8, 'tomato': 0xFF6347, 'turquoise': 0x40E0D0,
  11643. 'violet': 0xEE82EE, 'wheat': 0xF5DEB3, 'white': 0xFFFFFF, 'whitesmoke': 0xF5F5F5, 'yellow': 0xFFFF00, 'yellowgreen': 0x9ACD32 };
  11644. const _hslA = { h: 0, s: 0, l: 0 };
  11645. const _hslB = { h: 0, s: 0, l: 0 };
  11646. function hue2rgb( p, q, t ) {
  11647. if ( t < 0 ) t += 1;
  11648. if ( t > 1 ) t -= 1;
  11649. if ( t < 1 / 6 ) return p + ( q - p ) * 6 * t;
  11650. if ( t < 1 / 2 ) return q;
  11651. if ( t < 2 / 3 ) return p + ( q - p ) * 6 * ( 2 / 3 - t );
  11652. return p;
  11653. }
  11654. /**
  11655. * A Color instance is represented by RGB components in the linear <i>working
  11656. * color space</i>, which defaults to `LinearSRGBColorSpace`. Inputs
  11657. * conventionally using `SRGBColorSpace` (such as hexadecimals and CSS
  11658. * strings) are converted to the working color space automatically.
  11659. *
  11660. * ```js
  11661. * // converted automatically from SRGBColorSpace to LinearSRGBColorSpace
  11662. * const color = new THREE.Color().setHex( 0x112233 );
  11663. * ```
  11664. * Source color spaces may be specified explicitly, to ensure correct conversions.
  11665. * ```js
  11666. * // assumed already LinearSRGBColorSpace; no conversion
  11667. * const color = new THREE.Color().setRGB( 0.5, 0.5, 0.5 );
  11668. *
  11669. * // converted explicitly from SRGBColorSpace to LinearSRGBColorSpace
  11670. * const color = new THREE.Color().setRGB( 0.5, 0.5, 0.5, SRGBColorSpace );
  11671. * ```
  11672. * If THREE.ColorManagement is disabled, no conversions occur. For details,
  11673. * see <i>Color management</i>. Iterating through a Color instance will yield
  11674. * its components (r, g, b) in the corresponding order. A Color can be initialised
  11675. * in any of the following ways:
  11676. * ```js
  11677. * //empty constructor - will default white
  11678. * const color1 = new THREE.Color();
  11679. *
  11680. * //Hexadecimal color (recommended)
  11681. * const color2 = new THREE.Color( 0xff0000 );
  11682. *
  11683. * //RGB string
  11684. * const color3 = new THREE.Color("rgb(255, 0, 0)");
  11685. * const color4 = new THREE.Color("rgb(100%, 0%, 0%)");
  11686. *
  11687. * //X11 color name - all 140 color names are supported.
  11688. * //Note the lack of CamelCase in the name
  11689. * const color5 = new THREE.Color( 'skyblue' );
  11690. * //HSL string
  11691. * const color6 = new THREE.Color("hsl(0, 100%, 50%)");
  11692. *
  11693. * //Separate RGB values between 0 and 1
  11694. * const color7 = new THREE.Color( 1, 0, 0 );
  11695. * ```
  11696. */
  11697. class Color {
  11698. /**
  11699. * Constructs a new color.
  11700. *
  11701. * Note that standard method of specifying color in three.js is with a hexadecimal triplet,
  11702. * and that method is used throughout the rest of the documentation.
  11703. *
  11704. * @param {(number|string|Color)} [r] - The red component of the color. If `g` and `b` are
  11705. * not provided, it can be hexadecimal triplet, a CSS-style string or another `Color` instance.
  11706. * @param {number} [g] - The green component.
  11707. * @param {number} [b] - The blue component.
  11708. */
  11709. constructor( r, g, b ) {
  11710. /**
  11711. * This flag can be used for type testing.
  11712. *
  11713. * @type {boolean}
  11714. * @readonly
  11715. * @default true
  11716. */
  11717. this.isColor = true;
  11718. /**
  11719. * The red component.
  11720. *
  11721. * @type {number}
  11722. * @default 1
  11723. */
  11724. this.r = 1;
  11725. /**
  11726. * The green component.
  11727. *
  11728. * @type {number}
  11729. * @default 1
  11730. */
  11731. this.g = 1;
  11732. /**
  11733. * The blue component.
  11734. *
  11735. * @type {number}
  11736. * @default 1
  11737. */
  11738. this.b = 1;
  11739. return this.set( r, g, b );
  11740. }
  11741. /**
  11742. * Sets the colors's components from the given values.
  11743. *
  11744. * @param {(number|string|Color)} [r] - The red component of the color. If `g` and `b` are
  11745. * not provided, it can be hexadecimal triplet, a CSS-style string or another `Color` instance.
  11746. * @param {number} [g] - The green component.
  11747. * @param {number} [b] - The blue component.
  11748. * @return {Color} A reference to this color.
  11749. */
  11750. set( r, g, b ) {
  11751. if ( g === undefined && b === undefined ) {
  11752. // r is THREE.Color, hex or string
  11753. const value = r;
  11754. if ( value && value.isColor ) {
  11755. this.copy( value );
  11756. } else if ( typeof value === 'number' ) {
  11757. this.setHex( value );
  11758. } else if ( typeof value === 'string' ) {
  11759. this.setStyle( value );
  11760. }
  11761. } else {
  11762. this.setRGB( r, g, b );
  11763. }
  11764. return this;
  11765. }
  11766. /**
  11767. * Sets the colors's components to the given scalar value.
  11768. *
  11769. * @param {number} scalar - The scalar value.
  11770. * @return {Color} A reference to this color.
  11771. */
  11772. setScalar( scalar ) {
  11773. this.r = scalar;
  11774. this.g = scalar;
  11775. this.b = scalar;
  11776. return this;
  11777. }
  11778. /**
  11779. * Sets this color from a hexadecimal value.
  11780. *
  11781. * @param {number} hex - The hexadecimal value.
  11782. * @param {string} [colorSpace=SRGBColorSpace] - The color space.
  11783. * @return {Color} A reference to this color.
  11784. */
  11785. setHex( hex, colorSpace = SRGBColorSpace ) {
  11786. hex = Math.floor( hex );
  11787. this.r = ( hex >> 16 & 255 ) / 255;
  11788. this.g = ( hex >> 8 & 255 ) / 255;
  11789. this.b = ( hex & 255 ) / 255;
  11790. ColorManagement.colorSpaceToWorking( this, colorSpace );
  11791. return this;
  11792. }
  11793. /**
  11794. * Sets this color from RGB values.
  11795. *
  11796. * @param {number} r - Red channel value between `0.0` and `1.0`.
  11797. * @param {number} g - Green channel value between `0.0` and `1.0`.
  11798. * @param {number} b - Blue channel value between `0.0` and `1.0`.
  11799. * @param {string} [colorSpace=ColorManagement.workingColorSpace] - The color space.
  11800. * @return {Color} A reference to this color.
  11801. */
  11802. setRGB( r, g, b, colorSpace = ColorManagement.workingColorSpace ) {
  11803. this.r = r;
  11804. this.g = g;
  11805. this.b = b;
  11806. ColorManagement.colorSpaceToWorking( this, colorSpace );
  11807. return this;
  11808. }
  11809. /**
  11810. * Sets this color from RGB values.
  11811. *
  11812. * @param {number} h - Hue value between `0.0` and `1.0`.
  11813. * @param {number} s - Saturation value between `0.0` and `1.0`.
  11814. * @param {number} l - Lightness value between `0.0` and `1.0`.
  11815. * @param {string} [colorSpace=ColorManagement.workingColorSpace] - The color space.
  11816. * @return {Color} A reference to this color.
  11817. */
  11818. setHSL( h, s, l, colorSpace = ColorManagement.workingColorSpace ) {
  11819. // h,s,l ranges are in 0.0 - 1.0
  11820. h = euclideanModulo( h, 1 );
  11821. s = clamp( s, 0, 1 );
  11822. l = clamp( l, 0, 1 );
  11823. if ( s === 0 ) {
  11824. this.r = this.g = this.b = l;
  11825. } else {
  11826. const p = l <= 0.5 ? l * ( 1 + s ) : l + s - ( l * s );
  11827. const q = ( 2 * l ) - p;
  11828. this.r = hue2rgb( q, p, h + 1 / 3 );
  11829. this.g = hue2rgb( q, p, h );
  11830. this.b = hue2rgb( q, p, h - 1 / 3 );
  11831. }
  11832. ColorManagement.colorSpaceToWorking( this, colorSpace );
  11833. return this;
  11834. }
  11835. /**
  11836. * Sets this color from a CSS-style string. For example, `rgb(250, 0,0)`,
  11837. * `rgb(100%, 0%, 0%)`, `hsl(0, 100%, 50%)`, `#ff0000`, `#f00`, or `red` ( or
  11838. * any [X11 color name](https://en.wikipedia.org/wiki/X11_color_names#Color_name_chart) -
  11839. * all 140 color names are supported).
  11840. *
  11841. * @param {string} style - Color as a CSS-style string.
  11842. * @param {string} [colorSpace=SRGBColorSpace] - The color space.
  11843. * @return {Color} A reference to this color.
  11844. */
  11845. setStyle( style, colorSpace = SRGBColorSpace ) {
  11846. function handleAlpha( string ) {
  11847. if ( string === undefined ) return;
  11848. if ( parseFloat( string ) < 1 ) {
  11849. warn( 'Color: Alpha component of ' + style + ' will be ignored.' );
  11850. }
  11851. }
  11852. let m;
  11853. if ( m = /^(\w+)\(([^\)]*)\)/.exec( style ) ) {
  11854. // rgb / hsl
  11855. let color;
  11856. const name = m[ 1 ];
  11857. const components = m[ 2 ];
  11858. switch ( name ) {
  11859. case 'rgb':
  11860. case 'rgba':
  11861. if ( color = /^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) {
  11862. // rgb(255,0,0) rgba(255,0,0,0.5)
  11863. handleAlpha( color[ 4 ] );
  11864. return this.setRGB(
  11865. Math.min( 255, parseInt( color[ 1 ], 10 ) ) / 255,
  11866. Math.min( 255, parseInt( color[ 2 ], 10 ) ) / 255,
  11867. Math.min( 255, parseInt( color[ 3 ], 10 ) ) / 255,
  11868. colorSpace
  11869. );
  11870. }
  11871. if ( color = /^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) {
  11872. // rgb(100%,0%,0%) rgba(100%,0%,0%,0.5)
  11873. handleAlpha( color[ 4 ] );
  11874. return this.setRGB(
  11875. Math.min( 100, parseInt( color[ 1 ], 10 ) ) / 100,
  11876. Math.min( 100, parseInt( color[ 2 ], 10 ) ) / 100,
  11877. Math.min( 100, parseInt( color[ 3 ], 10 ) ) / 100,
  11878. colorSpace
  11879. );
  11880. }
  11881. break;
  11882. case 'hsl':
  11883. case 'hsla':
  11884. if ( color = /^\s*(\d*\.?\d+)\s*,\s*(\d*\.?\d+)\%\s*,\s*(\d*\.?\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) {
  11885. // hsl(120,50%,50%) hsla(120,50%,50%,0.5)
  11886. handleAlpha( color[ 4 ] );
  11887. return this.setHSL(
  11888. parseFloat( color[ 1 ] ) / 360,
  11889. parseFloat( color[ 2 ] ) / 100,
  11890. parseFloat( color[ 3 ] ) / 100,
  11891. colorSpace
  11892. );
  11893. }
  11894. break;
  11895. default:
  11896. warn( 'Color: Unknown color model ' + style );
  11897. }
  11898. } else if ( m = /^\#([A-Fa-f\d]+)$/.exec( style ) ) {
  11899. // hex color
  11900. const hex = m[ 1 ];
  11901. const size = hex.length;
  11902. if ( size === 3 ) {
  11903. // #ff0
  11904. return this.setRGB(
  11905. parseInt( hex.charAt( 0 ), 16 ) / 15,
  11906. parseInt( hex.charAt( 1 ), 16 ) / 15,
  11907. parseInt( hex.charAt( 2 ), 16 ) / 15,
  11908. colorSpace
  11909. );
  11910. } else if ( size === 6 ) {
  11911. // #ff0000
  11912. return this.setHex( parseInt( hex, 16 ), colorSpace );
  11913. } else {
  11914. warn( 'Color: Invalid hex color ' + style );
  11915. }
  11916. } else if ( style && style.length > 0 ) {
  11917. return this.setColorName( style, colorSpace );
  11918. }
  11919. return this;
  11920. }
  11921. /**
  11922. * Sets this color from a color name. Faster than {@link Color#setStyle} if
  11923. * you don't need the other CSS-style formats.
  11924. *
  11925. * For convenience, the list of names is exposed in `Color.NAMES` as a hash.
  11926. * ```js
  11927. * Color.NAMES.aliceblue // returns 0xF0F8FF
  11928. * ```
  11929. *
  11930. * @param {string} style - The color name.
  11931. * @param {string} [colorSpace=SRGBColorSpace] - The color space.
  11932. * @return {Color} A reference to this color.
  11933. */
  11934. setColorName( style, colorSpace = SRGBColorSpace ) {
  11935. // color keywords
  11936. const hex = _colorKeywords[ style.toLowerCase() ];
  11937. if ( hex !== undefined ) {
  11938. // red
  11939. this.setHex( hex, colorSpace );
  11940. } else {
  11941. // unknown color
  11942. warn( 'Color: Unknown color ' + style );
  11943. }
  11944. return this;
  11945. }
  11946. /**
  11947. * Returns a new color with copied values from this instance.
  11948. *
  11949. * @return {Color} A clone of this instance.
  11950. */
  11951. clone() {
  11952. return new this.constructor( this.r, this.g, this.b );
  11953. }
  11954. /**
  11955. * Copies the values of the given color to this instance.
  11956. *
  11957. * @param {Color} color - The color to copy.
  11958. * @return {Color} A reference to this color.
  11959. */
  11960. copy( color ) {
  11961. this.r = color.r;
  11962. this.g = color.g;
  11963. this.b = color.b;
  11964. return this;
  11965. }
  11966. /**
  11967. * Copies the given color into this color, and then converts this color from
  11968. * `SRGBColorSpace` to `LinearSRGBColorSpace`.
  11969. *
  11970. * @param {Color} color - The color to copy/convert.
  11971. * @return {Color} A reference to this color.
  11972. */
  11973. copySRGBToLinear( color ) {
  11974. this.r = SRGBToLinear( color.r );
  11975. this.g = SRGBToLinear( color.g );
  11976. this.b = SRGBToLinear( color.b );
  11977. return this;
  11978. }
  11979. /**
  11980. * Copies the given color into this color, and then converts this color from
  11981. * `LinearSRGBColorSpace` to `SRGBColorSpace`.
  11982. *
  11983. * @param {Color} color - The color to copy/convert.
  11984. * @return {Color} A reference to this color.
  11985. */
  11986. copyLinearToSRGB( color ) {
  11987. this.r = LinearToSRGB( color.r );
  11988. this.g = LinearToSRGB( color.g );
  11989. this.b = LinearToSRGB( color.b );
  11990. return this;
  11991. }
  11992. /**
  11993. * Converts this color from `SRGBColorSpace` to `LinearSRGBColorSpace`.
  11994. *
  11995. * @return {Color} A reference to this color.
  11996. */
  11997. convertSRGBToLinear() {
  11998. this.copySRGBToLinear( this );
  11999. return this;
  12000. }
  12001. /**
  12002. * Converts this color from `LinearSRGBColorSpace` to `SRGBColorSpace`.
  12003. *
  12004. * @return {Color} A reference to this color.
  12005. */
  12006. convertLinearToSRGB() {
  12007. this.copyLinearToSRGB( this );
  12008. return this;
  12009. }
  12010. /**
  12011. * Returns the hexadecimal value of this color.
  12012. *
  12013. * @param {string} [colorSpace=SRGBColorSpace] - The color space.
  12014. * @return {number} The hexadecimal value.
  12015. */
  12016. getHex( colorSpace = SRGBColorSpace ) {
  12017. ColorManagement.workingToColorSpace( _color.copy( this ), colorSpace );
  12018. 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 ) );
  12019. }
  12020. /**
  12021. * Returns the hexadecimal value of this color as a string (for example, 'FFFFFF').
  12022. *
  12023. * @param {string} [colorSpace=SRGBColorSpace] - The color space.
  12024. * @return {string} The hexadecimal value as a string.
  12025. */
  12026. getHexString( colorSpace = SRGBColorSpace ) {
  12027. return ( '000000' + this.getHex( colorSpace ).toString( 16 ) ).slice( -6 );
  12028. }
  12029. /**
  12030. * Converts the colors RGB values into the HSL format and stores them into the
  12031. * given target object.
  12032. *
  12033. * @param {{h:number,s:number,l:number}} target - The target object that is used to store the method's result.
  12034. * @param {string} [colorSpace=ColorManagement.workingColorSpace] - The color space.
  12035. * @return {{h:number,s:number,l:number}} The HSL representation of this color.
  12036. */
  12037. getHSL( target, colorSpace = ColorManagement.workingColorSpace ) {
  12038. // h,s,l ranges are in 0.0 - 1.0
  12039. ColorManagement.workingToColorSpace( _color.copy( this ), colorSpace );
  12040. const r = _color.r, g = _color.g, b = _color.b;
  12041. const max = Math.max( r, g, b );
  12042. const min = Math.min( r, g, b );
  12043. let hue, saturation;
  12044. const lightness = ( min + max ) / 2.0;
  12045. if ( min === max ) {
  12046. hue = 0;
  12047. saturation = 0;
  12048. } else {
  12049. const delta = max - min;
  12050. saturation = lightness <= 0.5 ? delta / ( max + min ) : delta / ( 2 - max - min );
  12051. switch ( max ) {
  12052. case r: hue = ( g - b ) / delta + ( g < b ? 6 : 0 ); break;
  12053. case g: hue = ( b - r ) / delta + 2; break;
  12054. case b: hue = ( r - g ) / delta + 4; break;
  12055. }
  12056. hue /= 6;
  12057. }
  12058. target.h = hue;
  12059. target.s = saturation;
  12060. target.l = lightness;
  12061. return target;
  12062. }
  12063. /**
  12064. * Returns the RGB values of this color and stores them into the given target object.
  12065. *
  12066. * @param {Color} target - The target color that is used to store the method's result.
  12067. * @param {string} [colorSpace=ColorManagement.workingColorSpace] - The color space.
  12068. * @return {Color} The RGB representation of this color.
  12069. */
  12070. getRGB( target, colorSpace = ColorManagement.workingColorSpace ) {
  12071. ColorManagement.workingToColorSpace( _color.copy( this ), colorSpace );
  12072. target.r = _color.r;
  12073. target.g = _color.g;
  12074. target.b = _color.b;
  12075. return target;
  12076. }
  12077. /**
  12078. * Returns the value of this color as a CSS style string. Example: `rgb(255,0,0)`.
  12079. *
  12080. * @param {string} [colorSpace=SRGBColorSpace] - The color space.
  12081. * @return {string} The CSS representation of this color.
  12082. */
  12083. getStyle( colorSpace = SRGBColorSpace ) {
  12084. ColorManagement.workingToColorSpace( _color.copy( this ), colorSpace );
  12085. const r = _color.r, g = _color.g, b = _color.b;
  12086. if ( colorSpace !== SRGBColorSpace ) {
  12087. // Requires CSS Color Module Level 4 (https://www.w3.org/TR/css-color-4/).
  12088. return `color(${ colorSpace } ${ r.toFixed( 3 ) } ${ g.toFixed( 3 ) } ${ b.toFixed( 3 ) })`;
  12089. }
  12090. return `rgb(${ Math.round( r * 255 ) },${ Math.round( g * 255 ) },${ Math.round( b * 255 ) })`;
  12091. }
  12092. /**
  12093. * Adds the given HSL values to this color's values.
  12094. * Internally, this converts the color's RGB values to HSL, adds HSL
  12095. * and then converts the color back to RGB.
  12096. *
  12097. * @param {number} h - Hue value between `0.0` and `1.0`.
  12098. * @param {number} s - Saturation value between `0.0` and `1.0`.
  12099. * @param {number} l - Lightness value between `0.0` and `1.0`.
  12100. * @return {Color} A reference to this color.
  12101. */
  12102. offsetHSL( h, s, l ) {
  12103. this.getHSL( _hslA );
  12104. return this.setHSL( _hslA.h + h, _hslA.s + s, _hslA.l + l );
  12105. }
  12106. /**
  12107. * Adds the RGB values of the given color to the RGB values of this color.
  12108. *
  12109. * @param {Color} color - The color to add.
  12110. * @return {Color} A reference to this color.
  12111. */
  12112. add( color ) {
  12113. this.r += color.r;
  12114. this.g += color.g;
  12115. this.b += color.b;
  12116. return this;
  12117. }
  12118. /**
  12119. * Adds the RGB values of the given colors and stores the result in this instance.
  12120. *
  12121. * @param {Color} color1 - The first color.
  12122. * @param {Color} color2 - The second color.
  12123. * @return {Color} A reference to this color.
  12124. */
  12125. addColors( color1, color2 ) {
  12126. this.r = color1.r + color2.r;
  12127. this.g = color1.g + color2.g;
  12128. this.b = color1.b + color2.b;
  12129. return this;
  12130. }
  12131. /**
  12132. * Adds the given scalar value to the RGB values of this color.
  12133. *
  12134. * @param {number} s - The scalar to add.
  12135. * @return {Color} A reference to this color.
  12136. */
  12137. addScalar( s ) {
  12138. this.r += s;
  12139. this.g += s;
  12140. this.b += s;
  12141. return this;
  12142. }
  12143. /**
  12144. * Subtracts the RGB values of the given color from the RGB values of this color.
  12145. *
  12146. * @param {Color} color - The color to subtract.
  12147. * @return {Color} A reference to this color.
  12148. */
  12149. sub( color ) {
  12150. this.r = Math.max( 0, this.r - color.r );
  12151. this.g = Math.max( 0, this.g - color.g );
  12152. this.b = Math.max( 0, this.b - color.b );
  12153. return this;
  12154. }
  12155. /**
  12156. * Multiplies the RGB values of the given color with the RGB values of this color.
  12157. *
  12158. * @param {Color} color - The color to multiply.
  12159. * @return {Color} A reference to this color.
  12160. */
  12161. multiply( color ) {
  12162. this.r *= color.r;
  12163. this.g *= color.g;
  12164. this.b *= color.b;
  12165. return this;
  12166. }
  12167. /**
  12168. * Multiplies the given scalar value with the RGB values of this color.
  12169. *
  12170. * @param {number} s - The scalar to multiply.
  12171. * @return {Color} A reference to this color.
  12172. */
  12173. multiplyScalar( s ) {
  12174. this.r *= s;
  12175. this.g *= s;
  12176. this.b *= s;
  12177. return this;
  12178. }
  12179. /**
  12180. * Linearly interpolates this color's RGB values toward the RGB values of the
  12181. * given color. The alpha argument can be thought of as the ratio between
  12182. * the two colors, where `0.0` is this color and `1.0` is the first argument.
  12183. *
  12184. * @param {Color} color - The color to converge on.
  12185. * @param {number} alpha - The interpolation factor in the closed interval `[0,1]`.
  12186. * @return {Color} A reference to this color.
  12187. */
  12188. lerp( color, alpha ) {
  12189. this.r += ( color.r - this.r ) * alpha;
  12190. this.g += ( color.g - this.g ) * alpha;
  12191. this.b += ( color.b - this.b ) * alpha;
  12192. return this;
  12193. }
  12194. /**
  12195. * Linearly interpolates between the given colors and stores the result in this instance.
  12196. * The alpha argument can be thought of as the ratio between the two colors, where `0.0`
  12197. * is the first and `1.0` is the second color.
  12198. *
  12199. * @param {Color} color1 - The first color.
  12200. * @param {Color} color2 - The second color.
  12201. * @param {number} alpha - The interpolation factor in the closed interval `[0,1]`.
  12202. * @return {Color} A reference to this color.
  12203. */
  12204. lerpColors( color1, color2, alpha ) {
  12205. this.r = color1.r + ( color2.r - color1.r ) * alpha;
  12206. this.g = color1.g + ( color2.g - color1.g ) * alpha;
  12207. this.b = color1.b + ( color2.b - color1.b ) * alpha;
  12208. return this;
  12209. }
  12210. /**
  12211. * Linearly interpolates this color's HSL values toward the HSL values of the
  12212. * given color. It differs from {@link Color#lerp} by not interpolating straight
  12213. * from one color to the other, but instead going through all the hues in between
  12214. * those two colors. The alpha argument can be thought of as the ratio between
  12215. * the two colors, where 0.0 is this color and 1.0 is the first argument.
  12216. *
  12217. * @param {Color} color - The color to converge on.
  12218. * @param {number} alpha - The interpolation factor in the closed interval `[0,1]`.
  12219. * @return {Color} A reference to this color.
  12220. */
  12221. lerpHSL( color, alpha ) {
  12222. this.getHSL( _hslA );
  12223. color.getHSL( _hslB );
  12224. const h = lerp( _hslA.h, _hslB.h, alpha );
  12225. const s = lerp( _hslA.s, _hslB.s, alpha );
  12226. const l = lerp( _hslA.l, _hslB.l, alpha );
  12227. this.setHSL( h, s, l );
  12228. return this;
  12229. }
  12230. /**
  12231. * Sets the color's RGB components from the given 3D vector.
  12232. *
  12233. * @param {Vector3} v - The vector to set.
  12234. * @return {Color} A reference to this color.
  12235. */
  12236. setFromVector3( v ) {
  12237. this.r = v.x;
  12238. this.g = v.y;
  12239. this.b = v.z;
  12240. return this;
  12241. }
  12242. /**
  12243. * Transforms this color with the given 3x3 matrix.
  12244. *
  12245. * @param {Matrix3} m - The matrix.
  12246. * @return {Color} A reference to this color.
  12247. */
  12248. applyMatrix3( m ) {
  12249. const r = this.r, g = this.g, b = this.b;
  12250. const e = m.elements;
  12251. this.r = e[ 0 ] * r + e[ 3 ] * g + e[ 6 ] * b;
  12252. this.g = e[ 1 ] * r + e[ 4 ] * g + e[ 7 ] * b;
  12253. this.b = e[ 2 ] * r + e[ 5 ] * g + e[ 8 ] * b;
  12254. return this;
  12255. }
  12256. /**
  12257. * Returns `true` if this color is equal with the given one.
  12258. *
  12259. * @param {Color} c - The color to test for equality.
  12260. * @return {boolean} Whether this bounding color is equal with the given one.
  12261. */
  12262. equals( c ) {
  12263. return ( c.r === this.r ) && ( c.g === this.g ) && ( c.b === this.b );
  12264. }
  12265. /**
  12266. * Sets this color's RGB components from the given array.
  12267. *
  12268. * @param {Array<number>} array - An array holding the RGB values.
  12269. * @param {number} [offset=0] - The offset into the array.
  12270. * @return {Color} A reference to this color.
  12271. */
  12272. fromArray( array, offset = 0 ) {
  12273. this.r = array[ offset ];
  12274. this.g = array[ offset + 1 ];
  12275. this.b = array[ offset + 2 ];
  12276. return this;
  12277. }
  12278. /**
  12279. * Writes the RGB components of this color to the given array. If no array is provided,
  12280. * the method returns a new instance.
  12281. *
  12282. * @param {Array<number>} [array=[]] - The target array holding the color components.
  12283. * @param {number} [offset=0] - Index of the first element in the array.
  12284. * @return {Array<number>} The color components.
  12285. */
  12286. toArray( array = [], offset = 0 ) {
  12287. array[ offset ] = this.r;
  12288. array[ offset + 1 ] = this.g;
  12289. array[ offset + 2 ] = this.b;
  12290. return array;
  12291. }
  12292. /**
  12293. * Sets the components of this color from the given buffer attribute.
  12294. *
  12295. * @param {BufferAttribute} attribute - The buffer attribute holding color data.
  12296. * @param {number} index - The index into the attribute.
  12297. * @return {Color} A reference to this color.
  12298. */
  12299. fromBufferAttribute( attribute, index ) {
  12300. this.r = attribute.getX( index );
  12301. this.g = attribute.getY( index );
  12302. this.b = attribute.getZ( index );
  12303. return this;
  12304. }
  12305. /**
  12306. * This methods defines the serialization result of this class. Returns the color
  12307. * as a hexadecimal value.
  12308. *
  12309. * @return {number} The hexadecimal value.
  12310. */
  12311. toJSON() {
  12312. return this.getHex();
  12313. }
  12314. *[ Symbol.iterator ]() {
  12315. yield this.r;
  12316. yield this.g;
  12317. yield this.b;
  12318. }
  12319. }
  12320. const _color = /*@__PURE__*/ new Color();
  12321. /**
  12322. * A dictionary with X11 color names.
  12323. *
  12324. * Note that multiple words such as Dark Orange become the string 'darkorange'.
  12325. *
  12326. * @static
  12327. * @type {Object}
  12328. */
  12329. Color.NAMES = _colorKeywords;
  12330. let _materialId = 0;
  12331. /**
  12332. * Abstract base class for materials.
  12333. *
  12334. * Materials define the appearance of renderable 3D objects.
  12335. *
  12336. * @abstract
  12337. * @augments EventDispatcher
  12338. */
  12339. class Material extends EventDispatcher {
  12340. /**
  12341. * Constructs a new material.
  12342. */
  12343. constructor() {
  12344. super();
  12345. /**
  12346. * This flag can be used for type testing.
  12347. *
  12348. * @type {boolean}
  12349. * @readonly
  12350. * @default true
  12351. */
  12352. this.isMaterial = true;
  12353. /**
  12354. * The ID of the material.
  12355. *
  12356. * @name Material#id
  12357. * @type {number}
  12358. * @readonly
  12359. */
  12360. Object.defineProperty( this, 'id', { value: _materialId ++ } );
  12361. /**
  12362. * The UUID of the material.
  12363. *
  12364. * @type {string}
  12365. * @readonly
  12366. */
  12367. this.uuid = generateUUID();
  12368. /**
  12369. * The name of the material.
  12370. *
  12371. * @type {string}
  12372. */
  12373. this.name = '';
  12374. /**
  12375. * The type property is used for detecting the object type
  12376. * in context of serialization/deserialization.
  12377. *
  12378. * @type {string}
  12379. * @readonly
  12380. */
  12381. this.type = 'Material';
  12382. /**
  12383. * Defines the blending type of the material.
  12384. *
  12385. * It must be set to `CustomBlending` if custom blending properties like
  12386. * {@link Material#blendSrc}, {@link Material#blendDst} or {@link Material#blendEquation}
  12387. * should have any effect.
  12388. *
  12389. * @type {(NoBlending|NormalBlending|AdditiveBlending|SubtractiveBlending|MultiplyBlending|CustomBlending)}
  12390. * @default NormalBlending
  12391. */
  12392. this.blending = NormalBlending;
  12393. /**
  12394. * Defines which side of faces will be rendered - front, back or both.
  12395. *
  12396. * @type {(FrontSide|BackSide|DoubleSide)}
  12397. * @default FrontSide
  12398. */
  12399. this.side = FrontSide;
  12400. /**
  12401. * If set to `true`, vertex colors should be used.
  12402. *
  12403. * The engine supports RGB and RGBA vertex colors depending on whether a three (RGB) or
  12404. * four (RGBA) component color buffer attribute is used.
  12405. *
  12406. * @type {boolean}
  12407. * @default false
  12408. */
  12409. this.vertexColors = false;
  12410. /**
  12411. * Defines how transparent the material is.
  12412. * A value of `0.0` indicates fully transparent, `1.0` is fully opaque.
  12413. *
  12414. * If the {@link Material#transparent} is not set to `true`,
  12415. * the material will remain fully opaque and this value will only affect its color.
  12416. *
  12417. * @type {number}
  12418. * @default 1
  12419. */
  12420. this.opacity = 1;
  12421. /**
  12422. * Defines whether this material is transparent. This has an effect on
  12423. * rendering as transparent objects need special treatment and are rendered
  12424. * after non-transparent objects.
  12425. *
  12426. * When set to true, the extent to which the material is transparent is
  12427. * controlled by {@link Material#opacity}.
  12428. *
  12429. * @type {boolean}
  12430. * @default false
  12431. */
  12432. this.transparent = false;
  12433. /**
  12434. * Enables alpha hashed transparency, an alternative to {@link Material#transparent} or
  12435. * {@link Material#alphaTest}. The material will not be rendered if opacity is lower than
  12436. * a random threshold. Randomization introduces some grain or noise, but approximates alpha
  12437. * blending without the associated problems of sorting. Using TAA can reduce the resulting noise.
  12438. *
  12439. * @type {boolean}
  12440. * @default false
  12441. */
  12442. this.alphaHash = false;
  12443. /**
  12444. * Defines the blending source factor.
  12445. *
  12446. * @type {(ZeroFactor|OneFactor|SrcColorFactor|OneMinusSrcColorFactor|SrcAlphaFactor|OneMinusSrcAlphaFactor|DstAlphaFactor|OneMinusDstAlphaFactor|DstColorFactor|OneMinusDstColorFactor|SrcAlphaSaturateFactor|ConstantColorFactor|OneMinusConstantColorFactor|ConstantAlphaFactor|OneMinusConstantAlphaFactor)}
  12447. * @default SrcAlphaFactor
  12448. */
  12449. this.blendSrc = SrcAlphaFactor;
  12450. /**
  12451. * Defines the blending destination factor.
  12452. *
  12453. * @type {(ZeroFactor|OneFactor|SrcColorFactor|OneMinusSrcColorFactor|SrcAlphaFactor|OneMinusSrcAlphaFactor|DstAlphaFactor|OneMinusDstAlphaFactor|DstColorFactor|OneMinusDstColorFactor|SrcAlphaSaturateFactor|ConstantColorFactor|OneMinusConstantColorFactor|ConstantAlphaFactor|OneMinusConstantAlphaFactor)}
  12454. * @default OneMinusSrcAlphaFactor
  12455. */
  12456. this.blendDst = OneMinusSrcAlphaFactor;
  12457. /**
  12458. * Defines the blending equation.
  12459. *
  12460. * @type {(AddEquation|SubtractEquation|ReverseSubtractEquation|MinEquation|MaxEquation)}
  12461. * @default AddEquation
  12462. */
  12463. this.blendEquation = AddEquation;
  12464. /**
  12465. * Defines the blending source alpha factor.
  12466. *
  12467. * @type {?(ZeroFactor|OneFactor|SrcColorFactor|OneMinusSrcColorFactor|SrcAlphaFactor|OneMinusSrcAlphaFactor|DstAlphaFactor|OneMinusDstAlphaFactor|DstColorFactor|OneMinusDstColorFactor|SrcAlphaSaturateFactor|ConstantColorFactor|OneMinusConstantColorFactor|ConstantAlphaFactor|OneMinusConstantAlphaFactor)}
  12468. * @default null
  12469. */
  12470. this.blendSrcAlpha = null;
  12471. /**
  12472. * Defines the blending destination alpha factor.
  12473. *
  12474. * @type {?(ZeroFactor|OneFactor|SrcColorFactor|OneMinusSrcColorFactor|SrcAlphaFactor|OneMinusSrcAlphaFactor|DstAlphaFactor|OneMinusDstAlphaFactor|DstColorFactor|OneMinusDstColorFactor|SrcAlphaSaturateFactor|ConstantColorFactor|OneMinusConstantColorFactor|ConstantAlphaFactor|OneMinusConstantAlphaFactor)}
  12475. * @default null
  12476. */
  12477. this.blendDstAlpha = null;
  12478. /**
  12479. * Defines the blending equation of the alpha channel.
  12480. *
  12481. * @type {?(AddEquation|SubtractEquation|ReverseSubtractEquation|MinEquation|MaxEquation)}
  12482. * @default null
  12483. */
  12484. this.blendEquationAlpha = null;
  12485. /**
  12486. * Represents the RGB values of the constant blend color.
  12487. *
  12488. * This property has only an effect when using custom blending with `ConstantColor` or `OneMinusConstantColor`.
  12489. *
  12490. * @type {Color}
  12491. * @default (0,0,0)
  12492. */
  12493. this.blendColor = new Color( 0, 0, 0 );
  12494. /**
  12495. * Represents the alpha value of the constant blend color.
  12496. *
  12497. * This property has only an effect when using custom blending with `ConstantAlpha` or `OneMinusConstantAlpha`.
  12498. *
  12499. * @type {number}
  12500. * @default 0
  12501. */
  12502. this.blendAlpha = 0;
  12503. /**
  12504. * Defines the depth function.
  12505. *
  12506. * @type {(NeverDepth|AlwaysDepth|LessDepth|LessEqualDepth|EqualDepth|GreaterEqualDepth|GreaterDepth|NotEqualDepth)}
  12507. * @default LessEqualDepth
  12508. */
  12509. this.depthFunc = LessEqualDepth;
  12510. /**
  12511. * Whether to have depth test enabled when rendering this material.
  12512. * When the depth test is disabled, the depth write will also be implicitly disabled.
  12513. *
  12514. * @type {boolean}
  12515. * @default true
  12516. */
  12517. this.depthTest = true;
  12518. /**
  12519. * Whether rendering this material has any effect on the depth buffer.
  12520. *
  12521. * When drawing 2D overlays it can be useful to disable the depth writing in
  12522. * order to layer several things together without creating z-index artifacts.
  12523. *
  12524. * @type {boolean}
  12525. * @default true
  12526. */
  12527. this.depthWrite = true;
  12528. /**
  12529. * The bit mask to use when writing to the stencil buffer.
  12530. *
  12531. * @type {number}
  12532. * @default 0xff
  12533. */
  12534. this.stencilWriteMask = 0xff;
  12535. /**
  12536. * The stencil comparison function to use.
  12537. *
  12538. * @type {NeverStencilFunc|LessStencilFunc|EqualStencilFunc|LessEqualStencilFunc|GreaterStencilFunc|NotEqualStencilFunc|GreaterEqualStencilFunc|AlwaysStencilFunc}
  12539. * @default AlwaysStencilFunc
  12540. */
  12541. this.stencilFunc = AlwaysStencilFunc;
  12542. /**
  12543. * The value to use when performing stencil comparisons or stencil operations.
  12544. *
  12545. * @type {number}
  12546. * @default 0
  12547. */
  12548. this.stencilRef = 0;
  12549. /**
  12550. * The bit mask to use when comparing against the stencil buffer.
  12551. *
  12552. * @type {number}
  12553. * @default 0xff
  12554. */
  12555. this.stencilFuncMask = 0xff;
  12556. /**
  12557. * Which stencil operation to perform when the comparison function returns `false`.
  12558. *
  12559. * @type {ZeroStencilOp|KeepStencilOp|ReplaceStencilOp|IncrementStencilOp|DecrementStencilOp|IncrementWrapStencilOp|DecrementWrapStencilOp|InvertStencilOp}
  12560. * @default KeepStencilOp
  12561. */
  12562. this.stencilFail = KeepStencilOp;
  12563. /**
  12564. * Which stencil operation to perform when the comparison function returns
  12565. * `true` but the depth test fails.
  12566. *
  12567. * @type {ZeroStencilOp|KeepStencilOp|ReplaceStencilOp|IncrementStencilOp|DecrementStencilOp|IncrementWrapStencilOp|DecrementWrapStencilOp|InvertStencilOp}
  12568. * @default KeepStencilOp
  12569. */
  12570. this.stencilZFail = KeepStencilOp;
  12571. /**
  12572. * Which stencil operation to perform when the comparison function returns
  12573. * `true` and the depth test passes.
  12574. *
  12575. * @type {ZeroStencilOp|KeepStencilOp|ReplaceStencilOp|IncrementStencilOp|DecrementStencilOp|IncrementWrapStencilOp|DecrementWrapStencilOp|InvertStencilOp}
  12576. * @default KeepStencilOp
  12577. */
  12578. this.stencilZPass = KeepStencilOp;
  12579. /**
  12580. * Whether stencil operations are performed against the stencil buffer. In
  12581. * order to perform writes or comparisons against the stencil buffer this
  12582. * value must be `true`.
  12583. *
  12584. * @type {boolean}
  12585. * @default false
  12586. */
  12587. this.stencilWrite = false;
  12588. /**
  12589. * User-defined clipping planes specified as THREE.Plane objects in world
  12590. * space. These planes apply to the objects this material is attached to.
  12591. * Points in space whose signed distance to the plane is negative are clipped
  12592. * (not rendered). This requires {@link WebGLRenderer#localClippingEnabled} to
  12593. * be `true`.
  12594. *
  12595. * @type {?Array<Plane>}
  12596. * @default null
  12597. */
  12598. this.clippingPlanes = null;
  12599. /**
  12600. * Changes the behavior of clipping planes so that only their intersection is
  12601. * clipped, rather than their union.
  12602. *
  12603. * @type {boolean}
  12604. * @default false
  12605. */
  12606. this.clipIntersection = false;
  12607. /**
  12608. * Defines whether to clip shadows according to the clipping planes specified
  12609. * on this material.
  12610. *
  12611. * @type {boolean}
  12612. * @default false
  12613. */
  12614. this.clipShadows = false;
  12615. /**
  12616. * Defines which side of faces cast shadows. If `null`, the side casting shadows
  12617. * is determined as follows:
  12618. *
  12619. * - When {@link Material#side} is set to `FrontSide`, the back side cast shadows.
  12620. * - When {@link Material#side} is set to `BackSide`, the front side cast shadows.
  12621. * - When {@link Material#side} is set to `DoubleSide`, both sides cast shadows.
  12622. *
  12623. * @type {?(FrontSide|BackSide|DoubleSide)}
  12624. * @default null
  12625. */
  12626. this.shadowSide = null;
  12627. /**
  12628. * Whether to render the material's color.
  12629. *
  12630. * This can be used in conjunction with {@link Object3D#renderOder} to create invisible
  12631. * objects that occlude other objects.
  12632. *
  12633. * @type {boolean}
  12634. * @default true
  12635. */
  12636. this.colorWrite = true;
  12637. /**
  12638. * Override the renderer's default precision for this material.
  12639. *
  12640. * @type {?('highp'|'mediump'|'lowp')}
  12641. * @default null
  12642. */
  12643. this.precision = null;
  12644. /**
  12645. * Whether to use polygon offset or not. When enabled, each fragment's depth value will
  12646. * be offset after it is interpolated from the depth values of the appropriate vertices.
  12647. * The offset is added before the depth test is performed and before the value is written
  12648. * into the depth buffer.
  12649. *
  12650. * Can be useful for rendering hidden-line images, for applying decals to surfaces, and for
  12651. * rendering solids with highlighted edges.
  12652. *
  12653. * @type {boolean}
  12654. * @default false
  12655. */
  12656. this.polygonOffset = false;
  12657. /**
  12658. * Specifies a scale factor that is used to create a variable depth offset for each polygon.
  12659. *
  12660. * @type {number}
  12661. * @default 0
  12662. */
  12663. this.polygonOffsetFactor = 0;
  12664. /**
  12665. * Is multiplied by an implementation-specific value to create a constant depth offset.
  12666. *
  12667. * @type {number}
  12668. * @default 0
  12669. */
  12670. this.polygonOffsetUnits = 0;
  12671. /**
  12672. * Whether to apply dithering to the color to remove the appearance of banding.
  12673. *
  12674. * @type {boolean}
  12675. * @default false
  12676. */
  12677. this.dithering = false;
  12678. /**
  12679. * Whether alpha to coverage should be enabled or not. Can only be used with MSAA-enabled contexts
  12680. * (meaning when the renderer was created with *antialias* parameter set to `true`). Enabling this
  12681. * will smooth aliasing on clip plane edges and alphaTest-clipped edges.
  12682. *
  12683. * @type {boolean}
  12684. * @default false
  12685. */
  12686. this.alphaToCoverage = false;
  12687. /**
  12688. * Whether to premultiply the alpha (transparency) value.
  12689. *
  12690. * @type {boolean}
  12691. * @default false
  12692. */
  12693. this.premultipliedAlpha = false;
  12694. /**
  12695. * Whether double-sided, transparent objects should be rendered with a single pass or not.
  12696. *
  12697. * The engine renders double-sided, transparent objects with two draw calls (back faces first,
  12698. * then front faces) to mitigate transparency artifacts. There are scenarios however where this
  12699. * approach produces no quality gains but still doubles draw calls e.g. when rendering flat
  12700. * vegetation like grass sprites. In these cases, set the `forceSinglePass` flag to `true` to
  12701. * disable the two pass rendering to avoid performance issues.
  12702. *
  12703. * @type {boolean}
  12704. * @default false
  12705. */
  12706. this.forceSinglePass = false;
  12707. /**
  12708. * Whether it's possible to override the material with {@link Scene#overrideMaterial} or not.
  12709. *
  12710. * @type {boolean}
  12711. * @default true
  12712. */
  12713. this.allowOverride = true;
  12714. /**
  12715. * Defines whether 3D objects using this material are visible.
  12716. *
  12717. * @type {boolean}
  12718. * @default true
  12719. */
  12720. this.visible = true;
  12721. /**
  12722. * Defines whether this material is tone mapped according to the renderer's tone mapping setting.
  12723. *
  12724. * It is ignored when rendering to a render target or using post processing or when using
  12725. * `WebGPURenderer`. In all these cases, all materials are honored by tone mapping.
  12726. *
  12727. * @type {boolean}
  12728. * @default true
  12729. */
  12730. this.toneMapped = true;
  12731. /**
  12732. * An object that can be used to store custom data about the Material. It
  12733. * should not hold references to functions as these will not be cloned.
  12734. *
  12735. * @type {Object}
  12736. */
  12737. this.userData = {};
  12738. /**
  12739. * This starts at `0` and counts how many times {@link Material#needsUpdate} is set to `true`.
  12740. *
  12741. * @type {number}
  12742. * @readonly
  12743. * @default 0
  12744. */
  12745. this.version = 0;
  12746. this._alphaTest = 0;
  12747. }
  12748. /**
  12749. * Sets the alpha value to be used when running an alpha test. The material
  12750. * will not be rendered if the opacity is lower than this value.
  12751. *
  12752. * @type {number}
  12753. * @readonly
  12754. * @default 0
  12755. */
  12756. get alphaTest() {
  12757. return this._alphaTest;
  12758. }
  12759. set alphaTest( value ) {
  12760. if ( this._alphaTest > 0 !== value > 0 ) {
  12761. this.version ++;
  12762. }
  12763. this._alphaTest = value;
  12764. }
  12765. /**
  12766. * An optional callback that is executed immediately before the material is used to render a 3D object.
  12767. *
  12768. * This method can only be used when rendering with {@link WebGLRenderer}.
  12769. *
  12770. * @param {WebGLRenderer} renderer - The renderer.
  12771. * @param {Scene} scene - The scene.
  12772. * @param {Camera} camera - The camera that is used to render the scene.
  12773. * @param {BufferGeometry} geometry - The 3D object's geometry.
  12774. * @param {Object3D} object - The 3D object.
  12775. * @param {Object} group - The geometry group data.
  12776. */
  12777. onBeforeRender( /* renderer, scene, camera, geometry, object, group */ ) {}
  12778. /**
  12779. * An optional callback that is executed immediately before the shader
  12780. * program is compiled. This function is called with the shader source code
  12781. * as a parameter. Useful for the modification of built-in materials.
  12782. *
  12783. * This method can only be used when rendering with {@link WebGLRenderer}. The
  12784. * recommended approach when customizing materials is to use `WebGPURenderer` with the new
  12785. * Node Material system and [TSL](https://github.com/mrdoob/three.js/wiki/Three.js-Shading-Language).
  12786. *
  12787. * @param {{vertexShader:string,fragmentShader:string,uniforms:Object}} shaderobject - The object holds the uniforms and the vertex and fragment shader source.
  12788. * @param {WebGLRenderer} renderer - A reference to the renderer.
  12789. */
  12790. onBeforeCompile( /* shaderobject, renderer */ ) {}
  12791. /**
  12792. * In case {@link Material#onBeforeCompile} is used, this callback can be used to identify
  12793. * values of settings used in `onBeforeCompile()`, so three.js can reuse a cached
  12794. * shader or recompile the shader for this material as needed.
  12795. *
  12796. * This method can only be used when rendering with {@link WebGLRenderer}.
  12797. *
  12798. * @return {string} The custom program cache key.
  12799. */
  12800. customProgramCacheKey() {
  12801. return this.onBeforeCompile.toString();
  12802. }
  12803. /**
  12804. * This method can be used to set default values from parameter objects.
  12805. * It is a generic implementation so it can be used with different types
  12806. * of materials.
  12807. *
  12808. * @param {Object} [values] - The material values to set.
  12809. */
  12810. setValues( values ) {
  12811. if ( values === undefined ) return;
  12812. for ( const key in values ) {
  12813. const newValue = values[ key ];
  12814. if ( newValue === undefined ) {
  12815. warn( `Material: parameter '${ key }' has value of undefined.` );
  12816. continue;
  12817. }
  12818. const currentValue = this[ key ];
  12819. if ( currentValue === undefined ) {
  12820. warn( `Material: '${ key }' is not a property of THREE.${ this.type }.` );
  12821. continue;
  12822. }
  12823. if ( currentValue && currentValue.isColor ) {
  12824. currentValue.set( newValue );
  12825. } else if ( ( currentValue && currentValue.isVector3 ) && ( newValue && newValue.isVector3 ) ) {
  12826. currentValue.copy( newValue );
  12827. } else {
  12828. this[ key ] = newValue;
  12829. }
  12830. }
  12831. }
  12832. /**
  12833. * Serializes the material into JSON.
  12834. *
  12835. * @param {?(Object|string)} meta - An optional value holding meta information about the serialization.
  12836. * @return {Object} A JSON object representing the serialized material.
  12837. * @see {@link ObjectLoader#parse}
  12838. */
  12839. toJSON( meta ) {
  12840. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  12841. if ( isRootObject ) {
  12842. meta = {
  12843. textures: {},
  12844. images: {}
  12845. };
  12846. }
  12847. const data = {
  12848. metadata: {
  12849. version: 4.7,
  12850. type: 'Material',
  12851. generator: 'Material.toJSON'
  12852. }
  12853. };
  12854. // standard Material serialization
  12855. data.uuid = this.uuid;
  12856. data.type = this.type;
  12857. if ( this.name !== '' ) data.name = this.name;
  12858. if ( this.color && this.color.isColor ) data.color = this.color.getHex();
  12859. if ( this.roughness !== undefined ) data.roughness = this.roughness;
  12860. if ( this.metalness !== undefined ) data.metalness = this.metalness;
  12861. if ( this.sheen !== undefined ) data.sheen = this.sheen;
  12862. if ( this.sheenColor && this.sheenColor.isColor ) data.sheenColor = this.sheenColor.getHex();
  12863. if ( this.sheenRoughness !== undefined ) data.sheenRoughness = this.sheenRoughness;
  12864. if ( this.emissive && this.emissive.isColor ) data.emissive = this.emissive.getHex();
  12865. if ( this.emissiveIntensity !== undefined && this.emissiveIntensity !== 1 ) data.emissiveIntensity = this.emissiveIntensity;
  12866. if ( this.specular && this.specular.isColor ) data.specular = this.specular.getHex();
  12867. if ( this.specularIntensity !== undefined ) data.specularIntensity = this.specularIntensity;
  12868. if ( this.specularColor && this.specularColor.isColor ) data.specularColor = this.specularColor.getHex();
  12869. if ( this.shininess !== undefined ) data.shininess = this.shininess;
  12870. if ( this.clearcoat !== undefined ) data.clearcoat = this.clearcoat;
  12871. if ( this.clearcoatRoughness !== undefined ) data.clearcoatRoughness = this.clearcoatRoughness;
  12872. if ( this.clearcoatMap && this.clearcoatMap.isTexture ) {
  12873. data.clearcoatMap = this.clearcoatMap.toJSON( meta ).uuid;
  12874. }
  12875. if ( this.clearcoatRoughnessMap && this.clearcoatRoughnessMap.isTexture ) {
  12876. data.clearcoatRoughnessMap = this.clearcoatRoughnessMap.toJSON( meta ).uuid;
  12877. }
  12878. if ( this.clearcoatNormalMap && this.clearcoatNormalMap.isTexture ) {
  12879. data.clearcoatNormalMap = this.clearcoatNormalMap.toJSON( meta ).uuid;
  12880. data.clearcoatNormalScale = this.clearcoatNormalScale.toArray();
  12881. }
  12882. if ( this.sheenColorMap && this.sheenColorMap.isTexture ) {
  12883. data.sheenColorMap = this.sheenColorMap.toJSON( meta ).uuid;
  12884. }
  12885. if ( this.sheenRoughnessMap && this.sheenRoughnessMap.isTexture ) {
  12886. data.sheenRoughnessMap = this.sheenRoughnessMap.toJSON( meta ).uuid;
  12887. }
  12888. if ( this.dispersion !== undefined ) data.dispersion = this.dispersion;
  12889. if ( this.iridescence !== undefined ) data.iridescence = this.iridescence;
  12890. if ( this.iridescenceIOR !== undefined ) data.iridescenceIOR = this.iridescenceIOR;
  12891. if ( this.iridescenceThicknessRange !== undefined ) data.iridescenceThicknessRange = this.iridescenceThicknessRange;
  12892. if ( this.iridescenceMap && this.iridescenceMap.isTexture ) {
  12893. data.iridescenceMap = this.iridescenceMap.toJSON( meta ).uuid;
  12894. }
  12895. if ( this.iridescenceThicknessMap && this.iridescenceThicknessMap.isTexture ) {
  12896. data.iridescenceThicknessMap = this.iridescenceThicknessMap.toJSON( meta ).uuid;
  12897. }
  12898. if ( this.anisotropy !== undefined ) data.anisotropy = this.anisotropy;
  12899. if ( this.anisotropyRotation !== undefined ) data.anisotropyRotation = this.anisotropyRotation;
  12900. if ( this.anisotropyMap && this.anisotropyMap.isTexture ) {
  12901. data.anisotropyMap = this.anisotropyMap.toJSON( meta ).uuid;
  12902. }
  12903. if ( this.map && this.map.isTexture ) data.map = this.map.toJSON( meta ).uuid;
  12904. if ( this.matcap && this.matcap.isTexture ) data.matcap = this.matcap.toJSON( meta ).uuid;
  12905. if ( this.alphaMap && this.alphaMap.isTexture ) data.alphaMap = this.alphaMap.toJSON( meta ).uuid;
  12906. if ( this.lightMap && this.lightMap.isTexture ) {
  12907. data.lightMap = this.lightMap.toJSON( meta ).uuid;
  12908. data.lightMapIntensity = this.lightMapIntensity;
  12909. }
  12910. if ( this.aoMap && this.aoMap.isTexture ) {
  12911. data.aoMap = this.aoMap.toJSON( meta ).uuid;
  12912. data.aoMapIntensity = this.aoMapIntensity;
  12913. }
  12914. if ( this.bumpMap && this.bumpMap.isTexture ) {
  12915. data.bumpMap = this.bumpMap.toJSON( meta ).uuid;
  12916. data.bumpScale = this.bumpScale;
  12917. }
  12918. if ( this.normalMap && this.normalMap.isTexture ) {
  12919. data.normalMap = this.normalMap.toJSON( meta ).uuid;
  12920. data.normalMapType = this.normalMapType;
  12921. data.normalScale = this.normalScale.toArray();
  12922. }
  12923. if ( this.displacementMap && this.displacementMap.isTexture ) {
  12924. data.displacementMap = this.displacementMap.toJSON( meta ).uuid;
  12925. data.displacementScale = this.displacementScale;
  12926. data.displacementBias = this.displacementBias;
  12927. }
  12928. if ( this.roughnessMap && this.roughnessMap.isTexture ) data.roughnessMap = this.roughnessMap.toJSON( meta ).uuid;
  12929. if ( this.metalnessMap && this.metalnessMap.isTexture ) data.metalnessMap = this.metalnessMap.toJSON( meta ).uuid;
  12930. if ( this.emissiveMap && this.emissiveMap.isTexture ) data.emissiveMap = this.emissiveMap.toJSON( meta ).uuid;
  12931. if ( this.specularMap && this.specularMap.isTexture ) data.specularMap = this.specularMap.toJSON( meta ).uuid;
  12932. if ( this.specularIntensityMap && this.specularIntensityMap.isTexture ) data.specularIntensityMap = this.specularIntensityMap.toJSON( meta ).uuid;
  12933. if ( this.specularColorMap && this.specularColorMap.isTexture ) data.specularColorMap = this.specularColorMap.toJSON( meta ).uuid;
  12934. if ( this.envMap && this.envMap.isTexture ) {
  12935. data.envMap = this.envMap.toJSON( meta ).uuid;
  12936. if ( this.combine !== undefined ) data.combine = this.combine;
  12937. }
  12938. if ( this.envMapRotation !== undefined ) data.envMapRotation = this.envMapRotation.toArray();
  12939. if ( this.envMapIntensity !== undefined ) data.envMapIntensity = this.envMapIntensity;
  12940. if ( this.reflectivity !== undefined ) data.reflectivity = this.reflectivity;
  12941. if ( this.refractionRatio !== undefined ) data.refractionRatio = this.refractionRatio;
  12942. if ( this.gradientMap && this.gradientMap.isTexture ) {
  12943. data.gradientMap = this.gradientMap.toJSON( meta ).uuid;
  12944. }
  12945. if ( this.transmission !== undefined ) data.transmission = this.transmission;
  12946. if ( this.transmissionMap && this.transmissionMap.isTexture ) data.transmissionMap = this.transmissionMap.toJSON( meta ).uuid;
  12947. if ( this.thickness !== undefined ) data.thickness = this.thickness;
  12948. if ( this.thicknessMap && this.thicknessMap.isTexture ) data.thicknessMap = this.thicknessMap.toJSON( meta ).uuid;
  12949. if ( this.attenuationDistance !== undefined && this.attenuationDistance !== Infinity ) data.attenuationDistance = this.attenuationDistance;
  12950. if ( this.attenuationColor !== undefined ) data.attenuationColor = this.attenuationColor.getHex();
  12951. if ( this.size !== undefined ) data.size = this.size;
  12952. if ( this.shadowSide !== null ) data.shadowSide = this.shadowSide;
  12953. if ( this.sizeAttenuation !== undefined ) data.sizeAttenuation = this.sizeAttenuation;
  12954. if ( this.blending !== NormalBlending ) data.blending = this.blending;
  12955. if ( this.side !== FrontSide ) data.side = this.side;
  12956. if ( this.vertexColors === true ) data.vertexColors = true;
  12957. if ( this.opacity < 1 ) data.opacity = this.opacity;
  12958. if ( this.transparent === true ) data.transparent = true;
  12959. if ( this.blendSrc !== SrcAlphaFactor ) data.blendSrc = this.blendSrc;
  12960. if ( this.blendDst !== OneMinusSrcAlphaFactor ) data.blendDst = this.blendDst;
  12961. if ( this.blendEquation !== AddEquation ) data.blendEquation = this.blendEquation;
  12962. if ( this.blendSrcAlpha !== null ) data.blendSrcAlpha = this.blendSrcAlpha;
  12963. if ( this.blendDstAlpha !== null ) data.blendDstAlpha = this.blendDstAlpha;
  12964. if ( this.blendEquationAlpha !== null ) data.blendEquationAlpha = this.blendEquationAlpha;
  12965. if ( this.blendColor && this.blendColor.isColor ) data.blendColor = this.blendColor.getHex();
  12966. if ( this.blendAlpha !== 0 ) data.blendAlpha = this.blendAlpha;
  12967. if ( this.depthFunc !== LessEqualDepth ) data.depthFunc = this.depthFunc;
  12968. if ( this.depthTest === false ) data.depthTest = this.depthTest;
  12969. if ( this.depthWrite === false ) data.depthWrite = this.depthWrite;
  12970. if ( this.colorWrite === false ) data.colorWrite = this.colorWrite;
  12971. if ( this.stencilWriteMask !== 0xff ) data.stencilWriteMask = this.stencilWriteMask;
  12972. if ( this.stencilFunc !== AlwaysStencilFunc ) data.stencilFunc = this.stencilFunc;
  12973. if ( this.stencilRef !== 0 ) data.stencilRef = this.stencilRef;
  12974. if ( this.stencilFuncMask !== 0xff ) data.stencilFuncMask = this.stencilFuncMask;
  12975. if ( this.stencilFail !== KeepStencilOp ) data.stencilFail = this.stencilFail;
  12976. if ( this.stencilZFail !== KeepStencilOp ) data.stencilZFail = this.stencilZFail;
  12977. if ( this.stencilZPass !== KeepStencilOp ) data.stencilZPass = this.stencilZPass;
  12978. if ( this.stencilWrite === true ) data.stencilWrite = this.stencilWrite;
  12979. // rotation (SpriteMaterial)
  12980. if ( this.rotation !== undefined && this.rotation !== 0 ) data.rotation = this.rotation;
  12981. if ( this.polygonOffset === true ) data.polygonOffset = true;
  12982. if ( this.polygonOffsetFactor !== 0 ) data.polygonOffsetFactor = this.polygonOffsetFactor;
  12983. if ( this.polygonOffsetUnits !== 0 ) data.polygonOffsetUnits = this.polygonOffsetUnits;
  12984. if ( this.linewidth !== undefined && this.linewidth !== 1 ) data.linewidth = this.linewidth;
  12985. if ( this.dashSize !== undefined ) data.dashSize = this.dashSize;
  12986. if ( this.gapSize !== undefined ) data.gapSize = this.gapSize;
  12987. if ( this.scale !== undefined ) data.scale = this.scale;
  12988. if ( this.dithering === true ) data.dithering = true;
  12989. if ( this.alphaTest > 0 ) data.alphaTest = this.alphaTest;
  12990. if ( this.alphaHash === true ) data.alphaHash = true;
  12991. if ( this.alphaToCoverage === true ) data.alphaToCoverage = true;
  12992. if ( this.premultipliedAlpha === true ) data.premultipliedAlpha = true;
  12993. if ( this.forceSinglePass === true ) data.forceSinglePass = true;
  12994. if ( this.allowOverride === false ) data.allowOverride = false;
  12995. if ( this.wireframe === true ) data.wireframe = true;
  12996. if ( this.wireframeLinewidth > 1 ) data.wireframeLinewidth = this.wireframeLinewidth;
  12997. if ( this.wireframeLinecap !== 'round' ) data.wireframeLinecap = this.wireframeLinecap;
  12998. if ( this.wireframeLinejoin !== 'round' ) data.wireframeLinejoin = this.wireframeLinejoin;
  12999. if ( this.flatShading === true ) data.flatShading = true;
  13000. if ( this.visible === false ) data.visible = false;
  13001. if ( this.toneMapped === false ) data.toneMapped = false;
  13002. if ( this.fog === false ) data.fog = false;
  13003. if ( Object.keys( this.userData ).length > 0 ) data.userData = this.userData;
  13004. // TODO: Copied from Object3D.toJSON
  13005. function extractFromCache( cache ) {
  13006. const values = [];
  13007. for ( const key in cache ) {
  13008. const data = cache[ key ];
  13009. delete data.metadata;
  13010. values.push( data );
  13011. }
  13012. return values;
  13013. }
  13014. if ( isRootObject ) {
  13015. const textures = extractFromCache( meta.textures );
  13016. const images = extractFromCache( meta.images );
  13017. if ( textures.length > 0 ) data.textures = textures;
  13018. if ( images.length > 0 ) data.images = images;
  13019. }
  13020. return data;
  13021. }
  13022. /**
  13023. * Returns a new material with copied values from this instance.
  13024. *
  13025. * @return {Material} A clone of this instance.
  13026. */
  13027. clone() {
  13028. return new this.constructor().copy( this );
  13029. }
  13030. /**
  13031. * Copies the values of the given material to this instance.
  13032. *
  13033. * @param {Material} source - The material to copy.
  13034. * @return {Material} A reference to this instance.
  13035. */
  13036. copy( source ) {
  13037. this.name = source.name;
  13038. this.blending = source.blending;
  13039. this.side = source.side;
  13040. this.vertexColors = source.vertexColors;
  13041. this.opacity = source.opacity;
  13042. this.transparent = source.transparent;
  13043. this.blendSrc = source.blendSrc;
  13044. this.blendDst = source.blendDst;
  13045. this.blendEquation = source.blendEquation;
  13046. this.blendSrcAlpha = source.blendSrcAlpha;
  13047. this.blendDstAlpha = source.blendDstAlpha;
  13048. this.blendEquationAlpha = source.blendEquationAlpha;
  13049. this.blendColor.copy( source.blendColor );
  13050. this.blendAlpha = source.blendAlpha;
  13051. this.depthFunc = source.depthFunc;
  13052. this.depthTest = source.depthTest;
  13053. this.depthWrite = source.depthWrite;
  13054. this.stencilWriteMask = source.stencilWriteMask;
  13055. this.stencilFunc = source.stencilFunc;
  13056. this.stencilRef = source.stencilRef;
  13057. this.stencilFuncMask = source.stencilFuncMask;
  13058. this.stencilFail = source.stencilFail;
  13059. this.stencilZFail = source.stencilZFail;
  13060. this.stencilZPass = source.stencilZPass;
  13061. this.stencilWrite = source.stencilWrite;
  13062. const srcPlanes = source.clippingPlanes;
  13063. let dstPlanes = null;
  13064. if ( srcPlanes !== null ) {
  13065. const n = srcPlanes.length;
  13066. dstPlanes = new Array( n );
  13067. for ( let i = 0; i !== n; ++ i ) {
  13068. dstPlanes[ i ] = srcPlanes[ i ].clone();
  13069. }
  13070. }
  13071. this.clippingPlanes = dstPlanes;
  13072. this.clipIntersection = source.clipIntersection;
  13073. this.clipShadows = source.clipShadows;
  13074. this.shadowSide = source.shadowSide;
  13075. this.colorWrite = source.colorWrite;
  13076. this.precision = source.precision;
  13077. this.polygonOffset = source.polygonOffset;
  13078. this.polygonOffsetFactor = source.polygonOffsetFactor;
  13079. this.polygonOffsetUnits = source.polygonOffsetUnits;
  13080. this.dithering = source.dithering;
  13081. this.alphaTest = source.alphaTest;
  13082. this.alphaHash = source.alphaHash;
  13083. this.alphaToCoverage = source.alphaToCoverage;
  13084. this.premultipliedAlpha = source.premultipliedAlpha;
  13085. this.forceSinglePass = source.forceSinglePass;
  13086. this.allowOverride = source.allowOverride;
  13087. this.visible = source.visible;
  13088. this.toneMapped = source.toneMapped;
  13089. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  13090. return this;
  13091. }
  13092. /**
  13093. * Frees the GPU-related resources allocated by this instance. Call this
  13094. * method whenever this instance is no longer used in your app.
  13095. *
  13096. * @fires Material#dispose
  13097. */
  13098. dispose() {
  13099. /**
  13100. * Fires when the material has been disposed of.
  13101. *
  13102. * @event Material#dispose
  13103. * @type {Object}
  13104. */
  13105. this.dispatchEvent( { type: 'dispose' } );
  13106. }
  13107. /**
  13108. * Setting this property to `true` indicates the engine the material
  13109. * needs to be recompiled.
  13110. *
  13111. * @type {boolean}
  13112. * @default false
  13113. * @param {boolean} value
  13114. */
  13115. set needsUpdate( value ) {
  13116. if ( value === true ) this.version ++;
  13117. }
  13118. }
  13119. /**
  13120. * A material for drawing geometries in a simple shaded (flat or wireframe) way.
  13121. *
  13122. * This material is not affected by lights.
  13123. *
  13124. * @augments Material
  13125. * @demo scenes/material-browser.html#MeshBasicMaterial
  13126. */
  13127. class MeshBasicMaterial extends Material {
  13128. /**
  13129. * Constructs a new mesh basic material.
  13130. *
  13131. * @param {Object} [parameters] - An object with one or more properties
  13132. * defining the material's appearance. Any property of the material
  13133. * (including any property from inherited materials) can be passed
  13134. * in here. Color values can be passed any type of value accepted
  13135. * by {@link Color#set}.
  13136. */
  13137. constructor( parameters ) {
  13138. super();
  13139. /**
  13140. * This flag can be used for type testing.
  13141. *
  13142. * @type {boolean}
  13143. * @readonly
  13144. * @default true
  13145. */
  13146. this.isMeshBasicMaterial = true;
  13147. this.type = 'MeshBasicMaterial';
  13148. /**
  13149. * Color of the material.
  13150. *
  13151. * @type {Color}
  13152. * @default (1,1,1)
  13153. */
  13154. this.color = new Color( 0xffffff ); // diffuse
  13155. /**
  13156. * The color map. May optionally include an alpha channel, typically combined
  13157. * with {@link Material#transparent} or {@link Material#alphaTest}. The texture map
  13158. * color is modulated by the diffuse `color`.
  13159. *
  13160. * @type {?Texture}
  13161. * @default null
  13162. */
  13163. this.map = null;
  13164. /**
  13165. * The light map. Requires a second set of UVs.
  13166. *
  13167. * @type {?Texture}
  13168. * @default null
  13169. */
  13170. this.lightMap = null;
  13171. /**
  13172. * Intensity of the baked light.
  13173. *
  13174. * @type {number}
  13175. * @default 1
  13176. */
  13177. this.lightMapIntensity = 1.0;
  13178. /**
  13179. * The red channel of this texture is used as the ambient occlusion map.
  13180. * Requires a second set of UVs.
  13181. *
  13182. * @type {?Texture}
  13183. * @default null
  13184. */
  13185. this.aoMap = null;
  13186. /**
  13187. * Intensity of the ambient occlusion effect. Range is `[0,1]`, where `0`
  13188. * disables ambient occlusion. Where intensity is `1` and the AO map's
  13189. * red channel is also `1`, ambient light is fully occluded on a surface.
  13190. *
  13191. * @type {number}
  13192. * @default 1
  13193. */
  13194. this.aoMapIntensity = 1.0;
  13195. /**
  13196. * Specular map used by the material.
  13197. *
  13198. * @type {?Texture}
  13199. * @default null
  13200. */
  13201. this.specularMap = null;
  13202. /**
  13203. * The alpha map is a grayscale texture that controls the opacity across the
  13204. * surface (black: fully transparent; white: fully opaque).
  13205. *
  13206. * Only the color of the texture is used, ignoring the alpha channel if one
  13207. * exists. For RGB and RGBA textures, the renderer will use the green channel
  13208. * when sampling this texture due to the extra bit of precision provided for
  13209. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  13210. * luminance/alpha textures will also still work as expected.
  13211. *
  13212. * @type {?Texture}
  13213. * @default null
  13214. */
  13215. this.alphaMap = null;
  13216. /**
  13217. * The environment map.
  13218. *
  13219. * @type {?Texture}
  13220. * @default null
  13221. */
  13222. this.envMap = null;
  13223. /**
  13224. * The rotation of the environment map in radians.
  13225. *
  13226. * @type {Euler}
  13227. * @default (0,0,0)
  13228. */
  13229. this.envMapRotation = new Euler();
  13230. /**
  13231. * How to combine the result of the surface's color with the environment map, if any.
  13232. *
  13233. * When set to `MixOperation`, the {@link MeshBasicMaterial#reflectivity} is used to
  13234. * blend between the two colors.
  13235. *
  13236. * @type {(MultiplyOperation|MixOperation|AddOperation)}
  13237. * @default MultiplyOperation
  13238. */
  13239. this.combine = MultiplyOperation;
  13240. /**
  13241. * How much the environment map affects the surface.
  13242. * The valid range is between `0` (no reflections) and `1` (full reflections).
  13243. *
  13244. * @type {number}
  13245. * @default 1
  13246. */
  13247. this.reflectivity = 1;
  13248. /**
  13249. * The index of refraction (IOR) of air (approximately 1) divided by the
  13250. * index of refraction of the material. It is used with environment mapping
  13251. * modes {@link CubeRefractionMapping} and {@link EquirectangularRefractionMapping}.
  13252. * The refraction ratio should not exceed `1`.
  13253. *
  13254. * @type {number}
  13255. * @default 0.98
  13256. */
  13257. this.refractionRatio = 0.98;
  13258. /**
  13259. * Renders the geometry as a wireframe.
  13260. *
  13261. * @type {boolean}
  13262. * @default false
  13263. */
  13264. this.wireframe = false;
  13265. /**
  13266. * Controls the thickness of the wireframe.
  13267. *
  13268. * Can only be used with {@link SVGRenderer}.
  13269. *
  13270. * @type {number}
  13271. * @default 1
  13272. */
  13273. this.wireframeLinewidth = 1;
  13274. /**
  13275. * Defines appearance of wireframe ends.
  13276. *
  13277. * Can only be used with {@link SVGRenderer}.
  13278. *
  13279. * @type {('round'|'bevel'|'miter')}
  13280. * @default 'round'
  13281. */
  13282. this.wireframeLinecap = 'round';
  13283. /**
  13284. * Defines appearance of wireframe joints.
  13285. *
  13286. * Can only be used with {@link SVGRenderer}.
  13287. *
  13288. * @type {('round'|'bevel'|'miter')}
  13289. * @default 'round'
  13290. */
  13291. this.wireframeLinejoin = 'round';
  13292. /**
  13293. * Whether the material is affected by fog or not.
  13294. *
  13295. * @type {boolean}
  13296. * @default true
  13297. */
  13298. this.fog = true;
  13299. this.setValues( parameters );
  13300. }
  13301. copy( source ) {
  13302. super.copy( source );
  13303. this.color.copy( source.color );
  13304. this.map = source.map;
  13305. this.lightMap = source.lightMap;
  13306. this.lightMapIntensity = source.lightMapIntensity;
  13307. this.aoMap = source.aoMap;
  13308. this.aoMapIntensity = source.aoMapIntensity;
  13309. this.specularMap = source.specularMap;
  13310. this.alphaMap = source.alphaMap;
  13311. this.envMap = source.envMap;
  13312. this.envMapRotation.copy( source.envMapRotation );
  13313. this.combine = source.combine;
  13314. this.reflectivity = source.reflectivity;
  13315. this.refractionRatio = source.refractionRatio;
  13316. this.wireframe = source.wireframe;
  13317. this.wireframeLinewidth = source.wireframeLinewidth;
  13318. this.wireframeLinecap = source.wireframeLinecap;
  13319. this.wireframeLinejoin = source.wireframeLinejoin;
  13320. this.fog = source.fog;
  13321. return this;
  13322. }
  13323. }
  13324. // Fast Half Float Conversions, http://www.fox-toolkit.org/ftp/fasthalffloatconversion.pdf
  13325. const _tables = /*@__PURE__*/ _generateTables();
  13326. function _generateTables() {
  13327. // float32 to float16 helpers
  13328. const buffer = new ArrayBuffer( 4 );
  13329. const floatView = new Float32Array( buffer );
  13330. const uint32View = new Uint32Array( buffer );
  13331. const baseTable = new Uint32Array( 512 );
  13332. const shiftTable = new Uint32Array( 512 );
  13333. for ( let i = 0; i < 256; ++ i ) {
  13334. const e = i - 127;
  13335. // very small number (0, -0)
  13336. if ( e < -27 ) {
  13337. baseTable[ i ] = 0x0000;
  13338. baseTable[ i | 0x100 ] = 0x8000;
  13339. shiftTable[ i ] = 24;
  13340. shiftTable[ i | 0x100 ] = 24;
  13341. // small number (denorm)
  13342. } else if ( e < -14 ) {
  13343. baseTable[ i ] = 0x0400 >> ( - e - 14 );
  13344. baseTable[ i | 0x100 ] = ( 0x0400 >> ( - e - 14 ) ) | 0x8000;
  13345. shiftTable[ i ] = - e - 1;
  13346. shiftTable[ i | 0x100 ] = - e - 1;
  13347. // normal number
  13348. } else if ( e <= 15 ) {
  13349. baseTable[ i ] = ( e + 15 ) << 10;
  13350. baseTable[ i | 0x100 ] = ( ( e + 15 ) << 10 ) | 0x8000;
  13351. shiftTable[ i ] = 13;
  13352. shiftTable[ i | 0x100 ] = 13;
  13353. // large number (Infinity, -Infinity)
  13354. } else if ( e < 128 ) {
  13355. baseTable[ i ] = 0x7c00;
  13356. baseTable[ i | 0x100 ] = 0xfc00;
  13357. shiftTable[ i ] = 24;
  13358. shiftTable[ i | 0x100 ] = 24;
  13359. // stay (NaN, Infinity, -Infinity)
  13360. } else {
  13361. baseTable[ i ] = 0x7c00;
  13362. baseTable[ i | 0x100 ] = 0xfc00;
  13363. shiftTable[ i ] = 13;
  13364. shiftTable[ i | 0x100 ] = 13;
  13365. }
  13366. }
  13367. // float16 to float32 helpers
  13368. const mantissaTable = new Uint32Array( 2048 );
  13369. const exponentTable = new Uint32Array( 64 );
  13370. const offsetTable = new Uint32Array( 64 );
  13371. for ( let i = 1; i < 1024; ++ i ) {
  13372. let m = i << 13; // zero pad mantissa bits
  13373. let e = 0; // zero exponent
  13374. // normalized
  13375. while ( ( m & 0x00800000 ) === 0 ) {
  13376. m <<= 1;
  13377. e -= 0x00800000; // decrement exponent
  13378. }
  13379. m &= -8388609; // clear leading 1 bit
  13380. e += 0x38800000; // adjust bias
  13381. mantissaTable[ i ] = m | e;
  13382. }
  13383. for ( let i = 1024; i < 2048; ++ i ) {
  13384. mantissaTable[ i ] = 0x38000000 + ( ( i - 1024 ) << 13 );
  13385. }
  13386. for ( let i = 1; i < 31; ++ i ) {
  13387. exponentTable[ i ] = i << 23;
  13388. }
  13389. exponentTable[ 31 ] = 0x47800000;
  13390. exponentTable[ 32 ] = 0x80000000;
  13391. for ( let i = 33; i < 63; ++ i ) {
  13392. exponentTable[ i ] = 0x80000000 + ( ( i - 32 ) << 23 );
  13393. }
  13394. exponentTable[ 63 ] = 0xc7800000;
  13395. for ( let i = 1; i < 64; ++ i ) {
  13396. if ( i !== 32 ) {
  13397. offsetTable[ i ] = 1024;
  13398. }
  13399. }
  13400. return {
  13401. floatView: floatView,
  13402. uint32View: uint32View,
  13403. baseTable: baseTable,
  13404. shiftTable: shiftTable,
  13405. mantissaTable: mantissaTable,
  13406. exponentTable: exponentTable,
  13407. offsetTable: offsetTable
  13408. };
  13409. }
  13410. /**
  13411. * Returns a half precision floating point value (FP16) from the given single
  13412. * precision floating point value (FP32).
  13413. *
  13414. * @param {number} val - A single precision floating point value.
  13415. * @return {number} The FP16 value.
  13416. */
  13417. function toHalfFloat( val ) {
  13418. if ( Math.abs( val ) > 65504 ) warn( 'DataUtils.toHalfFloat(): Value out of range.' );
  13419. val = clamp( val, -65504, 65504 );
  13420. _tables.floatView[ 0 ] = val;
  13421. const f = _tables.uint32View[ 0 ];
  13422. const e = ( f >> 23 ) & 0x1ff;
  13423. return _tables.baseTable[ e ] + ( ( f & 0x007fffff ) >> _tables.shiftTable[ e ] );
  13424. }
  13425. /**
  13426. * Returns a single precision floating point value (FP32) from the given half
  13427. * precision floating point value (FP16).
  13428. *
  13429. * @param {number} val - A half precision floating point value.
  13430. * @return {number} The FP32 value.
  13431. */
  13432. function fromHalfFloat( val ) {
  13433. const m = val >> 10;
  13434. _tables.uint32View[ 0 ] = _tables.mantissaTable[ _tables.offsetTable[ m ] + ( val & 0x3ff ) ] + _tables.exponentTable[ m ];
  13435. return _tables.floatView[ 0 ];
  13436. }
  13437. /**
  13438. * A class containing utility functions for data.
  13439. *
  13440. * @hideconstructor
  13441. */
  13442. class DataUtils {
  13443. /**
  13444. * Returns a half precision floating point value (FP16) from the given single
  13445. * precision floating point value (FP32).
  13446. *
  13447. * @param {number} val - A single precision floating point value.
  13448. * @return {number} The FP16 value.
  13449. */
  13450. static toHalfFloat( val ) {
  13451. return toHalfFloat( val );
  13452. }
  13453. /**
  13454. * Returns a single precision floating point value (FP32) from the given half
  13455. * precision floating point value (FP16).
  13456. *
  13457. * @param {number} val - A half precision floating point value.
  13458. * @return {number} The FP32 value.
  13459. */
  13460. static fromHalfFloat( val ) {
  13461. return fromHalfFloat( val );
  13462. }
  13463. }
  13464. const _vector$9 = /*@__PURE__*/ new Vector3();
  13465. const _vector2$1 = /*@__PURE__*/ new Vector2();
  13466. let _id$2 = 0;
  13467. /**
  13468. * This class stores data for an attribute (such as vertex positions, face
  13469. * indices, normals, colors, UVs, and any custom attributes ) associated with
  13470. * a geometry, which allows for more efficient passing of data to the GPU.
  13471. *
  13472. * When working with vector-like data, the `fromBufferAttribute( attribute, index )`
  13473. * helper methods on vector and color class might be helpful. E.g. {@link Vector3#fromBufferAttribute}.
  13474. */
  13475. class BufferAttribute {
  13476. /**
  13477. * Constructs a new buffer attribute.
  13478. *
  13479. * @param {TypedArray} array - The array holding the attribute data.
  13480. * @param {number} itemSize - The item size.
  13481. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  13482. */
  13483. constructor( array, itemSize, normalized = false ) {
  13484. if ( Array.isArray( array ) ) {
  13485. throw new TypeError( 'THREE.BufferAttribute: array should be a Typed Array.' );
  13486. }
  13487. /**
  13488. * This flag can be used for type testing.
  13489. *
  13490. * @type {boolean}
  13491. * @readonly
  13492. * @default true
  13493. */
  13494. this.isBufferAttribute = true;
  13495. /**
  13496. * The ID of the buffer attribute.
  13497. *
  13498. * @name BufferAttribute#id
  13499. * @type {number}
  13500. * @readonly
  13501. */
  13502. Object.defineProperty( this, 'id', { value: _id$2 ++ } );
  13503. /**
  13504. * The name of the buffer attribute.
  13505. *
  13506. * @type {string}
  13507. */
  13508. this.name = '';
  13509. /**
  13510. * The array holding the attribute data. It should have `itemSize * numVertices`
  13511. * elements, where `numVertices` is the number of vertices in the associated geometry.
  13512. *
  13513. * @type {TypedArray}
  13514. */
  13515. this.array = array;
  13516. /**
  13517. * The number of values of the array that should be associated with a particular vertex.
  13518. * For instance, if this attribute is storing a 3-component vector (such as a position,
  13519. * normal, or color), then the value should be `3`.
  13520. *
  13521. * @type {number}
  13522. */
  13523. this.itemSize = itemSize;
  13524. /**
  13525. * Represents the number of items this buffer attribute stores. It is internally computed
  13526. * by dividing the `array` length by the `itemSize`.
  13527. *
  13528. * @type {number}
  13529. * @readonly
  13530. */
  13531. this.count = array !== undefined ? array.length / itemSize : 0;
  13532. /**
  13533. * Applies to integer data only. Indicates how the underlying data in the buffer maps to
  13534. * the values in the GLSL code. For instance, if `array` is an instance of `UInt16Array`,
  13535. * and `normalized` is `true`, the values `0 - +65535` in the array data will be mapped to
  13536. * `0.0f - +1.0f` in the GLSL attribute. If `normalized` is `false`, the values will be converted
  13537. * to floats unmodified, i.e. `65535` becomes `65535.0f`.
  13538. *
  13539. * @type {boolean}
  13540. */
  13541. this.normalized = normalized;
  13542. /**
  13543. * Defines the intended usage pattern of the data store for optimization purposes.
  13544. *
  13545. * Note: After the initial use of a buffer, its usage cannot be changed. Instead,
  13546. * instantiate a new one and set the desired usage before the next render.
  13547. *
  13548. * @type {(StaticDrawUsage|DynamicDrawUsage|StreamDrawUsage|StaticReadUsage|DynamicReadUsage|StreamReadUsage|StaticCopyUsage|DynamicCopyUsage|StreamCopyUsage)}
  13549. * @default StaticDrawUsage
  13550. */
  13551. this.usage = StaticDrawUsage;
  13552. /**
  13553. * This can be used to only update some components of stored vectors (for example, just the
  13554. * component related to color). Use the `addUpdateRange()` function to add ranges to this array.
  13555. *
  13556. * @type {Array<Object>}
  13557. */
  13558. this.updateRanges = [];
  13559. /**
  13560. * Configures the bound GPU type for use in shaders.
  13561. *
  13562. * Note: this only has an effect for integer arrays and is not configurable for float arrays.
  13563. * For lower precision float types, use `Float16BufferAttribute`.
  13564. *
  13565. * @type {(FloatType|IntType)}
  13566. * @default FloatType
  13567. */
  13568. this.gpuType = FloatType;
  13569. /**
  13570. * A version number, incremented every time the `needsUpdate` is set to `true`.
  13571. *
  13572. * @type {number}
  13573. */
  13574. this.version = 0;
  13575. }
  13576. /**
  13577. * A callback function that is executed after the renderer has transferred the attribute
  13578. * array data to the GPU.
  13579. */
  13580. onUploadCallback() {}
  13581. /**
  13582. * Flag to indicate that this attribute has changed and should be re-sent to
  13583. * the GPU. Set this to `true` when you modify the value of the array.
  13584. *
  13585. * @type {number}
  13586. * @default false
  13587. * @param {boolean} value
  13588. */
  13589. set needsUpdate( value ) {
  13590. if ( value === true ) this.version ++;
  13591. }
  13592. /**
  13593. * Sets the usage of this buffer attribute.
  13594. *
  13595. * @param {(StaticDrawUsage|DynamicDrawUsage|StreamDrawUsage|StaticReadUsage|DynamicReadUsage|StreamReadUsage|StaticCopyUsage|DynamicCopyUsage|StreamCopyUsage)} value - The usage to set.
  13596. * @return {BufferAttribute} A reference to this buffer attribute.
  13597. */
  13598. setUsage( value ) {
  13599. this.usage = value;
  13600. return this;
  13601. }
  13602. /**
  13603. * Adds a range of data in the data array to be updated on the GPU.
  13604. *
  13605. * @param {number} start - Position at which to start update.
  13606. * @param {number} count - The number of components to update.
  13607. */
  13608. addUpdateRange( start, count ) {
  13609. this.updateRanges.push( { start, count } );
  13610. }
  13611. /**
  13612. * Clears the update ranges.
  13613. */
  13614. clearUpdateRanges() {
  13615. this.updateRanges.length = 0;
  13616. }
  13617. /**
  13618. * Copies the values of the given buffer attribute to this instance.
  13619. *
  13620. * @param {BufferAttribute} source - The buffer attribute to copy.
  13621. * @return {BufferAttribute} A reference to this instance.
  13622. */
  13623. copy( source ) {
  13624. this.name = source.name;
  13625. this.array = new source.array.constructor( source.array );
  13626. this.itemSize = source.itemSize;
  13627. this.count = source.count;
  13628. this.normalized = source.normalized;
  13629. this.usage = source.usage;
  13630. this.gpuType = source.gpuType;
  13631. return this;
  13632. }
  13633. /**
  13634. * Copies a vector from the given buffer attribute to this one. The start
  13635. * and destination position in the attribute buffers are represented by the
  13636. * given indices.
  13637. *
  13638. * @param {number} index1 - The destination index into this buffer attribute.
  13639. * @param {BufferAttribute} attribute - The buffer attribute to copy from.
  13640. * @param {number} index2 - The source index into the given buffer attribute.
  13641. * @return {BufferAttribute} A reference to this instance.
  13642. */
  13643. copyAt( index1, attribute, index2 ) {
  13644. index1 *= this.itemSize;
  13645. index2 *= attribute.itemSize;
  13646. for ( let i = 0, l = this.itemSize; i < l; i ++ ) {
  13647. this.array[ index1 + i ] = attribute.array[ index2 + i ];
  13648. }
  13649. return this;
  13650. }
  13651. /**
  13652. * Copies the given array data into this buffer attribute.
  13653. *
  13654. * @param {(TypedArray|Array)} array - The array to copy.
  13655. * @return {BufferAttribute} A reference to this instance.
  13656. */
  13657. copyArray( array ) {
  13658. this.array.set( array );
  13659. return this;
  13660. }
  13661. /**
  13662. * Applies the given 3x3 matrix to the given attribute. Works with
  13663. * item size `2` and `3`.
  13664. *
  13665. * @param {Matrix3} m - The matrix to apply.
  13666. * @return {BufferAttribute} A reference to this instance.
  13667. */
  13668. applyMatrix3( m ) {
  13669. if ( this.itemSize === 2 ) {
  13670. for ( let i = 0, l = this.count; i < l; i ++ ) {
  13671. _vector2$1.fromBufferAttribute( this, i );
  13672. _vector2$1.applyMatrix3( m );
  13673. this.setXY( i, _vector2$1.x, _vector2$1.y );
  13674. }
  13675. } else if ( this.itemSize === 3 ) {
  13676. for ( let i = 0, l = this.count; i < l; i ++ ) {
  13677. _vector$9.fromBufferAttribute( this, i );
  13678. _vector$9.applyMatrix3( m );
  13679. this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  13680. }
  13681. }
  13682. return this;
  13683. }
  13684. /**
  13685. * Applies the given 4x4 matrix to the given attribute. Only works with
  13686. * item size `3`.
  13687. *
  13688. * @param {Matrix4} m - The matrix to apply.
  13689. * @return {BufferAttribute} A reference to this instance.
  13690. */
  13691. applyMatrix4( m ) {
  13692. for ( let i = 0, l = this.count; i < l; i ++ ) {
  13693. _vector$9.fromBufferAttribute( this, i );
  13694. _vector$9.applyMatrix4( m );
  13695. this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  13696. }
  13697. return this;
  13698. }
  13699. /**
  13700. * Applies the given 3x3 normal matrix to the given attribute. Only works with
  13701. * item size `3`.
  13702. *
  13703. * @param {Matrix3} m - The normal matrix to apply.
  13704. * @return {BufferAttribute} A reference to this instance.
  13705. */
  13706. applyNormalMatrix( m ) {
  13707. for ( let i = 0, l = this.count; i < l; i ++ ) {
  13708. _vector$9.fromBufferAttribute( this, i );
  13709. _vector$9.applyNormalMatrix( m );
  13710. this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  13711. }
  13712. return this;
  13713. }
  13714. /**
  13715. * Applies the given 4x4 matrix to the given attribute. Only works with
  13716. * item size `3` and with direction vectors.
  13717. *
  13718. * @param {Matrix4} m - The matrix to apply.
  13719. * @return {BufferAttribute} A reference to this instance.
  13720. */
  13721. transformDirection( m ) {
  13722. for ( let i = 0, l = this.count; i < l; i ++ ) {
  13723. _vector$9.fromBufferAttribute( this, i );
  13724. _vector$9.transformDirection( m );
  13725. this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  13726. }
  13727. return this;
  13728. }
  13729. /**
  13730. * Sets the given array data in the buffer attribute.
  13731. *
  13732. * @param {(TypedArray|Array)} value - The array data to set.
  13733. * @param {number} [offset=0] - The offset in this buffer attribute's array.
  13734. * @return {BufferAttribute} A reference to this instance.
  13735. */
  13736. set( value, offset = 0 ) {
  13737. // Matching BufferAttribute constructor, do not normalize the array.
  13738. this.array.set( value, offset );
  13739. return this;
  13740. }
  13741. /**
  13742. * Returns the given component of the vector at the given index.
  13743. *
  13744. * @param {number} index - The index into the buffer attribute.
  13745. * @param {number} component - The component index.
  13746. * @return {number} The returned value.
  13747. */
  13748. getComponent( index, component ) {
  13749. let value = this.array[ index * this.itemSize + component ];
  13750. if ( this.normalized ) value = denormalize( value, this.array );
  13751. return value;
  13752. }
  13753. /**
  13754. * Sets the given value to the given component of the vector at the given index.
  13755. *
  13756. * @param {number} index - The index into the buffer attribute.
  13757. * @param {number} component - The component index.
  13758. * @param {number} value - The value to set.
  13759. * @return {BufferAttribute} A reference to this instance.
  13760. */
  13761. setComponent( index, component, value ) {
  13762. if ( this.normalized ) value = normalize( value, this.array );
  13763. this.array[ index * this.itemSize + component ] = value;
  13764. return this;
  13765. }
  13766. /**
  13767. * Returns the x component of the vector at the given index.
  13768. *
  13769. * @param {number} index - The index into the buffer attribute.
  13770. * @return {number} The x component.
  13771. */
  13772. getX( index ) {
  13773. let x = this.array[ index * this.itemSize ];
  13774. if ( this.normalized ) x = denormalize( x, this.array );
  13775. return x;
  13776. }
  13777. /**
  13778. * Sets the x component of the vector at the given index.
  13779. *
  13780. * @param {number} index - The index into the buffer attribute.
  13781. * @param {number} x - The value to set.
  13782. * @return {BufferAttribute} A reference to this instance.
  13783. */
  13784. setX( index, x ) {
  13785. if ( this.normalized ) x = normalize( x, this.array );
  13786. this.array[ index * this.itemSize ] = x;
  13787. return this;
  13788. }
  13789. /**
  13790. * Returns the y component of the vector at the given index.
  13791. *
  13792. * @param {number} index - The index into the buffer attribute.
  13793. * @return {number} The y component.
  13794. */
  13795. getY( index ) {
  13796. let y = this.array[ index * this.itemSize + 1 ];
  13797. if ( this.normalized ) y = denormalize( y, this.array );
  13798. return y;
  13799. }
  13800. /**
  13801. * Sets the y component of the vector at the given index.
  13802. *
  13803. * @param {number} index - The index into the buffer attribute.
  13804. * @param {number} y - The value to set.
  13805. * @return {BufferAttribute} A reference to this instance.
  13806. */
  13807. setY( index, y ) {
  13808. if ( this.normalized ) y = normalize( y, this.array );
  13809. this.array[ index * this.itemSize + 1 ] = y;
  13810. return this;
  13811. }
  13812. /**
  13813. * Returns the z component of the vector at the given index.
  13814. *
  13815. * @param {number} index - The index into the buffer attribute.
  13816. * @return {number} The z component.
  13817. */
  13818. getZ( index ) {
  13819. let z = this.array[ index * this.itemSize + 2 ];
  13820. if ( this.normalized ) z = denormalize( z, this.array );
  13821. return z;
  13822. }
  13823. /**
  13824. * Sets the z component of the vector at the given index.
  13825. *
  13826. * @param {number} index - The index into the buffer attribute.
  13827. * @param {number} z - The value to set.
  13828. * @return {BufferAttribute} A reference to this instance.
  13829. */
  13830. setZ( index, z ) {
  13831. if ( this.normalized ) z = normalize( z, this.array );
  13832. this.array[ index * this.itemSize + 2 ] = z;
  13833. return this;
  13834. }
  13835. /**
  13836. * Returns the w component of the vector at the given index.
  13837. *
  13838. * @param {number} index - The index into the buffer attribute.
  13839. * @return {number} The w component.
  13840. */
  13841. getW( index ) {
  13842. let w = this.array[ index * this.itemSize + 3 ];
  13843. if ( this.normalized ) w = denormalize( w, this.array );
  13844. return w;
  13845. }
  13846. /**
  13847. * Sets the w component of the vector at the given index.
  13848. *
  13849. * @param {number} index - The index into the buffer attribute.
  13850. * @param {number} w - The value to set.
  13851. * @return {BufferAttribute} A reference to this instance.
  13852. */
  13853. setW( index, w ) {
  13854. if ( this.normalized ) w = normalize( w, this.array );
  13855. this.array[ index * this.itemSize + 3 ] = w;
  13856. return this;
  13857. }
  13858. /**
  13859. * Sets the x and y component of the vector at the given index.
  13860. *
  13861. * @param {number} index - The index into the buffer attribute.
  13862. * @param {number} x - The value for the x component to set.
  13863. * @param {number} y - The value for the y component to set.
  13864. * @return {BufferAttribute} A reference to this instance.
  13865. */
  13866. setXY( index, x, y ) {
  13867. index *= this.itemSize;
  13868. if ( this.normalized ) {
  13869. x = normalize( x, this.array );
  13870. y = normalize( y, this.array );
  13871. }
  13872. this.array[ index + 0 ] = x;
  13873. this.array[ index + 1 ] = y;
  13874. return this;
  13875. }
  13876. /**
  13877. * Sets the x, y and z component of the vector at the given index.
  13878. *
  13879. * @param {number} index - The index into the buffer attribute.
  13880. * @param {number} x - The value for the x component to set.
  13881. * @param {number} y - The value for the y component to set.
  13882. * @param {number} z - The value for the z component to set.
  13883. * @return {BufferAttribute} A reference to this instance.
  13884. */
  13885. setXYZ( index, x, y, z ) {
  13886. index *= this.itemSize;
  13887. if ( this.normalized ) {
  13888. x = normalize( x, this.array );
  13889. y = normalize( y, this.array );
  13890. z = normalize( z, this.array );
  13891. }
  13892. this.array[ index + 0 ] = x;
  13893. this.array[ index + 1 ] = y;
  13894. this.array[ index + 2 ] = z;
  13895. return this;
  13896. }
  13897. /**
  13898. * Sets the x, y, z and w component of the vector at the given index.
  13899. *
  13900. * @param {number} index - The index into the buffer attribute.
  13901. * @param {number} x - The value for the x component to set.
  13902. * @param {number} y - The value for the y component to set.
  13903. * @param {number} z - The value for the z component to set.
  13904. * @param {number} w - The value for the w component to set.
  13905. * @return {BufferAttribute} A reference to this instance.
  13906. */
  13907. setXYZW( index, x, y, z, w ) {
  13908. index *= this.itemSize;
  13909. if ( this.normalized ) {
  13910. x = normalize( x, this.array );
  13911. y = normalize( y, this.array );
  13912. z = normalize( z, this.array );
  13913. w = normalize( w, this.array );
  13914. }
  13915. this.array[ index + 0 ] = x;
  13916. this.array[ index + 1 ] = y;
  13917. this.array[ index + 2 ] = z;
  13918. this.array[ index + 3 ] = w;
  13919. return this;
  13920. }
  13921. /**
  13922. * Sets the given callback function that is executed after the Renderer has transferred
  13923. * the attribute array data to the GPU. Can be used to perform clean-up operations after
  13924. * the upload when attribute data are not needed anymore on the CPU side.
  13925. *
  13926. * @param {Function} callback - The `onUpload()` callback.
  13927. * @return {BufferAttribute} A reference to this instance.
  13928. */
  13929. onUpload( callback ) {
  13930. this.onUploadCallback = callback;
  13931. return this;
  13932. }
  13933. /**
  13934. * Returns a new buffer attribute with copied values from this instance.
  13935. *
  13936. * @return {BufferAttribute} A clone of this instance.
  13937. */
  13938. clone() {
  13939. return new this.constructor( this.array, this.itemSize ).copy( this );
  13940. }
  13941. /**
  13942. * Serializes the buffer attribute into JSON.
  13943. *
  13944. * @return {Object} A JSON object representing the serialized buffer attribute.
  13945. */
  13946. toJSON() {
  13947. const data = {
  13948. itemSize: this.itemSize,
  13949. type: this.array.constructor.name,
  13950. array: Array.from( this.array ),
  13951. normalized: this.normalized
  13952. };
  13953. if ( this.name !== '' ) data.name = this.name;
  13954. if ( this.usage !== StaticDrawUsage ) data.usage = this.usage;
  13955. return data;
  13956. }
  13957. }
  13958. /**
  13959. * Convenient class that can be used when creating a `Int8` buffer attribute with
  13960. * a plain `Array` instance.
  13961. *
  13962. * @augments BufferAttribute
  13963. */
  13964. class Int8BufferAttribute extends BufferAttribute {
  13965. /**
  13966. * Constructs a new buffer attribute.
  13967. *
  13968. * @param {(Array<number>|Int8Array)} array - The array holding the attribute data.
  13969. * @param {number} itemSize - The item size.
  13970. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  13971. */
  13972. constructor( array, itemSize, normalized ) {
  13973. super( new Int8Array( array ), itemSize, normalized );
  13974. }
  13975. }
  13976. /**
  13977. * Convenient class that can be used when creating a `UInt8` buffer attribute with
  13978. * a plain `Array` instance.
  13979. *
  13980. * @augments BufferAttribute
  13981. */
  13982. class Uint8BufferAttribute extends BufferAttribute {
  13983. /**
  13984. * Constructs a new buffer attribute.
  13985. *
  13986. * @param {(Array<number>|Uint8Array)} array - The array holding the attribute data.
  13987. * @param {number} itemSize - The item size.
  13988. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  13989. */
  13990. constructor( array, itemSize, normalized ) {
  13991. super( new Uint8Array( array ), itemSize, normalized );
  13992. }
  13993. }
  13994. /**
  13995. * Convenient class that can be used when creating a `UInt8Clamped` buffer attribute with
  13996. * a plain `Array` instance.
  13997. *
  13998. * @augments BufferAttribute
  13999. */
  14000. class Uint8ClampedBufferAttribute extends BufferAttribute {
  14001. /**
  14002. * Constructs a new buffer attribute.
  14003. *
  14004. * @param {(Array<number>|Uint8ClampedArray)} array - The array holding the attribute data.
  14005. * @param {number} itemSize - The item size.
  14006. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  14007. */
  14008. constructor( array, itemSize, normalized ) {
  14009. super( new Uint8ClampedArray( array ), itemSize, normalized );
  14010. }
  14011. }
  14012. /**
  14013. * Convenient class that can be used when creating a `Int16` buffer attribute with
  14014. * a plain `Array` instance.
  14015. *
  14016. * @augments BufferAttribute
  14017. */
  14018. class Int16BufferAttribute extends BufferAttribute {
  14019. /**
  14020. * Constructs a new buffer attribute.
  14021. *
  14022. * @param {(Array<number>|Int16Array)} array - The array holding the attribute data.
  14023. * @param {number} itemSize - The item size.
  14024. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  14025. */
  14026. constructor( array, itemSize, normalized ) {
  14027. super( new Int16Array( array ), itemSize, normalized );
  14028. }
  14029. }
  14030. /**
  14031. * Convenient class that can be used when creating a `UInt16` buffer attribute with
  14032. * a plain `Array` instance.
  14033. *
  14034. * @augments BufferAttribute
  14035. */
  14036. class Uint16BufferAttribute extends BufferAttribute {
  14037. /**
  14038. * Constructs a new buffer attribute.
  14039. *
  14040. * @param {(Array<number>|Uint16Array)} array - The array holding the attribute data.
  14041. * @param {number} itemSize - The item size.
  14042. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  14043. */
  14044. constructor( array, itemSize, normalized ) {
  14045. super( new Uint16Array( array ), itemSize, normalized );
  14046. }
  14047. }
  14048. /**
  14049. * Convenient class that can be used when creating a `Int32` buffer attribute with
  14050. * a plain `Array` instance.
  14051. *
  14052. * @augments BufferAttribute
  14053. */
  14054. class Int32BufferAttribute extends BufferAttribute {
  14055. /**
  14056. * Constructs a new buffer attribute.
  14057. *
  14058. * @param {(Array<number>|Int32Array)} array - The array holding the attribute data.
  14059. * @param {number} itemSize - The item size.
  14060. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  14061. */
  14062. constructor( array, itemSize, normalized ) {
  14063. super( new Int32Array( array ), itemSize, normalized );
  14064. }
  14065. }
  14066. /**
  14067. * Convenient class that can be used when creating a `UInt32` buffer attribute with
  14068. * a plain `Array` instance.
  14069. *
  14070. * @augments BufferAttribute
  14071. */
  14072. class Uint32BufferAttribute extends BufferAttribute {
  14073. /**
  14074. * Constructs a new buffer attribute.
  14075. *
  14076. * @param {(Array<number>|Uint32Array)} array - The array holding the attribute data.
  14077. * @param {number} itemSize - The item size.
  14078. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  14079. */
  14080. constructor( array, itemSize, normalized ) {
  14081. super( new Uint32Array( array ), itemSize, normalized );
  14082. }
  14083. }
  14084. /**
  14085. * Convenient class that can be used when creating a `Float16` buffer attribute with
  14086. * a plain `Array` instance.
  14087. *
  14088. * This class automatically converts to and from FP16 via `Uint16Array` since `Float16Array`
  14089. * browser support is still problematic.
  14090. *
  14091. * @augments BufferAttribute
  14092. */
  14093. class Float16BufferAttribute extends BufferAttribute {
  14094. /**
  14095. * Constructs a new buffer attribute.
  14096. *
  14097. * @param {(Array<number>|Uint16Array)} array - The array holding the attribute data.
  14098. * @param {number} itemSize - The item size.
  14099. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  14100. */
  14101. constructor( array, itemSize, normalized ) {
  14102. super( new Uint16Array( array ), itemSize, normalized );
  14103. this.isFloat16BufferAttribute = true;
  14104. }
  14105. getX( index ) {
  14106. let x = fromHalfFloat( this.array[ index * this.itemSize ] );
  14107. if ( this.normalized ) x = denormalize( x, this.array );
  14108. return x;
  14109. }
  14110. setX( index, x ) {
  14111. if ( this.normalized ) x = normalize( x, this.array );
  14112. this.array[ index * this.itemSize ] = toHalfFloat( x );
  14113. return this;
  14114. }
  14115. getY( index ) {
  14116. let y = fromHalfFloat( this.array[ index * this.itemSize + 1 ] );
  14117. if ( this.normalized ) y = denormalize( y, this.array );
  14118. return y;
  14119. }
  14120. setY( index, y ) {
  14121. if ( this.normalized ) y = normalize( y, this.array );
  14122. this.array[ index * this.itemSize + 1 ] = toHalfFloat( y );
  14123. return this;
  14124. }
  14125. getZ( index ) {
  14126. let z = fromHalfFloat( this.array[ index * this.itemSize + 2 ] );
  14127. if ( this.normalized ) z = denormalize( z, this.array );
  14128. return z;
  14129. }
  14130. setZ( index, z ) {
  14131. if ( this.normalized ) z = normalize( z, this.array );
  14132. this.array[ index * this.itemSize + 2 ] = toHalfFloat( z );
  14133. return this;
  14134. }
  14135. getW( index ) {
  14136. let w = fromHalfFloat( this.array[ index * this.itemSize + 3 ] );
  14137. if ( this.normalized ) w = denormalize( w, this.array );
  14138. return w;
  14139. }
  14140. setW( index, w ) {
  14141. if ( this.normalized ) w = normalize( w, this.array );
  14142. this.array[ index * this.itemSize + 3 ] = toHalfFloat( w );
  14143. return this;
  14144. }
  14145. setXY( index, x, y ) {
  14146. index *= this.itemSize;
  14147. if ( this.normalized ) {
  14148. x = normalize( x, this.array );
  14149. y = normalize( y, this.array );
  14150. }
  14151. this.array[ index + 0 ] = toHalfFloat( x );
  14152. this.array[ index + 1 ] = toHalfFloat( y );
  14153. return this;
  14154. }
  14155. setXYZ( index, x, y, z ) {
  14156. index *= this.itemSize;
  14157. if ( this.normalized ) {
  14158. x = normalize( x, this.array );
  14159. y = normalize( y, this.array );
  14160. z = normalize( z, this.array );
  14161. }
  14162. this.array[ index + 0 ] = toHalfFloat( x );
  14163. this.array[ index + 1 ] = toHalfFloat( y );
  14164. this.array[ index + 2 ] = toHalfFloat( z );
  14165. return this;
  14166. }
  14167. setXYZW( index, x, y, z, w ) {
  14168. index *= this.itemSize;
  14169. if ( this.normalized ) {
  14170. x = normalize( x, this.array );
  14171. y = normalize( y, this.array );
  14172. z = normalize( z, this.array );
  14173. w = normalize( w, this.array );
  14174. }
  14175. this.array[ index + 0 ] = toHalfFloat( x );
  14176. this.array[ index + 1 ] = toHalfFloat( y );
  14177. this.array[ index + 2 ] = toHalfFloat( z );
  14178. this.array[ index + 3 ] = toHalfFloat( w );
  14179. return this;
  14180. }
  14181. }
  14182. /**
  14183. * Convenient class that can be used when creating a `Float32` buffer attribute with
  14184. * a plain `Array` instance.
  14185. *
  14186. * @augments BufferAttribute
  14187. */
  14188. class Float32BufferAttribute extends BufferAttribute {
  14189. /**
  14190. * Constructs a new buffer attribute.
  14191. *
  14192. * @param {(Array<number>|Float32Array)} array - The array holding the attribute data.
  14193. * @param {number} itemSize - The item size.
  14194. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  14195. */
  14196. constructor( array, itemSize, normalized ) {
  14197. super( new Float32Array( array ), itemSize, normalized );
  14198. }
  14199. }
  14200. let _id$1 = 0;
  14201. const _m1 = /*@__PURE__*/ new Matrix4();
  14202. const _obj = /*@__PURE__*/ new Object3D();
  14203. const _offset = /*@__PURE__*/ new Vector3();
  14204. const _box$2 = /*@__PURE__*/ new Box3();
  14205. const _boxMorphTargets = /*@__PURE__*/ new Box3();
  14206. const _vector$8 = /*@__PURE__*/ new Vector3();
  14207. /**
  14208. * A representation of mesh, line, or point geometry. Includes vertex
  14209. * positions, face indices, normals, colors, UVs, and custom attributes
  14210. * within buffers, reducing the cost of passing all this data to the GPU.
  14211. *
  14212. * ```js
  14213. * const geometry = new THREE.BufferGeometry();
  14214. * // create a simple square shape. We duplicate the top left and bottom right
  14215. * // vertices because each vertex needs to appear once per triangle.
  14216. * const vertices = new Float32Array( [
  14217. * -1.0, -1.0, 1.0, // v0
  14218. * 1.0, -1.0, 1.0, // v1
  14219. * 1.0, 1.0, 1.0, // v2
  14220. *
  14221. * 1.0, 1.0, 1.0, // v3
  14222. * -1.0, 1.0, 1.0, // v4
  14223. * -1.0, -1.0, 1.0 // v5
  14224. * ] );
  14225. * // itemSize = 3 because there are 3 values (components) per vertex
  14226. * geometry.setAttribute( 'position', new THREE.BufferAttribute( vertices, 3 ) );
  14227. * const material = new THREE.MeshBasicMaterial( { color: 0xff0000 } );
  14228. * const mesh = new THREE.Mesh( geometry, material );
  14229. * ```
  14230. *
  14231. * @augments EventDispatcher
  14232. */
  14233. class BufferGeometry extends EventDispatcher {
  14234. /**
  14235. * Constructs a new geometry.
  14236. */
  14237. constructor() {
  14238. super();
  14239. /**
  14240. * This flag can be used for type testing.
  14241. *
  14242. * @type {boolean}
  14243. * @readonly
  14244. * @default true
  14245. */
  14246. this.isBufferGeometry = true;
  14247. /**
  14248. * The ID of the geometry.
  14249. *
  14250. * @name BufferGeometry#id
  14251. * @type {number}
  14252. * @readonly
  14253. */
  14254. Object.defineProperty( this, 'id', { value: _id$1 ++ } );
  14255. /**
  14256. * The UUID of the geometry.
  14257. *
  14258. * @type {string}
  14259. * @readonly
  14260. */
  14261. this.uuid = generateUUID();
  14262. /**
  14263. * The name of the geometry.
  14264. *
  14265. * @type {string}
  14266. */
  14267. this.name = '';
  14268. this.type = 'BufferGeometry';
  14269. /**
  14270. * Allows for vertices to be re-used across multiple triangles; this is
  14271. * called using "indexed triangles". Each triangle is associated with the
  14272. * indices of three vertices. This attribute therefore stores the index of
  14273. * each vertex for each triangular face. If this attribute is not set, the
  14274. * renderer assumes that each three contiguous positions represent a single triangle.
  14275. *
  14276. * @type {?BufferAttribute}
  14277. * @default null
  14278. */
  14279. this.index = null;
  14280. /**
  14281. * A (storage) buffer attribute which was generated with a compute shader and
  14282. * now defines indirect draw calls.
  14283. *
  14284. * Can only be used with {@link WebGPURenderer} and a WebGPU backend.
  14285. *
  14286. * @type {?BufferAttribute}
  14287. * @default null
  14288. */
  14289. this.indirect = null;
  14290. /**
  14291. * The offset, in bytes, into the indirect drawing buffer where the value data begins. If an array is provided, multiple indirect draw calls will be made for each offset.
  14292. *
  14293. * Can only be used with {@link WebGPURenderer} and a WebGPU backend.
  14294. *
  14295. * @type {number|Array<number>}
  14296. * @default 0
  14297. */
  14298. this.indirectOffset = 0;
  14299. /**
  14300. * This dictionary has as id the name of the attribute to be set and as value
  14301. * the buffer attribute to set it to. Rather than accessing this property directly,
  14302. * use `setAttribute()` and `getAttribute()` to access attributes of this geometry.
  14303. *
  14304. * @type {Object<string,(BufferAttribute|InterleavedBufferAttribute)>}
  14305. */
  14306. this.attributes = {};
  14307. /**
  14308. * This dictionary holds the morph targets of the geometry.
  14309. *
  14310. * Note: Once the geometry has been rendered, the morph attribute data cannot
  14311. * be changed. You will have to call `dispose()`, and create a new geometry instance.
  14312. *
  14313. * @type {Object}
  14314. */
  14315. this.morphAttributes = {};
  14316. /**
  14317. * Used to control the morph target behavior; when set to `true`, the morph
  14318. * target data is treated as relative offsets, rather than as absolute
  14319. * positions/normals.
  14320. *
  14321. * @type {boolean}
  14322. * @default false
  14323. */
  14324. this.morphTargetsRelative = false;
  14325. /**
  14326. * Split the geometry into groups, each of which will be rendered in a
  14327. * separate draw call. This allows an array of materials to be used with the geometry.
  14328. *
  14329. * Use `addGroup()` and `clearGroups()` to edit groups, rather than modifying this array directly.
  14330. *
  14331. * Every vertex and index must belong to exactly one group — groups must not share vertices or
  14332. * indices, and must not leave vertices or indices unused.
  14333. *
  14334. * @type {Array<Object>}
  14335. */
  14336. this.groups = [];
  14337. /**
  14338. * Bounding box for the geometry which can be calculated with `computeBoundingBox()`.
  14339. *
  14340. * @type {?Box3}
  14341. * @default null
  14342. */
  14343. this.boundingBox = null;
  14344. /**
  14345. * Bounding sphere for the geometry which can be calculated with `computeBoundingSphere()`.
  14346. *
  14347. * @type {?Sphere}
  14348. * @default null
  14349. */
  14350. this.boundingSphere = null;
  14351. /**
  14352. * Determines the part of the geometry to render. This should not be set directly,
  14353. * instead use `setDrawRange()`.
  14354. *
  14355. * @type {{start:number,count:number}}
  14356. */
  14357. this.drawRange = { start: 0, count: Infinity };
  14358. /**
  14359. * An object that can be used to store custom data about the geometry.
  14360. * It should not hold references to functions as these will not be cloned.
  14361. *
  14362. * @type {Object}
  14363. */
  14364. this.userData = {};
  14365. }
  14366. /**
  14367. * Returns the index of this geometry.
  14368. *
  14369. * @return {?BufferAttribute} The index. Returns `null` if no index is defined.
  14370. */
  14371. getIndex() {
  14372. return this.index;
  14373. }
  14374. /**
  14375. * Sets the given index to this geometry.
  14376. *
  14377. * @param {Array<number>|BufferAttribute} index - The index to set.
  14378. * @return {BufferGeometry} A reference to this instance.
  14379. */
  14380. setIndex( index ) {
  14381. if ( Array.isArray( index ) ) {
  14382. this.index = new ( arrayNeedsUint32( index ) ? Uint32BufferAttribute : Uint16BufferAttribute )( index, 1 );
  14383. } else {
  14384. this.index = index;
  14385. }
  14386. return this;
  14387. }
  14388. /**
  14389. * Sets the given indirect attribute to this geometry.
  14390. *
  14391. * @param {BufferAttribute} indirect - The attribute holding indirect draw calls.
  14392. * @param {number|Array<number>} [indirectOffset=0] - The offset, in bytes, into the indirect drawing buffer where the value data begins. If an array is provided, multiple indirect draw calls will be made for each offset.
  14393. * @return {BufferGeometry} A reference to this instance.
  14394. */
  14395. setIndirect( indirect, indirectOffset = 0 ) {
  14396. this.indirect = indirect;
  14397. this.indirectOffset = indirectOffset;
  14398. return this;
  14399. }
  14400. /**
  14401. * Returns the indirect attribute of this geometry.
  14402. *
  14403. * @return {?BufferAttribute} The indirect attribute. Returns `null` if no indirect attribute is defined.
  14404. */
  14405. getIndirect() {
  14406. return this.indirect;
  14407. }
  14408. /**
  14409. * Returns the buffer attribute for the given name.
  14410. *
  14411. * @param {string} name - The attribute name.
  14412. * @return {BufferAttribute|InterleavedBufferAttribute|undefined} The buffer attribute.
  14413. * Returns `undefined` if not attribute has been found.
  14414. */
  14415. getAttribute( name ) {
  14416. return this.attributes[ name ];
  14417. }
  14418. /**
  14419. * Sets the given attribute for the given name.
  14420. *
  14421. * @param {string} name - The attribute name.
  14422. * @param {BufferAttribute|InterleavedBufferAttribute} attribute - The attribute to set.
  14423. * @return {BufferGeometry} A reference to this instance.
  14424. */
  14425. setAttribute( name, attribute ) {
  14426. this.attributes[ name ] = attribute;
  14427. return this;
  14428. }
  14429. /**
  14430. * Deletes the attribute for the given name.
  14431. *
  14432. * @param {string} name - The attribute name to delete.
  14433. * @return {BufferGeometry} A reference to this instance.
  14434. */
  14435. deleteAttribute( name ) {
  14436. delete this.attributes[ name ];
  14437. return this;
  14438. }
  14439. /**
  14440. * Returns `true` if this geometry has an attribute for the given name.
  14441. *
  14442. * @param {string} name - The attribute name.
  14443. * @return {boolean} Whether this geometry has an attribute for the given name or not.
  14444. */
  14445. hasAttribute( name ) {
  14446. return this.attributes[ name ] !== undefined;
  14447. }
  14448. /**
  14449. * Adds a group to this geometry.
  14450. *
  14451. * @param {number} start - The first element in this draw call. That is the first
  14452. * vertex for non-indexed geometry, otherwise the first triangle index.
  14453. * @param {number} count - Specifies how many vertices (or indices) are part of this group.
  14454. * @param {number} [materialIndex=0] - The material array index to use.
  14455. */
  14456. addGroup( start, count, materialIndex = 0 ) {
  14457. this.groups.push( {
  14458. start: start,
  14459. count: count,
  14460. materialIndex: materialIndex
  14461. } );
  14462. }
  14463. /**
  14464. * Clears all groups.
  14465. */
  14466. clearGroups() {
  14467. this.groups = [];
  14468. }
  14469. /**
  14470. * Sets the draw range for this geometry.
  14471. *
  14472. * @param {number} start - The first vertex for non-indexed geometry, otherwise the first triangle index.
  14473. * @param {number} count - For non-indexed BufferGeometry, `count` is the number of vertices to render.
  14474. * For indexed BufferGeometry, `count` is the number of indices to render.
  14475. */
  14476. setDrawRange( start, count ) {
  14477. this.drawRange.start = start;
  14478. this.drawRange.count = count;
  14479. }
  14480. /**
  14481. * Applies the given 4x4 transformation matrix to the geometry.
  14482. *
  14483. * @param {Matrix4} matrix - The matrix to apply.
  14484. * @return {BufferGeometry} A reference to this instance.
  14485. */
  14486. applyMatrix4( matrix ) {
  14487. const position = this.attributes.position;
  14488. if ( position !== undefined ) {
  14489. position.applyMatrix4( matrix );
  14490. position.needsUpdate = true;
  14491. }
  14492. const normal = this.attributes.normal;
  14493. if ( normal !== undefined ) {
  14494. const normalMatrix = new Matrix3().getNormalMatrix( matrix );
  14495. normal.applyNormalMatrix( normalMatrix );
  14496. normal.needsUpdate = true;
  14497. }
  14498. const tangent = this.attributes.tangent;
  14499. if ( tangent !== undefined ) {
  14500. tangent.transformDirection( matrix );
  14501. tangent.needsUpdate = true;
  14502. }
  14503. if ( this.boundingBox !== null ) {
  14504. this.computeBoundingBox();
  14505. }
  14506. if ( this.boundingSphere !== null ) {
  14507. this.computeBoundingSphere();
  14508. }
  14509. return this;
  14510. }
  14511. /**
  14512. * Applies the rotation represented by the Quaternion to the geometry.
  14513. *
  14514. * @param {Quaternion} q - The Quaternion to apply.
  14515. * @return {BufferGeometry} A reference to this instance.
  14516. */
  14517. applyQuaternion( q ) {
  14518. _m1.makeRotationFromQuaternion( q );
  14519. this.applyMatrix4( _m1 );
  14520. return this;
  14521. }
  14522. /**
  14523. * Rotates the geometry about the X axis. This is typically done as a one time
  14524. * operation, and not during a loop. Use {@link Object3D#rotation} for typical
  14525. * real-time mesh rotation.
  14526. *
  14527. * @param {number} angle - The angle in radians.
  14528. * @return {BufferGeometry} A reference to this instance.
  14529. */
  14530. rotateX( angle ) {
  14531. // rotate geometry around world x-axis
  14532. _m1.makeRotationX( angle );
  14533. this.applyMatrix4( _m1 );
  14534. return this;
  14535. }
  14536. /**
  14537. * Rotates the geometry about the Y axis. This is typically done as a one time
  14538. * operation, and not during a loop. Use {@link Object3D#rotation} for typical
  14539. * real-time mesh rotation.
  14540. *
  14541. * @param {number} angle - The angle in radians.
  14542. * @return {BufferGeometry} A reference to this instance.
  14543. */
  14544. rotateY( angle ) {
  14545. // rotate geometry around world y-axis
  14546. _m1.makeRotationY( angle );
  14547. this.applyMatrix4( _m1 );
  14548. return this;
  14549. }
  14550. /**
  14551. * Rotates the geometry about the Z axis. This is typically done as a one time
  14552. * operation, and not during a loop. Use {@link Object3D#rotation} for typical
  14553. * real-time mesh rotation.
  14554. *
  14555. * @param {number} angle - The angle in radians.
  14556. * @return {BufferGeometry} A reference to this instance.
  14557. */
  14558. rotateZ( angle ) {
  14559. // rotate geometry around world z-axis
  14560. _m1.makeRotationZ( angle );
  14561. this.applyMatrix4( _m1 );
  14562. return this;
  14563. }
  14564. /**
  14565. * Translates the geometry. This is typically done as a one time
  14566. * operation, and not during a loop. Use {@link Object3D#position} for typical
  14567. * real-time mesh rotation.
  14568. *
  14569. * @param {number} x - The x offset.
  14570. * @param {number} y - The y offset.
  14571. * @param {number} z - The z offset.
  14572. * @return {BufferGeometry} A reference to this instance.
  14573. */
  14574. translate( x, y, z ) {
  14575. // translate geometry
  14576. _m1.makeTranslation( x, y, z );
  14577. this.applyMatrix4( _m1 );
  14578. return this;
  14579. }
  14580. /**
  14581. * Scales the geometry. This is typically done as a one time
  14582. * operation, and not during a loop. Use {@link Object3D#scale} for typical
  14583. * real-time mesh rotation.
  14584. *
  14585. * @param {number} x - The x scale.
  14586. * @param {number} y - The y scale.
  14587. * @param {number} z - The z scale.
  14588. * @return {BufferGeometry} A reference to this instance.
  14589. */
  14590. scale( x, y, z ) {
  14591. // scale geometry
  14592. _m1.makeScale( x, y, z );
  14593. this.applyMatrix4( _m1 );
  14594. return this;
  14595. }
  14596. /**
  14597. * Rotates the geometry to face a point in 3D space. This is typically done as a one time
  14598. * operation, and not during a loop. Use {@link Object3D#lookAt} for typical
  14599. * real-time mesh rotation.
  14600. *
  14601. * @param {Vector3} vector - The target point.
  14602. * @return {BufferGeometry} A reference to this instance.
  14603. */
  14604. lookAt( vector ) {
  14605. _obj.lookAt( vector );
  14606. _obj.updateMatrix();
  14607. this.applyMatrix4( _obj.matrix );
  14608. return this;
  14609. }
  14610. /**
  14611. * Center the geometry based on its bounding box.
  14612. *
  14613. * @return {BufferGeometry} A reference to this instance.
  14614. */
  14615. center() {
  14616. this.computeBoundingBox();
  14617. this.boundingBox.getCenter( _offset ).negate();
  14618. this.translate( _offset.x, _offset.y, _offset.z );
  14619. return this;
  14620. }
  14621. /**
  14622. * Defines a geometry by creating a `position` attribute based on the given array of points. The array
  14623. * can hold 2D or 3D vectors. When using two-dimensional data, the `z` coordinate for all vertices is
  14624. * set to `0`.
  14625. *
  14626. * If the method is used with an existing `position` attribute, the vertex data are overwritten with the
  14627. * data from the array. The length of the array must match the vertex count.
  14628. *
  14629. * @param {Array<Vector2>|Array<Vector3>} points - The points.
  14630. * @return {BufferGeometry} A reference to this instance.
  14631. */
  14632. setFromPoints( points ) {
  14633. const positionAttribute = this.getAttribute( 'position' );
  14634. if ( positionAttribute === undefined ) {
  14635. const position = [];
  14636. for ( let i = 0, l = points.length; i < l; i ++ ) {
  14637. const point = points[ i ];
  14638. position.push( point.x, point.y, point.z || 0 );
  14639. }
  14640. this.setAttribute( 'position', new Float32BufferAttribute( position, 3 ) );
  14641. } else {
  14642. const l = Math.min( points.length, positionAttribute.count ); // make sure data do not exceed buffer size
  14643. for ( let i = 0; i < l; i ++ ) {
  14644. const point = points[ i ];
  14645. positionAttribute.setXYZ( i, point.x, point.y, point.z || 0 );
  14646. }
  14647. if ( points.length > positionAttribute.count ) {
  14648. warn( 'BufferGeometry: Buffer size too small for points data. Use .dispose() and create a new geometry.' );
  14649. }
  14650. positionAttribute.needsUpdate = true;
  14651. }
  14652. return this;
  14653. }
  14654. /**
  14655. * Computes the bounding box of the geometry, and updates the `boundingBox` member.
  14656. * The bounding box is not computed by the engine; it must be computed by your app.
  14657. * You may need to recompute the bounding box if the geometry vertices are modified.
  14658. */
  14659. computeBoundingBox() {
  14660. if ( this.boundingBox === null ) {
  14661. this.boundingBox = new Box3();
  14662. }
  14663. const position = this.attributes.position;
  14664. const morphAttributesPosition = this.morphAttributes.position;
  14665. if ( position && position.isGLBufferAttribute ) {
  14666. error( 'BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box.', this );
  14667. this.boundingBox.set(
  14668. new Vector3( - Infinity, - Infinity, - Infinity ),
  14669. new Vector3( + Infinity, + Infinity, + Infinity )
  14670. );
  14671. return;
  14672. }
  14673. if ( position !== undefined ) {
  14674. this.boundingBox.setFromBufferAttribute( position );
  14675. // process morph attributes if present
  14676. if ( morphAttributesPosition ) {
  14677. for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  14678. const morphAttribute = morphAttributesPosition[ i ];
  14679. _box$2.setFromBufferAttribute( morphAttribute );
  14680. if ( this.morphTargetsRelative ) {
  14681. _vector$8.addVectors( this.boundingBox.min, _box$2.min );
  14682. this.boundingBox.expandByPoint( _vector$8 );
  14683. _vector$8.addVectors( this.boundingBox.max, _box$2.max );
  14684. this.boundingBox.expandByPoint( _vector$8 );
  14685. } else {
  14686. this.boundingBox.expandByPoint( _box$2.min );
  14687. this.boundingBox.expandByPoint( _box$2.max );
  14688. }
  14689. }
  14690. }
  14691. } else {
  14692. this.boundingBox.makeEmpty();
  14693. }
  14694. if ( isNaN( this.boundingBox.min.x ) || isNaN( this.boundingBox.min.y ) || isNaN( this.boundingBox.min.z ) ) {
  14695. error( 'BufferGeometry.computeBoundingBox(): Computed min/max have NaN values. The "position" attribute is likely to have NaN values.', this );
  14696. }
  14697. }
  14698. /**
  14699. * Computes the bounding sphere of the geometry, and updates the `boundingSphere` member.
  14700. * The engine automatically computes the bounding sphere when it is needed, e.g., for ray casting or view frustum culling.
  14701. * You may need to recompute the bounding sphere if the geometry vertices are modified.
  14702. */
  14703. computeBoundingSphere() {
  14704. if ( this.boundingSphere === null ) {
  14705. this.boundingSphere = new Sphere();
  14706. }
  14707. const position = this.attributes.position;
  14708. const morphAttributesPosition = this.morphAttributes.position;
  14709. if ( position && position.isGLBufferAttribute ) {
  14710. error( 'BufferGeometry.computeBoundingSphere(): GLBufferAttribute requires a manual bounding sphere.', this );
  14711. this.boundingSphere.set( new Vector3(), Infinity );
  14712. return;
  14713. }
  14714. if ( position ) {
  14715. // first, find the center of the bounding sphere
  14716. const center = this.boundingSphere.center;
  14717. _box$2.setFromBufferAttribute( position );
  14718. // process morph attributes if present
  14719. if ( morphAttributesPosition ) {
  14720. for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  14721. const morphAttribute = morphAttributesPosition[ i ];
  14722. _boxMorphTargets.setFromBufferAttribute( morphAttribute );
  14723. if ( this.morphTargetsRelative ) {
  14724. _vector$8.addVectors( _box$2.min, _boxMorphTargets.min );
  14725. _box$2.expandByPoint( _vector$8 );
  14726. _vector$8.addVectors( _box$2.max, _boxMorphTargets.max );
  14727. _box$2.expandByPoint( _vector$8 );
  14728. } else {
  14729. _box$2.expandByPoint( _boxMorphTargets.min );
  14730. _box$2.expandByPoint( _boxMorphTargets.max );
  14731. }
  14732. }
  14733. }
  14734. _box$2.getCenter( center );
  14735. // second, try to find a boundingSphere with a radius smaller than the
  14736. // boundingSphere of the boundingBox: sqrt(3) smaller in the best case
  14737. let maxRadiusSq = 0;
  14738. for ( let i = 0, il = position.count; i < il; i ++ ) {
  14739. _vector$8.fromBufferAttribute( position, i );
  14740. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( _vector$8 ) );
  14741. }
  14742. // process morph attributes if present
  14743. if ( morphAttributesPosition ) {
  14744. for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  14745. const morphAttribute = morphAttributesPosition[ i ];
  14746. const morphTargetsRelative = this.morphTargetsRelative;
  14747. for ( let j = 0, jl = morphAttribute.count; j < jl; j ++ ) {
  14748. _vector$8.fromBufferAttribute( morphAttribute, j );
  14749. if ( morphTargetsRelative ) {
  14750. _offset.fromBufferAttribute( position, j );
  14751. _vector$8.add( _offset );
  14752. }
  14753. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( _vector$8 ) );
  14754. }
  14755. }
  14756. }
  14757. this.boundingSphere.radius = Math.sqrt( maxRadiusSq );
  14758. if ( isNaN( this.boundingSphere.radius ) ) {
  14759. error( 'BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.', this );
  14760. }
  14761. }
  14762. }
  14763. /**
  14764. * Calculates and adds a tangent attribute to this geometry.
  14765. *
  14766. * The computation is only supported for indexed geometries and if position, normal, and uv attributes
  14767. * are defined. When using a tangent space normal map, prefer the MikkTSpace algorithm provided by
  14768. * {@link BufferGeometryUtils#computeMikkTSpaceTangents} instead.
  14769. */
  14770. computeTangents() {
  14771. const index = this.index;
  14772. const attributes = this.attributes;
  14773. // based on http://www.terathon.com/code/tangent.html
  14774. // (per vertex tangents)
  14775. if ( index === null ||
  14776. attributes.position === undefined ||
  14777. attributes.normal === undefined ||
  14778. attributes.uv === undefined ) {
  14779. error( 'BufferGeometry: .computeTangents() failed. Missing required attributes (index, position, normal or uv)' );
  14780. return;
  14781. }
  14782. const positionAttribute = attributes.position;
  14783. const normalAttribute = attributes.normal;
  14784. const uvAttribute = attributes.uv;
  14785. if ( this.hasAttribute( 'tangent' ) === false ) {
  14786. this.setAttribute( 'tangent', new BufferAttribute( new Float32Array( 4 * positionAttribute.count ), 4 ) );
  14787. }
  14788. const tangentAttribute = this.getAttribute( 'tangent' );
  14789. const tan1 = [], tan2 = [];
  14790. for ( let i = 0; i < positionAttribute.count; i ++ ) {
  14791. tan1[ i ] = new Vector3();
  14792. tan2[ i ] = new Vector3();
  14793. }
  14794. const vA = new Vector3(),
  14795. vB = new Vector3(),
  14796. vC = new Vector3(),
  14797. uvA = new Vector2(),
  14798. uvB = new Vector2(),
  14799. uvC = new Vector2(),
  14800. sdir = new Vector3(),
  14801. tdir = new Vector3();
  14802. function handleTriangle( a, b, c ) {
  14803. vA.fromBufferAttribute( positionAttribute, a );
  14804. vB.fromBufferAttribute( positionAttribute, b );
  14805. vC.fromBufferAttribute( positionAttribute, c );
  14806. uvA.fromBufferAttribute( uvAttribute, a );
  14807. uvB.fromBufferAttribute( uvAttribute, b );
  14808. uvC.fromBufferAttribute( uvAttribute, c );
  14809. vB.sub( vA );
  14810. vC.sub( vA );
  14811. uvB.sub( uvA );
  14812. uvC.sub( uvA );
  14813. const r = 1.0 / ( uvB.x * uvC.y - uvC.x * uvB.y );
  14814. // silently ignore degenerate uv triangles having coincident or colinear vertices
  14815. if ( ! isFinite( r ) ) return;
  14816. sdir.copy( vB ).multiplyScalar( uvC.y ).addScaledVector( vC, - uvB.y ).multiplyScalar( r );
  14817. tdir.copy( vC ).multiplyScalar( uvB.x ).addScaledVector( vB, - uvC.x ).multiplyScalar( r );
  14818. tan1[ a ].add( sdir );
  14819. tan1[ b ].add( sdir );
  14820. tan1[ c ].add( sdir );
  14821. tan2[ a ].add( tdir );
  14822. tan2[ b ].add( tdir );
  14823. tan2[ c ].add( tdir );
  14824. }
  14825. let groups = this.groups;
  14826. if ( groups.length === 0 ) {
  14827. groups = [ {
  14828. start: 0,
  14829. count: index.count
  14830. } ];
  14831. }
  14832. for ( let i = 0, il = groups.length; i < il; ++ i ) {
  14833. const group = groups[ i ];
  14834. const start = group.start;
  14835. const count = group.count;
  14836. for ( let j = start, jl = start + count; j < jl; j += 3 ) {
  14837. handleTriangle(
  14838. index.getX( j + 0 ),
  14839. index.getX( j + 1 ),
  14840. index.getX( j + 2 )
  14841. );
  14842. }
  14843. }
  14844. const tmp = new Vector3(), tmp2 = new Vector3();
  14845. const n = new Vector3(), n2 = new Vector3();
  14846. function handleVertex( v ) {
  14847. n.fromBufferAttribute( normalAttribute, v );
  14848. n2.copy( n );
  14849. const t = tan1[ v ];
  14850. // Gram-Schmidt orthogonalize
  14851. tmp.copy( t );
  14852. tmp.sub( n.multiplyScalar( n.dot( t ) ) ).normalize();
  14853. // Calculate handedness
  14854. tmp2.crossVectors( n2, t );
  14855. const test = tmp2.dot( tan2[ v ] );
  14856. const w = ( test < 0.0 ) ? -1 : 1.0;
  14857. tangentAttribute.setXYZW( v, tmp.x, tmp.y, tmp.z, w );
  14858. }
  14859. for ( let i = 0, il = groups.length; i < il; ++ i ) {
  14860. const group = groups[ i ];
  14861. const start = group.start;
  14862. const count = group.count;
  14863. for ( let j = start, jl = start + count; j < jl; j += 3 ) {
  14864. handleVertex( index.getX( j + 0 ) );
  14865. handleVertex( index.getX( j + 1 ) );
  14866. handleVertex( index.getX( j + 2 ) );
  14867. }
  14868. }
  14869. }
  14870. /**
  14871. * Computes vertex normals for the given vertex data. For indexed geometries, the method sets
  14872. * each vertex normal to be the average of the face normals of the faces that share that vertex.
  14873. * For non-indexed geometries, vertices are not shared, and the method sets each vertex normal
  14874. * to be the same as the face normal.
  14875. */
  14876. computeVertexNormals() {
  14877. const index = this.index;
  14878. const positionAttribute = this.getAttribute( 'position' );
  14879. if ( positionAttribute !== undefined ) {
  14880. let normalAttribute = this.getAttribute( 'normal' );
  14881. if ( normalAttribute === undefined ) {
  14882. normalAttribute = new BufferAttribute( new Float32Array( positionAttribute.count * 3 ), 3 );
  14883. this.setAttribute( 'normal', normalAttribute );
  14884. } else {
  14885. // reset existing normals to zero
  14886. for ( let i = 0, il = normalAttribute.count; i < il; i ++ ) {
  14887. normalAttribute.setXYZ( i, 0, 0, 0 );
  14888. }
  14889. }
  14890. const pA = new Vector3(), pB = new Vector3(), pC = new Vector3();
  14891. const nA = new Vector3(), nB = new Vector3(), nC = new Vector3();
  14892. const cb = new Vector3(), ab = new Vector3();
  14893. // indexed elements
  14894. if ( index ) {
  14895. for ( let i = 0, il = index.count; i < il; i += 3 ) {
  14896. const vA = index.getX( i + 0 );
  14897. const vB = index.getX( i + 1 );
  14898. const vC = index.getX( i + 2 );
  14899. pA.fromBufferAttribute( positionAttribute, vA );
  14900. pB.fromBufferAttribute( positionAttribute, vB );
  14901. pC.fromBufferAttribute( positionAttribute, vC );
  14902. cb.subVectors( pC, pB );
  14903. ab.subVectors( pA, pB );
  14904. cb.cross( ab );
  14905. nA.fromBufferAttribute( normalAttribute, vA );
  14906. nB.fromBufferAttribute( normalAttribute, vB );
  14907. nC.fromBufferAttribute( normalAttribute, vC );
  14908. nA.add( cb );
  14909. nB.add( cb );
  14910. nC.add( cb );
  14911. normalAttribute.setXYZ( vA, nA.x, nA.y, nA.z );
  14912. normalAttribute.setXYZ( vB, nB.x, nB.y, nB.z );
  14913. normalAttribute.setXYZ( vC, nC.x, nC.y, nC.z );
  14914. }
  14915. } else {
  14916. // non-indexed elements (unconnected triangle soup)
  14917. for ( let i = 0, il = positionAttribute.count; i < il; i += 3 ) {
  14918. pA.fromBufferAttribute( positionAttribute, i + 0 );
  14919. pB.fromBufferAttribute( positionAttribute, i + 1 );
  14920. pC.fromBufferAttribute( positionAttribute, i + 2 );
  14921. cb.subVectors( pC, pB );
  14922. ab.subVectors( pA, pB );
  14923. cb.cross( ab );
  14924. normalAttribute.setXYZ( i + 0, cb.x, cb.y, cb.z );
  14925. normalAttribute.setXYZ( i + 1, cb.x, cb.y, cb.z );
  14926. normalAttribute.setXYZ( i + 2, cb.x, cb.y, cb.z );
  14927. }
  14928. }
  14929. this.normalizeNormals();
  14930. normalAttribute.needsUpdate = true;
  14931. }
  14932. }
  14933. /**
  14934. * Ensures every normal vector in a geometry will have a magnitude of `1`. This will
  14935. * correct lighting on the geometry surfaces.
  14936. */
  14937. normalizeNormals() {
  14938. const normals = this.attributes.normal;
  14939. for ( let i = 0, il = normals.count; i < il; i ++ ) {
  14940. _vector$8.fromBufferAttribute( normals, i );
  14941. _vector$8.normalize();
  14942. normals.setXYZ( i, _vector$8.x, _vector$8.y, _vector$8.z );
  14943. }
  14944. }
  14945. /**
  14946. * Return a new non-index version of this indexed geometry. If the geometry
  14947. * is already non-indexed, the method is a NOOP.
  14948. *
  14949. * @return {BufferGeometry} The non-indexed version of this indexed geometry.
  14950. */
  14951. toNonIndexed() {
  14952. function convertBufferAttribute( attribute, indices ) {
  14953. const array = attribute.array;
  14954. const itemSize = attribute.itemSize;
  14955. const normalized = attribute.normalized;
  14956. const array2 = new array.constructor( indices.length * itemSize );
  14957. let index = 0, index2 = 0;
  14958. for ( let i = 0, l = indices.length; i < l; i ++ ) {
  14959. if ( attribute.isInterleavedBufferAttribute ) {
  14960. index = indices[ i ] * attribute.data.stride + attribute.offset;
  14961. } else {
  14962. index = indices[ i ] * itemSize;
  14963. }
  14964. for ( let j = 0; j < itemSize; j ++ ) {
  14965. array2[ index2 ++ ] = array[ index ++ ];
  14966. }
  14967. }
  14968. return new BufferAttribute( array2, itemSize, normalized );
  14969. }
  14970. //
  14971. if ( this.index === null ) {
  14972. warn( 'BufferGeometry.toNonIndexed(): BufferGeometry is already non-indexed.' );
  14973. return this;
  14974. }
  14975. const geometry2 = new BufferGeometry();
  14976. const indices = this.index.array;
  14977. const attributes = this.attributes;
  14978. // attributes
  14979. for ( const name in attributes ) {
  14980. const attribute = attributes[ name ];
  14981. const newAttribute = convertBufferAttribute( attribute, indices );
  14982. geometry2.setAttribute( name, newAttribute );
  14983. }
  14984. // morph attributes
  14985. const morphAttributes = this.morphAttributes;
  14986. for ( const name in morphAttributes ) {
  14987. const morphArray = [];
  14988. const morphAttribute = morphAttributes[ name ]; // morphAttribute: array of Float32BufferAttributes
  14989. for ( let i = 0, il = morphAttribute.length; i < il; i ++ ) {
  14990. const attribute = morphAttribute[ i ];
  14991. const newAttribute = convertBufferAttribute( attribute, indices );
  14992. morphArray.push( newAttribute );
  14993. }
  14994. geometry2.morphAttributes[ name ] = morphArray;
  14995. }
  14996. geometry2.morphTargetsRelative = this.morphTargetsRelative;
  14997. // groups
  14998. const groups = this.groups;
  14999. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  15000. const group = groups[ i ];
  15001. geometry2.addGroup( group.start, group.count, group.materialIndex );
  15002. }
  15003. return geometry2;
  15004. }
  15005. /**
  15006. * Serializes the geometry into JSON.
  15007. *
  15008. * @return {Object} A JSON object representing the serialized geometry.
  15009. */
  15010. toJSON() {
  15011. const data = {
  15012. metadata: {
  15013. version: 4.7,
  15014. type: 'BufferGeometry',
  15015. generator: 'BufferGeometry.toJSON'
  15016. }
  15017. };
  15018. // standard BufferGeometry serialization
  15019. data.uuid = this.uuid;
  15020. data.type = this.type;
  15021. if ( this.name !== '' ) data.name = this.name;
  15022. if ( Object.keys( this.userData ).length > 0 ) data.userData = this.userData;
  15023. if ( this.parameters !== undefined ) {
  15024. const parameters = this.parameters;
  15025. for ( const key in parameters ) {
  15026. if ( parameters[ key ] !== undefined ) data[ key ] = parameters[ key ];
  15027. }
  15028. return data;
  15029. }
  15030. // for simplicity the code assumes attributes are not shared across geometries, see #15811
  15031. data.data = { attributes: {} };
  15032. const index = this.index;
  15033. if ( index !== null ) {
  15034. data.data.index = {
  15035. type: index.array.constructor.name,
  15036. array: Array.prototype.slice.call( index.array )
  15037. };
  15038. }
  15039. const attributes = this.attributes;
  15040. for ( const key in attributes ) {
  15041. const attribute = attributes[ key ];
  15042. data.data.attributes[ key ] = attribute.toJSON( data.data );
  15043. }
  15044. const morphAttributes = {};
  15045. let hasMorphAttributes = false;
  15046. for ( const key in this.morphAttributes ) {
  15047. const attributeArray = this.morphAttributes[ key ];
  15048. const array = [];
  15049. for ( let i = 0, il = attributeArray.length; i < il; i ++ ) {
  15050. const attribute = attributeArray[ i ];
  15051. array.push( attribute.toJSON( data.data ) );
  15052. }
  15053. if ( array.length > 0 ) {
  15054. morphAttributes[ key ] = array;
  15055. hasMorphAttributes = true;
  15056. }
  15057. }
  15058. if ( hasMorphAttributes ) {
  15059. data.data.morphAttributes = morphAttributes;
  15060. data.data.morphTargetsRelative = this.morphTargetsRelative;
  15061. }
  15062. const groups = this.groups;
  15063. if ( groups.length > 0 ) {
  15064. data.data.groups = JSON.parse( JSON.stringify( groups ) );
  15065. }
  15066. const boundingSphere = this.boundingSphere;
  15067. if ( boundingSphere !== null ) {
  15068. data.data.boundingSphere = boundingSphere.toJSON();
  15069. }
  15070. return data;
  15071. }
  15072. /**
  15073. * Returns a new geometry with copied values from this instance.
  15074. *
  15075. * @return {BufferGeometry} A clone of this instance.
  15076. */
  15077. clone() {
  15078. return new this.constructor().copy( this );
  15079. }
  15080. /**
  15081. * Copies the values of the given geometry to this instance.
  15082. *
  15083. * @param {BufferGeometry} source - The geometry to copy.
  15084. * @return {BufferGeometry} A reference to this instance.
  15085. */
  15086. copy( source ) {
  15087. // reset
  15088. this.index = null;
  15089. this.attributes = {};
  15090. this.morphAttributes = {};
  15091. this.groups = [];
  15092. this.boundingBox = null;
  15093. this.boundingSphere = null;
  15094. // used for storing cloned, shared data
  15095. const data = {};
  15096. // name
  15097. this.name = source.name;
  15098. // index
  15099. const index = source.index;
  15100. if ( index !== null ) {
  15101. this.setIndex( index.clone() );
  15102. }
  15103. // attributes
  15104. const attributes = source.attributes;
  15105. for ( const name in attributes ) {
  15106. const attribute = attributes[ name ];
  15107. this.setAttribute( name, attribute.clone( data ) );
  15108. }
  15109. // morph attributes
  15110. const morphAttributes = source.morphAttributes;
  15111. for ( const name in morphAttributes ) {
  15112. const array = [];
  15113. const morphAttribute = morphAttributes[ name ]; // morphAttribute: array of Float32BufferAttributes
  15114. for ( let i = 0, l = morphAttribute.length; i < l; i ++ ) {
  15115. array.push( morphAttribute[ i ].clone( data ) );
  15116. }
  15117. this.morphAttributes[ name ] = array;
  15118. }
  15119. this.morphTargetsRelative = source.morphTargetsRelative;
  15120. // groups
  15121. const groups = source.groups;
  15122. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  15123. const group = groups[ i ];
  15124. this.addGroup( group.start, group.count, group.materialIndex );
  15125. }
  15126. // bounding box
  15127. const boundingBox = source.boundingBox;
  15128. if ( boundingBox !== null ) {
  15129. this.boundingBox = boundingBox.clone();
  15130. }
  15131. // bounding sphere
  15132. const boundingSphere = source.boundingSphere;
  15133. if ( boundingSphere !== null ) {
  15134. this.boundingSphere = boundingSphere.clone();
  15135. }
  15136. // draw range
  15137. this.drawRange.start = source.drawRange.start;
  15138. this.drawRange.count = source.drawRange.count;
  15139. // user data
  15140. this.userData = source.userData;
  15141. return this;
  15142. }
  15143. /**
  15144. * Frees the GPU-related resources allocated by this instance. Call this
  15145. * method whenever this instance is no longer used in your app.
  15146. *
  15147. * @fires BufferGeometry#dispose
  15148. */
  15149. dispose() {
  15150. this.dispatchEvent( { type: 'dispose' } );
  15151. }
  15152. }
  15153. const _inverseMatrix$3 = /*@__PURE__*/ new Matrix4();
  15154. const _ray$3 = /*@__PURE__*/ new Ray();
  15155. const _sphere$6 = /*@__PURE__*/ new Sphere();
  15156. const _sphereHitAt = /*@__PURE__*/ new Vector3();
  15157. const _vA$1 = /*@__PURE__*/ new Vector3();
  15158. const _vB$1 = /*@__PURE__*/ new Vector3();
  15159. const _vC$1 = /*@__PURE__*/ new Vector3();
  15160. const _tempA = /*@__PURE__*/ new Vector3();
  15161. const _morphA = /*@__PURE__*/ new Vector3();
  15162. const _intersectionPoint = /*@__PURE__*/ new Vector3();
  15163. const _intersectionPointWorld = /*@__PURE__*/ new Vector3();
  15164. /**
  15165. * Class representing triangular polygon mesh based objects.
  15166. *
  15167. * ```js
  15168. * const geometry = new THREE.BoxGeometry( 1, 1, 1 );
  15169. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  15170. * const mesh = new THREE.Mesh( geometry, material );
  15171. * scene.add( mesh );
  15172. * ```
  15173. *
  15174. * @augments Object3D
  15175. */
  15176. class Mesh extends Object3D {
  15177. /**
  15178. * Constructs a new mesh.
  15179. *
  15180. * @param {BufferGeometry} [geometry] - The mesh geometry.
  15181. * @param {Material|Array<Material>} [material] - The mesh material.
  15182. */
  15183. constructor( geometry = new BufferGeometry(), material = new MeshBasicMaterial() ) {
  15184. super();
  15185. /**
  15186. * This flag can be used for type testing.
  15187. *
  15188. * @type {boolean}
  15189. * @readonly
  15190. * @default true
  15191. */
  15192. this.isMesh = true;
  15193. this.type = 'Mesh';
  15194. /**
  15195. * The mesh geometry.
  15196. *
  15197. * @type {BufferGeometry}
  15198. */
  15199. this.geometry = geometry;
  15200. /**
  15201. * The mesh material.
  15202. *
  15203. * @type {Material|Array<Material>}
  15204. * @default MeshBasicMaterial
  15205. */
  15206. this.material = material;
  15207. /**
  15208. * A dictionary representing the morph targets in the geometry. The key is the
  15209. * morph targets name, the value its attribute index. This member is `undefined`
  15210. * by default and only set when morph targets are detected in the geometry.
  15211. *
  15212. * @type {Object<string,number>|undefined}
  15213. * @default undefined
  15214. */
  15215. this.morphTargetDictionary = undefined;
  15216. /**
  15217. * An array of weights typically in the range `[0,1]` that specify how much of the morph
  15218. * is applied. This member is `undefined` by default and only set when morph targets are
  15219. * detected in the geometry.
  15220. *
  15221. * @type {Array<number>|undefined}
  15222. * @default undefined
  15223. */
  15224. this.morphTargetInfluences = undefined;
  15225. /**
  15226. * The number of instances of this mesh.
  15227. * Can only be used with {@link WebGPURenderer}.
  15228. *
  15229. * @type {number}
  15230. * @default 1
  15231. */
  15232. this.count = 1;
  15233. this.updateMorphTargets();
  15234. }
  15235. copy( source, recursive ) {
  15236. super.copy( source, recursive );
  15237. if ( source.morphTargetInfluences !== undefined ) {
  15238. this.morphTargetInfluences = source.morphTargetInfluences.slice();
  15239. }
  15240. if ( source.morphTargetDictionary !== undefined ) {
  15241. this.morphTargetDictionary = Object.assign( {}, source.morphTargetDictionary );
  15242. }
  15243. this.material = Array.isArray( source.material ) ? source.material.slice() : source.material;
  15244. this.geometry = source.geometry;
  15245. return this;
  15246. }
  15247. /**
  15248. * Sets the values of {@link Mesh#morphTargetDictionary} and {@link Mesh#morphTargetInfluences}
  15249. * to make sure existing morph targets can influence this 3D object.
  15250. */
  15251. updateMorphTargets() {
  15252. const geometry = this.geometry;
  15253. const morphAttributes = geometry.morphAttributes;
  15254. const keys = Object.keys( morphAttributes );
  15255. if ( keys.length > 0 ) {
  15256. const morphAttribute = morphAttributes[ keys[ 0 ] ];
  15257. if ( morphAttribute !== undefined ) {
  15258. this.morphTargetInfluences = [];
  15259. this.morphTargetDictionary = {};
  15260. for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  15261. const name = morphAttribute[ m ].name || String( m );
  15262. this.morphTargetInfluences.push( 0 );
  15263. this.morphTargetDictionary[ name ] = m;
  15264. }
  15265. }
  15266. }
  15267. }
  15268. /**
  15269. * Returns the local-space position of the vertex at the given index, taking into
  15270. * account the current animation state of both morph targets and skinning.
  15271. *
  15272. * @param {number} index - The vertex index.
  15273. * @param {Vector3} target - The target object that is used to store the method's result.
  15274. * @return {Vector3} The vertex position in local space.
  15275. */
  15276. getVertexPosition( index, target ) {
  15277. const geometry = this.geometry;
  15278. const position = geometry.attributes.position;
  15279. const morphPosition = geometry.morphAttributes.position;
  15280. const morphTargetsRelative = geometry.morphTargetsRelative;
  15281. target.fromBufferAttribute( position, index );
  15282. const morphInfluences = this.morphTargetInfluences;
  15283. if ( morphPosition && morphInfluences ) {
  15284. _morphA.set( 0, 0, 0 );
  15285. for ( let i = 0, il = morphPosition.length; i < il; i ++ ) {
  15286. const influence = morphInfluences[ i ];
  15287. const morphAttribute = morphPosition[ i ];
  15288. if ( influence === 0 ) continue;
  15289. _tempA.fromBufferAttribute( morphAttribute, index );
  15290. if ( morphTargetsRelative ) {
  15291. _morphA.addScaledVector( _tempA, influence );
  15292. } else {
  15293. _morphA.addScaledVector( _tempA.sub( target ), influence );
  15294. }
  15295. }
  15296. target.add( _morphA );
  15297. }
  15298. return target;
  15299. }
  15300. /**
  15301. * Computes intersection points between a casted ray and this line.
  15302. *
  15303. * @param {Raycaster} raycaster - The raycaster.
  15304. * @param {Array<Object>} intersects - The target array that holds the intersection points.
  15305. */
  15306. raycast( raycaster, intersects ) {
  15307. const geometry = this.geometry;
  15308. const material = this.material;
  15309. const matrixWorld = this.matrixWorld;
  15310. if ( material === undefined ) return;
  15311. // test with bounding sphere in world space
  15312. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  15313. _sphere$6.copy( geometry.boundingSphere );
  15314. _sphere$6.applyMatrix4( matrixWorld );
  15315. // check distance from ray origin to bounding sphere
  15316. _ray$3.copy( raycaster.ray ).recast( raycaster.near );
  15317. if ( _sphere$6.containsPoint( _ray$3.origin ) === false ) {
  15318. if ( _ray$3.intersectSphere( _sphere$6, _sphereHitAt ) === null ) return;
  15319. if ( _ray$3.origin.distanceToSquared( _sphereHitAt ) > ( raycaster.far - raycaster.near ) ** 2 ) return;
  15320. }
  15321. // convert ray to local space of mesh
  15322. _inverseMatrix$3.copy( matrixWorld ).invert();
  15323. _ray$3.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$3 );
  15324. // test with bounding box in local space
  15325. if ( geometry.boundingBox !== null ) {
  15326. if ( _ray$3.intersectsBox( geometry.boundingBox ) === false ) return;
  15327. }
  15328. // test for intersections with geometry
  15329. this._computeIntersections( raycaster, intersects, _ray$3 );
  15330. }
  15331. _computeIntersections( raycaster, intersects, rayLocalSpace ) {
  15332. let intersection;
  15333. const geometry = this.geometry;
  15334. const material = this.material;
  15335. const index = geometry.index;
  15336. const position = geometry.attributes.position;
  15337. const uv = geometry.attributes.uv;
  15338. const uv1 = geometry.attributes.uv1;
  15339. const normal = geometry.attributes.normal;
  15340. const groups = geometry.groups;
  15341. const drawRange = geometry.drawRange;
  15342. if ( index !== null ) {
  15343. // indexed buffer geometry
  15344. if ( Array.isArray( material ) ) {
  15345. for ( let i = 0, il = groups.length; i < il; i ++ ) {
  15346. const group = groups[ i ];
  15347. const groupMaterial = material[ group.materialIndex ];
  15348. const start = Math.max( group.start, drawRange.start );
  15349. const end = Math.min( index.count, Math.min( ( group.start + group.count ), ( drawRange.start + drawRange.count ) ) );
  15350. for ( let j = start, jl = end; j < jl; j += 3 ) {
  15351. const a = index.getX( j );
  15352. const b = index.getX( j + 1 );
  15353. const c = index.getX( j + 2 );
  15354. intersection = checkGeometryIntersection( this, groupMaterial, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c );
  15355. if ( intersection ) {
  15356. intersection.faceIndex = Math.floor( j / 3 ); // triangle number in indexed buffer semantics
  15357. intersection.face.materialIndex = group.materialIndex;
  15358. intersects.push( intersection );
  15359. }
  15360. }
  15361. }
  15362. } else {
  15363. const start = Math.max( 0, drawRange.start );
  15364. const end = Math.min( index.count, ( drawRange.start + drawRange.count ) );
  15365. for ( let i = start, il = end; i < il; i += 3 ) {
  15366. const a = index.getX( i );
  15367. const b = index.getX( i + 1 );
  15368. const c = index.getX( i + 2 );
  15369. intersection = checkGeometryIntersection( this, material, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c );
  15370. if ( intersection ) {
  15371. intersection.faceIndex = Math.floor( i / 3 ); // triangle number in indexed buffer semantics
  15372. intersects.push( intersection );
  15373. }
  15374. }
  15375. }
  15376. } else if ( position !== undefined ) {
  15377. // non-indexed buffer geometry
  15378. if ( Array.isArray( material ) ) {
  15379. for ( let i = 0, il = groups.length; i < il; i ++ ) {
  15380. const group = groups[ i ];
  15381. const groupMaterial = material[ group.materialIndex ];
  15382. const start = Math.max( group.start, drawRange.start );
  15383. const end = Math.min( position.count, Math.min( ( group.start + group.count ), ( drawRange.start + drawRange.count ) ) );
  15384. for ( let j = start, jl = end; j < jl; j += 3 ) {
  15385. const a = j;
  15386. const b = j + 1;
  15387. const c = j + 2;
  15388. intersection = checkGeometryIntersection( this, groupMaterial, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c );
  15389. if ( intersection ) {
  15390. intersection.faceIndex = Math.floor( j / 3 ); // triangle number in non-indexed buffer semantics
  15391. intersection.face.materialIndex = group.materialIndex;
  15392. intersects.push( intersection );
  15393. }
  15394. }
  15395. }
  15396. } else {
  15397. const start = Math.max( 0, drawRange.start );
  15398. const end = Math.min( position.count, ( drawRange.start + drawRange.count ) );
  15399. for ( let i = start, il = end; i < il; i += 3 ) {
  15400. const a = i;
  15401. const b = i + 1;
  15402. const c = i + 2;
  15403. intersection = checkGeometryIntersection( this, material, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c );
  15404. if ( intersection ) {
  15405. intersection.faceIndex = Math.floor( i / 3 ); // triangle number in non-indexed buffer semantics
  15406. intersects.push( intersection );
  15407. }
  15408. }
  15409. }
  15410. }
  15411. }
  15412. }
  15413. function checkIntersection$1( object, material, raycaster, ray, pA, pB, pC, point ) {
  15414. let intersect;
  15415. if ( material.side === BackSide ) {
  15416. intersect = ray.intersectTriangle( pC, pB, pA, true, point );
  15417. } else {
  15418. intersect = ray.intersectTriangle( pA, pB, pC, ( material.side === FrontSide ), point );
  15419. }
  15420. if ( intersect === null ) return null;
  15421. _intersectionPointWorld.copy( point );
  15422. _intersectionPointWorld.applyMatrix4( object.matrixWorld );
  15423. const distance = raycaster.ray.origin.distanceTo( _intersectionPointWorld );
  15424. if ( distance < raycaster.near || distance > raycaster.far ) return null;
  15425. return {
  15426. distance: distance,
  15427. point: _intersectionPointWorld.clone(),
  15428. object: object
  15429. };
  15430. }
  15431. function checkGeometryIntersection( object, material, raycaster, ray, uv, uv1, normal, a, b, c ) {
  15432. object.getVertexPosition( a, _vA$1 );
  15433. object.getVertexPosition( b, _vB$1 );
  15434. object.getVertexPosition( c, _vC$1 );
  15435. const intersection = checkIntersection$1( object, material, raycaster, ray, _vA$1, _vB$1, _vC$1, _intersectionPoint );
  15436. if ( intersection ) {
  15437. const barycoord = new Vector3();
  15438. Triangle.getBarycoord( _intersectionPoint, _vA$1, _vB$1, _vC$1, barycoord );
  15439. if ( uv ) {
  15440. intersection.uv = Triangle.getInterpolatedAttribute( uv, a, b, c, barycoord, new Vector2() );
  15441. }
  15442. if ( uv1 ) {
  15443. intersection.uv1 = Triangle.getInterpolatedAttribute( uv1, a, b, c, barycoord, new Vector2() );
  15444. }
  15445. if ( normal ) {
  15446. intersection.normal = Triangle.getInterpolatedAttribute( normal, a, b, c, barycoord, new Vector3() );
  15447. if ( intersection.normal.dot( ray.direction ) > 0 ) {
  15448. intersection.normal.multiplyScalar( -1 );
  15449. }
  15450. }
  15451. const face = {
  15452. a: a,
  15453. b: b,
  15454. c: c,
  15455. normal: new Vector3(),
  15456. materialIndex: 0
  15457. };
  15458. Triangle.getNormal( _vA$1, _vB$1, _vC$1, face.normal );
  15459. intersection.face = face;
  15460. intersection.barycoord = barycoord;
  15461. }
  15462. return intersection;
  15463. }
  15464. /**
  15465. * A geometry class for a rectangular cuboid with a given width, height, and depth.
  15466. * On creation, the cuboid is centred on the origin, with each edge parallel to one
  15467. * of the axes.
  15468. *
  15469. * ```js
  15470. * const geometry = new THREE.BoxGeometry( 1, 1, 1 );
  15471. * const material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } );
  15472. * const cube = new THREE.Mesh( geometry, material );
  15473. * scene.add( cube );
  15474. * ```
  15475. *
  15476. * @augments BufferGeometry
  15477. * @demo scenes/geometry-browser.html#BoxGeometry
  15478. */
  15479. class BoxGeometry extends BufferGeometry {
  15480. /**
  15481. * Constructs a new box geometry.
  15482. *
  15483. * @param {number} [width=1] - The width. That is, the length of the edges parallel to the X axis.
  15484. * @param {number} [height=1] - The height. That is, the length of the edges parallel to the Y axis.
  15485. * @param {number} [depth=1] - The depth. That is, the length of the edges parallel to the Z axis.
  15486. * @param {number} [widthSegments=1] - Number of segmented rectangular faces along the width of the sides.
  15487. * @param {number} [heightSegments=1] - Number of segmented rectangular faces along the height of the sides.
  15488. * @param {number} [depthSegments=1] - Number of segmented rectangular faces along the depth of the sides.
  15489. */
  15490. constructor( width = 1, height = 1, depth = 1, widthSegments = 1, heightSegments = 1, depthSegments = 1 ) {
  15491. super();
  15492. this.type = 'BoxGeometry';
  15493. /**
  15494. * Holds the constructor parameters that have been
  15495. * used to generate the geometry. Any modification
  15496. * after instantiation does not change the geometry.
  15497. *
  15498. * @type {Object}
  15499. */
  15500. this.parameters = {
  15501. width: width,
  15502. height: height,
  15503. depth: depth,
  15504. widthSegments: widthSegments,
  15505. heightSegments: heightSegments,
  15506. depthSegments: depthSegments
  15507. };
  15508. const scope = this;
  15509. // segments
  15510. widthSegments = Math.floor( widthSegments );
  15511. heightSegments = Math.floor( heightSegments );
  15512. depthSegments = Math.floor( depthSegments );
  15513. // buffers
  15514. const indices = [];
  15515. const vertices = [];
  15516. const normals = [];
  15517. const uvs = [];
  15518. // helper variables
  15519. let numberOfVertices = 0;
  15520. let groupStart = 0;
  15521. // build each side of the box geometry
  15522. buildPlane( 'z', 'y', 'x', -1, -1, depth, height, width, depthSegments, heightSegments, 0 ); // px
  15523. buildPlane( 'z', 'y', 'x', 1, -1, depth, height, - width, depthSegments, heightSegments, 1 ); // nx
  15524. buildPlane( 'x', 'z', 'y', 1, 1, width, depth, height, widthSegments, depthSegments, 2 ); // py
  15525. buildPlane( 'x', 'z', 'y', 1, -1, width, depth, - height, widthSegments, depthSegments, 3 ); // ny
  15526. buildPlane( 'x', 'y', 'z', 1, -1, width, height, depth, widthSegments, heightSegments, 4 ); // pz
  15527. buildPlane( 'x', 'y', 'z', -1, -1, width, height, - depth, widthSegments, heightSegments, 5 ); // nz
  15528. // build geometry
  15529. this.setIndex( indices );
  15530. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  15531. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  15532. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  15533. function buildPlane( u, v, w, udir, vdir, width, height, depth, gridX, gridY, materialIndex ) {
  15534. const segmentWidth = width / gridX;
  15535. const segmentHeight = height / gridY;
  15536. const widthHalf = width / 2;
  15537. const heightHalf = height / 2;
  15538. const depthHalf = depth / 2;
  15539. const gridX1 = gridX + 1;
  15540. const gridY1 = gridY + 1;
  15541. let vertexCounter = 0;
  15542. let groupCount = 0;
  15543. const vector = new Vector3();
  15544. // generate vertices, normals and uvs
  15545. for ( let iy = 0; iy < gridY1; iy ++ ) {
  15546. const y = iy * segmentHeight - heightHalf;
  15547. for ( let ix = 0; ix < gridX1; ix ++ ) {
  15548. const x = ix * segmentWidth - widthHalf;
  15549. // set values to correct vector component
  15550. vector[ u ] = x * udir;
  15551. vector[ v ] = y * vdir;
  15552. vector[ w ] = depthHalf;
  15553. // now apply vector to vertex buffer
  15554. vertices.push( vector.x, vector.y, vector.z );
  15555. // set values to correct vector component
  15556. vector[ u ] = 0;
  15557. vector[ v ] = 0;
  15558. vector[ w ] = depth > 0 ? 1 : -1;
  15559. // now apply vector to normal buffer
  15560. normals.push( vector.x, vector.y, vector.z );
  15561. // uvs
  15562. uvs.push( ix / gridX );
  15563. uvs.push( 1 - ( iy / gridY ) );
  15564. // counters
  15565. vertexCounter += 1;
  15566. }
  15567. }
  15568. // indices
  15569. // 1. you need three indices to draw a single face
  15570. // 2. a single segment consists of two faces
  15571. // 3. so we need to generate six (2*3) indices per segment
  15572. for ( let iy = 0; iy < gridY; iy ++ ) {
  15573. for ( let ix = 0; ix < gridX; ix ++ ) {
  15574. const a = numberOfVertices + ix + gridX1 * iy;
  15575. const b = numberOfVertices + ix + gridX1 * ( iy + 1 );
  15576. const c = numberOfVertices + ( ix + 1 ) + gridX1 * ( iy + 1 );
  15577. const d = numberOfVertices + ( ix + 1 ) + gridX1 * iy;
  15578. // faces
  15579. indices.push( a, b, d );
  15580. indices.push( b, c, d );
  15581. // increase counter
  15582. groupCount += 6;
  15583. }
  15584. }
  15585. // add a group to the geometry. this will ensure multi material support
  15586. scope.addGroup( groupStart, groupCount, materialIndex );
  15587. // calculate new start value for groups
  15588. groupStart += groupCount;
  15589. // update total number of vertices
  15590. numberOfVertices += vertexCounter;
  15591. }
  15592. }
  15593. copy( source ) {
  15594. super.copy( source );
  15595. this.parameters = Object.assign( {}, source.parameters );
  15596. return this;
  15597. }
  15598. /**
  15599. * Factory method for creating an instance of this class from the given
  15600. * JSON object.
  15601. *
  15602. * @param {Object} data - A JSON object representing the serialized geometry.
  15603. * @return {BoxGeometry} A new instance.
  15604. */
  15605. static fromJSON( data ) {
  15606. return new BoxGeometry( data.width, data.height, data.depth, data.widthSegments, data.heightSegments, data.depthSegments );
  15607. }
  15608. }
  15609. /**
  15610. * Provides utility functions for managing uniforms.
  15611. *
  15612. * @module UniformsUtils
  15613. */
  15614. /**
  15615. * Clones the given uniform definitions by performing a deep-copy. That means
  15616. * if the value of a uniform refers to an object like a Vector3 or Texture,
  15617. * the cloned uniform will refer to a new object reference.
  15618. *
  15619. * @param {Object} src - An object representing uniform definitions.
  15620. * @return {Object} The cloned uniforms.
  15621. */
  15622. function cloneUniforms( src ) {
  15623. const dst = {};
  15624. for ( const u in src ) {
  15625. dst[ u ] = {};
  15626. for ( const p in src[ u ] ) {
  15627. const property = src[ u ][ p ];
  15628. if ( property && ( property.isColor ||
  15629. property.isMatrix3 || property.isMatrix4 ||
  15630. property.isVector2 || property.isVector3 || property.isVector4 ||
  15631. property.isTexture || property.isQuaternion ) ) {
  15632. if ( property.isRenderTargetTexture ) {
  15633. warn( 'UniformsUtils: Textures of render targets cannot be cloned via cloneUniforms() or mergeUniforms().' );
  15634. dst[ u ][ p ] = null;
  15635. } else {
  15636. dst[ u ][ p ] = property.clone();
  15637. }
  15638. } else if ( Array.isArray( property ) ) {
  15639. dst[ u ][ p ] = property.slice();
  15640. } else {
  15641. dst[ u ][ p ] = property;
  15642. }
  15643. }
  15644. }
  15645. return dst;
  15646. }
  15647. /**
  15648. * Merges the given uniform definitions into a single object. Since the
  15649. * method internally uses cloneUniforms(), it performs a deep-copy when
  15650. * producing the merged uniform definitions.
  15651. *
  15652. * @param {Array} uniforms - An array of objects containing uniform definitions.
  15653. * @return {Object} The merged uniforms.
  15654. */
  15655. function mergeUniforms( uniforms ) {
  15656. const merged = {};
  15657. for ( let u = 0; u < uniforms.length; u ++ ) {
  15658. const tmp = cloneUniforms( uniforms[ u ] );
  15659. for ( const p in tmp ) {
  15660. merged[ p ] = tmp[ p ];
  15661. }
  15662. }
  15663. return merged;
  15664. }
  15665. function cloneUniformsGroups( src ) {
  15666. const dst = [];
  15667. for ( let u = 0; u < src.length; u ++ ) {
  15668. dst.push( src[ u ].clone() );
  15669. }
  15670. return dst;
  15671. }
  15672. function getUnlitUniformColorSpace( renderer ) {
  15673. const currentRenderTarget = renderer.getRenderTarget();
  15674. if ( currentRenderTarget === null ) {
  15675. // https://github.com/mrdoob/three.js/pull/23937#issuecomment-1111067398
  15676. return renderer.outputColorSpace;
  15677. }
  15678. // https://github.com/mrdoob/three.js/issues/27868
  15679. if ( currentRenderTarget.isXRRenderTarget === true ) {
  15680. return currentRenderTarget.texture.colorSpace;
  15681. }
  15682. return ColorManagement.workingColorSpace;
  15683. }
  15684. // Legacy
  15685. const UniformsUtils = { clone: cloneUniforms, merge: mergeUniforms };
  15686. var default_vertex = "void main() {\n\tgl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n}";
  15687. var default_fragment = "void main() {\n\tgl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );\n}";
  15688. /**
  15689. * A material rendered with custom shaders. A shader is a small program written in GLSL.
  15690. * that runs on the GPU. You may want to use a custom shader if you need to implement an
  15691. * effect not included with any of the built-in materials.
  15692. *
  15693. * There are the following notes to bear in mind when using a `ShaderMaterial`:
  15694. *
  15695. * - `ShaderMaterial` can only be used with {@link WebGLRenderer}.
  15696. * - Built in attributes and uniforms are passed to the shaders along with your code. If
  15697. * you don't want that, use {@link RawShaderMaterial} instead.
  15698. * - You can use the directive `#pragma unroll_loop_start` and `#pragma unroll_loop_end`
  15699. * in order to unroll a `for` loop in GLSL by the shader preprocessor. The directive has
  15700. * to be placed right above the loop. The loop formatting has to correspond to a defined standard.
  15701. * - The loop has to be [normalized](https://en.wikipedia.org/wiki/Normalized_loop).
  15702. * - The loop variable has to be *i*.
  15703. * - The value `UNROLLED_LOOP_INDEX` will be replaced with the explicitly
  15704. * value of *i* for the given iteration and can be used in preprocessor
  15705. * statements.
  15706. *
  15707. * ```js
  15708. * const material = new THREE.ShaderMaterial( {
  15709. * uniforms: {
  15710. * time: { value: 1.0 },
  15711. * resolution: { value: new THREE.Vector2() }
  15712. * },
  15713. * vertexShader: document.getElementById( 'vertexShader' ).textContent,
  15714. * fragmentShader: document.getElementById( 'fragmentShader' ).textContent
  15715. * } );
  15716. * ```
  15717. *
  15718. * @augments Material
  15719. */
  15720. class ShaderMaterial extends Material {
  15721. /**
  15722. * Constructs a new shader material.
  15723. *
  15724. * @param {Object} [parameters] - An object with one or more properties
  15725. * defining the material's appearance. Any property of the material
  15726. * (including any property from inherited materials) can be passed
  15727. * in here. Color values can be passed any type of value accepted
  15728. * by {@link Color#set}.
  15729. */
  15730. constructor( parameters ) {
  15731. super();
  15732. /**
  15733. * This flag can be used for type testing.
  15734. *
  15735. * @type {boolean}
  15736. * @readonly
  15737. * @default true
  15738. */
  15739. this.isShaderMaterial = true;
  15740. this.type = 'ShaderMaterial';
  15741. /**
  15742. * Defines custom constants using `#define` directives within the GLSL code
  15743. * for both the vertex shader and the fragment shader; each key/value pair
  15744. * yields another directive.
  15745. * ```js
  15746. * defines: {
  15747. * FOO: 15,
  15748. * BAR: true
  15749. * }
  15750. * ```
  15751. * Yields the lines:
  15752. * ```
  15753. * #define FOO 15
  15754. * #define BAR true
  15755. * ```
  15756. *
  15757. * @type {Object}
  15758. */
  15759. this.defines = {};
  15760. /**
  15761. * An object of the form:
  15762. * ```js
  15763. * {
  15764. * "uniform1": { value: 1.0 },
  15765. * "uniform2": { value: 2 }
  15766. * }
  15767. * ```
  15768. * specifying the uniforms to be passed to the shader code; keys are uniform
  15769. * names, values are definitions of the form
  15770. * ```
  15771. * {
  15772. * value: 1.0
  15773. * }
  15774. * ```
  15775. * where `value` is the value of the uniform. Names must match the name of
  15776. * the uniform, as defined in the GLSL code. Note that uniforms are refreshed
  15777. * on every frame, so updating the value of the uniform will immediately
  15778. * update the value available to the GLSL code.
  15779. *
  15780. * @type {Object}
  15781. */
  15782. this.uniforms = {};
  15783. /**
  15784. * An array holding uniforms groups for configuring UBOs.
  15785. *
  15786. * @type {Array<UniformsGroup>}
  15787. */
  15788. this.uniformsGroups = [];
  15789. /**
  15790. * Vertex shader GLSL code. This is the actual code for the shader.
  15791. *
  15792. * @type {string}
  15793. */
  15794. this.vertexShader = default_vertex;
  15795. /**
  15796. * Fragment shader GLSL code. This is the actual code for the shader.
  15797. *
  15798. * @type {string}
  15799. */
  15800. this.fragmentShader = default_fragment;
  15801. /**
  15802. * Controls line thickness or lines.
  15803. *
  15804. * WebGL and WebGPU ignore this setting and always render line primitives with a
  15805. * width of one pixel.
  15806. *
  15807. * @type {number}
  15808. * @default 1
  15809. */
  15810. this.linewidth = 1;
  15811. /**
  15812. * Renders the geometry as a wireframe.
  15813. *
  15814. * @type {boolean}
  15815. * @default false
  15816. */
  15817. this.wireframe = false;
  15818. /**
  15819. * Controls the thickness of the wireframe.
  15820. *
  15821. * WebGL and WebGPU ignore this property and always render
  15822. * 1 pixel wide lines.
  15823. *
  15824. * @type {number}
  15825. * @default 1
  15826. */
  15827. this.wireframeLinewidth = 1;
  15828. /**
  15829. * Defines whether the material color is affected by global fog settings; `true`
  15830. * to pass fog uniforms to the shader.
  15831. *
  15832. * Setting this property to `true` requires the definition of fog uniforms. It is
  15833. * recommended to use `UniformsUtils.merge()` to combine the custom shader uniforms
  15834. * with predefined fog uniforms.
  15835. *
  15836. * ```js
  15837. * const material = new ShaderMaterial( {
  15838. * uniforms: UniformsUtils.merge( [ UniformsLib[ 'fog' ], shaderUniforms ] );
  15839. * vertexShader: vertexShader,
  15840. * fragmentShader: fragmentShader,
  15841. * fog: true
  15842. * } );
  15843. * ```
  15844. *
  15845. * @type {boolean}
  15846. * @default false
  15847. */
  15848. this.fog = false;
  15849. /**
  15850. * Defines whether this material uses lighting; `true` to pass uniform data
  15851. * related to lighting to this shader.
  15852. *
  15853. * @type {boolean}
  15854. * @default false
  15855. */
  15856. this.lights = false;
  15857. /**
  15858. * Defines whether this material supports clipping; `true` to let the renderer
  15859. * pass the clippingPlanes uniform.
  15860. *
  15861. * @type {boolean}
  15862. * @default false
  15863. */
  15864. this.clipping = false;
  15865. /**
  15866. * Overwritten and set to `true` by default.
  15867. *
  15868. * @type {boolean}
  15869. * @default true
  15870. */
  15871. this.forceSinglePass = true;
  15872. /**
  15873. * This object allows to enable certain WebGL 2 extensions.
  15874. *
  15875. * - clipCullDistance: set to `true` to use vertex shader clipping
  15876. * - multiDraw: set to `true` to use vertex shader multi_draw / enable gl_DrawID
  15877. *
  15878. * @type {{clipCullDistance:false,multiDraw:false}}
  15879. */
  15880. this.extensions = {
  15881. clipCullDistance: false, // set to use vertex shader clipping
  15882. multiDraw: false // set to use vertex shader multi_draw / enable gl_DrawID
  15883. };
  15884. /**
  15885. * When the rendered geometry doesn't include these attributes but the
  15886. * material does, these default values will be passed to the shaders. This
  15887. * avoids errors when buffer data is missing.
  15888. *
  15889. * - color: [ 1, 1, 1 ]
  15890. * - uv: [ 0, 0 ]
  15891. * - uv1: [ 0, 0 ]
  15892. *
  15893. * @type {Object}
  15894. */
  15895. this.defaultAttributeValues = {
  15896. 'color': [ 1, 1, 1 ],
  15897. 'uv': [ 0, 0 ],
  15898. 'uv1': [ 0, 0 ]
  15899. };
  15900. /**
  15901. * If set, this calls [gl.bindAttribLocation](https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/bindAttribLocation)
  15902. * to bind a generic vertex index to an attribute variable.
  15903. *
  15904. * @type {string|undefined}
  15905. * @default undefined
  15906. */
  15907. this.index0AttributeName = undefined;
  15908. /**
  15909. * Can be used to force a uniform update while changing uniforms in
  15910. * {@link Object3D#onBeforeRender}.
  15911. *
  15912. * @type {boolean}
  15913. * @default false
  15914. */
  15915. this.uniformsNeedUpdate = false;
  15916. /**
  15917. * Defines the GLSL version of custom shader code.
  15918. *
  15919. * @type {?(GLSL1|GLSL3)}
  15920. * @default null
  15921. */
  15922. this.glslVersion = null;
  15923. if ( parameters !== undefined ) {
  15924. this.setValues( parameters );
  15925. }
  15926. }
  15927. copy( source ) {
  15928. super.copy( source );
  15929. this.fragmentShader = source.fragmentShader;
  15930. this.vertexShader = source.vertexShader;
  15931. this.uniforms = cloneUniforms( source.uniforms );
  15932. this.uniformsGroups = cloneUniformsGroups( source.uniformsGroups );
  15933. this.defines = Object.assign( {}, source.defines );
  15934. this.wireframe = source.wireframe;
  15935. this.wireframeLinewidth = source.wireframeLinewidth;
  15936. this.fog = source.fog;
  15937. this.lights = source.lights;
  15938. this.clipping = source.clipping;
  15939. this.extensions = Object.assign( {}, source.extensions );
  15940. this.glslVersion = source.glslVersion;
  15941. this.defaultAttributeValues = Object.assign( {}, source.defaultAttributeValues );
  15942. this.index0AttributeName = source.index0AttributeName;
  15943. this.uniformsNeedUpdate = source.uniformsNeedUpdate;
  15944. return this;
  15945. }
  15946. toJSON( meta ) {
  15947. const data = super.toJSON( meta );
  15948. data.glslVersion = this.glslVersion;
  15949. data.uniforms = {};
  15950. for ( const name in this.uniforms ) {
  15951. const uniform = this.uniforms[ name ];
  15952. const value = uniform.value;
  15953. if ( value && value.isTexture ) {
  15954. data.uniforms[ name ] = {
  15955. type: 't',
  15956. value: value.toJSON( meta ).uuid
  15957. };
  15958. } else if ( value && value.isColor ) {
  15959. data.uniforms[ name ] = {
  15960. type: 'c',
  15961. value: value.getHex()
  15962. };
  15963. } else if ( value && value.isVector2 ) {
  15964. data.uniforms[ name ] = {
  15965. type: 'v2',
  15966. value: value.toArray()
  15967. };
  15968. } else if ( value && value.isVector3 ) {
  15969. data.uniforms[ name ] = {
  15970. type: 'v3',
  15971. value: value.toArray()
  15972. };
  15973. } else if ( value && value.isVector4 ) {
  15974. data.uniforms[ name ] = {
  15975. type: 'v4',
  15976. value: value.toArray()
  15977. };
  15978. } else if ( value && value.isMatrix3 ) {
  15979. data.uniforms[ name ] = {
  15980. type: 'm3',
  15981. value: value.toArray()
  15982. };
  15983. } else if ( value && value.isMatrix4 ) {
  15984. data.uniforms[ name ] = {
  15985. type: 'm4',
  15986. value: value.toArray()
  15987. };
  15988. } else {
  15989. data.uniforms[ name ] = {
  15990. value: value
  15991. };
  15992. // note: the array variants v2v, v3v, v4v, m4v and tv are not supported so far
  15993. }
  15994. }
  15995. if ( Object.keys( this.defines ).length > 0 ) data.defines = this.defines;
  15996. data.vertexShader = this.vertexShader;
  15997. data.fragmentShader = this.fragmentShader;
  15998. data.lights = this.lights;
  15999. data.clipping = this.clipping;
  16000. const extensions = {};
  16001. for ( const key in this.extensions ) {
  16002. if ( this.extensions[ key ] === true ) extensions[ key ] = true;
  16003. }
  16004. if ( Object.keys( extensions ).length > 0 ) data.extensions = extensions;
  16005. return data;
  16006. }
  16007. }
  16008. /**
  16009. * Abstract base class for cameras. This class should always be inherited
  16010. * when you build a new camera.
  16011. *
  16012. * @abstract
  16013. * @augments Object3D
  16014. */
  16015. class Camera extends Object3D {
  16016. /**
  16017. * Constructs a new camera.
  16018. */
  16019. constructor() {
  16020. super();
  16021. /**
  16022. * This flag can be used for type testing.
  16023. *
  16024. * @type {boolean}
  16025. * @readonly
  16026. * @default true
  16027. */
  16028. this.isCamera = true;
  16029. this.type = 'Camera';
  16030. /**
  16031. * The inverse of the camera's world matrix.
  16032. *
  16033. * @type {Matrix4}
  16034. */
  16035. this.matrixWorldInverse = new Matrix4();
  16036. /**
  16037. * The camera's projection matrix.
  16038. *
  16039. * @type {Matrix4}
  16040. */
  16041. this.projectionMatrix = new Matrix4();
  16042. /**
  16043. * The inverse of the camera's projection matrix.
  16044. *
  16045. * @type {Matrix4}
  16046. */
  16047. this.projectionMatrixInverse = new Matrix4();
  16048. /**
  16049. * The coordinate system in which the camera is used.
  16050. *
  16051. * @type {(WebGLCoordinateSystem|WebGPUCoordinateSystem)}
  16052. */
  16053. this.coordinateSystem = WebGLCoordinateSystem;
  16054. this._reversedDepth = false;
  16055. }
  16056. /**
  16057. * The flag that indicates whether the camera uses a reversed depth buffer.
  16058. *
  16059. * @type {boolean}
  16060. * @default false
  16061. */
  16062. get reversedDepth() {
  16063. return this._reversedDepth;
  16064. }
  16065. copy( source, recursive ) {
  16066. super.copy( source, recursive );
  16067. this.matrixWorldInverse.copy( source.matrixWorldInverse );
  16068. this.projectionMatrix.copy( source.projectionMatrix );
  16069. this.projectionMatrixInverse.copy( source.projectionMatrixInverse );
  16070. this.coordinateSystem = source.coordinateSystem;
  16071. return this;
  16072. }
  16073. /**
  16074. * Returns a vector representing the ("look") direction of the 3D object in world space.
  16075. *
  16076. * This method is overwritten since cameras have a different forward vector compared to other
  16077. * 3D objects. A camera looks down its local, negative z-axis by default.
  16078. *
  16079. * @param {Vector3} target - The target vector the result is stored to.
  16080. * @return {Vector3} The 3D object's direction in world space.
  16081. */
  16082. getWorldDirection( target ) {
  16083. return super.getWorldDirection( target ).negate();
  16084. }
  16085. updateMatrixWorld( force ) {
  16086. super.updateMatrixWorld( force );
  16087. this.matrixWorldInverse.copy( this.matrixWorld ).invert();
  16088. }
  16089. updateWorldMatrix( updateParents, updateChildren ) {
  16090. super.updateWorldMatrix( updateParents, updateChildren );
  16091. this.matrixWorldInverse.copy( this.matrixWorld ).invert();
  16092. }
  16093. clone() {
  16094. return new this.constructor().copy( this );
  16095. }
  16096. }
  16097. const _v3$1 = /*@__PURE__*/ new Vector3();
  16098. const _minTarget = /*@__PURE__*/ new Vector2();
  16099. const _maxTarget = /*@__PURE__*/ new Vector2();
  16100. /**
  16101. * Camera that uses [perspective projection](https://en.wikipedia.org/wiki/Perspective_(graphical)).
  16102. *
  16103. * This projection mode is designed to mimic the way the human eye sees. It
  16104. * is the most common projection mode used for rendering a 3D scene.
  16105. *
  16106. * ```js
  16107. * const camera = new THREE.PerspectiveCamera( 45, width / height, 1, 1000 );
  16108. * scene.add( camera );
  16109. * ```
  16110. *
  16111. * @augments Camera
  16112. */
  16113. class PerspectiveCamera extends Camera {
  16114. /**
  16115. * Constructs a new perspective camera.
  16116. *
  16117. * @param {number} [fov=50] - The vertical field of view.
  16118. * @param {number} [aspect=1] - The aspect ratio.
  16119. * @param {number} [near=0.1] - The camera's near plane.
  16120. * @param {number} [far=2000] - The camera's far plane.
  16121. */
  16122. constructor( fov = 50, aspect = 1, near = 0.1, far = 2000 ) {
  16123. super();
  16124. /**
  16125. * This flag can be used for type testing.
  16126. *
  16127. * @type {boolean}
  16128. * @readonly
  16129. * @default true
  16130. */
  16131. this.isPerspectiveCamera = true;
  16132. this.type = 'PerspectiveCamera';
  16133. /**
  16134. * The vertical field of view, from bottom to top of view,
  16135. * in degrees.
  16136. *
  16137. * @type {number}
  16138. * @default 50
  16139. */
  16140. this.fov = fov;
  16141. /**
  16142. * The zoom factor of the camera.
  16143. *
  16144. * @type {number}
  16145. * @default 1
  16146. */
  16147. this.zoom = 1;
  16148. /**
  16149. * The camera's near plane. The valid range is greater than `0`
  16150. * and less than the current value of {@link PerspectiveCamera#far}.
  16151. *
  16152. * Note that, unlike for the {@link OrthographicCamera}, `0` is <em>not</em> a
  16153. * valid value for a perspective camera's near plane.
  16154. *
  16155. * @type {number}
  16156. * @default 0.1
  16157. */
  16158. this.near = near;
  16159. /**
  16160. * The camera's far plane. Must be greater than the
  16161. * current value of {@link PerspectiveCamera#near}.
  16162. *
  16163. * @type {number}
  16164. * @default 2000
  16165. */
  16166. this.far = far;
  16167. /**
  16168. * Object distance used for stereoscopy and depth-of-field effects. This
  16169. * parameter does not influence the projection matrix unless a
  16170. * {@link StereoCamera} is being used.
  16171. *
  16172. * @type {number}
  16173. * @default 10
  16174. */
  16175. this.focus = 10;
  16176. /**
  16177. * The aspect ratio, usually the canvas width / canvas height.
  16178. *
  16179. * @type {number}
  16180. * @default 1
  16181. */
  16182. this.aspect = aspect;
  16183. /**
  16184. * Represents the frustum window specification. This property should not be edited
  16185. * directly but via {@link PerspectiveCamera#setViewOffset} and {@link PerspectiveCamera#clearViewOffset}.
  16186. *
  16187. * @type {?Object}
  16188. * @default null
  16189. */
  16190. this.view = null;
  16191. /**
  16192. * Film size used for the larger axis. Default is `35` (millimeters). This
  16193. * parameter does not influence the projection matrix unless {@link PerspectiveCamera#filmOffset}
  16194. * is set to a nonzero value.
  16195. *
  16196. * @type {number}
  16197. * @default 35
  16198. */
  16199. this.filmGauge = 35;
  16200. /**
  16201. * Horizontal off-center offset in the same unit as {@link PerspectiveCamera#filmGauge}.
  16202. *
  16203. * @type {number}
  16204. * @default 0
  16205. */
  16206. this.filmOffset = 0;
  16207. this.updateProjectionMatrix();
  16208. }
  16209. copy( source, recursive ) {
  16210. super.copy( source, recursive );
  16211. this.fov = source.fov;
  16212. this.zoom = source.zoom;
  16213. this.near = source.near;
  16214. this.far = source.far;
  16215. this.focus = source.focus;
  16216. this.aspect = source.aspect;
  16217. this.view = source.view === null ? null : Object.assign( {}, source.view );
  16218. this.filmGauge = source.filmGauge;
  16219. this.filmOffset = source.filmOffset;
  16220. return this;
  16221. }
  16222. /**
  16223. * Sets the FOV by focal length in respect to the current {@link PerspectiveCamera#filmGauge}.
  16224. *
  16225. * The default film gauge is 35, so that the focal length can be specified for
  16226. * a 35mm (full frame) camera.
  16227. *
  16228. * @param {number} focalLength - Values for focal length and film gauge must have the same unit.
  16229. */
  16230. setFocalLength( focalLength ) {
  16231. /** see {@link http://www.bobatkins.com/photography/technical/field_of_view.html} */
  16232. const vExtentSlope = 0.5 * this.getFilmHeight() / focalLength;
  16233. this.fov = RAD2DEG * 2 * Math.atan( vExtentSlope );
  16234. this.updateProjectionMatrix();
  16235. }
  16236. /**
  16237. * Returns the focal length from the current {@link PerspectiveCamera#fov} and
  16238. * {@link PerspectiveCamera#filmGauge}.
  16239. *
  16240. * @return {number} The computed focal length.
  16241. */
  16242. getFocalLength() {
  16243. const vExtentSlope = Math.tan( DEG2RAD * 0.5 * this.fov );
  16244. return 0.5 * this.getFilmHeight() / vExtentSlope;
  16245. }
  16246. /**
  16247. * Returns the current vertical field of view angle in degrees considering {@link PerspectiveCamera#zoom}.
  16248. *
  16249. * @return {number} The effective FOV.
  16250. */
  16251. getEffectiveFOV() {
  16252. return RAD2DEG * 2 * Math.atan(
  16253. Math.tan( DEG2RAD * 0.5 * this.fov ) / this.zoom );
  16254. }
  16255. /**
  16256. * Returns the width of the image on the film. If {@link PerspectiveCamera#aspect} is greater than or
  16257. * equal to one (landscape format), the result equals {@link PerspectiveCamera#filmGauge}.
  16258. *
  16259. * @return {number} The film width.
  16260. */
  16261. getFilmWidth() {
  16262. // film not completely covered in portrait format (aspect < 1)
  16263. return this.filmGauge * Math.min( this.aspect, 1 );
  16264. }
  16265. /**
  16266. * Returns the height of the image on the film. If {@link PerspectiveCamera#aspect} is greater than or
  16267. * equal to one (landscape format), the result equals {@link PerspectiveCamera#filmGauge}.
  16268. *
  16269. * @return {number} The film width.
  16270. */
  16271. getFilmHeight() {
  16272. // film not completely covered in landscape format (aspect > 1)
  16273. return this.filmGauge / Math.max( this.aspect, 1 );
  16274. }
  16275. /**
  16276. * Computes the 2D bounds of the camera's viewable rectangle at a given distance along the viewing direction.
  16277. * Sets `minTarget` and `maxTarget` to the coordinates of the lower-left and upper-right corners of the view rectangle.
  16278. *
  16279. * @param {number} distance - The viewing distance.
  16280. * @param {Vector2} minTarget - The lower-left corner of the view rectangle is written into this vector.
  16281. * @param {Vector2} maxTarget - The upper-right corner of the view rectangle is written into this vector.
  16282. */
  16283. getViewBounds( distance, minTarget, maxTarget ) {
  16284. _v3$1.set( -1, -1, 0.5 ).applyMatrix4( this.projectionMatrixInverse );
  16285. minTarget.set( _v3$1.x, _v3$1.y ).multiplyScalar( - distance / _v3$1.z );
  16286. _v3$1.set( 1, 1, 0.5 ).applyMatrix4( this.projectionMatrixInverse );
  16287. maxTarget.set( _v3$1.x, _v3$1.y ).multiplyScalar( - distance / _v3$1.z );
  16288. }
  16289. /**
  16290. * Computes the width and height of the camera's viewable rectangle at a given distance along the viewing direction.
  16291. *
  16292. * @param {number} distance - The viewing distance.
  16293. * @param {Vector2} target - The target vector that is used to store result where x is width and y is height.
  16294. * @returns {Vector2} The view size.
  16295. */
  16296. getViewSize( distance, target ) {
  16297. this.getViewBounds( distance, _minTarget, _maxTarget );
  16298. return target.subVectors( _maxTarget, _minTarget );
  16299. }
  16300. /**
  16301. * Sets an offset in a larger frustum. This is useful for multi-window or
  16302. * multi-monitor/multi-machine setups.
  16303. *
  16304. * For example, if you have 3x2 monitors and each monitor is 1920x1080 and
  16305. * the monitors are in grid like this
  16306. *```
  16307. * +---+---+---+
  16308. * | A | B | C |
  16309. * +---+---+---+
  16310. * | D | E | F |
  16311. * +---+---+---+
  16312. *```
  16313. * then for each monitor you would call it like this:
  16314. *```js
  16315. * const w = 1920;
  16316. * const h = 1080;
  16317. * const fullWidth = w * 3;
  16318. * const fullHeight = h * 2;
  16319. *
  16320. * // --A--
  16321. * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 0, w, h );
  16322. * // --B--
  16323. * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 0, w, h );
  16324. * // --C--
  16325. * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 0, w, h );
  16326. * // --D--
  16327. * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 1, w, h );
  16328. * // --E--
  16329. * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 1, w, h );
  16330. * // --F--
  16331. * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 1, w, h );
  16332. * ```
  16333. *
  16334. * Note there is no reason monitors have to be the same size or in a grid.
  16335. *
  16336. * @param {number} fullWidth - The full width of multiview setup.
  16337. * @param {number} fullHeight - The full height of multiview setup.
  16338. * @param {number} x - The horizontal offset of the subcamera.
  16339. * @param {number} y - The vertical offset of the subcamera.
  16340. * @param {number} width - The width of subcamera.
  16341. * @param {number} height - The height of subcamera.
  16342. */
  16343. setViewOffset( fullWidth, fullHeight, x, y, width, height ) {
  16344. this.aspect = fullWidth / fullHeight;
  16345. if ( this.view === null ) {
  16346. this.view = {
  16347. enabled: true,
  16348. fullWidth: 1,
  16349. fullHeight: 1,
  16350. offsetX: 0,
  16351. offsetY: 0,
  16352. width: 1,
  16353. height: 1
  16354. };
  16355. }
  16356. this.view.enabled = true;
  16357. this.view.fullWidth = fullWidth;
  16358. this.view.fullHeight = fullHeight;
  16359. this.view.offsetX = x;
  16360. this.view.offsetY = y;
  16361. this.view.width = width;
  16362. this.view.height = height;
  16363. this.updateProjectionMatrix();
  16364. }
  16365. /**
  16366. * Removes the view offset from the projection matrix.
  16367. */
  16368. clearViewOffset() {
  16369. if ( this.view !== null ) {
  16370. this.view.enabled = false;
  16371. }
  16372. this.updateProjectionMatrix();
  16373. }
  16374. /**
  16375. * Updates the camera's projection matrix. Must be called after any change of
  16376. * camera properties.
  16377. */
  16378. updateProjectionMatrix() {
  16379. const near = this.near;
  16380. let top = near * Math.tan( DEG2RAD * 0.5 * this.fov ) / this.zoom;
  16381. let height = 2 * top;
  16382. let width = this.aspect * height;
  16383. let left = -0.5 * width;
  16384. const view = this.view;
  16385. if ( this.view !== null && this.view.enabled ) {
  16386. const fullWidth = view.fullWidth,
  16387. fullHeight = view.fullHeight;
  16388. left += view.offsetX * width / fullWidth;
  16389. top -= view.offsetY * height / fullHeight;
  16390. width *= view.width / fullWidth;
  16391. height *= view.height / fullHeight;
  16392. }
  16393. const skew = this.filmOffset;
  16394. if ( skew !== 0 ) left += near * skew / this.getFilmWidth();
  16395. this.projectionMatrix.makePerspective( left, left + width, top, top - height, near, this.far, this.coordinateSystem, this.reversedDepth );
  16396. this.projectionMatrixInverse.copy( this.projectionMatrix ).invert();
  16397. }
  16398. toJSON( meta ) {
  16399. const data = super.toJSON( meta );
  16400. data.object.fov = this.fov;
  16401. data.object.zoom = this.zoom;
  16402. data.object.near = this.near;
  16403. data.object.far = this.far;
  16404. data.object.focus = this.focus;
  16405. data.object.aspect = this.aspect;
  16406. if ( this.view !== null ) data.object.view = Object.assign( {}, this.view );
  16407. data.object.filmGauge = this.filmGauge;
  16408. data.object.filmOffset = this.filmOffset;
  16409. return data;
  16410. }
  16411. }
  16412. const fov = -90; // negative fov is not an error
  16413. const aspect = 1;
  16414. /**
  16415. * A special type of camera that is positioned in 3D space to render its surroundings into a
  16416. * cube render target. The render target can then be used as an environment map for rendering
  16417. * realtime reflections in your scene.
  16418. *
  16419. * ```js
  16420. * // Create cube render target
  16421. * const cubeRenderTarget = new THREE.WebGLCubeRenderTarget( 256, { generateMipmaps: true, minFilter: THREE.LinearMipmapLinearFilter } );
  16422. *
  16423. * // Create cube camera
  16424. * const cubeCamera = new THREE.CubeCamera( 1, 100000, cubeRenderTarget );
  16425. * scene.add( cubeCamera );
  16426. *
  16427. * // Create car
  16428. * const chromeMaterial = new THREE.MeshLambertMaterial( { color: 0xffffff, envMap: cubeRenderTarget.texture } );
  16429. * const car = new THREE.Mesh( carGeometry, chromeMaterial );
  16430. * scene.add( car );
  16431. *
  16432. * // Update the render target cube
  16433. * car.visible = false;
  16434. * cubeCamera.position.copy( car.position );
  16435. * cubeCamera.update( renderer, scene );
  16436. *
  16437. * // Render the scene
  16438. * car.visible = true;
  16439. * renderer.render( scene, camera );
  16440. * ```
  16441. *
  16442. * @augments Object3D
  16443. */
  16444. class CubeCamera extends Object3D {
  16445. /**
  16446. * Constructs a new cube camera.
  16447. *
  16448. * @param {number} near - The camera's near plane.
  16449. * @param {number} far - The camera's far plane.
  16450. * @param {WebGLCubeRenderTarget} renderTarget - The cube render target.
  16451. */
  16452. constructor( near, far, renderTarget ) {
  16453. super();
  16454. this.type = 'CubeCamera';
  16455. /**
  16456. * A reference to the cube render target.
  16457. *
  16458. * @type {WebGLCubeRenderTarget}
  16459. */
  16460. this.renderTarget = renderTarget;
  16461. /**
  16462. * The current active coordinate system.
  16463. *
  16464. * @type {?(WebGLCoordinateSystem|WebGPUCoordinateSystem)}
  16465. * @default null
  16466. */
  16467. this.coordinateSystem = null;
  16468. /**
  16469. * The current active mipmap level
  16470. *
  16471. * @type {number}
  16472. * @default 0
  16473. */
  16474. this.activeMipmapLevel = 0;
  16475. const cameraPX = new PerspectiveCamera( fov, aspect, near, far );
  16476. cameraPX.layers = this.layers;
  16477. this.add( cameraPX );
  16478. const cameraNX = new PerspectiveCamera( fov, aspect, near, far );
  16479. cameraNX.layers = this.layers;
  16480. this.add( cameraNX );
  16481. const cameraPY = new PerspectiveCamera( fov, aspect, near, far );
  16482. cameraPY.layers = this.layers;
  16483. this.add( cameraPY );
  16484. const cameraNY = new PerspectiveCamera( fov, aspect, near, far );
  16485. cameraNY.layers = this.layers;
  16486. this.add( cameraNY );
  16487. const cameraPZ = new PerspectiveCamera( fov, aspect, near, far );
  16488. cameraPZ.layers = this.layers;
  16489. this.add( cameraPZ );
  16490. const cameraNZ = new PerspectiveCamera( fov, aspect, near, far );
  16491. cameraNZ.layers = this.layers;
  16492. this.add( cameraNZ );
  16493. }
  16494. /**
  16495. * Must be called when the coordinate system of the cube camera is changed.
  16496. */
  16497. updateCoordinateSystem() {
  16498. const coordinateSystem = this.coordinateSystem;
  16499. const cameras = this.children.concat();
  16500. const [ cameraPX, cameraNX, cameraPY, cameraNY, cameraPZ, cameraNZ ] = cameras;
  16501. for ( const camera of cameras ) this.remove( camera );
  16502. if ( coordinateSystem === WebGLCoordinateSystem ) {
  16503. cameraPX.up.set( 0, 1, 0 );
  16504. cameraPX.lookAt( 1, 0, 0 );
  16505. cameraNX.up.set( 0, 1, 0 );
  16506. cameraNX.lookAt( -1, 0, 0 );
  16507. cameraPY.up.set( 0, 0, -1 );
  16508. cameraPY.lookAt( 0, 1, 0 );
  16509. cameraNY.up.set( 0, 0, 1 );
  16510. cameraNY.lookAt( 0, -1, 0 );
  16511. cameraPZ.up.set( 0, 1, 0 );
  16512. cameraPZ.lookAt( 0, 0, 1 );
  16513. cameraNZ.up.set( 0, 1, 0 );
  16514. cameraNZ.lookAt( 0, 0, -1 );
  16515. } else if ( coordinateSystem === WebGPUCoordinateSystem ) {
  16516. cameraPX.up.set( 0, -1, 0 );
  16517. cameraPX.lookAt( -1, 0, 0 );
  16518. cameraNX.up.set( 0, -1, 0 );
  16519. cameraNX.lookAt( 1, 0, 0 );
  16520. cameraPY.up.set( 0, 0, 1 );
  16521. cameraPY.lookAt( 0, 1, 0 );
  16522. cameraNY.up.set( 0, 0, -1 );
  16523. cameraNY.lookAt( 0, -1, 0 );
  16524. cameraPZ.up.set( 0, -1, 0 );
  16525. cameraPZ.lookAt( 0, 0, 1 );
  16526. cameraNZ.up.set( 0, -1, 0 );
  16527. cameraNZ.lookAt( 0, 0, -1 );
  16528. } else {
  16529. throw new Error( 'THREE.CubeCamera.updateCoordinateSystem(): Invalid coordinate system: ' + coordinateSystem );
  16530. }
  16531. for ( const camera of cameras ) {
  16532. this.add( camera );
  16533. camera.updateMatrixWorld();
  16534. }
  16535. }
  16536. /**
  16537. * Calling this method will render the given scene with the given renderer
  16538. * into the cube render target of the camera.
  16539. *
  16540. * @param {(Renderer|WebGLRenderer)} renderer - The renderer.
  16541. * @param {Scene} scene - The scene to render.
  16542. */
  16543. update( renderer, scene ) {
  16544. if ( this.parent === null ) this.updateMatrixWorld();
  16545. const { renderTarget, activeMipmapLevel } = this;
  16546. if ( this.coordinateSystem !== renderer.coordinateSystem ) {
  16547. this.coordinateSystem = renderer.coordinateSystem;
  16548. this.updateCoordinateSystem();
  16549. }
  16550. const [ cameraPX, cameraNX, cameraPY, cameraNY, cameraPZ, cameraNZ ] = this.children;
  16551. const currentRenderTarget = renderer.getRenderTarget();
  16552. const currentActiveCubeFace = renderer.getActiveCubeFace();
  16553. const currentActiveMipmapLevel = renderer.getActiveMipmapLevel();
  16554. const currentXrEnabled = renderer.xr.enabled;
  16555. renderer.xr.enabled = false;
  16556. const generateMipmaps = renderTarget.texture.generateMipmaps;
  16557. renderTarget.texture.generateMipmaps = false;
  16558. renderer.setRenderTarget( renderTarget, 0, activeMipmapLevel );
  16559. renderer.render( scene, cameraPX );
  16560. renderer.setRenderTarget( renderTarget, 1, activeMipmapLevel );
  16561. renderer.render( scene, cameraNX );
  16562. renderer.setRenderTarget( renderTarget, 2, activeMipmapLevel );
  16563. renderer.render( scene, cameraPY );
  16564. renderer.setRenderTarget( renderTarget, 3, activeMipmapLevel );
  16565. renderer.render( scene, cameraNY );
  16566. renderer.setRenderTarget( renderTarget, 4, activeMipmapLevel );
  16567. renderer.render( scene, cameraPZ );
  16568. // mipmaps are generated during the last call of render()
  16569. // at this point, all sides of the cube render target are defined
  16570. renderTarget.texture.generateMipmaps = generateMipmaps;
  16571. renderer.setRenderTarget( renderTarget, 5, activeMipmapLevel );
  16572. renderer.render( scene, cameraNZ );
  16573. renderer.setRenderTarget( currentRenderTarget, currentActiveCubeFace, currentActiveMipmapLevel );
  16574. renderer.xr.enabled = currentXrEnabled;
  16575. renderTarget.texture.needsPMREMUpdate = true;
  16576. }
  16577. }
  16578. /**
  16579. * Creates a cube texture made up of six images.
  16580. *
  16581. * ```js
  16582. * const loader = new THREE.CubeTextureLoader();
  16583. * loader.setPath( 'textures/cube/pisa/' );
  16584. *
  16585. * const textureCube = loader.load( [
  16586. * 'px.png', 'nx.png', 'py.png', 'ny.png', 'pz.png', 'nz.png'
  16587. * ] );
  16588. *
  16589. * const material = new THREE.MeshBasicMaterial( { color: 0xffffff, envMap: textureCube } );
  16590. * ```
  16591. *
  16592. * @augments Texture
  16593. */
  16594. class CubeTexture extends Texture {
  16595. /**
  16596. * Constructs a new cube texture.
  16597. *
  16598. * @param {Array<Image>} [images=[]] - An array holding a image for each side of a cube.
  16599. * @param {number} [mapping=CubeReflectionMapping] - The texture mapping.
  16600. * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value.
  16601. * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value.
  16602. * @param {number} [magFilter=LinearFilter] - The mag filter value.
  16603. * @param {number} [minFilter=LinearMipmapLinearFilter] - The min filter value.
  16604. * @param {number} [format=RGBAFormat] - The texture format.
  16605. * @param {number} [type=UnsignedByteType] - The texture type.
  16606. * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value.
  16607. * @param {string} [colorSpace=NoColorSpace] - The color space value.
  16608. */
  16609. constructor( images = [], mapping = CubeReflectionMapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace ) {
  16610. super( images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace );
  16611. /**
  16612. * This flag can be used for type testing.
  16613. *
  16614. * @type {boolean}
  16615. * @readonly
  16616. * @default true
  16617. */
  16618. this.isCubeTexture = true;
  16619. /**
  16620. * If set to `true`, the texture is flipped along the vertical axis when
  16621. * uploaded to the GPU.
  16622. *
  16623. * Overwritten and set to `false` by default.
  16624. *
  16625. * @type {boolean}
  16626. * @default false
  16627. */
  16628. this.flipY = false;
  16629. }
  16630. /**
  16631. * Alias for {@link CubeTexture#image}.
  16632. *
  16633. * @type {Array<Image>}
  16634. */
  16635. get images() {
  16636. return this.image;
  16637. }
  16638. set images( value ) {
  16639. this.image = value;
  16640. }
  16641. }
  16642. /**
  16643. * A cube render target used in context of {@link WebGLRenderer}.
  16644. *
  16645. * @augments WebGLRenderTarget
  16646. */
  16647. class WebGLCubeRenderTarget extends WebGLRenderTarget {
  16648. /**
  16649. * Constructs a new cube render target.
  16650. *
  16651. * @param {number} [size=1] - The size of the render target.
  16652. * @param {RenderTarget~Options} [options] - The configuration object.
  16653. */
  16654. constructor( size = 1, options = {} ) {
  16655. super( size, size, options );
  16656. /**
  16657. * This flag can be used for type testing.
  16658. *
  16659. * @type {boolean}
  16660. * @readonly
  16661. * @default true
  16662. */
  16663. this.isWebGLCubeRenderTarget = true;
  16664. const image = { width: size, height: size, depth: 1 };
  16665. const images = [ image, image, image, image, image, image ];
  16666. /**
  16667. * Overwritten with a different texture type.
  16668. *
  16669. * @type {DataArrayTexture}
  16670. */
  16671. this.texture = new CubeTexture( images );
  16672. this._setTextureOptions( options );
  16673. // By convention -- likely based on the RenderMan spec from the 1990's -- cube maps are specified by WebGL (and three.js)
  16674. // in a coordinate system in which positive-x is to the right when looking up the positive-z axis -- in other words,
  16675. // in a left-handed coordinate system. By continuing this convention, preexisting cube maps continued to render correctly.
  16676. // three.js uses a right-handed coordinate system. So environment maps used in three.js appear to have px and nx swapped
  16677. // and the flag isRenderTargetTexture controls this conversion. The flip is not required when using WebGLCubeRenderTarget.texture
  16678. // as a cube texture (this is detected when isRenderTargetTexture is set to true for cube textures).
  16679. this.texture.isRenderTargetTexture = true;
  16680. }
  16681. /**
  16682. * Converts the given equirectangular texture to a cube map.
  16683. *
  16684. * @param {WebGLRenderer} renderer - The renderer.
  16685. * @param {Texture} texture - The equirectangular texture.
  16686. * @return {WebGLCubeRenderTarget} A reference to this cube render target.
  16687. */
  16688. fromEquirectangularTexture( renderer, texture ) {
  16689. this.texture.type = texture.type;
  16690. this.texture.colorSpace = texture.colorSpace;
  16691. this.texture.generateMipmaps = texture.generateMipmaps;
  16692. this.texture.minFilter = texture.minFilter;
  16693. this.texture.magFilter = texture.magFilter;
  16694. const shader = {
  16695. uniforms: {
  16696. tEquirect: { value: null },
  16697. },
  16698. vertexShader: /* glsl */`
  16699. varying vec3 vWorldDirection;
  16700. vec3 transformDirection( in vec3 dir, in mat4 matrix ) {
  16701. return normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );
  16702. }
  16703. void main() {
  16704. vWorldDirection = transformDirection( position, modelMatrix );
  16705. #include <begin_vertex>
  16706. #include <project_vertex>
  16707. }
  16708. `,
  16709. fragmentShader: /* glsl */`
  16710. uniform sampler2D tEquirect;
  16711. varying vec3 vWorldDirection;
  16712. #include <common>
  16713. void main() {
  16714. vec3 direction = normalize( vWorldDirection );
  16715. vec2 sampleUV = equirectUv( direction );
  16716. gl_FragColor = texture2D( tEquirect, sampleUV );
  16717. }
  16718. `
  16719. };
  16720. const geometry = new BoxGeometry( 5, 5, 5 );
  16721. const material = new ShaderMaterial( {
  16722. name: 'CubemapFromEquirect',
  16723. uniforms: cloneUniforms( shader.uniforms ),
  16724. vertexShader: shader.vertexShader,
  16725. fragmentShader: shader.fragmentShader,
  16726. side: BackSide,
  16727. blending: NoBlending
  16728. } );
  16729. material.uniforms.tEquirect.value = texture;
  16730. const mesh = new Mesh( geometry, material );
  16731. const currentMinFilter = texture.minFilter;
  16732. // Avoid blurred poles
  16733. if ( texture.minFilter === LinearMipmapLinearFilter ) texture.minFilter = LinearFilter;
  16734. const camera = new CubeCamera( 1, 10, this );
  16735. camera.update( renderer, mesh );
  16736. texture.minFilter = currentMinFilter;
  16737. mesh.geometry.dispose();
  16738. mesh.material.dispose();
  16739. return this;
  16740. }
  16741. /**
  16742. * Clears this cube render target.
  16743. *
  16744. * @param {WebGLRenderer} renderer - The renderer.
  16745. * @param {boolean} [color=true] - Whether the color buffer should be cleared or not.
  16746. * @param {boolean} [depth=true] - Whether the depth buffer should be cleared or not.
  16747. * @param {boolean} [stencil=true] - Whether the stencil buffer should be cleared or not.
  16748. */
  16749. clear( renderer, color = true, depth = true, stencil = true ) {
  16750. const currentRenderTarget = renderer.getRenderTarget();
  16751. for ( let i = 0; i < 6; i ++ ) {
  16752. renderer.setRenderTarget( this, i );
  16753. renderer.clear( color, depth, stencil );
  16754. }
  16755. renderer.setRenderTarget( currentRenderTarget );
  16756. }
  16757. }
  16758. /**
  16759. * This is almost identical to an {@link Object3D}. Its purpose is to
  16760. * make working with groups of objects syntactically clearer.
  16761. *
  16762. * ```js
  16763. * // Create a group and add the two cubes.
  16764. * // These cubes can now be rotated / scaled etc as a group.
  16765. * const group = new THREE.Group();
  16766. *
  16767. * group.add( meshA );
  16768. * group.add( meshB );
  16769. *
  16770. * scene.add( group );
  16771. * ```
  16772. *
  16773. * @augments Object3D
  16774. */
  16775. class Group extends Object3D {
  16776. constructor() {
  16777. super();
  16778. /**
  16779. * This flag can be used for type testing.
  16780. *
  16781. * @type {boolean}
  16782. * @readonly
  16783. * @default true
  16784. */
  16785. this.isGroup = true;
  16786. this.type = 'Group';
  16787. }
  16788. }
  16789. const _moveEvent = { type: 'move' };
  16790. /**
  16791. * Class for representing a XR controller with its
  16792. * different coordinate systems.
  16793. *
  16794. * @private
  16795. */
  16796. class WebXRController {
  16797. /**
  16798. * Constructs a new XR controller.
  16799. */
  16800. constructor() {
  16801. /**
  16802. * A group representing the target ray space
  16803. * of the XR controller.
  16804. *
  16805. * @private
  16806. * @type {?Group}
  16807. * @default null
  16808. */
  16809. this._targetRay = null;
  16810. /**
  16811. * A group representing the grip space
  16812. * of the XR controller.
  16813. *
  16814. * @private
  16815. * @type {?Group}
  16816. * @default null
  16817. */
  16818. this._grip = null;
  16819. /**
  16820. * A group representing the hand space
  16821. * of the XR controller.
  16822. *
  16823. * @private
  16824. * @type {?Group}
  16825. * @default null
  16826. */
  16827. this._hand = null;
  16828. }
  16829. /**
  16830. * Returns a group representing the hand space of the XR controller.
  16831. *
  16832. * @return {Group} A group representing the hand space of the XR controller.
  16833. */
  16834. getHandSpace() {
  16835. if ( this._hand === null ) {
  16836. this._hand = new Group();
  16837. this._hand.matrixAutoUpdate = false;
  16838. this._hand.visible = false;
  16839. this._hand.joints = {};
  16840. this._hand.inputState = { pinching: false };
  16841. }
  16842. return this._hand;
  16843. }
  16844. /**
  16845. * Returns a group representing the target ray space of the XR controller.
  16846. *
  16847. * @return {Group} A group representing the target ray space of the XR controller.
  16848. */
  16849. getTargetRaySpace() {
  16850. if ( this._targetRay === null ) {
  16851. this._targetRay = new Group();
  16852. this._targetRay.matrixAutoUpdate = false;
  16853. this._targetRay.visible = false;
  16854. this._targetRay.hasLinearVelocity = false;
  16855. this._targetRay.linearVelocity = new Vector3();
  16856. this._targetRay.hasAngularVelocity = false;
  16857. this._targetRay.angularVelocity = new Vector3();
  16858. }
  16859. return this._targetRay;
  16860. }
  16861. /**
  16862. * Returns a group representing the grip space of the XR controller.
  16863. *
  16864. * @return {Group} A group representing the grip space of the XR controller.
  16865. */
  16866. getGripSpace() {
  16867. if ( this._grip === null ) {
  16868. this._grip = new Group();
  16869. this._grip.matrixAutoUpdate = false;
  16870. this._grip.visible = false;
  16871. this._grip.hasLinearVelocity = false;
  16872. this._grip.linearVelocity = new Vector3();
  16873. this._grip.hasAngularVelocity = false;
  16874. this._grip.angularVelocity = new Vector3();
  16875. }
  16876. return this._grip;
  16877. }
  16878. /**
  16879. * Dispatches the given event to the groups representing
  16880. * the different coordinate spaces of the XR controller.
  16881. *
  16882. * @param {Object} event - The event to dispatch.
  16883. * @return {WebXRController} A reference to this instance.
  16884. */
  16885. dispatchEvent( event ) {
  16886. if ( this._targetRay !== null ) {
  16887. this._targetRay.dispatchEvent( event );
  16888. }
  16889. if ( this._grip !== null ) {
  16890. this._grip.dispatchEvent( event );
  16891. }
  16892. if ( this._hand !== null ) {
  16893. this._hand.dispatchEvent( event );
  16894. }
  16895. return this;
  16896. }
  16897. /**
  16898. * Connects the controller with the given XR input source.
  16899. *
  16900. * @param {XRInputSource} inputSource - The input source.
  16901. * @return {WebXRController} A reference to this instance.
  16902. */
  16903. connect( inputSource ) {
  16904. if ( inputSource && inputSource.hand ) {
  16905. const hand = this._hand;
  16906. if ( hand ) {
  16907. for ( const inputjoint of inputSource.hand.values() ) {
  16908. // Initialize hand with joints when connected
  16909. this._getHandJoint( hand, inputjoint );
  16910. }
  16911. }
  16912. }
  16913. this.dispatchEvent( { type: 'connected', data: inputSource } );
  16914. return this;
  16915. }
  16916. /**
  16917. * Disconnects the controller from the given XR input source.
  16918. *
  16919. * @param {XRInputSource} inputSource - The input source.
  16920. * @return {WebXRController} A reference to this instance.
  16921. */
  16922. disconnect( inputSource ) {
  16923. this.dispatchEvent( { type: 'disconnected', data: inputSource } );
  16924. if ( this._targetRay !== null ) {
  16925. this._targetRay.visible = false;
  16926. }
  16927. if ( this._grip !== null ) {
  16928. this._grip.visible = false;
  16929. }
  16930. if ( this._hand !== null ) {
  16931. this._hand.visible = false;
  16932. }
  16933. return this;
  16934. }
  16935. /**
  16936. * Updates the controller with the given input source, XR frame and reference space.
  16937. * This updates the transformations of the groups that represent the different
  16938. * coordinate systems of the controller.
  16939. *
  16940. * @param {XRInputSource} inputSource - The input source.
  16941. * @param {XRFrame} frame - The XR frame.
  16942. * @param {XRReferenceSpace} referenceSpace - The reference space.
  16943. * @return {WebXRController} A reference to this instance.
  16944. */
  16945. update( inputSource, frame, referenceSpace ) {
  16946. let inputPose = null;
  16947. let gripPose = null;
  16948. let handPose = null;
  16949. const targetRay = this._targetRay;
  16950. const grip = this._grip;
  16951. const hand = this._hand;
  16952. if ( inputSource && frame.session.visibilityState !== 'visible-blurred' ) {
  16953. if ( hand && inputSource.hand ) {
  16954. handPose = true;
  16955. for ( const inputjoint of inputSource.hand.values() ) {
  16956. // Update the joints groups with the XRJoint poses
  16957. const jointPose = frame.getJointPose( inputjoint, referenceSpace );
  16958. // The transform of this joint will be updated with the joint pose on each frame
  16959. const joint = this._getHandJoint( hand, inputjoint );
  16960. if ( jointPose !== null ) {
  16961. joint.matrix.fromArray( jointPose.transform.matrix );
  16962. joint.matrix.decompose( joint.position, joint.rotation, joint.scale );
  16963. joint.matrixWorldNeedsUpdate = true;
  16964. joint.jointRadius = jointPose.radius;
  16965. }
  16966. joint.visible = jointPose !== null;
  16967. }
  16968. // Custom events
  16969. // Check pinchz
  16970. const indexTip = hand.joints[ 'index-finger-tip' ];
  16971. const thumbTip = hand.joints[ 'thumb-tip' ];
  16972. const distance = indexTip.position.distanceTo( thumbTip.position );
  16973. const distanceToPinch = 0.02;
  16974. const threshold = 0.005;
  16975. if ( hand.inputState.pinching && distance > distanceToPinch + threshold ) {
  16976. hand.inputState.pinching = false;
  16977. this.dispatchEvent( {
  16978. type: 'pinchend',
  16979. handedness: inputSource.handedness,
  16980. target: this
  16981. } );
  16982. } else if ( ! hand.inputState.pinching && distance <= distanceToPinch - threshold ) {
  16983. hand.inputState.pinching = true;
  16984. this.dispatchEvent( {
  16985. type: 'pinchstart',
  16986. handedness: inputSource.handedness,
  16987. target: this
  16988. } );
  16989. }
  16990. } else {
  16991. if ( grip !== null && inputSource.gripSpace ) {
  16992. gripPose = frame.getPose( inputSource.gripSpace, referenceSpace );
  16993. if ( gripPose !== null ) {
  16994. grip.matrix.fromArray( gripPose.transform.matrix );
  16995. grip.matrix.decompose( grip.position, grip.rotation, grip.scale );
  16996. grip.matrixWorldNeedsUpdate = true;
  16997. if ( gripPose.linearVelocity ) {
  16998. grip.hasLinearVelocity = true;
  16999. grip.linearVelocity.copy( gripPose.linearVelocity );
  17000. } else {
  17001. grip.hasLinearVelocity = false;
  17002. }
  17003. if ( gripPose.angularVelocity ) {
  17004. grip.hasAngularVelocity = true;
  17005. grip.angularVelocity.copy( gripPose.angularVelocity );
  17006. } else {
  17007. grip.hasAngularVelocity = false;
  17008. }
  17009. }
  17010. }
  17011. }
  17012. if ( targetRay !== null ) {
  17013. inputPose = frame.getPose( inputSource.targetRaySpace, referenceSpace );
  17014. // Some runtimes (namely Vive Cosmos with Vive OpenXR Runtime) have only grip space and ray space is equal to it
  17015. if ( inputPose === null && gripPose !== null ) {
  17016. inputPose = gripPose;
  17017. }
  17018. if ( inputPose !== null ) {
  17019. targetRay.matrix.fromArray( inputPose.transform.matrix );
  17020. targetRay.matrix.decompose( targetRay.position, targetRay.rotation, targetRay.scale );
  17021. targetRay.matrixWorldNeedsUpdate = true;
  17022. if ( inputPose.linearVelocity ) {
  17023. targetRay.hasLinearVelocity = true;
  17024. targetRay.linearVelocity.copy( inputPose.linearVelocity );
  17025. } else {
  17026. targetRay.hasLinearVelocity = false;
  17027. }
  17028. if ( inputPose.angularVelocity ) {
  17029. targetRay.hasAngularVelocity = true;
  17030. targetRay.angularVelocity.copy( inputPose.angularVelocity );
  17031. } else {
  17032. targetRay.hasAngularVelocity = false;
  17033. }
  17034. this.dispatchEvent( _moveEvent );
  17035. }
  17036. }
  17037. }
  17038. if ( targetRay !== null ) {
  17039. targetRay.visible = ( inputPose !== null );
  17040. }
  17041. if ( grip !== null ) {
  17042. grip.visible = ( gripPose !== null );
  17043. }
  17044. if ( hand !== null ) {
  17045. hand.visible = ( handPose !== null );
  17046. }
  17047. return this;
  17048. }
  17049. /**
  17050. * Returns a group representing the hand joint for the given input joint.
  17051. *
  17052. * @private
  17053. * @param {Group} hand - The group representing the hand space.
  17054. * @param {XRJointSpace} inputjoint - The hand joint data.
  17055. * @return {Group} A group representing the hand joint for the given input joint.
  17056. */
  17057. _getHandJoint( hand, inputjoint ) {
  17058. if ( hand.joints[ inputjoint.jointName ] === undefined ) {
  17059. const joint = new Group();
  17060. joint.matrixAutoUpdate = false;
  17061. joint.visible = false;
  17062. hand.joints[ inputjoint.jointName ] = joint;
  17063. hand.add( joint );
  17064. }
  17065. return hand.joints[ inputjoint.jointName ];
  17066. }
  17067. }
  17068. /**
  17069. * This class can be used to define an exponential squared fog,
  17070. * which gives a clear view near the camera and a faster than exponentially
  17071. * densening fog farther from the camera.
  17072. *
  17073. * ```js
  17074. * const scene = new THREE.Scene();
  17075. * scene.fog = new THREE.FogExp2( 0xcccccc, 0.002 );
  17076. * ```
  17077. */
  17078. class FogExp2 {
  17079. /**
  17080. * Constructs a new fog.
  17081. *
  17082. * @param {number|Color} color - The fog's color.
  17083. * @param {number} [density=0.00025] - Defines how fast the fog will grow dense.
  17084. */
  17085. constructor( color, density = 0.00025 ) {
  17086. /**
  17087. * This flag can be used for type testing.
  17088. *
  17089. * @type {boolean}
  17090. * @readonly
  17091. * @default true
  17092. */
  17093. this.isFogExp2 = true;
  17094. /**
  17095. * The name of the fog.
  17096. *
  17097. * @type {string}
  17098. */
  17099. this.name = '';
  17100. /**
  17101. * The fog's color.
  17102. *
  17103. * @type {Color}
  17104. */
  17105. this.color = new Color( color );
  17106. /**
  17107. * Defines how fast the fog will grow dense.
  17108. *
  17109. * @type {number}
  17110. * @default 0.00025
  17111. */
  17112. this.density = density;
  17113. }
  17114. /**
  17115. * Returns a new fog with copied values from this instance.
  17116. *
  17117. * @return {FogExp2} A clone of this instance.
  17118. */
  17119. clone() {
  17120. return new FogExp2( this.color, this.density );
  17121. }
  17122. /**
  17123. * Serializes the fog into JSON.
  17124. *
  17125. * @param {?(Object|string)} meta - An optional value holding meta information about the serialization.
  17126. * @return {Object} A JSON object representing the serialized fog
  17127. */
  17128. toJSON( /* meta */ ) {
  17129. return {
  17130. type: 'FogExp2',
  17131. name: this.name,
  17132. color: this.color.getHex(),
  17133. density: this.density
  17134. };
  17135. }
  17136. }
  17137. /**
  17138. * This class can be used to define a linear fog that grows linearly denser
  17139. * with the distance.
  17140. *
  17141. * ```js
  17142. * const scene = new THREE.Scene();
  17143. * scene.fog = new THREE.Fog( 0xcccccc, 10, 15 );
  17144. * ```
  17145. */
  17146. class Fog {
  17147. /**
  17148. * Constructs a new fog.
  17149. *
  17150. * @param {number|Color} color - The fog's color.
  17151. * @param {number} [near=1] - The minimum distance to start applying fog.
  17152. * @param {number} [far=1000] - The maximum distance at which fog stops being calculated and applied.
  17153. */
  17154. constructor( color, near = 1, far = 1000 ) {
  17155. /**
  17156. * This flag can be used for type testing.
  17157. *
  17158. * @type {boolean}
  17159. * @readonly
  17160. * @default true
  17161. */
  17162. this.isFog = true;
  17163. /**
  17164. * The name of the fog.
  17165. *
  17166. * @type {string}
  17167. */
  17168. this.name = '';
  17169. /**
  17170. * The fog's color.
  17171. *
  17172. * @type {Color}
  17173. */
  17174. this.color = new Color( color );
  17175. /**
  17176. * The minimum distance to start applying fog. Objects that are less than
  17177. * `near` units from the active camera won't be affected by fog.
  17178. *
  17179. * @type {number}
  17180. * @default 1
  17181. */
  17182. this.near = near;
  17183. /**
  17184. * The maximum distance at which fog stops being calculated and applied.
  17185. * Objects that are more than `far` units away from the active camera won't
  17186. * be affected by fog.
  17187. *
  17188. * @type {number}
  17189. * @default 1000
  17190. */
  17191. this.far = far;
  17192. }
  17193. /**
  17194. * Returns a new fog with copied values from this instance.
  17195. *
  17196. * @return {Fog} A clone of this instance.
  17197. */
  17198. clone() {
  17199. return new Fog( this.color, this.near, this.far );
  17200. }
  17201. /**
  17202. * Serializes the fog into JSON.
  17203. *
  17204. * @param {?(Object|string)} meta - An optional value holding meta information about the serialization.
  17205. * @return {Object} A JSON object representing the serialized fog
  17206. */
  17207. toJSON( /* meta */ ) {
  17208. return {
  17209. type: 'Fog',
  17210. name: this.name,
  17211. color: this.color.getHex(),
  17212. near: this.near,
  17213. far: this.far
  17214. };
  17215. }
  17216. }
  17217. /**
  17218. * Scenes allow you to set up what is to be rendered and where by three.js.
  17219. * This is where you place 3D objects like meshes, lines or lights.
  17220. *
  17221. * @augments Object3D
  17222. */
  17223. class Scene extends Object3D {
  17224. /**
  17225. * Constructs a new scene.
  17226. */
  17227. constructor() {
  17228. super();
  17229. /**
  17230. * This flag can be used for type testing.
  17231. *
  17232. * @type {boolean}
  17233. * @readonly
  17234. * @default true
  17235. */
  17236. this.isScene = true;
  17237. this.type = 'Scene';
  17238. /**
  17239. * Defines the background of the scene. Valid inputs are:
  17240. *
  17241. * - A color for defining a uniform colored background.
  17242. * - A texture for defining a (flat) textured background.
  17243. * - Cube textures or equirectangular textures for defining a skybox.
  17244. *
  17245. * @type {?(Color|Texture)}
  17246. * @default null
  17247. */
  17248. this.background = null;
  17249. /**
  17250. * Sets the environment map for all physical materials in the scene. However,
  17251. * it's not possible to overwrite an existing texture assigned to the `envMap`
  17252. * material property.
  17253. *
  17254. * @type {?Texture}
  17255. * @default null
  17256. */
  17257. this.environment = null;
  17258. /**
  17259. * A fog instance defining the type of fog that affects everything
  17260. * rendered in the scene.
  17261. *
  17262. * @type {?(Fog|FogExp2)}
  17263. * @default null
  17264. */
  17265. this.fog = null;
  17266. /**
  17267. * Sets the blurriness of the background. Only influences environment maps
  17268. * assigned to {@link Scene#background}. Valid input is a float between `0`
  17269. * and `1`.
  17270. *
  17271. * @type {number}
  17272. * @default 0
  17273. */
  17274. this.backgroundBlurriness = 0;
  17275. /**
  17276. * Attenuates the color of the background. Only applies to background textures.
  17277. *
  17278. * @type {number}
  17279. * @default 1
  17280. */
  17281. this.backgroundIntensity = 1;
  17282. /**
  17283. * The rotation of the background in radians. Only influences environment maps
  17284. * assigned to {@link Scene#background}.
  17285. *
  17286. * @type {Euler}
  17287. * @default (0,0,0)
  17288. */
  17289. this.backgroundRotation = new Euler();
  17290. /**
  17291. * Attenuates the color of the environment. Only influences environment maps
  17292. * assigned to {@link Scene#environment}.
  17293. *
  17294. * @type {number}
  17295. * @default 1
  17296. */
  17297. this.environmentIntensity = 1;
  17298. /**
  17299. * The rotation of the environment map in radians. Only influences physical materials
  17300. * in the scene when {@link Scene#environment} is used.
  17301. *
  17302. * @type {Euler}
  17303. * @default (0,0,0)
  17304. */
  17305. this.environmentRotation = new Euler();
  17306. /**
  17307. * Forces everything in the scene to be rendered with the defined material. It is possible
  17308. * to exclude materials from override by setting {@link Material#allowOverride} to `false`.
  17309. *
  17310. * @type {?Material}
  17311. * @default null
  17312. */
  17313. this.overrideMaterial = null;
  17314. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  17315. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'observe', { detail: this } ) );
  17316. }
  17317. }
  17318. copy( source, recursive ) {
  17319. super.copy( source, recursive );
  17320. if ( source.background !== null ) this.background = source.background.clone();
  17321. if ( source.environment !== null ) this.environment = source.environment.clone();
  17322. if ( source.fog !== null ) this.fog = source.fog.clone();
  17323. this.backgroundBlurriness = source.backgroundBlurriness;
  17324. this.backgroundIntensity = source.backgroundIntensity;
  17325. this.backgroundRotation.copy( source.backgroundRotation );
  17326. this.environmentIntensity = source.environmentIntensity;
  17327. this.environmentRotation.copy( source.environmentRotation );
  17328. if ( source.overrideMaterial !== null ) this.overrideMaterial = source.overrideMaterial.clone();
  17329. this.matrixAutoUpdate = source.matrixAutoUpdate;
  17330. return this;
  17331. }
  17332. toJSON( meta ) {
  17333. const data = super.toJSON( meta );
  17334. if ( this.fog !== null ) data.object.fog = this.fog.toJSON();
  17335. if ( this.backgroundBlurriness > 0 ) data.object.backgroundBlurriness = this.backgroundBlurriness;
  17336. if ( this.backgroundIntensity !== 1 ) data.object.backgroundIntensity = this.backgroundIntensity;
  17337. data.object.backgroundRotation = this.backgroundRotation.toArray();
  17338. if ( this.environmentIntensity !== 1 ) data.object.environmentIntensity = this.environmentIntensity;
  17339. data.object.environmentRotation = this.environmentRotation.toArray();
  17340. return data;
  17341. }
  17342. }
  17343. /**
  17344. * "Interleaved" means that multiple attributes, possibly of different types,
  17345. * (e.g., position, normal, uv, color) are packed into a single array buffer.
  17346. *
  17347. * An introduction into interleaved arrays can be found here: [Interleaved array basics](https://blog.tojicode.com/2011/05/interleaved-array-basics.html)
  17348. */
  17349. class InterleavedBuffer {
  17350. /**
  17351. * Constructs a new interleaved buffer.
  17352. *
  17353. * @param {TypedArray} array - A typed array with a shared buffer storing attribute data.
  17354. * @param {number} stride - The number of typed-array elements per vertex.
  17355. */
  17356. constructor( array, stride ) {
  17357. /**
  17358. * This flag can be used for type testing.
  17359. *
  17360. * @type {boolean}
  17361. * @readonly
  17362. * @default true
  17363. */
  17364. this.isInterleavedBuffer = true;
  17365. /**
  17366. * A typed array with a shared buffer storing attribute data.
  17367. *
  17368. * @type {TypedArray}
  17369. */
  17370. this.array = array;
  17371. /**
  17372. * The number of typed-array elements per vertex.
  17373. *
  17374. * @type {number}
  17375. */
  17376. this.stride = stride;
  17377. /**
  17378. * The total number of elements in the array
  17379. *
  17380. * @type {number}
  17381. * @readonly
  17382. */
  17383. this.count = array !== undefined ? array.length / stride : 0;
  17384. /**
  17385. * Defines the intended usage pattern of the data store for optimization purposes.
  17386. *
  17387. * Note: After the initial use of a buffer, its usage cannot be changed. Instead,
  17388. * instantiate a new one and set the desired usage before the next render.
  17389. *
  17390. * @type {(StaticDrawUsage|DynamicDrawUsage|StreamDrawUsage|StaticReadUsage|DynamicReadUsage|StreamReadUsage|StaticCopyUsage|DynamicCopyUsage|StreamCopyUsage)}
  17391. * @default StaticDrawUsage
  17392. */
  17393. this.usage = StaticDrawUsage;
  17394. /**
  17395. * This can be used to only update some components of stored vectors (for example, just the
  17396. * component related to color). Use the `addUpdateRange()` function to add ranges to this array.
  17397. *
  17398. * @type {Array<Object>}
  17399. */
  17400. this.updateRanges = [];
  17401. /**
  17402. * A version number, incremented every time the `needsUpdate` is set to `true`.
  17403. *
  17404. * @type {number}
  17405. */
  17406. this.version = 0;
  17407. /**
  17408. * The UUID of the interleaved buffer.
  17409. *
  17410. * @type {string}
  17411. * @readonly
  17412. */
  17413. this.uuid = generateUUID();
  17414. }
  17415. /**
  17416. * A callback function that is executed after the renderer has transferred the attribute array
  17417. * data to the GPU.
  17418. */
  17419. onUploadCallback() {}
  17420. /**
  17421. * Flag to indicate that this attribute has changed and should be re-sent to
  17422. * the GPU. Set this to `true` when you modify the value of the array.
  17423. *
  17424. * @type {number}
  17425. * @default false
  17426. * @param {boolean} value
  17427. */
  17428. set needsUpdate( value ) {
  17429. if ( value === true ) this.version ++;
  17430. }
  17431. /**
  17432. * Sets the usage of this interleaved buffer.
  17433. *
  17434. * @param {(StaticDrawUsage|DynamicDrawUsage|StreamDrawUsage|StaticReadUsage|DynamicReadUsage|StreamReadUsage|StaticCopyUsage|DynamicCopyUsage|StreamCopyUsage)} value - The usage to set.
  17435. * @return {InterleavedBuffer} A reference to this interleaved buffer.
  17436. */
  17437. setUsage( value ) {
  17438. this.usage = value;
  17439. return this;
  17440. }
  17441. /**
  17442. * Adds a range of data in the data array to be updated on the GPU.
  17443. *
  17444. * @param {number} start - Position at which to start update.
  17445. * @param {number} count - The number of components to update.
  17446. */
  17447. addUpdateRange( start, count ) {
  17448. this.updateRanges.push( { start, count } );
  17449. }
  17450. /**
  17451. * Clears the update ranges.
  17452. */
  17453. clearUpdateRanges() {
  17454. this.updateRanges.length = 0;
  17455. }
  17456. /**
  17457. * Copies the values of the given interleaved buffer to this instance.
  17458. *
  17459. * @param {InterleavedBuffer} source - The interleaved buffer to copy.
  17460. * @return {InterleavedBuffer} A reference to this instance.
  17461. */
  17462. copy( source ) {
  17463. this.array = new source.array.constructor( source.array );
  17464. this.count = source.count;
  17465. this.stride = source.stride;
  17466. this.usage = source.usage;
  17467. return this;
  17468. }
  17469. /**
  17470. * Copies a vector from the given interleaved buffer to this one. The start
  17471. * and destination position in the attribute buffers are represented by the
  17472. * given indices.
  17473. *
  17474. * @param {number} index1 - The destination index into this interleaved buffer.
  17475. * @param {InterleavedBuffer} interleavedBuffer - The interleaved buffer to copy from.
  17476. * @param {number} index2 - The source index into the given interleaved buffer.
  17477. * @return {InterleavedBuffer} A reference to this instance.
  17478. */
  17479. copyAt( index1, interleavedBuffer, index2 ) {
  17480. index1 *= this.stride;
  17481. index2 *= interleavedBuffer.stride;
  17482. for ( let i = 0, l = this.stride; i < l; i ++ ) {
  17483. this.array[ index1 + i ] = interleavedBuffer.array[ index2 + i ];
  17484. }
  17485. return this;
  17486. }
  17487. /**
  17488. * Sets the given array data in the interleaved buffer.
  17489. *
  17490. * @param {(TypedArray|Array)} value - The array data to set.
  17491. * @param {number} [offset=0] - The offset in this interleaved buffer's array.
  17492. * @return {InterleavedBuffer} A reference to this instance.
  17493. */
  17494. set( value, offset = 0 ) {
  17495. this.array.set( value, offset );
  17496. return this;
  17497. }
  17498. /**
  17499. * Returns a new interleaved buffer with copied values from this instance.
  17500. *
  17501. * @param {Object} [data] - An object with shared array buffers that allows to retain shared structures.
  17502. * @return {InterleavedBuffer} A clone of this instance.
  17503. */
  17504. clone( data ) {
  17505. if ( data.arrayBuffers === undefined ) {
  17506. data.arrayBuffers = {};
  17507. }
  17508. if ( this.array.buffer._uuid === undefined ) {
  17509. this.array.buffer._uuid = generateUUID();
  17510. }
  17511. if ( data.arrayBuffers[ this.array.buffer._uuid ] === undefined ) {
  17512. data.arrayBuffers[ this.array.buffer._uuid ] = this.array.slice( 0 ).buffer;
  17513. }
  17514. const array = new this.array.constructor( data.arrayBuffers[ this.array.buffer._uuid ] );
  17515. const ib = new this.constructor( array, this.stride );
  17516. ib.setUsage( this.usage );
  17517. return ib;
  17518. }
  17519. /**
  17520. * Sets the given callback function that is executed after the Renderer has transferred
  17521. * the array data to the GPU. Can be used to perform clean-up operations after
  17522. * the upload when data are not needed anymore on the CPU side.
  17523. *
  17524. * @param {Function} callback - The `onUpload()` callback.
  17525. * @return {InterleavedBuffer} A reference to this instance.
  17526. */
  17527. onUpload( callback ) {
  17528. this.onUploadCallback = callback;
  17529. return this;
  17530. }
  17531. /**
  17532. * Serializes the interleaved buffer into JSON.
  17533. *
  17534. * @param {Object} [data] - An optional value holding meta information about the serialization.
  17535. * @return {Object} A JSON object representing the serialized interleaved buffer.
  17536. */
  17537. toJSON( data ) {
  17538. if ( data.arrayBuffers === undefined ) {
  17539. data.arrayBuffers = {};
  17540. }
  17541. // generate UUID for array buffer if necessary
  17542. if ( this.array.buffer._uuid === undefined ) {
  17543. this.array.buffer._uuid = generateUUID();
  17544. }
  17545. if ( data.arrayBuffers[ this.array.buffer._uuid ] === undefined ) {
  17546. data.arrayBuffers[ this.array.buffer._uuid ] = Array.from( new Uint32Array( this.array.buffer ) );
  17547. }
  17548. //
  17549. return {
  17550. uuid: this.uuid,
  17551. buffer: this.array.buffer._uuid,
  17552. type: this.array.constructor.name,
  17553. stride: this.stride
  17554. };
  17555. }
  17556. }
  17557. const _vector$7 = /*@__PURE__*/ new Vector3();
  17558. /**
  17559. * An alternative version of a buffer attribute with interleaved data. Interleaved
  17560. * attributes share a common interleaved data storage ({@link InterleavedBuffer}) and refer with
  17561. * different offsets into the buffer.
  17562. */
  17563. class InterleavedBufferAttribute {
  17564. /**
  17565. * Constructs a new interleaved buffer attribute.
  17566. *
  17567. * @param {InterleavedBuffer} interleavedBuffer - The buffer holding the interleaved data.
  17568. * @param {number} itemSize - The item size.
  17569. * @param {number} offset - The attribute offset into the buffer.
  17570. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  17571. */
  17572. constructor( interleavedBuffer, itemSize, offset, normalized = false ) {
  17573. /**
  17574. * This flag can be used for type testing.
  17575. *
  17576. * @type {boolean}
  17577. * @readonly
  17578. * @default true
  17579. */
  17580. this.isInterleavedBufferAttribute = true;
  17581. /**
  17582. * The name of the buffer attribute.
  17583. *
  17584. * @type {string}
  17585. */
  17586. this.name = '';
  17587. /**
  17588. * The buffer holding the interleaved data.
  17589. *
  17590. * @type {InterleavedBuffer}
  17591. */
  17592. this.data = interleavedBuffer;
  17593. /**
  17594. * The item size, see {@link BufferAttribute#itemSize}.
  17595. *
  17596. * @type {number}
  17597. */
  17598. this.itemSize = itemSize;
  17599. /**
  17600. * The attribute offset into the buffer.
  17601. *
  17602. * @type {number}
  17603. */
  17604. this.offset = offset;
  17605. /**
  17606. * Whether the data are normalized or not, see {@link BufferAttribute#normalized}
  17607. *
  17608. * @type {InterleavedBuffer}
  17609. */
  17610. this.normalized = normalized;
  17611. }
  17612. /**
  17613. * The item count of this buffer attribute.
  17614. *
  17615. * @type {number}
  17616. * @readonly
  17617. */
  17618. get count() {
  17619. return this.data.count;
  17620. }
  17621. /**
  17622. * The array holding the interleaved buffer attribute data.
  17623. *
  17624. * @type {TypedArray}
  17625. */
  17626. get array() {
  17627. return this.data.array;
  17628. }
  17629. /**
  17630. * Flag to indicate that this attribute has changed and should be re-sent to
  17631. * the GPU. Set this to `true` when you modify the value of the array.
  17632. *
  17633. * @type {number}
  17634. * @default false
  17635. * @param {boolean} value
  17636. */
  17637. set needsUpdate( value ) {
  17638. this.data.needsUpdate = value;
  17639. }
  17640. /**
  17641. * Applies the given 4x4 matrix to the given attribute. Only works with
  17642. * item size `3`.
  17643. *
  17644. * @param {Matrix4} m - The matrix to apply.
  17645. * @return {InterleavedBufferAttribute} A reference to this instance.
  17646. */
  17647. applyMatrix4( m ) {
  17648. for ( let i = 0, l = this.data.count; i < l; i ++ ) {
  17649. _vector$7.fromBufferAttribute( this, i );
  17650. _vector$7.applyMatrix4( m );
  17651. this.setXYZ( i, _vector$7.x, _vector$7.y, _vector$7.z );
  17652. }
  17653. return this;
  17654. }
  17655. /**
  17656. * Applies the given 3x3 normal matrix to the given attribute. Only works with
  17657. * item size `3`.
  17658. *
  17659. * @param {Matrix3} m - The normal matrix to apply.
  17660. * @return {InterleavedBufferAttribute} A reference to this instance.
  17661. */
  17662. applyNormalMatrix( m ) {
  17663. for ( let i = 0, l = this.count; i < l; i ++ ) {
  17664. _vector$7.fromBufferAttribute( this, i );
  17665. _vector$7.applyNormalMatrix( m );
  17666. this.setXYZ( i, _vector$7.x, _vector$7.y, _vector$7.z );
  17667. }
  17668. return this;
  17669. }
  17670. /**
  17671. * Applies the given 4x4 matrix to the given attribute. Only works with
  17672. * item size `3` and with direction vectors.
  17673. *
  17674. * @param {Matrix4} m - The matrix to apply.
  17675. * @return {InterleavedBufferAttribute} A reference to this instance.
  17676. */
  17677. transformDirection( m ) {
  17678. for ( let i = 0, l = this.count; i < l; i ++ ) {
  17679. _vector$7.fromBufferAttribute( this, i );
  17680. _vector$7.transformDirection( m );
  17681. this.setXYZ( i, _vector$7.x, _vector$7.y, _vector$7.z );
  17682. }
  17683. return this;
  17684. }
  17685. /**
  17686. * Returns the given component of the vector at the given index.
  17687. *
  17688. * @param {number} index - The index into the buffer attribute.
  17689. * @param {number} component - The component index.
  17690. * @return {number} The returned value.
  17691. */
  17692. getComponent( index, component ) {
  17693. let value = this.array[ index * this.data.stride + this.offset + component ];
  17694. if ( this.normalized ) value = denormalize( value, this.array );
  17695. return value;
  17696. }
  17697. /**
  17698. * Sets the given value to the given component of the vector at the given index.
  17699. *
  17700. * @param {number} index - The index into the buffer attribute.
  17701. * @param {number} component - The component index.
  17702. * @param {number} value - The value to set.
  17703. * @return {InterleavedBufferAttribute} A reference to this instance.
  17704. */
  17705. setComponent( index, component, value ) {
  17706. if ( this.normalized ) value = normalize( value, this.array );
  17707. this.data.array[ index * this.data.stride + this.offset + component ] = value;
  17708. return this;
  17709. }
  17710. /**
  17711. * Sets the x component of the vector at the given index.
  17712. *
  17713. * @param {number} index - The index into the buffer attribute.
  17714. * @param {number} x - The value to set.
  17715. * @return {InterleavedBufferAttribute} A reference to this instance.
  17716. */
  17717. setX( index, x ) {
  17718. if ( this.normalized ) x = normalize( x, this.array );
  17719. this.data.array[ index * this.data.stride + this.offset ] = x;
  17720. return this;
  17721. }
  17722. /**
  17723. * Sets the y component of the vector at the given index.
  17724. *
  17725. * @param {number} index - The index into the buffer attribute.
  17726. * @param {number} y - The value to set.
  17727. * @return {InterleavedBufferAttribute} A reference to this instance.
  17728. */
  17729. setY( index, y ) {
  17730. if ( this.normalized ) y = normalize( y, this.array );
  17731. this.data.array[ index * this.data.stride + this.offset + 1 ] = y;
  17732. return this;
  17733. }
  17734. /**
  17735. * Sets the z component of the vector at the given index.
  17736. *
  17737. * @param {number} index - The index into the buffer attribute.
  17738. * @param {number} z - The value to set.
  17739. * @return {InterleavedBufferAttribute} A reference to this instance.
  17740. */
  17741. setZ( index, z ) {
  17742. if ( this.normalized ) z = normalize( z, this.array );
  17743. this.data.array[ index * this.data.stride + this.offset + 2 ] = z;
  17744. return this;
  17745. }
  17746. /**
  17747. * Sets the w component of the vector at the given index.
  17748. *
  17749. * @param {number} index - The index into the buffer attribute.
  17750. * @param {number} w - The value to set.
  17751. * @return {InterleavedBufferAttribute} A reference to this instance.
  17752. */
  17753. setW( index, w ) {
  17754. if ( this.normalized ) w = normalize( w, this.array );
  17755. this.data.array[ index * this.data.stride + this.offset + 3 ] = w;
  17756. return this;
  17757. }
  17758. /**
  17759. * Returns the x component of the vector at the given index.
  17760. *
  17761. * @param {number} index - The index into the buffer attribute.
  17762. * @return {number} The x component.
  17763. */
  17764. getX( index ) {
  17765. let x = this.data.array[ index * this.data.stride + this.offset ];
  17766. if ( this.normalized ) x = denormalize( x, this.array );
  17767. return x;
  17768. }
  17769. /**
  17770. * Returns the y component of the vector at the given index.
  17771. *
  17772. * @param {number} index - The index into the buffer attribute.
  17773. * @return {number} The y component.
  17774. */
  17775. getY( index ) {
  17776. let y = this.data.array[ index * this.data.stride + this.offset + 1 ];
  17777. if ( this.normalized ) y = denormalize( y, this.array );
  17778. return y;
  17779. }
  17780. /**
  17781. * Returns the z component of the vector at the given index.
  17782. *
  17783. * @param {number} index - The index into the buffer attribute.
  17784. * @return {number} The z component.
  17785. */
  17786. getZ( index ) {
  17787. let z = this.data.array[ index * this.data.stride + this.offset + 2 ];
  17788. if ( this.normalized ) z = denormalize( z, this.array );
  17789. return z;
  17790. }
  17791. /**
  17792. * Returns the w component of the vector at the given index.
  17793. *
  17794. * @param {number} index - The index into the buffer attribute.
  17795. * @return {number} The w component.
  17796. */
  17797. getW( index ) {
  17798. let w = this.data.array[ index * this.data.stride + this.offset + 3 ];
  17799. if ( this.normalized ) w = denormalize( w, this.array );
  17800. return w;
  17801. }
  17802. /**
  17803. * Sets the x and y component of the vector at the given index.
  17804. *
  17805. * @param {number} index - The index into the buffer attribute.
  17806. * @param {number} x - The value for the x component to set.
  17807. * @param {number} y - The value for the y component to set.
  17808. * @return {InterleavedBufferAttribute} A reference to this instance.
  17809. */
  17810. setXY( index, x, y ) {
  17811. index = index * this.data.stride + this.offset;
  17812. if ( this.normalized ) {
  17813. x = normalize( x, this.array );
  17814. y = normalize( y, this.array );
  17815. }
  17816. this.data.array[ index + 0 ] = x;
  17817. this.data.array[ index + 1 ] = y;
  17818. return this;
  17819. }
  17820. /**
  17821. * Sets the x, y and z component of the vector at the given index.
  17822. *
  17823. * @param {number} index - The index into the buffer attribute.
  17824. * @param {number} x - The value for the x component to set.
  17825. * @param {number} y - The value for the y component to set.
  17826. * @param {number} z - The value for the z component to set.
  17827. * @return {InterleavedBufferAttribute} A reference to this instance.
  17828. */
  17829. setXYZ( index, x, y, z ) {
  17830. index = index * this.data.stride + this.offset;
  17831. if ( this.normalized ) {
  17832. x = normalize( x, this.array );
  17833. y = normalize( y, this.array );
  17834. z = normalize( z, this.array );
  17835. }
  17836. this.data.array[ index + 0 ] = x;
  17837. this.data.array[ index + 1 ] = y;
  17838. this.data.array[ index + 2 ] = z;
  17839. return this;
  17840. }
  17841. /**
  17842. * Sets the x, y, z and w component of the vector at the given index.
  17843. *
  17844. * @param {number} index - The index into the buffer attribute.
  17845. * @param {number} x - The value for the x component to set.
  17846. * @param {number} y - The value for the y component to set.
  17847. * @param {number} z - The value for the z component to set.
  17848. * @param {number} w - The value for the w component to set.
  17849. * @return {InterleavedBufferAttribute} A reference to this instance.
  17850. */
  17851. setXYZW( index, x, y, z, w ) {
  17852. index = index * this.data.stride + this.offset;
  17853. if ( this.normalized ) {
  17854. x = normalize( x, this.array );
  17855. y = normalize( y, this.array );
  17856. z = normalize( z, this.array );
  17857. w = normalize( w, this.array );
  17858. }
  17859. this.data.array[ index + 0 ] = x;
  17860. this.data.array[ index + 1 ] = y;
  17861. this.data.array[ index + 2 ] = z;
  17862. this.data.array[ index + 3 ] = w;
  17863. return this;
  17864. }
  17865. /**
  17866. * Returns a new buffer attribute with copied values from this instance.
  17867. *
  17868. * If no parameter is provided, cloning an interleaved buffer attribute will de-interleave buffer data.
  17869. *
  17870. * @param {Object} [data] - An object with interleaved buffers that allows to retain the interleaved property.
  17871. * @return {BufferAttribute|InterleavedBufferAttribute} A clone of this instance.
  17872. */
  17873. clone( data ) {
  17874. if ( data === undefined ) {
  17875. log( 'InterleavedBufferAttribute.clone(): Cloning an interleaved buffer attribute will de-interleave buffer data.' );
  17876. const array = [];
  17877. for ( let i = 0; i < this.count; i ++ ) {
  17878. const index = i * this.data.stride + this.offset;
  17879. for ( let j = 0; j < this.itemSize; j ++ ) {
  17880. array.push( this.data.array[ index + j ] );
  17881. }
  17882. }
  17883. return new BufferAttribute( new this.array.constructor( array ), this.itemSize, this.normalized );
  17884. } else {
  17885. if ( data.interleavedBuffers === undefined ) {
  17886. data.interleavedBuffers = {};
  17887. }
  17888. if ( data.interleavedBuffers[ this.data.uuid ] === undefined ) {
  17889. data.interleavedBuffers[ this.data.uuid ] = this.data.clone( data );
  17890. }
  17891. return new InterleavedBufferAttribute( data.interleavedBuffers[ this.data.uuid ], this.itemSize, this.offset, this.normalized );
  17892. }
  17893. }
  17894. /**
  17895. * Serializes the buffer attribute into JSON.
  17896. *
  17897. * If no parameter is provided, cloning an interleaved buffer attribute will de-interleave buffer data.
  17898. *
  17899. * @param {Object} [data] - An optional value holding meta information about the serialization.
  17900. * @return {Object} A JSON object representing the serialized buffer attribute.
  17901. */
  17902. toJSON( data ) {
  17903. if ( data === undefined ) {
  17904. log( 'InterleavedBufferAttribute.toJSON(): Serializing an interleaved buffer attribute will de-interleave buffer data.' );
  17905. const array = [];
  17906. for ( let i = 0; i < this.count; i ++ ) {
  17907. const index = i * this.data.stride + this.offset;
  17908. for ( let j = 0; j < this.itemSize; j ++ ) {
  17909. array.push( this.data.array[ index + j ] );
  17910. }
  17911. }
  17912. // de-interleave data and save it as an ordinary buffer attribute for now
  17913. return {
  17914. itemSize: this.itemSize,
  17915. type: this.array.constructor.name,
  17916. array: array,
  17917. normalized: this.normalized
  17918. };
  17919. } else {
  17920. // save as true interleaved attribute
  17921. if ( data.interleavedBuffers === undefined ) {
  17922. data.interleavedBuffers = {};
  17923. }
  17924. if ( data.interleavedBuffers[ this.data.uuid ] === undefined ) {
  17925. data.interleavedBuffers[ this.data.uuid ] = this.data.toJSON( data );
  17926. }
  17927. return {
  17928. isInterleavedBufferAttribute: true,
  17929. itemSize: this.itemSize,
  17930. data: this.data.uuid,
  17931. offset: this.offset,
  17932. normalized: this.normalized
  17933. };
  17934. }
  17935. }
  17936. }
  17937. /**
  17938. * A material for rendering instances of {@link Sprite}.
  17939. *
  17940. * ```js
  17941. * const map = new THREE.TextureLoader().load( 'textures/sprite.png' );
  17942. * const material = new THREE.SpriteMaterial( { map: map, color: 0xffffff } );
  17943. *
  17944. * const sprite = new THREE.Sprite( material );
  17945. * sprite.scale.set(200, 200, 1)
  17946. * scene.add( sprite );
  17947. * ```
  17948. *
  17949. * @augments Material
  17950. */
  17951. class SpriteMaterial extends Material {
  17952. /**
  17953. * Constructs a new sprite material.
  17954. *
  17955. * @param {Object} [parameters] - An object with one or more properties
  17956. * defining the material's appearance. Any property of the material
  17957. * (including any property from inherited materials) can be passed
  17958. * in here. Color values can be passed any type of value accepted
  17959. * by {@link Color#set}.
  17960. */
  17961. constructor( parameters ) {
  17962. super();
  17963. /**
  17964. * This flag can be used for type testing.
  17965. *
  17966. * @type {boolean}
  17967. * @readonly
  17968. * @default true
  17969. */
  17970. this.isSpriteMaterial = true;
  17971. this.type = 'SpriteMaterial';
  17972. /**
  17973. * Color of the material.
  17974. *
  17975. * @type {Color}
  17976. * @default (1,1,1)
  17977. */
  17978. this.color = new Color( 0xffffff );
  17979. /**
  17980. * The color map. May optionally include an alpha channel, typically combined
  17981. * with {@link Material#transparent} or {@link Material#alphaTest}. The texture map
  17982. * color is modulated by the diffuse `color`.
  17983. *
  17984. * @type {?Texture}
  17985. * @default null
  17986. */
  17987. this.map = null;
  17988. /**
  17989. * The alpha map is a grayscale texture that controls the opacity across the
  17990. * surface (black: fully transparent; white: fully opaque).
  17991. *
  17992. * Only the color of the texture is used, ignoring the alpha channel if one
  17993. * exists. For RGB and RGBA textures, the renderer will use the green channel
  17994. * when sampling this texture due to the extra bit of precision provided for
  17995. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  17996. * luminance/alpha textures will also still work as expected.
  17997. *
  17998. * @type {?Texture}
  17999. * @default null
  18000. */
  18001. this.alphaMap = null;
  18002. /**
  18003. * The rotation of the sprite in radians.
  18004. *
  18005. * @type {number}
  18006. * @default 0
  18007. */
  18008. this.rotation = 0;
  18009. /**
  18010. * Specifies whether size of the sprite is attenuated by the camera depth (perspective camera only).
  18011. *
  18012. * @type {boolean}
  18013. * @default true
  18014. */
  18015. this.sizeAttenuation = true;
  18016. /**
  18017. * Overwritten since sprite materials are transparent
  18018. * by default.
  18019. *
  18020. * @type {boolean}
  18021. * @default true
  18022. */
  18023. this.transparent = true;
  18024. /**
  18025. * Whether the material is affected by fog or not.
  18026. *
  18027. * @type {boolean}
  18028. * @default true
  18029. */
  18030. this.fog = true;
  18031. this.setValues( parameters );
  18032. }
  18033. copy( source ) {
  18034. super.copy( source );
  18035. this.color.copy( source.color );
  18036. this.map = source.map;
  18037. this.alphaMap = source.alphaMap;
  18038. this.rotation = source.rotation;
  18039. this.sizeAttenuation = source.sizeAttenuation;
  18040. this.fog = source.fog;
  18041. return this;
  18042. }
  18043. }
  18044. let _geometry;
  18045. const _intersectPoint = /*@__PURE__*/ new Vector3();
  18046. const _worldScale = /*@__PURE__*/ new Vector3();
  18047. const _mvPosition = /*@__PURE__*/ new Vector3();
  18048. const _alignedPosition = /*@__PURE__*/ new Vector2();
  18049. const _rotatedPosition = /*@__PURE__*/ new Vector2();
  18050. const _viewWorldMatrix = /*@__PURE__*/ new Matrix4();
  18051. const _vA = /*@__PURE__*/ new Vector3();
  18052. const _vB = /*@__PURE__*/ new Vector3();
  18053. const _vC = /*@__PURE__*/ new Vector3();
  18054. const _uvA = /*@__PURE__*/ new Vector2();
  18055. const _uvB = /*@__PURE__*/ new Vector2();
  18056. const _uvC = /*@__PURE__*/ new Vector2();
  18057. /**
  18058. * A sprite is a plane that always faces towards the camera, generally with a
  18059. * partially transparent texture applied.
  18060. *
  18061. * Sprites do not cast shadows, setting {@link Object3D#castShadow} to `true` will
  18062. * have no effect.
  18063. *
  18064. * ```js
  18065. * const map = new THREE.TextureLoader().load( 'sprite.png' );
  18066. * const material = new THREE.SpriteMaterial( { map: map } );
  18067. *
  18068. * const sprite = new THREE.Sprite( material );
  18069. * scene.add( sprite );
  18070. * ```
  18071. *
  18072. * @augments Object3D
  18073. */
  18074. class Sprite extends Object3D {
  18075. /**
  18076. * Constructs a new sprite.
  18077. *
  18078. * @param {(SpriteMaterial|SpriteNodeMaterial)} [material] - The sprite material.
  18079. */
  18080. constructor( material = new SpriteMaterial() ) {
  18081. super();
  18082. /**
  18083. * This flag can be used for type testing.
  18084. *
  18085. * @type {boolean}
  18086. * @readonly
  18087. * @default true
  18088. */
  18089. this.isSprite = true;
  18090. this.type = 'Sprite';
  18091. if ( _geometry === undefined ) {
  18092. _geometry = new BufferGeometry();
  18093. const float32Array = new Float32Array( [
  18094. -0.5, -0.5, 0, 0, 0,
  18095. 0.5, -0.5, 0, 1, 0,
  18096. 0.5, 0.5, 0, 1, 1,
  18097. -0.5, 0.5, 0, 0, 1
  18098. ] );
  18099. const interleavedBuffer = new InterleavedBuffer( float32Array, 5 );
  18100. _geometry.setIndex( [ 0, 1, 2, 0, 2, 3 ] );
  18101. _geometry.setAttribute( 'position', new InterleavedBufferAttribute( interleavedBuffer, 3, 0, false ) );
  18102. _geometry.setAttribute( 'uv', new InterleavedBufferAttribute( interleavedBuffer, 2, 3, false ) );
  18103. }
  18104. /**
  18105. * The sprite geometry.
  18106. *
  18107. * @type {BufferGeometry}
  18108. */
  18109. this.geometry = _geometry;
  18110. /**
  18111. * The sprite material.
  18112. *
  18113. * @type {(SpriteMaterial|SpriteNodeMaterial)}
  18114. */
  18115. this.material = material;
  18116. /**
  18117. * The sprite's anchor point, and the point around which the sprite rotates.
  18118. * A value of `(0.5, 0.5)` corresponds to the midpoint of the sprite. A value
  18119. * of `(0, 0)` corresponds to the lower left corner of the sprite.
  18120. *
  18121. * @type {Vector2}
  18122. * @default (0.5,0.5)
  18123. */
  18124. this.center = new Vector2( 0.5, 0.5 );
  18125. /**
  18126. * The number of instances of this sprite.
  18127. * Can only be used with {@link WebGPURenderer}.
  18128. *
  18129. * @type {number}
  18130. * @default 1
  18131. */
  18132. this.count = 1;
  18133. }
  18134. /**
  18135. * Computes intersection points between a casted ray and this sprite.
  18136. *
  18137. * @param {Raycaster} raycaster - The raycaster.
  18138. * @param {Array<Object>} intersects - The target array that holds the intersection points.
  18139. */
  18140. raycast( raycaster, intersects ) {
  18141. if ( raycaster.camera === null ) {
  18142. error( 'Sprite: "Raycaster.camera" needs to be set in order to raycast against sprites.' );
  18143. }
  18144. _worldScale.setFromMatrixScale( this.matrixWorld );
  18145. _viewWorldMatrix.copy( raycaster.camera.matrixWorld );
  18146. this.modelViewMatrix.multiplyMatrices( raycaster.camera.matrixWorldInverse, this.matrixWorld );
  18147. _mvPosition.setFromMatrixPosition( this.modelViewMatrix );
  18148. if ( raycaster.camera.isPerspectiveCamera && this.material.sizeAttenuation === false ) {
  18149. _worldScale.multiplyScalar( - _mvPosition.z );
  18150. }
  18151. const rotation = this.material.rotation;
  18152. let sin, cos;
  18153. if ( rotation !== 0 ) {
  18154. cos = Math.cos( rotation );
  18155. sin = Math.sin( rotation );
  18156. }
  18157. const center = this.center;
  18158. transformVertex( _vA.set( -0.5, -0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  18159. transformVertex( _vB.set( 0.5, -0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  18160. transformVertex( _vC.set( 0.5, 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  18161. _uvA.set( 0, 0 );
  18162. _uvB.set( 1, 0 );
  18163. _uvC.set( 1, 1 );
  18164. // check first triangle
  18165. let intersect = raycaster.ray.intersectTriangle( _vA, _vB, _vC, false, _intersectPoint );
  18166. if ( intersect === null ) {
  18167. // check second triangle
  18168. transformVertex( _vB.set( -0.5, 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  18169. _uvB.set( 0, 1 );
  18170. intersect = raycaster.ray.intersectTriangle( _vA, _vC, _vB, false, _intersectPoint );
  18171. if ( intersect === null ) {
  18172. return;
  18173. }
  18174. }
  18175. const distance = raycaster.ray.origin.distanceTo( _intersectPoint );
  18176. if ( distance < raycaster.near || distance > raycaster.far ) return;
  18177. intersects.push( {
  18178. distance: distance,
  18179. point: _intersectPoint.clone(),
  18180. uv: Triangle.getInterpolation( _intersectPoint, _vA, _vB, _vC, _uvA, _uvB, _uvC, new Vector2() ),
  18181. face: null,
  18182. object: this
  18183. } );
  18184. }
  18185. copy( source, recursive ) {
  18186. super.copy( source, recursive );
  18187. if ( source.center !== undefined ) this.center.copy( source.center );
  18188. this.material = source.material;
  18189. return this;
  18190. }
  18191. }
  18192. function transformVertex( vertexPosition, mvPosition, center, scale, sin, cos ) {
  18193. // compute position in camera space
  18194. _alignedPosition.subVectors( vertexPosition, center ).addScalar( 0.5 ).multiply( scale );
  18195. // to check if rotation is not zero
  18196. if ( sin !== undefined ) {
  18197. _rotatedPosition.x = ( cos * _alignedPosition.x ) - ( sin * _alignedPosition.y );
  18198. _rotatedPosition.y = ( sin * _alignedPosition.x ) + ( cos * _alignedPosition.y );
  18199. } else {
  18200. _rotatedPosition.copy( _alignedPosition );
  18201. }
  18202. vertexPosition.copy( mvPosition );
  18203. vertexPosition.x += _rotatedPosition.x;
  18204. vertexPosition.y += _rotatedPosition.y;
  18205. // transform to world space
  18206. vertexPosition.applyMatrix4( _viewWorldMatrix );
  18207. }
  18208. const _v1$2 = /*@__PURE__*/ new Vector3();
  18209. const _v2$1 = /*@__PURE__*/ new Vector3();
  18210. /**
  18211. * A component for providing a basic Level of Detail (LOD) mechanism.
  18212. *
  18213. * Every LOD level is associated with an object, and rendering can be switched
  18214. * between them at the distances specified. Typically you would create, say,
  18215. * three meshes, one for far away (low detail), one for mid range (medium
  18216. * detail) and one for close up (high detail).
  18217. *
  18218. * ```js
  18219. * const lod = new THREE.LOD();
  18220. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  18221. *
  18222. * //Create spheres with 3 levels of detail and create new LOD levels for them
  18223. * for( let i = 0; i < 3; i++ ) {
  18224. *
  18225. * const geometry = new THREE.IcosahedronGeometry( 10, 3 - i );
  18226. * const mesh = new THREE.Mesh( geometry, material );
  18227. * lod.addLevel( mesh, i * 75 );
  18228. *
  18229. * }
  18230. *
  18231. * scene.add( lod );
  18232. * ```
  18233. *
  18234. * @augments Object3D
  18235. */
  18236. class LOD extends Object3D {
  18237. /**
  18238. * Constructs a new LOD.
  18239. */
  18240. constructor() {
  18241. super();
  18242. /**
  18243. * This flag can be used for type testing.
  18244. *
  18245. * @type {boolean}
  18246. * @readonly
  18247. * @default true
  18248. */
  18249. this.isLOD = true;
  18250. /**
  18251. * The current LOD index.
  18252. *
  18253. * @private
  18254. * @type {number}
  18255. * @default 0
  18256. */
  18257. this._currentLevel = 0;
  18258. this.type = 'LOD';
  18259. Object.defineProperties( this, {
  18260. /**
  18261. * This array holds the LOD levels.
  18262. *
  18263. * @name LOD#levels
  18264. * @type {Array<{object:Object3D,distance:number,hysteresis:number}>}
  18265. */
  18266. levels: {
  18267. enumerable: true,
  18268. value: []
  18269. }
  18270. } );
  18271. /**
  18272. * Whether the LOD object is updated automatically by the renderer per frame
  18273. * or not. If set to `false`, you have to call {@link LOD#update} in the
  18274. * render loop by yourself.
  18275. *
  18276. * @type {boolean}
  18277. * @default true
  18278. */
  18279. this.autoUpdate = true;
  18280. }
  18281. copy( source ) {
  18282. super.copy( source, false );
  18283. const levels = source.levels;
  18284. for ( let i = 0, l = levels.length; i < l; i ++ ) {
  18285. const level = levels[ i ];
  18286. this.addLevel( level.object.clone(), level.distance, level.hysteresis );
  18287. }
  18288. this.autoUpdate = source.autoUpdate;
  18289. return this;
  18290. }
  18291. /**
  18292. * Adds a mesh that will display at a certain distance and greater. Typically
  18293. * the further away the distance, the lower the detail on the mesh.
  18294. *
  18295. * @param {Object3D} object - The 3D object to display at this level.
  18296. * @param {number} [distance=0] - The distance at which to display this level of detail.
  18297. * @param {number} [hysteresis=0] - Threshold used to avoid flickering at LOD boundaries, as a fraction of distance.
  18298. * @return {LOD} A reference to this instance.
  18299. */
  18300. addLevel( object, distance = 0, hysteresis = 0 ) {
  18301. distance = Math.abs( distance );
  18302. const levels = this.levels;
  18303. let l;
  18304. for ( l = 0; l < levels.length; l ++ ) {
  18305. if ( distance < levels[ l ].distance ) {
  18306. break;
  18307. }
  18308. }
  18309. levels.splice( l, 0, { distance: distance, hysteresis: hysteresis, object: object } );
  18310. this.add( object );
  18311. return this;
  18312. }
  18313. /**
  18314. * Removes an existing level, based on the distance from the camera.
  18315. * Returns `true` when the level has been removed. Otherwise `false`.
  18316. *
  18317. * @param {number} distance - Distance of the level to remove.
  18318. * @return {boolean} Whether the level has been removed or not.
  18319. */
  18320. removeLevel( distance ) {
  18321. const levels = this.levels;
  18322. for ( let i = 0; i < levels.length; i ++ ) {
  18323. if ( levels[ i ].distance === distance ) {
  18324. const removedElements = levels.splice( i, 1 );
  18325. this.remove( removedElements[ 0 ].object );
  18326. return true;
  18327. }
  18328. }
  18329. return false;
  18330. }
  18331. /**
  18332. * Returns the currently active LOD level index.
  18333. *
  18334. * @return {number} The current active LOD level index.
  18335. */
  18336. getCurrentLevel() {
  18337. return this._currentLevel;
  18338. }
  18339. /**
  18340. * Returns a reference to the first 3D object that is greater than
  18341. * the given distance.
  18342. *
  18343. * @param {number} distance - The LOD distance.
  18344. * @return {?Object3D} The found 3D object. `null` if no 3D object has been found.
  18345. */
  18346. getObjectForDistance( distance ) {
  18347. const levels = this.levels;
  18348. if ( levels.length > 0 ) {
  18349. let i, l;
  18350. for ( i = 1, l = levels.length; i < l; i ++ ) {
  18351. let levelDistance = levels[ i ].distance;
  18352. if ( levels[ i ].object.visible ) {
  18353. levelDistance -= levelDistance * levels[ i ].hysteresis;
  18354. }
  18355. if ( distance < levelDistance ) {
  18356. break;
  18357. }
  18358. }
  18359. return levels[ i - 1 ].object;
  18360. }
  18361. return null;
  18362. }
  18363. /**
  18364. * Computes intersection points between a casted ray and this LOD.
  18365. *
  18366. * @param {Raycaster} raycaster - The raycaster.
  18367. * @param {Array<Object>} intersects - The target array that holds the intersection points.
  18368. */
  18369. raycast( raycaster, intersects ) {
  18370. const levels = this.levels;
  18371. if ( levels.length > 0 ) {
  18372. _v1$2.setFromMatrixPosition( this.matrixWorld );
  18373. const distance = raycaster.ray.origin.distanceTo( _v1$2 );
  18374. this.getObjectForDistance( distance ).raycast( raycaster, intersects );
  18375. }
  18376. }
  18377. /**
  18378. * Updates the LOD by computing which LOD level should be visible according
  18379. * to the current distance of the given camera.
  18380. *
  18381. * @param {Camera} camera - The camera the scene is rendered with.
  18382. */
  18383. update( camera ) {
  18384. const levels = this.levels;
  18385. if ( levels.length > 1 ) {
  18386. _v1$2.setFromMatrixPosition( camera.matrixWorld );
  18387. _v2$1.setFromMatrixPosition( this.matrixWorld );
  18388. const distance = _v1$2.distanceTo( _v2$1 ) / camera.zoom;
  18389. levels[ 0 ].object.visible = true;
  18390. let i, l;
  18391. for ( i = 1, l = levels.length; i < l; i ++ ) {
  18392. let levelDistance = levels[ i ].distance;
  18393. if ( levels[ i ].object.visible ) {
  18394. levelDistance -= levelDistance * levels[ i ].hysteresis;
  18395. }
  18396. if ( distance >= levelDistance ) {
  18397. levels[ i - 1 ].object.visible = false;
  18398. levels[ i ].object.visible = true;
  18399. } else {
  18400. break;
  18401. }
  18402. }
  18403. this._currentLevel = i - 1;
  18404. for ( ; i < l; i ++ ) {
  18405. levels[ i ].object.visible = false;
  18406. }
  18407. }
  18408. }
  18409. toJSON( meta ) {
  18410. const data = super.toJSON( meta );
  18411. if ( this.autoUpdate === false ) data.object.autoUpdate = false;
  18412. data.object.levels = [];
  18413. const levels = this.levels;
  18414. for ( let i = 0, l = levels.length; i < l; i ++ ) {
  18415. const level = levels[ i ];
  18416. data.object.levels.push( {
  18417. object: level.object.uuid,
  18418. distance: level.distance,
  18419. hysteresis: level.hysteresis
  18420. } );
  18421. }
  18422. return data;
  18423. }
  18424. }
  18425. const _basePosition = /*@__PURE__*/ new Vector3();
  18426. const _skinIndex = /*@__PURE__*/ new Vector4();
  18427. const _skinWeight = /*@__PURE__*/ new Vector4();
  18428. const _vector3 = /*@__PURE__*/ new Vector3();
  18429. const _matrix4 = /*@__PURE__*/ new Matrix4();
  18430. const _vertex = /*@__PURE__*/ new Vector3();
  18431. const _sphere$5 = /*@__PURE__*/ new Sphere();
  18432. const _inverseMatrix$2 = /*@__PURE__*/ new Matrix4();
  18433. const _ray$2 = /*@__PURE__*/ new Ray();
  18434. /**
  18435. * A mesh that has a {@link Skeleton} that can then be used to animate the
  18436. * vertices of the geometry with skinning/skeleton animation.
  18437. *
  18438. * Next to a valid skeleton, the skinned mesh requires skin indices and weights
  18439. * as buffer attributes in its geometry. These attribute define which bones affect a single
  18440. * vertex to a certain extend.
  18441. *
  18442. * Typically skinned meshes are not created manually but loaders like {@link GLTFLoader}
  18443. * or {@link FBXLoader } import respective models.
  18444. *
  18445. * @augments Mesh
  18446. * @demo scenes/bones-browser.html
  18447. */
  18448. class SkinnedMesh extends Mesh {
  18449. /**
  18450. * Constructs a new skinned mesh.
  18451. *
  18452. * @param {BufferGeometry} [geometry] - The mesh geometry.
  18453. * @param {Material|Array<Material>} [material] - The mesh material.
  18454. */
  18455. constructor( geometry, material ) {
  18456. super( geometry, material );
  18457. /**
  18458. * This flag can be used for type testing.
  18459. *
  18460. * @type {boolean}
  18461. * @readonly
  18462. * @default true
  18463. */
  18464. this.isSkinnedMesh = true;
  18465. this.type = 'SkinnedMesh';
  18466. /**
  18467. * `AttachedBindMode` means the skinned mesh shares the same world space as the skeleton.
  18468. * This is not true when using `DetachedBindMode` which is useful when sharing a skeleton
  18469. * across multiple skinned meshes.
  18470. *
  18471. * @type {(AttachedBindMode|DetachedBindMode)}
  18472. * @default AttachedBindMode
  18473. */
  18474. this.bindMode = AttachedBindMode;
  18475. /**
  18476. * The base matrix that is used for the bound bone transforms.
  18477. *
  18478. * @type {Matrix4}
  18479. */
  18480. this.bindMatrix = new Matrix4();
  18481. /**
  18482. * The base matrix that is used for resetting the bound bone transforms.
  18483. *
  18484. * @type {Matrix4}
  18485. */
  18486. this.bindMatrixInverse = new Matrix4();
  18487. /**
  18488. * The bounding box of the skinned mesh. Can be computed via {@link SkinnedMesh#computeBoundingBox}.
  18489. *
  18490. * @type {?Box3}
  18491. * @default null
  18492. */
  18493. this.boundingBox = null;
  18494. /**
  18495. * The bounding sphere of the skinned mesh. Can be computed via {@link SkinnedMesh#computeBoundingSphere}.
  18496. *
  18497. * @type {?Sphere}
  18498. * @default null
  18499. */
  18500. this.boundingSphere = null;
  18501. }
  18502. /**
  18503. * Computes the bounding box of the skinned mesh, and updates {@link SkinnedMesh#boundingBox}.
  18504. * The bounding box is not automatically computed by the engine; this method must be called by your app.
  18505. * If the skinned mesh is animated, the bounding box should be recomputed per frame in order to reflect
  18506. * the current animation state.
  18507. */
  18508. computeBoundingBox() {
  18509. const geometry = this.geometry;
  18510. if ( this.boundingBox === null ) {
  18511. this.boundingBox = new Box3();
  18512. }
  18513. this.boundingBox.makeEmpty();
  18514. const positionAttribute = geometry.getAttribute( 'position' );
  18515. for ( let i = 0; i < positionAttribute.count; i ++ ) {
  18516. this.getVertexPosition( i, _vertex );
  18517. this.boundingBox.expandByPoint( _vertex );
  18518. }
  18519. }
  18520. /**
  18521. * Computes the bounding sphere of the skinned mesh, and updates {@link SkinnedMesh#boundingSphere}.
  18522. * The bounding sphere is automatically computed by the engine once when it is needed, e.g., for ray casting
  18523. * and view frustum culling. If the skinned mesh is animated, the bounding sphere should be recomputed
  18524. * per frame in order to reflect the current animation state.
  18525. */
  18526. computeBoundingSphere() {
  18527. const geometry = this.geometry;
  18528. if ( this.boundingSphere === null ) {
  18529. this.boundingSphere = new Sphere();
  18530. }
  18531. this.boundingSphere.makeEmpty();
  18532. const positionAttribute = geometry.getAttribute( 'position' );
  18533. for ( let i = 0; i < positionAttribute.count; i ++ ) {
  18534. this.getVertexPosition( i, _vertex );
  18535. this.boundingSphere.expandByPoint( _vertex );
  18536. }
  18537. }
  18538. copy( source, recursive ) {
  18539. super.copy( source, recursive );
  18540. this.bindMode = source.bindMode;
  18541. this.bindMatrix.copy( source.bindMatrix );
  18542. this.bindMatrixInverse.copy( source.bindMatrixInverse );
  18543. this.skeleton = source.skeleton;
  18544. if ( source.boundingBox !== null ) this.boundingBox = source.boundingBox.clone();
  18545. if ( source.boundingSphere !== null ) this.boundingSphere = source.boundingSphere.clone();
  18546. return this;
  18547. }
  18548. raycast( raycaster, intersects ) {
  18549. const material = this.material;
  18550. const matrixWorld = this.matrixWorld;
  18551. if ( material === undefined ) return;
  18552. // test with bounding sphere in world space
  18553. if ( this.boundingSphere === null ) this.computeBoundingSphere();
  18554. _sphere$5.copy( this.boundingSphere );
  18555. _sphere$5.applyMatrix4( matrixWorld );
  18556. if ( raycaster.ray.intersectsSphere( _sphere$5 ) === false ) return;
  18557. // convert ray to local space of skinned mesh
  18558. _inverseMatrix$2.copy( matrixWorld ).invert();
  18559. _ray$2.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$2 );
  18560. // test with bounding box in local space
  18561. if ( this.boundingBox !== null ) {
  18562. if ( _ray$2.intersectsBox( this.boundingBox ) === false ) return;
  18563. }
  18564. // test for intersections with geometry
  18565. this._computeIntersections( raycaster, intersects, _ray$2 );
  18566. }
  18567. getVertexPosition( index, target ) {
  18568. super.getVertexPosition( index, target );
  18569. this.applyBoneTransform( index, target );
  18570. return target;
  18571. }
  18572. /**
  18573. * Binds the given skeleton to the skinned mesh.
  18574. *
  18575. * @param {Skeleton} skeleton - The skeleton to bind.
  18576. * @param {Matrix4} [bindMatrix] - The bind matrix. If no bind matrix is provided,
  18577. * the skinned mesh's world matrix will be used instead.
  18578. */
  18579. bind( skeleton, bindMatrix ) {
  18580. this.skeleton = skeleton;
  18581. if ( bindMatrix === undefined ) {
  18582. this.updateMatrixWorld( true );
  18583. this.skeleton.calculateInverses();
  18584. bindMatrix = this.matrixWorld;
  18585. }
  18586. this.bindMatrix.copy( bindMatrix );
  18587. this.bindMatrixInverse.copy( bindMatrix ).invert();
  18588. }
  18589. /**
  18590. * This method sets the skinned mesh in the rest pose).
  18591. */
  18592. pose() {
  18593. this.skeleton.pose();
  18594. }
  18595. /**
  18596. * Normalizes the skin weights which are defined as a buffer attribute
  18597. * in the skinned mesh's geometry.
  18598. */
  18599. normalizeSkinWeights() {
  18600. const vector = new Vector4();
  18601. const skinWeight = this.geometry.attributes.skinWeight;
  18602. for ( let i = 0, l = skinWeight.count; i < l; i ++ ) {
  18603. vector.fromBufferAttribute( skinWeight, i );
  18604. const scale = 1.0 / vector.manhattanLength();
  18605. if ( scale !== Infinity ) {
  18606. vector.multiplyScalar( scale );
  18607. } else {
  18608. vector.set( 1, 0, 0, 0 ); // do something reasonable
  18609. }
  18610. skinWeight.setXYZW( i, vector.x, vector.y, vector.z, vector.w );
  18611. }
  18612. }
  18613. updateMatrixWorld( force ) {
  18614. super.updateMatrixWorld( force );
  18615. if ( this.bindMode === AttachedBindMode ) {
  18616. this.bindMatrixInverse.copy( this.matrixWorld ).invert();
  18617. } else if ( this.bindMode === DetachedBindMode ) {
  18618. this.bindMatrixInverse.copy( this.bindMatrix ).invert();
  18619. } else {
  18620. warn( 'SkinnedMesh: Unrecognized bindMode: ' + this.bindMode );
  18621. }
  18622. }
  18623. /**
  18624. * Applies the bone transform associated with the given index to the given
  18625. * vertex position. Returns the updated vector.
  18626. *
  18627. * @param {number} index - The vertex index.
  18628. * @param {Vector3} target - The target object that is used to store the method's result.
  18629. * the skinned mesh's world matrix will be used instead.
  18630. * @return {Vector3} The updated vertex position.
  18631. */
  18632. applyBoneTransform( index, target ) {
  18633. const skeleton = this.skeleton;
  18634. const geometry = this.geometry;
  18635. _skinIndex.fromBufferAttribute( geometry.attributes.skinIndex, index );
  18636. _skinWeight.fromBufferAttribute( geometry.attributes.skinWeight, index );
  18637. _basePosition.copy( target ).applyMatrix4( this.bindMatrix );
  18638. target.set( 0, 0, 0 );
  18639. for ( let i = 0; i < 4; i ++ ) {
  18640. const weight = _skinWeight.getComponent( i );
  18641. if ( weight !== 0 ) {
  18642. const boneIndex = _skinIndex.getComponent( i );
  18643. _matrix4.multiplyMatrices( skeleton.bones[ boneIndex ].matrixWorld, skeleton.boneInverses[ boneIndex ] );
  18644. target.addScaledVector( _vector3.copy( _basePosition ).applyMatrix4( _matrix4 ), weight );
  18645. }
  18646. }
  18647. return target.applyMatrix4( this.bindMatrixInverse );
  18648. }
  18649. }
  18650. /**
  18651. * A bone which is part of a {@link Skeleton}. The skeleton in turn is used by
  18652. * the {@link SkinnedMesh}.
  18653. *
  18654. * ```js
  18655. * const root = new THREE.Bone();
  18656. * const child = new THREE.Bone();
  18657. *
  18658. * root.add( child );
  18659. * child.position.y = 5;
  18660. * ```
  18661. *
  18662. * @augments Object3D
  18663. */
  18664. class Bone extends Object3D {
  18665. /**
  18666. * Constructs a new bone.
  18667. */
  18668. constructor() {
  18669. super();
  18670. /**
  18671. * This flag can be used for type testing.
  18672. *
  18673. * @type {boolean}
  18674. * @readonly
  18675. * @default true
  18676. */
  18677. this.isBone = true;
  18678. this.type = 'Bone';
  18679. }
  18680. }
  18681. /**
  18682. * Creates a texture directly from raw buffer data.
  18683. *
  18684. * The interpretation of the data depends on type and format: If the type is
  18685. * `UnsignedByteType`, a `Uint8Array` will be useful for addressing the
  18686. * texel data. If the format is `RGBAFormat`, data needs four values for
  18687. * one texel; Red, Green, Blue and Alpha (typically the opacity).
  18688. *
  18689. * @augments Texture
  18690. */
  18691. class DataTexture extends Texture {
  18692. /**
  18693. * Constructs a new data texture.
  18694. *
  18695. * @param {?TypedArray} [data=null] - The buffer data.
  18696. * @param {number} [width=1] - The width of the texture.
  18697. * @param {number} [height=1] - The height of the texture.
  18698. * @param {number} [format=RGBAFormat] - The texture format.
  18699. * @param {number} [type=UnsignedByteType] - The texture type.
  18700. * @param {number} [mapping=Texture.DEFAULT_MAPPING] - The texture mapping.
  18701. * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value.
  18702. * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value.
  18703. * @param {number} [magFilter=NearestFilter] - The mag filter value.
  18704. * @param {number} [minFilter=NearestFilter] - The min filter value.
  18705. * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value.
  18706. * @param {string} [colorSpace=NoColorSpace] - The color space.
  18707. */
  18708. constructor( data = null, width = 1, height = 1, format, type, mapping, wrapS, wrapT, magFilter = NearestFilter, minFilter = NearestFilter, anisotropy, colorSpace ) {
  18709. super( null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace );
  18710. /**
  18711. * This flag can be used for type testing.
  18712. *
  18713. * @type {boolean}
  18714. * @readonly
  18715. * @default true
  18716. */
  18717. this.isDataTexture = true;
  18718. /**
  18719. * The image definition of a data texture.
  18720. *
  18721. * @type {{data:TypedArray,width:number,height:number}}
  18722. */
  18723. this.image = { data: data, width: width, height: height };
  18724. /**
  18725. * Whether to generate mipmaps (if possible) for a texture.
  18726. *
  18727. * Overwritten and set to `false` by default.
  18728. *
  18729. * @type {boolean}
  18730. * @default false
  18731. */
  18732. this.generateMipmaps = false;
  18733. /**
  18734. * If set to `true`, the texture is flipped along the vertical axis when
  18735. * uploaded to the GPU.
  18736. *
  18737. * Overwritten and set to `false` by default.
  18738. *
  18739. * @type {boolean}
  18740. * @default false
  18741. */
  18742. this.flipY = false;
  18743. /**
  18744. * Specifies the alignment requirements for the start of each pixel row in memory.
  18745. *
  18746. * Overwritten and set to `1` by default.
  18747. *
  18748. * @type {boolean}
  18749. * @default 1
  18750. */
  18751. this.unpackAlignment = 1;
  18752. }
  18753. }
  18754. const _offsetMatrix = /*@__PURE__*/ new Matrix4();
  18755. const _identityMatrix = /*@__PURE__*/ new Matrix4();
  18756. /**
  18757. * Class for representing the armatures in `three.js`. The skeleton
  18758. * is defined by a hierarchy of bones.
  18759. *
  18760. * ```js
  18761. * const bones = [];
  18762. *
  18763. * const shoulder = new THREE.Bone();
  18764. * const elbow = new THREE.Bone();
  18765. * const hand = new THREE.Bone();
  18766. *
  18767. * shoulder.add( elbow );
  18768. * elbow.add( hand );
  18769. *
  18770. * bones.push( shoulder , elbow, hand);
  18771. *
  18772. * shoulder.position.y = -5;
  18773. * elbow.position.y = 0;
  18774. * hand.position.y = 5;
  18775. *
  18776. * const armSkeleton = new THREE.Skeleton( bones );
  18777. * ```
  18778. */
  18779. class Skeleton {
  18780. /**
  18781. * Constructs a new skeleton.
  18782. *
  18783. * @param {Array<Bone>} [bones] - An array of bones.
  18784. * @param {Array<Matrix4>} [boneInverses] - An array of bone inverse matrices.
  18785. * If not provided, these matrices will be computed automatically via {@link Skeleton#calculateInverses}.
  18786. */
  18787. constructor( bones = [], boneInverses = [] ) {
  18788. this.uuid = generateUUID();
  18789. /**
  18790. * An array of bones defining the skeleton.
  18791. *
  18792. * @type {Array<Bone>}
  18793. */
  18794. this.bones = bones.slice( 0 );
  18795. /**
  18796. * An array of bone inverse matrices.
  18797. *
  18798. * @type {Array<Matrix4>}
  18799. */
  18800. this.boneInverses = boneInverses;
  18801. /**
  18802. * An array buffer holding the bone data.
  18803. * Input data for {@link Skeleton#boneTexture}.
  18804. *
  18805. * @type {?Float32Array}
  18806. * @default null
  18807. */
  18808. this.boneMatrices = null;
  18809. /**
  18810. * An array buffer holding the bone data of the previous frame.
  18811. * Required for computing velocity. Maintained in {@link SkinningNode}.
  18812. *
  18813. * @type {?Float32Array}
  18814. * @default null
  18815. */
  18816. this.previousBoneMatrices = null;
  18817. /**
  18818. * A texture holding the bone data for use
  18819. * in the vertex shader.
  18820. *
  18821. * @type {?DataTexture}
  18822. * @default null
  18823. */
  18824. this.boneTexture = null;
  18825. this.init();
  18826. }
  18827. /**
  18828. * Initializes the skeleton. This method gets automatically called by the constructor
  18829. * but depending on how the skeleton is created it might be necessary to call this method
  18830. * manually.
  18831. */
  18832. init() {
  18833. const bones = this.bones;
  18834. const boneInverses = this.boneInverses;
  18835. this.boneMatrices = new Float32Array( bones.length * 16 );
  18836. // calculate inverse bone matrices if necessary
  18837. if ( boneInverses.length === 0 ) {
  18838. this.calculateInverses();
  18839. } else {
  18840. // handle special case
  18841. if ( bones.length !== boneInverses.length ) {
  18842. warn( 'Skeleton: Number of inverse bone matrices does not match amount of bones.' );
  18843. this.boneInverses = [];
  18844. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  18845. this.boneInverses.push( new Matrix4() );
  18846. }
  18847. }
  18848. }
  18849. }
  18850. /**
  18851. * Computes the bone inverse matrices. This method resets {@link Skeleton#boneInverses}
  18852. * and fills it with new matrices.
  18853. */
  18854. calculateInverses() {
  18855. this.boneInverses.length = 0;
  18856. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  18857. const inverse = new Matrix4();
  18858. if ( this.bones[ i ] ) {
  18859. inverse.copy( this.bones[ i ].matrixWorld ).invert();
  18860. }
  18861. this.boneInverses.push( inverse );
  18862. }
  18863. }
  18864. /**
  18865. * Resets the skeleton to the base pose.
  18866. */
  18867. pose() {
  18868. // recover the bind-time world matrices
  18869. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  18870. const bone = this.bones[ i ];
  18871. if ( bone ) {
  18872. bone.matrixWorld.copy( this.boneInverses[ i ] ).invert();
  18873. }
  18874. }
  18875. // compute the local matrices, positions, rotations and scales
  18876. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  18877. const bone = this.bones[ i ];
  18878. if ( bone ) {
  18879. if ( bone.parent && bone.parent.isBone ) {
  18880. bone.matrix.copy( bone.parent.matrixWorld ).invert();
  18881. bone.matrix.multiply( bone.matrixWorld );
  18882. } else {
  18883. bone.matrix.copy( bone.matrixWorld );
  18884. }
  18885. bone.matrix.decompose( bone.position, bone.quaternion, bone.scale );
  18886. }
  18887. }
  18888. }
  18889. /**
  18890. * Resets the skeleton to the base pose.
  18891. */
  18892. update() {
  18893. const bones = this.bones;
  18894. const boneInverses = this.boneInverses;
  18895. const boneMatrices = this.boneMatrices;
  18896. const boneTexture = this.boneTexture;
  18897. // flatten bone matrices to array
  18898. for ( let i = 0, il = bones.length; i < il; i ++ ) {
  18899. // compute the offset between the current and the original transform
  18900. const matrix = bones[ i ] ? bones[ i ].matrixWorld : _identityMatrix;
  18901. _offsetMatrix.multiplyMatrices( matrix, boneInverses[ i ] );
  18902. _offsetMatrix.toArray( boneMatrices, i * 16 );
  18903. }
  18904. if ( boneTexture !== null ) {
  18905. boneTexture.needsUpdate = true;
  18906. }
  18907. }
  18908. /**
  18909. * Returns a new skeleton with copied values from this instance.
  18910. *
  18911. * @return {Skeleton} A clone of this instance.
  18912. */
  18913. clone() {
  18914. return new Skeleton( this.bones, this.boneInverses );
  18915. }
  18916. /**
  18917. * Computes a data texture for passing bone data to the vertex shader.
  18918. *
  18919. * @return {Skeleton} A reference of this instance.
  18920. */
  18921. computeBoneTexture() {
  18922. // layout (1 matrix = 4 pixels)
  18923. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  18924. // with 8x8 pixel texture max 16 bones * 4 pixels = (8 * 8)
  18925. // 16x16 pixel texture max 64 bones * 4 pixels = (16 * 16)
  18926. // 32x32 pixel texture max 256 bones * 4 pixels = (32 * 32)
  18927. // 64x64 pixel texture max 1024 bones * 4 pixels = (64 * 64)
  18928. let size = Math.sqrt( this.bones.length * 4 ); // 4 pixels needed for 1 matrix
  18929. size = Math.ceil( size / 4 ) * 4;
  18930. size = Math.max( size, 4 );
  18931. const boneMatrices = new Float32Array( size * size * 4 ); // 4 floats per RGBA pixel
  18932. boneMatrices.set( this.boneMatrices ); // copy current values
  18933. const boneTexture = new DataTexture( boneMatrices, size, size, RGBAFormat, FloatType );
  18934. boneTexture.needsUpdate = true;
  18935. this.boneMatrices = boneMatrices;
  18936. this.boneTexture = boneTexture;
  18937. return this;
  18938. }
  18939. /**
  18940. * Searches through the skeleton's bone array and returns the first with a
  18941. * matching name.
  18942. *
  18943. * @param {string} name - The name of the bone.
  18944. * @return {Bone|undefined} The found bone. `undefined` if no bone has been found.
  18945. */
  18946. getBoneByName( name ) {
  18947. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  18948. const bone = this.bones[ i ];
  18949. if ( bone.name === name ) {
  18950. return bone;
  18951. }
  18952. }
  18953. return undefined;
  18954. }
  18955. /**
  18956. * Frees the GPU-related resources allocated by this instance. Call this
  18957. * method whenever this instance is no longer used in your app.
  18958. */
  18959. dispose( ) {
  18960. if ( this.boneTexture !== null ) {
  18961. this.boneTexture.dispose();
  18962. this.boneTexture = null;
  18963. }
  18964. }
  18965. /**
  18966. * Setups the skeleton by the given JSON and bones.
  18967. *
  18968. * @param {Object} json - The skeleton as serialized JSON.
  18969. * @param {Object<string, Bone>} bones - An array of bones.
  18970. * @return {Skeleton} A reference of this instance.
  18971. */
  18972. fromJSON( json, bones ) {
  18973. this.uuid = json.uuid;
  18974. for ( let i = 0, l = json.bones.length; i < l; i ++ ) {
  18975. const uuid = json.bones[ i ];
  18976. let bone = bones[ uuid ];
  18977. if ( bone === undefined ) {
  18978. warn( 'Skeleton: No bone found with UUID:', uuid );
  18979. bone = new Bone();
  18980. }
  18981. this.bones.push( bone );
  18982. this.boneInverses.push( new Matrix4().fromArray( json.boneInverses[ i ] ) );
  18983. }
  18984. this.init();
  18985. return this;
  18986. }
  18987. /**
  18988. * Serializes the skeleton into JSON.
  18989. *
  18990. * @return {Object} A JSON object representing the serialized skeleton.
  18991. * @see {@link ObjectLoader#parse}
  18992. */
  18993. toJSON() {
  18994. const data = {
  18995. metadata: {
  18996. version: 4.7,
  18997. type: 'Skeleton',
  18998. generator: 'Skeleton.toJSON'
  18999. },
  19000. bones: [],
  19001. boneInverses: []
  19002. };
  19003. data.uuid = this.uuid;
  19004. const bones = this.bones;
  19005. const boneInverses = this.boneInverses;
  19006. for ( let i = 0, l = bones.length; i < l; i ++ ) {
  19007. const bone = bones[ i ];
  19008. data.bones.push( bone.uuid );
  19009. const boneInverse = boneInverses[ i ];
  19010. data.boneInverses.push( boneInverse.toArray() );
  19011. }
  19012. return data;
  19013. }
  19014. }
  19015. /**
  19016. * An instanced version of a buffer attribute.
  19017. *
  19018. * @augments BufferAttribute
  19019. */
  19020. class InstancedBufferAttribute extends BufferAttribute {
  19021. /**
  19022. * Constructs a new instanced buffer attribute.
  19023. *
  19024. * @param {TypedArray} array - The array holding the attribute data.
  19025. * @param {number} itemSize - The item size.
  19026. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  19027. * @param {number} [meshPerAttribute=1] - How often a value of this buffer attribute should be repeated.
  19028. */
  19029. constructor( array, itemSize, normalized, meshPerAttribute = 1 ) {
  19030. super( array, itemSize, normalized );
  19031. /**
  19032. * This flag can be used for type testing.
  19033. *
  19034. * @type {boolean}
  19035. * @readonly
  19036. * @default true
  19037. */
  19038. this.isInstancedBufferAttribute = true;
  19039. /**
  19040. * Defines how often a value of this buffer attribute should be repeated. A
  19041. * value of one means that each value of the instanced attribute is used for
  19042. * a single instance. A value of two means that each value is used for two
  19043. * consecutive instances (and so on).
  19044. *
  19045. * @type {number}
  19046. * @default 1
  19047. */
  19048. this.meshPerAttribute = meshPerAttribute;
  19049. }
  19050. copy( source ) {
  19051. super.copy( source );
  19052. this.meshPerAttribute = source.meshPerAttribute;
  19053. return this;
  19054. }
  19055. toJSON() {
  19056. const data = super.toJSON();
  19057. data.meshPerAttribute = this.meshPerAttribute;
  19058. data.isInstancedBufferAttribute = true;
  19059. return data;
  19060. }
  19061. }
  19062. const _instanceLocalMatrix = /*@__PURE__*/ new Matrix4();
  19063. const _instanceWorldMatrix = /*@__PURE__*/ new Matrix4();
  19064. const _instanceIntersects = [];
  19065. const _box3 = /*@__PURE__*/ new Box3();
  19066. const _identity = /*@__PURE__*/ new Matrix4();
  19067. const _mesh$1 = /*@__PURE__*/ new Mesh();
  19068. const _sphere$4 = /*@__PURE__*/ new Sphere();
  19069. /**
  19070. * A special version of a mesh with instanced rendering support. Use
  19071. * this class if you have to render a large number of objects with the same
  19072. * geometry and material(s) but with different world transformations. The usage
  19073. * of 'InstancedMesh' will help you to reduce the number of draw calls and thus
  19074. * improve the overall rendering performance in your application.
  19075. *
  19076. * @augments Mesh
  19077. */
  19078. class InstancedMesh extends Mesh {
  19079. /**
  19080. * Constructs a new instanced mesh.
  19081. *
  19082. * @param {BufferGeometry} [geometry] - The mesh geometry.
  19083. * @param {Material|Array<Material>} [material] - The mesh material.
  19084. * @param {number} count - The number of instances.
  19085. */
  19086. constructor( geometry, material, count ) {
  19087. super( geometry, material );
  19088. /**
  19089. * This flag can be used for type testing.
  19090. *
  19091. * @type {boolean}
  19092. * @readonly
  19093. * @default true
  19094. */
  19095. this.isInstancedMesh = true;
  19096. /**
  19097. * Represents the local transformation of all instances. You have to set its
  19098. * {@link BufferAttribute#needsUpdate} flag to true if you modify instanced data
  19099. * via {@link InstancedMesh#setMatrixAt}.
  19100. *
  19101. * @type {InstancedBufferAttribute}
  19102. */
  19103. this.instanceMatrix = new InstancedBufferAttribute( new Float32Array( count * 16 ), 16 );
  19104. /**
  19105. * Represents the local transformation of all instances of the previous frame.
  19106. * Required for computing velocity. Maintained in {@link InstanceNode}.
  19107. *
  19108. * @type {?InstancedBufferAttribute}
  19109. * @default null
  19110. */
  19111. this.previousInstanceMatrix = null;
  19112. /**
  19113. * Represents the color of all instances. You have to set its
  19114. * {@link BufferAttribute#needsUpdate} flag to true if you modify instanced data
  19115. * via {@link InstancedMesh#setColorAt}.
  19116. *
  19117. * @type {?InstancedBufferAttribute}
  19118. * @default null
  19119. */
  19120. this.instanceColor = null;
  19121. /**
  19122. * Represents the morph target weights of all instances. You have to set its
  19123. * {@link Texture#needsUpdate} flag to true if you modify instanced data
  19124. * via {@link InstancedMesh#setMorphAt}.
  19125. *
  19126. * @type {?DataTexture}
  19127. * @default null
  19128. */
  19129. this.morphTexture = null;
  19130. /**
  19131. * The number of instances.
  19132. *
  19133. * @type {number}
  19134. */
  19135. this.count = count;
  19136. /**
  19137. * The bounding box of the instanced mesh. Can be computed via {@link InstancedMesh#computeBoundingBox}.
  19138. *
  19139. * @type {?Box3}
  19140. * @default null
  19141. */
  19142. this.boundingBox = null;
  19143. /**
  19144. * The bounding sphere of the instanced mesh. Can be computed via {@link InstancedMesh#computeBoundingSphere}.
  19145. *
  19146. * @type {?Sphere}
  19147. * @default null
  19148. */
  19149. this.boundingSphere = null;
  19150. for ( let i = 0; i < count; i ++ ) {
  19151. this.setMatrixAt( i, _identity );
  19152. }
  19153. }
  19154. /**
  19155. * Computes the bounding box of the instanced mesh, and updates {@link InstancedMesh#boundingBox}.
  19156. * The bounding box is not automatically computed by the engine; this method must be called by your app.
  19157. * You may need to recompute the bounding box if an instance is transformed via {@link InstancedMesh#setMatrixAt}.
  19158. */
  19159. computeBoundingBox() {
  19160. const geometry = this.geometry;
  19161. const count = this.count;
  19162. if ( this.boundingBox === null ) {
  19163. this.boundingBox = new Box3();
  19164. }
  19165. if ( geometry.boundingBox === null ) {
  19166. geometry.computeBoundingBox();
  19167. }
  19168. this.boundingBox.makeEmpty();
  19169. for ( let i = 0; i < count; i ++ ) {
  19170. this.getMatrixAt( i, _instanceLocalMatrix );
  19171. _box3.copy( geometry.boundingBox ).applyMatrix4( _instanceLocalMatrix );
  19172. this.boundingBox.union( _box3 );
  19173. }
  19174. }
  19175. /**
  19176. * Computes the bounding sphere of the instanced mesh, and updates {@link InstancedMesh#boundingSphere}
  19177. * The engine automatically computes the bounding sphere when it is needed, e.g., for ray casting or view frustum culling.
  19178. * You may need to recompute the bounding sphere if an instance is transformed via {@link InstancedMesh#setMatrixAt}.
  19179. */
  19180. computeBoundingSphere() {
  19181. const geometry = this.geometry;
  19182. const count = this.count;
  19183. if ( this.boundingSphere === null ) {
  19184. this.boundingSphere = new Sphere();
  19185. }
  19186. if ( geometry.boundingSphere === null ) {
  19187. geometry.computeBoundingSphere();
  19188. }
  19189. this.boundingSphere.makeEmpty();
  19190. for ( let i = 0; i < count; i ++ ) {
  19191. this.getMatrixAt( i, _instanceLocalMatrix );
  19192. _sphere$4.copy( geometry.boundingSphere ).applyMatrix4( _instanceLocalMatrix );
  19193. this.boundingSphere.union( _sphere$4 );
  19194. }
  19195. }
  19196. copy( source, recursive ) {
  19197. super.copy( source, recursive );
  19198. this.instanceMatrix.copy( source.instanceMatrix );
  19199. if ( source.previousInstanceMatrix !== null ) this.previousInstanceMatrix = source.previousInstanceMatrix.clone();
  19200. if ( source.morphTexture !== null ) this.morphTexture = source.morphTexture.clone();
  19201. if ( source.instanceColor !== null ) this.instanceColor = source.instanceColor.clone();
  19202. this.count = source.count;
  19203. if ( source.boundingBox !== null ) this.boundingBox = source.boundingBox.clone();
  19204. if ( source.boundingSphere !== null ) this.boundingSphere = source.boundingSphere.clone();
  19205. return this;
  19206. }
  19207. /**
  19208. * Gets the color of the defined instance.
  19209. *
  19210. * @param {number} index - The instance index.
  19211. * @param {Color} color - The target object that is used to store the method's result.
  19212. */
  19213. getColorAt( index, color ) {
  19214. color.fromArray( this.instanceColor.array, index * 3 );
  19215. }
  19216. /**
  19217. * Gets the local transformation matrix of the defined instance.
  19218. *
  19219. * @param {number} index - The instance index.
  19220. * @param {Matrix4} matrix - The target object that is used to store the method's result.
  19221. */
  19222. getMatrixAt( index, matrix ) {
  19223. matrix.fromArray( this.instanceMatrix.array, index * 16 );
  19224. }
  19225. /**
  19226. * Gets the morph target weights of the defined instance.
  19227. *
  19228. * @param {number} index - The instance index.
  19229. * @param {Mesh} object - The target object that is used to store the method's result.
  19230. */
  19231. getMorphAt( index, object ) {
  19232. const objectInfluences = object.morphTargetInfluences;
  19233. const array = this.morphTexture.source.data.data;
  19234. const len = objectInfluences.length + 1; // All influences + the baseInfluenceSum
  19235. const dataIndex = index * len + 1; // Skip the baseInfluenceSum at the beginning
  19236. for ( let i = 0; i < objectInfluences.length; i ++ ) {
  19237. objectInfluences[ i ] = array[ dataIndex + i ];
  19238. }
  19239. }
  19240. raycast( raycaster, intersects ) {
  19241. const matrixWorld = this.matrixWorld;
  19242. const raycastTimes = this.count;
  19243. _mesh$1.geometry = this.geometry;
  19244. _mesh$1.material = this.material;
  19245. if ( _mesh$1.material === undefined ) return;
  19246. // test with bounding sphere first
  19247. if ( this.boundingSphere === null ) this.computeBoundingSphere();
  19248. _sphere$4.copy( this.boundingSphere );
  19249. _sphere$4.applyMatrix4( matrixWorld );
  19250. if ( raycaster.ray.intersectsSphere( _sphere$4 ) === false ) return;
  19251. // now test each instance
  19252. for ( let instanceId = 0; instanceId < raycastTimes; instanceId ++ ) {
  19253. // calculate the world matrix for each instance
  19254. this.getMatrixAt( instanceId, _instanceLocalMatrix );
  19255. _instanceWorldMatrix.multiplyMatrices( matrixWorld, _instanceLocalMatrix );
  19256. // the mesh represents this single instance
  19257. _mesh$1.matrixWorld = _instanceWorldMatrix;
  19258. _mesh$1.raycast( raycaster, _instanceIntersects );
  19259. // process the result of raycast
  19260. for ( let i = 0, l = _instanceIntersects.length; i < l; i ++ ) {
  19261. const intersect = _instanceIntersects[ i ];
  19262. intersect.instanceId = instanceId;
  19263. intersect.object = this;
  19264. intersects.push( intersect );
  19265. }
  19266. _instanceIntersects.length = 0;
  19267. }
  19268. }
  19269. /**
  19270. * Sets the given color to the defined instance. Make sure you set the `needsUpdate` flag of
  19271. * {@link InstancedMesh#instanceColor} to `true` after updating all the colors.
  19272. *
  19273. * @param {number} index - The instance index.
  19274. * @param {Color} color - The instance color.
  19275. */
  19276. setColorAt( index, color ) {
  19277. if ( this.instanceColor === null ) {
  19278. this.instanceColor = new InstancedBufferAttribute( new Float32Array( this.instanceMatrix.count * 3 ).fill( 1 ), 3 );
  19279. }
  19280. color.toArray( this.instanceColor.array, index * 3 );
  19281. }
  19282. /**
  19283. * Sets the given local transformation matrix to the defined instance. Make sure you set the `needsUpdate` flag of
  19284. * {@link InstancedMesh#instanceMatrix} to `true` after updating all the colors.
  19285. *
  19286. * @param {number} index - The instance index.
  19287. * @param {Matrix4} matrix - The local transformation.
  19288. */
  19289. setMatrixAt( index, matrix ) {
  19290. matrix.toArray( this.instanceMatrix.array, index * 16 );
  19291. }
  19292. /**
  19293. * Sets the morph target weights to the defined instance. Make sure you set the `needsUpdate` flag of
  19294. * {@link InstancedMesh#morphTexture} to `true` after updating all the influences.
  19295. *
  19296. * @param {number} index - The instance index.
  19297. * @param {Mesh} object - A mesh which `morphTargetInfluences` property containing the morph target weights
  19298. * of a single instance.
  19299. */
  19300. setMorphAt( index, object ) {
  19301. const objectInfluences = object.morphTargetInfluences;
  19302. const len = objectInfluences.length + 1; // morphBaseInfluence + all influences
  19303. if ( this.morphTexture === null ) {
  19304. this.morphTexture = new DataTexture( new Float32Array( len * this.count ), len, this.count, RedFormat, FloatType );
  19305. }
  19306. const array = this.morphTexture.source.data.data;
  19307. let morphInfluencesSum = 0;
  19308. for ( let i = 0; i < objectInfluences.length; i ++ ) {
  19309. morphInfluencesSum += objectInfluences[ i ];
  19310. }
  19311. const morphBaseInfluence = this.geometry.morphTargetsRelative ? 1 : 1 - morphInfluencesSum;
  19312. const dataIndex = len * index;
  19313. array[ dataIndex ] = morphBaseInfluence;
  19314. array.set( objectInfluences, dataIndex + 1 );
  19315. }
  19316. updateMorphTargets() {
  19317. }
  19318. /**
  19319. * Frees the GPU-related resources allocated by this instance. Call this
  19320. * method whenever this instance is no longer used in your app.
  19321. */
  19322. dispose() {
  19323. this.dispatchEvent( { type: 'dispose' } );
  19324. if ( this.morphTexture !== null ) {
  19325. this.morphTexture.dispose();
  19326. this.morphTexture = null;
  19327. }
  19328. }
  19329. }
  19330. const _vector1 = /*@__PURE__*/ new Vector3();
  19331. const _vector2 = /*@__PURE__*/ new Vector3();
  19332. const _normalMatrix = /*@__PURE__*/ new Matrix3();
  19333. /**
  19334. * A two dimensional surface that extends infinitely in 3D space, represented
  19335. * in [Hessian normal form](http://mathworld.wolfram.com/HessianNormalForm.html)
  19336. * by a unit length normal vector and a constant.
  19337. */
  19338. class Plane {
  19339. /**
  19340. * Constructs a new plane.
  19341. *
  19342. * @param {Vector3} [normal=(1,0,0)] - A unit length vector defining the normal of the plane.
  19343. * @param {number} [constant=0] - The signed distance from the origin to the plane.
  19344. */
  19345. constructor( normal = new Vector3( 1, 0, 0 ), constant = 0 ) {
  19346. /**
  19347. * This flag can be used for type testing.
  19348. *
  19349. * @type {boolean}
  19350. * @readonly
  19351. * @default true
  19352. */
  19353. this.isPlane = true;
  19354. /**
  19355. * A unit length vector defining the normal of the plane.
  19356. *
  19357. * @type {Vector3}
  19358. */
  19359. this.normal = normal;
  19360. /**
  19361. * The signed distance from the origin to the plane.
  19362. *
  19363. * @type {number}
  19364. * @default 0
  19365. */
  19366. this.constant = constant;
  19367. }
  19368. /**
  19369. * Sets the plane components by copying the given values.
  19370. *
  19371. * @param {Vector3} normal - The normal.
  19372. * @param {number} constant - The constant.
  19373. * @return {Plane} A reference to this plane.
  19374. */
  19375. set( normal, constant ) {
  19376. this.normal.copy( normal );
  19377. this.constant = constant;
  19378. return this;
  19379. }
  19380. /**
  19381. * Sets the plane components by defining `x`, `y`, `z` as the
  19382. * plane normal and `w` as the constant.
  19383. *
  19384. * @param {number} x - The value for the normal's x component.
  19385. * @param {number} y - The value for the normal's y component.
  19386. * @param {number} z - The value for the normal's z component.
  19387. * @param {number} w - The constant value.
  19388. * @return {Plane} A reference to this plane.
  19389. */
  19390. setComponents( x, y, z, w ) {
  19391. this.normal.set( x, y, z );
  19392. this.constant = w;
  19393. return this;
  19394. }
  19395. /**
  19396. * Sets the plane from the given normal and coplanar point (that is a point
  19397. * that lies onto the plane).
  19398. *
  19399. * @param {Vector3} normal - The normal.
  19400. * @param {Vector3} point - A coplanar point.
  19401. * @return {Plane} A reference to this plane.
  19402. */
  19403. setFromNormalAndCoplanarPoint( normal, point ) {
  19404. this.normal.copy( normal );
  19405. this.constant = - point.dot( this.normal );
  19406. return this;
  19407. }
  19408. /**
  19409. * Sets the plane from three coplanar points. The winding order is
  19410. * assumed to be counter-clockwise, and determines the direction of
  19411. * the plane normal.
  19412. *
  19413. * @param {Vector3} a - The first coplanar point.
  19414. * @param {Vector3} b - The second coplanar point.
  19415. * @param {Vector3} c - The third coplanar point.
  19416. * @return {Plane} A reference to this plane.
  19417. */
  19418. setFromCoplanarPoints( a, b, c ) {
  19419. const normal = _vector1.subVectors( c, b ).cross( _vector2.subVectors( a, b ) ).normalize();
  19420. // Q: should an error be thrown if normal is zero (e.g. degenerate plane)?
  19421. this.setFromNormalAndCoplanarPoint( normal, a );
  19422. return this;
  19423. }
  19424. /**
  19425. * Copies the values of the given plane to this instance.
  19426. *
  19427. * @param {Plane} plane - The plane to copy.
  19428. * @return {Plane} A reference to this plane.
  19429. */
  19430. copy( plane ) {
  19431. this.normal.copy( plane.normal );
  19432. this.constant = plane.constant;
  19433. return this;
  19434. }
  19435. /**
  19436. * Normalizes the plane normal and adjusts the constant accordingly.
  19437. *
  19438. * @return {Plane} A reference to this plane.
  19439. */
  19440. normalize() {
  19441. // Note: will lead to a divide by zero if the plane is invalid.
  19442. const inverseNormalLength = 1.0 / this.normal.length();
  19443. this.normal.multiplyScalar( inverseNormalLength );
  19444. this.constant *= inverseNormalLength;
  19445. return this;
  19446. }
  19447. /**
  19448. * Negates both the plane normal and the constant.
  19449. *
  19450. * @return {Plane} A reference to this plane.
  19451. */
  19452. negate() {
  19453. this.constant *= -1;
  19454. this.normal.negate();
  19455. return this;
  19456. }
  19457. /**
  19458. * Returns the signed distance from the given point to this plane.
  19459. *
  19460. * @param {Vector3} point - The point to compute the distance for.
  19461. * @return {number} The signed distance.
  19462. */
  19463. distanceToPoint( point ) {
  19464. return this.normal.dot( point ) + this.constant;
  19465. }
  19466. /**
  19467. * Returns the signed distance from the given sphere to this plane.
  19468. *
  19469. * @param {Sphere} sphere - The sphere to compute the distance for.
  19470. * @return {number} The signed distance.
  19471. */
  19472. distanceToSphere( sphere ) {
  19473. return this.distanceToPoint( sphere.center ) - sphere.radius;
  19474. }
  19475. /**
  19476. * Projects a the given point onto the plane.
  19477. *
  19478. * @param {Vector3} point - The point to project.
  19479. * @param {Vector3} target - The target vector that is used to store the method's result.
  19480. * @return {Vector3} The projected point on the plane.
  19481. */
  19482. projectPoint( point, target ) {
  19483. return target.copy( point ).addScaledVector( this.normal, - this.distanceToPoint( point ) );
  19484. }
  19485. /**
  19486. * Returns the intersection point of the passed line and the plane. Returns
  19487. * `null` if the line does not intersect. Returns the line's starting point if
  19488. * the line is coplanar with the plane.
  19489. *
  19490. * @param {Line3} line - The line to compute the intersection for.
  19491. * @param {Vector3} target - The target vector that is used to store the method's result.
  19492. * @return {?Vector3} The intersection point.
  19493. */
  19494. intersectLine( line, target ) {
  19495. const direction = line.delta( _vector1 );
  19496. const denominator = this.normal.dot( direction );
  19497. if ( denominator === 0 ) {
  19498. // line is coplanar, return origin
  19499. if ( this.distanceToPoint( line.start ) === 0 ) {
  19500. return target.copy( line.start );
  19501. }
  19502. // Unsure if this is the correct method to handle this case.
  19503. return null;
  19504. }
  19505. const t = - ( line.start.dot( this.normal ) + this.constant ) / denominator;
  19506. if ( t < 0 || t > 1 ) {
  19507. return null;
  19508. }
  19509. return target.copy( line.start ).addScaledVector( direction, t );
  19510. }
  19511. /**
  19512. * Returns `true` if the given line segment intersects with (passes through) the plane.
  19513. *
  19514. * @param {Line3} line - The line to test.
  19515. * @return {boolean} Whether the given line segment intersects with the plane or not.
  19516. */
  19517. intersectsLine( line ) {
  19518. // Note: this tests if a line intersects the plane, not whether it (or its end-points) are coplanar with it.
  19519. const startSign = this.distanceToPoint( line.start );
  19520. const endSign = this.distanceToPoint( line.end );
  19521. return ( startSign < 0 && endSign > 0 ) || ( endSign < 0 && startSign > 0 );
  19522. }
  19523. /**
  19524. * Returns `true` if the given bounding box intersects with the plane.
  19525. *
  19526. * @param {Box3} box - The bounding box to test.
  19527. * @return {boolean} Whether the given bounding box intersects with the plane or not.
  19528. */
  19529. intersectsBox( box ) {
  19530. return box.intersectsPlane( this );
  19531. }
  19532. /**
  19533. * Returns `true` if the given bounding sphere intersects with the plane.
  19534. *
  19535. * @param {Sphere} sphere - The bounding sphere to test.
  19536. * @return {boolean} Whether the given bounding sphere intersects with the plane or not.
  19537. */
  19538. intersectsSphere( sphere ) {
  19539. return sphere.intersectsPlane( this );
  19540. }
  19541. /**
  19542. * Returns a coplanar vector to the plane, by calculating the
  19543. * projection of the normal at the origin onto the plane.
  19544. *
  19545. * @param {Vector3} target - The target vector that is used to store the method's result.
  19546. * @return {Vector3} The coplanar point.
  19547. */
  19548. coplanarPoint( target ) {
  19549. return target.copy( this.normal ).multiplyScalar( - this.constant );
  19550. }
  19551. /**
  19552. * Apply a 4x4 matrix to the plane. The matrix must be an affine, homogeneous transform.
  19553. *
  19554. * The optional normal matrix can be pre-computed like so:
  19555. * ```js
  19556. * const optionalNormalMatrix = new THREE.Matrix3().getNormalMatrix( matrix );
  19557. * ```
  19558. *
  19559. * @param {Matrix4} matrix - The transformation matrix.
  19560. * @param {Matrix4} [optionalNormalMatrix] - A pre-computed normal matrix.
  19561. * @return {Plane} A reference to this plane.
  19562. */
  19563. applyMatrix4( matrix, optionalNormalMatrix ) {
  19564. const normalMatrix = optionalNormalMatrix || _normalMatrix.getNormalMatrix( matrix );
  19565. const referencePoint = this.coplanarPoint( _vector1 ).applyMatrix4( matrix );
  19566. const normal = this.normal.applyMatrix3( normalMatrix ).normalize();
  19567. this.constant = - referencePoint.dot( normal );
  19568. return this;
  19569. }
  19570. /**
  19571. * Translates the plane by the distance defined by the given offset vector.
  19572. * Note that this only affects the plane constant and will not affect the normal vector.
  19573. *
  19574. * @param {Vector3} offset - The offset vector.
  19575. * @return {Plane} A reference to this plane.
  19576. */
  19577. translate( offset ) {
  19578. this.constant -= offset.dot( this.normal );
  19579. return this;
  19580. }
  19581. /**
  19582. * Returns `true` if this plane is equal with the given one.
  19583. *
  19584. * @param {Plane} plane - The plane to test for equality.
  19585. * @return {boolean} Whether this plane is equal with the given one.
  19586. */
  19587. equals( plane ) {
  19588. return plane.normal.equals( this.normal ) && ( plane.constant === this.constant );
  19589. }
  19590. /**
  19591. * Returns a new plane with copied values from this instance.
  19592. *
  19593. * @return {Plane} A clone of this instance.
  19594. */
  19595. clone() {
  19596. return new this.constructor().copy( this );
  19597. }
  19598. }
  19599. const _sphere$3 = /*@__PURE__*/ new Sphere();
  19600. const _defaultSpriteCenter = /*@__PURE__*/ new Vector2( 0.5, 0.5 );
  19601. const _vector$6 = /*@__PURE__*/ new Vector3();
  19602. /**
  19603. * Frustums are used to determine what is inside the camera's field of view.
  19604. * They help speed up the rendering process - objects which lie outside a camera's
  19605. * frustum can safely be excluded from rendering.
  19606. *
  19607. * This class is mainly intended for use internally by a renderer.
  19608. */
  19609. class Frustum {
  19610. /**
  19611. * Constructs a new frustum.
  19612. *
  19613. * @param {Plane} [p0] - The first plane that encloses the frustum.
  19614. * @param {Plane} [p1] - The second plane that encloses the frustum.
  19615. * @param {Plane} [p2] - The third plane that encloses the frustum.
  19616. * @param {Plane} [p3] - The fourth plane that encloses the frustum.
  19617. * @param {Plane} [p4] - The fifth plane that encloses the frustum.
  19618. * @param {Plane} [p5] - The sixth plane that encloses the frustum.
  19619. */
  19620. constructor( p0 = new Plane(), p1 = new Plane(), p2 = new Plane(), p3 = new Plane(), p4 = new Plane(), p5 = new Plane() ) {
  19621. /**
  19622. * This array holds the planes that enclose the frustum.
  19623. *
  19624. * @type {Array<Plane>}
  19625. */
  19626. this.planes = [ p0, p1, p2, p3, p4, p5 ];
  19627. }
  19628. /**
  19629. * Sets the frustum planes by copying the given planes.
  19630. *
  19631. * @param {Plane} [p0] - The first plane that encloses the frustum.
  19632. * @param {Plane} [p1] - The second plane that encloses the frustum.
  19633. * @param {Plane} [p2] - The third plane that encloses the frustum.
  19634. * @param {Plane} [p3] - The fourth plane that encloses the frustum.
  19635. * @param {Plane} [p4] - The fifth plane that encloses the frustum.
  19636. * @param {Plane} [p5] - The sixth plane that encloses the frustum.
  19637. * @return {Frustum} A reference to this frustum.
  19638. */
  19639. set( p0, p1, p2, p3, p4, p5 ) {
  19640. const planes = this.planes;
  19641. planes[ 0 ].copy( p0 );
  19642. planes[ 1 ].copy( p1 );
  19643. planes[ 2 ].copy( p2 );
  19644. planes[ 3 ].copy( p3 );
  19645. planes[ 4 ].copy( p4 );
  19646. planes[ 5 ].copy( p5 );
  19647. return this;
  19648. }
  19649. /**
  19650. * Copies the values of the given frustum to this instance.
  19651. *
  19652. * @param {Frustum} frustum - The frustum to copy.
  19653. * @return {Frustum} A reference to this frustum.
  19654. */
  19655. copy( frustum ) {
  19656. const planes = this.planes;
  19657. for ( let i = 0; i < 6; i ++ ) {
  19658. planes[ i ].copy( frustum.planes[ i ] );
  19659. }
  19660. return this;
  19661. }
  19662. /**
  19663. * Sets the frustum planes from the given projection matrix.
  19664. *
  19665. * @param {Matrix4} m - The projection matrix.
  19666. * @param {(WebGLCoordinateSystem|WebGPUCoordinateSystem)} coordinateSystem - The coordinate system.
  19667. * @param {boolean} [reversedDepth=false] - Whether to use a reversed depth.
  19668. * @return {Frustum} A reference to this frustum.
  19669. */
  19670. setFromProjectionMatrix( m, coordinateSystem = WebGLCoordinateSystem, reversedDepth = false ) {
  19671. const planes = this.planes;
  19672. const me = m.elements;
  19673. const me0 = me[ 0 ], me1 = me[ 1 ], me2 = me[ 2 ], me3 = me[ 3 ];
  19674. const me4 = me[ 4 ], me5 = me[ 5 ], me6 = me[ 6 ], me7 = me[ 7 ];
  19675. const me8 = me[ 8 ], me9 = me[ 9 ], me10 = me[ 10 ], me11 = me[ 11 ];
  19676. const me12 = me[ 12 ], me13 = me[ 13 ], me14 = me[ 14 ], me15 = me[ 15 ];
  19677. planes[ 0 ].setComponents( me3 - me0, me7 - me4, me11 - me8, me15 - me12 ).normalize();
  19678. planes[ 1 ].setComponents( me3 + me0, me7 + me4, me11 + me8, me15 + me12 ).normalize();
  19679. planes[ 2 ].setComponents( me3 + me1, me7 + me5, me11 + me9, me15 + me13 ).normalize();
  19680. planes[ 3 ].setComponents( me3 - me1, me7 - me5, me11 - me9, me15 - me13 ).normalize();
  19681. if ( reversedDepth ) {
  19682. planes[ 4 ].setComponents( me2, me6, me10, me14 ).normalize(); // far
  19683. planes[ 5 ].setComponents( me3 - me2, me7 - me6, me11 - me10, me15 - me14 ).normalize(); // near
  19684. } else {
  19685. planes[ 4 ].setComponents( me3 - me2, me7 - me6, me11 - me10, me15 - me14 ).normalize(); // far
  19686. if ( coordinateSystem === WebGLCoordinateSystem ) {
  19687. planes[ 5 ].setComponents( me3 + me2, me7 + me6, me11 + me10, me15 + me14 ).normalize(); // near
  19688. } else if ( coordinateSystem === WebGPUCoordinateSystem ) {
  19689. planes[ 5 ].setComponents( me2, me6, me10, me14 ).normalize(); // near
  19690. } else {
  19691. throw new Error( 'THREE.Frustum.setFromProjectionMatrix(): Invalid coordinate system: ' + coordinateSystem );
  19692. }
  19693. }
  19694. return this;
  19695. }
  19696. /**
  19697. * Returns `true` if the 3D object's bounding sphere is intersecting this frustum.
  19698. *
  19699. * Note that the 3D object must have a geometry so that the bounding sphere can be calculated.
  19700. *
  19701. * @param {Object3D} object - The 3D object to test.
  19702. * @return {boolean} Whether the 3D object's bounding sphere is intersecting this frustum or not.
  19703. */
  19704. intersectsObject( object ) {
  19705. if ( object.boundingSphere !== undefined ) {
  19706. if ( object.boundingSphere === null ) object.computeBoundingSphere();
  19707. _sphere$3.copy( object.boundingSphere ).applyMatrix4( object.matrixWorld );
  19708. } else {
  19709. const geometry = object.geometry;
  19710. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  19711. _sphere$3.copy( geometry.boundingSphere ).applyMatrix4( object.matrixWorld );
  19712. }
  19713. return this.intersectsSphere( _sphere$3 );
  19714. }
  19715. /**
  19716. * Returns `true` if the given sprite is intersecting this frustum.
  19717. *
  19718. * @param {Sprite} sprite - The sprite to test.
  19719. * @return {boolean} Whether the sprite is intersecting this frustum or not.
  19720. */
  19721. intersectsSprite( sprite ) {
  19722. _sphere$3.center.set( 0, 0, 0 );
  19723. const offset = _defaultSpriteCenter.distanceTo( sprite.center );
  19724. _sphere$3.radius = 0.7071067811865476 + offset;
  19725. _sphere$3.applyMatrix4( sprite.matrixWorld );
  19726. return this.intersectsSphere( _sphere$3 );
  19727. }
  19728. /**
  19729. * Returns `true` if the given bounding sphere is intersecting this frustum.
  19730. *
  19731. * @param {Sphere} sphere - The bounding sphere to test.
  19732. * @return {boolean} Whether the bounding sphere is intersecting this frustum or not.
  19733. */
  19734. intersectsSphere( sphere ) {
  19735. const planes = this.planes;
  19736. const center = sphere.center;
  19737. const negRadius = - sphere.radius;
  19738. for ( let i = 0; i < 6; i ++ ) {
  19739. const distance = planes[ i ].distanceToPoint( center );
  19740. if ( distance < negRadius ) {
  19741. return false;
  19742. }
  19743. }
  19744. return true;
  19745. }
  19746. /**
  19747. * Returns `true` if the given bounding box is intersecting this frustum.
  19748. *
  19749. * @param {Box3} box - The bounding box to test.
  19750. * @return {boolean} Whether the bounding box is intersecting this frustum or not.
  19751. */
  19752. intersectsBox( box ) {
  19753. const planes = this.planes;
  19754. for ( let i = 0; i < 6; i ++ ) {
  19755. const plane = planes[ i ];
  19756. // corner at max distance
  19757. _vector$6.x = plane.normal.x > 0 ? box.max.x : box.min.x;
  19758. _vector$6.y = plane.normal.y > 0 ? box.max.y : box.min.y;
  19759. _vector$6.z = plane.normal.z > 0 ? box.max.z : box.min.z;
  19760. if ( plane.distanceToPoint( _vector$6 ) < 0 ) {
  19761. return false;
  19762. }
  19763. }
  19764. return true;
  19765. }
  19766. /**
  19767. * Returns `true` if the given point lies within the frustum.
  19768. *
  19769. * @param {Vector3} point - The point to test.
  19770. * @return {boolean} Whether the point lies within this frustum or not.
  19771. */
  19772. containsPoint( point ) {
  19773. const planes = this.planes;
  19774. for ( let i = 0; i < 6; i ++ ) {
  19775. if ( planes[ i ].distanceToPoint( point ) < 0 ) {
  19776. return false;
  19777. }
  19778. }
  19779. return true;
  19780. }
  19781. /**
  19782. * Returns a new frustum with copied values from this instance.
  19783. *
  19784. * @return {Frustum} A clone of this instance.
  19785. */
  19786. clone() {
  19787. return new this.constructor().copy( this );
  19788. }
  19789. }
  19790. const _projScreenMatrix$1 = /*@__PURE__*/ new Matrix4();
  19791. const _frustum$1 = /*@__PURE__*/ new Frustum();
  19792. /**
  19793. * FrustumArray is used to determine if an object is visible in at least one camera
  19794. * from an array of cameras. This is particularly useful for multi-view renderers.
  19795. */
  19796. class FrustumArray {
  19797. /**
  19798. * Constructs a new frustum array.
  19799. *
  19800. */
  19801. constructor() {
  19802. /**
  19803. * The coordinate system to use.
  19804. *
  19805. * @type {WebGLCoordinateSystem|WebGPUCoordinateSystem}
  19806. * @default WebGLCoordinateSystem
  19807. */
  19808. this.coordinateSystem = WebGLCoordinateSystem;
  19809. }
  19810. /**
  19811. * Returns `true` if the 3D object's bounding sphere is intersecting any frustum
  19812. * from the camera array.
  19813. *
  19814. * @param {Object3D} object - The 3D object to test.
  19815. * @param {Object} cameraArray - An object with a cameras property containing an array of cameras.
  19816. * @return {boolean} Whether the 3D object is visible in any camera.
  19817. */
  19818. intersectsObject( object, cameraArray ) {
  19819. if ( ! cameraArray.isArrayCamera || cameraArray.cameras.length === 0 ) {
  19820. return false;
  19821. }
  19822. for ( let i = 0; i < cameraArray.cameras.length; i ++ ) {
  19823. const camera = cameraArray.cameras[ i ];
  19824. _projScreenMatrix$1.multiplyMatrices(
  19825. camera.projectionMatrix,
  19826. camera.matrixWorldInverse
  19827. );
  19828. _frustum$1.setFromProjectionMatrix(
  19829. _projScreenMatrix$1,
  19830. camera.coordinateSystem,
  19831. camera.reversedDepth
  19832. );
  19833. if ( _frustum$1.intersectsObject( object ) ) {
  19834. return true; // Object is visible in at least one camera
  19835. }
  19836. }
  19837. return false; // Not visible in any camera
  19838. }
  19839. /**
  19840. * Returns `true` if the given sprite is intersecting any frustum
  19841. * from the camera array.
  19842. *
  19843. * @param {Sprite} sprite - The sprite to test.
  19844. * @param {Object} cameraArray - An object with a cameras property containing an array of cameras.
  19845. * @return {boolean} Whether the sprite is visible in any camera.
  19846. */
  19847. intersectsSprite( sprite, cameraArray ) {
  19848. if ( ! cameraArray || ! cameraArray.cameras || cameraArray.cameras.length === 0 ) {
  19849. return false;
  19850. }
  19851. for ( let i = 0; i < cameraArray.cameras.length; i ++ ) {
  19852. const camera = cameraArray.cameras[ i ];
  19853. _projScreenMatrix$1.multiplyMatrices(
  19854. camera.projectionMatrix,
  19855. camera.matrixWorldInverse
  19856. );
  19857. _frustum$1.setFromProjectionMatrix(
  19858. _projScreenMatrix$1,
  19859. camera.coordinateSystem,
  19860. camera.reversedDepth
  19861. );
  19862. if ( _frustum$1.intersectsSprite( sprite ) ) {
  19863. return true; // Sprite is visible in at least one camera
  19864. }
  19865. }
  19866. return false; // Not visible in any camera
  19867. }
  19868. /**
  19869. * Returns `true` if the given bounding sphere is intersecting any frustum
  19870. * from the camera array.
  19871. *
  19872. * @param {Sphere} sphere - The bounding sphere to test.
  19873. * @param {Object} cameraArray - An object with a cameras property containing an array of cameras.
  19874. * @return {boolean} Whether the sphere is visible in any camera.
  19875. */
  19876. intersectsSphere( sphere, cameraArray ) {
  19877. if ( ! cameraArray || ! cameraArray.cameras || cameraArray.cameras.length === 0 ) {
  19878. return false;
  19879. }
  19880. for ( let i = 0; i < cameraArray.cameras.length; i ++ ) {
  19881. const camera = cameraArray.cameras[ i ];
  19882. _projScreenMatrix$1.multiplyMatrices(
  19883. camera.projectionMatrix,
  19884. camera.matrixWorldInverse
  19885. );
  19886. _frustum$1.setFromProjectionMatrix(
  19887. _projScreenMatrix$1,
  19888. camera.coordinateSystem,
  19889. camera.reversedDepth
  19890. );
  19891. if ( _frustum$1.intersectsSphere( sphere ) ) {
  19892. return true; // Sphere is visible in at least one camera
  19893. }
  19894. }
  19895. return false; // Not visible in any camera
  19896. }
  19897. /**
  19898. * Returns `true` if the given bounding box is intersecting any frustum
  19899. * from the camera array.
  19900. *
  19901. * @param {Box3} box - The bounding box to test.
  19902. * @param {Object} cameraArray - An object with a cameras property containing an array of cameras.
  19903. * @return {boolean} Whether the box is visible in any camera.
  19904. */
  19905. intersectsBox( box, cameraArray ) {
  19906. if ( ! cameraArray || ! cameraArray.cameras || cameraArray.cameras.length === 0 ) {
  19907. return false;
  19908. }
  19909. for ( let i = 0; i < cameraArray.cameras.length; i ++ ) {
  19910. const camera = cameraArray.cameras[ i ];
  19911. _projScreenMatrix$1.multiplyMatrices(
  19912. camera.projectionMatrix,
  19913. camera.matrixWorldInverse
  19914. );
  19915. _frustum$1.setFromProjectionMatrix(
  19916. _projScreenMatrix$1,
  19917. camera.coordinateSystem,
  19918. camera.reversedDepth
  19919. );
  19920. if ( _frustum$1.intersectsBox( box ) ) {
  19921. return true; // Box is visible in at least one camera
  19922. }
  19923. }
  19924. return false; // Not visible in any camera
  19925. }
  19926. /**
  19927. * Returns `true` if the given point lies within any frustum
  19928. * from the camera array.
  19929. *
  19930. * @param {Vector3} point - The point to test.
  19931. * @param {Object} cameraArray - An object with a cameras property containing an array of cameras.
  19932. * @return {boolean} Whether the point is visible in any camera.
  19933. */
  19934. containsPoint( point, cameraArray ) {
  19935. if ( ! cameraArray || ! cameraArray.cameras || cameraArray.cameras.length === 0 ) {
  19936. return false;
  19937. }
  19938. for ( let i = 0; i < cameraArray.cameras.length; i ++ ) {
  19939. const camera = cameraArray.cameras[ i ];
  19940. _projScreenMatrix$1.multiplyMatrices(
  19941. camera.projectionMatrix,
  19942. camera.matrixWorldInverse
  19943. );
  19944. _frustum$1.setFromProjectionMatrix(
  19945. _projScreenMatrix$1,
  19946. camera.coordinateSystem,
  19947. camera.reversedDepth
  19948. );
  19949. if ( _frustum$1.containsPoint( point ) ) {
  19950. return true; // Point is visible in at least one camera
  19951. }
  19952. }
  19953. return false; // Not visible in any camera
  19954. }
  19955. /**
  19956. * Returns a new frustum array with copied values from this instance.
  19957. *
  19958. * @return {FrustumArray} A clone of this instance.
  19959. */
  19960. clone() {
  19961. return new FrustumArray();
  19962. }
  19963. }
  19964. function ascIdSort( a, b ) {
  19965. return a - b;
  19966. }
  19967. function sortOpaque( a, b ) {
  19968. return a.z - b.z;
  19969. }
  19970. function sortTransparent( a, b ) {
  19971. return b.z - a.z;
  19972. }
  19973. class MultiDrawRenderList {
  19974. constructor() {
  19975. this.index = 0;
  19976. this.pool = [];
  19977. this.list = [];
  19978. }
  19979. push( start, count, z, index ) {
  19980. const pool = this.pool;
  19981. const list = this.list;
  19982. if ( this.index >= pool.length ) {
  19983. pool.push( {
  19984. start: -1,
  19985. count: -1,
  19986. z: -1,
  19987. index: -1,
  19988. } );
  19989. }
  19990. const item = pool[ this.index ];
  19991. list.push( item );
  19992. this.index ++;
  19993. item.start = start;
  19994. item.count = count;
  19995. item.z = z;
  19996. item.index = index;
  19997. }
  19998. reset() {
  19999. this.list.length = 0;
  20000. this.index = 0;
  20001. }
  20002. }
  20003. const _matrix$1 = /*@__PURE__*/ new Matrix4();
  20004. const _whiteColor = /*@__PURE__*/ new Color( 1, 1, 1 );
  20005. const _frustum = /*@__PURE__*/ new Frustum();
  20006. const _frustumArray = /*@__PURE__*/ new FrustumArray();
  20007. const _box$1 = /*@__PURE__*/ new Box3();
  20008. const _sphere$2 = /*@__PURE__*/ new Sphere();
  20009. const _vector$5 = /*@__PURE__*/ new Vector3();
  20010. const _forward$1 = /*@__PURE__*/ new Vector3();
  20011. const _temp = /*@__PURE__*/ new Vector3();
  20012. const _renderList = /*@__PURE__*/ new MultiDrawRenderList();
  20013. const _mesh = /*@__PURE__*/ new Mesh();
  20014. const _batchIntersects = [];
  20015. // copies data from attribute "src" into "target" starting at "targetOffset"
  20016. function copyAttributeData( src, target, targetOffset = 0 ) {
  20017. const itemSize = target.itemSize;
  20018. if ( src.isInterleavedBufferAttribute || src.array.constructor !== target.array.constructor ) {
  20019. // use the component getters and setters if the array data cannot
  20020. // be copied directly
  20021. const vertexCount = src.count;
  20022. for ( let i = 0; i < vertexCount; i ++ ) {
  20023. for ( let c = 0; c < itemSize; c ++ ) {
  20024. target.setComponent( i + targetOffset, c, src.getComponent( i, c ) );
  20025. }
  20026. }
  20027. } else {
  20028. // faster copy approach using typed array set function
  20029. target.array.set( src.array, targetOffset * itemSize );
  20030. }
  20031. target.needsUpdate = true;
  20032. }
  20033. // safely copies array contents to a potentially smaller array
  20034. function copyArrayContents( src, target ) {
  20035. if ( src.constructor !== target.constructor ) {
  20036. // if arrays are of a different type (eg due to index size increasing) then data must be per-element copied
  20037. const len = Math.min( src.length, target.length );
  20038. for ( let i = 0; i < len; i ++ ) {
  20039. target[ i ] = src[ i ];
  20040. }
  20041. } else {
  20042. // if the arrays use the same data layout we can use a fast block copy
  20043. const len = Math.min( src.length, target.length );
  20044. target.set( new src.constructor( src.buffer, 0, len ) );
  20045. }
  20046. }
  20047. /**
  20048. * A special version of a mesh with multi draw batch rendering support. Use
  20049. * this class if you have to render a large number of objects with the same
  20050. * material but with different geometries or world transformations. The usage of
  20051. * `BatchedMesh` will help you to reduce the number of draw calls and thus improve the overall
  20052. * rendering performance in your application.
  20053. *
  20054. * ```js
  20055. * const box = new THREE.BoxGeometry( 1, 1, 1 );
  20056. * const sphere = new THREE.SphereGeometry( 1, 12, 12 );
  20057. * const material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } );
  20058. *
  20059. * // initialize and add geometries into the batched mesh
  20060. * const batchedMesh = new BatchedMesh( 10, 5000, 10000, material );
  20061. * const boxGeometryId = batchedMesh.addGeometry( box );
  20062. * const sphereGeometryId = batchedMesh.addGeometry( sphere );
  20063. *
  20064. * // create instances of those geometries
  20065. * const boxInstancedId1 = batchedMesh.addInstance( boxGeometryId );
  20066. * const boxInstancedId2 = batchedMesh.addInstance( boxGeometryId );
  20067. *
  20068. * const sphereInstancedId1 = batchedMesh.addInstance( sphereGeometryId );
  20069. * const sphereInstancedId2 = batchedMesh.addInstance( sphereGeometryId );
  20070. *
  20071. * // position the geometries
  20072. * batchedMesh.setMatrixAt( boxInstancedId1, boxMatrix1 );
  20073. * batchedMesh.setMatrixAt( boxInstancedId2, boxMatrix2 );
  20074. *
  20075. * batchedMesh.setMatrixAt( sphereInstancedId1, sphereMatrix1 );
  20076. * batchedMesh.setMatrixAt( sphereInstancedId2, sphereMatrix2 );
  20077. *
  20078. * scene.add( batchedMesh );
  20079. * ```
  20080. *
  20081. * @augments Mesh
  20082. */
  20083. class BatchedMesh extends Mesh {
  20084. /**
  20085. * Constructs a new batched mesh.
  20086. *
  20087. * @param {number} maxInstanceCount - The maximum number of individual instances planned to be added and rendered.
  20088. * @param {number} maxVertexCount - The maximum number of vertices to be used by all unique geometries.
  20089. * @param {number} [maxIndexCount=maxVertexCount*2] - The maximum number of indices to be used by all unique geometries
  20090. * @param {Material|Array<Material>} [material] - The mesh material.
  20091. */
  20092. constructor( maxInstanceCount, maxVertexCount, maxIndexCount = maxVertexCount * 2, material ) {
  20093. super( new BufferGeometry(), material );
  20094. /**
  20095. * This flag can be used for type testing.
  20096. *
  20097. * @type {boolean}
  20098. * @readonly
  20099. * @default true
  20100. */
  20101. this.isBatchedMesh = true;
  20102. /**
  20103. * When set ot `true`, the individual objects of a batch are frustum culled.
  20104. *
  20105. * @type {boolean}
  20106. * @default true
  20107. */
  20108. this.perObjectFrustumCulled = true;
  20109. /**
  20110. * When set to `true`, the individual objects of a batch are sorted to improve overdraw-related artifacts.
  20111. * If the material is marked as "transparent" objects are rendered back to front and if not then they are
  20112. * rendered front to back.
  20113. *
  20114. * @type {boolean}
  20115. * @default true
  20116. */
  20117. this.sortObjects = true;
  20118. /**
  20119. * The bounding box of the batched mesh. Can be computed via {@link BatchedMesh#computeBoundingBox}.
  20120. *
  20121. * @type {?Box3}
  20122. * @default null
  20123. */
  20124. this.boundingBox = null;
  20125. /**
  20126. * The bounding sphere of the batched mesh. Can be computed via {@link BatchedMesh#computeBoundingSphere}.
  20127. *
  20128. * @type {?Sphere}
  20129. * @default null
  20130. */
  20131. this.boundingSphere = null;
  20132. /**
  20133. * Takes a sort a function that is run before render. The function takes a list of instances to
  20134. * sort and a camera. The objects in the list include a "z" field to perform a depth-ordered
  20135. * sort with.
  20136. *
  20137. * @type {?Function}
  20138. * @default null
  20139. */
  20140. this.customSort = null;
  20141. // stores visible, active, and geometry id per instance and reserved buffer ranges for geometries
  20142. this._instanceInfo = [];
  20143. this._geometryInfo = [];
  20144. // instance, geometry ids that have been set as inactive, and are available to be overwritten
  20145. this._availableInstanceIds = [];
  20146. this._availableGeometryIds = [];
  20147. // used to track where the next point is that geometry should be inserted
  20148. this._nextIndexStart = 0;
  20149. this._nextVertexStart = 0;
  20150. this._geometryCount = 0;
  20151. // flags
  20152. this._visibilityChanged = true;
  20153. this._geometryInitialized = false;
  20154. // cached user options
  20155. this._maxInstanceCount = maxInstanceCount;
  20156. this._maxVertexCount = maxVertexCount;
  20157. this._maxIndexCount = maxIndexCount;
  20158. // buffers for multi draw
  20159. this._multiDrawCounts = new Int32Array( maxInstanceCount );
  20160. this._multiDrawStarts = new Int32Array( maxInstanceCount );
  20161. this._multiDrawCount = 0;
  20162. this._multiDrawInstances = null;
  20163. // Local matrix per geometry by using data texture
  20164. this._matricesTexture = null;
  20165. this._indirectTexture = null;
  20166. this._colorsTexture = null;
  20167. this._initMatricesTexture();
  20168. this._initIndirectTexture();
  20169. }
  20170. /**
  20171. * The maximum number of individual instances that can be stored in the batch.
  20172. *
  20173. * @type {number}
  20174. * @readonly
  20175. */
  20176. get maxInstanceCount() {
  20177. return this._maxInstanceCount;
  20178. }
  20179. /**
  20180. * The instance count.
  20181. *
  20182. * @type {number}
  20183. * @readonly
  20184. */
  20185. get instanceCount() {
  20186. return this._instanceInfo.length - this._availableInstanceIds.length;
  20187. }
  20188. /**
  20189. * The number of unused vertices.
  20190. *
  20191. * @type {number}
  20192. * @readonly
  20193. */
  20194. get unusedVertexCount() {
  20195. return this._maxVertexCount - this._nextVertexStart;
  20196. }
  20197. /**
  20198. * The number of unused indices.
  20199. *
  20200. * @type {number}
  20201. * @readonly
  20202. */
  20203. get unusedIndexCount() {
  20204. return this._maxIndexCount - this._nextIndexStart;
  20205. }
  20206. _initMatricesTexture() {
  20207. // layout (1 matrix = 4 pixels)
  20208. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  20209. // with 8x8 pixel texture max 16 matrices * 4 pixels = (8 * 8)
  20210. // 16x16 pixel texture max 64 matrices * 4 pixels = (16 * 16)
  20211. // 32x32 pixel texture max 256 matrices * 4 pixels = (32 * 32)
  20212. // 64x64 pixel texture max 1024 matrices * 4 pixels = (64 * 64)
  20213. let size = Math.sqrt( this._maxInstanceCount * 4 ); // 4 pixels needed for 1 matrix
  20214. size = Math.ceil( size / 4 ) * 4;
  20215. size = Math.max( size, 4 );
  20216. const matricesArray = new Float32Array( size * size * 4 ); // 4 floats per RGBA pixel
  20217. const matricesTexture = new DataTexture( matricesArray, size, size, RGBAFormat, FloatType );
  20218. this._matricesTexture = matricesTexture;
  20219. }
  20220. _initIndirectTexture() {
  20221. let size = Math.sqrt( this._maxInstanceCount );
  20222. size = Math.ceil( size );
  20223. const indirectArray = new Uint32Array( size * size );
  20224. const indirectTexture = new DataTexture( indirectArray, size, size, RedIntegerFormat, UnsignedIntType );
  20225. this._indirectTexture = indirectTexture;
  20226. }
  20227. _initColorsTexture() {
  20228. let size = Math.sqrt( this._maxInstanceCount );
  20229. size = Math.ceil( size );
  20230. // 4 floats per RGBA pixel initialized to white
  20231. const colorsArray = new Float32Array( size * size * 4 ).fill( 1 );
  20232. const colorsTexture = new DataTexture( colorsArray, size, size, RGBAFormat, FloatType );
  20233. colorsTexture.colorSpace = ColorManagement.workingColorSpace;
  20234. this._colorsTexture = colorsTexture;
  20235. }
  20236. _initializeGeometry( reference ) {
  20237. const geometry = this.geometry;
  20238. const maxVertexCount = this._maxVertexCount;
  20239. const maxIndexCount = this._maxIndexCount;
  20240. if ( this._geometryInitialized === false ) {
  20241. for ( const attributeName in reference.attributes ) {
  20242. const srcAttribute = reference.getAttribute( attributeName );
  20243. const { array, itemSize, normalized } = srcAttribute;
  20244. const dstArray = new array.constructor( maxVertexCount * itemSize );
  20245. const dstAttribute = new BufferAttribute( dstArray, itemSize, normalized );
  20246. geometry.setAttribute( attributeName, dstAttribute );
  20247. }
  20248. if ( reference.getIndex() !== null ) {
  20249. // Reserve last u16 index for primitive restart.
  20250. const indexArray = maxVertexCount > 65535
  20251. ? new Uint32Array( maxIndexCount )
  20252. : new Uint16Array( maxIndexCount );
  20253. geometry.setIndex( new BufferAttribute( indexArray, 1 ) );
  20254. }
  20255. this._geometryInitialized = true;
  20256. }
  20257. }
  20258. // Make sure the geometry is compatible with the existing combined geometry attributes
  20259. _validateGeometry( geometry ) {
  20260. // check to ensure the geometries are using consistent attributes and indices
  20261. const batchGeometry = this.geometry;
  20262. if ( Boolean( geometry.getIndex() ) !== Boolean( batchGeometry.getIndex() ) ) {
  20263. throw new Error( 'THREE.BatchedMesh: All geometries must consistently have "index".' );
  20264. }
  20265. for ( const attributeName in batchGeometry.attributes ) {
  20266. if ( ! geometry.hasAttribute( attributeName ) ) {
  20267. throw new Error( `THREE.BatchedMesh: Added geometry missing "${ attributeName }". All geometries must have consistent attributes.` );
  20268. }
  20269. const srcAttribute = geometry.getAttribute( attributeName );
  20270. const dstAttribute = batchGeometry.getAttribute( attributeName );
  20271. if ( srcAttribute.itemSize !== dstAttribute.itemSize || srcAttribute.normalized !== dstAttribute.normalized ) {
  20272. throw new Error( 'THREE.BatchedMesh: All attributes must have a consistent itemSize and normalized value.' );
  20273. }
  20274. }
  20275. }
  20276. /**
  20277. * Validates the instance defined by the given ID.
  20278. *
  20279. * @param {number} instanceId - The instance to validate.
  20280. */
  20281. validateInstanceId( instanceId ) {
  20282. const instanceInfo = this._instanceInfo;
  20283. if ( instanceId < 0 || instanceId >= instanceInfo.length || instanceInfo[ instanceId ].active === false ) {
  20284. throw new Error( `THREE.BatchedMesh: Invalid instanceId ${instanceId}. Instance is either out of range or has been deleted.` );
  20285. }
  20286. }
  20287. /**
  20288. * Validates the geometry defined by the given ID.
  20289. *
  20290. * @param {number} geometryId - The geometry to validate.
  20291. */
  20292. validateGeometryId( geometryId ) {
  20293. const geometryInfoList = this._geometryInfo;
  20294. if ( geometryId < 0 || geometryId >= geometryInfoList.length || geometryInfoList[ geometryId ].active === false ) {
  20295. throw new Error( `THREE.BatchedMesh: Invalid geometryId ${geometryId}. Geometry is either out of range or has been deleted.` );
  20296. }
  20297. }
  20298. /**
  20299. * Takes a sort a function that is run before render. The function takes a list of instances to
  20300. * sort and a camera. The objects in the list include a "z" field to perform a depth-ordered sort with.
  20301. *
  20302. * @param {Function} func - The custom sort function.
  20303. * @return {BatchedMesh} A reference to this batched mesh.
  20304. */
  20305. setCustomSort( func ) {
  20306. this.customSort = func;
  20307. return this;
  20308. }
  20309. /**
  20310. * Computes the bounding box, updating {@link BatchedMesh#boundingBox}.
  20311. * Bounding boxes aren't computed by default. They need to be explicitly computed,
  20312. * otherwise they are `null`.
  20313. */
  20314. computeBoundingBox() {
  20315. if ( this.boundingBox === null ) {
  20316. this.boundingBox = new Box3();
  20317. }
  20318. const boundingBox = this.boundingBox;
  20319. const instanceInfo = this._instanceInfo;
  20320. boundingBox.makeEmpty();
  20321. for ( let i = 0, l = instanceInfo.length; i < l; i ++ ) {
  20322. if ( instanceInfo[ i ].active === false ) continue;
  20323. const geometryId = instanceInfo[ i ].geometryIndex;
  20324. this.getMatrixAt( i, _matrix$1 );
  20325. this.getBoundingBoxAt( geometryId, _box$1 ).applyMatrix4( _matrix$1 );
  20326. boundingBox.union( _box$1 );
  20327. }
  20328. }
  20329. /**
  20330. * Computes the bounding sphere, updating {@link BatchedMesh#boundingSphere}.
  20331. * Bounding spheres aren't computed by default. They need to be explicitly computed,
  20332. * otherwise they are `null`.
  20333. */
  20334. computeBoundingSphere() {
  20335. if ( this.boundingSphere === null ) {
  20336. this.boundingSphere = new Sphere();
  20337. }
  20338. const boundingSphere = this.boundingSphere;
  20339. const instanceInfo = this._instanceInfo;
  20340. boundingSphere.makeEmpty();
  20341. for ( let i = 0, l = instanceInfo.length; i < l; i ++ ) {
  20342. if ( instanceInfo[ i ].active === false ) continue;
  20343. const geometryId = instanceInfo[ i ].geometryIndex;
  20344. this.getMatrixAt( i, _matrix$1 );
  20345. this.getBoundingSphereAt( geometryId, _sphere$2 ).applyMatrix4( _matrix$1 );
  20346. boundingSphere.union( _sphere$2 );
  20347. }
  20348. }
  20349. /**
  20350. * Adds a new instance to the batch using the geometry of the given ID and returns
  20351. * a new id referring to the new instance to be used by other functions.
  20352. *
  20353. * @param {number} geometryId - The ID of a previously added geometry via {@link BatchedMesh#addGeometry}.
  20354. * @return {number} The instance ID.
  20355. */
  20356. addInstance( geometryId ) {
  20357. const atCapacity = this._instanceInfo.length >= this.maxInstanceCount;
  20358. // ensure we're not over geometry
  20359. if ( atCapacity && this._availableInstanceIds.length === 0 ) {
  20360. throw new Error( 'THREE.BatchedMesh: Maximum item count reached.' );
  20361. }
  20362. const instanceInfo = {
  20363. visible: true,
  20364. active: true,
  20365. geometryIndex: geometryId,
  20366. };
  20367. let drawId = null;
  20368. // Prioritize using previously freed instance ids
  20369. if ( this._availableInstanceIds.length > 0 ) {
  20370. this._availableInstanceIds.sort( ascIdSort );
  20371. drawId = this._availableInstanceIds.shift();
  20372. this._instanceInfo[ drawId ] = instanceInfo;
  20373. } else {
  20374. drawId = this._instanceInfo.length;
  20375. this._instanceInfo.push( instanceInfo );
  20376. }
  20377. const matricesTexture = this._matricesTexture;
  20378. _matrix$1.identity().toArray( matricesTexture.image.data, drawId * 16 );
  20379. matricesTexture.needsUpdate = true;
  20380. const colorsTexture = this._colorsTexture;
  20381. if ( colorsTexture ) {
  20382. _whiteColor.toArray( colorsTexture.image.data, drawId * 4 );
  20383. colorsTexture.needsUpdate = true;
  20384. }
  20385. this._visibilityChanged = true;
  20386. return drawId;
  20387. }
  20388. /**
  20389. * Adds the given geometry to the batch and returns the associated
  20390. * geometry id referring to it to be used in other functions.
  20391. *
  20392. * @param {BufferGeometry} geometry - The geometry to add.
  20393. * @param {number} [reservedVertexCount=-1] - Optional parameter specifying the amount of
  20394. * vertex buffer space to reserve for the added geometry. This is necessary if it is planned
  20395. * to set a new geometry at this index at a later time that is larger than the original geometry.
  20396. * Defaults to the length of the given geometry vertex buffer.
  20397. * @param {number} [reservedIndexCount=-1] - Optional parameter specifying the amount of index
  20398. * buffer space to reserve for the added geometry. This is necessary if it is planned to set a
  20399. * new geometry at this index at a later time that is larger than the original geometry. Defaults to
  20400. * the length of the given geometry index buffer.
  20401. * @return {number} The geometry ID.
  20402. */
  20403. addGeometry( geometry, reservedVertexCount = -1, reservedIndexCount = -1 ) {
  20404. this._initializeGeometry( geometry );
  20405. this._validateGeometry( geometry );
  20406. const geometryInfo = {
  20407. // geometry information
  20408. vertexStart: -1,
  20409. vertexCount: -1,
  20410. reservedVertexCount: -1,
  20411. indexStart: -1,
  20412. indexCount: -1,
  20413. reservedIndexCount: -1,
  20414. // draw range information
  20415. start: -1,
  20416. count: -1,
  20417. // state
  20418. boundingBox: null,
  20419. boundingSphere: null,
  20420. active: true,
  20421. };
  20422. const geometryInfoList = this._geometryInfo;
  20423. geometryInfo.vertexStart = this._nextVertexStart;
  20424. geometryInfo.reservedVertexCount = reservedVertexCount === -1 ? geometry.getAttribute( 'position' ).count : reservedVertexCount;
  20425. const index = geometry.getIndex();
  20426. const hasIndex = index !== null;
  20427. if ( hasIndex ) {
  20428. geometryInfo.indexStart = this._nextIndexStart;
  20429. geometryInfo.reservedIndexCount = reservedIndexCount === -1 ? index.count : reservedIndexCount;
  20430. }
  20431. if (
  20432. geometryInfo.indexStart !== -1 &&
  20433. geometryInfo.indexStart + geometryInfo.reservedIndexCount > this._maxIndexCount ||
  20434. geometryInfo.vertexStart + geometryInfo.reservedVertexCount > this._maxVertexCount
  20435. ) {
  20436. throw new Error( 'THREE.BatchedMesh: Reserved space request exceeds the maximum buffer size.' );
  20437. }
  20438. // update id
  20439. let geometryId;
  20440. if ( this._availableGeometryIds.length > 0 ) {
  20441. this._availableGeometryIds.sort( ascIdSort );
  20442. geometryId = this._availableGeometryIds.shift();
  20443. geometryInfoList[ geometryId ] = geometryInfo;
  20444. } else {
  20445. geometryId = this._geometryCount;
  20446. this._geometryCount ++;
  20447. geometryInfoList.push( geometryInfo );
  20448. }
  20449. // update the geometry
  20450. this.setGeometryAt( geometryId, geometry );
  20451. // increment the next geometry position
  20452. this._nextIndexStart = geometryInfo.indexStart + geometryInfo.reservedIndexCount;
  20453. this._nextVertexStart = geometryInfo.vertexStart + geometryInfo.reservedVertexCount;
  20454. return geometryId;
  20455. }
  20456. /**
  20457. * Replaces the geometry at the given ID with the provided geometry. Throws an error if there
  20458. * is not enough space reserved for geometry. Calling this will change all instances that are
  20459. * rendering that geometry.
  20460. *
  20461. * @param {number} geometryId - The ID of the geometry that should be replaced with the given geometry.
  20462. * @param {BufferGeometry} geometry - The new geometry.
  20463. * @return {number} The geometry ID.
  20464. */
  20465. setGeometryAt( geometryId, geometry ) {
  20466. if ( geometryId >= this._geometryCount ) {
  20467. throw new Error( 'THREE.BatchedMesh: Maximum geometry count reached.' );
  20468. }
  20469. this._validateGeometry( geometry );
  20470. const batchGeometry = this.geometry;
  20471. const hasIndex = batchGeometry.getIndex() !== null;
  20472. const dstIndex = batchGeometry.getIndex();
  20473. const srcIndex = geometry.getIndex();
  20474. const geometryInfo = this._geometryInfo[ geometryId ];
  20475. if (
  20476. hasIndex &&
  20477. srcIndex.count > geometryInfo.reservedIndexCount ||
  20478. geometry.attributes.position.count > geometryInfo.reservedVertexCount
  20479. ) {
  20480. throw new Error( 'THREE.BatchedMesh: Reserved space not large enough for provided geometry.' );
  20481. }
  20482. // copy geometry buffer data over
  20483. const vertexStart = geometryInfo.vertexStart;
  20484. const reservedVertexCount = geometryInfo.reservedVertexCount;
  20485. geometryInfo.vertexCount = geometry.getAttribute( 'position' ).count;
  20486. for ( const attributeName in batchGeometry.attributes ) {
  20487. // copy attribute data
  20488. const srcAttribute = geometry.getAttribute( attributeName );
  20489. const dstAttribute = batchGeometry.getAttribute( attributeName );
  20490. copyAttributeData( srcAttribute, dstAttribute, vertexStart );
  20491. // fill the rest in with zeroes
  20492. const itemSize = srcAttribute.itemSize;
  20493. for ( let i = srcAttribute.count, l = reservedVertexCount; i < l; i ++ ) {
  20494. const index = vertexStart + i;
  20495. for ( let c = 0; c < itemSize; c ++ ) {
  20496. dstAttribute.setComponent( index, c, 0 );
  20497. }
  20498. }
  20499. dstAttribute.needsUpdate = true;
  20500. dstAttribute.addUpdateRange( vertexStart * itemSize, reservedVertexCount * itemSize );
  20501. }
  20502. // copy index
  20503. if ( hasIndex ) {
  20504. const indexStart = geometryInfo.indexStart;
  20505. const reservedIndexCount = geometryInfo.reservedIndexCount;
  20506. geometryInfo.indexCount = geometry.getIndex().count;
  20507. // copy index data over
  20508. for ( let i = 0; i < srcIndex.count; i ++ ) {
  20509. dstIndex.setX( indexStart + i, vertexStart + srcIndex.getX( i ) );
  20510. }
  20511. // fill the rest in with zeroes
  20512. for ( let i = srcIndex.count, l = reservedIndexCount; i < l; i ++ ) {
  20513. dstIndex.setX( indexStart + i, vertexStart );
  20514. }
  20515. dstIndex.needsUpdate = true;
  20516. dstIndex.addUpdateRange( indexStart, geometryInfo.reservedIndexCount );
  20517. }
  20518. // update the draw range
  20519. geometryInfo.start = hasIndex ? geometryInfo.indexStart : geometryInfo.vertexStart;
  20520. geometryInfo.count = hasIndex ? geometryInfo.indexCount : geometryInfo.vertexCount;
  20521. // store the bounding boxes
  20522. geometryInfo.boundingBox = null;
  20523. if ( geometry.boundingBox !== null ) {
  20524. geometryInfo.boundingBox = geometry.boundingBox.clone();
  20525. }
  20526. geometryInfo.boundingSphere = null;
  20527. if ( geometry.boundingSphere !== null ) {
  20528. geometryInfo.boundingSphere = geometry.boundingSphere.clone();
  20529. }
  20530. this._visibilityChanged = true;
  20531. return geometryId;
  20532. }
  20533. /**
  20534. * Deletes the geometry defined by the given ID from this batch. Any instances referencing
  20535. * this geometry will also be removed as a side effect.
  20536. *
  20537. * @param {number} geometryId - The ID of the geometry to remove from the batch.
  20538. * @return {BatchedMesh} A reference to this batched mesh.
  20539. */
  20540. deleteGeometry( geometryId ) {
  20541. const geometryInfoList = this._geometryInfo;
  20542. if ( geometryId >= geometryInfoList.length || geometryInfoList[ geometryId ].active === false ) {
  20543. return this;
  20544. }
  20545. // delete any instances associated with this geometry
  20546. const instanceInfo = this._instanceInfo;
  20547. for ( let i = 0, l = instanceInfo.length; i < l; i ++ ) {
  20548. if ( instanceInfo[ i ].active && instanceInfo[ i ].geometryIndex === geometryId ) {
  20549. this.deleteInstance( i );
  20550. }
  20551. }
  20552. geometryInfoList[ geometryId ].active = false;
  20553. this._availableGeometryIds.push( geometryId );
  20554. this._visibilityChanged = true;
  20555. return this;
  20556. }
  20557. /**
  20558. * Deletes an existing instance from the batch using the given ID.
  20559. *
  20560. * @param {number} instanceId - The ID of the instance to remove from the batch.
  20561. * @return {BatchedMesh} A reference to this batched mesh.
  20562. */
  20563. deleteInstance( instanceId ) {
  20564. this.validateInstanceId( instanceId );
  20565. this._instanceInfo[ instanceId ].active = false;
  20566. this._availableInstanceIds.push( instanceId );
  20567. this._visibilityChanged = true;
  20568. return this;
  20569. }
  20570. /**
  20571. * Repacks the sub geometries in BatchedMesh to remove any unused space remaining from
  20572. * previously deleted geometry, freeing up space to add new geometry.
  20573. *
  20574. * @return {BatchedMesh} A reference to this batched mesh.
  20575. */
  20576. optimize() {
  20577. // track the next indices to copy data to
  20578. let nextVertexStart = 0;
  20579. let nextIndexStart = 0;
  20580. // Iterate over all geometry ranges in order sorted from earliest in the geometry buffer to latest
  20581. // in the geometry buffer. Because draw range objects can be reused there is no guarantee of their order.
  20582. const geometryInfoList = this._geometryInfo;
  20583. const indices = geometryInfoList
  20584. .map( ( e, i ) => i )
  20585. .sort( ( a, b ) => {
  20586. return geometryInfoList[ a ].vertexStart - geometryInfoList[ b ].vertexStart;
  20587. } );
  20588. const geometry = this.geometry;
  20589. for ( let i = 0, l = geometryInfoList.length; i < l; i ++ ) {
  20590. // if a geometry range is inactive then don't copy anything
  20591. const index = indices[ i ];
  20592. const geometryInfo = geometryInfoList[ index ];
  20593. if ( geometryInfo.active === false ) {
  20594. continue;
  20595. }
  20596. // if a geometry contains an index buffer then shift it, as well
  20597. if ( geometry.index !== null ) {
  20598. if ( geometryInfo.indexStart !== nextIndexStart ) {
  20599. const { indexStart, vertexStart, reservedIndexCount } = geometryInfo;
  20600. const index = geometry.index;
  20601. const array = index.array;
  20602. // shift the index pointers based on how the vertex data will shift
  20603. // adjusting the index must happen first so the original vertex start value is available
  20604. const elementDelta = nextVertexStart - vertexStart;
  20605. for ( let j = indexStart; j < indexStart + reservedIndexCount; j ++ ) {
  20606. array[ j ] = array[ j ] + elementDelta;
  20607. }
  20608. index.array.copyWithin( nextIndexStart, indexStart, indexStart + reservedIndexCount );
  20609. index.addUpdateRange( nextIndexStart, reservedIndexCount );
  20610. index.needsUpdate = true;
  20611. geometryInfo.indexStart = nextIndexStart;
  20612. }
  20613. nextIndexStart += geometryInfo.reservedIndexCount;
  20614. }
  20615. // if a geometry needs to be moved then copy attribute data to overwrite unused space
  20616. if ( geometryInfo.vertexStart !== nextVertexStart ) {
  20617. const { vertexStart, reservedVertexCount } = geometryInfo;
  20618. const attributes = geometry.attributes;
  20619. for ( const key in attributes ) {
  20620. const attribute = attributes[ key ];
  20621. const { array, itemSize } = attribute;
  20622. array.copyWithin( nextVertexStart * itemSize, vertexStart * itemSize, ( vertexStart + reservedVertexCount ) * itemSize );
  20623. attribute.addUpdateRange( nextVertexStart * itemSize, reservedVertexCount * itemSize );
  20624. attribute.needsUpdate = true;
  20625. }
  20626. geometryInfo.vertexStart = nextVertexStart;
  20627. }
  20628. nextVertexStart += geometryInfo.reservedVertexCount;
  20629. geometryInfo.start = geometry.index ? geometryInfo.indexStart : geometryInfo.vertexStart;
  20630. // step the next geometry points to the shifted position
  20631. this._nextIndexStart = geometry.index ? geometryInfo.indexStart + geometryInfo.reservedIndexCount : 0;
  20632. this._nextVertexStart = geometryInfo.vertexStart + geometryInfo.reservedVertexCount;
  20633. }
  20634. this._visibilityChanged = true;
  20635. return this;
  20636. }
  20637. /**
  20638. * Returns the bounding box for the given geometry.
  20639. *
  20640. * @param {number} geometryId - The ID of the geometry to return the bounding box for.
  20641. * @param {Box3} target - The target object that is used to store the method's result.
  20642. * @return {?Box3} The geometry's bounding box. Returns `null` if no geometry has been found for the given ID.
  20643. */
  20644. getBoundingBoxAt( geometryId, target ) {
  20645. if ( geometryId >= this._geometryCount ) {
  20646. return null;
  20647. }
  20648. // compute bounding box
  20649. const geometry = this.geometry;
  20650. const geometryInfo = this._geometryInfo[ geometryId ];
  20651. if ( geometryInfo.boundingBox === null ) {
  20652. const box = new Box3();
  20653. const index = geometry.index;
  20654. const position = geometry.attributes.position;
  20655. for ( let i = geometryInfo.start, l = geometryInfo.start + geometryInfo.count; i < l; i ++ ) {
  20656. let iv = i;
  20657. if ( index ) {
  20658. iv = index.getX( iv );
  20659. }
  20660. box.expandByPoint( _vector$5.fromBufferAttribute( position, iv ) );
  20661. }
  20662. geometryInfo.boundingBox = box;
  20663. }
  20664. target.copy( geometryInfo.boundingBox );
  20665. return target;
  20666. }
  20667. /**
  20668. * Returns the bounding sphere for the given geometry.
  20669. *
  20670. * @param {number} geometryId - The ID of the geometry to return the bounding sphere for.
  20671. * @param {Sphere} target - The target object that is used to store the method's result.
  20672. * @return {?Sphere} The geometry's bounding sphere. Returns `null` if no geometry has been found for the given ID.
  20673. */
  20674. getBoundingSphereAt( geometryId, target ) {
  20675. if ( geometryId >= this._geometryCount ) {
  20676. return null;
  20677. }
  20678. // compute bounding sphere
  20679. const geometry = this.geometry;
  20680. const geometryInfo = this._geometryInfo[ geometryId ];
  20681. if ( geometryInfo.boundingSphere === null ) {
  20682. const sphere = new Sphere();
  20683. this.getBoundingBoxAt( geometryId, _box$1 );
  20684. _box$1.getCenter( sphere.center );
  20685. const index = geometry.index;
  20686. const position = geometry.attributes.position;
  20687. let maxRadiusSq = 0;
  20688. for ( let i = geometryInfo.start, l = geometryInfo.start + geometryInfo.count; i < l; i ++ ) {
  20689. let iv = i;
  20690. if ( index ) {
  20691. iv = index.getX( iv );
  20692. }
  20693. _vector$5.fromBufferAttribute( position, iv );
  20694. maxRadiusSq = Math.max( maxRadiusSq, sphere.center.distanceToSquared( _vector$5 ) );
  20695. }
  20696. sphere.radius = Math.sqrt( maxRadiusSq );
  20697. geometryInfo.boundingSphere = sphere;
  20698. }
  20699. target.copy( geometryInfo.boundingSphere );
  20700. return target;
  20701. }
  20702. /**
  20703. * Sets the given local transformation matrix to the defined instance.
  20704. * Negatively scaled matrices are not supported.
  20705. *
  20706. * @param {number} instanceId - The ID of an instance to set the matrix of.
  20707. * @param {Matrix4} matrix - A 4x4 matrix representing the local transformation of a single instance.
  20708. * @return {BatchedMesh} A reference to this batched mesh.
  20709. */
  20710. setMatrixAt( instanceId, matrix ) {
  20711. this.validateInstanceId( instanceId );
  20712. const matricesTexture = this._matricesTexture;
  20713. const matricesArray = this._matricesTexture.image.data;
  20714. matrix.toArray( matricesArray, instanceId * 16 );
  20715. matricesTexture.needsUpdate = true;
  20716. return this;
  20717. }
  20718. /**
  20719. * Returns the local transformation matrix of the defined instance.
  20720. *
  20721. * @param {number} instanceId - The ID of an instance to get the matrix of.
  20722. * @param {Matrix4} matrix - The target object that is used to store the method's result.
  20723. * @return {Matrix4} The instance's local transformation matrix.
  20724. */
  20725. getMatrixAt( instanceId, matrix ) {
  20726. this.validateInstanceId( instanceId );
  20727. return matrix.fromArray( this._matricesTexture.image.data, instanceId * 16 );
  20728. }
  20729. /**
  20730. * Sets the given color to the defined instance.
  20731. *
  20732. * @param {number} instanceId - The ID of an instance to set the color of.
  20733. * @param {Color} color - The color to set the instance to.
  20734. * @return {BatchedMesh} A reference to this batched mesh.
  20735. */
  20736. setColorAt( instanceId, color ) {
  20737. this.validateInstanceId( instanceId );
  20738. if ( this._colorsTexture === null ) {
  20739. this._initColorsTexture();
  20740. }
  20741. color.toArray( this._colorsTexture.image.data, instanceId * 4 );
  20742. this._colorsTexture.needsUpdate = true;
  20743. return this;
  20744. }
  20745. /**
  20746. * Returns the color of the defined instance.
  20747. *
  20748. * @param {number} instanceId - The ID of an instance to get the color of.
  20749. * @param {Color} color - The target object that is used to store the method's result.
  20750. * @return {Color} The instance's color.
  20751. */
  20752. getColorAt( instanceId, color ) {
  20753. this.validateInstanceId( instanceId );
  20754. return color.fromArray( this._colorsTexture.image.data, instanceId * 4 );
  20755. }
  20756. /**
  20757. * Sets the visibility of the instance.
  20758. *
  20759. * @param {number} instanceId - The id of the instance to set the visibility of.
  20760. * @param {boolean} visible - Whether the instance is visible or not.
  20761. * @return {BatchedMesh} A reference to this batched mesh.
  20762. */
  20763. setVisibleAt( instanceId, visible ) {
  20764. this.validateInstanceId( instanceId );
  20765. if ( this._instanceInfo[ instanceId ].visible === visible ) {
  20766. return this;
  20767. }
  20768. this._instanceInfo[ instanceId ].visible = visible;
  20769. this._visibilityChanged = true;
  20770. return this;
  20771. }
  20772. /**
  20773. * Returns the visibility state of the defined instance.
  20774. *
  20775. * @param {number} instanceId - The ID of an instance to get the visibility state of.
  20776. * @return {boolean} Whether the instance is visible or not.
  20777. */
  20778. getVisibleAt( instanceId ) {
  20779. this.validateInstanceId( instanceId );
  20780. return this._instanceInfo[ instanceId ].visible;
  20781. }
  20782. /**
  20783. * Sets the geometry ID of the instance at the given index.
  20784. *
  20785. * @param {number} instanceId - The ID of the instance to set the geometry ID of.
  20786. * @param {number} geometryId - The geometry ID to be use by the instance.
  20787. * @return {BatchedMesh} A reference to this batched mesh.
  20788. */
  20789. setGeometryIdAt( instanceId, geometryId ) {
  20790. this.validateInstanceId( instanceId );
  20791. this.validateGeometryId( geometryId );
  20792. this._instanceInfo[ instanceId ].geometryIndex = geometryId;
  20793. return this;
  20794. }
  20795. /**
  20796. * Returns the geometry ID of the defined instance.
  20797. *
  20798. * @param {number} instanceId - The ID of an instance to get the geometry ID of.
  20799. * @return {number} The instance's geometry ID.
  20800. */
  20801. getGeometryIdAt( instanceId ) {
  20802. this.validateInstanceId( instanceId );
  20803. return this._instanceInfo[ instanceId ].geometryIndex;
  20804. }
  20805. /**
  20806. * Get the range representing the subset of triangles related to the attached geometry,
  20807. * indicating the starting offset and count, or `null` if invalid.
  20808. *
  20809. * @param {number} geometryId - The id of the geometry to get the range of.
  20810. * @param {Object} [target] - The target object that is used to store the method's result.
  20811. * @return {{
  20812. * vertexStart:number,vertexCount:number,reservedVertexCount:number,
  20813. * indexStart:number,indexCount:number,reservedIndexCount:number,
  20814. * start:number,count:number
  20815. * }} The result object with range data.
  20816. */
  20817. getGeometryRangeAt( geometryId, target = {} ) {
  20818. this.validateGeometryId( geometryId );
  20819. const geometryInfo = this._geometryInfo[ geometryId ];
  20820. target.vertexStart = geometryInfo.vertexStart;
  20821. target.vertexCount = geometryInfo.vertexCount;
  20822. target.reservedVertexCount = geometryInfo.reservedVertexCount;
  20823. target.indexStart = geometryInfo.indexStart;
  20824. target.indexCount = geometryInfo.indexCount;
  20825. target.reservedIndexCount = geometryInfo.reservedIndexCount;
  20826. target.start = geometryInfo.start;
  20827. target.count = geometryInfo.count;
  20828. return target;
  20829. }
  20830. /**
  20831. * Resizes the necessary buffers to support the provided number of instances.
  20832. * If the provided arguments shrink the number of instances but there are not enough
  20833. * unused Ids at the end of the list then an error is thrown.
  20834. *
  20835. * @param {number} maxInstanceCount - The max number of individual instances that can be added and rendered by the batch.
  20836. */
  20837. setInstanceCount( maxInstanceCount ) {
  20838. // shrink the available instances as much as possible
  20839. const availableInstanceIds = this._availableInstanceIds;
  20840. const instanceInfo = this._instanceInfo;
  20841. availableInstanceIds.sort( ascIdSort );
  20842. while ( availableInstanceIds[ availableInstanceIds.length - 1 ] === instanceInfo.length - 1 ) {
  20843. instanceInfo.pop();
  20844. availableInstanceIds.pop();
  20845. }
  20846. // throw an error if it can't be shrunk to the desired size
  20847. if ( maxInstanceCount < instanceInfo.length ) {
  20848. throw new Error( `BatchedMesh: Instance ids outside the range ${ maxInstanceCount } are being used. Cannot shrink instance count.` );
  20849. }
  20850. // copy the multi draw counts
  20851. const multiDrawCounts = new Int32Array( maxInstanceCount );
  20852. const multiDrawStarts = new Int32Array( maxInstanceCount );
  20853. copyArrayContents( this._multiDrawCounts, multiDrawCounts );
  20854. copyArrayContents( this._multiDrawStarts, multiDrawStarts );
  20855. this._multiDrawCounts = multiDrawCounts;
  20856. this._multiDrawStarts = multiDrawStarts;
  20857. this._maxInstanceCount = maxInstanceCount;
  20858. // update texture data for instance sampling
  20859. const indirectTexture = this._indirectTexture;
  20860. const matricesTexture = this._matricesTexture;
  20861. const colorsTexture = this._colorsTexture;
  20862. indirectTexture.dispose();
  20863. this._initIndirectTexture();
  20864. copyArrayContents( indirectTexture.image.data, this._indirectTexture.image.data );
  20865. matricesTexture.dispose();
  20866. this._initMatricesTexture();
  20867. copyArrayContents( matricesTexture.image.data, this._matricesTexture.image.data );
  20868. if ( colorsTexture ) {
  20869. colorsTexture.dispose();
  20870. this._initColorsTexture();
  20871. copyArrayContents( colorsTexture.image.data, this._colorsTexture.image.data );
  20872. }
  20873. }
  20874. /**
  20875. * Resizes the available space in the batch's vertex and index buffer attributes to the provided sizes.
  20876. * If the provided arguments shrink the geometry buffers but there is not enough unused space at the
  20877. * end of the geometry attributes then an error is thrown.
  20878. *
  20879. * @param {number} maxVertexCount - The maximum number of vertices to be used by all unique geometries to resize to.
  20880. * @param {number} maxIndexCount - The maximum number of indices to be used by all unique geometries to resize to.
  20881. */
  20882. setGeometrySize( maxVertexCount, maxIndexCount ) {
  20883. // Check if we can shrink to the requested vertex attribute size
  20884. const validRanges = [ ...this._geometryInfo ].filter( info => info.active );
  20885. const requiredVertexLength = Math.max( ...validRanges.map( range => range.vertexStart + range.reservedVertexCount ) );
  20886. if ( requiredVertexLength > maxVertexCount ) {
  20887. throw new Error( `BatchedMesh: Geometry vertex values are being used outside the range ${ maxIndexCount }. Cannot shrink further.` );
  20888. }
  20889. // Check if we can shrink to the requested index attribute size
  20890. if ( this.geometry.index ) {
  20891. const requiredIndexLength = Math.max( ...validRanges.map( range => range.indexStart + range.reservedIndexCount ) );
  20892. if ( requiredIndexLength > maxIndexCount ) {
  20893. throw new Error( `BatchedMesh: Geometry index values are being used outside the range ${ maxIndexCount }. Cannot shrink further.` );
  20894. }
  20895. }
  20896. //
  20897. // dispose of the previous geometry
  20898. const oldGeometry = this.geometry;
  20899. oldGeometry.dispose();
  20900. // recreate the geometry needed based on the previous variant
  20901. this._maxVertexCount = maxVertexCount;
  20902. this._maxIndexCount = maxIndexCount;
  20903. if ( this._geometryInitialized ) {
  20904. this._geometryInitialized = false;
  20905. this.geometry = new BufferGeometry();
  20906. this._initializeGeometry( oldGeometry );
  20907. }
  20908. // copy data from the previous geometry
  20909. const geometry = this.geometry;
  20910. if ( oldGeometry.index ) {
  20911. copyArrayContents( oldGeometry.index.array, geometry.index.array );
  20912. }
  20913. for ( const key in oldGeometry.attributes ) {
  20914. copyArrayContents( oldGeometry.attributes[ key ].array, geometry.attributes[ key ].array );
  20915. }
  20916. }
  20917. raycast( raycaster, intersects ) {
  20918. const instanceInfo = this._instanceInfo;
  20919. const geometryInfoList = this._geometryInfo;
  20920. const matrixWorld = this.matrixWorld;
  20921. const batchGeometry = this.geometry;
  20922. // iterate over each geometry
  20923. _mesh.material = this.material;
  20924. _mesh.geometry.index = batchGeometry.index;
  20925. _mesh.geometry.attributes = batchGeometry.attributes;
  20926. if ( _mesh.geometry.boundingBox === null ) {
  20927. _mesh.geometry.boundingBox = new Box3();
  20928. }
  20929. if ( _mesh.geometry.boundingSphere === null ) {
  20930. _mesh.geometry.boundingSphere = new Sphere();
  20931. }
  20932. for ( let i = 0, l = instanceInfo.length; i < l; i ++ ) {
  20933. if ( ! instanceInfo[ i ].visible || ! instanceInfo[ i ].active ) {
  20934. continue;
  20935. }
  20936. const geometryId = instanceInfo[ i ].geometryIndex;
  20937. const geometryInfo = geometryInfoList[ geometryId ];
  20938. _mesh.geometry.setDrawRange( geometryInfo.start, geometryInfo.count );
  20939. // get the intersects
  20940. this.getMatrixAt( i, _mesh.matrixWorld ).premultiply( matrixWorld );
  20941. this.getBoundingBoxAt( geometryId, _mesh.geometry.boundingBox );
  20942. this.getBoundingSphereAt( geometryId, _mesh.geometry.boundingSphere );
  20943. _mesh.raycast( raycaster, _batchIntersects );
  20944. // add batch id to the intersects
  20945. for ( let j = 0, l = _batchIntersects.length; j < l; j ++ ) {
  20946. const intersect = _batchIntersects[ j ];
  20947. intersect.object = this;
  20948. intersect.batchId = i;
  20949. intersects.push( intersect );
  20950. }
  20951. _batchIntersects.length = 0;
  20952. }
  20953. _mesh.material = null;
  20954. _mesh.geometry.index = null;
  20955. _mesh.geometry.attributes = {};
  20956. _mesh.geometry.setDrawRange( 0, Infinity );
  20957. }
  20958. copy( source ) {
  20959. super.copy( source );
  20960. this.geometry = source.geometry.clone();
  20961. this.perObjectFrustumCulled = source.perObjectFrustumCulled;
  20962. this.sortObjects = source.sortObjects;
  20963. this.boundingBox = source.boundingBox !== null ? source.boundingBox.clone() : null;
  20964. this.boundingSphere = source.boundingSphere !== null ? source.boundingSphere.clone() : null;
  20965. this._geometryInfo = source._geometryInfo.map( info => ( {
  20966. ...info,
  20967. boundingBox: info.boundingBox !== null ? info.boundingBox.clone() : null,
  20968. boundingSphere: info.boundingSphere !== null ? info.boundingSphere.clone() : null,
  20969. } ) );
  20970. this._instanceInfo = source._instanceInfo.map( info => ( { ...info } ) );
  20971. this._availableInstanceIds = source._availableInstanceIds.slice();
  20972. this._availableGeometryIds = source._availableGeometryIds.slice();
  20973. this._nextIndexStart = source._nextIndexStart;
  20974. this._nextVertexStart = source._nextVertexStart;
  20975. this._geometryCount = source._geometryCount;
  20976. this._maxInstanceCount = source._maxInstanceCount;
  20977. this._maxVertexCount = source._maxVertexCount;
  20978. this._maxIndexCount = source._maxIndexCount;
  20979. this._geometryInitialized = source._geometryInitialized;
  20980. this._multiDrawCounts = source._multiDrawCounts.slice();
  20981. this._multiDrawStarts = source._multiDrawStarts.slice();
  20982. this._indirectTexture = source._indirectTexture.clone();
  20983. this._indirectTexture.image.data = this._indirectTexture.image.data.slice();
  20984. this._matricesTexture = source._matricesTexture.clone();
  20985. this._matricesTexture.image.data = this._matricesTexture.image.data.slice();
  20986. if ( this._colorsTexture !== null ) {
  20987. this._colorsTexture = source._colorsTexture.clone();
  20988. this._colorsTexture.image.data = this._colorsTexture.image.data.slice();
  20989. }
  20990. return this;
  20991. }
  20992. /**
  20993. * Frees the GPU-related resources allocated by this instance. Call this
  20994. * method whenever this instance is no longer used in your app.
  20995. */
  20996. dispose() {
  20997. // Assuming the geometry is not shared with other meshes
  20998. this.geometry.dispose();
  20999. this._matricesTexture.dispose();
  21000. this._matricesTexture = null;
  21001. this._indirectTexture.dispose();
  21002. this._indirectTexture = null;
  21003. if ( this._colorsTexture !== null ) {
  21004. this._colorsTexture.dispose();
  21005. this._colorsTexture = null;
  21006. }
  21007. }
  21008. onBeforeRender( renderer, scene, camera, geometry, material/*, _group*/ ) {
  21009. // if visibility has not changed and frustum culling and object sorting is not required
  21010. // then skip iterating over all items
  21011. if ( ! this._visibilityChanged && ! this.perObjectFrustumCulled && ! this.sortObjects ) {
  21012. return;
  21013. }
  21014. // the indexed version of the multi draw function requires specifying the start
  21015. // offset in bytes.
  21016. const index = geometry.getIndex();
  21017. const bytesPerElement = index === null ? 1 : index.array.BYTES_PER_ELEMENT;
  21018. const instanceInfo = this._instanceInfo;
  21019. const multiDrawStarts = this._multiDrawStarts;
  21020. const multiDrawCounts = this._multiDrawCounts;
  21021. const geometryInfoList = this._geometryInfo;
  21022. const perObjectFrustumCulled = this.perObjectFrustumCulled;
  21023. const indirectTexture = this._indirectTexture;
  21024. const indirectArray = indirectTexture.image.data;
  21025. const frustum = camera.isArrayCamera ? _frustumArray : _frustum;
  21026. // prepare the frustum in the local frame
  21027. if ( perObjectFrustumCulled && ! camera.isArrayCamera ) {
  21028. _matrix$1
  21029. .multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse )
  21030. .multiply( this.matrixWorld );
  21031. _frustum.setFromProjectionMatrix(
  21032. _matrix$1,
  21033. camera.coordinateSystem,
  21034. camera.reversedDepth
  21035. );
  21036. }
  21037. let multiDrawCount = 0;
  21038. if ( this.sortObjects ) {
  21039. // get the camera position in the local frame
  21040. _matrix$1.copy( this.matrixWorld ).invert();
  21041. _vector$5.setFromMatrixPosition( camera.matrixWorld ).applyMatrix4( _matrix$1 );
  21042. _forward$1.set( 0, 0, -1 ).transformDirection( camera.matrixWorld ).transformDirection( _matrix$1 );
  21043. for ( let i = 0, l = instanceInfo.length; i < l; i ++ ) {
  21044. if ( instanceInfo[ i ].visible && instanceInfo[ i ].active ) {
  21045. const geometryId = instanceInfo[ i ].geometryIndex;
  21046. // get the bounds in world space
  21047. this.getMatrixAt( i, _matrix$1 );
  21048. this.getBoundingSphereAt( geometryId, _sphere$2 ).applyMatrix4( _matrix$1 );
  21049. // determine whether the batched geometry is within the frustum
  21050. let culled = false;
  21051. if ( perObjectFrustumCulled ) {
  21052. culled = ! frustum.intersectsSphere( _sphere$2, camera );
  21053. }
  21054. if ( ! culled ) {
  21055. // get the distance from camera used for sorting
  21056. const geometryInfo = geometryInfoList[ geometryId ];
  21057. const z = _temp.subVectors( _sphere$2.center, _vector$5 ).dot( _forward$1 );
  21058. _renderList.push( geometryInfo.start, geometryInfo.count, z, i );
  21059. }
  21060. }
  21061. }
  21062. // Sort the draw ranges and prep for rendering
  21063. const list = _renderList.list;
  21064. const customSort = this.customSort;
  21065. if ( customSort === null ) {
  21066. list.sort( material.transparent ? sortTransparent : sortOpaque );
  21067. } else {
  21068. customSort.call( this, list, camera );
  21069. }
  21070. for ( let i = 0, l = list.length; i < l; i ++ ) {
  21071. const item = list[ i ];
  21072. multiDrawStarts[ multiDrawCount ] = item.start * bytesPerElement;
  21073. multiDrawCounts[ multiDrawCount ] = item.count;
  21074. indirectArray[ multiDrawCount ] = item.index;
  21075. multiDrawCount ++;
  21076. }
  21077. _renderList.reset();
  21078. } else {
  21079. for ( let i = 0, l = instanceInfo.length; i < l; i ++ ) {
  21080. if ( instanceInfo[ i ].visible && instanceInfo[ i ].active ) {
  21081. const geometryId = instanceInfo[ i ].geometryIndex;
  21082. // determine whether the batched geometry is within the frustum
  21083. let culled = false;
  21084. if ( perObjectFrustumCulled ) {
  21085. // get the bounds in world space
  21086. this.getMatrixAt( i, _matrix$1 );
  21087. this.getBoundingSphereAt( geometryId, _sphere$2 ).applyMatrix4( _matrix$1 );
  21088. culled = ! frustum.intersectsSphere( _sphere$2, camera );
  21089. }
  21090. if ( ! culled ) {
  21091. const geometryInfo = geometryInfoList[ geometryId ];
  21092. multiDrawStarts[ multiDrawCount ] = geometryInfo.start * bytesPerElement;
  21093. multiDrawCounts[ multiDrawCount ] = geometryInfo.count;
  21094. indirectArray[ multiDrawCount ] = i;
  21095. multiDrawCount ++;
  21096. }
  21097. }
  21098. }
  21099. }
  21100. indirectTexture.needsUpdate = true;
  21101. this._multiDrawCount = multiDrawCount;
  21102. this._visibilityChanged = false;
  21103. }
  21104. onBeforeShadow( renderer, object, camera, shadowCamera, geometry, depthMaterial/* , group */ ) {
  21105. this.onBeforeRender( renderer, null, shadowCamera, geometry, depthMaterial );
  21106. }
  21107. }
  21108. /**
  21109. * A material for rendering line primitives.
  21110. *
  21111. * Materials define the appearance of renderable 3D objects.
  21112. *
  21113. * ```js
  21114. * const material = new THREE.LineBasicMaterial( { color: 0xffffff } );
  21115. * ```
  21116. *
  21117. * @augments Material
  21118. */
  21119. class LineBasicMaterial extends Material {
  21120. /**
  21121. * Constructs a new line basic material.
  21122. *
  21123. * @param {Object} [parameters] - An object with one or more properties
  21124. * defining the material's appearance. Any property of the material
  21125. * (including any property from inherited materials) can be passed
  21126. * in here. Color values can be passed any type of value accepted
  21127. * by {@link Color#set}.
  21128. */
  21129. constructor( parameters ) {
  21130. super();
  21131. /**
  21132. * This flag can be used for type testing.
  21133. *
  21134. * @type {boolean}
  21135. * @readonly
  21136. * @default true
  21137. */
  21138. this.isLineBasicMaterial = true;
  21139. this.type = 'LineBasicMaterial';
  21140. /**
  21141. * Color of the material.
  21142. *
  21143. * @type {Color}
  21144. * @default (1,1,1)
  21145. */
  21146. this.color = new Color( 0xffffff );
  21147. /**
  21148. * Sets the color of the lines using data from a texture. The texture map
  21149. * color is modulated by the diffuse `color`.
  21150. *
  21151. * @type {?Texture}
  21152. * @default null
  21153. */
  21154. this.map = null;
  21155. /**
  21156. * Controls line thickness or lines.
  21157. *
  21158. * Can only be used with {@link SVGRenderer}. WebGL and WebGPU
  21159. * ignore this setting and always render line primitives with a
  21160. * width of one pixel.
  21161. *
  21162. * @type {number}
  21163. * @default 1
  21164. */
  21165. this.linewidth = 1;
  21166. /**
  21167. * Defines appearance of line ends.
  21168. *
  21169. * Can only be used with {@link SVGRenderer}.
  21170. *
  21171. * @type {('butt'|'round'|'square')}
  21172. * @default 'round'
  21173. */
  21174. this.linecap = 'round';
  21175. /**
  21176. * Defines appearance of line joints.
  21177. *
  21178. * Can only be used with {@link SVGRenderer}.
  21179. *
  21180. * @type {('round'|'bevel'|'miter')}
  21181. * @default 'round'
  21182. */
  21183. this.linejoin = 'round';
  21184. /**
  21185. * Whether the material is affected by fog or not.
  21186. *
  21187. * @type {boolean}
  21188. * @default true
  21189. */
  21190. this.fog = true;
  21191. this.setValues( parameters );
  21192. }
  21193. copy( source ) {
  21194. super.copy( source );
  21195. this.color.copy( source.color );
  21196. this.map = source.map;
  21197. this.linewidth = source.linewidth;
  21198. this.linecap = source.linecap;
  21199. this.linejoin = source.linejoin;
  21200. this.fog = source.fog;
  21201. return this;
  21202. }
  21203. }
  21204. const _vStart = /*@__PURE__*/ new Vector3();
  21205. const _vEnd = /*@__PURE__*/ new Vector3();
  21206. const _inverseMatrix$1 = /*@__PURE__*/ new Matrix4();
  21207. const _ray$1 = /*@__PURE__*/ new Ray();
  21208. const _sphere$1 = /*@__PURE__*/ new Sphere();
  21209. const _intersectPointOnRay = /*@__PURE__*/ new Vector3();
  21210. const _intersectPointOnSegment = /*@__PURE__*/ new Vector3();
  21211. /**
  21212. * A continuous line. The line are rendered by connecting consecutive
  21213. * vertices with straight lines.
  21214. *
  21215. * ```js
  21216. * const material = new THREE.LineBasicMaterial( { color: 0x0000ff } );
  21217. *
  21218. * const points = [];
  21219. * points.push( new THREE.Vector3( - 10, 0, 0 ) );
  21220. * points.push( new THREE.Vector3( 0, 10, 0 ) );
  21221. * points.push( new THREE.Vector3( 10, 0, 0 ) );
  21222. *
  21223. * const geometry = new THREE.BufferGeometry().setFromPoints( points );
  21224. *
  21225. * const line = new THREE.Line( geometry, material );
  21226. * scene.add( line );
  21227. * ```
  21228. *
  21229. * @augments Object3D
  21230. */
  21231. class Line extends Object3D {
  21232. /**
  21233. * Constructs a new line.
  21234. *
  21235. * @param {BufferGeometry} [geometry] - The line geometry.
  21236. * @param {Material|Array<Material>} [material] - The line material.
  21237. */
  21238. constructor( geometry = new BufferGeometry(), material = new LineBasicMaterial() ) {
  21239. super();
  21240. /**
  21241. * This flag can be used for type testing.
  21242. *
  21243. * @type {boolean}
  21244. * @readonly
  21245. * @default true
  21246. */
  21247. this.isLine = true;
  21248. this.type = 'Line';
  21249. /**
  21250. * The line geometry.
  21251. *
  21252. * @type {BufferGeometry}
  21253. */
  21254. this.geometry = geometry;
  21255. /**
  21256. * The line material.
  21257. *
  21258. * @type {Material|Array<Material>}
  21259. * @default LineBasicMaterial
  21260. */
  21261. this.material = material;
  21262. /**
  21263. * A dictionary representing the morph targets in the geometry. The key is the
  21264. * morph targets name, the value its attribute index. This member is `undefined`
  21265. * by default and only set when morph targets are detected in the geometry.
  21266. *
  21267. * @type {Object<string,number>|undefined}
  21268. * @default undefined
  21269. */
  21270. this.morphTargetDictionary = undefined;
  21271. /**
  21272. * An array of weights typically in the range `[0,1]` that specify how much of the morph
  21273. * is applied. This member is `undefined` by default and only set when morph targets are
  21274. * detected in the geometry.
  21275. *
  21276. * @type {Array<number>|undefined}
  21277. * @default undefined
  21278. */
  21279. this.morphTargetInfluences = undefined;
  21280. this.updateMorphTargets();
  21281. }
  21282. copy( source, recursive ) {
  21283. super.copy( source, recursive );
  21284. this.material = Array.isArray( source.material ) ? source.material.slice() : source.material;
  21285. this.geometry = source.geometry;
  21286. return this;
  21287. }
  21288. /**
  21289. * Computes an array of distance values which are necessary for rendering dashed lines.
  21290. * For each vertex in the geometry, the method calculates the cumulative length from the
  21291. * current point to the very beginning of the line.
  21292. *
  21293. * @return {Line} A reference to this line.
  21294. */
  21295. computeLineDistances() {
  21296. const geometry = this.geometry;
  21297. // we assume non-indexed geometry
  21298. if ( geometry.index === null ) {
  21299. const positionAttribute = geometry.attributes.position;
  21300. const lineDistances = [ 0 ];
  21301. for ( let i = 1, l = positionAttribute.count; i < l; i ++ ) {
  21302. _vStart.fromBufferAttribute( positionAttribute, i - 1 );
  21303. _vEnd.fromBufferAttribute( positionAttribute, i );
  21304. lineDistances[ i ] = lineDistances[ i - 1 ];
  21305. lineDistances[ i ] += _vStart.distanceTo( _vEnd );
  21306. }
  21307. geometry.setAttribute( 'lineDistance', new Float32BufferAttribute( lineDistances, 1 ) );
  21308. } else {
  21309. warn( 'Line.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.' );
  21310. }
  21311. return this;
  21312. }
  21313. /**
  21314. * Computes intersection points between a casted ray and this line.
  21315. *
  21316. * @param {Raycaster} raycaster - The raycaster.
  21317. * @param {Array<Object>} intersects - The target array that holds the intersection points.
  21318. */
  21319. raycast( raycaster, intersects ) {
  21320. const geometry = this.geometry;
  21321. const matrixWorld = this.matrixWorld;
  21322. const threshold = raycaster.params.Line.threshold;
  21323. const drawRange = geometry.drawRange;
  21324. // Checking boundingSphere distance to ray
  21325. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  21326. _sphere$1.copy( geometry.boundingSphere );
  21327. _sphere$1.applyMatrix4( matrixWorld );
  21328. _sphere$1.radius += threshold;
  21329. if ( raycaster.ray.intersectsSphere( _sphere$1 ) === false ) return;
  21330. //
  21331. _inverseMatrix$1.copy( matrixWorld ).invert();
  21332. _ray$1.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$1 );
  21333. const localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 );
  21334. const localThresholdSq = localThreshold * localThreshold;
  21335. const step = this.isLineSegments ? 2 : 1;
  21336. const index = geometry.index;
  21337. const attributes = geometry.attributes;
  21338. const positionAttribute = attributes.position;
  21339. if ( index !== null ) {
  21340. const start = Math.max( 0, drawRange.start );
  21341. const end = Math.min( index.count, ( drawRange.start + drawRange.count ) );
  21342. for ( let i = start, l = end - 1; i < l; i += step ) {
  21343. const a = index.getX( i );
  21344. const b = index.getX( i + 1 );
  21345. const intersect = checkIntersection( this, raycaster, _ray$1, localThresholdSq, a, b, i );
  21346. if ( intersect ) {
  21347. intersects.push( intersect );
  21348. }
  21349. }
  21350. if ( this.isLineLoop ) {
  21351. const a = index.getX( end - 1 );
  21352. const b = index.getX( start );
  21353. const intersect = checkIntersection( this, raycaster, _ray$1, localThresholdSq, a, b, end - 1 );
  21354. if ( intersect ) {
  21355. intersects.push( intersect );
  21356. }
  21357. }
  21358. } else {
  21359. const start = Math.max( 0, drawRange.start );
  21360. const end = Math.min( positionAttribute.count, ( drawRange.start + drawRange.count ) );
  21361. for ( let i = start, l = end - 1; i < l; i += step ) {
  21362. const intersect = checkIntersection( this, raycaster, _ray$1, localThresholdSq, i, i + 1, i );
  21363. if ( intersect ) {
  21364. intersects.push( intersect );
  21365. }
  21366. }
  21367. if ( this.isLineLoop ) {
  21368. const intersect = checkIntersection( this, raycaster, _ray$1, localThresholdSq, end - 1, start, end - 1 );
  21369. if ( intersect ) {
  21370. intersects.push( intersect );
  21371. }
  21372. }
  21373. }
  21374. }
  21375. /**
  21376. * Sets the values of {@link Line#morphTargetDictionary} and {@link Line#morphTargetInfluences}
  21377. * to make sure existing morph targets can influence this 3D object.
  21378. */
  21379. updateMorphTargets() {
  21380. const geometry = this.geometry;
  21381. const morphAttributes = geometry.morphAttributes;
  21382. const keys = Object.keys( morphAttributes );
  21383. if ( keys.length > 0 ) {
  21384. const morphAttribute = morphAttributes[ keys[ 0 ] ];
  21385. if ( morphAttribute !== undefined ) {
  21386. this.morphTargetInfluences = [];
  21387. this.morphTargetDictionary = {};
  21388. for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  21389. const name = morphAttribute[ m ].name || String( m );
  21390. this.morphTargetInfluences.push( 0 );
  21391. this.morphTargetDictionary[ name ] = m;
  21392. }
  21393. }
  21394. }
  21395. }
  21396. }
  21397. function checkIntersection( object, raycaster, ray, thresholdSq, a, b, i ) {
  21398. const positionAttribute = object.geometry.attributes.position;
  21399. _vStart.fromBufferAttribute( positionAttribute, a );
  21400. _vEnd.fromBufferAttribute( positionAttribute, b );
  21401. const distSq = ray.distanceSqToSegment( _vStart, _vEnd, _intersectPointOnRay, _intersectPointOnSegment );
  21402. if ( distSq > thresholdSq ) return;
  21403. _intersectPointOnRay.applyMatrix4( object.matrixWorld ); // Move back to world space for distance calculation
  21404. const distance = raycaster.ray.origin.distanceTo( _intersectPointOnRay );
  21405. if ( distance < raycaster.near || distance > raycaster.far ) return;
  21406. return {
  21407. distance: distance,
  21408. // What do we want? intersection point on the ray or on the segment??
  21409. // point: raycaster.ray.at( distance ),
  21410. point: _intersectPointOnSegment.clone().applyMatrix4( object.matrixWorld ),
  21411. index: i,
  21412. face: null,
  21413. faceIndex: null,
  21414. barycoord: null,
  21415. object: object
  21416. };
  21417. }
  21418. const _start = /*@__PURE__*/ new Vector3();
  21419. const _end = /*@__PURE__*/ new Vector3();
  21420. /**
  21421. * A series of lines drawn between pairs of vertices.
  21422. *
  21423. * @augments Line
  21424. */
  21425. class LineSegments extends Line {
  21426. /**
  21427. * Constructs a new line segments.
  21428. *
  21429. * @param {BufferGeometry} [geometry] - The line geometry.
  21430. * @param {Material|Array<Material>} [material] - The line material.
  21431. */
  21432. constructor( geometry, material ) {
  21433. super( geometry, material );
  21434. /**
  21435. * This flag can be used for type testing.
  21436. *
  21437. * @type {boolean}
  21438. * @readonly
  21439. * @default true
  21440. */
  21441. this.isLineSegments = true;
  21442. this.type = 'LineSegments';
  21443. }
  21444. computeLineDistances() {
  21445. const geometry = this.geometry;
  21446. // we assume non-indexed geometry
  21447. if ( geometry.index === null ) {
  21448. const positionAttribute = geometry.attributes.position;
  21449. const lineDistances = [];
  21450. for ( let i = 0, l = positionAttribute.count; i < l; i += 2 ) {
  21451. _start.fromBufferAttribute( positionAttribute, i );
  21452. _end.fromBufferAttribute( positionAttribute, i + 1 );
  21453. lineDistances[ i ] = ( i === 0 ) ? 0 : lineDistances[ i - 1 ];
  21454. lineDistances[ i + 1 ] = lineDistances[ i ] + _start.distanceTo( _end );
  21455. }
  21456. geometry.setAttribute( 'lineDistance', new Float32BufferAttribute( lineDistances, 1 ) );
  21457. } else {
  21458. warn( 'LineSegments.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.' );
  21459. }
  21460. return this;
  21461. }
  21462. }
  21463. /**
  21464. * A continuous line. This is nearly the same as {@link Line} the only difference
  21465. * is that the last vertex is connected with the first vertex in order to close
  21466. * the line to form a loop.
  21467. *
  21468. * @augments Line
  21469. */
  21470. class LineLoop extends Line {
  21471. /**
  21472. * Constructs a new line loop.
  21473. *
  21474. * @param {BufferGeometry} [geometry] - The line geometry.
  21475. * @param {Material|Array<Material>} [material] - The line material.
  21476. */
  21477. constructor( geometry, material ) {
  21478. super( geometry, material );
  21479. /**
  21480. * This flag can be used for type testing.
  21481. *
  21482. * @type {boolean}
  21483. * @readonly
  21484. * @default true
  21485. */
  21486. this.isLineLoop = true;
  21487. this.type = 'LineLoop';
  21488. }
  21489. }
  21490. /**
  21491. * A material for rendering point primitives.
  21492. *
  21493. * Materials define the appearance of renderable 3D objects.
  21494. *
  21495. * ```js
  21496. * const vertices = [];
  21497. *
  21498. * for ( let i = 0; i < 10000; i ++ ) {
  21499. * const x = THREE.MathUtils.randFloatSpread( 2000 );
  21500. * const y = THREE.MathUtils.randFloatSpread( 2000 );
  21501. * const z = THREE.MathUtils.randFloatSpread( 2000 );
  21502. *
  21503. * vertices.push( x, y, z );
  21504. * }
  21505. *
  21506. * const geometry = new THREE.BufferGeometry();
  21507. * geometry.setAttribute( 'position', new THREE.Float32BufferAttribute( vertices, 3 ) );
  21508. * const material = new THREE.PointsMaterial( { color: 0x888888 } );
  21509. * const points = new THREE.Points( geometry, material );
  21510. * scene.add( points );
  21511. * ```
  21512. *
  21513. * @augments Material
  21514. */
  21515. class PointsMaterial extends Material {
  21516. /**
  21517. * Constructs a new points material.
  21518. *
  21519. * @param {Object} [parameters] - An object with one or more properties
  21520. * defining the material's appearance. Any property of the material
  21521. * (including any property from inherited materials) can be passed
  21522. * in here. Color values can be passed any type of value accepted
  21523. * by {@link Color#set}.
  21524. */
  21525. constructor( parameters ) {
  21526. super();
  21527. /**
  21528. * This flag can be used for type testing.
  21529. *
  21530. * @type {boolean}
  21531. * @readonly
  21532. * @default true
  21533. */
  21534. this.isPointsMaterial = true;
  21535. this.type = 'PointsMaterial';
  21536. /**
  21537. * Color of the material.
  21538. *
  21539. * @type {Color}
  21540. * @default (1,1,1)
  21541. */
  21542. this.color = new Color( 0xffffff );
  21543. /**
  21544. * The color map. May optionally include an alpha channel, typically combined
  21545. * with {@link Material#transparent} or {@link Material#alphaTest}. The texture map
  21546. * color is modulated by the diffuse `color`.
  21547. *
  21548. * @type {?Texture}
  21549. * @default null
  21550. */
  21551. this.map = null;
  21552. /**
  21553. * The alpha map is a grayscale texture that controls the opacity across the
  21554. * surface (black: fully transparent; white: fully opaque).
  21555. *
  21556. * Only the color of the texture is used, ignoring the alpha channel if one
  21557. * exists. For RGB and RGBA textures, the renderer will use the green channel
  21558. * when sampling this texture due to the extra bit of precision provided for
  21559. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  21560. * luminance/alpha textures will also still work as expected.
  21561. *
  21562. * @type {?Texture}
  21563. * @default null
  21564. */
  21565. this.alphaMap = null;
  21566. /**
  21567. * Defines the size of the points in pixels.
  21568. *
  21569. * Might be capped if the value exceeds hardware dependent parameters like [gl.ALIASED_POINT_SIZE_RANGE](https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/getParamete).
  21570. *
  21571. * @type {number}
  21572. * @default 1
  21573. */
  21574. this.size = 1;
  21575. /**
  21576. * Specifies whether size of individual points is attenuated by the camera depth (perspective camera only).
  21577. *
  21578. * @type {boolean}
  21579. * @default true
  21580. */
  21581. this.sizeAttenuation = true;
  21582. /**
  21583. * Whether the material is affected by fog or not.
  21584. *
  21585. * @type {boolean}
  21586. * @default true
  21587. */
  21588. this.fog = true;
  21589. this.setValues( parameters );
  21590. }
  21591. copy( source ) {
  21592. super.copy( source );
  21593. this.color.copy( source.color );
  21594. this.map = source.map;
  21595. this.alphaMap = source.alphaMap;
  21596. this.size = source.size;
  21597. this.sizeAttenuation = source.sizeAttenuation;
  21598. this.fog = source.fog;
  21599. return this;
  21600. }
  21601. }
  21602. const _inverseMatrix = /*@__PURE__*/ new Matrix4();
  21603. const _ray = /*@__PURE__*/ new Ray();
  21604. const _sphere = /*@__PURE__*/ new Sphere();
  21605. const _position$2 = /*@__PURE__*/ new Vector3();
  21606. /**
  21607. * A class for displaying points or point clouds.
  21608. *
  21609. * @augments Object3D
  21610. */
  21611. class Points extends Object3D {
  21612. /**
  21613. * Constructs a new point cloud.
  21614. *
  21615. * @param {BufferGeometry} [geometry] - The points geometry.
  21616. * @param {Material|Array<Material>} [material] - The points material.
  21617. */
  21618. constructor( geometry = new BufferGeometry(), material = new PointsMaterial() ) {
  21619. super();
  21620. /**
  21621. * This flag can be used for type testing.
  21622. *
  21623. * @type {boolean}
  21624. * @readonly
  21625. * @default true
  21626. */
  21627. this.isPoints = true;
  21628. this.type = 'Points';
  21629. /**
  21630. * The points geometry.
  21631. *
  21632. * @type {BufferGeometry}
  21633. */
  21634. this.geometry = geometry;
  21635. /**
  21636. * The line material.
  21637. *
  21638. * @type {Material|Array<Material>}
  21639. * @default PointsMaterial
  21640. */
  21641. this.material = material;
  21642. /**
  21643. * A dictionary representing the morph targets in the geometry. The key is the
  21644. * morph targets name, the value its attribute index. This member is `undefined`
  21645. * by default and only set when morph targets are detected in the geometry.
  21646. *
  21647. * @type {Object<string,number>|undefined}
  21648. * @default undefined
  21649. */
  21650. this.morphTargetDictionary = undefined;
  21651. /**
  21652. * An array of weights typically in the range `[0,1]` that specify how much of the morph
  21653. * is applied. This member is `undefined` by default and only set when morph targets are
  21654. * detected in the geometry.
  21655. *
  21656. * @type {Array<number>|undefined}
  21657. * @default undefined
  21658. */
  21659. this.morphTargetInfluences = undefined;
  21660. this.updateMorphTargets();
  21661. }
  21662. copy( source, recursive ) {
  21663. super.copy( source, recursive );
  21664. this.material = Array.isArray( source.material ) ? source.material.slice() : source.material;
  21665. this.geometry = source.geometry;
  21666. return this;
  21667. }
  21668. /**
  21669. * Computes intersection points between a casted ray and this point cloud.
  21670. *
  21671. * @param {Raycaster} raycaster - The raycaster.
  21672. * @param {Array<Object>} intersects - The target array that holds the intersection points.
  21673. */
  21674. raycast( raycaster, intersects ) {
  21675. const geometry = this.geometry;
  21676. const matrixWorld = this.matrixWorld;
  21677. const threshold = raycaster.params.Points.threshold;
  21678. const drawRange = geometry.drawRange;
  21679. // Checking boundingSphere distance to ray
  21680. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  21681. _sphere.copy( geometry.boundingSphere );
  21682. _sphere.applyMatrix4( matrixWorld );
  21683. _sphere.radius += threshold;
  21684. if ( raycaster.ray.intersectsSphere( _sphere ) === false ) return;
  21685. //
  21686. _inverseMatrix.copy( matrixWorld ).invert();
  21687. _ray.copy( raycaster.ray ).applyMatrix4( _inverseMatrix );
  21688. const localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 );
  21689. const localThresholdSq = localThreshold * localThreshold;
  21690. const index = geometry.index;
  21691. const attributes = geometry.attributes;
  21692. const positionAttribute = attributes.position;
  21693. if ( index !== null ) {
  21694. const start = Math.max( 0, drawRange.start );
  21695. const end = Math.min( index.count, ( drawRange.start + drawRange.count ) );
  21696. for ( let i = start, il = end; i < il; i ++ ) {
  21697. const a = index.getX( i );
  21698. _position$2.fromBufferAttribute( positionAttribute, a );
  21699. testPoint( _position$2, a, localThresholdSq, matrixWorld, raycaster, intersects, this );
  21700. }
  21701. } else {
  21702. const start = Math.max( 0, drawRange.start );
  21703. const end = Math.min( positionAttribute.count, ( drawRange.start + drawRange.count ) );
  21704. for ( let i = start, l = end; i < l; i ++ ) {
  21705. _position$2.fromBufferAttribute( positionAttribute, i );
  21706. testPoint( _position$2, i, localThresholdSq, matrixWorld, raycaster, intersects, this );
  21707. }
  21708. }
  21709. }
  21710. /**
  21711. * Sets the values of {@link Points#morphTargetDictionary} and {@link Points#morphTargetInfluences}
  21712. * to make sure existing morph targets can influence this 3D object.
  21713. */
  21714. updateMorphTargets() {
  21715. const geometry = this.geometry;
  21716. const morphAttributes = geometry.morphAttributes;
  21717. const keys = Object.keys( morphAttributes );
  21718. if ( keys.length > 0 ) {
  21719. const morphAttribute = morphAttributes[ keys[ 0 ] ];
  21720. if ( morphAttribute !== undefined ) {
  21721. this.morphTargetInfluences = [];
  21722. this.morphTargetDictionary = {};
  21723. for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  21724. const name = morphAttribute[ m ].name || String( m );
  21725. this.morphTargetInfluences.push( 0 );
  21726. this.morphTargetDictionary[ name ] = m;
  21727. }
  21728. }
  21729. }
  21730. }
  21731. }
  21732. function testPoint( point, index, localThresholdSq, matrixWorld, raycaster, intersects, object ) {
  21733. const rayPointDistanceSq = _ray.distanceSqToPoint( point );
  21734. if ( rayPointDistanceSq < localThresholdSq ) {
  21735. const intersectPoint = new Vector3();
  21736. _ray.closestPointToPoint( point, intersectPoint );
  21737. intersectPoint.applyMatrix4( matrixWorld );
  21738. const distance = raycaster.ray.origin.distanceTo( intersectPoint );
  21739. if ( distance < raycaster.near || distance > raycaster.far ) return;
  21740. intersects.push( {
  21741. distance: distance,
  21742. distanceToRay: Math.sqrt( rayPointDistanceSq ),
  21743. point: intersectPoint,
  21744. index: index,
  21745. face: null,
  21746. faceIndex: null,
  21747. barycoord: null,
  21748. object: object
  21749. } );
  21750. }
  21751. }
  21752. /**
  21753. * A texture for use with a video.
  21754. *
  21755. * ```js
  21756. * // assuming you have created a HTML video element with id="video"
  21757. * const video = document.getElementById( 'video' );
  21758. * const texture = new THREE.VideoTexture( video );
  21759. * ```
  21760. *
  21761. * Note: When using video textures with {@link WebGPURenderer}, {@link Texture#colorSpace} must be
  21762. * set to THREE.SRGBColorSpace.
  21763. *
  21764. * Note: After the initial use of a texture, its dimensions, format, and type
  21765. * cannot be changed. Instead, call {@link Texture#dispose} on the texture and instantiate a new one.
  21766. *
  21767. * @augments Texture
  21768. */
  21769. class VideoTexture extends Texture {
  21770. /**
  21771. * Constructs a new video texture.
  21772. *
  21773. * @param {HTMLVideoElement} video - The video element to use as a data source for the texture.
  21774. * @param {number} [mapping=Texture.DEFAULT_MAPPING] - The texture mapping.
  21775. * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value.
  21776. * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value.
  21777. * @param {number} [magFilter=LinearFilter] - The mag filter value.
  21778. * @param {number} [minFilter=LinearFilter] - The min filter value.
  21779. * @param {number} [format=RGBAFormat] - The texture format.
  21780. * @param {number} [type=UnsignedByteType] - The texture type.
  21781. * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value.
  21782. */
  21783. constructor( video, mapping, wrapS, wrapT, magFilter = LinearFilter, minFilter = LinearFilter, format, type, anisotropy ) {
  21784. super( video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  21785. /**
  21786. * This flag can be used for type testing.
  21787. *
  21788. * @type {boolean}
  21789. * @readonly
  21790. * @default true
  21791. */
  21792. this.isVideoTexture = true;
  21793. /**
  21794. * Whether to generate mipmaps (if possible) for a texture.
  21795. *
  21796. * Overwritten and set to `false` by default.
  21797. *
  21798. * @type {boolean}
  21799. * @default false
  21800. */
  21801. this.generateMipmaps = false;
  21802. /**
  21803. * The video frame request callback identifier, which is a positive integer.
  21804. *
  21805. * Value of 0 represents no scheduled rVFC.
  21806. *
  21807. * @private
  21808. * @type {number}
  21809. */
  21810. this._requestVideoFrameCallbackId = 0;
  21811. const scope = this;
  21812. function updateVideo() {
  21813. scope.needsUpdate = true;
  21814. scope._requestVideoFrameCallbackId = video.requestVideoFrameCallback( updateVideo );
  21815. }
  21816. if ( 'requestVideoFrameCallback' in video ) {
  21817. this._requestVideoFrameCallbackId = video.requestVideoFrameCallback( updateVideo );
  21818. }
  21819. }
  21820. clone() {
  21821. return new this.constructor( this.image ).copy( this );
  21822. }
  21823. /**
  21824. * This method is called automatically by the renderer and sets {@link Texture#needsUpdate}
  21825. * to `true` every time a new frame is available.
  21826. *
  21827. * Only relevant if `requestVideoFrameCallback` is not supported in the browser.
  21828. */
  21829. update() {
  21830. const video = this.image;
  21831. const hasVideoFrameCallback = 'requestVideoFrameCallback' in video;
  21832. if ( hasVideoFrameCallback === false && video.readyState >= video.HAVE_CURRENT_DATA ) {
  21833. this.needsUpdate = true;
  21834. }
  21835. }
  21836. dispose() {
  21837. if ( this._requestVideoFrameCallbackId !== 0 ) {
  21838. this.source.data.cancelVideoFrameCallback( this._requestVideoFrameCallbackId );
  21839. this._requestVideoFrameCallbackId = 0;
  21840. }
  21841. super.dispose();
  21842. }
  21843. }
  21844. /**
  21845. * This class can be used as an alternative way to define video data. Instead of using
  21846. * an instance of `HTMLVideoElement` like with `VideoTexture`, `VideoFrameTexture` expects each frame is
  21847. * defined manually via {@link VideoFrameTexture#setFrame}. A typical use case for this module is when
  21848. * video frames are decoded with the WebCodecs API.
  21849. *
  21850. * ```js
  21851. * const texture = new THREE.VideoFrameTexture();
  21852. * texture.setFrame( frame );
  21853. * ```
  21854. *
  21855. * @augments VideoTexture
  21856. */
  21857. class VideoFrameTexture extends VideoTexture {
  21858. /**
  21859. * Constructs a new video frame texture.
  21860. *
  21861. * @param {number} [mapping=Texture.DEFAULT_MAPPING] - The texture mapping.
  21862. * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value.
  21863. * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value.
  21864. * @param {number} [magFilter=LinearFilter] - The mag filter value.
  21865. * @param {number} [minFilter=LinearFilter] - The min filter value.
  21866. * @param {number} [format=RGBAFormat] - The texture format.
  21867. * @param {number} [type=UnsignedByteType] - The texture type.
  21868. * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value.
  21869. */
  21870. constructor( mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  21871. super( {}, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  21872. /**
  21873. * This flag can be used for type testing.
  21874. *
  21875. * @type {boolean}
  21876. * @readonly
  21877. * @default true
  21878. */
  21879. this.isVideoFrameTexture = true;
  21880. }
  21881. /**
  21882. * This method overwritten with an empty implementation since
  21883. * this type of texture is updated via `setFrame()`.
  21884. */
  21885. update() {}
  21886. clone() {
  21887. return new this.constructor().copy( this ); // restoring Texture.clone()
  21888. }
  21889. /**
  21890. * Sets the current frame of the video. This will automatically update the texture
  21891. * so the data can be used for rendering.
  21892. *
  21893. * @param {VideoFrame} frame - The video frame.
  21894. */
  21895. setFrame( frame ) {
  21896. this.image = frame;
  21897. this.needsUpdate = true;
  21898. }
  21899. }
  21900. /**
  21901. * This class can only be used in combination with `copyFramebufferToTexture()` methods
  21902. * of renderers. It extracts the contents of the current bound framebuffer and provides it
  21903. * as a texture for further usage.
  21904. *
  21905. * ```js
  21906. * const pixelRatio = window.devicePixelRatio;
  21907. * const textureSize = 128 * pixelRatio;
  21908. *
  21909. * const frameTexture = new FramebufferTexture( textureSize, textureSize );
  21910. *
  21911. * // calculate start position for copying part of the frame data
  21912. * const vector = new Vector2();
  21913. * vector.x = ( window.innerWidth * pixelRatio / 2 ) - ( textureSize / 2 );
  21914. * vector.y = ( window.innerHeight * pixelRatio / 2 ) - ( textureSize / 2 );
  21915. *
  21916. * renderer.render( scene, camera );
  21917. *
  21918. * // copy part of the rendered frame into the framebuffer texture
  21919. * renderer.copyFramebufferToTexture( frameTexture, vector );
  21920. * ```
  21921. *
  21922. * @augments Texture
  21923. */
  21924. class FramebufferTexture extends Texture {
  21925. /**
  21926. * Constructs a new framebuffer texture.
  21927. *
  21928. * @param {number} [width] - The width of the texture.
  21929. * @param {number} [height] - The height of the texture.
  21930. */
  21931. constructor( width, height ) {
  21932. super( { width, height } );
  21933. /**
  21934. * This flag can be used for type testing.
  21935. *
  21936. * @type {boolean}
  21937. * @readonly
  21938. * @default true
  21939. */
  21940. this.isFramebufferTexture = true;
  21941. /**
  21942. * How the texture is sampled when a texel covers more than one pixel.
  21943. *
  21944. * Overwritten and set to `NearestFilter` by default to disable filtering.
  21945. *
  21946. * @type {(NearestFilter|NearestMipmapNearestFilter|NearestMipmapLinearFilter|LinearFilter|LinearMipmapNearestFilter|LinearMipmapLinearFilter)}
  21947. * @default NearestFilter
  21948. */
  21949. this.magFilter = NearestFilter;
  21950. /**
  21951. * How the texture is sampled when a texel covers less than one pixel.
  21952. *
  21953. * Overwritten and set to `NearestFilter` by default to disable filtering.
  21954. *
  21955. * @type {(NearestFilter|NearestMipmapNearestFilter|NearestMipmapLinearFilter|LinearFilter|LinearMipmapNearestFilter|LinearMipmapLinearFilter)}
  21956. * @default NearestFilter
  21957. */
  21958. this.minFilter = NearestFilter;
  21959. /**
  21960. * Whether to generate mipmaps (if possible) for a texture.
  21961. *
  21962. * Overwritten and set to `false` by default.
  21963. *
  21964. * @type {boolean}
  21965. * @default false
  21966. */
  21967. this.generateMipmaps = false;
  21968. this.needsUpdate = true;
  21969. }
  21970. }
  21971. /**
  21972. * Creates a texture based on data in compressed form.
  21973. *
  21974. * These texture are usually loaded with {@link CompressedTextureLoader}.
  21975. *
  21976. * @augments Texture
  21977. */
  21978. class CompressedTexture extends Texture {
  21979. /**
  21980. * Constructs a new compressed texture.
  21981. *
  21982. * @param {Array<Object>} mipmaps - This array holds for all mipmaps (including the bases mip)
  21983. * the data and dimensions.
  21984. * @param {number} width - The width of the texture.
  21985. * @param {number} height - The height of the texture.
  21986. * @param {number} [format=RGBAFormat] - The texture format.
  21987. * @param {number} [type=UnsignedByteType] - The texture type.
  21988. * @param {number} [mapping=Texture.DEFAULT_MAPPING] - The texture mapping.
  21989. * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value.
  21990. * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value.
  21991. * @param {number} [magFilter=LinearFilter] - The mag filter value.
  21992. * @param {number} [minFilter=LinearMipmapLinearFilter] - The min filter value.
  21993. * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value.
  21994. * @param {string} [colorSpace=NoColorSpace] - The color space.
  21995. */
  21996. constructor( mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, colorSpace ) {
  21997. super( null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace );
  21998. /**
  21999. * This flag can be used for type testing.
  22000. *
  22001. * @type {boolean}
  22002. * @readonly
  22003. * @default true
  22004. */
  22005. this.isCompressedTexture = true;
  22006. /**
  22007. * The image property of a compressed texture just defines its dimensions.
  22008. *
  22009. * @type {{width:number,height:number}}
  22010. */
  22011. this.image = { width: width, height: height };
  22012. /**
  22013. * This array holds for all mipmaps (including the bases mip) the data and dimensions.
  22014. *
  22015. * @type {Array<Object>}
  22016. */
  22017. this.mipmaps = mipmaps;
  22018. /**
  22019. * If set to `true`, the texture is flipped along the vertical axis when
  22020. * uploaded to the GPU.
  22021. *
  22022. * Overwritten and set to `false` by default since it is not possible to
  22023. * flip compressed textures.
  22024. *
  22025. * @type {boolean}
  22026. * @default false
  22027. * @readonly
  22028. */
  22029. this.flipY = false;
  22030. /**
  22031. * Whether to generate mipmaps (if possible) for a texture.
  22032. *
  22033. * Overwritten and set to `false` by default since it is not
  22034. * possible to generate mipmaps for compressed data. Mipmaps
  22035. * must be embedded in the compressed texture file.
  22036. *
  22037. * @type {boolean}
  22038. * @default false
  22039. * @readonly
  22040. */
  22041. this.generateMipmaps = false;
  22042. }
  22043. }
  22044. /**
  22045. * Creates a texture 2D array based on data in compressed form.
  22046. *
  22047. * These texture are usually loaded with {@link CompressedTextureLoader}.
  22048. *
  22049. * @augments CompressedTexture
  22050. */
  22051. class CompressedArrayTexture extends CompressedTexture {
  22052. /**
  22053. * Constructs a new compressed array texture.
  22054. *
  22055. * @param {Array<Object>} mipmaps - This array holds for all mipmaps (including the bases mip)
  22056. * the data and dimensions.
  22057. * @param {number} width - The width of the texture.
  22058. * @param {number} height - The height of the texture.
  22059. * @param {number} depth - The depth of the texture.
  22060. * @param {number} [format=RGBAFormat] - The min filter value.
  22061. * @param {number} [type=UnsignedByteType] - The min filter value.
  22062. */
  22063. constructor( mipmaps, width, height, depth, format, type ) {
  22064. super( mipmaps, width, height, format, type );
  22065. /**
  22066. * This flag can be used for type testing.
  22067. *
  22068. * @type {boolean}
  22069. * @readonly
  22070. * @default true
  22071. */
  22072. this.isCompressedArrayTexture = true;
  22073. /**
  22074. * The image property of a compressed texture just defines its dimensions.
  22075. *
  22076. * @name CompressedArrayTexture#image
  22077. * @type {{width:number,height:number,depth:number}}
  22078. */
  22079. this.image.depth = depth;
  22080. /**
  22081. * This defines how the texture is wrapped in the depth and corresponds to
  22082. * *W* in UVW mapping.
  22083. *
  22084. * @type {(RepeatWrapping|ClampToEdgeWrapping|MirroredRepeatWrapping)}
  22085. * @default ClampToEdgeWrapping
  22086. */
  22087. this.wrapR = ClampToEdgeWrapping;
  22088. /**
  22089. * A set of all layers which need to be updated in the texture.
  22090. *
  22091. * @type {Set<number>}
  22092. */
  22093. this.layerUpdates = new Set();
  22094. }
  22095. /**
  22096. * Describes that a specific layer of the texture needs to be updated.
  22097. * Normally when {@link Texture#needsUpdate} is set to `true`, the
  22098. * entire compressed texture array is sent to the GPU. Marking specific
  22099. * layers will only transmit subsets of all mipmaps associated with a
  22100. * specific depth in the array which is often much more performant.
  22101. *
  22102. * @param {number} layerIndex - The layer index that should be updated.
  22103. */
  22104. addLayerUpdate( layerIndex ) {
  22105. this.layerUpdates.add( layerIndex );
  22106. }
  22107. /**
  22108. * Resets the layer updates registry.
  22109. */
  22110. clearLayerUpdates() {
  22111. this.layerUpdates.clear();
  22112. }
  22113. }
  22114. /**
  22115. * Creates a cube texture based on data in compressed form.
  22116. *
  22117. * These texture are usually loaded with {@link CompressedTextureLoader}.
  22118. *
  22119. * @augments CompressedTexture
  22120. */
  22121. class CompressedCubeTexture extends CompressedTexture {
  22122. /**
  22123. * Constructs a new compressed texture.
  22124. *
  22125. * @param {Array<CompressedTexture>} images - An array of compressed textures.
  22126. * @param {number} [format=RGBAFormat] - The texture format.
  22127. * @param {number} [type=UnsignedByteType] - The texture type.
  22128. */
  22129. constructor( images, format, type ) {
  22130. super( undefined, images[ 0 ].width, images[ 0 ].height, format, type, CubeReflectionMapping );
  22131. /**
  22132. * This flag can be used for type testing.
  22133. *
  22134. * @type {boolean}
  22135. * @readonly
  22136. * @default true
  22137. */
  22138. this.isCompressedCubeTexture = true;
  22139. /**
  22140. * This flag can be used for type testing.
  22141. *
  22142. * @type {boolean}
  22143. * @readonly
  22144. * @default true
  22145. */
  22146. this.isCubeTexture = true;
  22147. this.image = images;
  22148. }
  22149. }
  22150. /**
  22151. * Creates a texture from a canvas element.
  22152. *
  22153. * This is almost the same as the base texture class, except that it sets {@link Texture#needsUpdate}
  22154. * to `true` immediately since a canvas can directly be used for rendering.
  22155. *
  22156. * @augments Texture
  22157. */
  22158. class CanvasTexture extends Texture {
  22159. /**
  22160. * Constructs a new texture.
  22161. *
  22162. * @param {HTMLCanvasElement} [canvas] - The HTML canvas element.
  22163. * @param {number} [mapping=Texture.DEFAULT_MAPPING] - The texture mapping.
  22164. * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value.
  22165. * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value.
  22166. * @param {number} [magFilter=LinearFilter] - The mag filter value.
  22167. * @param {number} [minFilter=LinearMipmapLinearFilter] - The min filter value.
  22168. * @param {number} [format=RGBAFormat] - The texture format.
  22169. * @param {number} [type=UnsignedByteType] - The texture type.
  22170. * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value.
  22171. */
  22172. constructor( canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  22173. super( canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  22174. /**
  22175. * This flag can be used for type testing.
  22176. *
  22177. * @type {boolean}
  22178. * @readonly
  22179. * @default true
  22180. */
  22181. this.isCanvasTexture = true;
  22182. this.needsUpdate = true;
  22183. }
  22184. }
  22185. /**
  22186. * This class can be used to automatically save the depth information of a
  22187. * rendering into a texture.
  22188. *
  22189. * @augments Texture
  22190. */
  22191. class DepthTexture extends Texture {
  22192. /**
  22193. * Constructs a new depth texture.
  22194. *
  22195. * @param {number} width - The width of the texture.
  22196. * @param {number} height - The height of the texture.
  22197. * @param {number} [type=UnsignedIntType] - The texture type.
  22198. * @param {number} [mapping=Texture.DEFAULT_MAPPING] - The texture mapping.
  22199. * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value.
  22200. * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value.
  22201. * @param {number} [magFilter=LinearFilter] - The mag filter value.
  22202. * @param {number} [minFilter=LinearFilter] - The min filter value.
  22203. * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value.
  22204. * @param {number} [format=DepthFormat] - The texture format.
  22205. * @param {number} [depth=1] - The depth of the texture.
  22206. */
  22207. constructor( width, height, type = UnsignedIntType, mapping, wrapS, wrapT, magFilter = NearestFilter, minFilter = NearestFilter, anisotropy, format = DepthFormat, depth = 1 ) {
  22208. if ( format !== DepthFormat && format !== DepthStencilFormat ) {
  22209. throw new Error( 'DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat' );
  22210. }
  22211. const image = { width: width, height: height, depth: depth };
  22212. super( image, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  22213. /**
  22214. * This flag can be used for type testing.
  22215. *
  22216. * @type {boolean}
  22217. * @readonly
  22218. * @default true
  22219. */
  22220. this.isDepthTexture = true;
  22221. /**
  22222. * If set to `true`, the texture is flipped along the vertical axis when
  22223. * uploaded to the GPU.
  22224. *
  22225. * Overwritten and set to `false` by default.
  22226. *
  22227. * @type {boolean}
  22228. * @default false
  22229. */
  22230. this.flipY = false;
  22231. /**
  22232. * Whether to generate mipmaps (if possible) for a texture.
  22233. *
  22234. * Overwritten and set to `false` by default.
  22235. *
  22236. * @type {boolean}
  22237. * @default false
  22238. */
  22239. this.generateMipmaps = false;
  22240. /**
  22241. * Code corresponding to the depth compare function.
  22242. *
  22243. * @type {?(NeverCompare|LessCompare|EqualCompare|LessEqualCompare|GreaterCompare|NotEqualCompare|GreaterEqualCompare|AlwaysCompare)}
  22244. * @default null
  22245. */
  22246. this.compareFunction = null;
  22247. }
  22248. copy( source ) {
  22249. super.copy( source );
  22250. this.source = new Source( Object.assign( {}, source.image ) ); // see #30540
  22251. this.compareFunction = source.compareFunction;
  22252. return this;
  22253. }
  22254. toJSON( meta ) {
  22255. const data = super.toJSON( meta );
  22256. if ( this.compareFunction !== null ) data.compareFunction = this.compareFunction;
  22257. return data;
  22258. }
  22259. }
  22260. /**
  22261. * This class can be used to automatically save the depth information of a
  22262. * cube rendering into a cube texture with depth format. Used for PointLight shadows.
  22263. *
  22264. * @augments DepthTexture
  22265. */
  22266. class CubeDepthTexture extends DepthTexture {
  22267. /**
  22268. * Constructs a new cube depth texture.
  22269. *
  22270. * @param {number} size - The size (width and height) of each cube face.
  22271. * @param {number} [type=UnsignedIntType] - The texture type.
  22272. * @param {number} [mapping=CubeReflectionMapping] - The texture mapping.
  22273. * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value.
  22274. * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value.
  22275. * @param {number} [magFilter=NearestFilter] - The mag filter value.
  22276. * @param {number} [minFilter=NearestFilter] - The min filter value.
  22277. * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value.
  22278. * @param {number} [format=DepthFormat] - The texture format.
  22279. */
  22280. constructor( size, type = UnsignedIntType, mapping = CubeReflectionMapping, wrapS, wrapT, magFilter = NearestFilter, minFilter = NearestFilter, anisotropy, format = DepthFormat ) {
  22281. // Create 6 identical image descriptors for the cube faces
  22282. const image = { width: size, height: size, depth: 1 };
  22283. const images = [ image, image, image, image, image, image ];
  22284. // Call DepthTexture constructor with width, height
  22285. super( size, size, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, format );
  22286. // Replace the single image with the array of 6 images
  22287. this.image = images;
  22288. /**
  22289. * This flag can be used for type testing.
  22290. *
  22291. * @type {boolean}
  22292. * @readonly
  22293. * @default true
  22294. */
  22295. this.isCubeDepthTexture = true;
  22296. /**
  22297. * Set to true for cube texture handling in WebGLTextures.
  22298. *
  22299. * @type {boolean}
  22300. * @readonly
  22301. * @default true
  22302. */
  22303. this.isCubeTexture = true;
  22304. }
  22305. /**
  22306. * Alias for {@link CubeDepthTexture#image}.
  22307. *
  22308. * @type {Array<Image>}
  22309. */
  22310. get images() {
  22311. return this.image;
  22312. }
  22313. set images( value ) {
  22314. this.image = value;
  22315. }
  22316. }
  22317. /**
  22318. * Represents a texture created externally with the same renderer context.
  22319. *
  22320. * This may be a texture from a protected media stream, device camera feed,
  22321. * or other data feeds like a depth sensor.
  22322. *
  22323. * Note that this class is only supported in {@link WebGLRenderer}, and in
  22324. * the {@link WebGPURenderer} WebGPU backend.
  22325. *
  22326. * @augments Texture
  22327. */
  22328. class ExternalTexture extends Texture {
  22329. /**
  22330. * Creates a new raw texture.
  22331. *
  22332. * @param {?(WebGLTexture|GPUTexture)} [sourceTexture=null] - The external texture.
  22333. */
  22334. constructor( sourceTexture = null ) {
  22335. super();
  22336. /**
  22337. * The external source texture.
  22338. *
  22339. * @type {?(WebGLTexture|GPUTexture)}
  22340. * @default null
  22341. */
  22342. this.sourceTexture = sourceTexture;
  22343. /**
  22344. * This flag can be used for type testing.
  22345. *
  22346. * @type {boolean}
  22347. * @readonly
  22348. * @default true
  22349. */
  22350. this.isExternalTexture = true;
  22351. }
  22352. copy( source ) {
  22353. super.copy( source );
  22354. this.sourceTexture = source.sourceTexture;
  22355. return this;
  22356. }
  22357. }
  22358. /**
  22359. * A geometry class for representing a capsule.
  22360. *
  22361. * ```js
  22362. * const geometry = new THREE.CapsuleGeometry( 1, 1, 4, 8, 1 );
  22363. * const material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } );
  22364. * const capsule = new THREE.Mesh( geometry, material );
  22365. * scene.add( capsule );
  22366. * ```
  22367. *
  22368. * @augments BufferGeometry
  22369. * @demo scenes/geometry-browser.html#CapsuleGeometry
  22370. */
  22371. class CapsuleGeometry extends BufferGeometry {
  22372. /**
  22373. * Constructs a new capsule geometry.
  22374. *
  22375. * @param {number} [radius=1] - Radius of the capsule.
  22376. * @param {number} [height=1] - Height of the middle section.
  22377. * @param {number} [capSegments=4] - Number of curve segments used to build each cap.
  22378. * @param {number} [radialSegments=8] - Number of segmented faces around the circumference of the capsule. Must be an integer >= 3.
  22379. * @param {number} [heightSegments=1] - Number of rows of faces along the height of the middle section. Must be an integer >= 1.
  22380. */
  22381. constructor( radius = 1, height = 1, capSegments = 4, radialSegments = 8, heightSegments = 1 ) {
  22382. super();
  22383. this.type = 'CapsuleGeometry';
  22384. /**
  22385. * Holds the constructor parameters that have been
  22386. * used to generate the geometry. Any modification
  22387. * after instantiation does not change the geometry.
  22388. *
  22389. * @type {Object}
  22390. */
  22391. this.parameters = {
  22392. radius: radius,
  22393. height: height,
  22394. capSegments: capSegments,
  22395. radialSegments: radialSegments,
  22396. heightSegments: heightSegments,
  22397. };
  22398. height = Math.max( 0, height );
  22399. capSegments = Math.max( 1, Math.floor( capSegments ) );
  22400. radialSegments = Math.max( 3, Math.floor( radialSegments ) );
  22401. heightSegments = Math.max( 1, Math.floor( heightSegments ) );
  22402. // buffers
  22403. const indices = [];
  22404. const vertices = [];
  22405. const normals = [];
  22406. const uvs = [];
  22407. // helper variables
  22408. const halfHeight = height / 2;
  22409. const capArcLength = ( Math.PI / 2 ) * radius;
  22410. const cylinderPartLength = height;
  22411. const totalArcLength = 2 * capArcLength + cylinderPartLength;
  22412. const numVerticalSegments = capSegments * 2 + heightSegments;
  22413. const verticesPerRow = radialSegments + 1;
  22414. const normal = new Vector3();
  22415. const vertex = new Vector3();
  22416. // generate vertices, normals, and uvs
  22417. for ( let iy = 0; iy <= numVerticalSegments; iy ++ ) {
  22418. let currentArcLength = 0;
  22419. let profileY = 0;
  22420. let profileRadius = 0;
  22421. let normalYComponent = 0;
  22422. if ( iy <= capSegments ) {
  22423. // bottom cap
  22424. const segmentProgress = iy / capSegments;
  22425. const angle = ( segmentProgress * Math.PI ) / 2;
  22426. profileY = - halfHeight - radius * Math.cos( angle );
  22427. profileRadius = radius * Math.sin( angle );
  22428. normalYComponent = - radius * Math.cos( angle );
  22429. currentArcLength = segmentProgress * capArcLength;
  22430. } else if ( iy <= capSegments + heightSegments ) {
  22431. // middle section
  22432. const segmentProgress = ( iy - capSegments ) / heightSegments;
  22433. profileY = - halfHeight + segmentProgress * height;
  22434. profileRadius = radius;
  22435. normalYComponent = 0;
  22436. currentArcLength = capArcLength + segmentProgress * cylinderPartLength;
  22437. } else {
  22438. // top cap
  22439. const segmentProgress =
  22440. ( iy - capSegments - heightSegments ) / capSegments;
  22441. const angle = ( segmentProgress * Math.PI ) / 2;
  22442. profileY = halfHeight + radius * Math.sin( angle );
  22443. profileRadius = radius * Math.cos( angle );
  22444. normalYComponent = radius * Math.sin( angle );
  22445. currentArcLength =
  22446. capArcLength + cylinderPartLength + segmentProgress * capArcLength;
  22447. }
  22448. const v = Math.max( 0, Math.min( 1, currentArcLength / totalArcLength ) );
  22449. // special case for the poles
  22450. let uOffset = 0;
  22451. if ( iy === 0 ) {
  22452. uOffset = 0.5 / radialSegments;
  22453. } else if ( iy === numVerticalSegments ) {
  22454. uOffset = -0.5 / radialSegments;
  22455. }
  22456. for ( let ix = 0; ix <= radialSegments; ix ++ ) {
  22457. const u = ix / radialSegments;
  22458. const theta = u * Math.PI * 2;
  22459. const sinTheta = Math.sin( theta );
  22460. const cosTheta = Math.cos( theta );
  22461. // vertex
  22462. vertex.x = - profileRadius * cosTheta;
  22463. vertex.y = profileY;
  22464. vertex.z = profileRadius * sinTheta;
  22465. vertices.push( vertex.x, vertex.y, vertex.z );
  22466. // normal
  22467. normal.set(
  22468. - profileRadius * cosTheta,
  22469. normalYComponent,
  22470. profileRadius * sinTheta
  22471. );
  22472. normal.normalize();
  22473. normals.push( normal.x, normal.y, normal.z );
  22474. // uv
  22475. uvs.push( u + uOffset, v );
  22476. }
  22477. if ( iy > 0 ) {
  22478. const prevIndexRow = ( iy - 1 ) * verticesPerRow;
  22479. for ( let ix = 0; ix < radialSegments; ix ++ ) {
  22480. const i1 = prevIndexRow + ix;
  22481. const i2 = prevIndexRow + ix + 1;
  22482. const i3 = iy * verticesPerRow + ix;
  22483. const i4 = iy * verticesPerRow + ix + 1;
  22484. indices.push( i1, i2, i3 );
  22485. indices.push( i2, i4, i3 );
  22486. }
  22487. }
  22488. }
  22489. // build geometry
  22490. this.setIndex( indices );
  22491. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  22492. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  22493. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  22494. }
  22495. copy( source ) {
  22496. super.copy( source );
  22497. this.parameters = Object.assign( {}, source.parameters );
  22498. return this;
  22499. }
  22500. /**
  22501. * Factory method for creating an instance of this class from the given
  22502. * JSON object.
  22503. *
  22504. * @param {Object} data - A JSON object representing the serialized geometry.
  22505. * @return {CapsuleGeometry} A new instance.
  22506. */
  22507. static fromJSON( data ) {
  22508. return new CapsuleGeometry( data.radius, data.height, data.capSegments, data.radialSegments, data.heightSegments );
  22509. }
  22510. }
  22511. /**
  22512. * A simple shape of Euclidean geometry. It is constructed from a
  22513. * number of triangular segments that are oriented around a central point and
  22514. * extend as far out as a given radius. It is built counter-clockwise from a
  22515. * start angle and a given central angle. It can also be used to create
  22516. * regular polygons, where the number of segments determines the number of
  22517. * sides.
  22518. *
  22519. * ```js
  22520. * const geometry = new THREE.CircleGeometry( 5, 32 );
  22521. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  22522. * const circle = new THREE.Mesh( geometry, material );
  22523. * scene.add( circle )
  22524. * ```
  22525. *
  22526. * @augments BufferGeometry
  22527. * @demo scenes/geometry-browser.html#CircleGeometry
  22528. */
  22529. class CircleGeometry extends BufferGeometry {
  22530. /**
  22531. * Constructs a new circle geometry.
  22532. *
  22533. * @param {number} [radius=1] - Radius of the circle.
  22534. * @param {number} [segments=32] - Number of segments (triangles), minimum = `3`.
  22535. * @param {number} [thetaStart=0] - Start angle for first segment in radians.
  22536. * @param {number} [thetaLength=Math.PI*2] - The central angle, often called theta,
  22537. * of the circular sector in radians. The default value results in a complete circle.
  22538. */
  22539. constructor( radius = 1, segments = 32, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  22540. super();
  22541. this.type = 'CircleGeometry';
  22542. /**
  22543. * Holds the constructor parameters that have been
  22544. * used to generate the geometry. Any modification
  22545. * after instantiation does not change the geometry.
  22546. *
  22547. * @type {Object}
  22548. */
  22549. this.parameters = {
  22550. radius: radius,
  22551. segments: segments,
  22552. thetaStart: thetaStart,
  22553. thetaLength: thetaLength
  22554. };
  22555. segments = Math.max( 3, segments );
  22556. // buffers
  22557. const indices = [];
  22558. const vertices = [];
  22559. const normals = [];
  22560. const uvs = [];
  22561. // helper variables
  22562. const vertex = new Vector3();
  22563. const uv = new Vector2();
  22564. // center point
  22565. vertices.push( 0, 0, 0 );
  22566. normals.push( 0, 0, 1 );
  22567. uvs.push( 0.5, 0.5 );
  22568. for ( let s = 0, i = 3; s <= segments; s ++, i += 3 ) {
  22569. const segment = thetaStart + s / segments * thetaLength;
  22570. // vertex
  22571. vertex.x = radius * Math.cos( segment );
  22572. vertex.y = radius * Math.sin( segment );
  22573. vertices.push( vertex.x, vertex.y, vertex.z );
  22574. // normal
  22575. normals.push( 0, 0, 1 );
  22576. // uvs
  22577. uv.x = ( vertices[ i ] / radius + 1 ) / 2;
  22578. uv.y = ( vertices[ i + 1 ] / radius + 1 ) / 2;
  22579. uvs.push( uv.x, uv.y );
  22580. }
  22581. // indices
  22582. for ( let i = 1; i <= segments; i ++ ) {
  22583. indices.push( i, i + 1, 0 );
  22584. }
  22585. // build geometry
  22586. this.setIndex( indices );
  22587. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  22588. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  22589. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  22590. }
  22591. copy( source ) {
  22592. super.copy( source );
  22593. this.parameters = Object.assign( {}, source.parameters );
  22594. return this;
  22595. }
  22596. /**
  22597. * Factory method for creating an instance of this class from the given
  22598. * JSON object.
  22599. *
  22600. * @param {Object} data - A JSON object representing the serialized geometry.
  22601. * @return {CircleGeometry} A new instance.
  22602. */
  22603. static fromJSON( data ) {
  22604. return new CircleGeometry( data.radius, data.segments, data.thetaStart, data.thetaLength );
  22605. }
  22606. }
  22607. /**
  22608. * A geometry class for representing a cylinder.
  22609. *
  22610. * ```js
  22611. * const geometry = new THREE.CylinderGeometry( 5, 5, 20, 32 );
  22612. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  22613. * const cylinder = new THREE.Mesh( geometry, material );
  22614. * scene.add( cylinder );
  22615. * ```
  22616. *
  22617. * @augments BufferGeometry
  22618. * @demo scenes/geometry-browser.html#CylinderGeometry
  22619. */
  22620. class CylinderGeometry extends BufferGeometry {
  22621. /**
  22622. * Constructs a new cylinder geometry.
  22623. *
  22624. * @param {number} [radiusTop=1] - Radius of the cylinder at the top.
  22625. * @param {number} [radiusBottom=1] - Radius of the cylinder at the bottom.
  22626. * @param {number} [height=1] - Height of the cylinder.
  22627. * @param {number} [radialSegments=32] - Number of segmented faces around the circumference of the cylinder.
  22628. * @param {number} [heightSegments=1] - Number of rows of faces along the height of the cylinder.
  22629. * @param {boolean} [openEnded=false] - Whether the base of the cylinder is open or capped.
  22630. * @param {number} [thetaStart=0] - Start angle for first segment, in radians.
  22631. * @param {number} [thetaLength=Math.PI*2] - The central angle, often called theta, of the circular sector, in radians.
  22632. * The default value results in a complete cylinder.
  22633. */
  22634. constructor( radiusTop = 1, radiusBottom = 1, height = 1, radialSegments = 32, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  22635. super();
  22636. this.type = 'CylinderGeometry';
  22637. /**
  22638. * Holds the constructor parameters that have been
  22639. * used to generate the geometry. Any modification
  22640. * after instantiation does not change the geometry.
  22641. *
  22642. * @type {Object}
  22643. */
  22644. this.parameters = {
  22645. radiusTop: radiusTop,
  22646. radiusBottom: radiusBottom,
  22647. height: height,
  22648. radialSegments: radialSegments,
  22649. heightSegments: heightSegments,
  22650. openEnded: openEnded,
  22651. thetaStart: thetaStart,
  22652. thetaLength: thetaLength
  22653. };
  22654. const scope = this;
  22655. radialSegments = Math.floor( radialSegments );
  22656. heightSegments = Math.floor( heightSegments );
  22657. // buffers
  22658. const indices = [];
  22659. const vertices = [];
  22660. const normals = [];
  22661. const uvs = [];
  22662. // helper variables
  22663. let index = 0;
  22664. const indexArray = [];
  22665. const halfHeight = height / 2;
  22666. let groupStart = 0;
  22667. // generate geometry
  22668. generateTorso();
  22669. if ( openEnded === false ) {
  22670. if ( radiusTop > 0 ) generateCap( true );
  22671. if ( radiusBottom > 0 ) generateCap( false );
  22672. }
  22673. // build geometry
  22674. this.setIndex( indices );
  22675. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  22676. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  22677. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  22678. function generateTorso() {
  22679. const normal = new Vector3();
  22680. const vertex = new Vector3();
  22681. let groupCount = 0;
  22682. // this will be used to calculate the normal
  22683. const slope = ( radiusBottom - radiusTop ) / height;
  22684. // generate vertices, normals and uvs
  22685. for ( let y = 0; y <= heightSegments; y ++ ) {
  22686. const indexRow = [];
  22687. const v = y / heightSegments;
  22688. // calculate the radius of the current row
  22689. const radius = v * ( radiusBottom - radiusTop ) + radiusTop;
  22690. for ( let x = 0; x <= radialSegments; x ++ ) {
  22691. const u = x / radialSegments;
  22692. const theta = u * thetaLength + thetaStart;
  22693. const sinTheta = Math.sin( theta );
  22694. const cosTheta = Math.cos( theta );
  22695. // vertex
  22696. vertex.x = radius * sinTheta;
  22697. vertex.y = - v * height + halfHeight;
  22698. vertex.z = radius * cosTheta;
  22699. vertices.push( vertex.x, vertex.y, vertex.z );
  22700. // normal
  22701. normal.set( sinTheta, slope, cosTheta ).normalize();
  22702. normals.push( normal.x, normal.y, normal.z );
  22703. // uv
  22704. uvs.push( u, 1 - v );
  22705. // save index of vertex in respective row
  22706. indexRow.push( index ++ );
  22707. }
  22708. // now save vertices of the row in our index array
  22709. indexArray.push( indexRow );
  22710. }
  22711. // generate indices
  22712. for ( let x = 0; x < radialSegments; x ++ ) {
  22713. for ( let y = 0; y < heightSegments; y ++ ) {
  22714. // we use the index array to access the correct indices
  22715. const a = indexArray[ y ][ x ];
  22716. const b = indexArray[ y + 1 ][ x ];
  22717. const c = indexArray[ y + 1 ][ x + 1 ];
  22718. const d = indexArray[ y ][ x + 1 ];
  22719. // faces
  22720. if ( radiusTop > 0 || y !== 0 ) {
  22721. indices.push( a, b, d );
  22722. groupCount += 3;
  22723. }
  22724. if ( radiusBottom > 0 || y !== heightSegments - 1 ) {
  22725. indices.push( b, c, d );
  22726. groupCount += 3;
  22727. }
  22728. }
  22729. }
  22730. // add a group to the geometry. this will ensure multi material support
  22731. scope.addGroup( groupStart, groupCount, 0 );
  22732. // calculate new start value for groups
  22733. groupStart += groupCount;
  22734. }
  22735. function generateCap( top ) {
  22736. // save the index of the first center vertex
  22737. const centerIndexStart = index;
  22738. const uv = new Vector2();
  22739. const vertex = new Vector3();
  22740. let groupCount = 0;
  22741. const radius = ( top === true ) ? radiusTop : radiusBottom;
  22742. const sign = ( top === true ) ? 1 : -1;
  22743. // first we generate the center vertex data of the cap.
  22744. // because the geometry needs one set of uvs per face,
  22745. // we must generate a center vertex per face/segment
  22746. for ( let x = 1; x <= radialSegments; x ++ ) {
  22747. // vertex
  22748. vertices.push( 0, halfHeight * sign, 0 );
  22749. // normal
  22750. normals.push( 0, sign, 0 );
  22751. // uv
  22752. uvs.push( 0.5, 0.5 );
  22753. // increase index
  22754. index ++;
  22755. }
  22756. // save the index of the last center vertex
  22757. const centerIndexEnd = index;
  22758. // now we generate the surrounding vertices, normals and uvs
  22759. for ( let x = 0; x <= radialSegments; x ++ ) {
  22760. const u = x / radialSegments;
  22761. const theta = u * thetaLength + thetaStart;
  22762. const cosTheta = Math.cos( theta );
  22763. const sinTheta = Math.sin( theta );
  22764. // vertex
  22765. vertex.x = radius * sinTheta;
  22766. vertex.y = halfHeight * sign;
  22767. vertex.z = radius * cosTheta;
  22768. vertices.push( vertex.x, vertex.y, vertex.z );
  22769. // normal
  22770. normals.push( 0, sign, 0 );
  22771. // uv
  22772. uv.x = ( cosTheta * 0.5 ) + 0.5;
  22773. uv.y = ( sinTheta * 0.5 * sign ) + 0.5;
  22774. uvs.push( uv.x, uv.y );
  22775. // increase index
  22776. index ++;
  22777. }
  22778. // generate indices
  22779. for ( let x = 0; x < radialSegments; x ++ ) {
  22780. const c = centerIndexStart + x;
  22781. const i = centerIndexEnd + x;
  22782. if ( top === true ) {
  22783. // face top
  22784. indices.push( i, i + 1, c );
  22785. } else {
  22786. // face bottom
  22787. indices.push( i + 1, i, c );
  22788. }
  22789. groupCount += 3;
  22790. }
  22791. // add a group to the geometry. this will ensure multi material support
  22792. scope.addGroup( groupStart, groupCount, top === true ? 1 : 2 );
  22793. // calculate new start value for groups
  22794. groupStart += groupCount;
  22795. }
  22796. }
  22797. copy( source ) {
  22798. super.copy( source );
  22799. this.parameters = Object.assign( {}, source.parameters );
  22800. return this;
  22801. }
  22802. /**
  22803. * Factory method for creating an instance of this class from the given
  22804. * JSON object.
  22805. *
  22806. * @param {Object} data - A JSON object representing the serialized geometry.
  22807. * @return {CylinderGeometry} A new instance.
  22808. */
  22809. static fromJSON( data ) {
  22810. return new CylinderGeometry( data.radiusTop, data.radiusBottom, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength );
  22811. }
  22812. }
  22813. /**
  22814. * A geometry class for representing a cone.
  22815. *
  22816. * ```js
  22817. * const geometry = new THREE.ConeGeometry( 5, 20, 32 );
  22818. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  22819. * const cone = new THREE.Mesh(geometry, material );
  22820. * scene.add( cone );
  22821. * ```
  22822. *
  22823. * @augments CylinderGeometry
  22824. * @demo scenes/geometry-browser.html#ConeGeometry
  22825. */
  22826. class ConeGeometry extends CylinderGeometry {
  22827. /**
  22828. * Constructs a new cone geometry.
  22829. *
  22830. * @param {number} [radius=1] - Radius of the cone base.
  22831. * @param {number} [height=1] - Height of the cone.
  22832. * @param {number} [radialSegments=32] - Number of segmented faces around the circumference of the cone.
  22833. * @param {number} [heightSegments=1] - Number of rows of faces along the height of the cone.
  22834. * @param {boolean} [openEnded=false] - Whether the base of the cone is open or capped.
  22835. * @param {number} [thetaStart=0] - Start angle for first segment, in radians.
  22836. * @param {number} [thetaLength=Math.PI*2] - The central angle, often called theta, of the circular sector, in radians.
  22837. * The default value results in a complete cone.
  22838. */
  22839. constructor( radius = 1, height = 1, radialSegments = 32, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  22840. super( 0, radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength );
  22841. this.type = 'ConeGeometry';
  22842. /**
  22843. * Holds the constructor parameters that have been
  22844. * used to generate the geometry. Any modification
  22845. * after instantiation does not change the geometry.
  22846. *
  22847. * @type {Object}
  22848. */
  22849. this.parameters = {
  22850. radius: radius,
  22851. height: height,
  22852. radialSegments: radialSegments,
  22853. heightSegments: heightSegments,
  22854. openEnded: openEnded,
  22855. thetaStart: thetaStart,
  22856. thetaLength: thetaLength
  22857. };
  22858. }
  22859. /**
  22860. * Factory method for creating an instance of this class from the given
  22861. * JSON object.
  22862. *
  22863. * @param {Object} data - A JSON object representing the serialized geometry.
  22864. * @return {ConeGeometry} A new instance.
  22865. */
  22866. static fromJSON( data ) {
  22867. return new ConeGeometry( data.radius, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength );
  22868. }
  22869. }
  22870. /**
  22871. * A polyhedron is a solid in three dimensions with flat faces. This class
  22872. * will take an array of vertices, project them onto a sphere, and then
  22873. * divide them up to the desired level of detail.
  22874. *
  22875. * @augments BufferGeometry
  22876. */
  22877. class PolyhedronGeometry extends BufferGeometry {
  22878. /**
  22879. * Constructs a new polyhedron geometry.
  22880. *
  22881. * @param {Array<number>} [vertices] - A flat array of vertices describing the base shape.
  22882. * @param {Array<number>} [indices] - A flat array of indices describing the base shape.
  22883. * @param {number} [radius=1] - The radius of the shape.
  22884. * @param {number} [detail=0] - How many levels to subdivide the geometry. The more detail, the smoother the shape.
  22885. */
  22886. constructor( vertices = [], indices = [], radius = 1, detail = 0 ) {
  22887. super();
  22888. this.type = 'PolyhedronGeometry';
  22889. /**
  22890. * Holds the constructor parameters that have been
  22891. * used to generate the geometry. Any modification
  22892. * after instantiation does not change the geometry.
  22893. *
  22894. * @type {Object}
  22895. */
  22896. this.parameters = {
  22897. vertices: vertices,
  22898. indices: indices,
  22899. radius: radius,
  22900. detail: detail
  22901. };
  22902. // default buffer data
  22903. const vertexBuffer = [];
  22904. const uvBuffer = [];
  22905. // the subdivision creates the vertex buffer data
  22906. subdivide( detail );
  22907. // all vertices should lie on a conceptual sphere with a given radius
  22908. applyRadius( radius );
  22909. // finally, create the uv data
  22910. generateUVs();
  22911. // build non-indexed geometry
  22912. this.setAttribute( 'position', new Float32BufferAttribute( vertexBuffer, 3 ) );
  22913. this.setAttribute( 'normal', new Float32BufferAttribute( vertexBuffer.slice(), 3 ) );
  22914. this.setAttribute( 'uv', new Float32BufferAttribute( uvBuffer, 2 ) );
  22915. if ( detail === 0 ) {
  22916. this.computeVertexNormals(); // flat normals
  22917. } else {
  22918. this.normalizeNormals(); // smooth normals
  22919. }
  22920. // helper functions
  22921. function subdivide( detail ) {
  22922. const a = new Vector3();
  22923. const b = new Vector3();
  22924. const c = new Vector3();
  22925. // iterate over all faces and apply a subdivision with the given detail value
  22926. for ( let i = 0; i < indices.length; i += 3 ) {
  22927. // get the vertices of the face
  22928. getVertexByIndex( indices[ i + 0 ], a );
  22929. getVertexByIndex( indices[ i + 1 ], b );
  22930. getVertexByIndex( indices[ i + 2 ], c );
  22931. // perform subdivision
  22932. subdivideFace( a, b, c, detail );
  22933. }
  22934. }
  22935. function subdivideFace( a, b, c, detail ) {
  22936. const cols = detail + 1;
  22937. // we use this multidimensional array as a data structure for creating the subdivision
  22938. const v = [];
  22939. // construct all of the vertices for this subdivision
  22940. for ( let i = 0; i <= cols; i ++ ) {
  22941. v[ i ] = [];
  22942. const aj = a.clone().lerp( c, i / cols );
  22943. const bj = b.clone().lerp( c, i / cols );
  22944. const rows = cols - i;
  22945. for ( let j = 0; j <= rows; j ++ ) {
  22946. if ( j === 0 && i === cols ) {
  22947. v[ i ][ j ] = aj;
  22948. } else {
  22949. v[ i ][ j ] = aj.clone().lerp( bj, j / rows );
  22950. }
  22951. }
  22952. }
  22953. // construct all of the faces
  22954. for ( let i = 0; i < cols; i ++ ) {
  22955. for ( let j = 0; j < 2 * ( cols - i ) - 1; j ++ ) {
  22956. const k = Math.floor( j / 2 );
  22957. if ( j % 2 === 0 ) {
  22958. pushVertex( v[ i ][ k + 1 ] );
  22959. pushVertex( v[ i + 1 ][ k ] );
  22960. pushVertex( v[ i ][ k ] );
  22961. } else {
  22962. pushVertex( v[ i ][ k + 1 ] );
  22963. pushVertex( v[ i + 1 ][ k + 1 ] );
  22964. pushVertex( v[ i + 1 ][ k ] );
  22965. }
  22966. }
  22967. }
  22968. }
  22969. function applyRadius( radius ) {
  22970. const vertex = new Vector3();
  22971. // iterate over the entire buffer and apply the radius to each vertex
  22972. for ( let i = 0; i < vertexBuffer.length; i += 3 ) {
  22973. vertex.x = vertexBuffer[ i + 0 ];
  22974. vertex.y = vertexBuffer[ i + 1 ];
  22975. vertex.z = vertexBuffer[ i + 2 ];
  22976. vertex.normalize().multiplyScalar( radius );
  22977. vertexBuffer[ i + 0 ] = vertex.x;
  22978. vertexBuffer[ i + 1 ] = vertex.y;
  22979. vertexBuffer[ i + 2 ] = vertex.z;
  22980. }
  22981. }
  22982. function generateUVs() {
  22983. const vertex = new Vector3();
  22984. for ( let i = 0; i < vertexBuffer.length; i += 3 ) {
  22985. vertex.x = vertexBuffer[ i + 0 ];
  22986. vertex.y = vertexBuffer[ i + 1 ];
  22987. vertex.z = vertexBuffer[ i + 2 ];
  22988. const u = azimuth( vertex ) / 2 / Math.PI + 0.5;
  22989. const v = inclination( vertex ) / Math.PI + 0.5;
  22990. uvBuffer.push( u, 1 - v );
  22991. }
  22992. correctUVs();
  22993. correctSeam();
  22994. }
  22995. function correctSeam() {
  22996. // handle case when face straddles the seam, see #3269
  22997. for ( let i = 0; i < uvBuffer.length; i += 6 ) {
  22998. // uv data of a single face
  22999. const x0 = uvBuffer[ i + 0 ];
  23000. const x1 = uvBuffer[ i + 2 ];
  23001. const x2 = uvBuffer[ i + 4 ];
  23002. const max = Math.max( x0, x1, x2 );
  23003. const min = Math.min( x0, x1, x2 );
  23004. // 0.9 is somewhat arbitrary
  23005. if ( max > 0.9 && min < 0.1 ) {
  23006. if ( x0 < 0.2 ) uvBuffer[ i + 0 ] += 1;
  23007. if ( x1 < 0.2 ) uvBuffer[ i + 2 ] += 1;
  23008. if ( x2 < 0.2 ) uvBuffer[ i + 4 ] += 1;
  23009. }
  23010. }
  23011. }
  23012. function pushVertex( vertex ) {
  23013. vertexBuffer.push( vertex.x, vertex.y, vertex.z );
  23014. }
  23015. function getVertexByIndex( index, vertex ) {
  23016. const stride = index * 3;
  23017. vertex.x = vertices[ stride + 0 ];
  23018. vertex.y = vertices[ stride + 1 ];
  23019. vertex.z = vertices[ stride + 2 ];
  23020. }
  23021. function correctUVs() {
  23022. const a = new Vector3();
  23023. const b = new Vector3();
  23024. const c = new Vector3();
  23025. const centroid = new Vector3();
  23026. const uvA = new Vector2();
  23027. const uvB = new Vector2();
  23028. const uvC = new Vector2();
  23029. for ( let i = 0, j = 0; i < vertexBuffer.length; i += 9, j += 6 ) {
  23030. a.set( vertexBuffer[ i + 0 ], vertexBuffer[ i + 1 ], vertexBuffer[ i + 2 ] );
  23031. b.set( vertexBuffer[ i + 3 ], vertexBuffer[ i + 4 ], vertexBuffer[ i + 5 ] );
  23032. c.set( vertexBuffer[ i + 6 ], vertexBuffer[ i + 7 ], vertexBuffer[ i + 8 ] );
  23033. uvA.set( uvBuffer[ j + 0 ], uvBuffer[ j + 1 ] );
  23034. uvB.set( uvBuffer[ j + 2 ], uvBuffer[ j + 3 ] );
  23035. uvC.set( uvBuffer[ j + 4 ], uvBuffer[ j + 5 ] );
  23036. centroid.copy( a ).add( b ).add( c ).divideScalar( 3 );
  23037. const azi = azimuth( centroid );
  23038. correctUV( uvA, j + 0, a, azi );
  23039. correctUV( uvB, j + 2, b, azi );
  23040. correctUV( uvC, j + 4, c, azi );
  23041. }
  23042. }
  23043. function correctUV( uv, stride, vector, azimuth ) {
  23044. if ( ( azimuth < 0 ) && ( uv.x === 1 ) ) {
  23045. uvBuffer[ stride ] = uv.x - 1;
  23046. }
  23047. if ( ( vector.x === 0 ) && ( vector.z === 0 ) ) {
  23048. uvBuffer[ stride ] = azimuth / 2 / Math.PI + 0.5;
  23049. }
  23050. }
  23051. // Angle around the Y axis, counter-clockwise when looking from above.
  23052. function azimuth( vector ) {
  23053. return Math.atan2( vector.z, - vector.x );
  23054. }
  23055. // Angle above the XZ plane.
  23056. function inclination( vector ) {
  23057. return Math.atan2( - vector.y, Math.sqrt( ( vector.x * vector.x ) + ( vector.z * vector.z ) ) );
  23058. }
  23059. }
  23060. copy( source ) {
  23061. super.copy( source );
  23062. this.parameters = Object.assign( {}, source.parameters );
  23063. return this;
  23064. }
  23065. /**
  23066. * Factory method for creating an instance of this class from the given
  23067. * JSON object.
  23068. *
  23069. * @param {Object} data - A JSON object representing the serialized geometry.
  23070. * @return {PolyhedronGeometry} A new instance.
  23071. */
  23072. static fromJSON( data ) {
  23073. return new PolyhedronGeometry( data.vertices, data.indices, data.radius, data.detail );
  23074. }
  23075. }
  23076. /**
  23077. * A geometry class for representing a dodecahedron.
  23078. *
  23079. * ```js
  23080. * const geometry = new THREE.DodecahedronGeometry();
  23081. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  23082. * const dodecahedron = new THREE.Mesh( geometry, material );
  23083. * scene.add( dodecahedron );
  23084. * ```
  23085. *
  23086. * @augments PolyhedronGeometry
  23087. * @demo scenes/geometry-browser.html#DodecahedronGeometry
  23088. */
  23089. class DodecahedronGeometry extends PolyhedronGeometry {
  23090. /**
  23091. * Constructs a new dodecahedron geometry.
  23092. *
  23093. * @param {number} [radius=1] - Radius of the dodecahedron.
  23094. * @param {number} [detail=0] - Setting this to a value greater than `0` adds vertices making it no longer a dodecahedron.
  23095. */
  23096. constructor( radius = 1, detail = 0 ) {
  23097. const t = ( 1 + Math.sqrt( 5 ) ) / 2;
  23098. const r = 1 / t;
  23099. const vertices = [
  23100. // (±1, ±1, ±1)
  23101. -1, -1, -1, -1, -1, 1,
  23102. -1, 1, -1, -1, 1, 1,
  23103. 1, -1, -1, 1, -1, 1,
  23104. 1, 1, -1, 1, 1, 1,
  23105. // (0, ±1/φ, ±φ)
  23106. 0, - r, - t, 0, - r, t,
  23107. 0, r, - t, 0, r, t,
  23108. // (±1/φ, ±φ, 0)
  23109. - r, - t, 0, - r, t, 0,
  23110. r, - t, 0, r, t, 0,
  23111. // (±φ, 0, ±1/φ)
  23112. - t, 0, - r, t, 0, - r,
  23113. - t, 0, r, t, 0, r
  23114. ];
  23115. const indices = [
  23116. 3, 11, 7, 3, 7, 15, 3, 15, 13,
  23117. 7, 19, 17, 7, 17, 6, 7, 6, 15,
  23118. 17, 4, 8, 17, 8, 10, 17, 10, 6,
  23119. 8, 0, 16, 8, 16, 2, 8, 2, 10,
  23120. 0, 12, 1, 0, 1, 18, 0, 18, 16,
  23121. 6, 10, 2, 6, 2, 13, 6, 13, 15,
  23122. 2, 16, 18, 2, 18, 3, 2, 3, 13,
  23123. 18, 1, 9, 18, 9, 11, 18, 11, 3,
  23124. 4, 14, 12, 4, 12, 0, 4, 0, 8,
  23125. 11, 9, 5, 11, 5, 19, 11, 19, 7,
  23126. 19, 5, 14, 19, 14, 4, 19, 4, 17,
  23127. 1, 12, 14, 1, 14, 5, 1, 5, 9
  23128. ];
  23129. super( vertices, indices, radius, detail );
  23130. this.type = 'DodecahedronGeometry';
  23131. /**
  23132. * Holds the constructor parameters that have been
  23133. * used to generate the geometry. Any modification
  23134. * after instantiation does not change the geometry.
  23135. *
  23136. * @type {Object}
  23137. */
  23138. this.parameters = {
  23139. radius: radius,
  23140. detail: detail
  23141. };
  23142. }
  23143. /**
  23144. * Factory method for creating an instance of this class from the given
  23145. * JSON object.
  23146. *
  23147. * @param {Object} data - A JSON object representing the serialized geometry.
  23148. * @return {DodecahedronGeometry} A new instance.
  23149. */
  23150. static fromJSON( data ) {
  23151. return new DodecahedronGeometry( data.radius, data.detail );
  23152. }
  23153. }
  23154. const _v0 = /*@__PURE__*/ new Vector3();
  23155. const _v1$1 = /*@__PURE__*/ new Vector3();
  23156. const _normal = /*@__PURE__*/ new Vector3();
  23157. const _triangle = /*@__PURE__*/ new Triangle();
  23158. /**
  23159. * Can be used as a helper object to view the edges of a geometry.
  23160. *
  23161. * ```js
  23162. * const geometry = new THREE.BoxGeometry();
  23163. * const edges = new THREE.EdgesGeometry( geometry );
  23164. * const line = new THREE.LineSegments( edges );
  23165. * scene.add( line );
  23166. * ```
  23167. *
  23168. * Note: It is not yet possible to serialize/deserialize instances of this class.
  23169. *
  23170. * @augments BufferGeometry
  23171. */
  23172. class EdgesGeometry extends BufferGeometry {
  23173. /**
  23174. * Constructs a new edges geometry.
  23175. *
  23176. * @param {?BufferGeometry} [geometry=null] - The geometry.
  23177. * @param {number} [thresholdAngle=1] - An edge is only rendered if the angle (in degrees)
  23178. * between the face normals of the adjoining faces exceeds this value.
  23179. */
  23180. constructor( geometry = null, thresholdAngle = 1 ) {
  23181. super();
  23182. this.type = 'EdgesGeometry';
  23183. /**
  23184. * Holds the constructor parameters that have been
  23185. * used to generate the geometry. Any modification
  23186. * after instantiation does not change the geometry.
  23187. *
  23188. * @type {Object}
  23189. */
  23190. this.parameters = {
  23191. geometry: geometry,
  23192. thresholdAngle: thresholdAngle
  23193. };
  23194. if ( geometry !== null ) {
  23195. const precisionPoints = 4;
  23196. const precision = Math.pow( 10, precisionPoints );
  23197. const thresholdDot = Math.cos( DEG2RAD * thresholdAngle );
  23198. const indexAttr = geometry.getIndex();
  23199. const positionAttr = geometry.getAttribute( 'position' );
  23200. const indexCount = indexAttr ? indexAttr.count : positionAttr.count;
  23201. const indexArr = [ 0, 0, 0 ];
  23202. const vertKeys = [ 'a', 'b', 'c' ];
  23203. const hashes = new Array( 3 );
  23204. const edgeData = {};
  23205. const vertices = [];
  23206. for ( let i = 0; i < indexCount; i += 3 ) {
  23207. if ( indexAttr ) {
  23208. indexArr[ 0 ] = indexAttr.getX( i );
  23209. indexArr[ 1 ] = indexAttr.getX( i + 1 );
  23210. indexArr[ 2 ] = indexAttr.getX( i + 2 );
  23211. } else {
  23212. indexArr[ 0 ] = i;
  23213. indexArr[ 1 ] = i + 1;
  23214. indexArr[ 2 ] = i + 2;
  23215. }
  23216. const { a, b, c } = _triangle;
  23217. a.fromBufferAttribute( positionAttr, indexArr[ 0 ] );
  23218. b.fromBufferAttribute( positionAttr, indexArr[ 1 ] );
  23219. c.fromBufferAttribute( positionAttr, indexArr[ 2 ] );
  23220. _triangle.getNormal( _normal );
  23221. // create hashes for the edge from the vertices
  23222. hashes[ 0 ] = `${ Math.round( a.x * precision ) },${ Math.round( a.y * precision ) },${ Math.round( a.z * precision ) }`;
  23223. hashes[ 1 ] = `${ Math.round( b.x * precision ) },${ Math.round( b.y * precision ) },${ Math.round( b.z * precision ) }`;
  23224. hashes[ 2 ] = `${ Math.round( c.x * precision ) },${ Math.round( c.y * precision ) },${ Math.round( c.z * precision ) }`;
  23225. // skip degenerate triangles
  23226. if ( hashes[ 0 ] === hashes[ 1 ] || hashes[ 1 ] === hashes[ 2 ] || hashes[ 2 ] === hashes[ 0 ] ) {
  23227. continue;
  23228. }
  23229. // iterate over every edge
  23230. for ( let j = 0; j < 3; j ++ ) {
  23231. // get the first and next vertex making up the edge
  23232. const jNext = ( j + 1 ) % 3;
  23233. const vecHash0 = hashes[ j ];
  23234. const vecHash1 = hashes[ jNext ];
  23235. const v0 = _triangle[ vertKeys[ j ] ];
  23236. const v1 = _triangle[ vertKeys[ jNext ] ];
  23237. const hash = `${ vecHash0 }_${ vecHash1 }`;
  23238. const reverseHash = `${ vecHash1 }_${ vecHash0 }`;
  23239. if ( reverseHash in edgeData && edgeData[ reverseHash ] ) {
  23240. // if we found a sibling edge add it into the vertex array if
  23241. // it meets the angle threshold and delete the edge from the map.
  23242. if ( _normal.dot( edgeData[ reverseHash ].normal ) <= thresholdDot ) {
  23243. vertices.push( v0.x, v0.y, v0.z );
  23244. vertices.push( v1.x, v1.y, v1.z );
  23245. }
  23246. edgeData[ reverseHash ] = null;
  23247. } else if ( ! ( hash in edgeData ) ) {
  23248. // if we've already got an edge here then skip adding a new one
  23249. edgeData[ hash ] = {
  23250. index0: indexArr[ j ],
  23251. index1: indexArr[ jNext ],
  23252. normal: _normal.clone(),
  23253. };
  23254. }
  23255. }
  23256. }
  23257. // iterate over all remaining, unmatched edges and add them to the vertex array
  23258. for ( const key in edgeData ) {
  23259. if ( edgeData[ key ] ) {
  23260. const { index0, index1 } = edgeData[ key ];
  23261. _v0.fromBufferAttribute( positionAttr, index0 );
  23262. _v1$1.fromBufferAttribute( positionAttr, index1 );
  23263. vertices.push( _v0.x, _v0.y, _v0.z );
  23264. vertices.push( _v1$1.x, _v1$1.y, _v1$1.z );
  23265. }
  23266. }
  23267. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  23268. }
  23269. }
  23270. copy( source ) {
  23271. super.copy( source );
  23272. this.parameters = Object.assign( {}, source.parameters );
  23273. return this;
  23274. }
  23275. }
  23276. /**
  23277. * An abstract base class for creating an analytic curve object that contains methods
  23278. * for interpolation.
  23279. *
  23280. * @abstract
  23281. */
  23282. class Curve {
  23283. /**
  23284. * Constructs a new curve.
  23285. */
  23286. constructor() {
  23287. /**
  23288. * The type property is used for detecting the object type
  23289. * in context of serialization/deserialization.
  23290. *
  23291. * @type {string}
  23292. * @readonly
  23293. */
  23294. this.type = 'Curve';
  23295. /**
  23296. * This value determines the amount of divisions when calculating the
  23297. * cumulative segment lengths of a curve via {@link Curve#getLengths}. To ensure
  23298. * precision when using methods like {@link Curve#getSpacedPoints}, it is
  23299. * recommended to increase the value of this property if the curve is very large.
  23300. *
  23301. * @type {number}
  23302. * @default 200
  23303. */
  23304. this.arcLengthDivisions = 200;
  23305. /**
  23306. * Must be set to `true` if the curve parameters have changed.
  23307. *
  23308. * @type {boolean}
  23309. * @default false
  23310. */
  23311. this.needsUpdate = false;
  23312. /**
  23313. * An internal cache that holds precomputed curve length values.
  23314. *
  23315. * @private
  23316. * @type {?Array<number>}
  23317. * @default null
  23318. */
  23319. this.cacheArcLengths = null;
  23320. }
  23321. /**
  23322. * This method returns a vector in 2D or 3D space (depending on the curve definition)
  23323. * for the given interpolation factor.
  23324. *
  23325. * @abstract
  23326. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  23327. * @param {(Vector2|Vector3)} [optionalTarget] - The optional target vector the result is written to.
  23328. * @return {(Vector2|Vector3)} The position on the curve. It can be a 2D or 3D vector depending on the curve definition.
  23329. */
  23330. getPoint( /* t, optionalTarget */ ) {
  23331. warn( 'Curve: .getPoint() not implemented.' );
  23332. }
  23333. /**
  23334. * This method returns a vector in 2D or 3D space (depending on the curve definition)
  23335. * for the given interpolation factor. Unlike {@link Curve#getPoint}, this method honors the length
  23336. * of the curve which equidistant samples.
  23337. *
  23338. * @param {number} u - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  23339. * @param {(Vector2|Vector3)} [optionalTarget] - The optional target vector the result is written to.
  23340. * @return {(Vector2|Vector3)} The position on the curve. It can be a 2D or 3D vector depending on the curve definition.
  23341. */
  23342. getPointAt( u, optionalTarget ) {
  23343. const t = this.getUtoTmapping( u );
  23344. return this.getPoint( t, optionalTarget );
  23345. }
  23346. /**
  23347. * This method samples the curve via {@link Curve#getPoint} and returns an array of points representing
  23348. * the curve shape.
  23349. *
  23350. * @param {number} [divisions=5] - The number of divisions.
  23351. * @return {Array<(Vector2|Vector3)>} An array holding the sampled curve values. The number of points is `divisions + 1`.
  23352. */
  23353. getPoints( divisions = 5 ) {
  23354. const points = [];
  23355. for ( let d = 0; d <= divisions; d ++ ) {
  23356. points.push( this.getPoint( d / divisions ) );
  23357. }
  23358. return points;
  23359. }
  23360. // Get sequence of points using getPointAt( u )
  23361. /**
  23362. * This method samples the curve via {@link Curve#getPointAt} and returns an array of points representing
  23363. * the curve shape. Unlike {@link Curve#getPoints}, this method returns equi-spaced points across the entire
  23364. * curve.
  23365. *
  23366. * @param {number} [divisions=5] - The number of divisions.
  23367. * @return {Array<(Vector2|Vector3)>} An array holding the sampled curve values. The number of points is `divisions + 1`.
  23368. */
  23369. getSpacedPoints( divisions = 5 ) {
  23370. const points = [];
  23371. for ( let d = 0; d <= divisions; d ++ ) {
  23372. points.push( this.getPointAt( d / divisions ) );
  23373. }
  23374. return points;
  23375. }
  23376. /**
  23377. * Returns the total arc length of the curve.
  23378. *
  23379. * @return {number} The length of the curve.
  23380. */
  23381. getLength() {
  23382. const lengths = this.getLengths();
  23383. return lengths[ lengths.length - 1 ];
  23384. }
  23385. /**
  23386. * Returns an array of cumulative segment lengths of the curve.
  23387. *
  23388. * @param {number} [divisions=this.arcLengthDivisions] - The number of divisions.
  23389. * @return {Array<number>} An array holding the cumulative segment lengths.
  23390. */
  23391. getLengths( divisions = this.arcLengthDivisions ) {
  23392. if ( this.cacheArcLengths &&
  23393. ( this.cacheArcLengths.length === divisions + 1 ) &&
  23394. ! this.needsUpdate ) {
  23395. return this.cacheArcLengths;
  23396. }
  23397. this.needsUpdate = false;
  23398. const cache = [];
  23399. let current, last = this.getPoint( 0 );
  23400. let sum = 0;
  23401. cache.push( 0 );
  23402. for ( let p = 1; p <= divisions; p ++ ) {
  23403. current = this.getPoint( p / divisions );
  23404. sum += current.distanceTo( last );
  23405. cache.push( sum );
  23406. last = current;
  23407. }
  23408. this.cacheArcLengths = cache;
  23409. return cache; // { sums: cache, sum: sum }; Sum is in the last element.
  23410. }
  23411. /**
  23412. * Update the cumulative segment distance cache. The method must be called
  23413. * every time curve parameters are changed. If an updated curve is part of a
  23414. * composed curve like {@link CurvePath}, this method must be called on the
  23415. * composed curve, too.
  23416. */
  23417. updateArcLengths() {
  23418. this.needsUpdate = true;
  23419. this.getLengths();
  23420. }
  23421. /**
  23422. * Given an interpolation factor in the range `[0,1]`, this method returns an updated
  23423. * interpolation factor in the same range that can be ued to sample equidistant points
  23424. * from a curve.
  23425. *
  23426. * @param {number} u - The interpolation factor.
  23427. * @param {?number} distance - An optional distance on the curve.
  23428. * @return {number} The updated interpolation factor.
  23429. */
  23430. getUtoTmapping( u, distance = null ) {
  23431. const arcLengths = this.getLengths();
  23432. let i = 0;
  23433. const il = arcLengths.length;
  23434. let targetArcLength; // The targeted u distance value to get
  23435. if ( distance ) {
  23436. targetArcLength = distance;
  23437. } else {
  23438. targetArcLength = u * arcLengths[ il - 1 ];
  23439. }
  23440. // binary search for the index with largest value smaller than target u distance
  23441. let low = 0, high = il - 1, comparison;
  23442. while ( low <= high ) {
  23443. 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
  23444. comparison = arcLengths[ i ] - targetArcLength;
  23445. if ( comparison < 0 ) {
  23446. low = i + 1;
  23447. } else if ( comparison > 0 ) {
  23448. high = i - 1;
  23449. } else {
  23450. high = i;
  23451. break;
  23452. // DONE
  23453. }
  23454. }
  23455. i = high;
  23456. if ( arcLengths[ i ] === targetArcLength ) {
  23457. return i / ( il - 1 );
  23458. }
  23459. // we could get finer grain at lengths, or use simple interpolation between two points
  23460. const lengthBefore = arcLengths[ i ];
  23461. const lengthAfter = arcLengths[ i + 1 ];
  23462. const segmentLength = lengthAfter - lengthBefore;
  23463. // determine where we are between the 'before' and 'after' points
  23464. const segmentFraction = ( targetArcLength - lengthBefore ) / segmentLength;
  23465. // add that fractional amount to t
  23466. const t = ( i + segmentFraction ) / ( il - 1 );
  23467. return t;
  23468. }
  23469. /**
  23470. * Returns a unit vector tangent for the given interpolation factor.
  23471. * If the derived curve does not implement its tangent derivation,
  23472. * two points a small delta apart will be used to find its gradient
  23473. * which seems to give a reasonable approximation.
  23474. *
  23475. * @param {number} t - The interpolation factor.
  23476. * @param {(Vector2|Vector3)} [optionalTarget] - The optional target vector the result is written to.
  23477. * @return {(Vector2|Vector3)} The tangent vector.
  23478. */
  23479. getTangent( t, optionalTarget ) {
  23480. const delta = 0.0001;
  23481. let t1 = t - delta;
  23482. let t2 = t + delta;
  23483. // Capping in case of danger
  23484. if ( t1 < 0 ) t1 = 0;
  23485. if ( t2 > 1 ) t2 = 1;
  23486. const pt1 = this.getPoint( t1 );
  23487. const pt2 = this.getPoint( t2 );
  23488. const tangent = optionalTarget || ( ( pt1.isVector2 ) ? new Vector2() : new Vector3() );
  23489. tangent.copy( pt2 ).sub( pt1 ).normalize();
  23490. return tangent;
  23491. }
  23492. /**
  23493. * Same as {@link Curve#getTangent} but with equidistant samples.
  23494. *
  23495. * @param {number} u - The interpolation factor.
  23496. * @param {(Vector2|Vector3)} [optionalTarget] - The optional target vector the result is written to.
  23497. * @return {(Vector2|Vector3)} The tangent vector.
  23498. * @see {@link Curve#getPointAt}
  23499. */
  23500. getTangentAt( u, optionalTarget ) {
  23501. const t = this.getUtoTmapping( u );
  23502. return this.getTangent( t, optionalTarget );
  23503. }
  23504. /**
  23505. * Generates the Frenet Frames. Requires a curve definition in 3D space. Used
  23506. * in geometries like {@link TubeGeometry} or {@link ExtrudeGeometry}.
  23507. *
  23508. * @param {number} segments - The number of segments.
  23509. * @param {boolean} [closed=false] - Whether the curve is closed or not.
  23510. * @return {{tangents: Array<Vector3>, normals: Array<Vector3>, binormals: Array<Vector3>}} The Frenet Frames.
  23511. */
  23512. computeFrenetFrames( segments, closed = false ) {
  23513. // see http://www.cs.indiana.edu/pub/techreports/TR425.pdf
  23514. const normal = new Vector3();
  23515. const tangents = [];
  23516. const normals = [];
  23517. const binormals = [];
  23518. const vec = new Vector3();
  23519. const mat = new Matrix4();
  23520. // compute the tangent vectors for each segment on the curve
  23521. for ( let i = 0; i <= segments; i ++ ) {
  23522. const u = i / segments;
  23523. tangents[ i ] = this.getTangentAt( u, new Vector3() );
  23524. }
  23525. // select an initial normal vector perpendicular to the first tangent vector,
  23526. // and in the direction of the minimum tangent xyz component
  23527. normals[ 0 ] = new Vector3();
  23528. binormals[ 0 ] = new Vector3();
  23529. let min = Number.MAX_VALUE;
  23530. const tx = Math.abs( tangents[ 0 ].x );
  23531. const ty = Math.abs( tangents[ 0 ].y );
  23532. const tz = Math.abs( tangents[ 0 ].z );
  23533. if ( tx <= min ) {
  23534. min = tx;
  23535. normal.set( 1, 0, 0 );
  23536. }
  23537. if ( ty <= min ) {
  23538. min = ty;
  23539. normal.set( 0, 1, 0 );
  23540. }
  23541. if ( tz <= min ) {
  23542. normal.set( 0, 0, 1 );
  23543. }
  23544. vec.crossVectors( tangents[ 0 ], normal ).normalize();
  23545. normals[ 0 ].crossVectors( tangents[ 0 ], vec );
  23546. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] );
  23547. // compute the slowly-varying normal and binormal vectors for each segment on the curve
  23548. for ( let i = 1; i <= segments; i ++ ) {
  23549. normals[ i ] = normals[ i - 1 ].clone();
  23550. binormals[ i ] = binormals[ i - 1 ].clone();
  23551. vec.crossVectors( tangents[ i - 1 ], tangents[ i ] );
  23552. if ( vec.length() > Number.EPSILON ) {
  23553. vec.normalize();
  23554. const theta = Math.acos( clamp( tangents[ i - 1 ].dot( tangents[ i ] ), -1, 1 ) ); // clamp for floating pt errors
  23555. normals[ i ].applyMatrix4( mat.makeRotationAxis( vec, theta ) );
  23556. }
  23557. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  23558. }
  23559. // if the curve is closed, postprocess the vectors so the first and last normal vectors are the same
  23560. if ( closed === true ) {
  23561. let theta = Math.acos( clamp( normals[ 0 ].dot( normals[ segments ] ), -1, 1 ) );
  23562. theta /= segments;
  23563. if ( tangents[ 0 ].dot( vec.crossVectors( normals[ 0 ], normals[ segments ] ) ) > 0 ) {
  23564. theta = - theta;
  23565. }
  23566. for ( let i = 1; i <= segments; i ++ ) {
  23567. // twist a little...
  23568. normals[ i ].applyMatrix4( mat.makeRotationAxis( tangents[ i ], theta * i ) );
  23569. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  23570. }
  23571. }
  23572. return {
  23573. tangents: tangents,
  23574. normals: normals,
  23575. binormals: binormals
  23576. };
  23577. }
  23578. /**
  23579. * Returns a new curve with copied values from this instance.
  23580. *
  23581. * @return {Curve} A clone of this instance.
  23582. */
  23583. clone() {
  23584. return new this.constructor().copy( this );
  23585. }
  23586. /**
  23587. * Copies the values of the given curve to this instance.
  23588. *
  23589. * @param {Curve} source - The curve to copy.
  23590. * @return {Curve} A reference to this curve.
  23591. */
  23592. copy( source ) {
  23593. this.arcLengthDivisions = source.arcLengthDivisions;
  23594. return this;
  23595. }
  23596. /**
  23597. * Serializes the curve into JSON.
  23598. *
  23599. * @return {Object} A JSON object representing the serialized curve.
  23600. * @see {@link ObjectLoader#parse}
  23601. */
  23602. toJSON() {
  23603. const data = {
  23604. metadata: {
  23605. version: 4.7,
  23606. type: 'Curve',
  23607. generator: 'Curve.toJSON'
  23608. }
  23609. };
  23610. data.arcLengthDivisions = this.arcLengthDivisions;
  23611. data.type = this.type;
  23612. return data;
  23613. }
  23614. /**
  23615. * Deserializes the curve from the given JSON.
  23616. *
  23617. * @param {Object} json - The JSON holding the serialized curve.
  23618. * @return {Curve} A reference to this curve.
  23619. */
  23620. fromJSON( json ) {
  23621. this.arcLengthDivisions = json.arcLengthDivisions;
  23622. return this;
  23623. }
  23624. }
  23625. /**
  23626. * A curve representing an ellipse.
  23627. *
  23628. * ```js
  23629. * const curve = new THREE.EllipseCurve(
  23630. * 0, 0,
  23631. * 10, 10,
  23632. * 0, 2 * Math.PI,
  23633. * false,
  23634. * 0
  23635. * );
  23636. *
  23637. * const points = curve.getPoints( 50 );
  23638. * const geometry = new THREE.BufferGeometry().setFromPoints( points );
  23639. *
  23640. * const material = new THREE.LineBasicMaterial( { color: 0xff0000 } );
  23641. *
  23642. * // Create the final object to add to the scene
  23643. * const ellipse = new THREE.Line( geometry, material );
  23644. * ```
  23645. *
  23646. * @augments Curve
  23647. */
  23648. class EllipseCurve extends Curve {
  23649. /**
  23650. * Constructs a new ellipse curve.
  23651. *
  23652. * @param {number} [aX=0] - The X center of the ellipse.
  23653. * @param {number} [aY=0] - The Y center of the ellipse.
  23654. * @param {number} [xRadius=1] - The radius of the ellipse in the x direction.
  23655. * @param {number} [yRadius=1] - The radius of the ellipse in the y direction.
  23656. * @param {number} [aStartAngle=0] - The start angle of the curve in radians starting from the positive X axis.
  23657. * @param {number} [aEndAngle=Math.PI*2] - The end angle of the curve in radians starting from the positive X axis.
  23658. * @param {boolean} [aClockwise=false] - Whether the ellipse is drawn clockwise or not.
  23659. * @param {number} [aRotation=0] - The rotation angle of the ellipse in radians, counterclockwise from the positive X axis.
  23660. */
  23661. constructor( aX = 0, aY = 0, xRadius = 1, yRadius = 1, aStartAngle = 0, aEndAngle = Math.PI * 2, aClockwise = false, aRotation = 0 ) {
  23662. super();
  23663. /**
  23664. * This flag can be used for type testing.
  23665. *
  23666. * @type {boolean}
  23667. * @readonly
  23668. * @default true
  23669. */
  23670. this.isEllipseCurve = true;
  23671. this.type = 'EllipseCurve';
  23672. /**
  23673. * The X center of the ellipse.
  23674. *
  23675. * @type {number}
  23676. * @default 0
  23677. */
  23678. this.aX = aX;
  23679. /**
  23680. * The Y center of the ellipse.
  23681. *
  23682. * @type {number}
  23683. * @default 0
  23684. */
  23685. this.aY = aY;
  23686. /**
  23687. * The radius of the ellipse in the x direction.
  23688. * Setting the this value equal to the {@link EllipseCurve#yRadius} will result in a circle.
  23689. *
  23690. * @type {number}
  23691. * @default 1
  23692. */
  23693. this.xRadius = xRadius;
  23694. /**
  23695. * The radius of the ellipse in the y direction.
  23696. * Setting the this value equal to the {@link EllipseCurve#xRadius} will result in a circle.
  23697. *
  23698. * @type {number}
  23699. * @default 1
  23700. */
  23701. this.yRadius = yRadius;
  23702. /**
  23703. * The start angle of the curve in radians starting from the positive X axis.
  23704. *
  23705. * @type {number}
  23706. * @default 0
  23707. */
  23708. this.aStartAngle = aStartAngle;
  23709. /**
  23710. * The end angle of the curve in radians starting from the positive X axis.
  23711. *
  23712. * @type {number}
  23713. * @default Math.PI*2
  23714. */
  23715. this.aEndAngle = aEndAngle;
  23716. /**
  23717. * Whether the ellipse is drawn clockwise or not.
  23718. *
  23719. * @type {boolean}
  23720. * @default false
  23721. */
  23722. this.aClockwise = aClockwise;
  23723. /**
  23724. * The rotation angle of the ellipse in radians, counterclockwise from the positive X axis.
  23725. *
  23726. * @type {number}
  23727. * @default 0
  23728. */
  23729. this.aRotation = aRotation;
  23730. }
  23731. /**
  23732. * Returns a point on the curve.
  23733. *
  23734. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  23735. * @param {Vector2} [optionalTarget] - The optional target vector the result is written to.
  23736. * @return {Vector2} The position on the curve.
  23737. */
  23738. getPoint( t, optionalTarget = new Vector2() ) {
  23739. const point = optionalTarget;
  23740. const twoPi = Math.PI * 2;
  23741. let deltaAngle = this.aEndAngle - this.aStartAngle;
  23742. const samePoints = Math.abs( deltaAngle ) < Number.EPSILON;
  23743. // ensures that deltaAngle is 0 .. 2 PI
  23744. while ( deltaAngle < 0 ) deltaAngle += twoPi;
  23745. while ( deltaAngle > twoPi ) deltaAngle -= twoPi;
  23746. if ( deltaAngle < Number.EPSILON ) {
  23747. if ( samePoints ) {
  23748. deltaAngle = 0;
  23749. } else {
  23750. deltaAngle = twoPi;
  23751. }
  23752. }
  23753. if ( this.aClockwise === true && ! samePoints ) {
  23754. if ( deltaAngle === twoPi ) {
  23755. deltaAngle = - twoPi;
  23756. } else {
  23757. deltaAngle = deltaAngle - twoPi;
  23758. }
  23759. }
  23760. const angle = this.aStartAngle + t * deltaAngle;
  23761. let x = this.aX + this.xRadius * Math.cos( angle );
  23762. let y = this.aY + this.yRadius * Math.sin( angle );
  23763. if ( this.aRotation !== 0 ) {
  23764. const cos = Math.cos( this.aRotation );
  23765. const sin = Math.sin( this.aRotation );
  23766. const tx = x - this.aX;
  23767. const ty = y - this.aY;
  23768. // Rotate the point about the center of the ellipse.
  23769. x = tx * cos - ty * sin + this.aX;
  23770. y = tx * sin + ty * cos + this.aY;
  23771. }
  23772. return point.set( x, y );
  23773. }
  23774. copy( source ) {
  23775. super.copy( source );
  23776. this.aX = source.aX;
  23777. this.aY = source.aY;
  23778. this.xRadius = source.xRadius;
  23779. this.yRadius = source.yRadius;
  23780. this.aStartAngle = source.aStartAngle;
  23781. this.aEndAngle = source.aEndAngle;
  23782. this.aClockwise = source.aClockwise;
  23783. this.aRotation = source.aRotation;
  23784. return this;
  23785. }
  23786. toJSON() {
  23787. const data = super.toJSON();
  23788. data.aX = this.aX;
  23789. data.aY = this.aY;
  23790. data.xRadius = this.xRadius;
  23791. data.yRadius = this.yRadius;
  23792. data.aStartAngle = this.aStartAngle;
  23793. data.aEndAngle = this.aEndAngle;
  23794. data.aClockwise = this.aClockwise;
  23795. data.aRotation = this.aRotation;
  23796. return data;
  23797. }
  23798. fromJSON( json ) {
  23799. super.fromJSON( json );
  23800. this.aX = json.aX;
  23801. this.aY = json.aY;
  23802. this.xRadius = json.xRadius;
  23803. this.yRadius = json.yRadius;
  23804. this.aStartAngle = json.aStartAngle;
  23805. this.aEndAngle = json.aEndAngle;
  23806. this.aClockwise = json.aClockwise;
  23807. this.aRotation = json.aRotation;
  23808. return this;
  23809. }
  23810. }
  23811. /**
  23812. * A curve representing an arc.
  23813. *
  23814. * @augments EllipseCurve
  23815. */
  23816. class ArcCurve extends EllipseCurve {
  23817. /**
  23818. * Constructs a new arc curve.
  23819. *
  23820. * @param {number} [aX=0] - The X center of the ellipse.
  23821. * @param {number} [aY=0] - The Y center of the ellipse.
  23822. * @param {number} [aRadius=1] - The radius of the ellipse in the x direction.
  23823. * @param {number} [aStartAngle=0] - The start angle of the curve in radians starting from the positive X axis.
  23824. * @param {number} [aEndAngle=Math.PI*2] - The end angle of the curve in radians starting from the positive X axis.
  23825. * @param {boolean} [aClockwise=false] - Whether the ellipse is drawn clockwise or not.
  23826. */
  23827. constructor( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  23828. super( aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  23829. /**
  23830. * This flag can be used for type testing.
  23831. *
  23832. * @type {boolean}
  23833. * @readonly
  23834. * @default true
  23835. */
  23836. this.isArcCurve = true;
  23837. this.type = 'ArcCurve';
  23838. }
  23839. }
  23840. function CubicPoly() {
  23841. /**
  23842. * Centripetal CatmullRom Curve - which is useful for avoiding
  23843. * cusps and self-intersections in non-uniform catmull rom curves.
  23844. * http://www.cemyuksel.com/research/catmullrom_param/catmullrom.pdf
  23845. *
  23846. * curve.type accepts centripetal(default), chordal and catmullrom
  23847. * curve.tension is used for catmullrom which defaults to 0.5
  23848. */
  23849. /*
  23850. Based on an optimized c++ solution in
  23851. - http://stackoverflow.com/questions/9489736/catmull-rom-curve-with-no-cusps-and-no-self-intersections/
  23852. - http://ideone.com/NoEbVM
  23853. This CubicPoly class could be used for reusing some variables and calculations,
  23854. but for three.js curve use, it could be possible inlined and flatten into a single function call
  23855. which can be placed in CurveUtils.
  23856. */
  23857. let c0 = 0, c1 = 0, c2 = 0, c3 = 0;
  23858. /*
  23859. * Compute coefficients for a cubic polynomial
  23860. * p(s) = c0 + c1*s + c2*s^2 + c3*s^3
  23861. * such that
  23862. * p(0) = x0, p(1) = x1
  23863. * and
  23864. * p'(0) = t0, p'(1) = t1.
  23865. */
  23866. function init( x0, x1, t0, t1 ) {
  23867. c0 = x0;
  23868. c1 = t0;
  23869. c2 = -3 * x0 + 3 * x1 - 2 * t0 - t1;
  23870. c3 = 2 * x0 - 2 * x1 + t0 + t1;
  23871. }
  23872. return {
  23873. initCatmullRom: function ( x0, x1, x2, x3, tension ) {
  23874. init( x1, x2, tension * ( x2 - x0 ), tension * ( x3 - x1 ) );
  23875. },
  23876. initNonuniformCatmullRom: function ( x0, x1, x2, x3, dt0, dt1, dt2 ) {
  23877. // compute tangents when parameterized in [t1,t2]
  23878. let t1 = ( x1 - x0 ) / dt0 - ( x2 - x0 ) / ( dt0 + dt1 ) + ( x2 - x1 ) / dt1;
  23879. let t2 = ( x2 - x1 ) / dt1 - ( x3 - x1 ) / ( dt1 + dt2 ) + ( x3 - x2 ) / dt2;
  23880. // rescale tangents for parametrization in [0,1]
  23881. t1 *= dt1;
  23882. t2 *= dt1;
  23883. init( x1, x2, t1, t2 );
  23884. },
  23885. calc: function ( t ) {
  23886. const t2 = t * t;
  23887. const t3 = t2 * t;
  23888. return c0 + c1 * t + c2 * t2 + c3 * t3;
  23889. }
  23890. };
  23891. }
  23892. //
  23893. const tmp = /*@__PURE__*/ new Vector3();
  23894. const px = /*@__PURE__*/ new CubicPoly();
  23895. const py = /*@__PURE__*/ new CubicPoly();
  23896. const pz = /*@__PURE__*/ new CubicPoly();
  23897. /**
  23898. * A curve representing a Catmull-Rom spline.
  23899. *
  23900. * ```js
  23901. * //Create a closed wavey loop
  23902. * const curve = new THREE.CatmullRomCurve3( [
  23903. * new THREE.Vector3( -10, 0, 10 ),
  23904. * new THREE.Vector3( -5, 5, 5 ),
  23905. * new THREE.Vector3( 0, 0, 0 ),
  23906. * new THREE.Vector3( 5, -5, 5 ),
  23907. * new THREE.Vector3( 10, 0, 10 )
  23908. * ] );
  23909. *
  23910. * const points = curve.getPoints( 50 );
  23911. * const geometry = new THREE.BufferGeometry().setFromPoints( points );
  23912. *
  23913. * const material = new THREE.LineBasicMaterial( { color: 0xff0000 } );
  23914. *
  23915. * // Create the final object to add to the scene
  23916. * const curveObject = new THREE.Line( geometry, material );
  23917. * ```
  23918. *
  23919. * @augments Curve
  23920. */
  23921. class CatmullRomCurve3 extends Curve {
  23922. /**
  23923. * Constructs a new Catmull-Rom curve.
  23924. *
  23925. * @param {Array<Vector3>} [points] - An array of 3D points defining the curve.
  23926. * @param {boolean} [closed=false] - Whether the curve is closed or not.
  23927. * @param {('centripetal'|'chordal'|'catmullrom')} [curveType='centripetal'] - The curve type.
  23928. * @param {number} [tension=0.5] - Tension of the curve.
  23929. */
  23930. constructor( points = [], closed = false, curveType = 'centripetal', tension = 0.5 ) {
  23931. super();
  23932. /**
  23933. * This flag can be used for type testing.
  23934. *
  23935. * @type {boolean}
  23936. * @readonly
  23937. * @default true
  23938. */
  23939. this.isCatmullRomCurve3 = true;
  23940. this.type = 'CatmullRomCurve3';
  23941. /**
  23942. * An array of 3D points defining the curve.
  23943. *
  23944. * @type {Array<Vector3>}
  23945. */
  23946. this.points = points;
  23947. /**
  23948. * Whether the curve is closed or not.
  23949. *
  23950. * @type {boolean}
  23951. * @default false
  23952. */
  23953. this.closed = closed;
  23954. /**
  23955. * The curve type.
  23956. *
  23957. * @type {('centripetal'|'chordal'|'catmullrom')}
  23958. * @default 'centripetal'
  23959. */
  23960. this.curveType = curveType;
  23961. /**
  23962. * Tension of the curve.
  23963. *
  23964. * @type {number}
  23965. * @default 0.5
  23966. */
  23967. this.tension = tension;
  23968. }
  23969. /**
  23970. * Returns a point on the curve.
  23971. *
  23972. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  23973. * @param {Vector3} [optionalTarget] - The optional target vector the result is written to.
  23974. * @return {Vector3} The position on the curve.
  23975. */
  23976. getPoint( t, optionalTarget = new Vector3() ) {
  23977. const point = optionalTarget;
  23978. const points = this.points;
  23979. const l = points.length;
  23980. const p = ( l - ( this.closed ? 0 : 1 ) ) * t;
  23981. let intPoint = Math.floor( p );
  23982. let weight = p - intPoint;
  23983. if ( this.closed ) {
  23984. intPoint += intPoint > 0 ? 0 : ( Math.floor( Math.abs( intPoint ) / l ) + 1 ) * l;
  23985. } else if ( weight === 0 && intPoint === l - 1 ) {
  23986. intPoint = l - 2;
  23987. weight = 1;
  23988. }
  23989. let p0, p3; // 4 points (p1 & p2 defined below)
  23990. if ( this.closed || intPoint > 0 ) {
  23991. p0 = points[ ( intPoint - 1 ) % l ];
  23992. } else {
  23993. // extrapolate first point
  23994. tmp.subVectors( points[ 0 ], points[ 1 ] ).add( points[ 0 ] );
  23995. p0 = tmp;
  23996. }
  23997. const p1 = points[ intPoint % l ];
  23998. const p2 = points[ ( intPoint + 1 ) % l ];
  23999. if ( this.closed || intPoint + 2 < l ) {
  24000. p3 = points[ ( intPoint + 2 ) % l ];
  24001. } else {
  24002. // extrapolate last point
  24003. tmp.subVectors( points[ l - 1 ], points[ l - 2 ] ).add( points[ l - 1 ] );
  24004. p3 = tmp;
  24005. }
  24006. if ( this.curveType === 'centripetal' || this.curveType === 'chordal' ) {
  24007. // init Centripetal / Chordal Catmull-Rom
  24008. const pow = this.curveType === 'chordal' ? 0.5 : 0.25;
  24009. let dt0 = Math.pow( p0.distanceToSquared( p1 ), pow );
  24010. let dt1 = Math.pow( p1.distanceToSquared( p2 ), pow );
  24011. let dt2 = Math.pow( p2.distanceToSquared( p3 ), pow );
  24012. // safety check for repeated points
  24013. if ( dt1 < 1e-4 ) dt1 = 1.0;
  24014. if ( dt0 < 1e-4 ) dt0 = dt1;
  24015. if ( dt2 < 1e-4 ) dt2 = dt1;
  24016. px.initNonuniformCatmullRom( p0.x, p1.x, p2.x, p3.x, dt0, dt1, dt2 );
  24017. py.initNonuniformCatmullRom( p0.y, p1.y, p2.y, p3.y, dt0, dt1, dt2 );
  24018. pz.initNonuniformCatmullRom( p0.z, p1.z, p2.z, p3.z, dt0, dt1, dt2 );
  24019. } else if ( this.curveType === 'catmullrom' ) {
  24020. px.initCatmullRom( p0.x, p1.x, p2.x, p3.x, this.tension );
  24021. py.initCatmullRom( p0.y, p1.y, p2.y, p3.y, this.tension );
  24022. pz.initCatmullRom( p0.z, p1.z, p2.z, p3.z, this.tension );
  24023. }
  24024. point.set(
  24025. px.calc( weight ),
  24026. py.calc( weight ),
  24027. pz.calc( weight )
  24028. );
  24029. return point;
  24030. }
  24031. copy( source ) {
  24032. super.copy( source );
  24033. this.points = [];
  24034. for ( let i = 0, l = source.points.length; i < l; i ++ ) {
  24035. const point = source.points[ i ];
  24036. this.points.push( point.clone() );
  24037. }
  24038. this.closed = source.closed;
  24039. this.curveType = source.curveType;
  24040. this.tension = source.tension;
  24041. return this;
  24042. }
  24043. toJSON() {
  24044. const data = super.toJSON();
  24045. data.points = [];
  24046. for ( let i = 0, l = this.points.length; i < l; i ++ ) {
  24047. const point = this.points[ i ];
  24048. data.points.push( point.toArray() );
  24049. }
  24050. data.closed = this.closed;
  24051. data.curveType = this.curveType;
  24052. data.tension = this.tension;
  24053. return data;
  24054. }
  24055. fromJSON( json ) {
  24056. super.fromJSON( json );
  24057. this.points = [];
  24058. for ( let i = 0, l = json.points.length; i < l; i ++ ) {
  24059. const point = json.points[ i ];
  24060. this.points.push( new Vector3().fromArray( point ) );
  24061. }
  24062. this.closed = json.closed;
  24063. this.curveType = json.curveType;
  24064. this.tension = json.tension;
  24065. return this;
  24066. }
  24067. }
  24068. /**
  24069. * Interpolations contains spline and Bézier functions internally used by concrete curve classes.
  24070. *
  24071. * Bezier Curves formulas obtained from: https://en.wikipedia.org/wiki/B%C3%A9zier_curve
  24072. *
  24073. * @module Interpolations
  24074. */
  24075. /**
  24076. * Computes a point on a Catmull-Rom spline.
  24077. *
  24078. * @param {number} t - The interpolation factor.
  24079. * @param {number} p0 - The first control point.
  24080. * @param {number} p1 - The second control point.
  24081. * @param {number} p2 - The third control point.
  24082. * @param {number} p3 - The fourth control point.
  24083. * @return {number} The calculated point on a Catmull-Rom spline.
  24084. */
  24085. function CatmullRom( t, p0, p1, p2, p3 ) {
  24086. const v0 = ( p2 - p0 ) * 0.5;
  24087. const v1 = ( p3 - p1 ) * 0.5;
  24088. const t2 = t * t;
  24089. const t3 = t * t2;
  24090. return ( 2 * p1 - 2 * p2 + v0 + v1 ) * t3 + ( -3 * p1 + 3 * p2 - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  24091. }
  24092. //
  24093. function QuadraticBezierP0( t, p ) {
  24094. const k = 1 - t;
  24095. return k * k * p;
  24096. }
  24097. function QuadraticBezierP1( t, p ) {
  24098. return 2 * ( 1 - t ) * t * p;
  24099. }
  24100. function QuadraticBezierP2( t, p ) {
  24101. return t * t * p;
  24102. }
  24103. /**
  24104. * Computes a point on a Quadratic Bezier curve.
  24105. *
  24106. * @param {number} t - The interpolation factor.
  24107. * @param {number} p0 - The first control point.
  24108. * @param {number} p1 - The second control point.
  24109. * @param {number} p2 - The third control point.
  24110. * @return {number} The calculated point on a Quadratic Bezier curve.
  24111. */
  24112. function QuadraticBezier( t, p0, p1, p2 ) {
  24113. return QuadraticBezierP0( t, p0 ) + QuadraticBezierP1( t, p1 ) +
  24114. QuadraticBezierP2( t, p2 );
  24115. }
  24116. //
  24117. function CubicBezierP0( t, p ) {
  24118. const k = 1 - t;
  24119. return k * k * k * p;
  24120. }
  24121. function CubicBezierP1( t, p ) {
  24122. const k = 1 - t;
  24123. return 3 * k * k * t * p;
  24124. }
  24125. function CubicBezierP2( t, p ) {
  24126. return 3 * ( 1 - t ) * t * t * p;
  24127. }
  24128. function CubicBezierP3( t, p ) {
  24129. return t * t * t * p;
  24130. }
  24131. /**
  24132. * Computes a point on a Cubic Bezier curve.
  24133. *
  24134. * @param {number} t - The interpolation factor.
  24135. * @param {number} p0 - The first control point.
  24136. * @param {number} p1 - The second control point.
  24137. * @param {number} p2 - The third control point.
  24138. * @param {number} p3 - The fourth control point.
  24139. * @return {number} The calculated point on a Cubic Bezier curve.
  24140. */
  24141. function CubicBezier( t, p0, p1, p2, p3 ) {
  24142. return CubicBezierP0( t, p0 ) + CubicBezierP1( t, p1 ) + CubicBezierP2( t, p2 ) +
  24143. CubicBezierP3( t, p3 );
  24144. }
  24145. /**
  24146. * A curve representing a 2D Cubic Bezier curve.
  24147. *
  24148. * ```js
  24149. * const curve = new THREE.CubicBezierCurve(
  24150. * new THREE.Vector2( - 0, 0 ),
  24151. * new THREE.Vector2( - 5, 15 ),
  24152. * new THREE.Vector2( 20, 15 ),
  24153. * new THREE.Vector2( 10, 0 )
  24154. * );
  24155. *
  24156. * const points = curve.getPoints( 50 );
  24157. * const geometry = new THREE.BufferGeometry().setFromPoints( points );
  24158. *
  24159. * const material = new THREE.LineBasicMaterial( { color: 0xff0000 } );
  24160. *
  24161. * // Create the final object to add to the scene
  24162. * const curveObject = new THREE.Line( geometry, material );
  24163. * ```
  24164. *
  24165. * @augments Curve
  24166. */
  24167. class CubicBezierCurve extends Curve {
  24168. /**
  24169. * Constructs a new Cubic Bezier curve.
  24170. *
  24171. * @param {Vector2} [v0] - The start point.
  24172. * @param {Vector2} [v1] - The first control point.
  24173. * @param {Vector2} [v2] - The second control point.
  24174. * @param {Vector2} [v3] - The end point.
  24175. */
  24176. constructor( v0 = new Vector2(), v1 = new Vector2(), v2 = new Vector2(), v3 = new Vector2() ) {
  24177. super();
  24178. /**
  24179. * This flag can be used for type testing.
  24180. *
  24181. * @type {boolean}
  24182. * @readonly
  24183. * @default true
  24184. */
  24185. this.isCubicBezierCurve = true;
  24186. this.type = 'CubicBezierCurve';
  24187. /**
  24188. * The start point.
  24189. *
  24190. * @type {Vector2}
  24191. */
  24192. this.v0 = v0;
  24193. /**
  24194. * The first control point.
  24195. *
  24196. * @type {Vector2}
  24197. */
  24198. this.v1 = v1;
  24199. /**
  24200. * The second control point.
  24201. *
  24202. * @type {Vector2}
  24203. */
  24204. this.v2 = v2;
  24205. /**
  24206. * The end point.
  24207. *
  24208. * @type {Vector2}
  24209. */
  24210. this.v3 = v3;
  24211. }
  24212. /**
  24213. * Returns a point on the curve.
  24214. *
  24215. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  24216. * @param {Vector2} [optionalTarget] - The optional target vector the result is written to.
  24217. * @return {Vector2} The position on the curve.
  24218. */
  24219. getPoint( t, optionalTarget = new Vector2() ) {
  24220. const point = optionalTarget;
  24221. const v0 = this.v0, v1 = this.v1, v2 = this.v2, v3 = this.v3;
  24222. point.set(
  24223. CubicBezier( t, v0.x, v1.x, v2.x, v3.x ),
  24224. CubicBezier( t, v0.y, v1.y, v2.y, v3.y )
  24225. );
  24226. return point;
  24227. }
  24228. copy( source ) {
  24229. super.copy( source );
  24230. this.v0.copy( source.v0 );
  24231. this.v1.copy( source.v1 );
  24232. this.v2.copy( source.v2 );
  24233. this.v3.copy( source.v3 );
  24234. return this;
  24235. }
  24236. toJSON() {
  24237. const data = super.toJSON();
  24238. data.v0 = this.v0.toArray();
  24239. data.v1 = this.v1.toArray();
  24240. data.v2 = this.v2.toArray();
  24241. data.v3 = this.v3.toArray();
  24242. return data;
  24243. }
  24244. fromJSON( json ) {
  24245. super.fromJSON( json );
  24246. this.v0.fromArray( json.v0 );
  24247. this.v1.fromArray( json.v1 );
  24248. this.v2.fromArray( json.v2 );
  24249. this.v3.fromArray( json.v3 );
  24250. return this;
  24251. }
  24252. }
  24253. /**
  24254. * A curve representing a 3D Cubic Bezier curve.
  24255. *
  24256. * @augments Curve
  24257. */
  24258. class CubicBezierCurve3 extends Curve {
  24259. /**
  24260. * Constructs a new Cubic Bezier curve.
  24261. *
  24262. * @param {Vector3} [v0] - The start point.
  24263. * @param {Vector3} [v1] - The first control point.
  24264. * @param {Vector3} [v2] - The second control point.
  24265. * @param {Vector3} [v3] - The end point.
  24266. */
  24267. constructor( v0 = new Vector3(), v1 = new Vector3(), v2 = new Vector3(), v3 = new Vector3() ) {
  24268. super();
  24269. /**
  24270. * This flag can be used for type testing.
  24271. *
  24272. * @type {boolean}
  24273. * @readonly
  24274. * @default true
  24275. */
  24276. this.isCubicBezierCurve3 = true;
  24277. this.type = 'CubicBezierCurve3';
  24278. /**
  24279. * The start point.
  24280. *
  24281. * @type {Vector3}
  24282. */
  24283. this.v0 = v0;
  24284. /**
  24285. * The first control point.
  24286. *
  24287. * @type {Vector3}
  24288. */
  24289. this.v1 = v1;
  24290. /**
  24291. * The second control point.
  24292. *
  24293. * @type {Vector3}
  24294. */
  24295. this.v2 = v2;
  24296. /**
  24297. * The end point.
  24298. *
  24299. * @type {Vector3}
  24300. */
  24301. this.v3 = v3;
  24302. }
  24303. /**
  24304. * Returns a point on the curve.
  24305. *
  24306. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  24307. * @param {Vector3} [optionalTarget] - The optional target vector the result is written to.
  24308. * @return {Vector3} The position on the curve.
  24309. */
  24310. getPoint( t, optionalTarget = new Vector3() ) {
  24311. const point = optionalTarget;
  24312. const v0 = this.v0, v1 = this.v1, v2 = this.v2, v3 = this.v3;
  24313. point.set(
  24314. CubicBezier( t, v0.x, v1.x, v2.x, v3.x ),
  24315. CubicBezier( t, v0.y, v1.y, v2.y, v3.y ),
  24316. CubicBezier( t, v0.z, v1.z, v2.z, v3.z )
  24317. );
  24318. return point;
  24319. }
  24320. copy( source ) {
  24321. super.copy( source );
  24322. this.v0.copy( source.v0 );
  24323. this.v1.copy( source.v1 );
  24324. this.v2.copy( source.v2 );
  24325. this.v3.copy( source.v3 );
  24326. return this;
  24327. }
  24328. toJSON() {
  24329. const data = super.toJSON();
  24330. data.v0 = this.v0.toArray();
  24331. data.v1 = this.v1.toArray();
  24332. data.v2 = this.v2.toArray();
  24333. data.v3 = this.v3.toArray();
  24334. return data;
  24335. }
  24336. fromJSON( json ) {
  24337. super.fromJSON( json );
  24338. this.v0.fromArray( json.v0 );
  24339. this.v1.fromArray( json.v1 );
  24340. this.v2.fromArray( json.v2 );
  24341. this.v3.fromArray( json.v3 );
  24342. return this;
  24343. }
  24344. }
  24345. /**
  24346. * A curve representing a 2D line segment.
  24347. *
  24348. * @augments Curve
  24349. */
  24350. class LineCurve extends Curve {
  24351. /**
  24352. * Constructs a new line curve.
  24353. *
  24354. * @param {Vector2} [v1] - The start point.
  24355. * @param {Vector2} [v2] - The end point.
  24356. */
  24357. constructor( v1 = new Vector2(), v2 = new Vector2() ) {
  24358. super();
  24359. /**
  24360. * This flag can be used for type testing.
  24361. *
  24362. * @type {boolean}
  24363. * @readonly
  24364. * @default true
  24365. */
  24366. this.isLineCurve = true;
  24367. this.type = 'LineCurve';
  24368. /**
  24369. * The start point.
  24370. *
  24371. * @type {Vector2}
  24372. */
  24373. this.v1 = v1;
  24374. /**
  24375. * The end point.
  24376. *
  24377. * @type {Vector2}
  24378. */
  24379. this.v2 = v2;
  24380. }
  24381. /**
  24382. * Returns a point on the line.
  24383. *
  24384. * @param {number} t - A interpolation factor representing a position on the line. Must be in the range `[0,1]`.
  24385. * @param {Vector2} [optionalTarget] - The optional target vector the result is written to.
  24386. * @return {Vector2} The position on the line.
  24387. */
  24388. getPoint( t, optionalTarget = new Vector2() ) {
  24389. const point = optionalTarget;
  24390. if ( t === 1 ) {
  24391. point.copy( this.v2 );
  24392. } else {
  24393. point.copy( this.v2 ).sub( this.v1 );
  24394. point.multiplyScalar( t ).add( this.v1 );
  24395. }
  24396. return point;
  24397. }
  24398. // Line curve is linear, so we can overwrite default getPointAt
  24399. getPointAt( u, optionalTarget ) {
  24400. return this.getPoint( u, optionalTarget );
  24401. }
  24402. getTangent( t, optionalTarget = new Vector2() ) {
  24403. return optionalTarget.subVectors( this.v2, this.v1 ).normalize();
  24404. }
  24405. getTangentAt( u, optionalTarget ) {
  24406. return this.getTangent( u, optionalTarget );
  24407. }
  24408. copy( source ) {
  24409. super.copy( source );
  24410. this.v1.copy( source.v1 );
  24411. this.v2.copy( source.v2 );
  24412. return this;
  24413. }
  24414. toJSON() {
  24415. const data = super.toJSON();
  24416. data.v1 = this.v1.toArray();
  24417. data.v2 = this.v2.toArray();
  24418. return data;
  24419. }
  24420. fromJSON( json ) {
  24421. super.fromJSON( json );
  24422. this.v1.fromArray( json.v1 );
  24423. this.v2.fromArray( json.v2 );
  24424. return this;
  24425. }
  24426. }
  24427. /**
  24428. * A curve representing a 3D line segment.
  24429. *
  24430. * @augments Curve
  24431. */
  24432. class LineCurve3 extends Curve {
  24433. /**
  24434. * Constructs a new line curve.
  24435. *
  24436. * @param {Vector3} [v1] - The start point.
  24437. * @param {Vector3} [v2] - The end point.
  24438. */
  24439. constructor( v1 = new Vector3(), v2 = new Vector3() ) {
  24440. super();
  24441. /**
  24442. * This flag can be used for type testing.
  24443. *
  24444. * @type {boolean}
  24445. * @readonly
  24446. * @default true
  24447. */
  24448. this.isLineCurve3 = true;
  24449. this.type = 'LineCurve3';
  24450. /**
  24451. * The start point.
  24452. *
  24453. * @type {Vector3}
  24454. */
  24455. this.v1 = v1;
  24456. /**
  24457. * The end point.
  24458. *
  24459. * @type {Vector2}
  24460. */
  24461. this.v2 = v2;
  24462. }
  24463. /**
  24464. * Returns a point on the line.
  24465. *
  24466. * @param {number} t - A interpolation factor representing a position on the line. Must be in the range `[0,1]`.
  24467. * @param {Vector3} [optionalTarget] - The optional target vector the result is written to.
  24468. * @return {Vector3} The position on the line.
  24469. */
  24470. getPoint( t, optionalTarget = new Vector3() ) {
  24471. const point = optionalTarget;
  24472. if ( t === 1 ) {
  24473. point.copy( this.v2 );
  24474. } else {
  24475. point.copy( this.v2 ).sub( this.v1 );
  24476. point.multiplyScalar( t ).add( this.v1 );
  24477. }
  24478. return point;
  24479. }
  24480. // Line curve is linear, so we can overwrite default getPointAt
  24481. getPointAt( u, optionalTarget ) {
  24482. return this.getPoint( u, optionalTarget );
  24483. }
  24484. getTangent( t, optionalTarget = new Vector3() ) {
  24485. return optionalTarget.subVectors( this.v2, this.v1 ).normalize();
  24486. }
  24487. getTangentAt( u, optionalTarget ) {
  24488. return this.getTangent( u, optionalTarget );
  24489. }
  24490. copy( source ) {
  24491. super.copy( source );
  24492. this.v1.copy( source.v1 );
  24493. this.v2.copy( source.v2 );
  24494. return this;
  24495. }
  24496. toJSON() {
  24497. const data = super.toJSON();
  24498. data.v1 = this.v1.toArray();
  24499. data.v2 = this.v2.toArray();
  24500. return data;
  24501. }
  24502. fromJSON( json ) {
  24503. super.fromJSON( json );
  24504. this.v1.fromArray( json.v1 );
  24505. this.v2.fromArray( json.v2 );
  24506. return this;
  24507. }
  24508. }
  24509. /**
  24510. * A curve representing a 2D Quadratic Bezier curve.
  24511. *
  24512. * ```js
  24513. * const curve = new THREE.QuadraticBezierCurve(
  24514. * new THREE.Vector2( - 10, 0 ),
  24515. * new THREE.Vector2( 20, 15 ),
  24516. * new THREE.Vector2( 10, 0 )
  24517. * )
  24518. *
  24519. * const points = curve.getPoints( 50 );
  24520. * const geometry = new THREE.BufferGeometry().setFromPoints( points );
  24521. *
  24522. * const material = new THREE.LineBasicMaterial( { color: 0xff0000 } );
  24523. *
  24524. * // Create the final object to add to the scene
  24525. * const curveObject = new THREE.Line( geometry, material );
  24526. * ```
  24527. *
  24528. * @augments Curve
  24529. */
  24530. class QuadraticBezierCurve extends Curve {
  24531. /**
  24532. * Constructs a new Quadratic Bezier curve.
  24533. *
  24534. * @param {Vector2} [v0] - The start point.
  24535. * @param {Vector2} [v1] - The control point.
  24536. * @param {Vector2} [v2] - The end point.
  24537. */
  24538. constructor( v0 = new Vector2(), v1 = new Vector2(), v2 = new Vector2() ) {
  24539. super();
  24540. /**
  24541. * This flag can be used for type testing.
  24542. *
  24543. * @type {boolean}
  24544. * @readonly
  24545. * @default true
  24546. */
  24547. this.isQuadraticBezierCurve = true;
  24548. this.type = 'QuadraticBezierCurve';
  24549. /**
  24550. * The start point.
  24551. *
  24552. * @type {Vector2}
  24553. */
  24554. this.v0 = v0;
  24555. /**
  24556. * The control point.
  24557. *
  24558. * @type {Vector2}
  24559. */
  24560. this.v1 = v1;
  24561. /**
  24562. * The end point.
  24563. *
  24564. * @type {Vector2}
  24565. */
  24566. this.v2 = v2;
  24567. }
  24568. /**
  24569. * Returns a point on the curve.
  24570. *
  24571. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  24572. * @param {Vector2} [optionalTarget] - The optional target vector the result is written to.
  24573. * @return {Vector2} The position on the curve.
  24574. */
  24575. getPoint( t, optionalTarget = new Vector2() ) {
  24576. const point = optionalTarget;
  24577. const v0 = this.v0, v1 = this.v1, v2 = this.v2;
  24578. point.set(
  24579. QuadraticBezier( t, v0.x, v1.x, v2.x ),
  24580. QuadraticBezier( t, v0.y, v1.y, v2.y )
  24581. );
  24582. return point;
  24583. }
  24584. copy( source ) {
  24585. super.copy( source );
  24586. this.v0.copy( source.v0 );
  24587. this.v1.copy( source.v1 );
  24588. this.v2.copy( source.v2 );
  24589. return this;
  24590. }
  24591. toJSON() {
  24592. const data = super.toJSON();
  24593. data.v0 = this.v0.toArray();
  24594. data.v1 = this.v1.toArray();
  24595. data.v2 = this.v2.toArray();
  24596. return data;
  24597. }
  24598. fromJSON( json ) {
  24599. super.fromJSON( json );
  24600. this.v0.fromArray( json.v0 );
  24601. this.v1.fromArray( json.v1 );
  24602. this.v2.fromArray( json.v2 );
  24603. return this;
  24604. }
  24605. }
  24606. /**
  24607. * A curve representing a 3D Quadratic Bezier curve.
  24608. *
  24609. * @augments Curve
  24610. */
  24611. class QuadraticBezierCurve3 extends Curve {
  24612. /**
  24613. * Constructs a new Quadratic Bezier curve.
  24614. *
  24615. * @param {Vector3} [v0] - The start point.
  24616. * @param {Vector3} [v1] - The control point.
  24617. * @param {Vector3} [v2] - The end point.
  24618. */
  24619. constructor( v0 = new Vector3(), v1 = new Vector3(), v2 = new Vector3() ) {
  24620. super();
  24621. /**
  24622. * This flag can be used for type testing.
  24623. *
  24624. * @type {boolean}
  24625. * @readonly
  24626. * @default true
  24627. */
  24628. this.isQuadraticBezierCurve3 = true;
  24629. this.type = 'QuadraticBezierCurve3';
  24630. /**
  24631. * The start point.
  24632. *
  24633. * @type {Vector3}
  24634. */
  24635. this.v0 = v0;
  24636. /**
  24637. * The control point.
  24638. *
  24639. * @type {Vector3}
  24640. */
  24641. this.v1 = v1;
  24642. /**
  24643. * The end point.
  24644. *
  24645. * @type {Vector3}
  24646. */
  24647. this.v2 = v2;
  24648. }
  24649. /**
  24650. * Returns a point on the curve.
  24651. *
  24652. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  24653. * @param {Vector3} [optionalTarget] - The optional target vector the result is written to.
  24654. * @return {Vector3} The position on the curve.
  24655. */
  24656. getPoint( t, optionalTarget = new Vector3() ) {
  24657. const point = optionalTarget;
  24658. const v0 = this.v0, v1 = this.v1, v2 = this.v2;
  24659. point.set(
  24660. QuadraticBezier( t, v0.x, v1.x, v2.x ),
  24661. QuadraticBezier( t, v0.y, v1.y, v2.y ),
  24662. QuadraticBezier( t, v0.z, v1.z, v2.z )
  24663. );
  24664. return point;
  24665. }
  24666. copy( source ) {
  24667. super.copy( source );
  24668. this.v0.copy( source.v0 );
  24669. this.v1.copy( source.v1 );
  24670. this.v2.copy( source.v2 );
  24671. return this;
  24672. }
  24673. toJSON() {
  24674. const data = super.toJSON();
  24675. data.v0 = this.v0.toArray();
  24676. data.v1 = this.v1.toArray();
  24677. data.v2 = this.v2.toArray();
  24678. return data;
  24679. }
  24680. fromJSON( json ) {
  24681. super.fromJSON( json );
  24682. this.v0.fromArray( json.v0 );
  24683. this.v1.fromArray( json.v1 );
  24684. this.v2.fromArray( json.v2 );
  24685. return this;
  24686. }
  24687. }
  24688. /**
  24689. * A curve representing a 2D spline curve.
  24690. *
  24691. * ```js
  24692. * // Create a sine-like wave
  24693. * const curve = new THREE.SplineCurve( [
  24694. * new THREE.Vector2( -10, 0 ),
  24695. * new THREE.Vector2( -5, 5 ),
  24696. * new THREE.Vector2( 0, 0 ),
  24697. * new THREE.Vector2( 5, -5 ),
  24698. * new THREE.Vector2( 10, 0 )
  24699. * ] );
  24700. *
  24701. * const points = curve.getPoints( 50 );
  24702. * const geometry = new THREE.BufferGeometry().setFromPoints( points );
  24703. *
  24704. * const material = new THREE.LineBasicMaterial( { color: 0xff0000 } );
  24705. *
  24706. * // Create the final object to add to the scene
  24707. * const splineObject = new THREE.Line( geometry, material );
  24708. * ```
  24709. *
  24710. * @augments Curve
  24711. */
  24712. class SplineCurve extends Curve {
  24713. /**
  24714. * Constructs a new 2D spline curve.
  24715. *
  24716. * @param {Array<Vector2>} [points] - An array of 2D points defining the curve.
  24717. */
  24718. constructor( points = [] ) {
  24719. super();
  24720. /**
  24721. * This flag can be used for type testing.
  24722. *
  24723. * @type {boolean}
  24724. * @readonly
  24725. * @default true
  24726. */
  24727. this.isSplineCurve = true;
  24728. this.type = 'SplineCurve';
  24729. /**
  24730. * An array of 2D points defining the curve.
  24731. *
  24732. * @type {Array<Vector2>}
  24733. */
  24734. this.points = points;
  24735. }
  24736. /**
  24737. * Returns a point on the curve.
  24738. *
  24739. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  24740. * @param {Vector2} [optionalTarget] - The optional target vector the result is written to.
  24741. * @return {Vector2} The position on the curve.
  24742. */
  24743. getPoint( t, optionalTarget = new Vector2() ) {
  24744. const point = optionalTarget;
  24745. const points = this.points;
  24746. const p = ( points.length - 1 ) * t;
  24747. const intPoint = Math.floor( p );
  24748. const weight = p - intPoint;
  24749. const p0 = points[ intPoint === 0 ? intPoint : intPoint - 1 ];
  24750. const p1 = points[ intPoint ];
  24751. const p2 = points[ intPoint > points.length - 2 ? points.length - 1 : intPoint + 1 ];
  24752. const p3 = points[ intPoint > points.length - 3 ? points.length - 1 : intPoint + 2 ];
  24753. point.set(
  24754. CatmullRom( weight, p0.x, p1.x, p2.x, p3.x ),
  24755. CatmullRom( weight, p0.y, p1.y, p2.y, p3.y )
  24756. );
  24757. return point;
  24758. }
  24759. copy( source ) {
  24760. super.copy( source );
  24761. this.points = [];
  24762. for ( let i = 0, l = source.points.length; i < l; i ++ ) {
  24763. const point = source.points[ i ];
  24764. this.points.push( point.clone() );
  24765. }
  24766. return this;
  24767. }
  24768. toJSON() {
  24769. const data = super.toJSON();
  24770. data.points = [];
  24771. for ( let i = 0, l = this.points.length; i < l; i ++ ) {
  24772. const point = this.points[ i ];
  24773. data.points.push( point.toArray() );
  24774. }
  24775. return data;
  24776. }
  24777. fromJSON( json ) {
  24778. super.fromJSON( json );
  24779. this.points = [];
  24780. for ( let i = 0, l = json.points.length; i < l; i ++ ) {
  24781. const point = json.points[ i ];
  24782. this.points.push( new Vector2().fromArray( point ) );
  24783. }
  24784. return this;
  24785. }
  24786. }
  24787. var Curves = /*#__PURE__*/Object.freeze({
  24788. __proto__: null,
  24789. ArcCurve: ArcCurve,
  24790. CatmullRomCurve3: CatmullRomCurve3,
  24791. CubicBezierCurve: CubicBezierCurve,
  24792. CubicBezierCurve3: CubicBezierCurve3,
  24793. EllipseCurve: EllipseCurve,
  24794. LineCurve: LineCurve,
  24795. LineCurve3: LineCurve3,
  24796. QuadraticBezierCurve: QuadraticBezierCurve,
  24797. QuadraticBezierCurve3: QuadraticBezierCurve3,
  24798. SplineCurve: SplineCurve
  24799. });
  24800. /**
  24801. * A base class extending {@link Curve}. `CurvePath` is simply an
  24802. * array of connected curves, but retains the API of a curve.
  24803. *
  24804. * @augments Curve
  24805. */
  24806. class CurvePath extends Curve {
  24807. /**
  24808. * Constructs a new curve path.
  24809. */
  24810. constructor() {
  24811. super();
  24812. this.type = 'CurvePath';
  24813. /**
  24814. * An array of curves defining the
  24815. * path.
  24816. *
  24817. * @type {Array<Curve>}
  24818. */
  24819. this.curves = [];
  24820. /**
  24821. * Whether the path should automatically be closed
  24822. * by a line curve.
  24823. *
  24824. * @type {boolean}
  24825. * @default false
  24826. */
  24827. this.autoClose = false;
  24828. }
  24829. /**
  24830. * Adds a curve to this curve path.
  24831. *
  24832. * @param {Curve} curve - The curve to add.
  24833. */
  24834. add( curve ) {
  24835. this.curves.push( curve );
  24836. }
  24837. /**
  24838. * Adds a line curve to close the path.
  24839. *
  24840. * @return {CurvePath} A reference to this curve path.
  24841. */
  24842. closePath() {
  24843. // Add a line curve if start and end of lines are not connected
  24844. const startPoint = this.curves[ 0 ].getPoint( 0 );
  24845. const endPoint = this.curves[ this.curves.length - 1 ].getPoint( 1 );
  24846. if ( ! startPoint.equals( endPoint ) ) {
  24847. const lineType = ( startPoint.isVector2 === true ) ? 'LineCurve' : 'LineCurve3';
  24848. this.curves.push( new Curves[ lineType ]( endPoint, startPoint ) );
  24849. }
  24850. return this;
  24851. }
  24852. /**
  24853. * This method returns a vector in 2D or 3D space (depending on the curve definitions)
  24854. * for the given interpolation factor.
  24855. *
  24856. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  24857. * @param {(Vector2|Vector3)} [optionalTarget] - The optional target vector the result is written to.
  24858. * @return {?(Vector2|Vector3)} The position on the curve. It can be a 2D or 3D vector depending on the curve definition.
  24859. */
  24860. getPoint( t, optionalTarget ) {
  24861. // To get accurate point with reference to
  24862. // entire path distance at time t,
  24863. // following has to be done:
  24864. // 1. Length of each sub path have to be known
  24865. // 2. Locate and identify type of curve
  24866. // 3. Get t for the curve
  24867. // 4. Return curve.getPointAt(t')
  24868. const d = t * this.getLength();
  24869. const curveLengths = this.getCurveLengths();
  24870. let i = 0;
  24871. // To think about boundaries points.
  24872. while ( i < curveLengths.length ) {
  24873. if ( curveLengths[ i ] >= d ) {
  24874. const diff = curveLengths[ i ] - d;
  24875. const curve = this.curves[ i ];
  24876. const segmentLength = curve.getLength();
  24877. const u = segmentLength === 0 ? 0 : 1 - diff / segmentLength;
  24878. return curve.getPointAt( u, optionalTarget );
  24879. }
  24880. i ++;
  24881. }
  24882. return null;
  24883. // loop where sum != 0, sum > d , sum+1 <d
  24884. }
  24885. getLength() {
  24886. // We cannot use the default THREE.Curve getPoint() with getLength() because in
  24887. // THREE.Curve, getLength() depends on getPoint() but in THREE.CurvePath
  24888. // getPoint() depends on getLength
  24889. const lens = this.getCurveLengths();
  24890. return lens[ lens.length - 1 ];
  24891. }
  24892. updateArcLengths() {
  24893. // cacheLengths must be recalculated.
  24894. this.needsUpdate = true;
  24895. this.cacheLengths = null;
  24896. this.getCurveLengths();
  24897. }
  24898. /**
  24899. * Returns list of cumulative curve lengths of the defined curves.
  24900. *
  24901. * @return {Array<number>} The curve lengths.
  24902. */
  24903. getCurveLengths() {
  24904. // Compute lengths and cache them
  24905. // We cannot overwrite getLengths() because UtoT mapping uses it.
  24906. // We use cache values if curves and cache array are same length
  24907. if ( this.cacheLengths && this.cacheLengths.length === this.curves.length ) {
  24908. return this.cacheLengths;
  24909. }
  24910. // Get length of sub-curve
  24911. // Push sums into cached array
  24912. const lengths = [];
  24913. let sums = 0;
  24914. for ( let i = 0, l = this.curves.length; i < l; i ++ ) {
  24915. sums += this.curves[ i ].getLength();
  24916. lengths.push( sums );
  24917. }
  24918. this.cacheLengths = lengths;
  24919. return lengths;
  24920. }
  24921. getSpacedPoints( divisions = 40 ) {
  24922. const points = [];
  24923. for ( let i = 0; i <= divisions; i ++ ) {
  24924. points.push( this.getPoint( i / divisions ) );
  24925. }
  24926. if ( this.autoClose ) {
  24927. points.push( points[ 0 ] );
  24928. }
  24929. return points;
  24930. }
  24931. getPoints( divisions = 12 ) {
  24932. const points = [];
  24933. let last;
  24934. for ( let i = 0, curves = this.curves; i < curves.length; i ++ ) {
  24935. const curve = curves[ i ];
  24936. const resolution = curve.isEllipseCurve ? divisions * 2
  24937. : ( curve.isLineCurve || curve.isLineCurve3 ) ? 1
  24938. : curve.isSplineCurve ? divisions * curve.points.length
  24939. : divisions;
  24940. const pts = curve.getPoints( resolution );
  24941. for ( let j = 0; j < pts.length; j ++ ) {
  24942. const point = pts[ j ];
  24943. if ( last && last.equals( point ) ) continue; // ensures no consecutive points are duplicates
  24944. points.push( point );
  24945. last = point;
  24946. }
  24947. }
  24948. if ( this.autoClose && points.length > 1 && ! points[ points.length - 1 ].equals( points[ 0 ] ) ) {
  24949. points.push( points[ 0 ] );
  24950. }
  24951. return points;
  24952. }
  24953. copy( source ) {
  24954. super.copy( source );
  24955. this.curves = [];
  24956. for ( let i = 0, l = source.curves.length; i < l; i ++ ) {
  24957. const curve = source.curves[ i ];
  24958. this.curves.push( curve.clone() );
  24959. }
  24960. this.autoClose = source.autoClose;
  24961. return this;
  24962. }
  24963. toJSON() {
  24964. const data = super.toJSON();
  24965. data.autoClose = this.autoClose;
  24966. data.curves = [];
  24967. for ( let i = 0, l = this.curves.length; i < l; i ++ ) {
  24968. const curve = this.curves[ i ];
  24969. data.curves.push( curve.toJSON() );
  24970. }
  24971. return data;
  24972. }
  24973. fromJSON( json ) {
  24974. super.fromJSON( json );
  24975. this.autoClose = json.autoClose;
  24976. this.curves = [];
  24977. for ( let i = 0, l = json.curves.length; i < l; i ++ ) {
  24978. const curve = json.curves[ i ];
  24979. this.curves.push( new Curves[ curve.type ]().fromJSON( curve ) );
  24980. }
  24981. return this;
  24982. }
  24983. }
  24984. /**
  24985. * A 2D path representation. The class provides methods for creating paths
  24986. * and contours of 2D shapes similar to the 2D Canvas API.
  24987. *
  24988. * ```js
  24989. * const path = new THREE.Path();
  24990. *
  24991. * path.lineTo( 0, 0.8 );
  24992. * path.quadraticCurveTo( 0, 1, 0.2, 1 );
  24993. * path.lineTo( 1, 1 );
  24994. *
  24995. * const points = path.getPoints();
  24996. *
  24997. * const geometry = new THREE.BufferGeometry().setFromPoints( points );
  24998. * const material = new THREE.LineBasicMaterial( { color: 0xffffff } );
  24999. *
  25000. * const line = new THREE.Line( geometry, material );
  25001. * scene.add( line );
  25002. * ```
  25003. *
  25004. * @augments CurvePath
  25005. */
  25006. class Path extends CurvePath {
  25007. /**
  25008. * Constructs a new path.
  25009. *
  25010. * @param {Array<Vector2>} [points] - An array of 2D points defining the path.
  25011. */
  25012. constructor( points ) {
  25013. super();
  25014. this.type = 'Path';
  25015. /**
  25016. * The current offset of the path. Any new curve added will start here.
  25017. *
  25018. * @type {Vector2}
  25019. */
  25020. this.currentPoint = new Vector2();
  25021. if ( points ) {
  25022. this.setFromPoints( points );
  25023. }
  25024. }
  25025. /**
  25026. * Creates a path from the given list of points. The points are added
  25027. * to the path as instances of {@link LineCurve}.
  25028. *
  25029. * @param {Array<Vector2>} points - An array of 2D points.
  25030. * @return {Path} A reference to this path.
  25031. */
  25032. setFromPoints( points ) {
  25033. this.moveTo( points[ 0 ].x, points[ 0 ].y );
  25034. for ( let i = 1, l = points.length; i < l; i ++ ) {
  25035. this.lineTo( points[ i ].x, points[ i ].y );
  25036. }
  25037. return this;
  25038. }
  25039. /**
  25040. * Moves {@link Path#currentPoint} to the given point.
  25041. *
  25042. * @param {number} x - The x coordinate.
  25043. * @param {number} y - The y coordinate.
  25044. * @return {Path} A reference to this path.
  25045. */
  25046. moveTo( x, y ) {
  25047. this.currentPoint.set( x, y ); // TODO consider referencing vectors instead of copying?
  25048. return this;
  25049. }
  25050. /**
  25051. * Adds an instance of {@link LineCurve} to the path by connecting
  25052. * the current point with the given one.
  25053. *
  25054. * @param {number} x - The x coordinate of the end point.
  25055. * @param {number} y - The y coordinate of the end point.
  25056. * @return {Path} A reference to this path.
  25057. */
  25058. lineTo( x, y ) {
  25059. const curve = new LineCurve( this.currentPoint.clone(), new Vector2( x, y ) );
  25060. this.curves.push( curve );
  25061. this.currentPoint.set( x, y );
  25062. return this;
  25063. }
  25064. /**
  25065. * Adds an instance of {@link QuadraticBezierCurve} to the path by connecting
  25066. * the current point with the given one.
  25067. *
  25068. * @param {number} aCPx - The x coordinate of the control point.
  25069. * @param {number} aCPy - The y coordinate of the control point.
  25070. * @param {number} aX - The x coordinate of the end point.
  25071. * @param {number} aY - The y coordinate of the end point.
  25072. * @return {Path} A reference to this path.
  25073. */
  25074. quadraticCurveTo( aCPx, aCPy, aX, aY ) {
  25075. const curve = new QuadraticBezierCurve(
  25076. this.currentPoint.clone(),
  25077. new Vector2( aCPx, aCPy ),
  25078. new Vector2( aX, aY )
  25079. );
  25080. this.curves.push( curve );
  25081. this.currentPoint.set( aX, aY );
  25082. return this;
  25083. }
  25084. /**
  25085. * Adds an instance of {@link CubicBezierCurve} to the path by connecting
  25086. * the current point with the given one.
  25087. *
  25088. * @param {number} aCP1x - The x coordinate of the first control point.
  25089. * @param {number} aCP1y - The y coordinate of the first control point.
  25090. * @param {number} aCP2x - The x coordinate of the second control point.
  25091. * @param {number} aCP2y - The y coordinate of the second control point.
  25092. * @param {number} aX - The x coordinate of the end point.
  25093. * @param {number} aY - The y coordinate of the end point.
  25094. * @return {Path} A reference to this path.
  25095. */
  25096. bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) {
  25097. const curve = new CubicBezierCurve(
  25098. this.currentPoint.clone(),
  25099. new Vector2( aCP1x, aCP1y ),
  25100. new Vector2( aCP2x, aCP2y ),
  25101. new Vector2( aX, aY )
  25102. );
  25103. this.curves.push( curve );
  25104. this.currentPoint.set( aX, aY );
  25105. return this;
  25106. }
  25107. /**
  25108. * Adds an instance of {@link SplineCurve} to the path by connecting
  25109. * the current point with the given list of points.
  25110. *
  25111. * @param {Array<Vector2>} pts - An array of points in 2D space.
  25112. * @return {Path} A reference to this path.
  25113. */
  25114. splineThru( pts ) {
  25115. const npts = [ this.currentPoint.clone() ].concat( pts );
  25116. const curve = new SplineCurve( npts );
  25117. this.curves.push( curve );
  25118. this.currentPoint.copy( pts[ pts.length - 1 ] );
  25119. return this;
  25120. }
  25121. /**
  25122. * Adds an arc as an instance of {@link EllipseCurve} to the path, positioned relative
  25123. * to the current point.
  25124. *
  25125. * @param {number} [aX=0] - The x coordinate of the center of the arc offsetted from the previous curve.
  25126. * @param {number} [aY=0] - The y coordinate of the center of the arc offsetted from the previous curve.
  25127. * @param {number} [aRadius=1] - The radius of the arc.
  25128. * @param {number} [aStartAngle=0] - The start angle in radians.
  25129. * @param {number} [aEndAngle=Math.PI*2] - The end angle in radians.
  25130. * @param {boolean} [aClockwise=false] - Whether to sweep the arc clockwise or not.
  25131. * @return {Path} A reference to this path.
  25132. */
  25133. arc( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  25134. const x0 = this.currentPoint.x;
  25135. const y0 = this.currentPoint.y;
  25136. this.absarc( aX + x0, aY + y0, aRadius,
  25137. aStartAngle, aEndAngle, aClockwise );
  25138. return this;
  25139. }
  25140. /**
  25141. * Adds an absolutely positioned arc as an instance of {@link EllipseCurve} to the path.
  25142. *
  25143. * @param {number} [aX=0] - The x coordinate of the center of the arc.
  25144. * @param {number} [aY=0] - The y coordinate of the center of the arc.
  25145. * @param {number} [aRadius=1] - The radius of the arc.
  25146. * @param {number} [aStartAngle=0] - The start angle in radians.
  25147. * @param {number} [aEndAngle=Math.PI*2] - The end angle in radians.
  25148. * @param {boolean} [aClockwise=false] - Whether to sweep the arc clockwise or not.
  25149. * @return {Path} A reference to this path.
  25150. */
  25151. absarc( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  25152. this.absellipse( aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  25153. return this;
  25154. }
  25155. /**
  25156. * Adds an ellipse as an instance of {@link EllipseCurve} to the path, positioned relative
  25157. * to the current point
  25158. *
  25159. * @param {number} [aX=0] - The x coordinate of the center of the ellipse offsetted from the previous curve.
  25160. * @param {number} [aY=0] - The y coordinate of the center of the ellipse offsetted from the previous curve.
  25161. * @param {number} [xRadius=1] - The radius of the ellipse in the x axis.
  25162. * @param {number} [yRadius=1] - The radius of the ellipse in the y axis.
  25163. * @param {number} [aStartAngle=0] - The start angle in radians.
  25164. * @param {number} [aEndAngle=Math.PI*2] - The end angle in radians.
  25165. * @param {boolean} [aClockwise=false] - Whether to sweep the ellipse clockwise or not.
  25166. * @param {number} [aRotation=0] - The rotation angle of the ellipse in radians, counterclockwise from the positive X axis.
  25167. * @return {Path} A reference to this path.
  25168. */
  25169. ellipse( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  25170. const x0 = this.currentPoint.x;
  25171. const y0 = this.currentPoint.y;
  25172. this.absellipse( aX + x0, aY + y0, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation );
  25173. return this;
  25174. }
  25175. /**
  25176. * Adds an absolutely positioned ellipse as an instance of {@link EllipseCurve} to the path.
  25177. *
  25178. * @param {number} [aX=0] - The x coordinate of the absolute center of the ellipse.
  25179. * @param {number} [aY=0] - The y coordinate of the absolute center of the ellipse.
  25180. * @param {number} [xRadius=1] - The radius of the ellipse in the x axis.
  25181. * @param {number} [yRadius=1] - The radius of the ellipse in the y axis.
  25182. * @param {number} [aStartAngle=0] - The start angle in radians.
  25183. * @param {number} [aEndAngle=Math.PI*2] - The end angle in radians.
  25184. * @param {boolean} [aClockwise=false] - Whether to sweep the ellipse clockwise or not.
  25185. * @param {number} [aRotation=0] - The rotation angle of the ellipse in radians, counterclockwise from the positive X axis.
  25186. * @return {Path} A reference to this path.
  25187. */
  25188. absellipse( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  25189. const curve = new EllipseCurve( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation );
  25190. if ( this.curves.length > 0 ) {
  25191. // if a previous curve is present, attempt to join
  25192. const firstPoint = curve.getPoint( 0 );
  25193. if ( ! firstPoint.equals( this.currentPoint ) ) {
  25194. this.lineTo( firstPoint.x, firstPoint.y );
  25195. }
  25196. }
  25197. this.curves.push( curve );
  25198. const lastPoint = curve.getPoint( 1 );
  25199. this.currentPoint.copy( lastPoint );
  25200. return this;
  25201. }
  25202. copy( source ) {
  25203. super.copy( source );
  25204. this.currentPoint.copy( source.currentPoint );
  25205. return this;
  25206. }
  25207. toJSON() {
  25208. const data = super.toJSON();
  25209. data.currentPoint = this.currentPoint.toArray();
  25210. return data;
  25211. }
  25212. fromJSON( json ) {
  25213. super.fromJSON( json );
  25214. this.currentPoint.fromArray( json.currentPoint );
  25215. return this;
  25216. }
  25217. }
  25218. /**
  25219. * Defines an arbitrary 2d shape plane using paths with optional holes. It
  25220. * can be used with {@link ExtrudeGeometry}, {@link ShapeGeometry}, to get
  25221. * points, or to get triangulated faces.
  25222. *
  25223. * ```js
  25224. * const heartShape = new THREE.Shape();
  25225. *
  25226. * heartShape.moveTo( 25, 25 );
  25227. * heartShape.bezierCurveTo( 25, 25, 20, 0, 0, 0 );
  25228. * heartShape.bezierCurveTo( - 30, 0, - 30, 35, - 30, 35 );
  25229. * heartShape.bezierCurveTo( - 30, 55, - 10, 77, 25, 95 );
  25230. * heartShape.bezierCurveTo( 60, 77, 80, 55, 80, 35 );
  25231. * heartShape.bezierCurveTo( 80, 35, 80, 0, 50, 0 );
  25232. * heartShape.bezierCurveTo( 35, 0, 25, 25, 25, 25 );
  25233. *
  25234. * const extrudeSettings = {
  25235. * depth: 8,
  25236. * bevelEnabled: true,
  25237. * bevelSegments: 2,
  25238. * steps: 2,
  25239. * bevelSize: 1,
  25240. * bevelThickness: 1
  25241. * };
  25242. *
  25243. * const geometry = new THREE.ExtrudeGeometry( heartShape, extrudeSettings );
  25244. * const mesh = new THREE.Mesh( geometry, new THREE.MeshBasicMaterial() );
  25245. * ```
  25246. *
  25247. * @augments Path
  25248. */
  25249. class Shape extends Path {
  25250. /**
  25251. * Constructs a new shape.
  25252. *
  25253. * @param {Array<Vector2>} [points] - An array of 2D points defining the shape.
  25254. */
  25255. constructor( points ) {
  25256. super( points );
  25257. /**
  25258. * The UUID of the shape.
  25259. *
  25260. * @type {string}
  25261. * @readonly
  25262. */
  25263. this.uuid = generateUUID();
  25264. this.type = 'Shape';
  25265. /**
  25266. * Defines the holes in the shape. Hole definitions must use the
  25267. * opposite winding order (CW/CCW) than the outer shape.
  25268. *
  25269. * @type {Array<Path>}
  25270. * @readonly
  25271. */
  25272. this.holes = [];
  25273. }
  25274. /**
  25275. * Returns an array representing each contour of the holes
  25276. * as a list of 2D points.
  25277. *
  25278. * @param {number} divisions - The fineness of the result.
  25279. * @return {Array<Array<Vector2>>} The holes as a series of 2D points.
  25280. */
  25281. getPointsHoles( divisions ) {
  25282. const holesPts = [];
  25283. for ( let i = 0, l = this.holes.length; i < l; i ++ ) {
  25284. holesPts[ i ] = this.holes[ i ].getPoints( divisions );
  25285. }
  25286. return holesPts;
  25287. }
  25288. // get points of shape and holes (keypoints based on segments parameter)
  25289. /**
  25290. * Returns an object that holds contour data for the shape and its holes as
  25291. * arrays of 2D points.
  25292. *
  25293. * @param {number} divisions - The fineness of the result.
  25294. * @return {{shape:Array<Vector2>,holes:Array<Array<Vector2>>}} An object with contour data.
  25295. */
  25296. extractPoints( divisions ) {
  25297. return {
  25298. shape: this.getPoints( divisions ),
  25299. holes: this.getPointsHoles( divisions )
  25300. };
  25301. }
  25302. copy( source ) {
  25303. super.copy( source );
  25304. this.holes = [];
  25305. for ( let i = 0, l = source.holes.length; i < l; i ++ ) {
  25306. const hole = source.holes[ i ];
  25307. this.holes.push( hole.clone() );
  25308. }
  25309. return this;
  25310. }
  25311. toJSON() {
  25312. const data = super.toJSON();
  25313. data.uuid = this.uuid;
  25314. data.holes = [];
  25315. for ( let i = 0, l = this.holes.length; i < l; i ++ ) {
  25316. const hole = this.holes[ i ];
  25317. data.holes.push( hole.toJSON() );
  25318. }
  25319. return data;
  25320. }
  25321. fromJSON( json ) {
  25322. super.fromJSON( json );
  25323. this.uuid = json.uuid;
  25324. this.holes = [];
  25325. for ( let i = 0, l = json.holes.length; i < l; i ++ ) {
  25326. const hole = json.holes[ i ];
  25327. this.holes.push( new Path().fromJSON( hole ) );
  25328. }
  25329. return this;
  25330. }
  25331. }
  25332. /* eslint-disable */
  25333. // copy of mapbox/earcut version 3.0.2
  25334. // https://github.com/mapbox/earcut/tree/v3.0.2
  25335. function earcut(data, holeIndices, dim = 2) {
  25336. const hasHoles = holeIndices && holeIndices.length;
  25337. const outerLen = hasHoles ? holeIndices[0] * dim : data.length;
  25338. let outerNode = linkedList(data, 0, outerLen, dim, true);
  25339. const triangles = [];
  25340. if (!outerNode || outerNode.next === outerNode.prev) return triangles;
  25341. let minX, minY, invSize;
  25342. if (hasHoles) outerNode = eliminateHoles(data, holeIndices, outerNode, dim);
  25343. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  25344. if (data.length > 80 * dim) {
  25345. minX = data[0];
  25346. minY = data[1];
  25347. let maxX = minX;
  25348. let maxY = minY;
  25349. for (let i = dim; i < outerLen; i += dim) {
  25350. const x = data[i];
  25351. const y = data[i + 1];
  25352. if (x < minX) minX = x;
  25353. if (y < minY) minY = y;
  25354. if (x > maxX) maxX = x;
  25355. if (y > maxY) maxY = y;
  25356. }
  25357. // minX, minY and invSize are later used to transform coords into integers for z-order calculation
  25358. invSize = Math.max(maxX - minX, maxY - minY);
  25359. invSize = invSize !== 0 ? 32767 / invSize : 0;
  25360. }
  25361. earcutLinked(outerNode, triangles, dim, minX, minY, invSize, 0);
  25362. return triangles;
  25363. }
  25364. // create a circular doubly linked list from polygon points in the specified winding order
  25365. function linkedList(data, start, end, dim, clockwise) {
  25366. let last;
  25367. if (clockwise === (signedArea(data, start, end, dim) > 0)) {
  25368. for (let i = start; i < end; i += dim) last = insertNode(i / dim | 0, data[i], data[i + 1], last);
  25369. } else {
  25370. for (let i = end - dim; i >= start; i -= dim) last = insertNode(i / dim | 0, data[i], data[i + 1], last);
  25371. }
  25372. if (last && equals(last, last.next)) {
  25373. removeNode(last);
  25374. last = last.next;
  25375. }
  25376. return last;
  25377. }
  25378. // eliminate colinear or duplicate points
  25379. function filterPoints(start, end) {
  25380. if (!start) return start;
  25381. if (!end) end = start;
  25382. let p = start,
  25383. again;
  25384. do {
  25385. again = false;
  25386. if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
  25387. removeNode(p);
  25388. p = end = p.prev;
  25389. if (p === p.next) break;
  25390. again = true;
  25391. } else {
  25392. p = p.next;
  25393. }
  25394. } while (again || p !== end);
  25395. return end;
  25396. }
  25397. // main ear slicing loop which triangulates a polygon (given as a linked list)
  25398. function earcutLinked(ear, triangles, dim, minX, minY, invSize, pass) {
  25399. if (!ear) return;
  25400. // interlink polygon nodes in z-order
  25401. if (!pass && invSize) indexCurve(ear, minX, minY, invSize);
  25402. let stop = ear;
  25403. // iterate through ears, slicing them one by one
  25404. while (ear.prev !== ear.next) {
  25405. const prev = ear.prev;
  25406. const next = ear.next;
  25407. if (invSize ? isEarHashed(ear, minX, minY, invSize) : isEar(ear)) {
  25408. triangles.push(prev.i, ear.i, next.i); // cut off the triangle
  25409. removeNode(ear);
  25410. // skipping the next vertex leads to less sliver triangles
  25411. ear = next.next;
  25412. stop = next.next;
  25413. continue;
  25414. }
  25415. ear = next;
  25416. // if we looped through the whole remaining polygon and can't find any more ears
  25417. if (ear === stop) {
  25418. // try filtering points and slicing again
  25419. if (!pass) {
  25420. earcutLinked(filterPoints(ear), triangles, dim, minX, minY, invSize, 1);
  25421. // if this didn't work, try curing all small self-intersections locally
  25422. } else if (pass === 1) {
  25423. ear = cureLocalIntersections(filterPoints(ear), triangles);
  25424. earcutLinked(ear, triangles, dim, minX, minY, invSize, 2);
  25425. // as a last resort, try splitting the remaining polygon into two
  25426. } else if (pass === 2) {
  25427. splitEarcut(ear, triangles, dim, minX, minY, invSize);
  25428. }
  25429. break;
  25430. }
  25431. }
  25432. }
  25433. // check whether a polygon node forms a valid ear with adjacent nodes
  25434. function isEar(ear) {
  25435. const a = ear.prev,
  25436. b = ear,
  25437. c = ear.next;
  25438. if (area(a, b, c) >= 0) return false; // reflex, can't be an ear
  25439. // now make sure we don't have other points inside the potential ear
  25440. const ax = a.x, bx = b.x, cx = c.x, ay = a.y, by = b.y, cy = c.y;
  25441. // triangle bbox
  25442. const x0 = Math.min(ax, bx, cx),
  25443. y0 = Math.min(ay, by, cy),
  25444. x1 = Math.max(ax, bx, cx),
  25445. y1 = Math.max(ay, by, cy);
  25446. let p = c.next;
  25447. while (p !== a) {
  25448. if (p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 &&
  25449. pointInTriangleExceptFirst(ax, ay, bx, by, cx, cy, p.x, p.y) &&
  25450. area(p.prev, p, p.next) >= 0) return false;
  25451. p = p.next;
  25452. }
  25453. return true;
  25454. }
  25455. function isEarHashed(ear, minX, minY, invSize) {
  25456. const a = ear.prev,
  25457. b = ear,
  25458. c = ear.next;
  25459. if (area(a, b, c) >= 0) return false; // reflex, can't be an ear
  25460. const ax = a.x, bx = b.x, cx = c.x, ay = a.y, by = b.y, cy = c.y;
  25461. // triangle bbox
  25462. const x0 = Math.min(ax, bx, cx),
  25463. y0 = Math.min(ay, by, cy),
  25464. x1 = Math.max(ax, bx, cx),
  25465. y1 = Math.max(ay, by, cy);
  25466. // z-order range for the current triangle bbox;
  25467. const minZ = zOrder(x0, y0, minX, minY, invSize),
  25468. maxZ = zOrder(x1, y1, minX, minY, invSize);
  25469. let p = ear.prevZ,
  25470. n = ear.nextZ;
  25471. // look for points inside the triangle in both directions
  25472. while (p && p.z >= minZ && n && n.z <= maxZ) {
  25473. if (p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 && p !== a && p !== c &&
  25474. pointInTriangleExceptFirst(ax, ay, bx, by, cx, cy, p.x, p.y) && area(p.prev, p, p.next) >= 0) return false;
  25475. p = p.prevZ;
  25476. if (n.x >= x0 && n.x <= x1 && n.y >= y0 && n.y <= y1 && n !== a && n !== c &&
  25477. pointInTriangleExceptFirst(ax, ay, bx, by, cx, cy, n.x, n.y) && area(n.prev, n, n.next) >= 0) return false;
  25478. n = n.nextZ;
  25479. }
  25480. // look for remaining points in decreasing z-order
  25481. while (p && p.z >= minZ) {
  25482. if (p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 && p !== a && p !== c &&
  25483. pointInTriangleExceptFirst(ax, ay, bx, by, cx, cy, p.x, p.y) && area(p.prev, p, p.next) >= 0) return false;
  25484. p = p.prevZ;
  25485. }
  25486. // look for remaining points in increasing z-order
  25487. while (n && n.z <= maxZ) {
  25488. if (n.x >= x0 && n.x <= x1 && n.y >= y0 && n.y <= y1 && n !== a && n !== c &&
  25489. pointInTriangleExceptFirst(ax, ay, bx, by, cx, cy, n.x, n.y) && area(n.prev, n, n.next) >= 0) return false;
  25490. n = n.nextZ;
  25491. }
  25492. return true;
  25493. }
  25494. // go through all polygon nodes and cure small local self-intersections
  25495. function cureLocalIntersections(start, triangles) {
  25496. let p = start;
  25497. do {
  25498. const a = p.prev,
  25499. b = p.next.next;
  25500. if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
  25501. triangles.push(a.i, p.i, b.i);
  25502. // remove two nodes involved
  25503. removeNode(p);
  25504. removeNode(p.next);
  25505. p = start = b;
  25506. }
  25507. p = p.next;
  25508. } while (p !== start);
  25509. return filterPoints(p);
  25510. }
  25511. // try splitting polygon into two and triangulate them independently
  25512. function splitEarcut(start, triangles, dim, minX, minY, invSize) {
  25513. // look for a valid diagonal that divides the polygon into two
  25514. let a = start;
  25515. do {
  25516. let b = a.next.next;
  25517. while (b !== a.prev) {
  25518. if (a.i !== b.i && isValidDiagonal(a, b)) {
  25519. // split the polygon in two by the diagonal
  25520. let c = splitPolygon(a, b);
  25521. // filter colinear points around the cuts
  25522. a = filterPoints(a, a.next);
  25523. c = filterPoints(c, c.next);
  25524. // run earcut on each half
  25525. earcutLinked(a, triangles, dim, minX, minY, invSize, 0);
  25526. earcutLinked(c, triangles, dim, minX, minY, invSize, 0);
  25527. return;
  25528. }
  25529. b = b.next;
  25530. }
  25531. a = a.next;
  25532. } while (a !== start);
  25533. }
  25534. // link every hole into the outer loop, producing a single-ring polygon without holes
  25535. function eliminateHoles(data, holeIndices, outerNode, dim) {
  25536. const queue = [];
  25537. for (let i = 0, len = holeIndices.length; i < len; i++) {
  25538. const start = holeIndices[i] * dim;
  25539. const end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  25540. const list = linkedList(data, start, end, dim, false);
  25541. if (list === list.next) list.steiner = true;
  25542. queue.push(getLeftmost(list));
  25543. }
  25544. queue.sort(compareXYSlope);
  25545. // process holes from left to right
  25546. for (let i = 0; i < queue.length; i++) {
  25547. outerNode = eliminateHole(queue[i], outerNode);
  25548. }
  25549. return outerNode;
  25550. }
  25551. function compareXYSlope(a, b) {
  25552. let result = a.x - b.x;
  25553. // when the left-most point of 2 holes meet at a vertex, sort the holes counterclockwise so that when we find
  25554. // the bridge to the outer shell is always the point that they meet at.
  25555. if (result === 0) {
  25556. result = a.y - b.y;
  25557. if (result === 0) {
  25558. const aSlope = (a.next.y - a.y) / (a.next.x - a.x);
  25559. const bSlope = (b.next.y - b.y) / (b.next.x - b.x);
  25560. result = aSlope - bSlope;
  25561. }
  25562. }
  25563. return result;
  25564. }
  25565. // find a bridge between vertices that connects hole with an outer ring and link it
  25566. function eliminateHole(hole, outerNode) {
  25567. const bridge = findHoleBridge(hole, outerNode);
  25568. if (!bridge) {
  25569. return outerNode;
  25570. }
  25571. const bridgeReverse = splitPolygon(bridge, hole);
  25572. // filter collinear points around the cuts
  25573. filterPoints(bridgeReverse, bridgeReverse.next);
  25574. return filterPoints(bridge, bridge.next);
  25575. }
  25576. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  25577. function findHoleBridge(hole, outerNode) {
  25578. let p = outerNode;
  25579. const hx = hole.x;
  25580. const hy = hole.y;
  25581. let qx = -Infinity;
  25582. let m;
  25583. // find a segment intersected by a ray from the hole's leftmost point to the left;
  25584. // segment's endpoint with lesser x will be potential connection point
  25585. // unless they intersect at a vertex, then choose the vertex
  25586. if (equals(hole, p)) return p;
  25587. do {
  25588. if (equals(hole, p.next)) return p.next;
  25589. else if (hy <= p.y && hy >= p.next.y && p.next.y !== p.y) {
  25590. const x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
  25591. if (x <= hx && x > qx) {
  25592. qx = x;
  25593. m = p.x < p.next.x ? p : p.next;
  25594. if (x === hx) return m; // hole touches outer segment; pick leftmost endpoint
  25595. }
  25596. }
  25597. p = p.next;
  25598. } while (p !== outerNode);
  25599. if (!m) return null;
  25600. // look for points inside the triangle of hole point, segment intersection and endpoint;
  25601. // if there are no points found, we have a valid connection;
  25602. // otherwise choose the point of the minimum angle with the ray as connection point
  25603. const stop = m;
  25604. const mx = m.x;
  25605. const my = m.y;
  25606. let tanMin = Infinity;
  25607. p = m;
  25608. do {
  25609. if (hx >= p.x && p.x >= mx && hx !== p.x &&
  25610. pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {
  25611. const tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
  25612. if (locallyInside(p, hole) &&
  25613. (tan < tanMin || (tan === tanMin && (p.x > m.x || (p.x === m.x && sectorContainsSector(m, p)))))) {
  25614. m = p;
  25615. tanMin = tan;
  25616. }
  25617. }
  25618. p = p.next;
  25619. } while (p !== stop);
  25620. return m;
  25621. }
  25622. // whether sector in vertex m contains sector in vertex p in the same coordinates
  25623. function sectorContainsSector(m, p) {
  25624. return area(m.prev, m, p.prev) < 0 && area(p.next, m, m.next) < 0;
  25625. }
  25626. // interlink polygon nodes in z-order
  25627. function indexCurve(start, minX, minY, invSize) {
  25628. let p = start;
  25629. do {
  25630. if (p.z === 0) p.z = zOrder(p.x, p.y, minX, minY, invSize);
  25631. p.prevZ = p.prev;
  25632. p.nextZ = p.next;
  25633. p = p.next;
  25634. } while (p !== start);
  25635. p.prevZ.nextZ = null;
  25636. p.prevZ = null;
  25637. sortLinked(p);
  25638. }
  25639. // Simon Tatham's linked list merge sort algorithm
  25640. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  25641. function sortLinked(list) {
  25642. let numMerges;
  25643. let inSize = 1;
  25644. do {
  25645. let p = list;
  25646. let e;
  25647. list = null;
  25648. let tail = null;
  25649. numMerges = 0;
  25650. while (p) {
  25651. numMerges++;
  25652. let q = p;
  25653. let pSize = 0;
  25654. for (let i = 0; i < inSize; i++) {
  25655. pSize++;
  25656. q = q.nextZ;
  25657. if (!q) break;
  25658. }
  25659. let qSize = inSize;
  25660. while (pSize > 0 || (qSize > 0 && q)) {
  25661. if (pSize !== 0 && (qSize === 0 || !q || p.z <= q.z)) {
  25662. e = p;
  25663. p = p.nextZ;
  25664. pSize--;
  25665. } else {
  25666. e = q;
  25667. q = q.nextZ;
  25668. qSize--;
  25669. }
  25670. if (tail) tail.nextZ = e;
  25671. else list = e;
  25672. e.prevZ = tail;
  25673. tail = e;
  25674. }
  25675. p = q;
  25676. }
  25677. tail.nextZ = null;
  25678. inSize *= 2;
  25679. } while (numMerges > 1);
  25680. return list;
  25681. }
  25682. // z-order of a point given coords and inverse of the longer side of data bbox
  25683. function zOrder(x, y, minX, minY, invSize) {
  25684. // coords are transformed into non-negative 15-bit integer range
  25685. x = (x - minX) * invSize | 0;
  25686. y = (y - minY) * invSize | 0;
  25687. x = (x | (x << 8)) & 0x00FF00FF;
  25688. x = (x | (x << 4)) & 0x0F0F0F0F;
  25689. x = (x | (x << 2)) & 0x33333333;
  25690. x = (x | (x << 1)) & 0x55555555;
  25691. y = (y | (y << 8)) & 0x00FF00FF;
  25692. y = (y | (y << 4)) & 0x0F0F0F0F;
  25693. y = (y | (y << 2)) & 0x33333333;
  25694. y = (y | (y << 1)) & 0x55555555;
  25695. return x | (y << 1);
  25696. }
  25697. // find the leftmost node of a polygon ring
  25698. function getLeftmost(start) {
  25699. let p = start,
  25700. leftmost = start;
  25701. do {
  25702. if (p.x < leftmost.x || (p.x === leftmost.x && p.y < leftmost.y)) leftmost = p;
  25703. p = p.next;
  25704. } while (p !== start);
  25705. return leftmost;
  25706. }
  25707. // check if a point lies within a convex triangle
  25708. function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
  25709. return (cx - px) * (ay - py) >= (ax - px) * (cy - py) &&
  25710. (ax - px) * (by - py) >= (bx - px) * (ay - py) &&
  25711. (bx - px) * (cy - py) >= (cx - px) * (by - py);
  25712. }
  25713. // check if a point lies within a convex triangle but false if its equal to the first point of the triangle
  25714. function pointInTriangleExceptFirst(ax, ay, bx, by, cx, cy, px, py) {
  25715. return !(ax === px && ay === py) && pointInTriangle(ax, ay, bx, by, cx, cy, px, py);
  25716. }
  25717. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  25718. function isValidDiagonal(a, b) {
  25719. return a.next.i !== b.i && a.prev.i !== b.i && !intersectsPolygon(a, b) && // doesn't intersect other edges
  25720. (locallyInside(a, b) && locallyInside(b, a) && middleInside(a, b) && // locally visible
  25721. (area(a.prev, a, b.prev) || area(a, b.prev, b)) || // does not create opposite-facing sectors
  25722. equals(a, b) && area(a.prev, a, a.next) > 0 && area(b.prev, b, b.next) > 0); // special zero-length case
  25723. }
  25724. // signed area of a triangle
  25725. function area(p, q, r) {
  25726. return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
  25727. }
  25728. // check if two points are equal
  25729. function equals(p1, p2) {
  25730. return p1.x === p2.x && p1.y === p2.y;
  25731. }
  25732. // check if two segments intersect
  25733. function intersects(p1, q1, p2, q2) {
  25734. const o1 = sign(area(p1, q1, p2));
  25735. const o2 = sign(area(p1, q1, q2));
  25736. const o3 = sign(area(p2, q2, p1));
  25737. const o4 = sign(area(p2, q2, q1));
  25738. if (o1 !== o2 && o3 !== o4) return true; // general case
  25739. if (o1 === 0 && onSegment(p1, p2, q1)) return true; // p1, q1 and p2 are collinear and p2 lies on p1q1
  25740. if (o2 === 0 && onSegment(p1, q2, q1)) return true; // p1, q1 and q2 are collinear and q2 lies on p1q1
  25741. if (o3 === 0 && onSegment(p2, p1, q2)) return true; // p2, q2 and p1 are collinear and p1 lies on p2q2
  25742. if (o4 === 0 && onSegment(p2, q1, q2)) return true; // p2, q2 and q1 are collinear and q1 lies on p2q2
  25743. return false;
  25744. }
  25745. // for collinear points p, q, r, check if point q lies on segment pr
  25746. function onSegment(p, q, r) {
  25747. 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);
  25748. }
  25749. function sign(num) {
  25750. return num > 0 ? 1 : num < 0 ? -1 : 0;
  25751. }
  25752. // check if a polygon diagonal intersects any polygon segments
  25753. function intersectsPolygon(a, b) {
  25754. let p = a;
  25755. do {
  25756. if (p.i !== a.i && p.next.i !== a.i && p.i !== b.i && p.next.i !== b.i &&
  25757. intersects(p, p.next, a, b)) return true;
  25758. p = p.next;
  25759. } while (p !== a);
  25760. return false;
  25761. }
  25762. // check if a polygon diagonal is locally inside the polygon
  25763. function locallyInside(a, b) {
  25764. return area(a.prev, a, a.next) < 0 ?
  25765. area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0 :
  25766. area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;
  25767. }
  25768. // check if the middle point of a polygon diagonal is inside the polygon
  25769. function middleInside(a, b) {
  25770. let p = a;
  25771. let inside = false;
  25772. const px = (a.x + b.x) / 2;
  25773. const py = (a.y + b.y) / 2;
  25774. do {
  25775. if (((p.y > py) !== (p.next.y > py)) && p.next.y !== p.y &&
  25776. (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x))
  25777. inside = !inside;
  25778. p = p.next;
  25779. } while (p !== a);
  25780. return inside;
  25781. }
  25782. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  25783. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  25784. function splitPolygon(a, b) {
  25785. const a2 = createNode(a.i, a.x, a.y),
  25786. b2 = createNode(b.i, b.x, b.y),
  25787. an = a.next,
  25788. bp = b.prev;
  25789. a.next = b;
  25790. b.prev = a;
  25791. a2.next = an;
  25792. an.prev = a2;
  25793. b2.next = a2;
  25794. a2.prev = b2;
  25795. bp.next = b2;
  25796. b2.prev = bp;
  25797. return b2;
  25798. }
  25799. // create a node and optionally link it with previous one (in a circular doubly linked list)
  25800. function insertNode(i, x, y, last) {
  25801. const p = createNode(i, x, y);
  25802. if (!last) {
  25803. p.prev = p;
  25804. p.next = p;
  25805. } else {
  25806. p.next = last.next;
  25807. p.prev = last;
  25808. last.next.prev = p;
  25809. last.next = p;
  25810. }
  25811. return p;
  25812. }
  25813. function removeNode(p) {
  25814. p.next.prev = p.prev;
  25815. p.prev.next = p.next;
  25816. if (p.prevZ) p.prevZ.nextZ = p.nextZ;
  25817. if (p.nextZ) p.nextZ.prevZ = p.prevZ;
  25818. }
  25819. function createNode(i, x, y) {
  25820. return {
  25821. i, // vertex index in coordinates array
  25822. x, y, // vertex coordinates
  25823. prev: null, // previous and next vertex nodes in a polygon ring
  25824. next: null,
  25825. z: 0, // z-order curve value
  25826. prevZ: null, // previous and next nodes in z-order
  25827. nextZ: null,
  25828. steiner: false // indicates whether this is a steiner point
  25829. };
  25830. }
  25831. function signedArea(data, start, end, dim) {
  25832. let sum = 0;
  25833. for (let i = start, j = end - dim; i < end; i += dim) {
  25834. sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
  25835. j = i;
  25836. }
  25837. return sum;
  25838. }
  25839. /**
  25840. * An implementation of the earcut polygon triangulation algorithm.
  25841. * The code is a port of [mapbox/earcut](https://github.com/mapbox/earcut).
  25842. *
  25843. * @see https://github.com/mapbox/earcut
  25844. */
  25845. class Earcut {
  25846. /**
  25847. * Triangulates the given shape definition by returning an array of triangles.
  25848. *
  25849. * @param {Array<number>} data - An array with 2D points.
  25850. * @param {Array<number>} holeIndices - An array with indices defining holes.
  25851. * @param {number} [dim=2] - The number of coordinates per vertex in the input array.
  25852. * @return {Array<number>} An array representing the triangulated faces. Each face is defined by three consecutive numbers
  25853. * representing vertex indices.
  25854. */
  25855. static triangulate( data, holeIndices, dim = 2 ) {
  25856. return earcut( data, holeIndices, dim );
  25857. }
  25858. }
  25859. /**
  25860. * A class containing utility functions for shapes.
  25861. *
  25862. * @hideconstructor
  25863. */
  25864. class ShapeUtils {
  25865. /**
  25866. * Calculate area of a ( 2D ) contour polygon.
  25867. *
  25868. * @param {Array<Vector2>} contour - An array of 2D points.
  25869. * @return {number} The area.
  25870. */
  25871. static area( contour ) {
  25872. const n = contour.length;
  25873. let a = 0.0;
  25874. for ( let p = n - 1, q = 0; q < n; p = q ++ ) {
  25875. a += contour[ p ].x * contour[ q ].y - contour[ q ].x * contour[ p ].y;
  25876. }
  25877. return a * 0.5;
  25878. }
  25879. /**
  25880. * Returns `true` if the given contour uses a clockwise winding order.
  25881. *
  25882. * @param {Array<Vector2>} pts - An array of 2D points defining a polygon.
  25883. * @return {boolean} Whether the given contour uses a clockwise winding order or not.
  25884. */
  25885. static isClockWise( pts ) {
  25886. return ShapeUtils.area( pts ) < 0;
  25887. }
  25888. /**
  25889. * Triangulates the given shape definition.
  25890. *
  25891. * @param {Array<Vector2>} contour - An array of 2D points defining the contour.
  25892. * @param {Array<Array<Vector2>>} holes - An array that holds arrays of 2D points defining the holes.
  25893. * @return {Array<Array<number>>} An array that holds for each face definition an array with three indices.
  25894. */
  25895. static triangulateShape( contour, holes ) {
  25896. const vertices = []; // flat array of vertices like [ x0,y0, x1,y1, x2,y2, ... ]
  25897. const holeIndices = []; // array of hole indices
  25898. const faces = []; // final array of vertex indices like [ [ a,b,d ], [ b,c,d ] ]
  25899. removeDupEndPts( contour );
  25900. addContour( vertices, contour );
  25901. //
  25902. let holeIndex = contour.length;
  25903. holes.forEach( removeDupEndPts );
  25904. for ( let i = 0; i < holes.length; i ++ ) {
  25905. holeIndices.push( holeIndex );
  25906. holeIndex += holes[ i ].length;
  25907. addContour( vertices, holes[ i ] );
  25908. }
  25909. //
  25910. const triangles = Earcut.triangulate( vertices, holeIndices );
  25911. //
  25912. for ( let i = 0; i < triangles.length; i += 3 ) {
  25913. faces.push( triangles.slice( i, i + 3 ) );
  25914. }
  25915. return faces;
  25916. }
  25917. }
  25918. function removeDupEndPts( points ) {
  25919. const l = points.length;
  25920. if ( l > 2 && points[ l - 1 ].equals( points[ 0 ] ) ) {
  25921. points.pop();
  25922. }
  25923. }
  25924. function addContour( vertices, contour ) {
  25925. for ( let i = 0; i < contour.length; i ++ ) {
  25926. vertices.push( contour[ i ].x );
  25927. vertices.push( contour[ i ].y );
  25928. }
  25929. }
  25930. /**
  25931. * Creates extruded geometry from a path shape.
  25932. *
  25933. * ```js
  25934. * const length = 12, width = 8;
  25935. *
  25936. * const shape = new THREE.Shape();
  25937. * shape.moveTo( 0,0 );
  25938. * shape.lineTo( 0, width );
  25939. * shape.lineTo( length, width );
  25940. * shape.lineTo( length, 0 );
  25941. * shape.lineTo( 0, 0 );
  25942. *
  25943. * const geometry = new THREE.ExtrudeGeometry( shape );
  25944. * const material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } );
  25945. * const mesh = new THREE.Mesh( geometry, material ) ;
  25946. * scene.add( mesh );
  25947. * ```
  25948. *
  25949. * @augments BufferGeometry
  25950. * @demo scenes/geometry-browser.html#ExtrudeGeometry
  25951. */
  25952. class ExtrudeGeometry extends BufferGeometry {
  25953. /**
  25954. * Constructs a new extrude geometry.
  25955. *
  25956. * @param {Shape|Array<Shape>} [shapes] - A shape or an array of shapes.
  25957. * @param {ExtrudeGeometry~Options} [options] - The extrude settings.
  25958. */
  25959. 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 = {} ) {
  25960. super();
  25961. this.type = 'ExtrudeGeometry';
  25962. /**
  25963. * Holds the constructor parameters that have been
  25964. * used to generate the geometry. Any modification
  25965. * after instantiation does not change the geometry.
  25966. *
  25967. * @type {Object}
  25968. */
  25969. this.parameters = {
  25970. shapes: shapes,
  25971. options: options
  25972. };
  25973. shapes = Array.isArray( shapes ) ? shapes : [ shapes ];
  25974. const scope = this;
  25975. const verticesArray = [];
  25976. const uvArray = [];
  25977. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  25978. const shape = shapes[ i ];
  25979. addShape( shape );
  25980. }
  25981. // build geometry
  25982. this.setAttribute( 'position', new Float32BufferAttribute( verticesArray, 3 ) );
  25983. this.setAttribute( 'uv', new Float32BufferAttribute( uvArray, 2 ) );
  25984. this.computeVertexNormals();
  25985. // functions
  25986. function addShape( shape ) {
  25987. const placeholder = [];
  25988. // options
  25989. const curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  25990. const steps = options.steps !== undefined ? options.steps : 1;
  25991. const depth = options.depth !== undefined ? options.depth : 1;
  25992. let bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true;
  25993. let bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 0.2;
  25994. let bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 0.1;
  25995. let bevelOffset = options.bevelOffset !== undefined ? options.bevelOffset : 0;
  25996. let bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3;
  25997. const extrudePath = options.extrudePath;
  25998. const uvgen = options.UVGenerator !== undefined ? options.UVGenerator : WorldUVGenerator;
  25999. //
  26000. let extrudePts, extrudeByPath = false;
  26001. let splineTube, binormal, normal, position2;
  26002. if ( extrudePath ) {
  26003. extrudePts = extrudePath.getSpacedPoints( steps );
  26004. extrudeByPath = true;
  26005. bevelEnabled = false; // bevels not supported for path extrusion
  26006. // SETUP TNB variables
  26007. const isClosed = extrudePath.isCatmullRomCurve3 ? extrudePath.closed : false;
  26008. splineTube = extrudePath.computeFrenetFrames( steps, isClosed );
  26009. // log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length);
  26010. binormal = new Vector3();
  26011. normal = new Vector3();
  26012. position2 = new Vector3();
  26013. }
  26014. // Safeguards if bevels are not enabled
  26015. if ( ! bevelEnabled ) {
  26016. bevelSegments = 0;
  26017. bevelThickness = 0;
  26018. bevelSize = 0;
  26019. bevelOffset = 0;
  26020. }
  26021. // Variables initialization
  26022. const shapePoints = shape.extractPoints( curveSegments );
  26023. let vertices = shapePoints.shape;
  26024. const holes = shapePoints.holes;
  26025. const reverse = ! ShapeUtils.isClockWise( vertices );
  26026. if ( reverse ) {
  26027. vertices = vertices.reverse();
  26028. // Maybe we should also check if holes are in the opposite direction, just to be safe ...
  26029. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  26030. const ahole = holes[ h ];
  26031. if ( ShapeUtils.isClockWise( ahole ) ) {
  26032. holes[ h ] = ahole.reverse();
  26033. }
  26034. }
  26035. }
  26036. /**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.
  26037. * @param {Array<Vector2>} points
  26038. */
  26039. function mergeOverlappingPoints( points ) {
  26040. const THRESHOLD = 1e-10;
  26041. const THRESHOLD_SQ = THRESHOLD * THRESHOLD;
  26042. let prevPos = points[ 0 ];
  26043. for ( let i = 1; i <= points.length; i ++ ) {
  26044. const currentIndex = i % points.length;
  26045. const currentPos = points[ currentIndex ];
  26046. const dx = currentPos.x - prevPos.x;
  26047. const dy = currentPos.y - prevPos.y;
  26048. const distSq = dx * dx + dy * dy;
  26049. const scalingFactorSqrt = Math.max(
  26050. Math.abs( currentPos.x ),
  26051. Math.abs( currentPos.y ),
  26052. Math.abs( prevPos.x ),
  26053. Math.abs( prevPos.y )
  26054. );
  26055. const thresholdSqScaled = THRESHOLD_SQ * scalingFactorSqrt * scalingFactorSqrt;
  26056. if ( distSq <= thresholdSqScaled ) {
  26057. points.splice( currentIndex, 1 );
  26058. i --;
  26059. continue;
  26060. }
  26061. prevPos = currentPos;
  26062. }
  26063. }
  26064. mergeOverlappingPoints( vertices );
  26065. holes.forEach( mergeOverlappingPoints );
  26066. const numHoles = holes.length;
  26067. /* Vertices */
  26068. const contour = vertices; // vertices has all points but contour has only points of circumference
  26069. for ( let h = 0; h < numHoles; h ++ ) {
  26070. const ahole = holes[ h ];
  26071. vertices = vertices.concat( ahole );
  26072. }
  26073. function scalePt2( pt, vec, size ) {
  26074. if ( ! vec ) error( 'ExtrudeGeometry: vec does not exist' );
  26075. return pt.clone().addScaledVector( vec, size );
  26076. }
  26077. const vlen = vertices.length;
  26078. // Find directions for point movement
  26079. function getBevelVec( inPt, inPrev, inNext ) {
  26080. // computes for inPt the corresponding point inPt' on a new contour
  26081. // shifted by 1 unit (length of normalized vector) to the left
  26082. // if we walk along contour clockwise, this new contour is outside the old one
  26083. //
  26084. // inPt' is the intersection of the two lines parallel to the two
  26085. // adjacent edges of inPt at a distance of 1 unit on the left side.
  26086. let v_trans_x, v_trans_y, shrink_by; // resulting translation vector for inPt
  26087. // good reading for geometry algorithms (here: line-line intersection)
  26088. // http://geomalgorithms.com/a05-_intersect-1.html
  26089. const v_prev_x = inPt.x - inPrev.x,
  26090. v_prev_y = inPt.y - inPrev.y;
  26091. const v_next_x = inNext.x - inPt.x,
  26092. v_next_y = inNext.y - inPt.y;
  26093. const v_prev_lensq = ( v_prev_x * v_prev_x + v_prev_y * v_prev_y );
  26094. // check for collinear edges
  26095. const collinear0 = ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  26096. if ( Math.abs( collinear0 ) > Number.EPSILON ) {
  26097. // not collinear
  26098. // length of vectors for normalizing
  26099. const v_prev_len = Math.sqrt( v_prev_lensq );
  26100. const v_next_len = Math.sqrt( v_next_x * v_next_x + v_next_y * v_next_y );
  26101. // shift adjacent points by unit vectors to the left
  26102. const ptPrevShift_x = ( inPrev.x - v_prev_y / v_prev_len );
  26103. const ptPrevShift_y = ( inPrev.y + v_prev_x / v_prev_len );
  26104. const ptNextShift_x = ( inNext.x - v_next_y / v_next_len );
  26105. const ptNextShift_y = ( inNext.y + v_next_x / v_next_len );
  26106. // scaling factor for v_prev to intersection point
  26107. const sf = ( ( ptNextShift_x - ptPrevShift_x ) * v_next_y -
  26108. ( ptNextShift_y - ptPrevShift_y ) * v_next_x ) /
  26109. ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  26110. // vector from inPt to intersection point
  26111. v_trans_x = ( ptPrevShift_x + v_prev_x * sf - inPt.x );
  26112. v_trans_y = ( ptPrevShift_y + v_prev_y * sf - inPt.y );
  26113. // Don't normalize!, otherwise sharp corners become ugly
  26114. // but prevent crazy spikes
  26115. const v_trans_lensq = ( v_trans_x * v_trans_x + v_trans_y * v_trans_y );
  26116. if ( v_trans_lensq <= 2 ) {
  26117. return new Vector2( v_trans_x, v_trans_y );
  26118. } else {
  26119. shrink_by = Math.sqrt( v_trans_lensq / 2 );
  26120. }
  26121. } else {
  26122. // handle special case of collinear edges
  26123. let direction_eq = false; // assumes: opposite
  26124. if ( v_prev_x > Number.EPSILON ) {
  26125. if ( v_next_x > Number.EPSILON ) {
  26126. direction_eq = true;
  26127. }
  26128. } else {
  26129. if ( v_prev_x < - Number.EPSILON ) {
  26130. if ( v_next_x < - Number.EPSILON ) {
  26131. direction_eq = true;
  26132. }
  26133. } else {
  26134. if ( Math.sign( v_prev_y ) === Math.sign( v_next_y ) ) {
  26135. direction_eq = true;
  26136. }
  26137. }
  26138. }
  26139. if ( direction_eq ) {
  26140. // log("Warning: lines are a straight sequence");
  26141. v_trans_x = - v_prev_y;
  26142. v_trans_y = v_prev_x;
  26143. shrink_by = Math.sqrt( v_prev_lensq );
  26144. } else {
  26145. // log("Warning: lines are a straight spike");
  26146. v_trans_x = v_prev_x;
  26147. v_trans_y = v_prev_y;
  26148. shrink_by = Math.sqrt( v_prev_lensq / 2 );
  26149. }
  26150. }
  26151. return new Vector2( v_trans_x / shrink_by, v_trans_y / shrink_by );
  26152. }
  26153. const contourMovements = [];
  26154. for ( let i = 0, il = contour.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  26155. if ( j === il ) j = 0;
  26156. if ( k === il ) k = 0;
  26157. // (j)---(i)---(k)
  26158. // log('i,j,k', i, j , k)
  26159. contourMovements[ i ] = getBevelVec( contour[ i ], contour[ j ], contour[ k ] );
  26160. }
  26161. const holesMovements = [];
  26162. let oneHoleMovements, verticesMovements = contourMovements.concat();
  26163. for ( let h = 0, hl = numHoles; h < hl; h ++ ) {
  26164. const ahole = holes[ h ];
  26165. oneHoleMovements = [];
  26166. for ( let i = 0, il = ahole.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  26167. if ( j === il ) j = 0;
  26168. if ( k === il ) k = 0;
  26169. // (j)---(i)---(k)
  26170. oneHoleMovements[ i ] = getBevelVec( ahole[ i ], ahole[ j ], ahole[ k ] );
  26171. }
  26172. holesMovements.push( oneHoleMovements );
  26173. verticesMovements = verticesMovements.concat( oneHoleMovements );
  26174. }
  26175. let faces;
  26176. if ( bevelSegments === 0 ) {
  26177. faces = ShapeUtils.triangulateShape( contour, holes );
  26178. } else {
  26179. const contractedContourVertices = [];
  26180. const expandedHoleVertices = [];
  26181. // Loop bevelSegments, 1 for the front, 1 for the back
  26182. for ( let b = 0; b < bevelSegments; b ++ ) {
  26183. //for ( b = bevelSegments; b > 0; b -- ) {
  26184. const t = b / bevelSegments;
  26185. const z = bevelThickness * Math.cos( t * Math.PI / 2 );
  26186. const bs = bevelSize * Math.sin( t * Math.PI / 2 ) + bevelOffset;
  26187. // contract shape
  26188. for ( let i = 0, il = contour.length; i < il; i ++ ) {
  26189. const vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  26190. v( vert.x, vert.y, - z );
  26191. if ( t === 0 ) contractedContourVertices.push( vert );
  26192. }
  26193. // expand holes
  26194. for ( let h = 0, hl = numHoles; h < hl; h ++ ) {
  26195. const ahole = holes[ h ];
  26196. oneHoleMovements = holesMovements[ h ];
  26197. const oneHoleVertices = [];
  26198. for ( let i = 0, il = ahole.length; i < il; i ++ ) {
  26199. const vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  26200. v( vert.x, vert.y, - z );
  26201. if ( t === 0 ) oneHoleVertices.push( vert );
  26202. }
  26203. if ( t === 0 ) expandedHoleVertices.push( oneHoleVertices );
  26204. }
  26205. }
  26206. faces = ShapeUtils.triangulateShape( contractedContourVertices, expandedHoleVertices );
  26207. }
  26208. const flen = faces.length;
  26209. const bs = bevelSize + bevelOffset;
  26210. // Back facing vertices
  26211. for ( let i = 0; i < vlen; i ++ ) {
  26212. const vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  26213. if ( ! extrudeByPath ) {
  26214. v( vert.x, vert.y, 0 );
  26215. } else {
  26216. // v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x );
  26217. normal.copy( splineTube.normals[ 0 ] ).multiplyScalar( vert.x );
  26218. binormal.copy( splineTube.binormals[ 0 ] ).multiplyScalar( vert.y );
  26219. position2.copy( extrudePts[ 0 ] ).add( normal ).add( binormal );
  26220. v( position2.x, position2.y, position2.z );
  26221. }
  26222. }
  26223. // Add stepped vertices...
  26224. // Including front facing vertices
  26225. for ( let s = 1; s <= steps; s ++ ) {
  26226. for ( let i = 0; i < vlen; i ++ ) {
  26227. const vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  26228. if ( ! extrudeByPath ) {
  26229. v( vert.x, vert.y, depth / steps * s );
  26230. } else {
  26231. // v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x );
  26232. normal.copy( splineTube.normals[ s ] ).multiplyScalar( vert.x );
  26233. binormal.copy( splineTube.binormals[ s ] ).multiplyScalar( vert.y );
  26234. position2.copy( extrudePts[ s ] ).add( normal ).add( binormal );
  26235. v( position2.x, position2.y, position2.z );
  26236. }
  26237. }
  26238. }
  26239. // Add bevel segments planes
  26240. //for ( b = 1; b <= bevelSegments; b ++ ) {
  26241. for ( let b = bevelSegments - 1; b >= 0; b -- ) {
  26242. const t = b / bevelSegments;
  26243. const z = bevelThickness * Math.cos( t * Math.PI / 2 );
  26244. const bs = bevelSize * Math.sin( t * Math.PI / 2 ) + bevelOffset;
  26245. // contract shape
  26246. for ( let i = 0, il = contour.length; i < il; i ++ ) {
  26247. const vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  26248. v( vert.x, vert.y, depth + z );
  26249. }
  26250. // expand holes
  26251. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  26252. const ahole = holes[ h ];
  26253. oneHoleMovements = holesMovements[ h ];
  26254. for ( let i = 0, il = ahole.length; i < il; i ++ ) {
  26255. const vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  26256. if ( ! extrudeByPath ) {
  26257. v( vert.x, vert.y, depth + z );
  26258. } else {
  26259. v( vert.x, vert.y + extrudePts[ steps - 1 ].y, extrudePts[ steps - 1 ].x + z );
  26260. }
  26261. }
  26262. }
  26263. }
  26264. /* Faces */
  26265. // Top and bottom faces
  26266. buildLidFaces();
  26267. // Sides faces
  26268. buildSideFaces();
  26269. ///// Internal functions
  26270. function buildLidFaces() {
  26271. const start = verticesArray.length / 3;
  26272. if ( bevelEnabled ) {
  26273. let layer = 0; // steps + 1
  26274. let offset = vlen * layer;
  26275. // Bottom faces
  26276. for ( let i = 0; i < flen; i ++ ) {
  26277. const face = faces[ i ];
  26278. f3( face[ 2 ] + offset, face[ 1 ] + offset, face[ 0 ] + offset );
  26279. }
  26280. layer = steps + bevelSegments * 2;
  26281. offset = vlen * layer;
  26282. // Top faces
  26283. for ( let i = 0; i < flen; i ++ ) {
  26284. const face = faces[ i ];
  26285. f3( face[ 0 ] + offset, face[ 1 ] + offset, face[ 2 ] + offset );
  26286. }
  26287. } else {
  26288. // Bottom faces
  26289. for ( let i = 0; i < flen; i ++ ) {
  26290. const face = faces[ i ];
  26291. f3( face[ 2 ], face[ 1 ], face[ 0 ] );
  26292. }
  26293. // Top faces
  26294. for ( let i = 0; i < flen; i ++ ) {
  26295. const face = faces[ i ];
  26296. f3( face[ 0 ] + vlen * steps, face[ 1 ] + vlen * steps, face[ 2 ] + vlen * steps );
  26297. }
  26298. }
  26299. scope.addGroup( start, verticesArray.length / 3 - start, 0 );
  26300. }
  26301. // Create faces for the z-sides of the shape
  26302. function buildSideFaces() {
  26303. const start = verticesArray.length / 3;
  26304. let layeroffset = 0;
  26305. sidewalls( contour, layeroffset );
  26306. layeroffset += contour.length;
  26307. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  26308. const ahole = holes[ h ];
  26309. sidewalls( ahole, layeroffset );
  26310. //, true
  26311. layeroffset += ahole.length;
  26312. }
  26313. scope.addGroup( start, verticesArray.length / 3 - start, 1 );
  26314. }
  26315. function sidewalls( contour, layeroffset ) {
  26316. let i = contour.length;
  26317. while ( -- i >= 0 ) {
  26318. const j = i;
  26319. let k = i - 1;
  26320. if ( k < 0 ) k = contour.length - 1;
  26321. //log('b', i,j, i-1, k,vertices.length);
  26322. for ( let s = 0, sl = ( steps + bevelSegments * 2 ); s < sl; s ++ ) {
  26323. const slen1 = vlen * s;
  26324. const slen2 = vlen * ( s + 1 );
  26325. const a = layeroffset + j + slen1,
  26326. b = layeroffset + k + slen1,
  26327. c = layeroffset + k + slen2,
  26328. d = layeroffset + j + slen2;
  26329. f4( a, b, c, d );
  26330. }
  26331. }
  26332. }
  26333. function v( x, y, z ) {
  26334. placeholder.push( x );
  26335. placeholder.push( y );
  26336. placeholder.push( z );
  26337. }
  26338. function f3( a, b, c ) {
  26339. addVertex( a );
  26340. addVertex( b );
  26341. addVertex( c );
  26342. const nextIndex = verticesArray.length / 3;
  26343. const uvs = uvgen.generateTopUV( scope, verticesArray, nextIndex - 3, nextIndex - 2, nextIndex - 1 );
  26344. addUV( uvs[ 0 ] );
  26345. addUV( uvs[ 1 ] );
  26346. addUV( uvs[ 2 ] );
  26347. }
  26348. function f4( a, b, c, d ) {
  26349. addVertex( a );
  26350. addVertex( b );
  26351. addVertex( d );
  26352. addVertex( b );
  26353. addVertex( c );
  26354. addVertex( d );
  26355. const nextIndex = verticesArray.length / 3;
  26356. const uvs = uvgen.generateSideWallUV( scope, verticesArray, nextIndex - 6, nextIndex - 3, nextIndex - 2, nextIndex - 1 );
  26357. addUV( uvs[ 0 ] );
  26358. addUV( uvs[ 1 ] );
  26359. addUV( uvs[ 3 ] );
  26360. addUV( uvs[ 1 ] );
  26361. addUV( uvs[ 2 ] );
  26362. addUV( uvs[ 3 ] );
  26363. }
  26364. function addVertex( index ) {
  26365. verticesArray.push( placeholder[ index * 3 + 0 ] );
  26366. verticesArray.push( placeholder[ index * 3 + 1 ] );
  26367. verticesArray.push( placeholder[ index * 3 + 2 ] );
  26368. }
  26369. function addUV( vector2 ) {
  26370. uvArray.push( vector2.x );
  26371. uvArray.push( vector2.y );
  26372. }
  26373. }
  26374. }
  26375. copy( source ) {
  26376. super.copy( source );
  26377. this.parameters = Object.assign( {}, source.parameters );
  26378. return this;
  26379. }
  26380. toJSON() {
  26381. const data = super.toJSON();
  26382. const shapes = this.parameters.shapes;
  26383. const options = this.parameters.options;
  26384. return toJSON$1( shapes, options, data );
  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. * @param {Array<Shape>} shapes - An array of shapes.
  26392. * @return {ExtrudeGeometry} A new instance.
  26393. */
  26394. static fromJSON( data, shapes ) {
  26395. const geometryShapes = [];
  26396. for ( let j = 0, jl = data.shapes.length; j < jl; j ++ ) {
  26397. const shape = shapes[ data.shapes[ j ] ];
  26398. geometryShapes.push( shape );
  26399. }
  26400. const extrudePath = data.options.extrudePath;
  26401. if ( extrudePath !== undefined ) {
  26402. data.options.extrudePath = new Curves[ extrudePath.type ]().fromJSON( extrudePath );
  26403. }
  26404. return new ExtrudeGeometry( geometryShapes, data.options );
  26405. }
  26406. }
  26407. const WorldUVGenerator = {
  26408. generateTopUV: function ( geometry, vertices, indexA, indexB, indexC ) {
  26409. const a_x = vertices[ indexA * 3 ];
  26410. const a_y = vertices[ indexA * 3 + 1 ];
  26411. const b_x = vertices[ indexB * 3 ];
  26412. const b_y = vertices[ indexB * 3 + 1 ];
  26413. const c_x = vertices[ indexC * 3 ];
  26414. const c_y = vertices[ indexC * 3 + 1 ];
  26415. return [
  26416. new Vector2( a_x, a_y ),
  26417. new Vector2( b_x, b_y ),
  26418. new Vector2( c_x, c_y )
  26419. ];
  26420. },
  26421. generateSideWallUV: function ( geometry, vertices, indexA, indexB, indexC, indexD ) {
  26422. const a_x = vertices[ indexA * 3 ];
  26423. const a_y = vertices[ indexA * 3 + 1 ];
  26424. const a_z = vertices[ indexA * 3 + 2 ];
  26425. const b_x = vertices[ indexB * 3 ];
  26426. const b_y = vertices[ indexB * 3 + 1 ];
  26427. const b_z = vertices[ indexB * 3 + 2 ];
  26428. const c_x = vertices[ indexC * 3 ];
  26429. const c_y = vertices[ indexC * 3 + 1 ];
  26430. const c_z = vertices[ indexC * 3 + 2 ];
  26431. const d_x = vertices[ indexD * 3 ];
  26432. const d_y = vertices[ indexD * 3 + 1 ];
  26433. const d_z = vertices[ indexD * 3 + 2 ];
  26434. if ( Math.abs( a_y - b_y ) < Math.abs( a_x - b_x ) ) {
  26435. return [
  26436. new Vector2( a_x, 1 - a_z ),
  26437. new Vector2( b_x, 1 - b_z ),
  26438. new Vector2( c_x, 1 - c_z ),
  26439. new Vector2( d_x, 1 - d_z )
  26440. ];
  26441. } else {
  26442. return [
  26443. new Vector2( a_y, 1 - a_z ),
  26444. new Vector2( b_y, 1 - b_z ),
  26445. new Vector2( c_y, 1 - c_z ),
  26446. new Vector2( d_y, 1 - d_z )
  26447. ];
  26448. }
  26449. }
  26450. };
  26451. function toJSON$1( shapes, options, data ) {
  26452. data.shapes = [];
  26453. if ( Array.isArray( shapes ) ) {
  26454. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  26455. const shape = shapes[ i ];
  26456. data.shapes.push( shape.uuid );
  26457. }
  26458. } else {
  26459. data.shapes.push( shapes.uuid );
  26460. }
  26461. data.options = Object.assign( {}, options );
  26462. if ( options.extrudePath !== undefined ) data.options.extrudePath = options.extrudePath.toJSON();
  26463. return data;
  26464. }
  26465. /**
  26466. * A geometry class for representing an icosahedron.
  26467. *
  26468. * ```js
  26469. * const geometry = new THREE.IcosahedronGeometry();
  26470. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  26471. * const icosahedron = new THREE.Mesh( geometry, material );
  26472. * scene.add( icosahedron );
  26473. * ```
  26474. *
  26475. * @augments PolyhedronGeometry
  26476. * @demo scenes/geometry-browser.html#IcosahedronGeometry
  26477. */
  26478. class IcosahedronGeometry extends PolyhedronGeometry {
  26479. /**
  26480. * Constructs a new icosahedron geometry.
  26481. *
  26482. * @param {number} [radius=1] - Radius of the icosahedron.
  26483. * @param {number} [detail=0] - Setting this to a value greater than `0` adds vertices making it no longer a icosahedron.
  26484. */
  26485. constructor( radius = 1, detail = 0 ) {
  26486. const t = ( 1 + Math.sqrt( 5 ) ) / 2;
  26487. const vertices = [
  26488. -1, t, 0, 1, t, 0, -1, - t, 0, 1, - t, 0,
  26489. 0, -1, t, 0, 1, t, 0, -1, - t, 0, 1, - t,
  26490. t, 0, -1, t, 0, 1, - t, 0, -1, - t, 0, 1
  26491. ];
  26492. const indices = [
  26493. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 0, 10, 11,
  26494. 1, 5, 9, 5, 11, 4, 11, 10, 2, 10, 7, 6, 7, 1, 8,
  26495. 3, 9, 4, 3, 4, 2, 3, 2, 6, 3, 6, 8, 3, 8, 9,
  26496. 4, 9, 5, 2, 4, 11, 6, 2, 10, 8, 6, 7, 9, 8, 1
  26497. ];
  26498. super( vertices, indices, radius, detail );
  26499. this.type = 'IcosahedronGeometry';
  26500. /**
  26501. * Holds the constructor parameters that have been
  26502. * used to generate the geometry. Any modification
  26503. * after instantiation does not change the geometry.
  26504. *
  26505. * @type {Object}
  26506. */
  26507. this.parameters = {
  26508. radius: radius,
  26509. detail: detail
  26510. };
  26511. }
  26512. /**
  26513. * Factory method for creating an instance of this class from the given
  26514. * JSON object.
  26515. *
  26516. * @param {Object} data - A JSON object representing the serialized geometry.
  26517. * @return {IcosahedronGeometry} A new instance.
  26518. */
  26519. static fromJSON( data ) {
  26520. return new IcosahedronGeometry( data.radius, data.detail );
  26521. }
  26522. }
  26523. /**
  26524. * Creates meshes with axial symmetry like vases. The lathe rotates around the Y axis.
  26525. *
  26526. * ```js
  26527. * const points = [];
  26528. * for ( let i = 0; i < 10; i ++ ) {
  26529. * points.push( new THREE.Vector2( Math.sin( i * 0.2 ) * 10 + 5, ( i - 5 ) * 2 ) );
  26530. * }
  26531. * const geometry = new THREE.LatheGeometry( points );
  26532. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  26533. * const lathe = new THREE.Mesh( geometry, material );
  26534. * scene.add( lathe );
  26535. * ```
  26536. *
  26537. * @augments BufferGeometry
  26538. * @demo scenes/geometry-browser.html#LatheGeometry
  26539. */
  26540. class LatheGeometry extends BufferGeometry {
  26541. /**
  26542. * Constructs a new lathe geometry.
  26543. *
  26544. * @param {Array<Vector2|Vector3>} [points] - An array of points in 2D space. The x-coordinate of each point
  26545. * must be greater than zero.
  26546. * @param {number} [segments=12] - The number of circumference segments to generate.
  26547. * @param {number} [phiStart=0] - The starting angle in radians.
  26548. * @param {number} [phiLength=Math.PI*2] - The radian (0 to 2PI) range of the lathed section 2PI is a
  26549. * closed lathe, less than 2PI is a portion.
  26550. */
  26551. 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 ) {
  26552. super();
  26553. this.type = 'LatheGeometry';
  26554. /**
  26555. * Holds the constructor parameters that have been
  26556. * used to generate the geometry. Any modification
  26557. * after instantiation does not change the geometry.
  26558. *
  26559. * @type {Object}
  26560. */
  26561. this.parameters = {
  26562. points: points,
  26563. segments: segments,
  26564. phiStart: phiStart,
  26565. phiLength: phiLength
  26566. };
  26567. segments = Math.floor( segments );
  26568. // clamp phiLength so it's in range of [ 0, 2PI ]
  26569. phiLength = clamp( phiLength, 0, Math.PI * 2 );
  26570. // buffers
  26571. const indices = [];
  26572. const vertices = [];
  26573. const uvs = [];
  26574. const initNormals = [];
  26575. const normals = [];
  26576. // helper variables
  26577. const inverseSegments = 1.0 / segments;
  26578. const vertex = new Vector3();
  26579. const uv = new Vector2();
  26580. const normal = new Vector3();
  26581. const curNormal = new Vector3();
  26582. const prevNormal = new Vector3();
  26583. let dx = 0;
  26584. let dy = 0;
  26585. // pre-compute normals for initial "meridian"
  26586. for ( let j = 0; j <= ( points.length - 1 ); j ++ ) {
  26587. switch ( j ) {
  26588. case 0: // special handling for 1st vertex on path
  26589. dx = points[ j + 1 ].x - points[ j ].x;
  26590. dy = points[ j + 1 ].y - points[ j ].y;
  26591. normal.x = dy * 1.0;
  26592. normal.y = - dx;
  26593. normal.z = dy * 0.0;
  26594. prevNormal.copy( normal );
  26595. normal.normalize();
  26596. initNormals.push( normal.x, normal.y, normal.z );
  26597. break;
  26598. case ( points.length - 1 ): // special handling for last Vertex on path
  26599. initNormals.push( prevNormal.x, prevNormal.y, prevNormal.z );
  26600. break;
  26601. default: // default handling for all vertices in between
  26602. dx = points[ j + 1 ].x - points[ j ].x;
  26603. dy = points[ j + 1 ].y - points[ j ].y;
  26604. normal.x = dy * 1.0;
  26605. normal.y = - dx;
  26606. normal.z = dy * 0.0;
  26607. curNormal.copy( normal );
  26608. normal.x += prevNormal.x;
  26609. normal.y += prevNormal.y;
  26610. normal.z += prevNormal.z;
  26611. normal.normalize();
  26612. initNormals.push( normal.x, normal.y, normal.z );
  26613. prevNormal.copy( curNormal );
  26614. }
  26615. }
  26616. // generate vertices, uvs and normals
  26617. for ( let i = 0; i <= segments; i ++ ) {
  26618. const phi = phiStart + i * inverseSegments * phiLength;
  26619. const sin = Math.sin( phi );
  26620. const cos = Math.cos( phi );
  26621. for ( let j = 0; j <= ( points.length - 1 ); j ++ ) {
  26622. // vertex
  26623. vertex.x = points[ j ].x * sin;
  26624. vertex.y = points[ j ].y;
  26625. vertex.z = points[ j ].x * cos;
  26626. vertices.push( vertex.x, vertex.y, vertex.z );
  26627. // uv
  26628. uv.x = i / segments;
  26629. uv.y = j / ( points.length - 1 );
  26630. uvs.push( uv.x, uv.y );
  26631. // normal
  26632. const x = initNormals[ 3 * j + 0 ] * sin;
  26633. const y = initNormals[ 3 * j + 1 ];
  26634. const z = initNormals[ 3 * j + 0 ] * cos;
  26635. normals.push( x, y, z );
  26636. }
  26637. }
  26638. // indices
  26639. for ( let i = 0; i < segments; i ++ ) {
  26640. for ( let j = 0; j < ( points.length - 1 ); j ++ ) {
  26641. const base = j + i * points.length;
  26642. const a = base;
  26643. const b = base + points.length;
  26644. const c = base + points.length + 1;
  26645. const d = base + 1;
  26646. // faces
  26647. indices.push( a, b, d );
  26648. indices.push( c, d, b );
  26649. }
  26650. }
  26651. // build geometry
  26652. this.setIndex( indices );
  26653. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  26654. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  26655. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  26656. }
  26657. copy( source ) {
  26658. super.copy( source );
  26659. this.parameters = Object.assign( {}, source.parameters );
  26660. return this;
  26661. }
  26662. /**
  26663. * Factory method for creating an instance of this class from the given
  26664. * JSON object.
  26665. *
  26666. * @param {Object} data - A JSON object representing the serialized geometry.
  26667. * @return {LatheGeometry} A new instance.
  26668. */
  26669. static fromJSON( data ) {
  26670. return new LatheGeometry( data.points, data.segments, data.phiStart, data.phiLength );
  26671. }
  26672. }
  26673. /**
  26674. * A geometry class for representing an octahedron.
  26675. *
  26676. * ```js
  26677. * const geometry = new THREE.OctahedronGeometry();
  26678. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  26679. * const octahedron = new THREE.Mesh( geometry, material );
  26680. * scene.add( octahedron );
  26681. * ```
  26682. *
  26683. * @augments PolyhedronGeometry
  26684. * @demo scenes/geometry-browser.html#OctahedronGeometry
  26685. */
  26686. class OctahedronGeometry extends PolyhedronGeometry {
  26687. /**
  26688. * Constructs a new octahedron geometry.
  26689. *
  26690. * @param {number} [radius=1] - Radius of the octahedron.
  26691. * @param {number} [detail=0] - Setting this to a value greater than `0` adds vertices making it no longer a octahedron.
  26692. */
  26693. constructor( radius = 1, detail = 0 ) {
  26694. const vertices = [
  26695. 1, 0, 0, -1, 0, 0, 0, 1, 0,
  26696. 0, -1, 0, 0, 0, 1, 0, 0, -1
  26697. ];
  26698. const indices = [
  26699. 0, 2, 4, 0, 4, 3, 0, 3, 5,
  26700. 0, 5, 2, 1, 2, 5, 1, 5, 3,
  26701. 1, 3, 4, 1, 4, 2
  26702. ];
  26703. super( vertices, indices, radius, detail );
  26704. this.type = 'OctahedronGeometry';
  26705. /**
  26706. * Holds the constructor parameters that have been
  26707. * used to generate the geometry. Any modification
  26708. * after instantiation does not change the geometry.
  26709. *
  26710. * @type {Object}
  26711. */
  26712. this.parameters = {
  26713. radius: radius,
  26714. detail: detail
  26715. };
  26716. }
  26717. /**
  26718. * Factory method for creating an instance of this class from the given
  26719. * JSON object.
  26720. *
  26721. * @param {Object} data - A JSON object representing the serialized geometry.
  26722. * @return {OctahedronGeometry} A new instance.
  26723. */
  26724. static fromJSON( data ) {
  26725. return new OctahedronGeometry( data.radius, data.detail );
  26726. }
  26727. }
  26728. /**
  26729. * A geometry class for representing a plane.
  26730. *
  26731. * ```js
  26732. * const geometry = new THREE.PlaneGeometry( 1, 1 );
  26733. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00, side: THREE.DoubleSide } );
  26734. * const plane = new THREE.Mesh( geometry, material );
  26735. * scene.add( plane );
  26736. * ```
  26737. *
  26738. * @augments BufferGeometry
  26739. * @demo scenes/geometry-browser.html#PlaneGeometry
  26740. */
  26741. class PlaneGeometry extends BufferGeometry {
  26742. /**
  26743. * Constructs a new plane geometry.
  26744. *
  26745. * @param {number} [width=1] - The width along the X axis.
  26746. * @param {number} [height=1] - The height along the Y axis
  26747. * @param {number} [widthSegments=1] - The number of segments along the X axis.
  26748. * @param {number} [heightSegments=1] - The number of segments along the Y axis.
  26749. */
  26750. constructor( width = 1, height = 1, widthSegments = 1, heightSegments = 1 ) {
  26751. super();
  26752. this.type = 'PlaneGeometry';
  26753. /**
  26754. * Holds the constructor parameters that have been
  26755. * used to generate the geometry. Any modification
  26756. * after instantiation does not change the geometry.
  26757. *
  26758. * @type {Object}
  26759. */
  26760. this.parameters = {
  26761. width: width,
  26762. height: height,
  26763. widthSegments: widthSegments,
  26764. heightSegments: heightSegments
  26765. };
  26766. const width_half = width / 2;
  26767. const height_half = height / 2;
  26768. const gridX = Math.floor( widthSegments );
  26769. const gridY = Math.floor( heightSegments );
  26770. const gridX1 = gridX + 1;
  26771. const gridY1 = gridY + 1;
  26772. const segment_width = width / gridX;
  26773. const segment_height = height / gridY;
  26774. //
  26775. const indices = [];
  26776. const vertices = [];
  26777. const normals = [];
  26778. const uvs = [];
  26779. for ( let iy = 0; iy < gridY1; iy ++ ) {
  26780. const y = iy * segment_height - height_half;
  26781. for ( let ix = 0; ix < gridX1; ix ++ ) {
  26782. const x = ix * segment_width - width_half;
  26783. vertices.push( x, - y, 0 );
  26784. normals.push( 0, 0, 1 );
  26785. uvs.push( ix / gridX );
  26786. uvs.push( 1 - ( iy / gridY ) );
  26787. }
  26788. }
  26789. for ( let iy = 0; iy < gridY; iy ++ ) {
  26790. for ( let ix = 0; ix < gridX; ix ++ ) {
  26791. const a = ix + gridX1 * iy;
  26792. const b = ix + gridX1 * ( iy + 1 );
  26793. const c = ( ix + 1 ) + gridX1 * ( iy + 1 );
  26794. const d = ( ix + 1 ) + gridX1 * iy;
  26795. indices.push( a, b, d );
  26796. indices.push( b, c, d );
  26797. }
  26798. }
  26799. this.setIndex( indices );
  26800. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  26801. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  26802. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  26803. }
  26804. copy( source ) {
  26805. super.copy( source );
  26806. this.parameters = Object.assign( {}, source.parameters );
  26807. return this;
  26808. }
  26809. /**
  26810. * Factory method for creating an instance of this class from the given
  26811. * JSON object.
  26812. *
  26813. * @param {Object} data - A JSON object representing the serialized geometry.
  26814. * @return {PlaneGeometry} A new instance.
  26815. */
  26816. static fromJSON( data ) {
  26817. return new PlaneGeometry( data.width, data.height, data.widthSegments, data.heightSegments );
  26818. }
  26819. }
  26820. /**
  26821. * A class for generating a two-dimensional ring geometry.
  26822. *
  26823. * ```js
  26824. * const geometry = new THREE.RingGeometry( 1, 5, 32 );
  26825. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00, side: THREE.DoubleSide } );
  26826. * const mesh = new THREE.Mesh( geometry, material );
  26827. * scene.add( mesh );
  26828. * ```
  26829. *
  26830. * @augments BufferGeometry
  26831. * @demo scenes/geometry-browser.html#RingGeometry
  26832. */
  26833. class RingGeometry extends BufferGeometry {
  26834. /**
  26835. * Constructs a new ring geometry.
  26836. *
  26837. * @param {number} [innerRadius=0.5] - The inner radius of the ring.
  26838. * @param {number} [outerRadius=1] - The outer radius of the ring.
  26839. * @param {number} [thetaSegments=32] - Number of segments. A higher number means the ring will be more round. Minimum is `3`.
  26840. * @param {number} [phiSegments=1] - Number of segments per ring segment. Minimum is `1`.
  26841. * @param {number} [thetaStart=0] - Starting angle in radians.
  26842. * @param {number} [thetaLength=Math.PI*2] - Central angle in radians.
  26843. */
  26844. constructor( innerRadius = 0.5, outerRadius = 1, thetaSegments = 32, phiSegments = 1, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  26845. super();
  26846. this.type = 'RingGeometry';
  26847. /**
  26848. * Holds the constructor parameters that have been
  26849. * used to generate the geometry. Any modification
  26850. * after instantiation does not change the geometry.
  26851. *
  26852. * @type {Object}
  26853. */
  26854. this.parameters = {
  26855. innerRadius: innerRadius,
  26856. outerRadius: outerRadius,
  26857. thetaSegments: thetaSegments,
  26858. phiSegments: phiSegments,
  26859. thetaStart: thetaStart,
  26860. thetaLength: thetaLength
  26861. };
  26862. thetaSegments = Math.max( 3, thetaSegments );
  26863. phiSegments = Math.max( 1, phiSegments );
  26864. // buffers
  26865. const indices = [];
  26866. const vertices = [];
  26867. const normals = [];
  26868. const uvs = [];
  26869. // some helper variables
  26870. let radius = innerRadius;
  26871. const radiusStep = ( ( outerRadius - innerRadius ) / phiSegments );
  26872. const vertex = new Vector3();
  26873. const uv = new Vector2();
  26874. // generate vertices, normals and uvs
  26875. for ( let j = 0; j <= phiSegments; j ++ ) {
  26876. for ( let i = 0; i <= thetaSegments; i ++ ) {
  26877. // values are generate from the inside of the ring to the outside
  26878. const segment = thetaStart + i / thetaSegments * thetaLength;
  26879. // vertex
  26880. vertex.x = radius * Math.cos( segment );
  26881. vertex.y = radius * Math.sin( segment );
  26882. vertices.push( vertex.x, vertex.y, vertex.z );
  26883. // normal
  26884. normals.push( 0, 0, 1 );
  26885. // uv
  26886. uv.x = ( vertex.x / outerRadius + 1 ) / 2;
  26887. uv.y = ( vertex.y / outerRadius + 1 ) / 2;
  26888. uvs.push( uv.x, uv.y );
  26889. }
  26890. // increase the radius for next row of vertices
  26891. radius += radiusStep;
  26892. }
  26893. // indices
  26894. for ( let j = 0; j < phiSegments; j ++ ) {
  26895. const thetaSegmentLevel = j * ( thetaSegments + 1 );
  26896. for ( let i = 0; i < thetaSegments; i ++ ) {
  26897. const segment = i + thetaSegmentLevel;
  26898. const a = segment;
  26899. const b = segment + thetaSegments + 1;
  26900. const c = segment + thetaSegments + 2;
  26901. const d = segment + 1;
  26902. // faces
  26903. indices.push( a, b, d );
  26904. indices.push( b, c, d );
  26905. }
  26906. }
  26907. // build geometry
  26908. this.setIndex( indices );
  26909. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  26910. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  26911. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  26912. }
  26913. copy( source ) {
  26914. super.copy( source );
  26915. this.parameters = Object.assign( {}, source.parameters );
  26916. return this;
  26917. }
  26918. /**
  26919. * Factory method for creating an instance of this class from the given
  26920. * JSON object.
  26921. *
  26922. * @param {Object} data - A JSON object representing the serialized geometry.
  26923. * @return {RingGeometry} A new instance.
  26924. */
  26925. static fromJSON( data ) {
  26926. return new RingGeometry( data.innerRadius, data.outerRadius, data.thetaSegments, data.phiSegments, data.thetaStart, data.thetaLength );
  26927. }
  26928. }
  26929. /**
  26930. * Creates an one-sided polygonal geometry from one or more path shapes.
  26931. *
  26932. * ```js
  26933. * const arcShape = new THREE.Shape()
  26934. * .moveTo( 5, 1 )
  26935. * .absarc( 1, 1, 4, 0, Math.PI * 2, false );
  26936. *
  26937. * const geometry = new THREE.ShapeGeometry( arcShape );
  26938. * const material = new THREE.MeshBasicMaterial( { color: 0x00ff00, side: THREE.DoubleSide } );
  26939. * const mesh = new THREE.Mesh( geometry, material ) ;
  26940. * scene.add( mesh );
  26941. * ```
  26942. *
  26943. * @augments BufferGeometry
  26944. * @demo scenes/geometry-browser.html#ShapeGeometry
  26945. */
  26946. class ShapeGeometry extends BufferGeometry {
  26947. /**
  26948. * Constructs a new shape geometry.
  26949. *
  26950. * @param {Shape|Array<Shape>} [shapes] - A shape or an array of shapes.
  26951. * @param {number} [curveSegments=12] - Number of segments per shape.
  26952. */
  26953. constructor( shapes = new Shape( [ new Vector2( 0, 0.5 ), new Vector2( -0.5, -0.5 ), new Vector2( 0.5, -0.5 ) ] ), curveSegments = 12 ) {
  26954. super();
  26955. this.type = 'ShapeGeometry';
  26956. /**
  26957. * Holds the constructor parameters that have been
  26958. * used to generate the geometry. Any modification
  26959. * after instantiation does not change the geometry.
  26960. *
  26961. * @type {Object}
  26962. */
  26963. this.parameters = {
  26964. shapes: shapes,
  26965. curveSegments: curveSegments
  26966. };
  26967. // buffers
  26968. const indices = [];
  26969. const vertices = [];
  26970. const normals = [];
  26971. const uvs = [];
  26972. // helper variables
  26973. let groupStart = 0;
  26974. let groupCount = 0;
  26975. // allow single and array values for "shapes" parameter
  26976. if ( Array.isArray( shapes ) === false ) {
  26977. addShape( shapes );
  26978. } else {
  26979. for ( let i = 0; i < shapes.length; i ++ ) {
  26980. addShape( shapes[ i ] );
  26981. this.addGroup( groupStart, groupCount, i ); // enables MultiMaterial support
  26982. groupStart += groupCount;
  26983. groupCount = 0;
  26984. }
  26985. }
  26986. // build geometry
  26987. this.setIndex( indices );
  26988. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  26989. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  26990. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  26991. // helper functions
  26992. function addShape( shape ) {
  26993. const indexOffset = vertices.length / 3;
  26994. const points = shape.extractPoints( curveSegments );
  26995. let shapeVertices = points.shape;
  26996. const shapeHoles = points.holes;
  26997. // check direction of vertices
  26998. if ( ShapeUtils.isClockWise( shapeVertices ) === false ) {
  26999. shapeVertices = shapeVertices.reverse();
  27000. }
  27001. for ( let i = 0, l = shapeHoles.length; i < l; i ++ ) {
  27002. const shapeHole = shapeHoles[ i ];
  27003. if ( ShapeUtils.isClockWise( shapeHole ) === true ) {
  27004. shapeHoles[ i ] = shapeHole.reverse();
  27005. }
  27006. }
  27007. const faces = ShapeUtils.triangulateShape( shapeVertices, shapeHoles );
  27008. // join vertices of inner and outer paths to a single array
  27009. for ( let i = 0, l = shapeHoles.length; i < l; i ++ ) {
  27010. const shapeHole = shapeHoles[ i ];
  27011. shapeVertices = shapeVertices.concat( shapeHole );
  27012. }
  27013. // vertices, normals, uvs
  27014. for ( let i = 0, l = shapeVertices.length; i < l; i ++ ) {
  27015. const vertex = shapeVertices[ i ];
  27016. vertices.push( vertex.x, vertex.y, 0 );
  27017. normals.push( 0, 0, 1 );
  27018. uvs.push( vertex.x, vertex.y ); // world uvs
  27019. }
  27020. // indices
  27021. for ( let i = 0, l = faces.length; i < l; i ++ ) {
  27022. const face = faces[ i ];
  27023. const a = face[ 0 ] + indexOffset;
  27024. const b = face[ 1 ] + indexOffset;
  27025. const c = face[ 2 ] + indexOffset;
  27026. indices.push( a, b, c );
  27027. groupCount += 3;
  27028. }
  27029. }
  27030. }
  27031. copy( source ) {
  27032. super.copy( source );
  27033. this.parameters = Object.assign( {}, source.parameters );
  27034. return this;
  27035. }
  27036. toJSON() {
  27037. const data = super.toJSON();
  27038. const shapes = this.parameters.shapes;
  27039. return toJSON( shapes, data );
  27040. }
  27041. /**
  27042. * Factory method for creating an instance of this class from the given
  27043. * JSON object.
  27044. *
  27045. * @param {Object} data - A JSON object representing the serialized geometry.
  27046. * @param {Array<Shape>} shapes - An array of shapes.
  27047. * @return {ShapeGeometry} A new instance.
  27048. */
  27049. static fromJSON( data, shapes ) {
  27050. const geometryShapes = [];
  27051. for ( let j = 0, jl = data.shapes.length; j < jl; j ++ ) {
  27052. const shape = shapes[ data.shapes[ j ] ];
  27053. geometryShapes.push( shape );
  27054. }
  27055. return new ShapeGeometry( geometryShapes, data.curveSegments );
  27056. }
  27057. }
  27058. function toJSON( shapes, data ) {
  27059. data.shapes = [];
  27060. if ( Array.isArray( shapes ) ) {
  27061. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  27062. const shape = shapes[ i ];
  27063. data.shapes.push( shape.uuid );
  27064. }
  27065. } else {
  27066. data.shapes.push( shapes.uuid );
  27067. }
  27068. return data;
  27069. }
  27070. /**
  27071. * A class for generating a sphere geometry.
  27072. *
  27073. * ```js
  27074. * const geometry = new THREE.SphereGeometry( 15, 32, 16 );
  27075. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  27076. * const sphere = new THREE.Mesh( geometry, material );
  27077. * scene.add( sphere );
  27078. * ```
  27079. *
  27080. * @augments BufferGeometry
  27081. * @demo scenes/geometry-browser.html#SphereGeometry
  27082. */
  27083. class SphereGeometry extends BufferGeometry {
  27084. /**
  27085. * Constructs a new sphere geometry.
  27086. *
  27087. * @param {number} [radius=1] - The sphere radius.
  27088. * @param {number} [widthSegments=32] - The number of horizontal segments. Minimum value is `3`.
  27089. * @param {number} [heightSegments=16] - The number of vertical segments. Minimum value is `2`.
  27090. * @param {number} [phiStart=0] - The horizontal starting angle in radians.
  27091. * @param {number} [phiLength=Math.PI*2] - The horizontal sweep angle size.
  27092. * @param {number} [thetaStart=0] - The vertical starting angle in radians.
  27093. * @param {number} [thetaLength=Math.PI] - The vertical sweep angle size.
  27094. */
  27095. constructor( radius = 1, widthSegments = 32, heightSegments = 16, phiStart = 0, phiLength = Math.PI * 2, thetaStart = 0, thetaLength = Math.PI ) {
  27096. super();
  27097. this.type = 'SphereGeometry';
  27098. /**
  27099. * Holds the constructor parameters that have been
  27100. * used to generate the geometry. Any modification
  27101. * after instantiation does not change the geometry.
  27102. *
  27103. * @type {Object}
  27104. */
  27105. this.parameters = {
  27106. radius: radius,
  27107. widthSegments: widthSegments,
  27108. heightSegments: heightSegments,
  27109. phiStart: phiStart,
  27110. phiLength: phiLength,
  27111. thetaStart: thetaStart,
  27112. thetaLength: thetaLength
  27113. };
  27114. widthSegments = Math.max( 3, Math.floor( widthSegments ) );
  27115. heightSegments = Math.max( 2, Math.floor( heightSegments ) );
  27116. const thetaEnd = Math.min( thetaStart + thetaLength, Math.PI );
  27117. let index = 0;
  27118. const grid = [];
  27119. const vertex = new Vector3();
  27120. const normal = new Vector3();
  27121. // buffers
  27122. const indices = [];
  27123. const vertices = [];
  27124. const normals = [];
  27125. const uvs = [];
  27126. // generate vertices, normals and uvs
  27127. for ( let iy = 0; iy <= heightSegments; iy ++ ) {
  27128. const verticesRow = [];
  27129. const v = iy / heightSegments;
  27130. // special case for the poles
  27131. let uOffset = 0;
  27132. if ( iy === 0 && thetaStart === 0 ) {
  27133. uOffset = 0.5 / widthSegments;
  27134. } else if ( iy === heightSegments && thetaEnd === Math.PI ) {
  27135. uOffset = -0.5 / widthSegments;
  27136. }
  27137. for ( let ix = 0; ix <= widthSegments; ix ++ ) {
  27138. const u = ix / widthSegments;
  27139. // vertex
  27140. vertex.x = - radius * Math.cos( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  27141. vertex.y = radius * Math.cos( thetaStart + v * thetaLength );
  27142. vertex.z = radius * Math.sin( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  27143. vertices.push( vertex.x, vertex.y, vertex.z );
  27144. // normal
  27145. normal.copy( vertex ).normalize();
  27146. normals.push( normal.x, normal.y, normal.z );
  27147. // uv
  27148. uvs.push( u + uOffset, 1 - v );
  27149. verticesRow.push( index ++ );
  27150. }
  27151. grid.push( verticesRow );
  27152. }
  27153. // indices
  27154. for ( let iy = 0; iy < heightSegments; iy ++ ) {
  27155. for ( let ix = 0; ix < widthSegments; ix ++ ) {
  27156. const a = grid[ iy ][ ix + 1 ];
  27157. const b = grid[ iy ][ ix ];
  27158. const c = grid[ iy + 1 ][ ix ];
  27159. const d = grid[ iy + 1 ][ ix + 1 ];
  27160. if ( iy !== 0 || thetaStart > 0 ) indices.push( a, b, d );
  27161. if ( iy !== heightSegments - 1 || thetaEnd < Math.PI ) indices.push( b, c, d );
  27162. }
  27163. }
  27164. // build geometry
  27165. this.setIndex( indices );
  27166. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  27167. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  27168. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  27169. }
  27170. copy( source ) {
  27171. super.copy( source );
  27172. this.parameters = Object.assign( {}, source.parameters );
  27173. return this;
  27174. }
  27175. /**
  27176. * Factory method for creating an instance of this class from the given
  27177. * JSON object.
  27178. *
  27179. * @param {Object} data - A JSON object representing the serialized geometry.
  27180. * @return {SphereGeometry} A new instance.
  27181. */
  27182. static fromJSON( data ) {
  27183. return new SphereGeometry( data.radius, data.widthSegments, data.heightSegments, data.phiStart, data.phiLength, data.thetaStart, data.thetaLength );
  27184. }
  27185. }
  27186. /**
  27187. * A geometry class for representing an tetrahedron.
  27188. *
  27189. * ```js
  27190. * const geometry = new THREE.TetrahedronGeometry();
  27191. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  27192. * const tetrahedron = new THREE.Mesh( geometry, material );
  27193. * scene.add( tetrahedron );
  27194. * ```
  27195. *
  27196. * @augments PolyhedronGeometry
  27197. * @demo scenes/geometry-browser.html#TetrahedronGeometry
  27198. */
  27199. class TetrahedronGeometry extends PolyhedronGeometry {
  27200. /**
  27201. * Constructs a new tetrahedron geometry.
  27202. *
  27203. * @param {number} [radius=1] - Radius of the tetrahedron.
  27204. * @param {number} [detail=0] - Setting this to a value greater than `0` adds vertices making it no longer a tetrahedron.
  27205. */
  27206. constructor( radius = 1, detail = 0 ) {
  27207. const vertices = [
  27208. 1, 1, 1, -1, -1, 1, -1, 1, -1, 1, -1, -1
  27209. ];
  27210. const indices = [
  27211. 2, 1, 0, 0, 3, 2, 1, 3, 0, 2, 3, 1
  27212. ];
  27213. super( vertices, indices, radius, detail );
  27214. this.type = 'TetrahedronGeometry';
  27215. /**
  27216. * Holds the constructor parameters that have been
  27217. * used to generate the geometry. Any modification
  27218. * after instantiation does not change the geometry.
  27219. *
  27220. * @type {Object}
  27221. */
  27222. this.parameters = {
  27223. radius: radius,
  27224. detail: detail
  27225. };
  27226. }
  27227. /**
  27228. * Factory method for creating an instance of this class from the given
  27229. * JSON object.
  27230. *
  27231. * @param {Object} data - A JSON object representing the serialized geometry.
  27232. * @return {TetrahedronGeometry} A new instance.
  27233. */
  27234. static fromJSON( data ) {
  27235. return new TetrahedronGeometry( data.radius, data.detail );
  27236. }
  27237. }
  27238. /**
  27239. * A geometry class for representing an torus.
  27240. *
  27241. * ```js
  27242. * const geometry = new THREE.TorusGeometry( 10, 3, 16, 100 );
  27243. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  27244. * const torus = new THREE.Mesh( geometry, material );
  27245. * scene.add( torus );
  27246. * ```
  27247. *
  27248. * @augments BufferGeometry
  27249. * @demo scenes/geometry-browser.html#TorusGeometry
  27250. */
  27251. class TorusGeometry extends BufferGeometry {
  27252. /**
  27253. * Constructs a new torus geometry.
  27254. *
  27255. * @param {number} [radius=1] - Radius of the torus, from the center of the torus to the center of the tube.
  27256. * @param {number} [tube=0.4] - Radius of the tube. Must be smaller than `radius`.
  27257. * @param {number} [radialSegments=12] - The number of radial segments.
  27258. * @param {number} [tubularSegments=48] - The number of tubular segments.
  27259. * @param {number} [arc=Math.PI*2] - Central angle in radians.
  27260. */
  27261. constructor( radius = 1, tube = 0.4, radialSegments = 12, tubularSegments = 48, arc = Math.PI * 2 ) {
  27262. super();
  27263. this.type = 'TorusGeometry';
  27264. /**
  27265. * Holds the constructor parameters that have been
  27266. * used to generate the geometry. Any modification
  27267. * after instantiation does not change the geometry.
  27268. *
  27269. * @type {Object}
  27270. */
  27271. this.parameters = {
  27272. radius: radius,
  27273. tube: tube,
  27274. radialSegments: radialSegments,
  27275. tubularSegments: tubularSegments,
  27276. arc: arc
  27277. };
  27278. radialSegments = Math.floor( radialSegments );
  27279. tubularSegments = Math.floor( tubularSegments );
  27280. // buffers
  27281. const indices = [];
  27282. const vertices = [];
  27283. const normals = [];
  27284. const uvs = [];
  27285. // helper variables
  27286. const center = new Vector3();
  27287. const vertex = new Vector3();
  27288. const normal = new Vector3();
  27289. // generate vertices, normals and uvs
  27290. for ( let j = 0; j <= radialSegments; j ++ ) {
  27291. for ( let i = 0; i <= tubularSegments; i ++ ) {
  27292. const u = i / tubularSegments * arc;
  27293. const v = j / radialSegments * Math.PI * 2;
  27294. // vertex
  27295. vertex.x = ( radius + tube * Math.cos( v ) ) * Math.cos( u );
  27296. vertex.y = ( radius + tube * Math.cos( v ) ) * Math.sin( u );
  27297. vertex.z = tube * Math.sin( v );
  27298. vertices.push( vertex.x, vertex.y, vertex.z );
  27299. // normal
  27300. center.x = radius * Math.cos( u );
  27301. center.y = radius * Math.sin( u );
  27302. normal.subVectors( vertex, center ).normalize();
  27303. normals.push( normal.x, normal.y, normal.z );
  27304. // uv
  27305. uvs.push( i / tubularSegments );
  27306. uvs.push( j / radialSegments );
  27307. }
  27308. }
  27309. // generate indices
  27310. for ( let j = 1; j <= radialSegments; j ++ ) {
  27311. for ( let i = 1; i <= tubularSegments; i ++ ) {
  27312. // indices
  27313. const a = ( tubularSegments + 1 ) * j + i - 1;
  27314. const b = ( tubularSegments + 1 ) * ( j - 1 ) + i - 1;
  27315. const c = ( tubularSegments + 1 ) * ( j - 1 ) + i;
  27316. const d = ( tubularSegments + 1 ) * j + i;
  27317. // faces
  27318. indices.push( a, b, d );
  27319. indices.push( b, c, d );
  27320. }
  27321. }
  27322. // build geometry
  27323. this.setIndex( indices );
  27324. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  27325. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  27326. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  27327. }
  27328. copy( source ) {
  27329. super.copy( source );
  27330. this.parameters = Object.assign( {}, source.parameters );
  27331. return this;
  27332. }
  27333. /**
  27334. * Factory method for creating an instance of this class from the given
  27335. * JSON object.
  27336. *
  27337. * @param {Object} data - A JSON object representing the serialized geometry.
  27338. * @return {TorusGeometry} A new instance.
  27339. */
  27340. static fromJSON( data ) {
  27341. return new TorusGeometry( data.radius, data.tube, data.radialSegments, data.tubularSegments, data.arc );
  27342. }
  27343. }
  27344. /**
  27345. * Creates a torus knot, the particular shape of which is defined by a pair
  27346. * of coprime integers, p and q. If p and q are not coprime, the result will
  27347. * be a torus link.
  27348. *
  27349. * ```js
  27350. * const geometry = new THREE.TorusKnotGeometry( 10, 3, 100, 16 );
  27351. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  27352. * const torusKnot = new THREE.Mesh( geometry, material );
  27353. * scene.add( torusKnot );
  27354. * ```
  27355. *
  27356. * @augments BufferGeometry
  27357. * @demo scenes/geometry-browser.html#TorusKnotGeometry
  27358. */
  27359. class TorusKnotGeometry extends BufferGeometry {
  27360. /**
  27361. * Constructs a new torus knot geometry.
  27362. *
  27363. * @param {number} [radius=1] - Radius of the torus knot.
  27364. * @param {number} [tube=0.4] - Radius of the tube.
  27365. * @param {number} [tubularSegments=64] - The number of tubular segments.
  27366. * @param {number} [radialSegments=8] - The number of radial segments.
  27367. * @param {number} [p=2] - This value determines, how many times the geometry winds around its axis of rotational symmetry.
  27368. * @param {number} [q=3] - This value determines, how many times the geometry winds around a circle in the interior of the torus.
  27369. */
  27370. constructor( radius = 1, tube = 0.4, tubularSegments = 64, radialSegments = 8, p = 2, q = 3 ) {
  27371. super();
  27372. this.type = 'TorusKnotGeometry';
  27373. /**
  27374. * Holds the constructor parameters that have been
  27375. * used to generate the geometry. Any modification
  27376. * after instantiation does not change the geometry.
  27377. *
  27378. * @type {Object}
  27379. */
  27380. this.parameters = {
  27381. radius: radius,
  27382. tube: tube,
  27383. tubularSegments: tubularSegments,
  27384. radialSegments: radialSegments,
  27385. p: p,
  27386. q: q
  27387. };
  27388. tubularSegments = Math.floor( tubularSegments );
  27389. radialSegments = Math.floor( radialSegments );
  27390. // buffers
  27391. const indices = [];
  27392. const vertices = [];
  27393. const normals = [];
  27394. const uvs = [];
  27395. // helper variables
  27396. const vertex = new Vector3();
  27397. const normal = new Vector3();
  27398. const P1 = new Vector3();
  27399. const P2 = new Vector3();
  27400. const B = new Vector3();
  27401. const T = new Vector3();
  27402. const N = new Vector3();
  27403. // generate vertices, normals and uvs
  27404. for ( let i = 0; i <= tubularSegments; ++ i ) {
  27405. // the radian "u" is used to calculate the position on the torus curve of the current tubular segment
  27406. const u = i / tubularSegments * p * Math.PI * 2;
  27407. // now we calculate two points. P1 is our current position on the curve, P2 is a little farther ahead.
  27408. // these points are used to create a special "coordinate space", which is necessary to calculate the correct vertex positions
  27409. calculatePositionOnCurve( u, p, q, radius, P1 );
  27410. calculatePositionOnCurve( u + 0.01, p, q, radius, P2 );
  27411. // calculate orthonormal basis
  27412. T.subVectors( P2, P1 );
  27413. N.addVectors( P2, P1 );
  27414. B.crossVectors( T, N );
  27415. N.crossVectors( B, T );
  27416. // normalize B, N. T can be ignored, we don't use it
  27417. B.normalize();
  27418. N.normalize();
  27419. for ( let j = 0; j <= radialSegments; ++ j ) {
  27420. // now calculate the vertices. they are nothing more than an extrusion of the torus curve.
  27421. // because we extrude a shape in the xy-plane, there is no need to calculate a z-value.
  27422. const v = j / radialSegments * Math.PI * 2;
  27423. const cx = - tube * Math.cos( v );
  27424. const cy = tube * Math.sin( v );
  27425. // now calculate the final vertex position.
  27426. // first we orient the extrusion with our basis vectors, then we add it to the current position on the curve
  27427. vertex.x = P1.x + ( cx * N.x + cy * B.x );
  27428. vertex.y = P1.y + ( cx * N.y + cy * B.y );
  27429. vertex.z = P1.z + ( cx * N.z + cy * B.z );
  27430. vertices.push( vertex.x, vertex.y, vertex.z );
  27431. // normal (P1 is always the center/origin of the extrusion, thus we can use it to calculate the normal)
  27432. normal.subVectors( vertex, P1 ).normalize();
  27433. normals.push( normal.x, normal.y, normal.z );
  27434. // uv
  27435. uvs.push( i / tubularSegments );
  27436. uvs.push( j / radialSegments );
  27437. }
  27438. }
  27439. // generate indices
  27440. for ( let j = 1; j <= tubularSegments; j ++ ) {
  27441. for ( let i = 1; i <= radialSegments; i ++ ) {
  27442. // indices
  27443. const a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 );
  27444. const b = ( radialSegments + 1 ) * j + ( i - 1 );
  27445. const c = ( radialSegments + 1 ) * j + i;
  27446. const d = ( radialSegments + 1 ) * ( j - 1 ) + i;
  27447. // faces
  27448. indices.push( a, b, d );
  27449. indices.push( b, c, d );
  27450. }
  27451. }
  27452. // build geometry
  27453. this.setIndex( indices );
  27454. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  27455. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  27456. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  27457. // this function calculates the current position on the torus curve
  27458. function calculatePositionOnCurve( u, p, q, radius, position ) {
  27459. const cu = Math.cos( u );
  27460. const su = Math.sin( u );
  27461. const quOverP = q / p * u;
  27462. const cs = Math.cos( quOverP );
  27463. position.x = radius * ( 2 + cs ) * 0.5 * cu;
  27464. position.y = radius * ( 2 + cs ) * su * 0.5;
  27465. position.z = radius * Math.sin( quOverP ) * 0.5;
  27466. }
  27467. }
  27468. copy( source ) {
  27469. super.copy( source );
  27470. this.parameters = Object.assign( {}, source.parameters );
  27471. return this;
  27472. }
  27473. /**
  27474. * Factory method for creating an instance of this class from the given
  27475. * JSON object.
  27476. *
  27477. * @param {Object} data - A JSON object representing the serialized geometry.
  27478. * @return {TorusKnotGeometry} A new instance.
  27479. */
  27480. static fromJSON( data ) {
  27481. return new TorusKnotGeometry( data.radius, data.tube, data.tubularSegments, data.radialSegments, data.p, data.q );
  27482. }
  27483. }
  27484. /**
  27485. * Creates a tube that extrudes along a 3D curve.
  27486. *
  27487. * ```js
  27488. * class CustomSinCurve extends THREE.Curve {
  27489. *
  27490. * getPoint( t, optionalTarget = new THREE.Vector3() ) {
  27491. *
  27492. * const tx = t * 3 - 1.5;
  27493. * const ty = Math.sin( 2 * Math.PI * t );
  27494. * const tz = 0;
  27495. *
  27496. * return optionalTarget.set( tx, ty, tz );
  27497. * }
  27498. *
  27499. * }
  27500. *
  27501. * const path = new CustomSinCurve( 10 );
  27502. * const geometry = new THREE.TubeGeometry( path, 20, 2, 8, false );
  27503. * const material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } );
  27504. * const mesh = new THREE.Mesh( geometry, material );
  27505. * scene.add( mesh );
  27506. * ```
  27507. *
  27508. * @augments BufferGeometry
  27509. * @demo scenes/geometry-browser.html#TubeGeometry
  27510. */
  27511. class TubeGeometry extends BufferGeometry {
  27512. /**
  27513. * Constructs a new tube geometry.
  27514. *
  27515. * @param {Curve} [path=QuadraticBezierCurve3] - A 3D curve defining the path of the tube.
  27516. * @param {number} [tubularSegments=64] - The number of segments that make up the tube.
  27517. * @param {number} [radius=1] -The radius of the tube.
  27518. * @param {number} [radialSegments=8] - The number of segments that make up the cross-section.
  27519. * @param {boolean} [closed=false] - Whether the tube is closed or not.
  27520. */
  27521. 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 ) {
  27522. super();
  27523. this.type = 'TubeGeometry';
  27524. /**
  27525. * Holds the constructor parameters that have been
  27526. * used to generate the geometry. Any modification
  27527. * after instantiation does not change the geometry.
  27528. *
  27529. * @type {Object}
  27530. */
  27531. this.parameters = {
  27532. path: path,
  27533. tubularSegments: tubularSegments,
  27534. radius: radius,
  27535. radialSegments: radialSegments,
  27536. closed: closed
  27537. };
  27538. const frames = path.computeFrenetFrames( tubularSegments, closed );
  27539. // expose internals
  27540. this.tangents = frames.tangents;
  27541. this.normals = frames.normals;
  27542. this.binormals = frames.binormals;
  27543. // helper variables
  27544. const vertex = new Vector3();
  27545. const normal = new Vector3();
  27546. const uv = new Vector2();
  27547. let P = new Vector3();
  27548. // buffer
  27549. const vertices = [];
  27550. const normals = [];
  27551. const uvs = [];
  27552. const indices = [];
  27553. // create buffer data
  27554. generateBufferData();
  27555. // build geometry
  27556. this.setIndex( indices );
  27557. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  27558. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  27559. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  27560. // functions
  27561. function generateBufferData() {
  27562. for ( let i = 0; i < tubularSegments; i ++ ) {
  27563. generateSegment( i );
  27564. }
  27565. // if the geometry is not closed, generate the last row of vertices and normals
  27566. // at the regular position on the given path
  27567. //
  27568. // if the geometry is closed, duplicate the first row of vertices and normals (uvs will differ)
  27569. generateSegment( ( closed === false ) ? tubularSegments : 0 );
  27570. // uvs are generated in a separate function.
  27571. // this makes it easy compute correct values for closed geometries
  27572. generateUVs();
  27573. // finally create faces
  27574. generateIndices();
  27575. }
  27576. function generateSegment( i ) {
  27577. // we use getPointAt to sample evenly distributed points from the given path
  27578. P = path.getPointAt( i / tubularSegments, P );
  27579. // retrieve corresponding normal and binormal
  27580. const N = frames.normals[ i ];
  27581. const B = frames.binormals[ i ];
  27582. // generate normals and vertices for the current segment
  27583. for ( let j = 0; j <= radialSegments; j ++ ) {
  27584. const v = j / radialSegments * Math.PI * 2;
  27585. const sin = Math.sin( v );
  27586. const cos = - Math.cos( v );
  27587. // normal
  27588. normal.x = ( cos * N.x + sin * B.x );
  27589. normal.y = ( cos * N.y + sin * B.y );
  27590. normal.z = ( cos * N.z + sin * B.z );
  27591. normal.normalize();
  27592. normals.push( normal.x, normal.y, normal.z );
  27593. // vertex
  27594. vertex.x = P.x + radius * normal.x;
  27595. vertex.y = P.y + radius * normal.y;
  27596. vertex.z = P.z + radius * normal.z;
  27597. vertices.push( vertex.x, vertex.y, vertex.z );
  27598. }
  27599. }
  27600. function generateIndices() {
  27601. for ( let j = 1; j <= tubularSegments; j ++ ) {
  27602. for ( let i = 1; i <= radialSegments; i ++ ) {
  27603. const a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 );
  27604. const b = ( radialSegments + 1 ) * j + ( i - 1 );
  27605. const c = ( radialSegments + 1 ) * j + i;
  27606. const d = ( radialSegments + 1 ) * ( j - 1 ) + i;
  27607. // faces
  27608. indices.push( a, b, d );
  27609. indices.push( b, c, d );
  27610. }
  27611. }
  27612. }
  27613. function generateUVs() {
  27614. for ( let i = 0; i <= tubularSegments; i ++ ) {
  27615. for ( let j = 0; j <= radialSegments; j ++ ) {
  27616. uv.x = i / tubularSegments;
  27617. uv.y = j / radialSegments;
  27618. uvs.push( uv.x, uv.y );
  27619. }
  27620. }
  27621. }
  27622. }
  27623. copy( source ) {
  27624. super.copy( source );
  27625. this.parameters = Object.assign( {}, source.parameters );
  27626. return this;
  27627. }
  27628. toJSON() {
  27629. const data = super.toJSON();
  27630. data.path = this.parameters.path.toJSON();
  27631. return data;
  27632. }
  27633. /**
  27634. * Factory method for creating an instance of this class from the given
  27635. * JSON object.
  27636. *
  27637. * @param {Object} data - A JSON object representing the serialized geometry.
  27638. * @return {TubeGeometry} A new instance.
  27639. */
  27640. static fromJSON( data ) {
  27641. // This only works for built-in curves (e.g. CatmullRomCurve3).
  27642. // User defined curves or instances of CurvePath will not be deserialized.
  27643. return new TubeGeometry(
  27644. new Curves[ data.path.type ]().fromJSON( data.path ),
  27645. data.tubularSegments,
  27646. data.radius,
  27647. data.radialSegments,
  27648. data.closed
  27649. );
  27650. }
  27651. }
  27652. /**
  27653. * Can be used as a helper object to visualize a geometry as a wireframe.
  27654. *
  27655. * ```js
  27656. * const geometry = new THREE.SphereGeometry();
  27657. *
  27658. * const wireframe = new THREE.WireframeGeometry( geometry );
  27659. *
  27660. * const line = new THREE.LineSegments( wireframe );
  27661. * line.material.depthWrite = false;
  27662. * line.material.opacity = 0.25;
  27663. * line.material.transparent = true;
  27664. *
  27665. * scene.add( line );
  27666. * ```
  27667. *
  27668. * Note: It is not yet possible to serialize/deserialize instances of this class.
  27669. *
  27670. * @augments BufferGeometry
  27671. */
  27672. class WireframeGeometry extends BufferGeometry {
  27673. /**
  27674. * Constructs a new wireframe geometry.
  27675. *
  27676. * @param {?BufferGeometry} [geometry=null] - The geometry.
  27677. */
  27678. constructor( geometry = null ) {
  27679. super();
  27680. this.type = 'WireframeGeometry';
  27681. /**
  27682. * Holds the constructor parameters that have been
  27683. * used to generate the geometry. Any modification
  27684. * after instantiation does not change the geometry.
  27685. *
  27686. * @type {Object}
  27687. */
  27688. this.parameters = {
  27689. geometry: geometry
  27690. };
  27691. if ( geometry !== null ) {
  27692. // buffer
  27693. const vertices = [];
  27694. const edges = new Set();
  27695. // helper variables
  27696. const start = new Vector3();
  27697. const end = new Vector3();
  27698. if ( geometry.index !== null ) {
  27699. // indexed BufferGeometry
  27700. const position = geometry.attributes.position;
  27701. const indices = geometry.index;
  27702. let groups = geometry.groups;
  27703. if ( groups.length === 0 ) {
  27704. groups = [ { start: 0, count: indices.count, materialIndex: 0 } ];
  27705. }
  27706. // create a data structure that contains all edges without duplicates
  27707. for ( let o = 0, ol = groups.length; o < ol; ++ o ) {
  27708. const group = groups[ o ];
  27709. const groupStart = group.start;
  27710. const groupCount = group.count;
  27711. for ( let i = groupStart, l = ( groupStart + groupCount ); i < l; i += 3 ) {
  27712. for ( let j = 0; j < 3; j ++ ) {
  27713. const index1 = indices.getX( i + j );
  27714. const index2 = indices.getX( i + ( j + 1 ) % 3 );
  27715. start.fromBufferAttribute( position, index1 );
  27716. end.fromBufferAttribute( position, index2 );
  27717. if ( isUniqueEdge( start, end, edges ) === true ) {
  27718. vertices.push( start.x, start.y, start.z );
  27719. vertices.push( end.x, end.y, end.z );
  27720. }
  27721. }
  27722. }
  27723. }
  27724. } else {
  27725. // non-indexed BufferGeometry
  27726. const position = geometry.attributes.position;
  27727. for ( let i = 0, l = ( position.count / 3 ); i < l; i ++ ) {
  27728. for ( let j = 0; j < 3; j ++ ) {
  27729. // three edges per triangle, an edge is represented as (index1, index2)
  27730. // e.g. the first triangle has the following edges: (0,1),(1,2),(2,0)
  27731. const index1 = 3 * i + j;
  27732. const index2 = 3 * i + ( ( j + 1 ) % 3 );
  27733. start.fromBufferAttribute( position, index1 );
  27734. end.fromBufferAttribute( position, index2 );
  27735. if ( isUniqueEdge( start, end, edges ) === true ) {
  27736. vertices.push( start.x, start.y, start.z );
  27737. vertices.push( end.x, end.y, end.z );
  27738. }
  27739. }
  27740. }
  27741. }
  27742. // build geometry
  27743. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  27744. }
  27745. }
  27746. copy( source ) {
  27747. super.copy( source );
  27748. this.parameters = Object.assign( {}, source.parameters );
  27749. return this;
  27750. }
  27751. }
  27752. function isUniqueEdge( start, end, edges ) {
  27753. const hash1 = `${start.x},${start.y},${start.z}-${end.x},${end.y},${end.z}`;
  27754. const hash2 = `${end.x},${end.y},${end.z}-${start.x},${start.y},${start.z}`; // coincident edge
  27755. if ( edges.has( hash1 ) === true || edges.has( hash2 ) === true ) {
  27756. return false;
  27757. } else {
  27758. edges.add( hash1 );
  27759. edges.add( hash2 );
  27760. return true;
  27761. }
  27762. }
  27763. var Geometries = /*#__PURE__*/Object.freeze({
  27764. __proto__: null,
  27765. BoxGeometry: BoxGeometry,
  27766. CapsuleGeometry: CapsuleGeometry,
  27767. CircleGeometry: CircleGeometry,
  27768. ConeGeometry: ConeGeometry,
  27769. CylinderGeometry: CylinderGeometry,
  27770. DodecahedronGeometry: DodecahedronGeometry,
  27771. EdgesGeometry: EdgesGeometry,
  27772. ExtrudeGeometry: ExtrudeGeometry,
  27773. IcosahedronGeometry: IcosahedronGeometry,
  27774. LatheGeometry: LatheGeometry,
  27775. OctahedronGeometry: OctahedronGeometry,
  27776. PlaneGeometry: PlaneGeometry,
  27777. PolyhedronGeometry: PolyhedronGeometry,
  27778. RingGeometry: RingGeometry,
  27779. ShapeGeometry: ShapeGeometry,
  27780. SphereGeometry: SphereGeometry,
  27781. TetrahedronGeometry: TetrahedronGeometry,
  27782. TorusGeometry: TorusGeometry,
  27783. TorusKnotGeometry: TorusKnotGeometry,
  27784. TubeGeometry: TubeGeometry,
  27785. WireframeGeometry: WireframeGeometry
  27786. });
  27787. /**
  27788. * This material can receive shadows, but otherwise is completely transparent.
  27789. *
  27790. * ```js
  27791. * const geometry = new THREE.PlaneGeometry( 2000, 2000 );
  27792. * geometry.rotateX( - Math.PI / 2 );
  27793. *
  27794. * const material = new THREE.ShadowMaterial();
  27795. * material.opacity = 0.2;
  27796. *
  27797. * const plane = new THREE.Mesh( geometry, material );
  27798. * plane.position.y = -200;
  27799. * plane.receiveShadow = true;
  27800. * scene.add( plane );
  27801. * ```
  27802. *
  27803. * @augments Material
  27804. */
  27805. class ShadowMaterial extends Material {
  27806. /**
  27807. * Constructs a new shadow material.
  27808. *
  27809. * @param {Object} [parameters] - An object with one or more properties
  27810. * defining the material's appearance. Any property of the material
  27811. * (including any property from inherited materials) can be passed
  27812. * in here. Color values can be passed any type of value accepted
  27813. * by {@link Color#set}.
  27814. */
  27815. constructor( parameters ) {
  27816. super();
  27817. /**
  27818. * This flag can be used for type testing.
  27819. *
  27820. * @type {boolean}
  27821. * @readonly
  27822. * @default true
  27823. */
  27824. this.isShadowMaterial = true;
  27825. this.type = 'ShadowMaterial';
  27826. /**
  27827. * Color of the material.
  27828. *
  27829. * @type {Color}
  27830. * @default (0,0,0)
  27831. */
  27832. this.color = new Color( 0x000000 );
  27833. /**
  27834. * Overwritten since shadow materials are transparent
  27835. * by default.
  27836. *
  27837. * @type {boolean}
  27838. * @default true
  27839. */
  27840. this.transparent = true;
  27841. /**
  27842. * Whether the material is affected by fog or not.
  27843. *
  27844. * @type {boolean}
  27845. * @default true
  27846. */
  27847. this.fog = true;
  27848. this.setValues( parameters );
  27849. }
  27850. copy( source ) {
  27851. super.copy( source );
  27852. this.color.copy( source.color );
  27853. this.fog = source.fog;
  27854. return this;
  27855. }
  27856. }
  27857. /**
  27858. * This class works just like {@link ShaderMaterial}, except that definitions
  27859. * of built-in uniforms and attributes are not automatically prepended to the
  27860. * GLSL shader code.
  27861. *
  27862. * `RawShaderMaterial` can only be used with {@link WebGLRenderer}.
  27863. *
  27864. * @augments ShaderMaterial
  27865. */
  27866. class RawShaderMaterial extends ShaderMaterial {
  27867. /**
  27868. * Constructs a new raw shader material.
  27869. *
  27870. * @param {Object} [parameters] - An object with one or more properties
  27871. * defining the material's appearance. Any property of the material
  27872. * (including any property from inherited materials) can be passed
  27873. * in here. Color values can be passed any type of value accepted
  27874. * by {@link Color#set}.
  27875. */
  27876. constructor( parameters ) {
  27877. super( parameters );
  27878. /**
  27879. * This flag can be used for type testing.
  27880. *
  27881. * @type {boolean}
  27882. * @readonly
  27883. * @default true
  27884. */
  27885. this.isRawShaderMaterial = true;
  27886. this.type = 'RawShaderMaterial';
  27887. }
  27888. }
  27889. /**
  27890. * A standard physically based material, using Metallic-Roughness workflow.
  27891. *
  27892. * Physically based rendering (PBR) has recently become the standard in many
  27893. * 3D applications, such as [Unity](https://blogs.unity3d.com/2014/10/29/physically-based-shading-in-unity-5-a-primer/),
  27894. * [Unreal](https://docs.unrealengine.com/latest/INT/Engine/Rendering/Materials/PhysicallyBased/) and
  27895. * [3D Studio Max](http://area.autodesk.com/blogs/the-3ds-max-blog/what039s-new-for-rendering-in-3ds-max-2017).
  27896. *
  27897. * This approach differs from older approaches in that instead of using
  27898. * approximations for the way in which light interacts with a surface, a
  27899. * physically correct model is used. The idea is that, instead of tweaking
  27900. * materials to look good under specific lighting, a material can be created
  27901. * that will react 'correctly' under all lighting scenarios.
  27902. *
  27903. * In practice this gives a more accurate and realistic looking result than
  27904. * the {@link MeshLambertMaterial} or {@link MeshPhongMaterial}, at the cost of
  27905. * being somewhat more computationally expensive. `MeshStandardMaterial` uses per-fragment
  27906. * shading.
  27907. *
  27908. * Note that for best results you should always specify an environment map when using this material.
  27909. *
  27910. * For a non-technical introduction to the concept of PBR and how to set up a
  27911. * PBR material, check out these articles by the people at [marmoset](https://www.marmoset.co):
  27912. *
  27913. * - [Basic Theory of Physically Based Rendering](https://www.marmoset.co/posts/basic-theory-of-physically-based-rendering/)
  27914. * - [Physically Based Rendering and You Can Too](https://www.marmoset.co/posts/physically-based-rendering-and-you-can-too/)
  27915. *
  27916. * Technical details of the approach used in three.js (and most other PBR systems) can be found is this
  27917. * [paper from Disney](https://media.disneyanimation.com/uploads/production/publication_asset/48/asset/s2012_pbs_disney_brdf_notes_v3.pdf)
  27918. * (pdf), by Brent Burley.
  27919. *
  27920. * @augments Material
  27921. * @demo scenes/material-browser.html#MeshStandardMaterial
  27922. */
  27923. class MeshStandardMaterial extends Material {
  27924. /**
  27925. * Constructs a new mesh standard material.
  27926. *
  27927. * @param {Object} [parameters] - An object with one or more properties
  27928. * defining the material's appearance. Any property of the material
  27929. * (including any property from inherited materials) can be passed
  27930. * in here. Color values can be passed any type of value accepted
  27931. * by {@link Color#set}.
  27932. */
  27933. constructor( parameters ) {
  27934. super();
  27935. /**
  27936. * This flag can be used for type testing.
  27937. *
  27938. * @type {boolean}
  27939. * @readonly
  27940. * @default true
  27941. */
  27942. this.isMeshStandardMaterial = true;
  27943. this.type = 'MeshStandardMaterial';
  27944. this.defines = { 'STANDARD': '' };
  27945. /**
  27946. * Color of the material.
  27947. *
  27948. * @type {Color}
  27949. * @default (1,1,1)
  27950. */
  27951. this.color = new Color( 0xffffff ); // diffuse
  27952. /**
  27953. * How rough the material appears. `0.0` means a smooth mirror reflection, `1.0`
  27954. * means fully diffuse. If `roughnessMap` is also provided,
  27955. * both values are multiplied.
  27956. *
  27957. * @type {number}
  27958. * @default 1
  27959. */
  27960. this.roughness = 1.0;
  27961. /**
  27962. * How much the material is like a metal. Non-metallic materials such as wood
  27963. * or stone use `0.0`, metallic use `1.0`, with nothing (usually) in between.
  27964. * A value between `0.0` and `1.0` could be used for a rusty metal look.
  27965. * If `metalnessMap` is also provided, both values are multiplied.
  27966. *
  27967. * @type {number}
  27968. * @default 0
  27969. */
  27970. this.metalness = 0.0;
  27971. /**
  27972. * The color map. May optionally include an alpha channel, typically combined
  27973. * with {@link Material#transparent} or {@link Material#alphaTest}. The texture map
  27974. * color is modulated by the diffuse `color`.
  27975. *
  27976. * @type {?Texture}
  27977. * @default null
  27978. */
  27979. this.map = null;
  27980. /**
  27981. * The light map. Requires a second set of UVs.
  27982. *
  27983. * @type {?Texture}
  27984. * @default null
  27985. */
  27986. this.lightMap = null;
  27987. /**
  27988. * Intensity of the baked light.
  27989. *
  27990. * @type {number}
  27991. * @default 1
  27992. */
  27993. this.lightMapIntensity = 1.0;
  27994. /**
  27995. * The red channel of this texture is used as the ambient occlusion map.
  27996. * Requires a second set of UVs.
  27997. *
  27998. * @type {?Texture}
  27999. * @default null
  28000. */
  28001. this.aoMap = null;
  28002. /**
  28003. * Intensity of the ambient occlusion effect. Range is `[0,1]`, where `0`
  28004. * disables ambient occlusion. Where intensity is `1` and the AO map's
  28005. * red channel is also `1`, ambient light is fully occluded on a surface.
  28006. *
  28007. * @type {number}
  28008. * @default 1
  28009. */
  28010. this.aoMapIntensity = 1.0;
  28011. /**
  28012. * Emissive (light) color of the material, essentially a solid color
  28013. * unaffected by other lighting.
  28014. *
  28015. * @type {Color}
  28016. * @default (0,0,0)
  28017. */
  28018. this.emissive = new Color( 0x000000 );
  28019. /**
  28020. * Intensity of the emissive light. Modulates the emissive color.
  28021. *
  28022. * @type {number}
  28023. * @default 1
  28024. */
  28025. this.emissiveIntensity = 1.0;
  28026. /**
  28027. * Set emissive (glow) map. The emissive map color is modulated by the
  28028. * emissive color and the emissive intensity. If you have an emissive map,
  28029. * be sure to set the emissive color to something other than black.
  28030. *
  28031. * @type {?Texture}
  28032. * @default null
  28033. */
  28034. this.emissiveMap = null;
  28035. /**
  28036. * The texture to create a bump map. The black and white values map to the
  28037. * perceived depth in relation to the lights. Bump doesn't actually affect
  28038. * the geometry of the object, only the lighting. If a normal map is defined
  28039. * this will be ignored.
  28040. *
  28041. * @type {?Texture}
  28042. * @default null
  28043. */
  28044. this.bumpMap = null;
  28045. /**
  28046. * How much the bump map affects the material. Typical range is `[0,1]`.
  28047. *
  28048. * @type {number}
  28049. * @default 1
  28050. */
  28051. this.bumpScale = 1;
  28052. /**
  28053. * The texture to create a normal map. The RGB values affect the surface
  28054. * normal for each pixel fragment and change the way the color is lit. Normal
  28055. * maps do not change the actual shape of the surface, only the lighting. In
  28056. * case the material has a normal map authored using the left handed
  28057. * convention, the `y` component of `normalScale` should be negated to compensate
  28058. * for the different handedness.
  28059. *
  28060. * @type {?Texture}
  28061. * @default null
  28062. */
  28063. this.normalMap = null;
  28064. /**
  28065. * The type of normal map.
  28066. *
  28067. * @type {(TangentSpaceNormalMap|ObjectSpaceNormalMap)}
  28068. * @default TangentSpaceNormalMap
  28069. */
  28070. this.normalMapType = TangentSpaceNormalMap;
  28071. /**
  28072. * How much the normal map affects the material. Typical value range is `[0,1]`.
  28073. *
  28074. * @type {Vector2}
  28075. * @default (1,1)
  28076. */
  28077. this.normalScale = new Vector2( 1, 1 );
  28078. /**
  28079. * The displacement map affects the position of the mesh's vertices. Unlike
  28080. * other maps which only affect the light and shade of the material the
  28081. * displaced vertices can cast shadows, block other objects, and otherwise
  28082. * act as real geometry. The displacement texture is an image where the value
  28083. * of each pixel (white being the highest) is mapped against, and
  28084. * repositions, the vertices of the mesh.
  28085. *
  28086. * @type {?Texture}
  28087. * @default null
  28088. */
  28089. this.displacementMap = null;
  28090. /**
  28091. * How much the displacement map affects the mesh (where black is no
  28092. * displacement, and white is maximum displacement). Without a displacement
  28093. * map set, this value is not applied.
  28094. *
  28095. * @type {number}
  28096. * @default 0
  28097. */
  28098. this.displacementScale = 1;
  28099. /**
  28100. * The offset of the displacement map's values on the mesh's vertices.
  28101. * The bias is added to the scaled sample of the displacement map.
  28102. * Without a displacement map set, this value is not applied.
  28103. *
  28104. * @type {number}
  28105. * @default 0
  28106. */
  28107. this.displacementBias = 0;
  28108. /**
  28109. * The green channel of this texture is used to alter the roughness of the
  28110. * material.
  28111. *
  28112. * @type {?Texture}
  28113. * @default null
  28114. */
  28115. this.roughnessMap = null;
  28116. /**
  28117. * The blue channel of this texture is used to alter the metalness of the
  28118. * material.
  28119. *
  28120. * @type {?Texture}
  28121. * @default null
  28122. */
  28123. this.metalnessMap = null;
  28124. /**
  28125. * The alpha map is a grayscale texture that controls the opacity across the
  28126. * surface (black: fully transparent; white: fully opaque).
  28127. *
  28128. * Only the color of the texture is used, ignoring the alpha channel if one
  28129. * exists. For RGB and RGBA textures, the renderer will use the green channel
  28130. * when sampling this texture due to the extra bit of precision provided for
  28131. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  28132. * luminance/alpha textures will also still work as expected.
  28133. *
  28134. * @type {?Texture}
  28135. * @default null
  28136. */
  28137. this.alphaMap = null;
  28138. /**
  28139. * The environment map. To ensure a physically correct rendering, environment maps
  28140. * are internally pre-processed with {@link PMREMGenerator}.
  28141. *
  28142. * @type {?Texture}
  28143. * @default null
  28144. */
  28145. this.envMap = null;
  28146. /**
  28147. * The rotation of the environment map in radians.
  28148. *
  28149. * @type {Euler}
  28150. * @default (0,0,0)
  28151. */
  28152. this.envMapRotation = new Euler();
  28153. /**
  28154. * Scales the effect of the environment map by multiplying its color.
  28155. *
  28156. * @type {number}
  28157. * @default 1
  28158. */
  28159. this.envMapIntensity = 1.0;
  28160. /**
  28161. * Renders the geometry as a wireframe.
  28162. *
  28163. * @type {boolean}
  28164. * @default false
  28165. */
  28166. this.wireframe = false;
  28167. /**
  28168. * Controls the thickness of the wireframe.
  28169. *
  28170. * Can only be used with {@link SVGRenderer}.
  28171. *
  28172. * @type {number}
  28173. * @default 1
  28174. */
  28175. this.wireframeLinewidth = 1;
  28176. /**
  28177. * Defines appearance of wireframe ends.
  28178. *
  28179. * Can only be used with {@link SVGRenderer}.
  28180. *
  28181. * @type {('round'|'bevel'|'miter')}
  28182. * @default 'round'
  28183. */
  28184. this.wireframeLinecap = 'round';
  28185. /**
  28186. * Defines appearance of wireframe joints.
  28187. *
  28188. * Can only be used with {@link SVGRenderer}.
  28189. *
  28190. * @type {('round'|'bevel'|'miter')}
  28191. * @default 'round'
  28192. */
  28193. this.wireframeLinejoin = 'round';
  28194. /**
  28195. * Whether the material is rendered with flat shading or not.
  28196. *
  28197. * @type {boolean}
  28198. * @default false
  28199. */
  28200. this.flatShading = false;
  28201. /**
  28202. * Whether the material is affected by fog or not.
  28203. *
  28204. * @type {boolean}
  28205. * @default true
  28206. */
  28207. this.fog = true;
  28208. this.setValues( parameters );
  28209. }
  28210. copy( source ) {
  28211. super.copy( source );
  28212. this.defines = { 'STANDARD': '' };
  28213. this.color.copy( source.color );
  28214. this.roughness = source.roughness;
  28215. this.metalness = source.metalness;
  28216. this.map = source.map;
  28217. this.lightMap = source.lightMap;
  28218. this.lightMapIntensity = source.lightMapIntensity;
  28219. this.aoMap = source.aoMap;
  28220. this.aoMapIntensity = source.aoMapIntensity;
  28221. this.emissive.copy( source.emissive );
  28222. this.emissiveMap = source.emissiveMap;
  28223. this.emissiveIntensity = source.emissiveIntensity;
  28224. this.bumpMap = source.bumpMap;
  28225. this.bumpScale = source.bumpScale;
  28226. this.normalMap = source.normalMap;
  28227. this.normalMapType = source.normalMapType;
  28228. this.normalScale.copy( source.normalScale );
  28229. this.displacementMap = source.displacementMap;
  28230. this.displacementScale = source.displacementScale;
  28231. this.displacementBias = source.displacementBias;
  28232. this.roughnessMap = source.roughnessMap;
  28233. this.metalnessMap = source.metalnessMap;
  28234. this.alphaMap = source.alphaMap;
  28235. this.envMap = source.envMap;
  28236. this.envMapRotation.copy( source.envMapRotation );
  28237. this.envMapIntensity = source.envMapIntensity;
  28238. this.wireframe = source.wireframe;
  28239. this.wireframeLinewidth = source.wireframeLinewidth;
  28240. this.wireframeLinecap = source.wireframeLinecap;
  28241. this.wireframeLinejoin = source.wireframeLinejoin;
  28242. this.flatShading = source.flatShading;
  28243. this.fog = source.fog;
  28244. return this;
  28245. }
  28246. }
  28247. /**
  28248. * An extension of the {@link MeshStandardMaterial}, providing more advanced
  28249. * physically-based rendering properties:
  28250. *
  28251. * - Anisotropy: Ability to represent the anisotropic property of materials
  28252. * as observable with brushed metals.
  28253. * - Clearcoat: Some materials — like car paints, carbon fiber, and wet surfaces — require
  28254. * a clear, reflective layer on top of another layer that may be irregular or rough.
  28255. * Clearcoat approximates this effect, without the need for a separate transparent surface.
  28256. * - Iridescence: Allows to render the effect where hue varies depending on the viewing
  28257. * angle and illumination angle. This can be seen on soap bubbles, oil films, or on the
  28258. * wings of many insects.
  28259. * - Physically-based transparency: One limitation of {@link Material#opacity} is that highly
  28260. * transparent materials are less reflective. Physically-based transmission provides a more
  28261. * realistic option for thin, transparent surfaces like glass.
  28262. * - Advanced reflectivity: More flexible reflectivity for non-metallic materials.
  28263. * - Sheen: Can be used for representing cloth and fabric materials.
  28264. *
  28265. * As a result of these complex shading features, `MeshPhysicalMaterial` has a
  28266. * higher performance cost, per pixel, than other three.js materials. Most
  28267. * effects are disabled by default, and add cost as they are enabled. For
  28268. * best results, always specify an environment map when using this material.
  28269. *
  28270. * @augments MeshStandardMaterial
  28271. * @demo scenes/material-browser.html#MeshPhysicalMaterial
  28272. */
  28273. class MeshPhysicalMaterial extends MeshStandardMaterial {
  28274. /**
  28275. * Constructs a new mesh physical material.
  28276. *
  28277. * @param {Object} [parameters] - An object with one or more properties
  28278. * defining the material's appearance. Any property of the material
  28279. * (including any property from inherited materials) can be passed
  28280. * in here. Color values can be passed any type of value accepted
  28281. * by {@link Color#set}.
  28282. */
  28283. constructor( parameters ) {
  28284. super();
  28285. /**
  28286. * This flag can be used for type testing.
  28287. *
  28288. * @type {boolean}
  28289. * @readonly
  28290. * @default true
  28291. */
  28292. this.isMeshPhysicalMaterial = true;
  28293. this.defines = {
  28294. 'STANDARD': '',
  28295. 'PHYSICAL': ''
  28296. };
  28297. this.type = 'MeshPhysicalMaterial';
  28298. /**
  28299. * The rotation of the anisotropy in tangent, bitangent space, measured in radians
  28300. * counter-clockwise from the tangent. When `anisotropyMap` is present, this
  28301. * property provides additional rotation to the vectors in the texture.
  28302. *
  28303. * @type {number}
  28304. * @default 1
  28305. */
  28306. this.anisotropyRotation = 0;
  28307. /**
  28308. * Red and green channels represent the anisotropy direction in `[-1, 1]` tangent,
  28309. * bitangent space, to be rotated by `anisotropyRotation`. The blue channel
  28310. * contains strength as `[0, 1]` to be multiplied by `anisotropy`.
  28311. *
  28312. * @type {?Texture}
  28313. * @default null
  28314. */
  28315. this.anisotropyMap = null;
  28316. /**
  28317. * The red channel of this texture is multiplied against `clearcoat`,
  28318. * for per-pixel control over a coating's intensity.
  28319. *
  28320. * @type {?Texture}
  28321. * @default null
  28322. */
  28323. this.clearcoatMap = null;
  28324. /**
  28325. * Roughness of the clear coat layer, from `0.0` to `1.0`.
  28326. *
  28327. * @type {number}
  28328. * @default 0
  28329. */
  28330. this.clearcoatRoughness = 0.0;
  28331. /**
  28332. * The green channel of this texture is multiplied against
  28333. * `clearcoatRoughness`, for per-pixel control over a coating's roughness.
  28334. *
  28335. * @type {?Texture}
  28336. * @default null
  28337. */
  28338. this.clearcoatRoughnessMap = null;
  28339. /**
  28340. * How much `clearcoatNormalMap` affects the clear coat layer, from
  28341. * `(0,0)` to `(1,1)`.
  28342. *
  28343. * @type {Vector2}
  28344. * @default (1,1)
  28345. */
  28346. this.clearcoatNormalScale = new Vector2( 1, 1 );
  28347. /**
  28348. * Can be used to enable independent normals for the clear coat layer.
  28349. *
  28350. * @type {?Texture}
  28351. * @default null
  28352. */
  28353. this.clearcoatNormalMap = null;
  28354. /**
  28355. * Index-of-refraction for non-metallic materials, from `1.0` to `2.333`.
  28356. *
  28357. * @type {number}
  28358. * @default 1.5
  28359. */
  28360. this.ior = 1.5;
  28361. /**
  28362. * Degree of reflectivity, from `0.0` to `1.0`. Default is `0.5`, which
  28363. * corresponds to an index-of-refraction of `1.5`.
  28364. *
  28365. * This models the reflectivity of non-metallic materials. It has no effect
  28366. * when `metalness` is `1.0`
  28367. *
  28368. * @name MeshPhysicalMaterial#reflectivity
  28369. * @type {number}
  28370. * @default 0.5
  28371. */
  28372. Object.defineProperty( this, 'reflectivity', {
  28373. get: function () {
  28374. return ( clamp( 2.5 * ( this.ior - 1 ) / ( this.ior + 1 ), 0, 1 ) );
  28375. },
  28376. set: function ( reflectivity ) {
  28377. this.ior = ( 1 + 0.4 * reflectivity ) / ( 1 - 0.4 * reflectivity );
  28378. }
  28379. } );
  28380. /**
  28381. * The red channel of this texture is multiplied against `iridescence`, for per-pixel
  28382. * control over iridescence.
  28383. *
  28384. * @type {?Texture}
  28385. * @default null
  28386. */
  28387. this.iridescenceMap = null;
  28388. /**
  28389. * Strength of the iridescence RGB color shift effect, represented by an index-of-refraction.
  28390. * Between `1.0` to `2.333`.
  28391. *
  28392. * @type {number}
  28393. * @default 1.3
  28394. */
  28395. this.iridescenceIOR = 1.3;
  28396. /**
  28397. *Array of exactly 2 elements, specifying minimum and maximum thickness of the iridescence layer.
  28398. Thickness of iridescence layer has an equivalent effect of the one `thickness` has on `ior`.
  28399. *
  28400. * @type {Array<number,number>}
  28401. * @default [100,400]
  28402. */
  28403. this.iridescenceThicknessRange = [ 100, 400 ];
  28404. /**
  28405. * A texture that defines the thickness of the iridescence layer, stored in the green channel.
  28406. * Minimum and maximum values of thickness are defined by `iridescenceThicknessRange` array:
  28407. * - `0.0` in the green channel will result in thickness equal to first element of the array.
  28408. * - `1.0` in the green channel will result in thickness equal to second element of the array.
  28409. * - Values in-between will linearly interpolate between the elements of the array.
  28410. *
  28411. * @type {?Texture}
  28412. * @default null
  28413. */
  28414. this.iridescenceThicknessMap = null;
  28415. /**
  28416. * The sheen tint.
  28417. *
  28418. * @type {Color}
  28419. * @default (0,0,0)
  28420. */
  28421. this.sheenColor = new Color( 0x000000 );
  28422. /**
  28423. * The RGB channels of this texture are multiplied against `sheenColor`, for per-pixel control
  28424. * over sheen tint.
  28425. *
  28426. * @type {?Texture}
  28427. * @default null
  28428. */
  28429. this.sheenColorMap = null;
  28430. /**
  28431. * Roughness of the sheen layer, from `0.0` to `1.0`.
  28432. *
  28433. * @type {number}
  28434. * @default 1
  28435. */
  28436. this.sheenRoughness = 1.0;
  28437. /**
  28438. * The alpha channel of this texture is multiplied against `sheenRoughness`, for per-pixel control
  28439. * over sheen roughness.
  28440. *
  28441. * @type {?Texture}
  28442. * @default null
  28443. */
  28444. this.sheenRoughnessMap = null;
  28445. /**
  28446. * The red channel of this texture is multiplied against `transmission`, for per-pixel control over
  28447. * optical transparency.
  28448. *
  28449. * @type {?Texture}
  28450. * @default null
  28451. */
  28452. this.transmissionMap = null;
  28453. /**
  28454. * The thickness of the volume beneath the surface. The value is given in the
  28455. * coordinate space of the mesh. If the value is `0` the material is
  28456. * thin-walled. Otherwise the material is a volume boundary.
  28457. *
  28458. * @type {number}
  28459. * @default 0
  28460. */
  28461. this.thickness = 0;
  28462. /**
  28463. * A texture that defines the thickness, stored in the green channel. This will
  28464. * be multiplied by `thickness`.
  28465. *
  28466. * @type {?Texture}
  28467. * @default null
  28468. */
  28469. this.thicknessMap = null;
  28470. /**
  28471. * Density of the medium given as the average distance that light travels in
  28472. * the medium before interacting with a particle. The value is given in world
  28473. * space units, and must be greater than zero.
  28474. *
  28475. * @type {number}
  28476. * @default Infinity
  28477. */
  28478. this.attenuationDistance = Infinity;
  28479. /**
  28480. * The color that white light turns into due to absorption when reaching the
  28481. * attenuation distance.
  28482. *
  28483. * @type {Color}
  28484. * @default (1,1,1)
  28485. */
  28486. this.attenuationColor = new Color( 1, 1, 1 );
  28487. /**
  28488. * A float that scales the amount of specular reflection for non-metals only.
  28489. * When set to zero, the model is effectively Lambertian. From `0.0` to `1.0`.
  28490. *
  28491. * @type {number}
  28492. * @default 1
  28493. */
  28494. this.specularIntensity = 1.0;
  28495. /**
  28496. * The alpha channel of this texture is multiplied against `specularIntensity`,
  28497. * for per-pixel control over specular intensity.
  28498. *
  28499. * @type {?Texture}
  28500. * @default null
  28501. */
  28502. this.specularIntensityMap = null;
  28503. /**
  28504. * Tints the specular reflection at normal incidence for non-metals only.
  28505. *
  28506. * @type {Color}
  28507. * @default (1,1,1)
  28508. */
  28509. this.specularColor = new Color( 1, 1, 1 );
  28510. /**
  28511. * The RGB channels of this texture are multiplied against `specularColor`,
  28512. * for per-pixel control over specular color.
  28513. *
  28514. * @type {?Texture}
  28515. * @default null
  28516. */
  28517. this.specularColorMap = null;
  28518. this._anisotropy = 0;
  28519. this._clearcoat = 0;
  28520. this._dispersion = 0;
  28521. this._iridescence = 0;
  28522. this._sheen = 0.0;
  28523. this._transmission = 0;
  28524. this.setValues( parameters );
  28525. }
  28526. /**
  28527. * The anisotropy strength, from `0.0` to `1.0`.
  28528. *
  28529. * @type {number}
  28530. * @default 0
  28531. */
  28532. get anisotropy() {
  28533. return this._anisotropy;
  28534. }
  28535. set anisotropy( value ) {
  28536. if ( this._anisotropy > 0 !== value > 0 ) {
  28537. this.version ++;
  28538. }
  28539. this._anisotropy = value;
  28540. }
  28541. /**
  28542. * Represents the intensity of the clear coat layer, from `0.0` to `1.0`. Use
  28543. * clear coat related properties to enable multilayer materials that have a
  28544. * thin translucent layer over the base layer.
  28545. *
  28546. * @type {number}
  28547. * @default 0
  28548. */
  28549. get clearcoat() {
  28550. return this._clearcoat;
  28551. }
  28552. set clearcoat( value ) {
  28553. if ( this._clearcoat > 0 !== value > 0 ) {
  28554. this.version ++;
  28555. }
  28556. this._clearcoat = value;
  28557. }
  28558. /**
  28559. * The intensity of the iridescence layer, simulating RGB color shift based on the angle between
  28560. * the surface and the viewer, from `0.0` to `1.0`.
  28561. *
  28562. * @type {number}
  28563. * @default 0
  28564. */
  28565. get iridescence() {
  28566. return this._iridescence;
  28567. }
  28568. set iridescence( value ) {
  28569. if ( this._iridescence > 0 !== value > 0 ) {
  28570. this.version ++;
  28571. }
  28572. this._iridescence = value;
  28573. }
  28574. /**
  28575. * Defines the strength of the angular separation of colors (chromatic aberration) transmitting
  28576. * through a relatively clear volume. Any value zero or larger is valid, the typical range of
  28577. * realistic values is `[0, 1]`. This property can be only be used with transmissive objects.
  28578. *
  28579. * @type {number}
  28580. * @default 0
  28581. */
  28582. get dispersion() {
  28583. return this._dispersion;
  28584. }
  28585. set dispersion( value ) {
  28586. if ( this._dispersion > 0 !== value > 0 ) {
  28587. this.version ++;
  28588. }
  28589. this._dispersion = value;
  28590. }
  28591. /**
  28592. * The intensity of the sheen layer, from `0.0` to `1.0`.
  28593. *
  28594. * @type {number}
  28595. * @default 0
  28596. */
  28597. get sheen() {
  28598. return this._sheen;
  28599. }
  28600. set sheen( value ) {
  28601. if ( this._sheen > 0 !== value > 0 ) {
  28602. this.version ++;
  28603. }
  28604. this._sheen = value;
  28605. }
  28606. /**
  28607. * Degree of transmission (or optical transparency), from `0.0` to `1.0`.
  28608. *
  28609. * Thin, transparent or semitransparent, plastic or glass materials remain
  28610. * largely reflective even if they are fully transmissive. The transmission
  28611. * property can be used to model these materials.
  28612. *
  28613. * When transmission is non-zero, `opacity` should be set to `1`.
  28614. *
  28615. * @type {number}
  28616. * @default 0
  28617. */
  28618. get transmission() {
  28619. return this._transmission;
  28620. }
  28621. set transmission( value ) {
  28622. if ( this._transmission > 0 !== value > 0 ) {
  28623. this.version ++;
  28624. }
  28625. this._transmission = value;
  28626. }
  28627. copy( source ) {
  28628. super.copy( source );
  28629. this.defines = {
  28630. 'STANDARD': '',
  28631. 'PHYSICAL': ''
  28632. };
  28633. this.anisotropy = source.anisotropy;
  28634. this.anisotropyRotation = source.anisotropyRotation;
  28635. this.anisotropyMap = source.anisotropyMap;
  28636. this.clearcoat = source.clearcoat;
  28637. this.clearcoatMap = source.clearcoatMap;
  28638. this.clearcoatRoughness = source.clearcoatRoughness;
  28639. this.clearcoatRoughnessMap = source.clearcoatRoughnessMap;
  28640. this.clearcoatNormalMap = source.clearcoatNormalMap;
  28641. this.clearcoatNormalScale.copy( source.clearcoatNormalScale );
  28642. this.dispersion = source.dispersion;
  28643. this.ior = source.ior;
  28644. this.iridescence = source.iridescence;
  28645. this.iridescenceMap = source.iridescenceMap;
  28646. this.iridescenceIOR = source.iridescenceIOR;
  28647. this.iridescenceThicknessRange = [ ...source.iridescenceThicknessRange ];
  28648. this.iridescenceThicknessMap = source.iridescenceThicknessMap;
  28649. this.sheen = source.sheen;
  28650. this.sheenColor.copy( source.sheenColor );
  28651. this.sheenColorMap = source.sheenColorMap;
  28652. this.sheenRoughness = source.sheenRoughness;
  28653. this.sheenRoughnessMap = source.sheenRoughnessMap;
  28654. this.transmission = source.transmission;
  28655. this.transmissionMap = source.transmissionMap;
  28656. this.thickness = source.thickness;
  28657. this.thicknessMap = source.thicknessMap;
  28658. this.attenuationDistance = source.attenuationDistance;
  28659. this.attenuationColor.copy( source.attenuationColor );
  28660. this.specularIntensity = source.specularIntensity;
  28661. this.specularIntensityMap = source.specularIntensityMap;
  28662. this.specularColor.copy( source.specularColor );
  28663. this.specularColorMap = source.specularColorMap;
  28664. return this;
  28665. }
  28666. }
  28667. /**
  28668. * A material for shiny surfaces with specular highlights.
  28669. *
  28670. * The material uses a non-physically based [Blinn-Phong](https://en.wikipedia.org/wiki/Blinn-Phong_shading_model)
  28671. * model for calculating reflectance. Unlike the Lambertian model used in the
  28672. * {@link MeshLambertMaterial} this can simulate shiny surfaces with specular
  28673. * highlights (such as varnished wood). `MeshPhongMaterial` uses per-fragment shading.
  28674. *
  28675. * Performance will generally be greater when using this material over the
  28676. * {@link MeshStandardMaterial} or {@link MeshPhysicalMaterial}, at the cost of
  28677. * some graphical accuracy.
  28678. *
  28679. * @augments Material
  28680. * @demo scenes/material-browser.html#MeshPhongMaterial
  28681. */
  28682. class MeshPhongMaterial extends Material {
  28683. /**
  28684. * Constructs a new mesh phong material.
  28685. *
  28686. * @param {Object} [parameters] - An object with one or more properties
  28687. * defining the material's appearance. Any property of the material
  28688. * (including any property from inherited materials) can be passed
  28689. * in here. Color values can be passed any type of value accepted
  28690. * by {@link Color#set}.
  28691. */
  28692. constructor( parameters ) {
  28693. super();
  28694. /**
  28695. * This flag can be used for type testing.
  28696. *
  28697. * @type {boolean}
  28698. * @readonly
  28699. * @default true
  28700. */
  28701. this.isMeshPhongMaterial = true;
  28702. this.type = 'MeshPhongMaterial';
  28703. /**
  28704. * Color of the material.
  28705. *
  28706. * @type {Color}
  28707. * @default (1,1,1)
  28708. */
  28709. this.color = new Color( 0xffffff ); // diffuse
  28710. /**
  28711. * Specular color of the material. The default color is set to `0x111111` (very dark grey)
  28712. *
  28713. * This defines how shiny the material is and the color of its shine.
  28714. *
  28715. * @type {Color}
  28716. */
  28717. this.specular = new Color( 0x111111 );
  28718. /**
  28719. * How shiny the specular highlight is; a higher value gives a sharper highlight.
  28720. *
  28721. * @type {number}
  28722. * @default 30
  28723. */
  28724. this.shininess = 30;
  28725. /**
  28726. * The color map. May optionally include an alpha channel, typically combined
  28727. * with {@link Material#transparent} or {@link Material#alphaTest}. The texture map
  28728. * color is modulated by the diffuse `color`.
  28729. *
  28730. * @type {?Texture}
  28731. * @default null
  28732. */
  28733. this.map = null;
  28734. /**
  28735. * The light map. Requires a second set of UVs.
  28736. *
  28737. * @type {?Texture}
  28738. * @default null
  28739. */
  28740. this.lightMap = null;
  28741. /**
  28742. * Intensity of the baked light.
  28743. *
  28744. * @type {number}
  28745. * @default 1
  28746. */
  28747. this.lightMapIntensity = 1.0;
  28748. /**
  28749. * The red channel of this texture is used as the ambient occlusion map.
  28750. * Requires a second set of UVs.
  28751. *
  28752. * @type {?Texture}
  28753. * @default null
  28754. */
  28755. this.aoMap = null;
  28756. /**
  28757. * Intensity of the ambient occlusion effect. Range is `[0,1]`, where `0`
  28758. * disables ambient occlusion. Where intensity is `1` and the AO map's
  28759. * red channel is also `1`, ambient light is fully occluded on a surface.
  28760. *
  28761. * @type {number}
  28762. * @default 1
  28763. */
  28764. this.aoMapIntensity = 1.0;
  28765. /**
  28766. * Emissive (light) color of the material, essentially a solid color
  28767. * unaffected by other lighting.
  28768. *
  28769. * @type {Color}
  28770. * @default (0,0,0)
  28771. */
  28772. this.emissive = new Color( 0x000000 );
  28773. /**
  28774. * Intensity of the emissive light. Modulates the emissive color.
  28775. *
  28776. * @type {number}
  28777. * @default 1
  28778. */
  28779. this.emissiveIntensity = 1.0;
  28780. /**
  28781. * Set emissive (glow) map. The emissive map color is modulated by the
  28782. * emissive color and the emissive intensity. If you have an emissive map,
  28783. * be sure to set the emissive color to something other than black.
  28784. *
  28785. * @type {?Texture}
  28786. * @default null
  28787. */
  28788. this.emissiveMap = null;
  28789. /**
  28790. * The texture to create a bump map. The black and white values map to the
  28791. * perceived depth in relation to the lights. Bump doesn't actually affect
  28792. * the geometry of the object, only the lighting. If a normal map is defined
  28793. * this will be ignored.
  28794. *
  28795. * @type {?Texture}
  28796. * @default null
  28797. */
  28798. this.bumpMap = null;
  28799. /**
  28800. * How much the bump map affects the material. Typical range is `[0,1]`.
  28801. *
  28802. * @type {number}
  28803. * @default 1
  28804. */
  28805. this.bumpScale = 1;
  28806. /**
  28807. * The texture to create a normal map. The RGB values affect the surface
  28808. * normal for each pixel fragment and change the way the color is lit. Normal
  28809. * maps do not change the actual shape of the surface, only the lighting. In
  28810. * case the material has a normal map authored using the left handed
  28811. * convention, the `y` component of `normalScale` should be negated to compensate
  28812. * for the different handedness.
  28813. *
  28814. * @type {?Texture}
  28815. * @default null
  28816. */
  28817. this.normalMap = null;
  28818. /**
  28819. * The type of normal map.
  28820. *
  28821. * @type {(TangentSpaceNormalMap|ObjectSpaceNormalMap)}
  28822. * @default TangentSpaceNormalMap
  28823. */
  28824. this.normalMapType = TangentSpaceNormalMap;
  28825. /**
  28826. * How much the normal map affects the material. Typical value range is `[0,1]`.
  28827. *
  28828. * @type {Vector2}
  28829. * @default (1,1)
  28830. */
  28831. this.normalScale = new Vector2( 1, 1 );
  28832. /**
  28833. * The displacement map affects the position of the mesh's vertices. Unlike
  28834. * other maps which only affect the light and shade of the material the
  28835. * displaced vertices can cast shadows, block other objects, and otherwise
  28836. * act as real geometry. The displacement texture is an image where the value
  28837. * of each pixel (white being the highest) is mapped against, and
  28838. * repositions, the vertices of the mesh.
  28839. *
  28840. * @type {?Texture}
  28841. * @default null
  28842. */
  28843. this.displacementMap = null;
  28844. /**
  28845. * How much the displacement map affects the mesh (where black is no
  28846. * displacement, and white is maximum displacement). Without a displacement
  28847. * map set, this value is not applied.
  28848. *
  28849. * @type {number}
  28850. * @default 0
  28851. */
  28852. this.displacementScale = 1;
  28853. /**
  28854. * The offset of the displacement map's values on the mesh's vertices.
  28855. * The bias is added to the scaled sample of the displacement map.
  28856. * Without a displacement map set, this value is not applied.
  28857. *
  28858. * @type {number}
  28859. * @default 0
  28860. */
  28861. this.displacementBias = 0;
  28862. /**
  28863. * The specular map value affects both how much the specular surface
  28864. * highlight contributes and how much of the environment map affects the
  28865. * surface.
  28866. *
  28867. * @type {?Texture}
  28868. * @default null
  28869. */
  28870. this.specularMap = null;
  28871. /**
  28872. * The alpha map is a grayscale texture that controls the opacity across the
  28873. * surface (black: fully transparent; white: fully opaque).
  28874. *
  28875. * Only the color of the texture is used, ignoring the alpha channel if one
  28876. * exists. For RGB and RGBA textures, the renderer will use the green channel
  28877. * when sampling this texture due to the extra bit of precision provided for
  28878. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  28879. * luminance/alpha textures will also still work as expected.
  28880. *
  28881. * @type {?Texture}
  28882. * @default null
  28883. */
  28884. this.alphaMap = null;
  28885. /**
  28886. * The environment map.
  28887. *
  28888. * @type {?Texture}
  28889. * @default null
  28890. */
  28891. this.envMap = null;
  28892. /**
  28893. * The rotation of the environment map in radians.
  28894. *
  28895. * @type {Euler}
  28896. * @default (0,0,0)
  28897. */
  28898. this.envMapRotation = new Euler();
  28899. /**
  28900. * How to combine the result of the surface's color with the environment map, if any.
  28901. *
  28902. * When set to `MixOperation`, the {@link MeshBasicMaterial#reflectivity} is used to
  28903. * blend between the two colors.
  28904. *
  28905. * @type {(MultiplyOperation|MixOperation|AddOperation)}
  28906. * @default MultiplyOperation
  28907. */
  28908. this.combine = MultiplyOperation;
  28909. /**
  28910. * How much the environment map affects the surface.
  28911. * The valid range is between `0` (no reflections) and `1` (full reflections).
  28912. *
  28913. * @type {number}
  28914. * @default 1
  28915. */
  28916. this.reflectivity = 1;
  28917. /**
  28918. * The index of refraction (IOR) of air (approximately 1) divided by the
  28919. * index of refraction of the material. It is used with environment mapping
  28920. * modes {@link CubeRefractionMapping} and {@link EquirectangularRefractionMapping}.
  28921. * The refraction ratio should not exceed `1`.
  28922. *
  28923. * @type {number}
  28924. * @default 0.98
  28925. */
  28926. this.refractionRatio = 0.98;
  28927. /**
  28928. * Renders the geometry as a wireframe.
  28929. *
  28930. * @type {boolean}
  28931. * @default false
  28932. */
  28933. this.wireframe = false;
  28934. /**
  28935. * Controls the thickness of the wireframe.
  28936. *
  28937. * Can only be used with {@link SVGRenderer}.
  28938. *
  28939. * @type {number}
  28940. * @default 1
  28941. */
  28942. this.wireframeLinewidth = 1;
  28943. /**
  28944. * Defines appearance of wireframe ends.
  28945. *
  28946. * Can only be used with {@link SVGRenderer}.
  28947. *
  28948. * @type {('round'|'bevel'|'miter')}
  28949. * @default 'round'
  28950. */
  28951. this.wireframeLinecap = 'round';
  28952. /**
  28953. * Defines appearance of wireframe joints.
  28954. *
  28955. * Can only be used with {@link SVGRenderer}.
  28956. *
  28957. * @type {('round'|'bevel'|'miter')}
  28958. * @default 'round'
  28959. */
  28960. this.wireframeLinejoin = 'round';
  28961. /**
  28962. * Whether the material is rendered with flat shading or not.
  28963. *
  28964. * @type {boolean}
  28965. * @default false
  28966. */
  28967. this.flatShading = false;
  28968. /**
  28969. * Whether the material is affected by fog or not.
  28970. *
  28971. * @type {boolean}
  28972. * @default true
  28973. */
  28974. this.fog = true;
  28975. this.setValues( parameters );
  28976. }
  28977. copy( source ) {
  28978. super.copy( source );
  28979. this.color.copy( source.color );
  28980. this.specular.copy( source.specular );
  28981. this.shininess = source.shininess;
  28982. this.map = source.map;
  28983. this.lightMap = source.lightMap;
  28984. this.lightMapIntensity = source.lightMapIntensity;
  28985. this.aoMap = source.aoMap;
  28986. this.aoMapIntensity = source.aoMapIntensity;
  28987. this.emissive.copy( source.emissive );
  28988. this.emissiveMap = source.emissiveMap;
  28989. this.emissiveIntensity = source.emissiveIntensity;
  28990. this.bumpMap = source.bumpMap;
  28991. this.bumpScale = source.bumpScale;
  28992. this.normalMap = source.normalMap;
  28993. this.normalMapType = source.normalMapType;
  28994. this.normalScale.copy( source.normalScale );
  28995. this.displacementMap = source.displacementMap;
  28996. this.displacementScale = source.displacementScale;
  28997. this.displacementBias = source.displacementBias;
  28998. this.specularMap = source.specularMap;
  28999. this.alphaMap = source.alphaMap;
  29000. this.envMap = source.envMap;
  29001. this.envMapRotation.copy( source.envMapRotation );
  29002. this.combine = source.combine;
  29003. this.reflectivity = source.reflectivity;
  29004. this.refractionRatio = source.refractionRatio;
  29005. this.wireframe = source.wireframe;
  29006. this.wireframeLinewidth = source.wireframeLinewidth;
  29007. this.wireframeLinecap = source.wireframeLinecap;
  29008. this.wireframeLinejoin = source.wireframeLinejoin;
  29009. this.flatShading = source.flatShading;
  29010. this.fog = source.fog;
  29011. return this;
  29012. }
  29013. }
  29014. /**
  29015. * A material implementing toon shading.
  29016. *
  29017. * @augments Material
  29018. * @demo scenes/material-browser.html#MeshToonMaterial
  29019. */
  29020. class MeshToonMaterial extends Material {
  29021. /**
  29022. * Constructs a new mesh toon material.
  29023. *
  29024. * @param {Object} [parameters] - An object with one or more properties
  29025. * defining the material's appearance. Any property of the material
  29026. * (including any property from inherited materials) can be passed
  29027. * in here. Color values can be passed any type of value accepted
  29028. * by {@link Color#set}.
  29029. */
  29030. constructor( parameters ) {
  29031. super();
  29032. /**
  29033. * This flag can be used for type testing.
  29034. *
  29035. * @type {boolean}
  29036. * @readonly
  29037. * @default true
  29038. */
  29039. this.isMeshToonMaterial = true;
  29040. this.defines = { 'TOON': '' };
  29041. this.type = 'MeshToonMaterial';
  29042. /**
  29043. * Color of the material.
  29044. *
  29045. * @type {Color}
  29046. * @default (1,1,1)
  29047. */
  29048. this.color = new Color( 0xffffff );
  29049. /**
  29050. * The color map. May optionally include an alpha channel, typically combined
  29051. * with {@link Material#transparent} or {@link Material#alphaTest}. The texture map
  29052. * color is modulated by the diffuse `color`.
  29053. *
  29054. * @type {?Texture}
  29055. * @default null
  29056. */
  29057. this.map = null;
  29058. /**
  29059. * Gradient map for toon shading. It's required to set
  29060. * {@link Texture#minFilter} and {@link Texture#magFilter} to {@linkNearestFilter}
  29061. * when using this type of texture.
  29062. *
  29063. * @type {?Texture}
  29064. * @default null
  29065. */
  29066. this.gradientMap = null;
  29067. /**
  29068. * The light map. Requires a second set of UVs.
  29069. *
  29070. * @type {?Texture}
  29071. * @default null
  29072. */
  29073. this.lightMap = null;
  29074. /**
  29075. * Intensity of the baked light.
  29076. *
  29077. * @type {number}
  29078. * @default 1
  29079. */
  29080. this.lightMapIntensity = 1.0;
  29081. /**
  29082. * The red channel of this texture is used as the ambient occlusion map.
  29083. * Requires a second set of UVs.
  29084. *
  29085. * @type {?Texture}
  29086. * @default null
  29087. */
  29088. this.aoMap = null;
  29089. /**
  29090. * Intensity of the ambient occlusion effect. Range is `[0,1]`, where `0`
  29091. * disables ambient occlusion. Where intensity is `1` and the AO map's
  29092. * red channel is also `1`, ambient light is fully occluded on a surface.
  29093. *
  29094. * @type {number}
  29095. * @default 1
  29096. */
  29097. this.aoMapIntensity = 1.0;
  29098. /**
  29099. * Emissive (light) color of the material, essentially a solid color
  29100. * unaffected by other lighting.
  29101. *
  29102. * @type {Color}
  29103. * @default (0,0,0)
  29104. */
  29105. this.emissive = new Color( 0x000000 );
  29106. /**
  29107. * Intensity of the emissive light. Modulates the emissive color.
  29108. *
  29109. * @type {number}
  29110. * @default 1
  29111. */
  29112. this.emissiveIntensity = 1.0;
  29113. /**
  29114. * Set emissive (glow) map. The emissive map color is modulated by the
  29115. * emissive color and the emissive intensity. If you have an emissive map,
  29116. * be sure to set the emissive color to something other than black.
  29117. *
  29118. * @type {?Texture}
  29119. * @default null
  29120. */
  29121. this.emissiveMap = null;
  29122. /**
  29123. * The texture to create a bump map. The black and white values map to the
  29124. * perceived depth in relation to the lights. Bump doesn't actually affect
  29125. * the geometry of the object, only the lighting. If a normal map is defined
  29126. * this will be ignored.
  29127. *
  29128. * @type {?Texture}
  29129. * @default null
  29130. */
  29131. this.bumpMap = null;
  29132. /**
  29133. * How much the bump map affects the material. Typical range is `[0,1]`.
  29134. *
  29135. * @type {number}
  29136. * @default 1
  29137. */
  29138. this.bumpScale = 1;
  29139. /**
  29140. * The texture to create a normal map. The RGB values affect the surface
  29141. * normal for each pixel fragment and change the way the color is lit. Normal
  29142. * maps do not change the actual shape of the surface, only the lighting. In
  29143. * case the material has a normal map authored using the left handed
  29144. * convention, the `y` component of `normalScale` should be negated to compensate
  29145. * for the different handedness.
  29146. *
  29147. * @type {?Texture}
  29148. * @default null
  29149. */
  29150. this.normalMap = null;
  29151. /**
  29152. * The type of normal map.
  29153. *
  29154. * @type {(TangentSpaceNormalMap|ObjectSpaceNormalMap)}
  29155. * @default TangentSpaceNormalMap
  29156. */
  29157. this.normalMapType = TangentSpaceNormalMap;
  29158. /**
  29159. * How much the normal map affects the material. Typical value range is `[0,1]`.
  29160. *
  29161. * @type {Vector2}
  29162. * @default (1,1)
  29163. */
  29164. this.normalScale = new Vector2( 1, 1 );
  29165. /**
  29166. * The displacement map affects the position of the mesh's vertices. Unlike
  29167. * other maps which only affect the light and shade of the material the
  29168. * displaced vertices can cast shadows, block other objects, and otherwise
  29169. * act as real geometry. The displacement texture is an image where the value
  29170. * of each pixel (white being the highest) is mapped against, and
  29171. * repositions, the vertices of the mesh.
  29172. *
  29173. * @type {?Texture}
  29174. * @default null
  29175. */
  29176. this.displacementMap = null;
  29177. /**
  29178. * How much the displacement map affects the mesh (where black is no
  29179. * displacement, and white is maximum displacement). Without a displacement
  29180. * map set, this value is not applied.
  29181. *
  29182. * @type {number}
  29183. * @default 0
  29184. */
  29185. this.displacementScale = 1;
  29186. /**
  29187. * The offset of the displacement map's values on the mesh's vertices.
  29188. * The bias is added to the scaled sample of the displacement map.
  29189. * Without a displacement map set, this value is not applied.
  29190. *
  29191. * @type {number}
  29192. * @default 0
  29193. */
  29194. this.displacementBias = 0;
  29195. /**
  29196. * The alpha map is a grayscale texture that controls the opacity across the
  29197. * surface (black: fully transparent; white: fully opaque).
  29198. *
  29199. * Only the color of the texture is used, ignoring the alpha channel if one
  29200. * exists. For RGB and RGBA textures, the renderer will use the green channel
  29201. * when sampling this texture due to the extra bit of precision provided for
  29202. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  29203. * luminance/alpha textures will also still work as expected.
  29204. *
  29205. * @type {?Texture}
  29206. * @default null
  29207. */
  29208. this.alphaMap = null;
  29209. /**
  29210. * Renders the geometry as a wireframe.
  29211. *
  29212. * @type {boolean}
  29213. * @default false
  29214. */
  29215. this.wireframe = false;
  29216. /**
  29217. * Controls the thickness of the wireframe.
  29218. *
  29219. * Can only be used with {@link SVGRenderer}.
  29220. *
  29221. * @type {number}
  29222. * @default 1
  29223. */
  29224. this.wireframeLinewidth = 1;
  29225. /**
  29226. * Defines appearance of wireframe ends.
  29227. *
  29228. * Can only be used with {@link SVGRenderer}.
  29229. *
  29230. * @type {('round'|'bevel'|'miter')}
  29231. * @default 'round'
  29232. */
  29233. this.wireframeLinecap = 'round';
  29234. /**
  29235. * Defines appearance of wireframe joints.
  29236. *
  29237. * Can only be used with {@link SVGRenderer}.
  29238. *
  29239. * @type {('round'|'bevel'|'miter')}
  29240. * @default 'round'
  29241. */
  29242. this.wireframeLinejoin = 'round';
  29243. /**
  29244. * Whether the material is affected by fog or not.
  29245. *
  29246. * @type {boolean}
  29247. * @default true
  29248. */
  29249. this.fog = true;
  29250. this.setValues( parameters );
  29251. }
  29252. copy( source ) {
  29253. super.copy( source );
  29254. this.color.copy( source.color );
  29255. this.map = source.map;
  29256. this.gradientMap = source.gradientMap;
  29257. this.lightMap = source.lightMap;
  29258. this.lightMapIntensity = source.lightMapIntensity;
  29259. this.aoMap = source.aoMap;
  29260. this.aoMapIntensity = source.aoMapIntensity;
  29261. this.emissive.copy( source.emissive );
  29262. this.emissiveMap = source.emissiveMap;
  29263. this.emissiveIntensity = source.emissiveIntensity;
  29264. this.bumpMap = source.bumpMap;
  29265. this.bumpScale = source.bumpScale;
  29266. this.normalMap = source.normalMap;
  29267. this.normalMapType = source.normalMapType;
  29268. this.normalScale.copy( source.normalScale );
  29269. this.displacementMap = source.displacementMap;
  29270. this.displacementScale = source.displacementScale;
  29271. this.displacementBias = source.displacementBias;
  29272. this.alphaMap = source.alphaMap;
  29273. this.wireframe = source.wireframe;
  29274. this.wireframeLinewidth = source.wireframeLinewidth;
  29275. this.wireframeLinecap = source.wireframeLinecap;
  29276. this.wireframeLinejoin = source.wireframeLinejoin;
  29277. this.fog = source.fog;
  29278. return this;
  29279. }
  29280. }
  29281. /**
  29282. * A material that maps the normal vectors to RGB colors.
  29283. *
  29284. * @augments Material
  29285. * @demo scenes/material-browser.html#MeshNormalMaterial
  29286. */
  29287. class MeshNormalMaterial extends Material {
  29288. /**
  29289. * Constructs a new mesh normal material.
  29290. *
  29291. * @param {Object} [parameters] - An object with one or more properties
  29292. * defining the material's appearance. Any property of the material
  29293. * (including any property from inherited materials) can be passed
  29294. * in here. Color values can be passed any type of value accepted
  29295. * by {@link Color#set}.
  29296. */
  29297. constructor( parameters ) {
  29298. super();
  29299. /**
  29300. * This flag can be used for type testing.
  29301. *
  29302. * @type {boolean}
  29303. * @readonly
  29304. * @default true
  29305. */
  29306. this.isMeshNormalMaterial = true;
  29307. this.type = 'MeshNormalMaterial';
  29308. /**
  29309. * The texture to create a bump map. The black and white values map to the
  29310. * perceived depth in relation to the lights. Bump doesn't actually affect
  29311. * the geometry of the object, only the lighting. If a normal map is defined
  29312. * this will be ignored.
  29313. *
  29314. * @type {?Texture}
  29315. * @default null
  29316. */
  29317. this.bumpMap = null;
  29318. /**
  29319. * How much the bump map affects the material. Typical range is `[0,1]`.
  29320. *
  29321. * @type {number}
  29322. * @default 1
  29323. */
  29324. this.bumpScale = 1;
  29325. /**
  29326. * The texture to create a normal map. The RGB values affect the surface
  29327. * normal for each pixel fragment and change the way the color is lit. Normal
  29328. * maps do not change the actual shape of the surface, only the lighting. In
  29329. * case the material has a normal map authored using the left handed
  29330. * convention, the `y` component of `normalScale` should be negated to compensate
  29331. * for the different handedness.
  29332. *
  29333. * @type {?Texture}
  29334. * @default null
  29335. */
  29336. this.normalMap = null;
  29337. /**
  29338. * The type of normal map.
  29339. *
  29340. * @type {(TangentSpaceNormalMap|ObjectSpaceNormalMap)}
  29341. * @default TangentSpaceNormalMap
  29342. */
  29343. this.normalMapType = TangentSpaceNormalMap;
  29344. /**
  29345. * How much the normal map affects the material. Typical value range is `[0,1]`.
  29346. *
  29347. * @type {Vector2}
  29348. * @default (1,1)
  29349. */
  29350. this.normalScale = new Vector2( 1, 1 );
  29351. /**
  29352. * The displacement map affects the position of the mesh's vertices. Unlike
  29353. * other maps which only affect the light and shade of the material the
  29354. * displaced vertices can cast shadows, block other objects, and otherwise
  29355. * act as real geometry. The displacement texture is an image where the value
  29356. * of each pixel (white being the highest) is mapped against, and
  29357. * repositions, the vertices of the mesh.
  29358. *
  29359. * @type {?Texture}
  29360. * @default null
  29361. */
  29362. this.displacementMap = null;
  29363. /**
  29364. * How much the displacement map affects the mesh (where black is no
  29365. * displacement, and white is maximum displacement). Without a displacement
  29366. * map set, this value is not applied.
  29367. *
  29368. * @type {number}
  29369. * @default 0
  29370. */
  29371. this.displacementScale = 1;
  29372. /**
  29373. * The offset of the displacement map's values on the mesh's vertices.
  29374. * The bias is added to the scaled sample of the displacement map.
  29375. * Without a displacement map set, this value is not applied.
  29376. *
  29377. * @type {number}
  29378. * @default 0
  29379. */
  29380. this.displacementBias = 0;
  29381. /**
  29382. * Renders the geometry as a wireframe.
  29383. *
  29384. * @type {boolean}
  29385. * @default false
  29386. */
  29387. this.wireframe = false;
  29388. /**
  29389. * Controls the thickness of the wireframe.
  29390. *
  29391. * WebGL and WebGPU ignore this property and always render
  29392. * 1 pixel wide lines.
  29393. *
  29394. * @type {number}
  29395. * @default 1
  29396. */
  29397. this.wireframeLinewidth = 1;
  29398. /**
  29399. * Whether the material is rendered with flat shading or not.
  29400. *
  29401. * @type {boolean}
  29402. * @default false
  29403. */
  29404. this.flatShading = false;
  29405. this.setValues( parameters );
  29406. }
  29407. copy( source ) {
  29408. super.copy( source );
  29409. this.bumpMap = source.bumpMap;
  29410. this.bumpScale = source.bumpScale;
  29411. this.normalMap = source.normalMap;
  29412. this.normalMapType = source.normalMapType;
  29413. this.normalScale.copy( source.normalScale );
  29414. this.displacementMap = source.displacementMap;
  29415. this.displacementScale = source.displacementScale;
  29416. this.displacementBias = source.displacementBias;
  29417. this.wireframe = source.wireframe;
  29418. this.wireframeLinewidth = source.wireframeLinewidth;
  29419. this.flatShading = source.flatShading;
  29420. return this;
  29421. }
  29422. }
  29423. /**
  29424. * A material for non-shiny surfaces, without specular highlights.
  29425. *
  29426. * The material uses a non-physically based [Lambertian](https://en.wikipedia.org/wiki/Lambertian_reflectance)
  29427. * model for calculating reflectance. This can simulate some surfaces (such
  29428. * as untreated wood or stone) well, but cannot simulate shiny surfaces with
  29429. * specular highlights (such as varnished wood). `MeshLambertMaterial` uses per-fragment
  29430. * shading.
  29431. *
  29432. * Due to the simplicity of the reflectance and illumination models,
  29433. * performance will be greater when using this material over the
  29434. * {@link MeshPhongMaterial}, {@link MeshStandardMaterial} or
  29435. * {@link MeshPhysicalMaterial}, at the cost of some graphical accuracy.
  29436. *
  29437. * @augments Material
  29438. * @demo scenes/material-browser.html#MeshLambertMaterial
  29439. */
  29440. class MeshLambertMaterial extends Material {
  29441. /**
  29442. * Constructs a new mesh lambert material.
  29443. *
  29444. * @param {Object} [parameters] - An object with one or more properties
  29445. * defining the material's appearance. Any property of the material
  29446. * (including any property from inherited materials) can be passed
  29447. * in here. Color values can be passed any type of value accepted
  29448. * by {@link Color#set}.
  29449. */
  29450. constructor( parameters ) {
  29451. super();
  29452. /**
  29453. * This flag can be used for type testing.
  29454. *
  29455. * @type {boolean}
  29456. * @readonly
  29457. * @default true
  29458. */
  29459. this.isMeshLambertMaterial = true;
  29460. this.type = 'MeshLambertMaterial';
  29461. /**
  29462. * Color of the material.
  29463. *
  29464. * @type {Color}
  29465. * @default (1,1,1)
  29466. */
  29467. this.color = new Color( 0xffffff ); // diffuse
  29468. /**
  29469. * The color map. May optionally include an alpha channel, typically combined
  29470. * with {@link Material#transparent} or {@link Material#alphaTest}. The texture map
  29471. * color is modulated by the diffuse `color`.
  29472. *
  29473. * @type {?Texture}
  29474. * @default null
  29475. */
  29476. this.map = null;
  29477. /**
  29478. * The light map. Requires a second set of UVs.
  29479. *
  29480. * @type {?Texture}
  29481. * @default null
  29482. */
  29483. this.lightMap = null;
  29484. /**
  29485. * Intensity of the baked light.
  29486. *
  29487. * @type {number}
  29488. * @default 1
  29489. */
  29490. this.lightMapIntensity = 1.0;
  29491. /**
  29492. * The red channel of this texture is used as the ambient occlusion map.
  29493. * Requires a second set of UVs.
  29494. *
  29495. * @type {?Texture}
  29496. * @default null
  29497. */
  29498. this.aoMap = null;
  29499. /**
  29500. * Intensity of the ambient occlusion effect. Range is `[0,1]`, where `0`
  29501. * disables ambient occlusion. Where intensity is `1` and the AO map's
  29502. * red channel is also `1`, ambient light is fully occluded on a surface.
  29503. *
  29504. * @type {number}
  29505. * @default 1
  29506. */
  29507. this.aoMapIntensity = 1.0;
  29508. /**
  29509. * Emissive (light) color of the material, essentially a solid color
  29510. * unaffected by other lighting.
  29511. *
  29512. * @type {Color}
  29513. * @default (0,0,0)
  29514. */
  29515. this.emissive = new Color( 0x000000 );
  29516. /**
  29517. * Intensity of the emissive light. Modulates the emissive color.
  29518. *
  29519. * @type {number}
  29520. * @default 1
  29521. */
  29522. this.emissiveIntensity = 1.0;
  29523. /**
  29524. * Set emissive (glow) map. The emissive map color is modulated by the
  29525. * emissive color and the emissive intensity. If you have an emissive map,
  29526. * be sure to set the emissive color to something other than black.
  29527. *
  29528. * @type {?Texture}
  29529. * @default null
  29530. */
  29531. this.emissiveMap = null;
  29532. /**
  29533. * The texture to create a bump map. The black and white values map to the
  29534. * perceived depth in relation to the lights. Bump doesn't actually affect
  29535. * the geometry of the object, only the lighting. If a normal map is defined
  29536. * this will be ignored.
  29537. *
  29538. * @type {?Texture}
  29539. * @default null
  29540. */
  29541. this.bumpMap = null;
  29542. /**
  29543. * How much the bump map affects the material. Typical range is `[0,1]`.
  29544. *
  29545. * @type {number}
  29546. * @default 1
  29547. */
  29548. this.bumpScale = 1;
  29549. /**
  29550. * The texture to create a normal map. The RGB values affect the surface
  29551. * normal for each pixel fragment and change the way the color is lit. Normal
  29552. * maps do not change the actual shape of the surface, only the lighting. In
  29553. * case the material has a normal map authored using the left handed
  29554. * convention, the `y` component of `normalScale` should be negated to compensate
  29555. * for the different handedness.
  29556. *
  29557. * @type {?Texture}
  29558. * @default null
  29559. */
  29560. this.normalMap = null;
  29561. /**
  29562. * The type of normal map.
  29563. *
  29564. * @type {(TangentSpaceNormalMap|ObjectSpaceNormalMap)}
  29565. * @default TangentSpaceNormalMap
  29566. */
  29567. this.normalMapType = TangentSpaceNormalMap;
  29568. /**
  29569. * How much the normal map affects the material. Typical value range is `[0,1]`.
  29570. *
  29571. * @type {Vector2}
  29572. * @default (1,1)
  29573. */
  29574. this.normalScale = new Vector2( 1, 1 );
  29575. /**
  29576. * The displacement map affects the position of the mesh's vertices. Unlike
  29577. * other maps which only affect the light and shade of the material the
  29578. * displaced vertices can cast shadows, block other objects, and otherwise
  29579. * act as real geometry. The displacement texture is an image where the value
  29580. * of each pixel (white being the highest) is mapped against, and
  29581. * repositions, the vertices of the mesh.
  29582. *
  29583. * @type {?Texture}
  29584. * @default null
  29585. */
  29586. this.displacementMap = null;
  29587. /**
  29588. * How much the displacement map affects the mesh (where black is no
  29589. * displacement, and white is maximum displacement). Without a displacement
  29590. * map set, this value is not applied.
  29591. *
  29592. * @type {number}
  29593. * @default 0
  29594. */
  29595. this.displacementScale = 1;
  29596. /**
  29597. * The offset of the displacement map's values on the mesh's vertices.
  29598. * The bias is added to the scaled sample of the displacement map.
  29599. * Without a displacement map set, this value is not applied.
  29600. *
  29601. * @type {number}
  29602. * @default 0
  29603. */
  29604. this.displacementBias = 0;
  29605. /**
  29606. * Specular map used by the material.
  29607. *
  29608. * @type {?Texture}
  29609. * @default null
  29610. */
  29611. this.specularMap = null;
  29612. /**
  29613. * The alpha map is a grayscale texture that controls the opacity across the
  29614. * surface (black: fully transparent; white: fully opaque).
  29615. *
  29616. * Only the color of the texture is used, ignoring the alpha channel if one
  29617. * exists. For RGB and RGBA textures, the renderer will use the green channel
  29618. * when sampling this texture due to the extra bit of precision provided for
  29619. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  29620. * luminance/alpha textures will also still work as expected.
  29621. *
  29622. * @type {?Texture}
  29623. * @default null
  29624. */
  29625. this.alphaMap = null;
  29626. /**
  29627. * The environment map.
  29628. *
  29629. * @type {?Texture}
  29630. * @default null
  29631. */
  29632. this.envMap = null;
  29633. /**
  29634. * The rotation of the environment map in radians.
  29635. *
  29636. * @type {Euler}
  29637. * @default (0,0,0)
  29638. */
  29639. this.envMapRotation = new Euler();
  29640. /**
  29641. * How to combine the result of the surface's color with the environment map, if any.
  29642. *
  29643. * When set to `MixOperation`, the {@link MeshBasicMaterial#reflectivity} is used to
  29644. * blend between the two colors.
  29645. *
  29646. * @type {(MultiplyOperation|MixOperation|AddOperation)}
  29647. * @default MultiplyOperation
  29648. */
  29649. this.combine = MultiplyOperation;
  29650. /**
  29651. * How much the environment map affects the surface.
  29652. * The valid range is between `0` (no reflections) and `1` (full reflections).
  29653. *
  29654. * @type {number}
  29655. * @default 1
  29656. */
  29657. this.reflectivity = 1;
  29658. /**
  29659. * The index of refraction (IOR) of air (approximately 1) divided by the
  29660. * index of refraction of the material. It is used with environment mapping
  29661. * modes {@link CubeRefractionMapping} and {@link EquirectangularRefractionMapping}.
  29662. * The refraction ratio should not exceed `1`.
  29663. *
  29664. * @type {number}
  29665. * @default 0.98
  29666. */
  29667. this.refractionRatio = 0.98;
  29668. /**
  29669. * Renders the geometry as a wireframe.
  29670. *
  29671. * @type {boolean}
  29672. * @default false
  29673. */
  29674. this.wireframe = false;
  29675. /**
  29676. * Controls the thickness of the wireframe.
  29677. *
  29678. * Can only be used with {@link SVGRenderer}.
  29679. *
  29680. * @type {number}
  29681. * @default 1
  29682. */
  29683. this.wireframeLinewidth = 1;
  29684. /**
  29685. * Defines appearance of wireframe ends.
  29686. *
  29687. * Can only be used with {@link SVGRenderer}.
  29688. *
  29689. * @type {('round'|'bevel'|'miter')}
  29690. * @default 'round'
  29691. */
  29692. this.wireframeLinecap = 'round';
  29693. /**
  29694. * Defines appearance of wireframe joints.
  29695. *
  29696. * Can only be used with {@link SVGRenderer}.
  29697. *
  29698. * @type {('round'|'bevel'|'miter')}
  29699. * @default 'round'
  29700. */
  29701. this.wireframeLinejoin = 'round';
  29702. /**
  29703. * Whether the material is rendered with flat shading or not.
  29704. *
  29705. * @type {boolean}
  29706. * @default false
  29707. */
  29708. this.flatShading = false;
  29709. /**
  29710. * Whether the material is affected by fog or not.
  29711. *
  29712. * @type {boolean}
  29713. * @default true
  29714. */
  29715. this.fog = true;
  29716. this.setValues( parameters );
  29717. }
  29718. copy( source ) {
  29719. super.copy( source );
  29720. this.color.copy( source.color );
  29721. this.map = source.map;
  29722. this.lightMap = source.lightMap;
  29723. this.lightMapIntensity = source.lightMapIntensity;
  29724. this.aoMap = source.aoMap;
  29725. this.aoMapIntensity = source.aoMapIntensity;
  29726. this.emissive.copy( source.emissive );
  29727. this.emissiveMap = source.emissiveMap;
  29728. this.emissiveIntensity = source.emissiveIntensity;
  29729. this.bumpMap = source.bumpMap;
  29730. this.bumpScale = source.bumpScale;
  29731. this.normalMap = source.normalMap;
  29732. this.normalMapType = source.normalMapType;
  29733. this.normalScale.copy( source.normalScale );
  29734. this.displacementMap = source.displacementMap;
  29735. this.displacementScale = source.displacementScale;
  29736. this.displacementBias = source.displacementBias;
  29737. this.specularMap = source.specularMap;
  29738. this.alphaMap = source.alphaMap;
  29739. this.envMap = source.envMap;
  29740. this.envMapRotation.copy( source.envMapRotation );
  29741. this.combine = source.combine;
  29742. this.reflectivity = source.reflectivity;
  29743. this.refractionRatio = source.refractionRatio;
  29744. this.wireframe = source.wireframe;
  29745. this.wireframeLinewidth = source.wireframeLinewidth;
  29746. this.wireframeLinecap = source.wireframeLinecap;
  29747. this.wireframeLinejoin = source.wireframeLinejoin;
  29748. this.flatShading = source.flatShading;
  29749. this.fog = source.fog;
  29750. return this;
  29751. }
  29752. }
  29753. /**
  29754. * A material for drawing geometry by depth. Depth is based off of the camera
  29755. * near and far plane. White is nearest, black is farthest.
  29756. *
  29757. * @augments Material
  29758. * @demo scenes/material-browser.html#MeshDepthMaterial
  29759. */
  29760. class MeshDepthMaterial extends Material {
  29761. /**
  29762. * Constructs a new mesh depth material.
  29763. *
  29764. * @param {Object} [parameters] - An object with one or more properties
  29765. * defining the material's appearance. Any property of the material
  29766. * (including any property from inherited materials) can be passed
  29767. * in here. Color values can be passed any type of value accepted
  29768. * by {@link Color#set}.
  29769. */
  29770. constructor( parameters ) {
  29771. super();
  29772. /**
  29773. * This flag can be used for type testing.
  29774. *
  29775. * @type {boolean}
  29776. * @readonly
  29777. * @default true
  29778. */
  29779. this.isMeshDepthMaterial = true;
  29780. this.type = 'MeshDepthMaterial';
  29781. /**
  29782. * Type for depth packing.
  29783. *
  29784. * @type {(BasicDepthPacking|RGBADepthPacking|RGBDepthPacking|RGDepthPacking)}
  29785. * @default BasicDepthPacking
  29786. */
  29787. this.depthPacking = BasicDepthPacking;
  29788. /**
  29789. * The color map. May optionally include an alpha channel, typically combined
  29790. * with {@link Material#transparent} or {@link Material#alphaTest}.
  29791. *
  29792. * @type {?Texture}
  29793. * @default null
  29794. */
  29795. this.map = null;
  29796. /**
  29797. * The alpha map is a grayscale texture that controls the opacity across the
  29798. * surface (black: fully transparent; white: fully opaque).
  29799. *
  29800. * Only the color of the texture is used, ignoring the alpha channel if one
  29801. * exists. For RGB and RGBA textures, the renderer will use the green channel
  29802. * when sampling this texture due to the extra bit of precision provided for
  29803. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  29804. * luminance/alpha textures will also still work as expected.
  29805. *
  29806. * @type {?Texture}
  29807. * @default null
  29808. */
  29809. this.alphaMap = null;
  29810. /**
  29811. * The displacement map affects the position of the mesh's vertices. Unlike
  29812. * other maps which only affect the light and shade of the material the
  29813. * displaced vertices can cast shadows, block other objects, and otherwise
  29814. * act as real geometry. The displacement texture is an image where the value
  29815. * of each pixel (white being the highest) is mapped against, and
  29816. * repositions, the vertices of the mesh.
  29817. *
  29818. * @type {?Texture}
  29819. * @default null
  29820. */
  29821. this.displacementMap = null;
  29822. /**
  29823. * How much the displacement map affects the mesh (where black is no
  29824. * displacement, and white is maximum displacement). Without a displacement
  29825. * map set, this value is not applied.
  29826. *
  29827. * @type {number}
  29828. * @default 0
  29829. */
  29830. this.displacementScale = 1;
  29831. /**
  29832. * The offset of the displacement map's values on the mesh's vertices.
  29833. * The bias is added to the scaled sample of the displacement map.
  29834. * Without a displacement map set, this value is not applied.
  29835. *
  29836. * @type {number}
  29837. * @default 0
  29838. */
  29839. this.displacementBias = 0;
  29840. /**
  29841. * Renders the geometry as a wireframe.
  29842. *
  29843. * @type {boolean}
  29844. * @default false
  29845. */
  29846. this.wireframe = false;
  29847. /**
  29848. * Controls the thickness of the wireframe.
  29849. *
  29850. * WebGL and WebGPU ignore this property and always render
  29851. * 1 pixel wide lines.
  29852. *
  29853. * @type {number}
  29854. * @default 1
  29855. */
  29856. this.wireframeLinewidth = 1;
  29857. this.setValues( parameters );
  29858. }
  29859. copy( source ) {
  29860. super.copy( source );
  29861. this.depthPacking = source.depthPacking;
  29862. this.map = source.map;
  29863. this.alphaMap = source.alphaMap;
  29864. this.displacementMap = source.displacementMap;
  29865. this.displacementScale = source.displacementScale;
  29866. this.displacementBias = source.displacementBias;
  29867. this.wireframe = source.wireframe;
  29868. this.wireframeLinewidth = source.wireframeLinewidth;
  29869. return this;
  29870. }
  29871. }
  29872. /**
  29873. * A material used internally for implementing shadow mapping with
  29874. * point lights.
  29875. *
  29876. * Can also be used to customize the shadow casting of an object by assigning
  29877. * an instance of `MeshDistanceMaterial` to {@link Object3D#customDistanceMaterial}.
  29878. * The following examples demonstrates this approach in order to ensure
  29879. * transparent parts of objects do not cast shadows.
  29880. *
  29881. * @augments Material
  29882. */
  29883. class MeshDistanceMaterial extends Material {
  29884. /**
  29885. * Constructs a new mesh distance material.
  29886. *
  29887. * @param {Object} [parameters] - An object with one or more properties
  29888. * defining the material's appearance. Any property of the material
  29889. * (including any property from inherited materials) can be passed
  29890. * in here. Color values can be passed any type of value accepted
  29891. * by {@link Color#set}.
  29892. */
  29893. constructor( parameters ) {
  29894. super();
  29895. /**
  29896. * This flag can be used for type testing.
  29897. *
  29898. * @type {boolean}
  29899. * @readonly
  29900. * @default true
  29901. */
  29902. this.isMeshDistanceMaterial = true;
  29903. this.type = 'MeshDistanceMaterial';
  29904. /**
  29905. * The color map. May optionally include an alpha channel, typically combined
  29906. * with {@link Material#transparent} or {@link Material#alphaTest}.
  29907. *
  29908. * @type {?Texture}
  29909. * @default null
  29910. */
  29911. this.map = null;
  29912. /**
  29913. * The alpha map is a grayscale texture that controls the opacity across the
  29914. * surface (black: fully transparent; white: fully opaque).
  29915. *
  29916. * Only the color of the texture is used, ignoring the alpha channel if one
  29917. * exists. For RGB and RGBA textures, the renderer will use the green channel
  29918. * when sampling this texture due to the extra bit of precision provided for
  29919. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  29920. * luminance/alpha textures will also still work as expected.
  29921. *
  29922. * @type {?Texture}
  29923. * @default null
  29924. */
  29925. this.alphaMap = null;
  29926. /**
  29927. * The displacement map affects the position of the mesh's vertices. Unlike
  29928. * other maps which only affect the light and shade of the material the
  29929. * displaced vertices can cast shadows, block other objects, and otherwise
  29930. * act as real geometry. The displacement texture is an image where the value
  29931. * of each pixel (white being the highest) is mapped against, and
  29932. * repositions, the vertices of the mesh.
  29933. *
  29934. * @type {?Texture}
  29935. * @default null
  29936. */
  29937. this.displacementMap = null;
  29938. /**
  29939. * How much the displacement map affects the mesh (where black is no
  29940. * displacement, and white is maximum displacement). Without a displacement
  29941. * map set, this value is not applied.
  29942. *
  29943. * @type {number}
  29944. * @default 0
  29945. */
  29946. this.displacementScale = 1;
  29947. /**
  29948. * The offset of the displacement map's values on the mesh's vertices.
  29949. * The bias is added to the scaled sample of the displacement map.
  29950. * Without a displacement map set, this value is not applied.
  29951. *
  29952. * @type {number}
  29953. * @default 0
  29954. */
  29955. this.displacementBias = 0;
  29956. this.setValues( parameters );
  29957. }
  29958. copy( source ) {
  29959. super.copy( source );
  29960. this.map = source.map;
  29961. this.alphaMap = source.alphaMap;
  29962. this.displacementMap = source.displacementMap;
  29963. this.displacementScale = source.displacementScale;
  29964. this.displacementBias = source.displacementBias;
  29965. return this;
  29966. }
  29967. }
  29968. /**
  29969. * This material is defined by a MatCap (or Lit Sphere) texture, which encodes the
  29970. * material color and shading.
  29971. *
  29972. * `MeshMatcapMaterial` does not respond to lights since the matcap image file encodes
  29973. * baked lighting. It will cast a shadow onto an object that receives shadows
  29974. * (and shadow clipping works), but it will not self-shadow or receive
  29975. * shadows.
  29976. *
  29977. * @augments Material
  29978. * @demo scenes/material-browser.html#MeshMatcapMaterial
  29979. */
  29980. class MeshMatcapMaterial extends Material {
  29981. /**
  29982. * Constructs a new mesh matcap material.
  29983. *
  29984. * @param {Object} [parameters] - An object with one or more properties
  29985. * defining the material's appearance. Any property of the material
  29986. * (including any property from inherited materials) can be passed
  29987. * in here. Color values can be passed any type of value accepted
  29988. * by {@link Color#set}.
  29989. */
  29990. constructor( parameters ) {
  29991. super();
  29992. /**
  29993. * This flag can be used for type testing.
  29994. *
  29995. * @type {boolean}
  29996. * @readonly
  29997. * @default true
  29998. */
  29999. this.isMeshMatcapMaterial = true;
  30000. this.defines = { 'MATCAP': '' };
  30001. this.type = 'MeshMatcapMaterial';
  30002. /**
  30003. * Color of the material.
  30004. *
  30005. * @type {Color}
  30006. * @default (1,1,1)
  30007. */
  30008. this.color = new Color( 0xffffff ); // diffuse
  30009. /**
  30010. * The matcap map.
  30011. *
  30012. * @type {?Texture}
  30013. * @default null
  30014. */
  30015. this.matcap = null;
  30016. /**
  30017. * The color map. May optionally include an alpha channel, typically combined
  30018. * with {@link Material#transparent} or {@link Material#alphaTest}. The texture map
  30019. * color is modulated by the diffuse `color`.
  30020. *
  30021. * @type {?Texture}
  30022. * @default null
  30023. */
  30024. this.map = null;
  30025. /**
  30026. * The texture to create a bump map. The black and white values map to the
  30027. * perceived depth in relation to the lights. Bump doesn't actually affect
  30028. * the geometry of the object, only the lighting. If a normal map is defined
  30029. * this will be ignored.
  30030. *
  30031. * @type {?Texture}
  30032. * @default null
  30033. */
  30034. this.bumpMap = null;
  30035. /**
  30036. * How much the bump map affects the material. Typical range is `[0,1]`.
  30037. *
  30038. * @type {number}
  30039. * @default 1
  30040. */
  30041. this.bumpScale = 1;
  30042. /**
  30043. * The texture to create a normal map. The RGB values affect the surface
  30044. * normal for each pixel fragment and change the way the color is lit. Normal
  30045. * maps do not change the actual shape of the surface, only the lighting. In
  30046. * case the material has a normal map authored using the left handed
  30047. * convention, the `y` component of `normalScale` should be negated to compensate
  30048. * for the different handedness.
  30049. *
  30050. * @type {?Texture}
  30051. * @default null
  30052. */
  30053. this.normalMap = null;
  30054. /**
  30055. * The type of normal map.
  30056. *
  30057. * @type {(TangentSpaceNormalMap|ObjectSpaceNormalMap)}
  30058. * @default TangentSpaceNormalMap
  30059. */
  30060. this.normalMapType = TangentSpaceNormalMap;
  30061. /**
  30062. * How much the normal map affects the material. Typical value range is `[0,1]`.
  30063. *
  30064. * @type {Vector2}
  30065. * @default (1,1)
  30066. */
  30067. this.normalScale = new Vector2( 1, 1 );
  30068. /**
  30069. * The displacement map affects the position of the mesh's vertices. Unlike
  30070. * other maps which only affect the light and shade of the material the
  30071. * displaced vertices can cast shadows, block other objects, and otherwise
  30072. * act as real geometry. The displacement texture is an image where the value
  30073. * of each pixel (white being the highest) is mapped against, and
  30074. * repositions, the vertices of the mesh.
  30075. *
  30076. * @type {?Texture}
  30077. * @default null
  30078. */
  30079. this.displacementMap = null;
  30080. /**
  30081. * How much the displacement map affects the mesh (where black is no
  30082. * displacement, and white is maximum displacement). Without a displacement
  30083. * map set, this value is not applied.
  30084. *
  30085. * @type {number}
  30086. * @default 0
  30087. */
  30088. this.displacementScale = 1;
  30089. /**
  30090. * The offset of the displacement map's values on the mesh's vertices.
  30091. * The bias is added to the scaled sample of the displacement map.
  30092. * Without a displacement map set, this value is not applied.
  30093. *
  30094. * @type {number}
  30095. * @default 0
  30096. */
  30097. this.displacementBias = 0;
  30098. /**
  30099. * The alpha map is a grayscale texture that controls the opacity across the
  30100. * surface (black: fully transparent; white: fully opaque).
  30101. *
  30102. * Only the color of the texture is used, ignoring the alpha channel if one
  30103. * exists. For RGB and RGBA textures, the renderer will use the green channel
  30104. * when sampling this texture due to the extra bit of precision provided for
  30105. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  30106. * luminance/alpha textures will also still work as expected.
  30107. *
  30108. * @type {?Texture}
  30109. * @default null
  30110. */
  30111. this.alphaMap = null;
  30112. /**
  30113. * Renders the geometry as a wireframe.
  30114. *
  30115. * @type {boolean}
  30116. * @default false
  30117. */
  30118. this.wireframe = false;
  30119. /**
  30120. * Controls the thickness of the wireframe.
  30121. *
  30122. * Can only be used with {@link SVGRenderer}.
  30123. *
  30124. * @type {number}
  30125. * @default 1
  30126. */
  30127. this.wireframeLinewidth = 1;
  30128. /**
  30129. * Whether the material is rendered with flat shading or not.
  30130. *
  30131. * @type {boolean}
  30132. * @default false
  30133. */
  30134. this.flatShading = false;
  30135. /**
  30136. * Whether the material is affected by fog or not.
  30137. *
  30138. * @type {boolean}
  30139. * @default true
  30140. */
  30141. this.fog = true;
  30142. this.setValues( parameters );
  30143. }
  30144. copy( source ) {
  30145. super.copy( source );
  30146. this.defines = { 'MATCAP': '' };
  30147. this.color.copy( source.color );
  30148. this.matcap = source.matcap;
  30149. this.map = source.map;
  30150. this.bumpMap = source.bumpMap;
  30151. this.bumpScale = source.bumpScale;
  30152. this.normalMap = source.normalMap;
  30153. this.normalMapType = source.normalMapType;
  30154. this.normalScale.copy( source.normalScale );
  30155. this.displacementMap = source.displacementMap;
  30156. this.displacementScale = source.displacementScale;
  30157. this.displacementBias = source.displacementBias;
  30158. this.alphaMap = source.alphaMap;
  30159. this.wireframe = source.wireframe;
  30160. this.wireframeLinewidth = source.wireframeLinewidth;
  30161. this.flatShading = source.flatShading;
  30162. this.fog = source.fog;
  30163. return this;
  30164. }
  30165. }
  30166. /**
  30167. * A material for rendering line primitives.
  30168. *
  30169. * Materials define the appearance of renderable 3D objects.
  30170. *
  30171. * ```js
  30172. * const material = new THREE.LineDashedMaterial( {
  30173. * color: 0xffffff,
  30174. * scale: 1,
  30175. * dashSize: 3,
  30176. * gapSize: 1,
  30177. * } );
  30178. * ```
  30179. *
  30180. * @augments LineBasicMaterial
  30181. */
  30182. class LineDashedMaterial extends LineBasicMaterial {
  30183. /**
  30184. * Constructs a new line dashed material.
  30185. *
  30186. * @param {Object} [parameters] - An object with one or more properties
  30187. * defining the material's appearance. Any property of the material
  30188. * (including any property from inherited materials) can be passed
  30189. * in here. Color values can be passed any type of value accepted
  30190. * by {@link Color#set}.
  30191. */
  30192. constructor( parameters ) {
  30193. super();
  30194. /**
  30195. * This flag can be used for type testing.
  30196. *
  30197. * @type {boolean}
  30198. * @readonly
  30199. * @default true
  30200. */
  30201. this.isLineDashedMaterial = true;
  30202. this.type = 'LineDashedMaterial';
  30203. /**
  30204. * The scale of the dashed part of a line.
  30205. *
  30206. * @type {number}
  30207. * @default 1
  30208. */
  30209. this.scale = 1;
  30210. /**
  30211. * The size of the dash. This is both the gap with the stroke.
  30212. *
  30213. * @type {number}
  30214. * @default 3
  30215. */
  30216. this.dashSize = 3;
  30217. /**
  30218. * The size of the gap.
  30219. *
  30220. * @type {number}
  30221. * @default 1
  30222. */
  30223. this.gapSize = 1;
  30224. this.setValues( parameters );
  30225. }
  30226. copy( source ) {
  30227. super.copy( source );
  30228. this.scale = source.scale;
  30229. this.dashSize = source.dashSize;
  30230. this.gapSize = source.gapSize;
  30231. return this;
  30232. }
  30233. }
  30234. /**
  30235. * Converts an array to a specific type.
  30236. *
  30237. * @param {TypedArray|Array} array - The array to convert.
  30238. * @param {TypedArray.constructor} type - The constructor of a typed array that defines the new type.
  30239. * @return {TypedArray} The converted array.
  30240. */
  30241. function convertArray( array, type ) {
  30242. if ( ! array || array.constructor === type ) return array;
  30243. if ( typeof type.BYTES_PER_ELEMENT === 'number' ) {
  30244. return new type( array ); // create typed array
  30245. }
  30246. return Array.prototype.slice.call( array ); // create Array
  30247. }
  30248. /**
  30249. * Returns an array by which times and values can be sorted.
  30250. *
  30251. * @param {Array<number>} times - The keyframe time values.
  30252. * @return {Array<number>} The array.
  30253. */
  30254. function getKeyframeOrder( times ) {
  30255. function compareTime( i, j ) {
  30256. return times[ i ] - times[ j ];
  30257. }
  30258. const n = times.length;
  30259. const result = new Array( n );
  30260. for ( let i = 0; i !== n; ++ i ) result[ i ] = i;
  30261. result.sort( compareTime );
  30262. return result;
  30263. }
  30264. /**
  30265. * Sorts the given array by the previously computed order via `getKeyframeOrder()`.
  30266. *
  30267. * @param {Array<number>} values - The values to sort.
  30268. * @param {number} stride - The stride.
  30269. * @param {Array<number>} order - The sort order.
  30270. * @return {Array<number>} The sorted values.
  30271. */
  30272. function sortedArray( values, stride, order ) {
  30273. const nValues = values.length;
  30274. const result = new values.constructor( nValues );
  30275. for ( let i = 0, dstOffset = 0; dstOffset !== nValues; ++ i ) {
  30276. const srcOffset = order[ i ] * stride;
  30277. for ( let j = 0; j !== stride; ++ j ) {
  30278. result[ dstOffset ++ ] = values[ srcOffset + j ];
  30279. }
  30280. }
  30281. return result;
  30282. }
  30283. /**
  30284. * Used for parsing AOS keyframe formats.
  30285. *
  30286. * @param {Array<number>} jsonKeys - A list of JSON keyframes.
  30287. * @param {Array<number>} times - This array will be filled with keyframe times by this function.
  30288. * @param {Array<number>} values - This array will be filled with keyframe values by this function.
  30289. * @param {string} valuePropertyName - The name of the property to use.
  30290. */
  30291. function flattenJSON( jsonKeys, times, values, valuePropertyName ) {
  30292. let i = 1, key = jsonKeys[ 0 ];
  30293. while ( key !== undefined && key[ valuePropertyName ] === undefined ) {
  30294. key = jsonKeys[ i ++ ];
  30295. }
  30296. if ( key === undefined ) return; // no data
  30297. let value = key[ valuePropertyName ];
  30298. if ( value === undefined ) return; // no data
  30299. if ( Array.isArray( value ) ) {
  30300. do {
  30301. value = key[ valuePropertyName ];
  30302. if ( value !== undefined ) {
  30303. times.push( key.time );
  30304. values.push( ...value ); // push all elements
  30305. }
  30306. key = jsonKeys[ i ++ ];
  30307. } while ( key !== undefined );
  30308. } else if ( value.toArray !== undefined ) {
  30309. // ...assume THREE.Math-ish
  30310. do {
  30311. value = key[ valuePropertyName ];
  30312. if ( value !== undefined ) {
  30313. times.push( key.time );
  30314. value.toArray( values, values.length );
  30315. }
  30316. key = jsonKeys[ i ++ ];
  30317. } while ( key !== undefined );
  30318. } else {
  30319. // otherwise push as-is
  30320. do {
  30321. value = key[ valuePropertyName ];
  30322. if ( value !== undefined ) {
  30323. times.push( key.time );
  30324. values.push( value );
  30325. }
  30326. key = jsonKeys[ i ++ ];
  30327. } while ( key !== undefined );
  30328. }
  30329. }
  30330. /**
  30331. * Creates a new clip, containing only the segment of the original clip between the given frames.
  30332. *
  30333. * @param {AnimationClip} sourceClip - The values to sort.
  30334. * @param {string} name - The name of the clip.
  30335. * @param {number} startFrame - The start frame.
  30336. * @param {number} endFrame - The end frame.
  30337. * @param {number} [fps=30] - The FPS.
  30338. * @return {AnimationClip} The new sub clip.
  30339. */
  30340. function subclip( sourceClip, name, startFrame, endFrame, fps = 30 ) {
  30341. const clip = sourceClip.clone();
  30342. clip.name = name;
  30343. const tracks = [];
  30344. for ( let i = 0; i < clip.tracks.length; ++ i ) {
  30345. const track = clip.tracks[ i ];
  30346. const valueSize = track.getValueSize();
  30347. const times = [];
  30348. const values = [];
  30349. for ( let j = 0; j < track.times.length; ++ j ) {
  30350. const frame = track.times[ j ] * fps;
  30351. if ( frame < startFrame || frame >= endFrame ) continue;
  30352. times.push( track.times[ j ] );
  30353. for ( let k = 0; k < valueSize; ++ k ) {
  30354. values.push( track.values[ j * valueSize + k ] );
  30355. }
  30356. }
  30357. if ( times.length === 0 ) continue;
  30358. track.times = convertArray( times, track.times.constructor );
  30359. track.values = convertArray( values, track.values.constructor );
  30360. tracks.push( track );
  30361. }
  30362. clip.tracks = tracks;
  30363. // find minimum .times value across all tracks in the trimmed clip
  30364. let minStartTime = Infinity;
  30365. for ( let i = 0; i < clip.tracks.length; ++ i ) {
  30366. if ( minStartTime > clip.tracks[ i ].times[ 0 ] ) {
  30367. minStartTime = clip.tracks[ i ].times[ 0 ];
  30368. }
  30369. }
  30370. // shift all tracks such that clip begins at t=0
  30371. for ( let i = 0; i < clip.tracks.length; ++ i ) {
  30372. clip.tracks[ i ].shift( -1 * minStartTime );
  30373. }
  30374. clip.resetDuration();
  30375. return clip;
  30376. }
  30377. /**
  30378. * Converts the keyframes of the given animation clip to an additive format.
  30379. *
  30380. * @param {AnimationClip} targetClip - The clip to make additive.
  30381. * @param {number} [referenceFrame=0] - The reference frame.
  30382. * @param {AnimationClip} [referenceClip=targetClip] - The reference clip.
  30383. * @param {number} [fps=30] - The FPS.
  30384. * @return {AnimationClip} The updated clip which is now additive.
  30385. */
  30386. function makeClipAdditive( targetClip, referenceFrame = 0, referenceClip = targetClip, fps = 30 ) {
  30387. if ( fps <= 0 ) fps = 30;
  30388. const numTracks = referenceClip.tracks.length;
  30389. const referenceTime = referenceFrame / fps;
  30390. // Make each track's values relative to the values at the reference frame
  30391. for ( let i = 0; i < numTracks; ++ i ) {
  30392. const referenceTrack = referenceClip.tracks[ i ];
  30393. const referenceTrackType = referenceTrack.ValueTypeName;
  30394. // Skip this track if it's non-numeric
  30395. if ( referenceTrackType === 'bool' || referenceTrackType === 'string' ) continue;
  30396. // Find the track in the target clip whose name and type matches the reference track
  30397. const targetTrack = targetClip.tracks.find( function ( track ) {
  30398. return track.name === referenceTrack.name
  30399. && track.ValueTypeName === referenceTrackType;
  30400. } );
  30401. if ( targetTrack === undefined ) continue;
  30402. let referenceOffset = 0;
  30403. const referenceValueSize = referenceTrack.getValueSize();
  30404. if ( referenceTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline ) {
  30405. referenceOffset = referenceValueSize / 3;
  30406. }
  30407. let targetOffset = 0;
  30408. const targetValueSize = targetTrack.getValueSize();
  30409. if ( targetTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline ) {
  30410. targetOffset = targetValueSize / 3;
  30411. }
  30412. const lastIndex = referenceTrack.times.length - 1;
  30413. let referenceValue;
  30414. // Find the value to subtract out of the track
  30415. if ( referenceTime <= referenceTrack.times[ 0 ] ) {
  30416. // Reference frame is earlier than the first keyframe, so just use the first keyframe
  30417. const startIndex = referenceOffset;
  30418. const endIndex = referenceValueSize - referenceOffset;
  30419. referenceValue = referenceTrack.values.slice( startIndex, endIndex );
  30420. } else if ( referenceTime >= referenceTrack.times[ lastIndex ] ) {
  30421. // Reference frame is after the last keyframe, so just use the last keyframe
  30422. const startIndex = lastIndex * referenceValueSize + referenceOffset;
  30423. const endIndex = startIndex + referenceValueSize - referenceOffset;
  30424. referenceValue = referenceTrack.values.slice( startIndex, endIndex );
  30425. } else {
  30426. // Interpolate to the reference value
  30427. const interpolant = referenceTrack.createInterpolant();
  30428. const startIndex = referenceOffset;
  30429. const endIndex = referenceValueSize - referenceOffset;
  30430. interpolant.evaluate( referenceTime );
  30431. referenceValue = interpolant.resultBuffer.slice( startIndex, endIndex );
  30432. }
  30433. // Conjugate the quaternion
  30434. if ( referenceTrackType === 'quaternion' ) {
  30435. const referenceQuat = new Quaternion().fromArray( referenceValue ).normalize().conjugate();
  30436. referenceQuat.toArray( referenceValue );
  30437. }
  30438. // Subtract the reference value from all of the track values
  30439. const numTimes = targetTrack.times.length;
  30440. for ( let j = 0; j < numTimes; ++ j ) {
  30441. const valueStart = j * targetValueSize + targetOffset;
  30442. if ( referenceTrackType === 'quaternion' ) {
  30443. // Multiply the conjugate for quaternion track types
  30444. Quaternion.multiplyQuaternionsFlat(
  30445. targetTrack.values,
  30446. valueStart,
  30447. referenceValue,
  30448. 0,
  30449. targetTrack.values,
  30450. valueStart
  30451. );
  30452. } else {
  30453. const valueEnd = targetValueSize - targetOffset * 2;
  30454. // Subtract each value for all other numeric track types
  30455. for ( let k = 0; k < valueEnd; ++ k ) {
  30456. targetTrack.values[ valueStart + k ] -= referenceValue[ k ];
  30457. }
  30458. }
  30459. }
  30460. }
  30461. targetClip.blendMode = AdditiveAnimationBlendMode;
  30462. return targetClip;
  30463. }
  30464. /**
  30465. * A class with various methods to assist with animations.
  30466. *
  30467. * @hideconstructor
  30468. */
  30469. class AnimationUtils {
  30470. /**
  30471. * Converts an array to a specific type
  30472. *
  30473. * @static
  30474. * @param {TypedArray|Array} array - The array to convert.
  30475. * @param {TypedArray.constructor} type - The constructor of a type array.
  30476. * @return {TypedArray} The converted array
  30477. */
  30478. static convertArray( array, type ) {
  30479. return convertArray( array, type );
  30480. }
  30481. /**
  30482. * Returns `true` if the given object is a typed array.
  30483. *
  30484. * @static
  30485. * @param {any} object - The object to check.
  30486. * @return {boolean} Whether the given object is a typed array.
  30487. */
  30488. static isTypedArray( object ) {
  30489. return isTypedArray( object );
  30490. }
  30491. /**
  30492. * Returns an array by which times and values can be sorted.
  30493. *
  30494. * @static
  30495. * @param {Array<number>} times - The keyframe time values.
  30496. * @return {Array<number>} The array.
  30497. */
  30498. static getKeyframeOrder( times ) {
  30499. return getKeyframeOrder( times );
  30500. }
  30501. /**
  30502. * Sorts the given array by the previously computed order via `getKeyframeOrder()`.
  30503. *
  30504. * @static
  30505. * @param {Array<number>} values - The values to sort.
  30506. * @param {number} stride - The stride.
  30507. * @param {Array<number>} order - The sort order.
  30508. * @return {Array<number>} The sorted values.
  30509. */
  30510. static sortedArray( values, stride, order ) {
  30511. return sortedArray( values, stride, order );
  30512. }
  30513. /**
  30514. * Used for parsing AOS keyframe formats.
  30515. *
  30516. * @static
  30517. * @param {Array<number>} jsonKeys - A list of JSON keyframes.
  30518. * @param {Array<number>} times - This array will be filled with keyframe times by this method.
  30519. * @param {Array<number>} values - This array will be filled with keyframe values by this method.
  30520. * @param {string} valuePropertyName - The name of the property to use.
  30521. */
  30522. static flattenJSON( jsonKeys, times, values, valuePropertyName ) {
  30523. flattenJSON( jsonKeys, times, values, valuePropertyName );
  30524. }
  30525. /**
  30526. * Creates a new clip, containing only the segment of the original clip between the given frames.
  30527. *
  30528. * @static
  30529. * @param {AnimationClip} sourceClip - The values to sort.
  30530. * @param {string} name - The name of the clip.
  30531. * @param {number} startFrame - The start frame.
  30532. * @param {number} endFrame - The end frame.
  30533. * @param {number} [fps=30] - The FPS.
  30534. * @return {AnimationClip} The new sub clip.
  30535. */
  30536. static subclip( sourceClip, name, startFrame, endFrame, fps = 30 ) {
  30537. return subclip( sourceClip, name, startFrame, endFrame, fps );
  30538. }
  30539. /**
  30540. * Converts the keyframes of the given animation clip to an additive format.
  30541. *
  30542. * @static
  30543. * @param {AnimationClip} targetClip - The clip to make additive.
  30544. * @param {number} [referenceFrame=0] - The reference frame.
  30545. * @param {AnimationClip} [referenceClip=targetClip] - The reference clip.
  30546. * @param {number} [fps=30] - The FPS.
  30547. * @return {AnimationClip} The updated clip which is now additive.
  30548. */
  30549. static makeClipAdditive( targetClip, referenceFrame = 0, referenceClip = targetClip, fps = 30 ) {
  30550. return makeClipAdditive( targetClip, referenceFrame, referenceClip, fps );
  30551. }
  30552. }
  30553. /**
  30554. * Abstract base class of interpolants over parametric samples.
  30555. *
  30556. * The parameter domain is one dimensional, typically the time or a path
  30557. * along a curve defined by the data.
  30558. *
  30559. * The sample values can have any dimensionality and derived classes may
  30560. * apply special interpretations to the data.
  30561. *
  30562. * This class provides the interval seek in a Template Method, deferring
  30563. * the actual interpolation to derived classes.
  30564. *
  30565. * Time complexity is O(1) for linear access crossing at most two points
  30566. * and O(log N) for random access, where N is the number of positions.
  30567. *
  30568. * References: {@link http://www.oodesign.com/template-method-pattern.html}
  30569. *
  30570. * @abstract
  30571. */
  30572. class Interpolant {
  30573. /**
  30574. * Constructs a new interpolant.
  30575. *
  30576. * @param {TypedArray} parameterPositions - The parameter positions hold the interpolation factors.
  30577. * @param {TypedArray} sampleValues - The sample values.
  30578. * @param {number} sampleSize - The sample size
  30579. * @param {TypedArray} [resultBuffer] - The result buffer.
  30580. */
  30581. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  30582. /**
  30583. * The parameter positions.
  30584. *
  30585. * @type {TypedArray}
  30586. */
  30587. this.parameterPositions = parameterPositions;
  30588. /**
  30589. * A cache index.
  30590. *
  30591. * @private
  30592. * @type {number}
  30593. * @default 0
  30594. */
  30595. this._cachedIndex = 0;
  30596. /**
  30597. * The result buffer.
  30598. *
  30599. * @type {TypedArray}
  30600. */
  30601. this.resultBuffer = resultBuffer !== undefined ? resultBuffer : new sampleValues.constructor( sampleSize );
  30602. /**
  30603. * The sample values.
  30604. *
  30605. * @type {TypedArray}
  30606. */
  30607. this.sampleValues = sampleValues;
  30608. /**
  30609. * The value size.
  30610. *
  30611. * @type {TypedArray}
  30612. */
  30613. this.valueSize = sampleSize;
  30614. /**
  30615. * The interpolation settings.
  30616. *
  30617. * @type {?Object}
  30618. * @default null
  30619. */
  30620. this.settings = null;
  30621. /**
  30622. * The default settings object.
  30623. *
  30624. * @type {Object}
  30625. */
  30626. this.DefaultSettings_ = {};
  30627. }
  30628. /**
  30629. * Evaluate the interpolant at position `t`.
  30630. *
  30631. * @param {number} t - The interpolation factor.
  30632. * @return {TypedArray} The result buffer.
  30633. */
  30634. evaluate( t ) {
  30635. const pp = this.parameterPositions;
  30636. let i1 = this._cachedIndex,
  30637. t1 = pp[ i1 ],
  30638. t0 = pp[ i1 - 1 ];
  30639. validate_interval: {
  30640. seek: {
  30641. let right;
  30642. linear_scan: {
  30643. //- See http://jsperf.com/comparison-to-undefined/3
  30644. //- slower code:
  30645. //-
  30646. //- if ( t >= t1 || t1 === undefined ) {
  30647. forward_scan: if ( ! ( t < t1 ) ) {
  30648. for ( let giveUpAt = i1 + 2; ; ) {
  30649. if ( t1 === undefined ) {
  30650. if ( t < t0 ) break forward_scan;
  30651. // after end
  30652. i1 = pp.length;
  30653. this._cachedIndex = i1;
  30654. return this.copySampleValue_( i1 - 1 );
  30655. }
  30656. if ( i1 === giveUpAt ) break; // this loop
  30657. t0 = t1;
  30658. t1 = pp[ ++ i1 ];
  30659. if ( t < t1 ) {
  30660. // we have arrived at the sought interval
  30661. break seek;
  30662. }
  30663. }
  30664. // prepare binary search on the right side of the index
  30665. right = pp.length;
  30666. break linear_scan;
  30667. }
  30668. //- slower code:
  30669. //- if ( t < t0 || t0 === undefined ) {
  30670. if ( ! ( t >= t0 ) ) {
  30671. // looping?
  30672. const t1global = pp[ 1 ];
  30673. if ( t < t1global ) {
  30674. i1 = 2; // + 1, using the scan for the details
  30675. t0 = t1global;
  30676. }
  30677. // linear reverse scan
  30678. for ( let giveUpAt = i1 - 2; ; ) {
  30679. if ( t0 === undefined ) {
  30680. // before start
  30681. this._cachedIndex = 0;
  30682. return this.copySampleValue_( 0 );
  30683. }
  30684. if ( i1 === giveUpAt ) break; // this loop
  30685. t1 = t0;
  30686. t0 = pp[ -- i1 - 1 ];
  30687. if ( t >= t0 ) {
  30688. // we have arrived at the sought interval
  30689. break seek;
  30690. }
  30691. }
  30692. // prepare binary search on the left side of the index
  30693. right = i1;
  30694. i1 = 0;
  30695. break linear_scan;
  30696. }
  30697. // the interval is valid
  30698. break validate_interval;
  30699. } // linear scan
  30700. // binary search
  30701. while ( i1 < right ) {
  30702. const mid = ( i1 + right ) >>> 1;
  30703. if ( t < pp[ mid ] ) {
  30704. right = mid;
  30705. } else {
  30706. i1 = mid + 1;
  30707. }
  30708. }
  30709. t1 = pp[ i1 ];
  30710. t0 = pp[ i1 - 1 ];
  30711. // check boundary cases, again
  30712. if ( t0 === undefined ) {
  30713. this._cachedIndex = 0;
  30714. return this.copySampleValue_( 0 );
  30715. }
  30716. if ( t1 === undefined ) {
  30717. i1 = pp.length;
  30718. this._cachedIndex = i1;
  30719. return this.copySampleValue_( i1 - 1 );
  30720. }
  30721. } // seek
  30722. this._cachedIndex = i1;
  30723. this.intervalChanged_( i1, t0, t1 );
  30724. } // validate_interval
  30725. return this.interpolate_( i1, t0, t, t1 );
  30726. }
  30727. /**
  30728. * Returns the interpolation settings.
  30729. *
  30730. * @return {Object} The interpolation settings.
  30731. */
  30732. getSettings_() {
  30733. return this.settings || this.DefaultSettings_;
  30734. }
  30735. /**
  30736. * Copies a sample value to the result buffer.
  30737. *
  30738. * @param {number} index - An index into the sample value buffer.
  30739. * @return {TypedArray} The result buffer.
  30740. */
  30741. copySampleValue_( index ) {
  30742. // copies a sample value to the result buffer
  30743. const result = this.resultBuffer,
  30744. values = this.sampleValues,
  30745. stride = this.valueSize,
  30746. offset = index * stride;
  30747. for ( let i = 0; i !== stride; ++ i ) {
  30748. result[ i ] = values[ offset + i ];
  30749. }
  30750. return result;
  30751. }
  30752. /**
  30753. * Copies a sample value to the result buffer.
  30754. *
  30755. * @abstract
  30756. * @param {number} i1 - An index into the sample value buffer.
  30757. * @param {number} t0 - The previous interpolation factor.
  30758. * @param {number} t - The current interpolation factor.
  30759. * @param {number} t1 - The next interpolation factor.
  30760. * @return {TypedArray} The result buffer.
  30761. */
  30762. interpolate_( /* i1, t0, t, t1 */ ) {
  30763. throw new Error( 'call to abstract method' );
  30764. // implementations shall return this.resultBuffer
  30765. }
  30766. /**
  30767. * Optional method that is executed when the interval has changed.
  30768. *
  30769. * @param {number} i1 - An index into the sample value buffer.
  30770. * @param {number} t0 - The previous interpolation factor.
  30771. * @param {number} t - The current interpolation factor.
  30772. */
  30773. intervalChanged_( /* i1, t0, t1 */ ) {
  30774. // empty
  30775. }
  30776. }
  30777. /**
  30778. * Fast and simple cubic spline interpolant.
  30779. *
  30780. * It was derived from a Hermitian construction setting the first derivative
  30781. * at each sample position to the linear slope between neighboring positions
  30782. * over their parameter interval.
  30783. *
  30784. * @augments Interpolant
  30785. */
  30786. class CubicInterpolant extends Interpolant {
  30787. /**
  30788. * Constructs a new cubic interpolant.
  30789. *
  30790. * @param {TypedArray} parameterPositions - The parameter positions hold the interpolation factors.
  30791. * @param {TypedArray} sampleValues - The sample values.
  30792. * @param {number} sampleSize - The sample size
  30793. * @param {TypedArray} [resultBuffer] - The result buffer.
  30794. */
  30795. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  30796. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  30797. this._weightPrev = -0;
  30798. this._offsetPrev = -0;
  30799. this._weightNext = -0;
  30800. this._offsetNext = -0;
  30801. this.DefaultSettings_ = {
  30802. endingStart: ZeroCurvatureEnding,
  30803. endingEnd: ZeroCurvatureEnding
  30804. };
  30805. }
  30806. intervalChanged_( i1, t0, t1 ) {
  30807. const pp = this.parameterPositions;
  30808. let iPrev = i1 - 2,
  30809. iNext = i1 + 1,
  30810. tPrev = pp[ iPrev ],
  30811. tNext = pp[ iNext ];
  30812. if ( tPrev === undefined ) {
  30813. switch ( this.getSettings_().endingStart ) {
  30814. case ZeroSlopeEnding:
  30815. // f'(t0) = 0
  30816. iPrev = i1;
  30817. tPrev = 2 * t0 - t1;
  30818. break;
  30819. case WrapAroundEnding:
  30820. // use the other end of the curve
  30821. iPrev = pp.length - 2;
  30822. tPrev = t0 + pp[ iPrev ] - pp[ iPrev + 1 ];
  30823. break;
  30824. default: // ZeroCurvatureEnding
  30825. // f''(t0) = 0 a.k.a. Natural Spline
  30826. iPrev = i1;
  30827. tPrev = t1;
  30828. }
  30829. }
  30830. if ( tNext === undefined ) {
  30831. switch ( this.getSettings_().endingEnd ) {
  30832. case ZeroSlopeEnding:
  30833. // f'(tN) = 0
  30834. iNext = i1;
  30835. tNext = 2 * t1 - t0;
  30836. break;
  30837. case WrapAroundEnding:
  30838. // use the other end of the curve
  30839. iNext = 1;
  30840. tNext = t1 + pp[ 1 ] - pp[ 0 ];
  30841. break;
  30842. default: // ZeroCurvatureEnding
  30843. // f''(tN) = 0, a.k.a. Natural Spline
  30844. iNext = i1 - 1;
  30845. tNext = t0;
  30846. }
  30847. }
  30848. const halfDt = ( t1 - t0 ) * 0.5,
  30849. stride = this.valueSize;
  30850. this._weightPrev = halfDt / ( t0 - tPrev );
  30851. this._weightNext = halfDt / ( tNext - t1 );
  30852. this._offsetPrev = iPrev * stride;
  30853. this._offsetNext = iNext * stride;
  30854. }
  30855. interpolate_( i1, t0, t, t1 ) {
  30856. const result = this.resultBuffer,
  30857. values = this.sampleValues,
  30858. stride = this.valueSize,
  30859. o1 = i1 * stride, o0 = o1 - stride,
  30860. oP = this._offsetPrev, oN = this._offsetNext,
  30861. wP = this._weightPrev, wN = this._weightNext,
  30862. p = ( t - t0 ) / ( t1 - t0 ),
  30863. pp = p * p,
  30864. ppp = pp * p;
  30865. // evaluate polynomials
  30866. const sP = - wP * ppp + 2 * wP * pp - wP * p;
  30867. const s0 = ( 1 + wP ) * ppp + ( -1.5 - 2 * wP ) * pp + ( -0.5 + wP ) * p + 1;
  30868. const s1 = ( -1 - wN ) * ppp + ( 1.5 + wN ) * pp + 0.5 * p;
  30869. const sN = wN * ppp - wN * pp;
  30870. // combine data linearly
  30871. for ( let i = 0; i !== stride; ++ i ) {
  30872. result[ i ] =
  30873. sP * values[ oP + i ] +
  30874. s0 * values[ o0 + i ] +
  30875. s1 * values[ o1 + i ] +
  30876. sN * values[ oN + i ];
  30877. }
  30878. return result;
  30879. }
  30880. }
  30881. /**
  30882. * A basic linear interpolant.
  30883. *
  30884. * @augments Interpolant
  30885. */
  30886. class LinearInterpolant extends Interpolant {
  30887. /**
  30888. * Constructs a new linear interpolant.
  30889. *
  30890. * @param {TypedArray} parameterPositions - The parameter positions hold the interpolation factors.
  30891. * @param {TypedArray} sampleValues - The sample values.
  30892. * @param {number} sampleSize - The sample size
  30893. * @param {TypedArray} [resultBuffer] - The result buffer.
  30894. */
  30895. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  30896. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  30897. }
  30898. interpolate_( i1, t0, t, t1 ) {
  30899. const result = this.resultBuffer,
  30900. values = this.sampleValues,
  30901. stride = this.valueSize,
  30902. offset1 = i1 * stride,
  30903. offset0 = offset1 - stride,
  30904. weight1 = ( t - t0 ) / ( t1 - t0 ),
  30905. weight0 = 1 - weight1;
  30906. for ( let i = 0; i !== stride; ++ i ) {
  30907. result[ i ] =
  30908. values[ offset0 + i ] * weight0 +
  30909. values[ offset1 + i ] * weight1;
  30910. }
  30911. return result;
  30912. }
  30913. }
  30914. /**
  30915. * Interpolant that evaluates to the sample value at the position preceding
  30916. * the parameter.
  30917. *
  30918. * @augments Interpolant
  30919. */
  30920. class DiscreteInterpolant extends Interpolant {
  30921. /**
  30922. * Constructs a new discrete interpolant.
  30923. *
  30924. * @param {TypedArray} parameterPositions - The parameter positions hold the interpolation factors.
  30925. * @param {TypedArray} sampleValues - The sample values.
  30926. * @param {number} sampleSize - The sample size
  30927. * @param {TypedArray} [resultBuffer] - The result buffer.
  30928. */
  30929. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  30930. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  30931. }
  30932. interpolate_( i1 /*, t0, t, t1 */ ) {
  30933. return this.copySampleValue_( i1 - 1 );
  30934. }
  30935. }
  30936. /**
  30937. * Represents s a timed sequence of keyframes, which are composed of lists of
  30938. * times and related values, and which are used to animate a specific property
  30939. * of an object.
  30940. */
  30941. class KeyframeTrack {
  30942. /**
  30943. * Constructs a new keyframe track.
  30944. *
  30945. * @param {string} name - The keyframe track's name.
  30946. * @param {Array<number>} times - A list of keyframe times.
  30947. * @param {Array<number|string|boolean>} values - A list of keyframe values.
  30948. * @param {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)} [interpolation] - The interpolation type.
  30949. */
  30950. constructor( name, times, values, interpolation ) {
  30951. if ( name === undefined ) throw new Error( 'THREE.KeyframeTrack: track name is undefined' );
  30952. if ( times === undefined || times.length === 0 ) throw new Error( 'THREE.KeyframeTrack: no keyframes in track named ' + name );
  30953. /**
  30954. * The track's name can refer to morph targets or bones or
  30955. * possibly other values within an animated object. See {@link PropertyBinding#parseTrackName}
  30956. * for the forms of strings that can be parsed for property binding.
  30957. *
  30958. * @type {string}
  30959. */
  30960. this.name = name;
  30961. /**
  30962. * The keyframe times.
  30963. *
  30964. * @type {Float32Array}
  30965. */
  30966. this.times = convertArray( times, this.TimeBufferType );
  30967. /**
  30968. * The keyframe values.
  30969. *
  30970. * @type {Float32Array}
  30971. */
  30972. this.values = convertArray( values, this.ValueBufferType );
  30973. this.setInterpolation( interpolation || this.DefaultInterpolation );
  30974. }
  30975. /**
  30976. * Converts the keyframe track to JSON.
  30977. *
  30978. * @static
  30979. * @param {KeyframeTrack} track - The keyframe track to serialize.
  30980. * @return {Object} The serialized keyframe track as JSON.
  30981. */
  30982. static toJSON( track ) {
  30983. const trackType = track.constructor;
  30984. let json;
  30985. // derived classes can define a static toJSON method
  30986. if ( trackType.toJSON !== this.toJSON ) {
  30987. json = trackType.toJSON( track );
  30988. } else {
  30989. // by default, we assume the data can be serialized as-is
  30990. json = {
  30991. 'name': track.name,
  30992. 'times': convertArray( track.times, Array ),
  30993. 'values': convertArray( track.values, Array )
  30994. };
  30995. const interpolation = track.getInterpolation();
  30996. if ( interpolation !== track.DefaultInterpolation ) {
  30997. json.interpolation = interpolation;
  30998. }
  30999. }
  31000. json.type = track.ValueTypeName; // mandatory
  31001. return json;
  31002. }
  31003. /**
  31004. * Factory method for creating a new discrete interpolant.
  31005. *
  31006. * @static
  31007. * @param {TypedArray} [result] - The result buffer.
  31008. * @return {DiscreteInterpolant} The new interpolant.
  31009. */
  31010. InterpolantFactoryMethodDiscrete( result ) {
  31011. return new DiscreteInterpolant( this.times, this.values, this.getValueSize(), result );
  31012. }
  31013. /**
  31014. * Factory method for creating a new linear interpolant.
  31015. *
  31016. * @static
  31017. * @param {TypedArray} [result] - The result buffer.
  31018. * @return {LinearInterpolant} The new interpolant.
  31019. */
  31020. InterpolantFactoryMethodLinear( result ) {
  31021. return new LinearInterpolant( this.times, this.values, this.getValueSize(), result );
  31022. }
  31023. /**
  31024. * Factory method for creating a new smooth interpolant.
  31025. *
  31026. * @static
  31027. * @param {TypedArray} [result] - The result buffer.
  31028. * @return {CubicInterpolant} The new interpolant.
  31029. */
  31030. InterpolantFactoryMethodSmooth( result ) {
  31031. return new CubicInterpolant( this.times, this.values, this.getValueSize(), result );
  31032. }
  31033. /**
  31034. * Defines the interpolation factor method for this keyframe track.
  31035. *
  31036. * @param {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)} interpolation - The interpolation type.
  31037. * @return {KeyframeTrack} A reference to this keyframe track.
  31038. */
  31039. setInterpolation( interpolation ) {
  31040. let factoryMethod;
  31041. switch ( interpolation ) {
  31042. case InterpolateDiscrete:
  31043. factoryMethod = this.InterpolantFactoryMethodDiscrete;
  31044. break;
  31045. case InterpolateLinear:
  31046. factoryMethod = this.InterpolantFactoryMethodLinear;
  31047. break;
  31048. case InterpolateSmooth:
  31049. factoryMethod = this.InterpolantFactoryMethodSmooth;
  31050. break;
  31051. }
  31052. if ( factoryMethod === undefined ) {
  31053. const message = 'unsupported interpolation for ' +
  31054. this.ValueTypeName + ' keyframe track named ' + this.name;
  31055. if ( this.createInterpolant === undefined ) {
  31056. // fall back to default, unless the default itself is messed up
  31057. if ( interpolation !== this.DefaultInterpolation ) {
  31058. this.setInterpolation( this.DefaultInterpolation );
  31059. } else {
  31060. throw new Error( message ); // fatal, in this case
  31061. }
  31062. }
  31063. warn( 'KeyframeTrack:', message );
  31064. return this;
  31065. }
  31066. this.createInterpolant = factoryMethod;
  31067. return this;
  31068. }
  31069. /**
  31070. * Returns the current interpolation type.
  31071. *
  31072. * @return {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)} The interpolation type.
  31073. */
  31074. getInterpolation() {
  31075. switch ( this.createInterpolant ) {
  31076. case this.InterpolantFactoryMethodDiscrete:
  31077. return InterpolateDiscrete;
  31078. case this.InterpolantFactoryMethodLinear:
  31079. return InterpolateLinear;
  31080. case this.InterpolantFactoryMethodSmooth:
  31081. return InterpolateSmooth;
  31082. }
  31083. }
  31084. /**
  31085. * Returns the value size.
  31086. *
  31087. * @return {number} The value size.
  31088. */
  31089. getValueSize() {
  31090. return this.values.length / this.times.length;
  31091. }
  31092. /**
  31093. * Moves all keyframes either forward or backward in time.
  31094. *
  31095. * @param {number} timeOffset - The offset to move the time values.
  31096. * @return {KeyframeTrack} A reference to this keyframe track.
  31097. */
  31098. shift( timeOffset ) {
  31099. if ( timeOffset !== 0.0 ) {
  31100. const times = this.times;
  31101. for ( let i = 0, n = times.length; i !== n; ++ i ) {
  31102. times[ i ] += timeOffset;
  31103. }
  31104. }
  31105. return this;
  31106. }
  31107. /**
  31108. * Scale all keyframe times by a factor (useful for frame - seconds conversions).
  31109. *
  31110. * @param {number} timeScale - The time scale.
  31111. * @return {KeyframeTrack} A reference to this keyframe track.
  31112. */
  31113. scale( timeScale ) {
  31114. if ( timeScale !== 1.0 ) {
  31115. const times = this.times;
  31116. for ( let i = 0, n = times.length; i !== n; ++ i ) {
  31117. times[ i ] *= timeScale;
  31118. }
  31119. }
  31120. return this;
  31121. }
  31122. /**
  31123. * Removes keyframes before and after animation without changing any values within the defined time range.
  31124. *
  31125. * Note: The method does not shift around keys to the start of the track time, because for interpolated
  31126. * keys this will change their values
  31127. *
  31128. * @param {number} startTime - The start time.
  31129. * @param {number} endTime - The end time.
  31130. * @return {KeyframeTrack} A reference to this keyframe track.
  31131. */
  31132. trim( startTime, endTime ) {
  31133. const times = this.times,
  31134. nKeys = times.length;
  31135. let from = 0,
  31136. to = nKeys - 1;
  31137. while ( from !== nKeys && times[ from ] < startTime ) {
  31138. ++ from;
  31139. }
  31140. while ( to !== -1 && times[ to ] > endTime ) {
  31141. -- to;
  31142. }
  31143. ++ to; // inclusive -> exclusive bound
  31144. if ( from !== 0 || to !== nKeys ) {
  31145. // empty tracks are forbidden, so keep at least one keyframe
  31146. if ( from >= to ) {
  31147. to = Math.max( to, 1 );
  31148. from = to - 1;
  31149. }
  31150. const stride = this.getValueSize();
  31151. this.times = times.slice( from, to );
  31152. this.values = this.values.slice( from * stride, to * stride );
  31153. }
  31154. return this;
  31155. }
  31156. /**
  31157. * Performs minimal validation on the keyframe track. Returns `true` if the values
  31158. * are valid.
  31159. *
  31160. * @return {boolean} Whether the keyframes are valid or not.
  31161. */
  31162. validate() {
  31163. let valid = true;
  31164. const valueSize = this.getValueSize();
  31165. if ( valueSize - Math.floor( valueSize ) !== 0 ) {
  31166. error( 'KeyframeTrack: Invalid value size in track.', this );
  31167. valid = false;
  31168. }
  31169. const times = this.times,
  31170. values = this.values,
  31171. nKeys = times.length;
  31172. if ( nKeys === 0 ) {
  31173. error( 'KeyframeTrack: Track is empty.', this );
  31174. valid = false;
  31175. }
  31176. let prevTime = null;
  31177. for ( let i = 0; i !== nKeys; i ++ ) {
  31178. const currTime = times[ i ];
  31179. if ( typeof currTime === 'number' && isNaN( currTime ) ) {
  31180. error( 'KeyframeTrack: Time is not a valid number.', this, i, currTime );
  31181. valid = false;
  31182. break;
  31183. }
  31184. if ( prevTime !== null && prevTime > currTime ) {
  31185. error( 'KeyframeTrack: Out of order keys.', this, i, currTime, prevTime );
  31186. valid = false;
  31187. break;
  31188. }
  31189. prevTime = currTime;
  31190. }
  31191. if ( values !== undefined ) {
  31192. if ( isTypedArray( values ) ) {
  31193. for ( let i = 0, n = values.length; i !== n; ++ i ) {
  31194. const value = values[ i ];
  31195. if ( isNaN( value ) ) {
  31196. error( 'KeyframeTrack: Value is not a valid number.', this, i, value );
  31197. valid = false;
  31198. break;
  31199. }
  31200. }
  31201. }
  31202. }
  31203. return valid;
  31204. }
  31205. /**
  31206. * Optimizes this keyframe track by removing equivalent sequential keys (which are
  31207. * common in morph target sequences).
  31208. *
  31209. * @return {AnimationClip} A reference to this animation clip.
  31210. */
  31211. optimize() {
  31212. // (0,0,0,0,1,1,1,0,0,0,0,0,0,0) --> (0,0,1,1,0,0)
  31213. // times or values may be shared with other tracks, so overwriting is unsafe
  31214. const times = this.times.slice(),
  31215. values = this.values.slice(),
  31216. stride = this.getValueSize(),
  31217. smoothInterpolation = this.getInterpolation() === InterpolateSmooth,
  31218. lastIndex = times.length - 1;
  31219. let writeIndex = 1;
  31220. for ( let i = 1; i < lastIndex; ++ i ) {
  31221. let keep = false;
  31222. const time = times[ i ];
  31223. const timeNext = times[ i + 1 ];
  31224. // remove adjacent keyframes scheduled at the same time
  31225. if ( time !== timeNext && ( i !== 1 || time !== times[ 0 ] ) ) {
  31226. if ( ! smoothInterpolation ) {
  31227. // remove unnecessary keyframes same as their neighbors
  31228. const offset = i * stride,
  31229. offsetP = offset - stride,
  31230. offsetN = offset + stride;
  31231. for ( let j = 0; j !== stride; ++ j ) {
  31232. const value = values[ offset + j ];
  31233. if ( value !== values[ offsetP + j ] ||
  31234. value !== values[ offsetN + j ] ) {
  31235. keep = true;
  31236. break;
  31237. }
  31238. }
  31239. } else {
  31240. keep = true;
  31241. }
  31242. }
  31243. // in-place compaction
  31244. if ( keep ) {
  31245. if ( i !== writeIndex ) {
  31246. times[ writeIndex ] = times[ i ];
  31247. const readOffset = i * stride,
  31248. writeOffset = writeIndex * stride;
  31249. for ( let j = 0; j !== stride; ++ j ) {
  31250. values[ writeOffset + j ] = values[ readOffset + j ];
  31251. }
  31252. }
  31253. ++ writeIndex;
  31254. }
  31255. }
  31256. // flush last keyframe (compaction looks ahead)
  31257. if ( lastIndex > 0 ) {
  31258. times[ writeIndex ] = times[ lastIndex ];
  31259. for ( let readOffset = lastIndex * stride, writeOffset = writeIndex * stride, j = 0; j !== stride; ++ j ) {
  31260. values[ writeOffset + j ] = values[ readOffset + j ];
  31261. }
  31262. ++ writeIndex;
  31263. }
  31264. if ( writeIndex !== times.length ) {
  31265. this.times = times.slice( 0, writeIndex );
  31266. this.values = values.slice( 0, writeIndex * stride );
  31267. } else {
  31268. this.times = times;
  31269. this.values = values;
  31270. }
  31271. return this;
  31272. }
  31273. /**
  31274. * Returns a new keyframe track with copied values from this instance.
  31275. *
  31276. * @return {KeyframeTrack} A clone of this instance.
  31277. */
  31278. clone() {
  31279. const times = this.times.slice();
  31280. const values = this.values.slice();
  31281. const TypedKeyframeTrack = this.constructor;
  31282. const track = new TypedKeyframeTrack( this.name, times, values );
  31283. // Interpolant argument to constructor is not saved, so copy the factory method directly.
  31284. track.createInterpolant = this.createInterpolant;
  31285. return track;
  31286. }
  31287. }
  31288. /**
  31289. * The value type name.
  31290. *
  31291. * @type {string}
  31292. * @default ''
  31293. */
  31294. KeyframeTrack.prototype.ValueTypeName = '';
  31295. /**
  31296. * The time buffer type of this keyframe track.
  31297. *
  31298. * @type {TypedArray|Array}
  31299. * @default Float32Array.constructor
  31300. */
  31301. KeyframeTrack.prototype.TimeBufferType = Float32Array;
  31302. /**
  31303. * The value buffer type of this keyframe track.
  31304. *
  31305. * @type {TypedArray|Array}
  31306. * @default Float32Array.constructor
  31307. */
  31308. KeyframeTrack.prototype.ValueBufferType = Float32Array;
  31309. /**
  31310. * The default interpolation type of this keyframe track.
  31311. *
  31312. * @type {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)}
  31313. * @default InterpolateLinear
  31314. */
  31315. KeyframeTrack.prototype.DefaultInterpolation = InterpolateLinear;
  31316. /**
  31317. * A track for boolean keyframe values.
  31318. *
  31319. * @augments KeyframeTrack
  31320. */
  31321. class BooleanKeyframeTrack extends KeyframeTrack {
  31322. /**
  31323. * Constructs a new boolean keyframe track.
  31324. *
  31325. * This keyframe track type has no `interpolation` parameter because the
  31326. * interpolation is always discrete.
  31327. *
  31328. * @param {string} name - The keyframe track's name.
  31329. * @param {Array<number>} times - A list of keyframe times.
  31330. * @param {Array<boolean>} values - A list of keyframe values.
  31331. */
  31332. constructor( name, times, values ) {
  31333. super( name, times, values );
  31334. }
  31335. }
  31336. /**
  31337. * The value type name.
  31338. *
  31339. * @type {string}
  31340. * @default 'bool'
  31341. */
  31342. BooleanKeyframeTrack.prototype.ValueTypeName = 'bool';
  31343. /**
  31344. * The value buffer type of this keyframe track.
  31345. *
  31346. * @type {TypedArray|Array}
  31347. * @default Array.constructor
  31348. */
  31349. BooleanKeyframeTrack.prototype.ValueBufferType = Array;
  31350. /**
  31351. * The default interpolation type of this keyframe track.
  31352. *
  31353. * @type {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)}
  31354. * @default InterpolateDiscrete
  31355. */
  31356. BooleanKeyframeTrack.prototype.DefaultInterpolation = InterpolateDiscrete;
  31357. BooleanKeyframeTrack.prototype.InterpolantFactoryMethodLinear = undefined;
  31358. BooleanKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  31359. /**
  31360. * A track for color keyframe values.
  31361. *
  31362. * @augments KeyframeTrack
  31363. */
  31364. class ColorKeyframeTrack extends KeyframeTrack {
  31365. /**
  31366. * Constructs a new color keyframe track.
  31367. *
  31368. * @param {string} name - The keyframe track's name.
  31369. * @param {Array<number>} times - A list of keyframe times.
  31370. * @param {Array<number>} values - A list of keyframe values.
  31371. * @param {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)} [interpolation] - The interpolation type.
  31372. */
  31373. constructor( name, times, values, interpolation ) {
  31374. super( name, times, values, interpolation );
  31375. }
  31376. }
  31377. /**
  31378. * The value type name.
  31379. *
  31380. * @type {string}
  31381. * @default 'color'
  31382. */
  31383. ColorKeyframeTrack.prototype.ValueTypeName = 'color';
  31384. /**
  31385. * A track for numeric keyframe values.
  31386. *
  31387. * @augments KeyframeTrack
  31388. */
  31389. class NumberKeyframeTrack extends KeyframeTrack {
  31390. /**
  31391. * Constructs a new number keyframe track.
  31392. *
  31393. * @param {string} name - The keyframe track's name.
  31394. * @param {Array<number>} times - A list of keyframe times.
  31395. * @param {Array<number>} values - A list of keyframe values.
  31396. * @param {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)} [interpolation] - The interpolation type.
  31397. */
  31398. constructor( name, times, values, interpolation ) {
  31399. super( name, times, values, interpolation );
  31400. }
  31401. }
  31402. /**
  31403. * The value type name.
  31404. *
  31405. * @type {string}
  31406. * @default 'number'
  31407. */
  31408. NumberKeyframeTrack.prototype.ValueTypeName = 'number';
  31409. /**
  31410. * Spherical linear unit quaternion interpolant.
  31411. *
  31412. * @augments Interpolant
  31413. */
  31414. class QuaternionLinearInterpolant extends Interpolant {
  31415. /**
  31416. * Constructs a new SLERP interpolant.
  31417. *
  31418. * @param {TypedArray} parameterPositions - The parameter positions hold the interpolation factors.
  31419. * @param {TypedArray} sampleValues - The sample values.
  31420. * @param {number} sampleSize - The sample size
  31421. * @param {TypedArray} [resultBuffer] - The result buffer.
  31422. */
  31423. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  31424. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  31425. }
  31426. interpolate_( i1, t0, t, t1 ) {
  31427. const result = this.resultBuffer,
  31428. values = this.sampleValues,
  31429. stride = this.valueSize,
  31430. alpha = ( t - t0 ) / ( t1 - t0 );
  31431. let offset = i1 * stride;
  31432. for ( let end = offset + stride; offset !== end; offset += 4 ) {
  31433. Quaternion.slerpFlat( result, 0, values, offset - stride, values, offset, alpha );
  31434. }
  31435. return result;
  31436. }
  31437. }
  31438. /**
  31439. * A track for Quaternion keyframe values.
  31440. *
  31441. * @augments KeyframeTrack
  31442. */
  31443. class QuaternionKeyframeTrack extends KeyframeTrack {
  31444. /**
  31445. * Constructs a new Quaternion keyframe track.
  31446. *
  31447. * @param {string} name - The keyframe track's name.
  31448. * @param {Array<number>} times - A list of keyframe times.
  31449. * @param {Array<number>} values - A list of keyframe values.
  31450. * @param {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)} [interpolation] - The interpolation type.
  31451. */
  31452. constructor( name, times, values, interpolation ) {
  31453. super( name, times, values, interpolation );
  31454. }
  31455. /**
  31456. * Overwritten so the method returns Quaternion based interpolant.
  31457. *
  31458. * @static
  31459. * @param {TypedArray} [result] - The result buffer.
  31460. * @return {QuaternionLinearInterpolant} The new interpolant.
  31461. */
  31462. InterpolantFactoryMethodLinear( result ) {
  31463. return new QuaternionLinearInterpolant( this.times, this.values, this.getValueSize(), result );
  31464. }
  31465. }
  31466. /**
  31467. * The value type name.
  31468. *
  31469. * @type {string}
  31470. * @default 'quaternion'
  31471. */
  31472. QuaternionKeyframeTrack.prototype.ValueTypeName = 'quaternion';
  31473. // ValueBufferType is inherited
  31474. // DefaultInterpolation is inherited;
  31475. QuaternionKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  31476. /**
  31477. * A track for string keyframe values.
  31478. *
  31479. * @augments KeyframeTrack
  31480. */
  31481. class StringKeyframeTrack extends KeyframeTrack {
  31482. /**
  31483. * Constructs a new string keyframe track.
  31484. *
  31485. * This keyframe track type has no `interpolation` parameter because the
  31486. * interpolation is always discrete.
  31487. *
  31488. * @param {string} name - The keyframe track's name.
  31489. * @param {Array<number>} times - A list of keyframe times.
  31490. * @param {Array<string>} values - A list of keyframe values.
  31491. */
  31492. constructor( name, times, values ) {
  31493. super( name, times, values );
  31494. }
  31495. }
  31496. /**
  31497. * The value type name.
  31498. *
  31499. * @type {string}
  31500. * @default 'string'
  31501. */
  31502. StringKeyframeTrack.prototype.ValueTypeName = 'string';
  31503. /**
  31504. * The value buffer type of this keyframe track.
  31505. *
  31506. * @type {TypedArray|Array}
  31507. * @default Array.constructor
  31508. */
  31509. StringKeyframeTrack.prototype.ValueBufferType = Array;
  31510. /**
  31511. * The default interpolation type of this keyframe track.
  31512. *
  31513. * @type {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)}
  31514. * @default InterpolateDiscrete
  31515. */
  31516. StringKeyframeTrack.prototype.DefaultInterpolation = InterpolateDiscrete;
  31517. StringKeyframeTrack.prototype.InterpolantFactoryMethodLinear = undefined;
  31518. StringKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  31519. /**
  31520. * A track for vector keyframe values.
  31521. *
  31522. * @augments KeyframeTrack
  31523. */
  31524. class VectorKeyframeTrack extends KeyframeTrack {
  31525. /**
  31526. * Constructs a new vector keyframe track.
  31527. *
  31528. * @param {string} name - The keyframe track's name.
  31529. * @param {Array<number>} times - A list of keyframe times.
  31530. * @param {Array<number>} values - A list of keyframe values.
  31531. * @param {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)} [interpolation] - The interpolation type.
  31532. */
  31533. constructor( name, times, values, interpolation ) {
  31534. super( name, times, values, interpolation );
  31535. }
  31536. }
  31537. /**
  31538. * The value type name.
  31539. *
  31540. * @type {string}
  31541. * @default 'vector'
  31542. */
  31543. VectorKeyframeTrack.prototype.ValueTypeName = 'vector';
  31544. /**
  31545. * A reusable set of keyframe tracks which represent an animation.
  31546. */
  31547. class AnimationClip {
  31548. /**
  31549. * Constructs a new animation clip.
  31550. *
  31551. * Note: Instead of instantiating an AnimationClip directly with the constructor, you can
  31552. * use the static interface of this class for creating clips. In most cases though, animation clips
  31553. * will automatically be created by loaders when importing animated 3D assets.
  31554. *
  31555. * @param {string} [name=''] - The clip's name.
  31556. * @param {number} [duration=-1] - The clip's duration in seconds. If a negative value is passed,
  31557. * the duration will be calculated from the passed keyframes.
  31558. * @param {Array<KeyframeTrack>} tracks - An array of keyframe tracks.
  31559. * @param {(NormalAnimationBlendMode|AdditiveAnimationBlendMode)} [blendMode=NormalAnimationBlendMode] - Defines how the animation
  31560. * is blended/combined when two or more animations are simultaneously played.
  31561. */
  31562. constructor( name = '', duration = -1, tracks = [], blendMode = NormalAnimationBlendMode ) {
  31563. /**
  31564. * The clip's name.
  31565. *
  31566. * @type {string}
  31567. */
  31568. this.name = name;
  31569. /**
  31570. * An array of keyframe tracks.
  31571. *
  31572. * @type {Array<KeyframeTrack>}
  31573. */
  31574. this.tracks = tracks;
  31575. /**
  31576. * The clip's duration in seconds.
  31577. *
  31578. * @type {number}
  31579. */
  31580. this.duration = duration;
  31581. /**
  31582. * Defines how the animation is blended/combined when two or more animations
  31583. * are simultaneously played.
  31584. *
  31585. * @type {(NormalAnimationBlendMode|AdditiveAnimationBlendMode)}
  31586. */
  31587. this.blendMode = blendMode;
  31588. /**
  31589. * The UUID of the animation clip.
  31590. *
  31591. * @type {string}
  31592. * @readonly
  31593. */
  31594. this.uuid = generateUUID();
  31595. /**
  31596. * An object that can be used to store custom data about the animation clip.
  31597. * It should not hold references to functions as these will not be cloned.
  31598. *
  31599. * @type {Object}
  31600. */
  31601. this.userData = {};
  31602. // this means it should figure out its duration by scanning the tracks
  31603. if ( this.duration < 0 ) {
  31604. this.resetDuration();
  31605. }
  31606. }
  31607. /**
  31608. * Factory method for creating an animation clip from the given JSON.
  31609. *
  31610. * @static
  31611. * @param {Object} json - The serialized animation clip.
  31612. * @return {AnimationClip} The new animation clip.
  31613. */
  31614. static parse( json ) {
  31615. const tracks = [],
  31616. jsonTracks = json.tracks,
  31617. frameTime = 1.0 / ( json.fps || 1.0 );
  31618. for ( let i = 0, n = jsonTracks.length; i !== n; ++ i ) {
  31619. tracks.push( parseKeyframeTrack( jsonTracks[ i ] ).scale( frameTime ) );
  31620. }
  31621. const clip = new this( json.name, json.duration, tracks, json.blendMode );
  31622. clip.uuid = json.uuid;
  31623. clip.userData = JSON.parse( json.userData || '{}' );
  31624. return clip;
  31625. }
  31626. /**
  31627. * Serializes the given animation clip into JSON.
  31628. *
  31629. * @static
  31630. * @param {AnimationClip} clip - The animation clip to serialize.
  31631. * @return {Object} The JSON object.
  31632. */
  31633. static toJSON( clip ) {
  31634. const tracks = [],
  31635. clipTracks = clip.tracks;
  31636. const json = {
  31637. 'name': clip.name,
  31638. 'duration': clip.duration,
  31639. 'tracks': tracks,
  31640. 'uuid': clip.uuid,
  31641. 'blendMode': clip.blendMode,
  31642. 'userData': JSON.stringify( clip.userData ),
  31643. };
  31644. for ( let i = 0, n = clipTracks.length; i !== n; ++ i ) {
  31645. tracks.push( KeyframeTrack.toJSON( clipTracks[ i ] ) );
  31646. }
  31647. return json;
  31648. }
  31649. /**
  31650. * Returns a new animation clip from the passed morph targets array of a
  31651. * geometry, taking a name and the number of frames per second.
  31652. *
  31653. * Note: The fps parameter is required, but the animation speed can be
  31654. * overridden via {@link AnimationAction#setDuration}.
  31655. *
  31656. * @static
  31657. * @param {string} name - The name of the animation clip.
  31658. * @param {Array<Object>} morphTargetSequence - A sequence of morph targets.
  31659. * @param {number} fps - The Frames-Per-Second value.
  31660. * @param {boolean} noLoop - Whether the clip should be no loop or not.
  31661. * @return {AnimationClip} The new animation clip.
  31662. */
  31663. static CreateFromMorphTargetSequence( name, morphTargetSequence, fps, noLoop ) {
  31664. const numMorphTargets = morphTargetSequence.length;
  31665. const tracks = [];
  31666. for ( let i = 0; i < numMorphTargets; i ++ ) {
  31667. let times = [];
  31668. let values = [];
  31669. times.push(
  31670. ( i + numMorphTargets - 1 ) % numMorphTargets,
  31671. i,
  31672. ( i + 1 ) % numMorphTargets );
  31673. values.push( 0, 1, 0 );
  31674. const order = getKeyframeOrder( times );
  31675. times = sortedArray( times, 1, order );
  31676. values = sortedArray( values, 1, order );
  31677. // if there is a key at the first frame, duplicate it as the
  31678. // last frame as well for perfect loop.
  31679. if ( ! noLoop && times[ 0 ] === 0 ) {
  31680. times.push( numMorphTargets );
  31681. values.push( values[ 0 ] );
  31682. }
  31683. tracks.push(
  31684. new NumberKeyframeTrack(
  31685. '.morphTargetInfluences[' + morphTargetSequence[ i ].name + ']',
  31686. times, values
  31687. ).scale( 1.0 / fps ) );
  31688. }
  31689. return new this( name, -1, tracks );
  31690. }
  31691. /**
  31692. * Searches for an animation clip by name, taking as its first parameter
  31693. * either an array of clips, or a mesh or geometry that contains an
  31694. * array named "animations" property.
  31695. *
  31696. * @static
  31697. * @param {(Array<AnimationClip>|Object3D)} objectOrClipArray - The array or object to search through.
  31698. * @param {string} name - The name to search for.
  31699. * @return {?AnimationClip} The found animation clip. Returns `null` if no clip has been found.
  31700. */
  31701. static findByName( objectOrClipArray, name ) {
  31702. let clipArray = objectOrClipArray;
  31703. if ( ! Array.isArray( objectOrClipArray ) ) {
  31704. const o = objectOrClipArray;
  31705. clipArray = o.geometry && o.geometry.animations || o.animations;
  31706. }
  31707. for ( let i = 0; i < clipArray.length; i ++ ) {
  31708. if ( clipArray[ i ].name === name ) {
  31709. return clipArray[ i ];
  31710. }
  31711. }
  31712. return null;
  31713. }
  31714. /**
  31715. * Returns an array of new AnimationClips created from the morph target
  31716. * sequences of a geometry, trying to sort morph target names into
  31717. * animation-group-based patterns like "Walk_001, Walk_002, Run_001, Run_002...".
  31718. *
  31719. * See {@link MD2Loader#parse} as an example for how the method should be used.
  31720. *
  31721. * @static
  31722. * @param {Array<Object>} morphTargets - A sequence of morph targets.
  31723. * @param {number} fps - The Frames-Per-Second value.
  31724. * @param {boolean} noLoop - Whether the clip should be no loop or not.
  31725. * @return {Array<AnimationClip>} An array of new animation clips.
  31726. */
  31727. static CreateClipsFromMorphTargetSequences( morphTargets, fps, noLoop ) {
  31728. const animationToMorphTargets = {};
  31729. // tested with https://regex101.com/ on trick sequences
  31730. // such flamingo_flyA_003, flamingo_run1_003, crdeath0059
  31731. const pattern = /^([\w-]*?)([\d]+)$/;
  31732. // sort morph target names into animation groups based
  31733. // patterns like Walk_001, Walk_002, Run_001, Run_002
  31734. for ( let i = 0, il = morphTargets.length; i < il; i ++ ) {
  31735. const morphTarget = morphTargets[ i ];
  31736. const parts = morphTarget.name.match( pattern );
  31737. if ( parts && parts.length > 1 ) {
  31738. const name = parts[ 1 ];
  31739. let animationMorphTargets = animationToMorphTargets[ name ];
  31740. if ( ! animationMorphTargets ) {
  31741. animationToMorphTargets[ name ] = animationMorphTargets = [];
  31742. }
  31743. animationMorphTargets.push( morphTarget );
  31744. }
  31745. }
  31746. const clips = [];
  31747. for ( const name in animationToMorphTargets ) {
  31748. clips.push( this.CreateFromMorphTargetSequence( name, animationToMorphTargets[ name ], fps, noLoop ) );
  31749. }
  31750. return clips;
  31751. }
  31752. /**
  31753. * Parses the `animation.hierarchy` format and returns a new animation clip.
  31754. *
  31755. * @static
  31756. * @deprecated since r175.
  31757. * @param {Object} animation - A serialized animation clip as JSON.
  31758. * @param {Array<Bones>} bones - An array of bones.
  31759. * @return {?AnimationClip} The new animation clip.
  31760. */
  31761. static parseAnimation( animation, bones ) {
  31762. warn( 'AnimationClip: parseAnimation() is deprecated and will be removed with r185' );
  31763. if ( ! animation ) {
  31764. error( 'AnimationClip: No animation in JSONLoader data.' );
  31765. return null;
  31766. }
  31767. const addNonemptyTrack = function ( trackType, trackName, animationKeys, propertyName, destTracks ) {
  31768. // only return track if there are actually keys.
  31769. if ( animationKeys.length !== 0 ) {
  31770. const times = [];
  31771. const values = [];
  31772. flattenJSON( animationKeys, times, values, propertyName );
  31773. // empty keys are filtered out, so check again
  31774. if ( times.length !== 0 ) {
  31775. destTracks.push( new trackType( trackName, times, values ) );
  31776. }
  31777. }
  31778. };
  31779. const tracks = [];
  31780. const clipName = animation.name || 'default';
  31781. const fps = animation.fps || 30;
  31782. const blendMode = animation.blendMode;
  31783. // automatic length determination in AnimationClip.
  31784. let duration = animation.length || -1;
  31785. const hierarchyTracks = animation.hierarchy || [];
  31786. for ( let h = 0; h < hierarchyTracks.length; h ++ ) {
  31787. const animationKeys = hierarchyTracks[ h ].keys;
  31788. // skip empty tracks
  31789. if ( ! animationKeys || animationKeys.length === 0 ) continue;
  31790. // process morph targets
  31791. if ( animationKeys[ 0 ].morphTargets ) {
  31792. // figure out all morph targets used in this track
  31793. const morphTargetNames = {};
  31794. let k;
  31795. for ( k = 0; k < animationKeys.length; k ++ ) {
  31796. if ( animationKeys[ k ].morphTargets ) {
  31797. for ( let m = 0; m < animationKeys[ k ].morphTargets.length; m ++ ) {
  31798. morphTargetNames[ animationKeys[ k ].morphTargets[ m ] ] = -1;
  31799. }
  31800. }
  31801. }
  31802. // create a track for each morph target with all zero
  31803. // morphTargetInfluences except for the keys in which
  31804. // the morphTarget is named.
  31805. for ( const morphTargetName in morphTargetNames ) {
  31806. const times = [];
  31807. const values = [];
  31808. for ( let m = 0; m !== animationKeys[ k ].morphTargets.length; ++ m ) {
  31809. const animationKey = animationKeys[ k ];
  31810. times.push( animationKey.time );
  31811. values.push( ( animationKey.morphTarget === morphTargetName ) ? 1 : 0 );
  31812. }
  31813. tracks.push( new NumberKeyframeTrack( '.morphTargetInfluence[' + morphTargetName + ']', times, values ) );
  31814. }
  31815. duration = morphTargetNames.length * fps;
  31816. } else {
  31817. // ...assume skeletal animation
  31818. const boneName = '.bones[' + bones[ h ].name + ']';
  31819. addNonemptyTrack(
  31820. VectorKeyframeTrack, boneName + '.position',
  31821. animationKeys, 'pos', tracks );
  31822. addNonemptyTrack(
  31823. QuaternionKeyframeTrack, boneName + '.quaternion',
  31824. animationKeys, 'rot', tracks );
  31825. addNonemptyTrack(
  31826. VectorKeyframeTrack, boneName + '.scale',
  31827. animationKeys, 'scl', tracks );
  31828. }
  31829. }
  31830. if ( tracks.length === 0 ) {
  31831. return null;
  31832. }
  31833. const clip = new this( clipName, duration, tracks, blendMode );
  31834. return clip;
  31835. }
  31836. /**
  31837. * Sets the duration of this clip to the duration of its longest keyframe track.
  31838. *
  31839. * @return {AnimationClip} A reference to this animation clip.
  31840. */
  31841. resetDuration() {
  31842. const tracks = this.tracks;
  31843. let duration = 0;
  31844. for ( let i = 0, n = tracks.length; i !== n; ++ i ) {
  31845. const track = this.tracks[ i ];
  31846. duration = Math.max( duration, track.times[ track.times.length - 1 ] );
  31847. }
  31848. this.duration = duration;
  31849. return this;
  31850. }
  31851. /**
  31852. * Trims all tracks to the clip's duration.
  31853. *
  31854. * @return {AnimationClip} A reference to this animation clip.
  31855. */
  31856. trim() {
  31857. for ( let i = 0; i < this.tracks.length; i ++ ) {
  31858. this.tracks[ i ].trim( 0, this.duration );
  31859. }
  31860. return this;
  31861. }
  31862. /**
  31863. * Performs minimal validation on each track in the clip. Returns `true` if all
  31864. * tracks are valid.
  31865. *
  31866. * @return {boolean} Whether the clip's keyframes are valid or not.
  31867. */
  31868. validate() {
  31869. let valid = true;
  31870. for ( let i = 0; i < this.tracks.length; i ++ ) {
  31871. valid = valid && this.tracks[ i ].validate();
  31872. }
  31873. return valid;
  31874. }
  31875. /**
  31876. * Optimizes each track by removing equivalent sequential keys (which are
  31877. * common in morph target sequences).
  31878. *
  31879. * @return {AnimationClip} A reference to this animation clip.
  31880. */
  31881. optimize() {
  31882. for ( let i = 0; i < this.tracks.length; i ++ ) {
  31883. this.tracks[ i ].optimize();
  31884. }
  31885. return this;
  31886. }
  31887. /**
  31888. * Returns a new animation clip with copied values from this instance.
  31889. *
  31890. * @return {AnimationClip} A clone of this instance.
  31891. */
  31892. clone() {
  31893. const tracks = [];
  31894. for ( let i = 0; i < this.tracks.length; i ++ ) {
  31895. tracks.push( this.tracks[ i ].clone() );
  31896. }
  31897. const clip = new this.constructor( this.name, this.duration, tracks, this.blendMode );
  31898. clip.userData = JSON.parse( JSON.stringify( this.userData ) );
  31899. return clip;
  31900. }
  31901. /**
  31902. * Serializes this animation clip into JSON.
  31903. *
  31904. * @return {Object} The JSON object.
  31905. */
  31906. toJSON() {
  31907. return this.constructor.toJSON( this );
  31908. }
  31909. }
  31910. function getTrackTypeForValueTypeName( typeName ) {
  31911. switch ( typeName.toLowerCase() ) {
  31912. case 'scalar':
  31913. case 'double':
  31914. case 'float':
  31915. case 'number':
  31916. case 'integer':
  31917. return NumberKeyframeTrack;
  31918. case 'vector':
  31919. case 'vector2':
  31920. case 'vector3':
  31921. case 'vector4':
  31922. return VectorKeyframeTrack;
  31923. case 'color':
  31924. return ColorKeyframeTrack;
  31925. case 'quaternion':
  31926. return QuaternionKeyframeTrack;
  31927. case 'bool':
  31928. case 'boolean':
  31929. return BooleanKeyframeTrack;
  31930. case 'string':
  31931. return StringKeyframeTrack;
  31932. }
  31933. throw new Error( 'THREE.KeyframeTrack: Unsupported typeName: ' + typeName );
  31934. }
  31935. function parseKeyframeTrack( json ) {
  31936. if ( json.type === undefined ) {
  31937. throw new Error( 'THREE.KeyframeTrack: track type undefined, can not parse' );
  31938. }
  31939. const trackType = getTrackTypeForValueTypeName( json.type );
  31940. if ( json.times === undefined ) {
  31941. const times = [], values = [];
  31942. flattenJSON( json.keys, times, values, 'value' );
  31943. json.times = times;
  31944. json.values = values;
  31945. }
  31946. // derived classes can define a static parse method
  31947. if ( trackType.parse !== undefined ) {
  31948. return trackType.parse( json );
  31949. } else {
  31950. // by default, we assume a constructor compatible with the base
  31951. return new trackType( json.name, json.times, json.values, json.interpolation );
  31952. }
  31953. }
  31954. /**
  31955. * @class
  31956. * @classdesc A simple caching system, used internally by {@link FileLoader}.
  31957. * To enable caching across all loaders that use {@link FileLoader}, add `THREE.Cache.enabled = true.` once in your app.
  31958. * @hideconstructor
  31959. */
  31960. const Cache = {
  31961. /**
  31962. * Whether caching is enabled or not.
  31963. *
  31964. * @static
  31965. * @type {boolean}
  31966. * @default false
  31967. */
  31968. enabled: false,
  31969. /**
  31970. * A dictionary that holds cached files.
  31971. *
  31972. * @static
  31973. * @type {Object<string,Object>}
  31974. */
  31975. files: {},
  31976. /**
  31977. * Adds a cache entry with a key to reference the file. If this key already
  31978. * holds a file, it is overwritten.
  31979. *
  31980. * @static
  31981. * @param {string} key - The key to reference the cached file.
  31982. * @param {Object} file - The file to be cached.
  31983. */
  31984. add: function ( key, file ) {
  31985. if ( this.enabled === false ) return;
  31986. // log( 'Cache', 'Adding key:', key );
  31987. this.files[ key ] = file;
  31988. },
  31989. /**
  31990. * Gets the cached value for the given key.
  31991. *
  31992. * @static
  31993. * @param {string} key - The key to reference the cached file.
  31994. * @return {Object|undefined} The cached file. If the key does not exist `undefined` is returned.
  31995. */
  31996. get: function ( key ) {
  31997. if ( this.enabled === false ) return;
  31998. // log( 'Cache', 'Checking key:', key );
  31999. return this.files[ key ];
  32000. },
  32001. /**
  32002. * Removes the cached file associated with the given key.
  32003. *
  32004. * @static
  32005. * @param {string} key - The key to reference the cached file.
  32006. */
  32007. remove: function ( key ) {
  32008. delete this.files[ key ];
  32009. },
  32010. /**
  32011. * Remove all values from the cache.
  32012. *
  32013. * @static
  32014. */
  32015. clear: function () {
  32016. this.files = {};
  32017. }
  32018. };
  32019. /**
  32020. * Handles and keeps track of loaded and pending data. A default global
  32021. * instance of this class is created and used by loaders if not supplied
  32022. * manually.
  32023. *
  32024. * In general that should be sufficient, however there are times when it can
  32025. * be useful to have separate loaders - for example if you want to show
  32026. * separate loading bars for objects and textures.
  32027. *
  32028. * ```js
  32029. * const manager = new THREE.LoadingManager();
  32030. * manager.onLoad = () => console.log( 'Loading complete!' );
  32031. *
  32032. * const loader1 = new OBJLoader( manager );
  32033. * const loader2 = new ColladaLoader( manager );
  32034. * ```
  32035. */
  32036. class LoadingManager {
  32037. /**
  32038. * Constructs a new loading manager.
  32039. *
  32040. * @param {Function} [onLoad] - Executes when all items have been loaded.
  32041. * @param {Function} [onProgress] - Executes when single items have been loaded.
  32042. * @param {Function} [onError] - Executes when an error occurs.
  32043. */
  32044. constructor( onLoad, onProgress, onError ) {
  32045. const scope = this;
  32046. let isLoading = false;
  32047. let itemsLoaded = 0;
  32048. let itemsTotal = 0;
  32049. let urlModifier = undefined;
  32050. const handlers = [];
  32051. // Refer to #5689 for the reason why we don't set .onStart
  32052. // in the constructor
  32053. /**
  32054. * Executes when an item starts loading.
  32055. *
  32056. * @type {Function|undefined}
  32057. * @default undefined
  32058. */
  32059. this.onStart = undefined;
  32060. /**
  32061. * Executes when all items have been loaded.
  32062. *
  32063. * @type {Function|undefined}
  32064. * @default undefined
  32065. */
  32066. this.onLoad = onLoad;
  32067. /**
  32068. * Executes when single items have been loaded.
  32069. *
  32070. * @type {Function|undefined}
  32071. * @default undefined
  32072. */
  32073. this.onProgress = onProgress;
  32074. /**
  32075. * Executes when an error occurs.
  32076. *
  32077. * @type {Function|undefined}
  32078. * @default undefined
  32079. */
  32080. this.onError = onError;
  32081. /**
  32082. * Used for aborting ongoing requests in loaders using this manager.
  32083. *
  32084. * @private
  32085. * @type {AbortController | null}
  32086. */
  32087. this._abortController = null;
  32088. /**
  32089. * This should be called by any loader using the manager when the loader
  32090. * starts loading an item.
  32091. *
  32092. * @param {string} url - The URL to load.
  32093. */
  32094. this.itemStart = function ( url ) {
  32095. itemsTotal ++;
  32096. if ( isLoading === false ) {
  32097. if ( scope.onStart !== undefined ) {
  32098. scope.onStart( url, itemsLoaded, itemsTotal );
  32099. }
  32100. }
  32101. isLoading = true;
  32102. };
  32103. /**
  32104. * This should be called by any loader using the manager when the loader
  32105. * ended loading an item.
  32106. *
  32107. * @param {string} url - The URL of the loaded item.
  32108. */
  32109. this.itemEnd = function ( url ) {
  32110. itemsLoaded ++;
  32111. if ( scope.onProgress !== undefined ) {
  32112. scope.onProgress( url, itemsLoaded, itemsTotal );
  32113. }
  32114. if ( itemsLoaded === itemsTotal ) {
  32115. isLoading = false;
  32116. if ( scope.onLoad !== undefined ) {
  32117. scope.onLoad();
  32118. }
  32119. }
  32120. };
  32121. /**
  32122. * This should be called by any loader using the manager when the loader
  32123. * encounters an error when loading an item.
  32124. *
  32125. * @param {string} url - The URL of the item that produces an error.
  32126. */
  32127. this.itemError = function ( url ) {
  32128. if ( scope.onError !== undefined ) {
  32129. scope.onError( url );
  32130. }
  32131. };
  32132. /**
  32133. * Given a URL, uses the URL modifier callback (if any) and returns a
  32134. * resolved URL. If no URL modifier is set, returns the original URL.
  32135. *
  32136. * @param {string} url - The URL to load.
  32137. * @return {string} The resolved URL.
  32138. */
  32139. this.resolveURL = function ( url ) {
  32140. if ( urlModifier ) {
  32141. return urlModifier( url );
  32142. }
  32143. return url;
  32144. };
  32145. /**
  32146. * If provided, the callback will be passed each resource URL before a
  32147. * request is sent. The callback may return the original URL, or a new URL to
  32148. * override loading behavior. This behavior can be used to load assets from
  32149. * .ZIP files, drag-and-drop APIs, and Data URIs.
  32150. *
  32151. * ```js
  32152. * const blobs = {'fish.gltf': blob1, 'diffuse.png': blob2, 'normal.png': blob3};
  32153. *
  32154. * const manager = new THREE.LoadingManager();
  32155. *
  32156. * // Initialize loading manager with URL callback.
  32157. * const objectURLs = [];
  32158. * manager.setURLModifier( ( url ) => {
  32159. *
  32160. * url = URL.createObjectURL( blobs[ url ] );
  32161. * objectURLs.push( url );
  32162. * return url;
  32163. *
  32164. * } );
  32165. *
  32166. * // Load as usual, then revoke the blob URLs.
  32167. * const loader = new GLTFLoader( manager );
  32168. * loader.load( 'fish.gltf', (gltf) => {
  32169. *
  32170. * scene.add( gltf.scene );
  32171. * objectURLs.forEach( ( url ) => URL.revokeObjectURL( url ) );
  32172. *
  32173. * } );
  32174. * ```
  32175. *
  32176. * @param {function(string):string} transform - URL modifier callback. Called with an URL and must return a resolved URL.
  32177. * @return {LoadingManager} A reference to this loading manager.
  32178. */
  32179. this.setURLModifier = function ( transform ) {
  32180. urlModifier = transform;
  32181. return this;
  32182. };
  32183. /**
  32184. * Registers a loader with the given regular expression. Can be used to
  32185. * define what loader should be used in order to load specific files. A
  32186. * typical use case is to overwrite the default loader for textures.
  32187. *
  32188. * ```js
  32189. * // add handler for TGA textures
  32190. * manager.addHandler( /\.tga$/i, new TGALoader() );
  32191. * ```
  32192. *
  32193. * @param {string} regex - A regular expression.
  32194. * @param {Loader} loader - A loader that should handle matched cases.
  32195. * @return {LoadingManager} A reference to this loading manager.
  32196. */
  32197. this.addHandler = function ( regex, loader ) {
  32198. handlers.push( regex, loader );
  32199. return this;
  32200. };
  32201. /**
  32202. * Removes the loader for the given regular expression.
  32203. *
  32204. * @param {string} regex - A regular expression.
  32205. * @return {LoadingManager} A reference to this loading manager.
  32206. */
  32207. this.removeHandler = function ( regex ) {
  32208. const index = handlers.indexOf( regex );
  32209. if ( index !== -1 ) {
  32210. handlers.splice( index, 2 );
  32211. }
  32212. return this;
  32213. };
  32214. /**
  32215. * Can be used to retrieve the registered loader for the given file path.
  32216. *
  32217. * @param {string} file - The file path.
  32218. * @return {?Loader} The registered loader. Returns `null` if no loader was found.
  32219. */
  32220. this.getHandler = function ( file ) {
  32221. for ( let i = 0, l = handlers.length; i < l; i += 2 ) {
  32222. const regex = handlers[ i ];
  32223. const loader = handlers[ i + 1 ];
  32224. if ( regex.global ) regex.lastIndex = 0; // see #17920
  32225. if ( regex.test( file ) ) {
  32226. return loader;
  32227. }
  32228. }
  32229. return null;
  32230. };
  32231. /**
  32232. * Can be used to abort ongoing loading requests in loaders using this manager.
  32233. * The abort only works if the loaders implement {@link Loader#abort} and `AbortSignal.any()`
  32234. * is supported in the browser.
  32235. *
  32236. * @return {LoadingManager} A reference to this loading manager.
  32237. */
  32238. this.abort = function () {
  32239. this.abortController.abort();
  32240. this._abortController = null;
  32241. return this;
  32242. };
  32243. }
  32244. // TODO: Revert this back to a single member variable once this issue has been fixed
  32245. // https://github.com/cloudflare/workerd/issues/3657
  32246. /**
  32247. * Used for aborting ongoing requests in loaders using this manager.
  32248. *
  32249. * @type {AbortController}
  32250. */
  32251. get abortController() {
  32252. if ( ! this._abortController ) {
  32253. this._abortController = new AbortController();
  32254. }
  32255. return this._abortController;
  32256. }
  32257. }
  32258. /**
  32259. * The global default loading manager.
  32260. *
  32261. * @constant
  32262. * @type {LoadingManager}
  32263. */
  32264. const DefaultLoadingManager = /*@__PURE__*/ new LoadingManager();
  32265. /**
  32266. * Abstract base class for loaders.
  32267. *
  32268. * @abstract
  32269. */
  32270. class Loader {
  32271. /**
  32272. * Constructs a new loader.
  32273. *
  32274. * @param {LoadingManager} [manager] - The loading manager.
  32275. */
  32276. constructor( manager ) {
  32277. /**
  32278. * The loading manager.
  32279. *
  32280. * @type {LoadingManager}
  32281. * @default DefaultLoadingManager
  32282. */
  32283. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  32284. /**
  32285. * The crossOrigin string to implement CORS for loading the url from a
  32286. * different domain that allows CORS.
  32287. *
  32288. * @type {string}
  32289. * @default 'anonymous'
  32290. */
  32291. this.crossOrigin = 'anonymous';
  32292. /**
  32293. * Whether the XMLHttpRequest uses credentials.
  32294. *
  32295. * @type {boolean}
  32296. * @default false
  32297. */
  32298. this.withCredentials = false;
  32299. /**
  32300. * The base path from which the asset will be loaded.
  32301. *
  32302. * @type {string}
  32303. */
  32304. this.path = '';
  32305. /**
  32306. * The base path from which additional resources like textures will be loaded.
  32307. *
  32308. * @type {string}
  32309. */
  32310. this.resourcePath = '';
  32311. /**
  32312. * The [request header](https://developer.mozilla.org/en-US/docs/Glossary/Request_header)
  32313. * used in HTTP request.
  32314. *
  32315. * @type {Object<string, any>}
  32316. */
  32317. this.requestHeader = {};
  32318. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  32319. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'observe', { detail: this } ) );
  32320. }
  32321. }
  32322. /**
  32323. * This method needs to be implemented by all concrete loaders. It holds the
  32324. * logic for loading assets from the backend.
  32325. *
  32326. * @abstract
  32327. * @param {string} url - The path/URL of the file to be loaded.
  32328. * @param {Function} onLoad - Executed when the loading process has been finished.
  32329. * @param {onProgressCallback} [onProgress] - Executed while the loading is in progress.
  32330. * @param {onErrorCallback} [onError] - Executed when errors occur.
  32331. */
  32332. load( /* url, onLoad, onProgress, onError */ ) {}
  32333. /**
  32334. * A async version of {@link Loader#load}.
  32335. *
  32336. * @param {string} url - The path/URL of the file to be loaded.
  32337. * @param {onProgressCallback} [onProgress] - Executed while the loading is in progress.
  32338. * @return {Promise} A Promise that resolves when the asset has been loaded.
  32339. */
  32340. loadAsync( url, onProgress ) {
  32341. const scope = this;
  32342. return new Promise( function ( resolve, reject ) {
  32343. scope.load( url, resolve, onProgress, reject );
  32344. } );
  32345. }
  32346. /**
  32347. * This method needs to be implemented by all concrete loaders. It holds the
  32348. * logic for parsing the asset into three.js entities.
  32349. *
  32350. * @abstract
  32351. * @param {any} data - The data to parse.
  32352. */
  32353. parse( /* data */ ) {}
  32354. /**
  32355. * Sets the `crossOrigin` String to implement CORS for loading the URL
  32356. * from a different domain that allows CORS.
  32357. *
  32358. * @param {string} crossOrigin - The `crossOrigin` value.
  32359. * @return {Loader} A reference to this instance.
  32360. */
  32361. setCrossOrigin( crossOrigin ) {
  32362. this.crossOrigin = crossOrigin;
  32363. return this;
  32364. }
  32365. /**
  32366. * Whether the XMLHttpRequest uses credentials such as cookies, authorization
  32367. * headers or TLS client certificates, see [XMLHttpRequest.withCredentials](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/withCredentials).
  32368. *
  32369. * Note: This setting has no effect if you are loading files locally or from the same domain.
  32370. *
  32371. * @param {boolean} value - The `withCredentials` value.
  32372. * @return {Loader} A reference to this instance.
  32373. */
  32374. setWithCredentials( value ) {
  32375. this.withCredentials = value;
  32376. return this;
  32377. }
  32378. /**
  32379. * Sets the base path for the asset.
  32380. *
  32381. * @param {string} path - The base path.
  32382. * @return {Loader} A reference to this instance.
  32383. */
  32384. setPath( path ) {
  32385. this.path = path;
  32386. return this;
  32387. }
  32388. /**
  32389. * Sets the base path for dependent resources like textures.
  32390. *
  32391. * @param {string} resourcePath - The resource path.
  32392. * @return {Loader} A reference to this instance.
  32393. */
  32394. setResourcePath( resourcePath ) {
  32395. this.resourcePath = resourcePath;
  32396. return this;
  32397. }
  32398. /**
  32399. * Sets the given request header.
  32400. *
  32401. * @param {Object} requestHeader - A [request header](https://developer.mozilla.org/en-US/docs/Glossary/Request_header)
  32402. * for configuring the HTTP request.
  32403. * @return {Loader} A reference to this instance.
  32404. */
  32405. setRequestHeader( requestHeader ) {
  32406. this.requestHeader = requestHeader;
  32407. return this;
  32408. }
  32409. /**
  32410. * This method can be implemented in loaders for aborting ongoing requests.
  32411. *
  32412. * @abstract
  32413. * @return {Loader} A reference to this instance.
  32414. */
  32415. abort() {
  32416. return this;
  32417. }
  32418. }
  32419. /**
  32420. * Callback for onProgress in loaders.
  32421. *
  32422. * @callback onProgressCallback
  32423. * @param {ProgressEvent} event - An instance of `ProgressEvent` that represents the current loading status.
  32424. */
  32425. /**
  32426. * Callback for onError in loaders.
  32427. *
  32428. * @callback onErrorCallback
  32429. * @param {Error} error - The error which occurred during the loading process.
  32430. */
  32431. /**
  32432. * The default material name that is used by loaders
  32433. * when creating materials for loaded 3D objects.
  32434. *
  32435. * Note: Not all loaders might honor this setting.
  32436. *
  32437. * @static
  32438. * @type {string}
  32439. * @default '__DEFAULT'
  32440. */
  32441. Loader.DEFAULT_MATERIAL_NAME = '__DEFAULT';
  32442. const loading = {};
  32443. class HttpError extends Error {
  32444. constructor( message, response ) {
  32445. super( message );
  32446. this.response = response;
  32447. }
  32448. }
  32449. /**
  32450. * A low level class for loading resources with the Fetch API, used internally by
  32451. * most loaders. It can also be used directly to load any file type that does
  32452. * not have a loader.
  32453. *
  32454. * This loader supports caching. If you want to use it, add `THREE.Cache.enabled = true;`
  32455. * once to your application.
  32456. *
  32457. * ```js
  32458. * const loader = new THREE.FileLoader();
  32459. * const data = await loader.loadAsync( 'example.txt' );
  32460. * ```
  32461. *
  32462. * @augments Loader
  32463. */
  32464. class FileLoader extends Loader {
  32465. /**
  32466. * Constructs a new file loader.
  32467. *
  32468. * @param {LoadingManager} [manager] - The loading manager.
  32469. */
  32470. constructor( manager ) {
  32471. super( manager );
  32472. /**
  32473. * The expected mime type. Valid values can be found
  32474. * [here](hhttps://developer.mozilla.org/en-US/docs/Web/API/DOMParser/parseFromString#mimetype)
  32475. *
  32476. * @type {string}
  32477. */
  32478. this.mimeType = '';
  32479. /**
  32480. * The expected response type.
  32481. *
  32482. * @type {('arraybuffer'|'blob'|'document'|'json'|'')}
  32483. * @default ''
  32484. */
  32485. this.responseType = '';
  32486. /**
  32487. * Used for aborting requests.
  32488. *
  32489. * @private
  32490. * @type {AbortController}
  32491. */
  32492. this._abortController = new AbortController();
  32493. }
  32494. /**
  32495. * Starts loading from the given URL and pass the loaded response to the `onLoad()` callback.
  32496. *
  32497. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  32498. * @param {function(any)} onLoad - Executed when the loading process has been finished.
  32499. * @param {onProgressCallback} [onProgress] - Executed while the loading is in progress.
  32500. * @param {onErrorCallback} [onError] - Executed when errors occur.
  32501. * @return {any|undefined} The cached resource if available.
  32502. */
  32503. load( url, onLoad, onProgress, onError ) {
  32504. if ( url === undefined ) url = '';
  32505. if ( this.path !== undefined ) url = this.path + url;
  32506. url = this.manager.resolveURL( url );
  32507. const cached = Cache.get( `file:${url}` );
  32508. if ( cached !== undefined ) {
  32509. this.manager.itemStart( url );
  32510. setTimeout( () => {
  32511. if ( onLoad ) onLoad( cached );
  32512. this.manager.itemEnd( url );
  32513. }, 0 );
  32514. return cached;
  32515. }
  32516. // Check if request is duplicate
  32517. if ( loading[ url ] !== undefined ) {
  32518. loading[ url ].push( {
  32519. onLoad: onLoad,
  32520. onProgress: onProgress,
  32521. onError: onError
  32522. } );
  32523. return;
  32524. }
  32525. // Initialise array for duplicate requests
  32526. loading[ url ] = [];
  32527. loading[ url ].push( {
  32528. onLoad: onLoad,
  32529. onProgress: onProgress,
  32530. onError: onError,
  32531. } );
  32532. // create request
  32533. const req = new Request( url, {
  32534. headers: new Headers( this.requestHeader ),
  32535. credentials: this.withCredentials ? 'include' : 'same-origin',
  32536. signal: ( typeof AbortSignal.any === 'function' ) ? AbortSignal.any( [ this._abortController.signal, this.manager.abortController.signal ] ) : this._abortController.signal
  32537. } );
  32538. // record states ( avoid data race )
  32539. const mimeType = this.mimeType;
  32540. const responseType = this.responseType;
  32541. // start the fetch
  32542. fetch( req )
  32543. .then( response => {
  32544. if ( response.status === 200 || response.status === 0 ) {
  32545. // Some browsers return HTTP Status 0 when using non-http protocol
  32546. // e.g. 'file://' or 'data://'. Handle as success.
  32547. if ( response.status === 0 ) {
  32548. warn( 'FileLoader: HTTP Status 0 received.' );
  32549. }
  32550. // Workaround: Checking if response.body === undefined for Alipay browser #23548
  32551. if ( typeof ReadableStream === 'undefined' || response.body === undefined || response.body.getReader === undefined ) {
  32552. return response;
  32553. }
  32554. const callbacks = loading[ url ];
  32555. const reader = response.body.getReader();
  32556. // Nginx needs X-File-Size check
  32557. // https://serverfault.com/questions/482875/why-does-nginx-remove-content-length-header-for-chunked-content
  32558. const contentLength = response.headers.get( 'X-File-Size' ) || response.headers.get( 'Content-Length' );
  32559. const total = contentLength ? parseInt( contentLength ) : 0;
  32560. const lengthComputable = total !== 0;
  32561. let loaded = 0;
  32562. // periodically read data into the new stream tracking while download progress
  32563. const stream = new ReadableStream( {
  32564. start( controller ) {
  32565. readData();
  32566. function readData() {
  32567. reader.read().then( ( { done, value } ) => {
  32568. if ( done ) {
  32569. controller.close();
  32570. } else {
  32571. loaded += value.byteLength;
  32572. const event = new ProgressEvent( 'progress', { lengthComputable, loaded, total } );
  32573. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  32574. const callback = callbacks[ i ];
  32575. if ( callback.onProgress ) callback.onProgress( event );
  32576. }
  32577. controller.enqueue( value );
  32578. readData();
  32579. }
  32580. }, ( e ) => {
  32581. controller.error( e );
  32582. } );
  32583. }
  32584. }
  32585. } );
  32586. return new Response( stream );
  32587. } else {
  32588. throw new HttpError( `fetch for "${response.url}" responded with ${response.status}: ${response.statusText}`, response );
  32589. }
  32590. } )
  32591. .then( response => {
  32592. switch ( responseType ) {
  32593. case 'arraybuffer':
  32594. return response.arrayBuffer();
  32595. case 'blob':
  32596. return response.blob();
  32597. case 'document':
  32598. return response.text()
  32599. .then( text => {
  32600. const parser = new DOMParser();
  32601. return parser.parseFromString( text, mimeType );
  32602. } );
  32603. case 'json':
  32604. return response.json();
  32605. default:
  32606. if ( mimeType === '' ) {
  32607. return response.text();
  32608. } else {
  32609. // sniff encoding
  32610. const re = /charset="?([^;"\s]*)"?/i;
  32611. const exec = re.exec( mimeType );
  32612. const label = exec && exec[ 1 ] ? exec[ 1 ].toLowerCase() : undefined;
  32613. const decoder = new TextDecoder( label );
  32614. return response.arrayBuffer().then( ab => decoder.decode( ab ) );
  32615. }
  32616. }
  32617. } )
  32618. .then( data => {
  32619. // Add to cache only on HTTP success, so that we do not cache
  32620. // error response bodies as proper responses to requests.
  32621. Cache.add( `file:${url}`, data );
  32622. const callbacks = loading[ url ];
  32623. delete loading[ url ];
  32624. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  32625. const callback = callbacks[ i ];
  32626. if ( callback.onLoad ) callback.onLoad( data );
  32627. }
  32628. } )
  32629. .catch( err => {
  32630. // Abort errors and other errors are handled the same
  32631. const callbacks = loading[ url ];
  32632. if ( callbacks === undefined ) {
  32633. // When onLoad was called and url was deleted in `loading`
  32634. this.manager.itemError( url );
  32635. throw err;
  32636. }
  32637. delete loading[ url ];
  32638. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  32639. const callback = callbacks[ i ];
  32640. if ( callback.onError ) callback.onError( err );
  32641. }
  32642. this.manager.itemError( url );
  32643. } )
  32644. .finally( () => {
  32645. this.manager.itemEnd( url );
  32646. } );
  32647. this.manager.itemStart( url );
  32648. }
  32649. /**
  32650. * Sets the expected response type.
  32651. *
  32652. * @param {('arraybuffer'|'blob'|'document'|'json'|'')} value - The response type.
  32653. * @return {FileLoader} A reference to this file loader.
  32654. */
  32655. setResponseType( value ) {
  32656. this.responseType = value;
  32657. return this;
  32658. }
  32659. /**
  32660. * Sets the expected mime type of the loaded file.
  32661. *
  32662. * @param {string} value - The mime type.
  32663. * @return {FileLoader} A reference to this file loader.
  32664. */
  32665. setMimeType( value ) {
  32666. this.mimeType = value;
  32667. return this;
  32668. }
  32669. /**
  32670. * Aborts ongoing fetch requests.
  32671. *
  32672. * @return {FileLoader} A reference to this instance.
  32673. */
  32674. abort() {
  32675. this._abortController.abort();
  32676. this._abortController = new AbortController();
  32677. return this;
  32678. }
  32679. }
  32680. /**
  32681. * Class for loading animation clips in the JSON format. The files are internally
  32682. * loaded via {@link FileLoader}.
  32683. *
  32684. * ```js
  32685. * const loader = new THREE.AnimationLoader();
  32686. * const animations = await loader.loadAsync( 'animations/animation.js' );
  32687. * ```
  32688. *
  32689. * @augments Loader
  32690. */
  32691. class AnimationLoader extends Loader {
  32692. /**
  32693. * Constructs a new animation loader.
  32694. *
  32695. * @param {LoadingManager} [manager] - The loading manager.
  32696. */
  32697. constructor( manager ) {
  32698. super( manager );
  32699. }
  32700. /**
  32701. * Starts loading from the given URL and pass the loaded animations as an array
  32702. * holding instances of {@link AnimationClip} to the `onLoad()` callback.
  32703. *
  32704. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  32705. * @param {function(Array<AnimationClip>)} onLoad - Executed when the loading process has been finished.
  32706. * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
  32707. * @param {onErrorCallback} onError - Executed when errors occur.
  32708. */
  32709. load( url, onLoad, onProgress, onError ) {
  32710. const scope = this;
  32711. const loader = new FileLoader( this.manager );
  32712. loader.setPath( this.path );
  32713. loader.setRequestHeader( this.requestHeader );
  32714. loader.setWithCredentials( this.withCredentials );
  32715. loader.load( url, function ( text ) {
  32716. try {
  32717. onLoad( scope.parse( JSON.parse( text ) ) );
  32718. } catch ( e ) {
  32719. if ( onError ) {
  32720. onError( e );
  32721. } else {
  32722. error( e );
  32723. }
  32724. scope.manager.itemError( url );
  32725. }
  32726. }, onProgress, onError );
  32727. }
  32728. /**
  32729. * Parses the given JSON object and returns an array of animation clips.
  32730. *
  32731. * @param {Object} json - The serialized animation clips.
  32732. * @return {Array<AnimationClip>} The parsed animation clips.
  32733. */
  32734. parse( json ) {
  32735. const animations = [];
  32736. for ( let i = 0; i < json.length; i ++ ) {
  32737. const clip = AnimationClip.parse( json[ i ] );
  32738. animations.push( clip );
  32739. }
  32740. return animations;
  32741. }
  32742. }
  32743. /**
  32744. * Abstract base class for loading compressed texture formats S3TC, ASTC or ETC.
  32745. * Textures are internally loaded via {@link FileLoader}.
  32746. *
  32747. * Derived classes have to implement the `parse()` method which holds the parsing
  32748. * for the respective format.
  32749. *
  32750. * @abstract
  32751. * @augments Loader
  32752. */
  32753. class CompressedTextureLoader extends Loader {
  32754. /**
  32755. * Constructs a new compressed texture loader.
  32756. *
  32757. * @param {LoadingManager} [manager] - The loading manager.
  32758. */
  32759. constructor( manager ) {
  32760. super( manager );
  32761. }
  32762. /**
  32763. * Starts loading from the given URL and passes the loaded compressed texture
  32764. * to the `onLoad()` callback. The method also returns a new texture object which can
  32765. * directly be used for material creation. If you do it this way, the texture
  32766. * may pop up in your scene once the respective loading process is finished.
  32767. *
  32768. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  32769. * @param {function(CompressedTexture)} onLoad - Executed when the loading process has been finished.
  32770. * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
  32771. * @param {onErrorCallback} onError - Executed when errors occur.
  32772. * @return {CompressedTexture} The compressed texture.
  32773. */
  32774. load( url, onLoad, onProgress, onError ) {
  32775. const scope = this;
  32776. const images = [];
  32777. const texture = new CompressedTexture();
  32778. const loader = new FileLoader( this.manager );
  32779. loader.setPath( this.path );
  32780. loader.setResponseType( 'arraybuffer' );
  32781. loader.setRequestHeader( this.requestHeader );
  32782. loader.setWithCredentials( scope.withCredentials );
  32783. let loaded = 0;
  32784. function loadTexture( i ) {
  32785. loader.load( url[ i ], function ( buffer ) {
  32786. const texDatas = scope.parse( buffer, true );
  32787. images[ i ] = {
  32788. width: texDatas.width,
  32789. height: texDatas.height,
  32790. format: texDatas.format,
  32791. mipmaps: texDatas.mipmaps
  32792. };
  32793. loaded += 1;
  32794. if ( loaded === 6 ) {
  32795. if ( texDatas.mipmapCount === 1 ) texture.minFilter = LinearFilter;
  32796. texture.image = images;
  32797. texture.format = texDatas.format;
  32798. texture.needsUpdate = true;
  32799. if ( onLoad ) onLoad( texture );
  32800. }
  32801. }, onProgress, onError );
  32802. }
  32803. if ( Array.isArray( url ) ) {
  32804. for ( let i = 0, il = url.length; i < il; ++ i ) {
  32805. loadTexture( i );
  32806. }
  32807. } else {
  32808. // compressed cubemap texture stored in a single DDS file
  32809. loader.load( url, function ( buffer ) {
  32810. const texDatas = scope.parse( buffer, true );
  32811. if ( texDatas.isCubemap ) {
  32812. const faces = texDatas.mipmaps.length / texDatas.mipmapCount;
  32813. for ( let f = 0; f < faces; f ++ ) {
  32814. images[ f ] = { mipmaps: [] };
  32815. for ( let i = 0; i < texDatas.mipmapCount; i ++ ) {
  32816. images[ f ].mipmaps.push( texDatas.mipmaps[ f * texDatas.mipmapCount + i ] );
  32817. images[ f ].format = texDatas.format;
  32818. images[ f ].width = texDatas.width;
  32819. images[ f ].height = texDatas.height;
  32820. }
  32821. }
  32822. texture.image = images;
  32823. } else {
  32824. texture.image.width = texDatas.width;
  32825. texture.image.height = texDatas.height;
  32826. texture.mipmaps = texDatas.mipmaps;
  32827. }
  32828. if ( texDatas.mipmapCount === 1 ) {
  32829. texture.minFilter = LinearFilter;
  32830. }
  32831. texture.format = texDatas.format;
  32832. texture.needsUpdate = true;
  32833. if ( onLoad ) onLoad( texture );
  32834. }, onProgress, onError );
  32835. }
  32836. return texture;
  32837. }
  32838. }
  32839. const _loading = new WeakMap();
  32840. /**
  32841. * A loader for loading images. The class loads images with the HTML `Image` API.
  32842. *
  32843. * ```js
  32844. * const loader = new THREE.ImageLoader();
  32845. * const image = await loader.loadAsync( 'image.png' );
  32846. * ```
  32847. * Please note that `ImageLoader` has dropped support for progress
  32848. * events in `r84`. For an `ImageLoader` that supports progress events, see
  32849. * [this thread](https://github.com/mrdoob/three.js/issues/10439#issuecomment-275785639).
  32850. *
  32851. * @augments Loader
  32852. */
  32853. class ImageLoader extends Loader {
  32854. /**
  32855. * Constructs a new image loader.
  32856. *
  32857. * @param {LoadingManager} [manager] - The loading manager.
  32858. */
  32859. constructor( manager ) {
  32860. super( manager );
  32861. }
  32862. /**
  32863. * Starts loading from the given URL and passes the loaded image
  32864. * to the `onLoad()` callback. The method also returns a new `Image` object which can
  32865. * directly be used for texture creation. If you do it this way, the texture
  32866. * may pop up in your scene once the respective loading process is finished.
  32867. *
  32868. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  32869. * @param {function(Image)} onLoad - Executed when the loading process has been finished.
  32870. * @param {onProgressCallback} onProgress - Unsupported in this loader.
  32871. * @param {onErrorCallback} onError - Executed when errors occur.
  32872. * @return {Image} The image.
  32873. */
  32874. load( url, onLoad, onProgress, onError ) {
  32875. if ( this.path !== undefined ) url = this.path + url;
  32876. url = this.manager.resolveURL( url );
  32877. const scope = this;
  32878. const cached = Cache.get( `image:${url}` );
  32879. if ( cached !== undefined ) {
  32880. if ( cached.complete === true ) {
  32881. scope.manager.itemStart( url );
  32882. setTimeout( function () {
  32883. if ( onLoad ) onLoad( cached );
  32884. scope.manager.itemEnd( url );
  32885. }, 0 );
  32886. } else {
  32887. let arr = _loading.get( cached );
  32888. if ( arr === undefined ) {
  32889. arr = [];
  32890. _loading.set( cached, arr );
  32891. }
  32892. arr.push( { onLoad, onError } );
  32893. }
  32894. return cached;
  32895. }
  32896. const image = createElementNS( 'img' );
  32897. function onImageLoad() {
  32898. removeEventListeners();
  32899. if ( onLoad ) onLoad( this );
  32900. //
  32901. const callbacks = _loading.get( this ) || [];
  32902. for ( let i = 0; i < callbacks.length; i ++ ) {
  32903. const callback = callbacks[ i ];
  32904. if ( callback.onLoad ) callback.onLoad( this );
  32905. }
  32906. _loading.delete( this );
  32907. scope.manager.itemEnd( url );
  32908. }
  32909. function onImageError( event ) {
  32910. removeEventListeners();
  32911. if ( onError ) onError( event );
  32912. Cache.remove( `image:${url}` );
  32913. //
  32914. const callbacks = _loading.get( this ) || [];
  32915. for ( let i = 0; i < callbacks.length; i ++ ) {
  32916. const callback = callbacks[ i ];
  32917. if ( callback.onError ) callback.onError( event );
  32918. }
  32919. _loading.delete( this );
  32920. scope.manager.itemError( url );
  32921. scope.manager.itemEnd( url );
  32922. }
  32923. function removeEventListeners() {
  32924. image.removeEventListener( 'load', onImageLoad, false );
  32925. image.removeEventListener( 'error', onImageError, false );
  32926. }
  32927. image.addEventListener( 'load', onImageLoad, false );
  32928. image.addEventListener( 'error', onImageError, false );
  32929. if ( url.slice( 0, 5 ) !== 'data:' ) {
  32930. if ( this.crossOrigin !== undefined ) image.crossOrigin = this.crossOrigin;
  32931. }
  32932. Cache.add( `image:${url}`, image );
  32933. scope.manager.itemStart( url );
  32934. image.src = url;
  32935. return image;
  32936. }
  32937. }
  32938. /**
  32939. * Class for loading cube textures. Images are internally loaded via {@link ImageLoader}.
  32940. *
  32941. * The loader returns an instance of {@link CubeTexture} and expects the cube map to
  32942. * be defined as six separate images representing the sides of a cube. Other cube map definitions
  32943. * like vertical and horizontal cross, column and row layouts are not supported.
  32944. *
  32945. * Note that, by convention, cube maps are specified in a coordinate system
  32946. * in which positive-x is to the right when looking up the positive-z axis --
  32947. * in other words, using a left-handed coordinate system. Since three.js uses
  32948. * a right-handed coordinate system, environment maps used in three.js will
  32949. * have pos-x and neg-x swapped.
  32950. *
  32951. * The loaded cube texture is in sRGB color space. Meaning {@link Texture#colorSpace}
  32952. * is set to `SRGBColorSpace` by default.
  32953. *
  32954. * ```js
  32955. * const loader = new THREE.CubeTextureLoader().setPath( 'textures/cubeMaps/' );
  32956. * const cubeTexture = await loader.loadAsync( [
  32957. * 'px.png', 'nx.png', 'py.png', 'ny.png', 'pz.png', 'nz.png'
  32958. * ] );
  32959. * scene.background = cubeTexture;
  32960. * ```
  32961. *
  32962. * @augments Loader
  32963. */
  32964. class CubeTextureLoader extends Loader {
  32965. /**
  32966. * Constructs a new cube texture loader.
  32967. *
  32968. * @param {LoadingManager} [manager] - The loading manager.
  32969. */
  32970. constructor( manager ) {
  32971. super( manager );
  32972. }
  32973. /**
  32974. * Starts loading from the given URL and pass the fully loaded cube texture
  32975. * to the `onLoad()` callback. The method also returns a new cube texture object which can
  32976. * directly be used for material creation. If you do it this way, the cube texture
  32977. * may pop up in your scene once the respective loading process is finished.
  32978. *
  32979. * @param {Array<string>} urls - Array of 6 URLs to images, one for each side of the
  32980. * cube texture. The urls should be specified in the following order: pos-x,
  32981. * neg-x, pos-y, neg-y, pos-z, neg-z. An array of data URIs are allowed as well.
  32982. * @param {function(CubeTexture)} onLoad - Executed when the loading process has been finished.
  32983. * @param {onProgressCallback} onProgress - Unsupported in this loader.
  32984. * @param {onErrorCallback} onError - Executed when errors occur.
  32985. * @return {CubeTexture} The cube texture.
  32986. */
  32987. load( urls, onLoad, onProgress, onError ) {
  32988. const texture = new CubeTexture();
  32989. texture.colorSpace = SRGBColorSpace;
  32990. const loader = new ImageLoader( this.manager );
  32991. loader.setCrossOrigin( this.crossOrigin );
  32992. loader.setPath( this.path );
  32993. let loaded = 0;
  32994. function loadTexture( i ) {
  32995. loader.load( urls[ i ], function ( image ) {
  32996. texture.images[ i ] = image;
  32997. loaded ++;
  32998. if ( loaded === 6 ) {
  32999. texture.needsUpdate = true;
  33000. if ( onLoad ) onLoad( texture );
  33001. }
  33002. }, undefined, onError );
  33003. }
  33004. for ( let i = 0; i < urls.length; ++ i ) {
  33005. loadTexture( i );
  33006. }
  33007. return texture;
  33008. }
  33009. }
  33010. /**
  33011. * Abstract base class for loading binary texture formats RGBE, EXR or TGA.
  33012. * Textures are internally loaded via {@link FileLoader}.
  33013. *
  33014. * Derived classes have to implement the `parse()` method which holds the parsing
  33015. * for the respective format.
  33016. *
  33017. * @abstract
  33018. * @augments Loader
  33019. */
  33020. class DataTextureLoader extends Loader {
  33021. /**
  33022. * Constructs a new data texture loader.
  33023. *
  33024. * @param {LoadingManager} [manager] - The loading manager.
  33025. */
  33026. constructor( manager ) {
  33027. super( manager );
  33028. }
  33029. /**
  33030. * Starts loading from the given URL and passes the loaded data texture
  33031. * to the `onLoad()` callback. The method also returns a new texture object which can
  33032. * directly be used for material creation. If you do it this way, the texture
  33033. * may pop up in your scene once the respective loading process is finished.
  33034. *
  33035. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  33036. * @param {function(DataTexture)} onLoad - Executed when the loading process has been finished.
  33037. * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
  33038. * @param {onErrorCallback} onError - Executed when errors occur.
  33039. * @return {DataTexture} The data texture.
  33040. */
  33041. load( url, onLoad, onProgress, onError ) {
  33042. const scope = this;
  33043. const texture = new DataTexture();
  33044. const loader = new FileLoader( this.manager );
  33045. loader.setResponseType( 'arraybuffer' );
  33046. loader.setRequestHeader( this.requestHeader );
  33047. loader.setPath( this.path );
  33048. loader.setWithCredentials( scope.withCredentials );
  33049. loader.load( url, function ( buffer ) {
  33050. let texData;
  33051. try {
  33052. texData = scope.parse( buffer );
  33053. } catch ( error ) {
  33054. if ( onError !== undefined ) {
  33055. onError( error );
  33056. } else {
  33057. error( error );
  33058. return;
  33059. }
  33060. }
  33061. if ( texData.image !== undefined ) {
  33062. texture.image = texData.image;
  33063. } else if ( texData.data !== undefined ) {
  33064. texture.image.width = texData.width;
  33065. texture.image.height = texData.height;
  33066. texture.image.data = texData.data;
  33067. }
  33068. texture.wrapS = texData.wrapS !== undefined ? texData.wrapS : ClampToEdgeWrapping;
  33069. texture.wrapT = texData.wrapT !== undefined ? texData.wrapT : ClampToEdgeWrapping;
  33070. texture.magFilter = texData.magFilter !== undefined ? texData.magFilter : LinearFilter;
  33071. texture.minFilter = texData.minFilter !== undefined ? texData.minFilter : LinearFilter;
  33072. texture.anisotropy = texData.anisotropy !== undefined ? texData.anisotropy : 1;
  33073. if ( texData.colorSpace !== undefined ) {
  33074. texture.colorSpace = texData.colorSpace;
  33075. }
  33076. if ( texData.flipY !== undefined ) {
  33077. texture.flipY = texData.flipY;
  33078. }
  33079. if ( texData.format !== undefined ) {
  33080. texture.format = texData.format;
  33081. }
  33082. if ( texData.type !== undefined ) {
  33083. texture.type = texData.type;
  33084. }
  33085. if ( texData.mipmaps !== undefined ) {
  33086. texture.mipmaps = texData.mipmaps;
  33087. texture.minFilter = LinearMipmapLinearFilter; // presumably...
  33088. }
  33089. if ( texData.mipmapCount === 1 ) {
  33090. texture.minFilter = LinearFilter;
  33091. }
  33092. if ( texData.generateMipmaps !== undefined ) {
  33093. texture.generateMipmaps = texData.generateMipmaps;
  33094. }
  33095. texture.needsUpdate = true;
  33096. if ( onLoad ) onLoad( texture, texData );
  33097. }, onProgress, onError );
  33098. return texture;
  33099. }
  33100. }
  33101. /**
  33102. * Class for loading textures. Images are internally
  33103. * loaded via {@link ImageLoader}.
  33104. *
  33105. * ```js
  33106. * const loader = new THREE.TextureLoader();
  33107. * const texture = await loader.loadAsync( 'textures/land_ocean_ice_cloud_2048.jpg' );
  33108. *
  33109. * const material = new THREE.MeshBasicMaterial( { map:texture } );
  33110. * ```
  33111. * Please note that `TextureLoader` has dropped support for progress
  33112. * events in `r84`. For a `TextureLoader` that supports progress events, see
  33113. * [this thread](https://github.com/mrdoob/three.js/issues/10439#issuecomment-293260145).
  33114. *
  33115. * @augments Loader
  33116. */
  33117. class TextureLoader extends Loader {
  33118. /**
  33119. * Constructs a new texture loader.
  33120. *
  33121. * @param {LoadingManager} [manager] - The loading manager.
  33122. */
  33123. constructor( manager ) {
  33124. super( manager );
  33125. }
  33126. /**
  33127. * Starts loading from the given URL and pass the fully loaded texture
  33128. * to the `onLoad()` callback. The method also returns a new texture object which can
  33129. * directly be used for material creation. If you do it this way, the texture
  33130. * may pop up in your scene once the respective loading process is finished.
  33131. *
  33132. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  33133. * @param {function(Texture)} onLoad - Executed when the loading process has been finished.
  33134. * @param {onProgressCallback} onProgress - Unsupported in this loader.
  33135. * @param {onErrorCallback} onError - Executed when errors occur.
  33136. * @return {Texture} The texture.
  33137. */
  33138. load( url, onLoad, onProgress, onError ) {
  33139. const texture = new Texture();
  33140. const loader = new ImageLoader( this.manager );
  33141. loader.setCrossOrigin( this.crossOrigin );
  33142. loader.setPath( this.path );
  33143. loader.load( url, function ( image ) {
  33144. texture.image = image;
  33145. texture.needsUpdate = true;
  33146. if ( onLoad !== undefined ) {
  33147. onLoad( texture );
  33148. }
  33149. }, onProgress, onError );
  33150. return texture;
  33151. }
  33152. }
  33153. /**
  33154. * Abstract base class for lights - all other light types inherit the
  33155. * properties and methods described here.
  33156. *
  33157. * @abstract
  33158. * @augments Object3D
  33159. */
  33160. class Light extends Object3D {
  33161. /**
  33162. * Constructs a new light.
  33163. *
  33164. * @param {(number|Color|string)} [color=0xffffff] - The light's color.
  33165. * @param {number} [intensity=1] - The light's strength/intensity.
  33166. */
  33167. constructor( color, intensity = 1 ) {
  33168. super();
  33169. /**
  33170. * This flag can be used for type testing.
  33171. *
  33172. * @type {boolean}
  33173. * @readonly
  33174. * @default true
  33175. */
  33176. this.isLight = true;
  33177. this.type = 'Light';
  33178. /**
  33179. * The light's color.
  33180. *
  33181. * @type {Color}
  33182. */
  33183. this.color = new Color( color );
  33184. /**
  33185. * The light's intensity.
  33186. *
  33187. * @type {number}
  33188. * @default 1
  33189. */
  33190. this.intensity = intensity;
  33191. }
  33192. /**
  33193. * Frees the GPU-related resources allocated by this instance. Call this
  33194. * method whenever this instance is no longer used in your app.
  33195. */
  33196. dispose() {
  33197. this.dispatchEvent( { type: 'dispose' } );
  33198. }
  33199. copy( source, recursive ) {
  33200. super.copy( source, recursive );
  33201. this.color.copy( source.color );
  33202. this.intensity = source.intensity;
  33203. return this;
  33204. }
  33205. toJSON( meta ) {
  33206. const data = super.toJSON( meta );
  33207. data.object.color = this.color.getHex();
  33208. data.object.intensity = this.intensity;
  33209. return data;
  33210. }
  33211. }
  33212. /**
  33213. * A light source positioned directly above the scene, with color fading from
  33214. * the sky color to the ground color.
  33215. *
  33216. * This light cannot be used to cast shadows.
  33217. *
  33218. * ```js
  33219. * const light = new THREE.HemisphereLight( 0xffffbb, 0x080820, 1 );
  33220. * scene.add( light );
  33221. * ```
  33222. *
  33223. * @augments Light
  33224. */
  33225. class HemisphereLight extends Light {
  33226. /**
  33227. * Constructs a new hemisphere light.
  33228. *
  33229. * @param {(number|Color|string)} [skyColor=0xffffff] - The light's sky color.
  33230. * @param {(number|Color|string)} [groundColor=0xffffff] - The light's ground color.
  33231. * @param {number} [intensity=1] - The light's strength/intensity.
  33232. */
  33233. constructor( skyColor, groundColor, intensity ) {
  33234. super( skyColor, intensity );
  33235. /**
  33236. * This flag can be used for type testing.
  33237. *
  33238. * @type {boolean}
  33239. * @readonly
  33240. * @default true
  33241. */
  33242. this.isHemisphereLight = true;
  33243. this.type = 'HemisphereLight';
  33244. this.position.copy( Object3D.DEFAULT_UP );
  33245. this.updateMatrix();
  33246. /**
  33247. * The light's ground color.
  33248. *
  33249. * @type {Color}
  33250. */
  33251. this.groundColor = new Color( groundColor );
  33252. }
  33253. copy( source, recursive ) {
  33254. super.copy( source, recursive );
  33255. this.groundColor.copy( source.groundColor );
  33256. return this;
  33257. }
  33258. toJSON( meta ) {
  33259. const data = super.toJSON( meta );
  33260. data.object.groundColor = this.groundColor.getHex();
  33261. return data;
  33262. }
  33263. }
  33264. const _projScreenMatrix = /*@__PURE__*/ new Matrix4();
  33265. const _lightPositionWorld = /*@__PURE__*/ new Vector3();
  33266. const _lookTarget = /*@__PURE__*/ new Vector3();
  33267. /**
  33268. * Abstract base class for light shadow classes. These classes
  33269. * represent the shadow configuration for different light types.
  33270. *
  33271. * @abstract
  33272. */
  33273. class LightShadow {
  33274. /**
  33275. * Constructs a new light shadow.
  33276. *
  33277. * @param {Camera} camera - The light's view of the world.
  33278. */
  33279. constructor( camera ) {
  33280. /**
  33281. * The light's view of the world.
  33282. *
  33283. * @type {Camera}
  33284. */
  33285. this.camera = camera;
  33286. /**
  33287. * The intensity of the shadow. The default is `1`.
  33288. * Valid values are in the range `[0, 1]`.
  33289. *
  33290. * @type {number}
  33291. * @default 1
  33292. */
  33293. this.intensity = 1;
  33294. /**
  33295. * Shadow map bias, how much to add or subtract from the normalized depth
  33296. * when deciding whether a surface is in shadow.
  33297. *
  33298. * The default is `0`. Very tiny adjustments here (in the order of `0.0001`)
  33299. * may help reduce artifacts in shadows.
  33300. *
  33301. * @type {number}
  33302. * @default 0
  33303. */
  33304. this.bias = 0;
  33305. /**
  33306. * Defines how much the position used to query the shadow map is offset along
  33307. * the object normal. The default is `0`. Increasing this value can be used to
  33308. * reduce shadow acne especially in large scenes where light shines onto
  33309. * geometry at a shallow angle. The cost is that shadows may appear distorted.
  33310. *
  33311. * @type {number}
  33312. * @default 0
  33313. */
  33314. this.normalBias = 0;
  33315. /**
  33316. * Setting this to values greater than 1 will blur the edges of the shadow.
  33317. * High values will cause unwanted banding effects in the shadows - a greater
  33318. * map size will allow for a higher value to be used here before these effects
  33319. * become visible.
  33320. *
  33321. * The property has no effect when the shadow map type is `BasicShadowMap`.
  33322. *
  33323. * @type {number}
  33324. * @default 1
  33325. */
  33326. this.radius = 1;
  33327. /**
  33328. * The amount of samples to use when blurring a VSM shadow map.
  33329. *
  33330. * @type {number}
  33331. * @default 8
  33332. */
  33333. this.blurSamples = 8;
  33334. /**
  33335. * Defines the width and height of the shadow map. Higher values give better quality
  33336. * shadows at the cost of computation time. Values must be powers of two.
  33337. *
  33338. * @type {Vector2}
  33339. * @default (512,512)
  33340. */
  33341. this.mapSize = new Vector2( 512, 512 );
  33342. /**
  33343. * The type of shadow texture. The default is `UnsignedByteType`.
  33344. *
  33345. * @type {number}
  33346. * @default UnsignedByteType
  33347. */
  33348. this.mapType = UnsignedByteType;
  33349. /**
  33350. * The depth map generated using the internal camera; a location beyond a
  33351. * pixel's depth is in shadow. Computed internally during rendering.
  33352. *
  33353. * @type {?RenderTarget}
  33354. * @default null
  33355. */
  33356. this.map = null;
  33357. /**
  33358. * The distribution map generated using the internal camera; an occlusion is
  33359. * calculated based on the distribution of depths. Computed internally during
  33360. * rendering.
  33361. *
  33362. * @type {?RenderTarget}
  33363. * @default null
  33364. */
  33365. this.mapPass = null;
  33366. /**
  33367. * Model to shadow camera space, to compute location and depth in shadow map.
  33368. * This is computed internally during rendering.
  33369. *
  33370. * @type {Matrix4}
  33371. */
  33372. this.matrix = new Matrix4();
  33373. /**
  33374. * Enables automatic updates of the light's shadow. If you do not require dynamic
  33375. * lighting / shadows, you may set this to `false`.
  33376. *
  33377. * @type {boolean}
  33378. * @default true
  33379. */
  33380. this.autoUpdate = true;
  33381. /**
  33382. * When set to `true`, shadow maps will be updated in the next `render` call.
  33383. * If you have set {@link LightShadow#autoUpdate} to `false`, you will need to
  33384. * set this property to `true` and then make a render call to update the light's shadow.
  33385. *
  33386. * @type {boolean}
  33387. * @default false
  33388. */
  33389. this.needsUpdate = false;
  33390. this._frustum = new Frustum();
  33391. this._frameExtents = new Vector2( 1, 1 );
  33392. this._viewportCount = 1;
  33393. this._viewports = [
  33394. new Vector4( 0, 0, 1, 1 )
  33395. ];
  33396. }
  33397. /**
  33398. * Used internally by the renderer to get the number of viewports that need
  33399. * to be rendered for this shadow.
  33400. *
  33401. * @return {number} The viewport count.
  33402. */
  33403. getViewportCount() {
  33404. return this._viewportCount;
  33405. }
  33406. /**
  33407. * Gets the shadow cameras frustum. Used internally by the renderer to cull objects.
  33408. *
  33409. * @return {Frustum} The shadow camera frustum.
  33410. */
  33411. getFrustum() {
  33412. return this._frustum;
  33413. }
  33414. /**
  33415. * Update the matrices for the camera and shadow, used internally by the renderer.
  33416. *
  33417. * @param {Light} light - The light for which the shadow is being rendered.
  33418. */
  33419. updateMatrices( light ) {
  33420. const shadowCamera = this.camera;
  33421. const shadowMatrix = this.matrix;
  33422. _lightPositionWorld.setFromMatrixPosition( light.matrixWorld );
  33423. shadowCamera.position.copy( _lightPositionWorld );
  33424. _lookTarget.setFromMatrixPosition( light.target.matrixWorld );
  33425. shadowCamera.lookAt( _lookTarget );
  33426. shadowCamera.updateMatrixWorld();
  33427. _projScreenMatrix.multiplyMatrices( shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse );
  33428. this._frustum.setFromProjectionMatrix( _projScreenMatrix, shadowCamera.coordinateSystem, shadowCamera.reversedDepth );
  33429. if ( shadowCamera.reversedDepth ) {
  33430. shadowMatrix.set(
  33431. 0.5, 0.0, 0.0, 0.5,
  33432. 0.0, 0.5, 0.0, 0.5,
  33433. 0.0, 0.0, 1.0, 0.0,
  33434. 0.0, 0.0, 0.0, 1.0
  33435. );
  33436. } else {
  33437. shadowMatrix.set(
  33438. 0.5, 0.0, 0.0, 0.5,
  33439. 0.0, 0.5, 0.0, 0.5,
  33440. 0.0, 0.0, 0.5, 0.5,
  33441. 0.0, 0.0, 0.0, 1.0
  33442. );
  33443. }
  33444. shadowMatrix.multiply( _projScreenMatrix );
  33445. }
  33446. /**
  33447. * Returns a viewport definition for the given viewport index.
  33448. *
  33449. * @param {number} viewportIndex - The viewport index.
  33450. * @return {Vector4} The viewport.
  33451. */
  33452. getViewport( viewportIndex ) {
  33453. return this._viewports[ viewportIndex ];
  33454. }
  33455. /**
  33456. * Returns the frame extends.
  33457. *
  33458. * @return {Vector2} The frame extends.
  33459. */
  33460. getFrameExtents() {
  33461. return this._frameExtents;
  33462. }
  33463. /**
  33464. * Frees the GPU-related resources allocated by this instance. Call this
  33465. * method whenever this instance is no longer used in your app.
  33466. */
  33467. dispose() {
  33468. if ( this.map ) {
  33469. this.map.dispose();
  33470. }
  33471. if ( this.mapPass ) {
  33472. this.mapPass.dispose();
  33473. }
  33474. }
  33475. /**
  33476. * Copies the values of the given light shadow instance to this instance.
  33477. *
  33478. * @param {LightShadow} source - The light shadow to copy.
  33479. * @return {LightShadow} A reference to this light shadow instance.
  33480. */
  33481. copy( source ) {
  33482. this.camera = source.camera.clone();
  33483. this.intensity = source.intensity;
  33484. this.bias = source.bias;
  33485. this.radius = source.radius;
  33486. this.autoUpdate = source.autoUpdate;
  33487. this.needsUpdate = source.needsUpdate;
  33488. this.normalBias = source.normalBias;
  33489. this.blurSamples = source.blurSamples;
  33490. this.mapSize.copy( source.mapSize );
  33491. return this;
  33492. }
  33493. /**
  33494. * Returns a new light shadow instance with copied values from this instance.
  33495. *
  33496. * @return {LightShadow} A clone of this instance.
  33497. */
  33498. clone() {
  33499. return new this.constructor().copy( this );
  33500. }
  33501. /**
  33502. * Serializes the light shadow into JSON.
  33503. *
  33504. * @return {Object} A JSON object representing the serialized light shadow.
  33505. * @see {@link ObjectLoader#parse}
  33506. */
  33507. toJSON() {
  33508. const object = {};
  33509. if ( this.intensity !== 1 ) object.intensity = this.intensity;
  33510. if ( this.bias !== 0 ) object.bias = this.bias;
  33511. if ( this.normalBias !== 0 ) object.normalBias = this.normalBias;
  33512. if ( this.radius !== 1 ) object.radius = this.radius;
  33513. if ( this.mapSize.x !== 512 || this.mapSize.y !== 512 ) object.mapSize = this.mapSize.toArray();
  33514. object.camera = this.camera.toJSON( false ).object;
  33515. delete object.camera.matrix;
  33516. return object;
  33517. }
  33518. }
  33519. /**
  33520. * Represents the shadow configuration of directional lights.
  33521. *
  33522. * @augments LightShadow
  33523. */
  33524. class SpotLightShadow extends LightShadow {
  33525. /**
  33526. * Constructs a new spot light shadow.
  33527. */
  33528. constructor() {
  33529. super( new PerspectiveCamera( 50, 1, 0.5, 500 ) );
  33530. /**
  33531. * This flag can be used for type testing.
  33532. *
  33533. * @type {boolean}
  33534. * @readonly
  33535. * @default true
  33536. */
  33537. this.isSpotLightShadow = true;
  33538. /**
  33539. * Used to focus the shadow camera. The camera's field of view is set as a
  33540. * percentage of the spotlight's field-of-view. Range is `[0, 1]`.
  33541. *
  33542. * @type {number}
  33543. * @default 1
  33544. */
  33545. this.focus = 1;
  33546. /**
  33547. * Texture aspect ratio.
  33548. *
  33549. * @type {number}
  33550. * @default 1
  33551. */
  33552. this.aspect = 1;
  33553. }
  33554. updateMatrices( light ) {
  33555. const camera = this.camera;
  33556. const fov = RAD2DEG * 2 * light.angle * this.focus;
  33557. const aspect = ( this.mapSize.width / this.mapSize.height ) * this.aspect;
  33558. const far = light.distance || camera.far;
  33559. if ( fov !== camera.fov || aspect !== camera.aspect || far !== camera.far ) {
  33560. camera.fov = fov;
  33561. camera.aspect = aspect;
  33562. camera.far = far;
  33563. camera.updateProjectionMatrix();
  33564. }
  33565. super.updateMatrices( light );
  33566. }
  33567. copy( source ) {
  33568. super.copy( source );
  33569. this.focus = source.focus;
  33570. return this;
  33571. }
  33572. }
  33573. /**
  33574. * This light gets emitted from a single point in one direction, along a cone
  33575. * that increases in size the further from the light it gets.
  33576. *
  33577. * This light can cast shadows - see the {@link SpotLightShadow} for details.
  33578. *
  33579. * ```js
  33580. * // white spotlight shining from the side, modulated by a texture
  33581. * const spotLight = new THREE.SpotLight( 0xffffff );
  33582. * spotLight.position.set( 100, 1000, 100 );
  33583. * spotLight.map = new THREE.TextureLoader().load( url );
  33584. *
  33585. * spotLight.castShadow = true;
  33586. * spotLight.shadow.mapSize.width = 1024;
  33587. * spotLight.shadow.mapSize.height = 1024;
  33588. * spotLight.shadow.camera.near = 500;
  33589. * spotLight.shadow.camera.far = 4000;
  33590. * spotLight.shadow.camera.fov = 30;s
  33591. * ```
  33592. *
  33593. * @augments Light
  33594. */
  33595. class SpotLight extends Light {
  33596. /**
  33597. * Constructs a new spot light.
  33598. *
  33599. * @param {(number|Color|string)} [color=0xffffff] - The light's color.
  33600. * @param {number} [intensity=1] - The light's strength/intensity measured in candela (cd).
  33601. * @param {number} [distance=0] - Maximum range of the light. `0` means no limit.
  33602. * @param {number} [angle=Math.PI/3] - Maximum angle of light dispersion from its direction whose upper bound is `Math.PI/2`.
  33603. * @param {number} [penumbra=0] - Percent of the spotlight cone that is attenuated due to penumbra. Value range is `[0,1]`.
  33604. * @param {number} [decay=2] - The amount the light dims along the distance of the light.
  33605. */
  33606. constructor( color, intensity, distance = 0, angle = Math.PI / 3, penumbra = 0, decay = 2 ) {
  33607. super( color, intensity );
  33608. /**
  33609. * This flag can be used for type testing.
  33610. *
  33611. * @type {boolean}
  33612. * @readonly
  33613. * @default true
  33614. */
  33615. this.isSpotLight = true;
  33616. this.type = 'SpotLight';
  33617. this.position.copy( Object3D.DEFAULT_UP );
  33618. this.updateMatrix();
  33619. /**
  33620. * The spot light points from its position to the
  33621. * target's position.
  33622. *
  33623. * For the target's position to be changed to anything other
  33624. * than the default, it must be added to the scene.
  33625. *
  33626. * It is also possible to set the target to be another 3D object
  33627. * in the scene. The light will now track the target object.
  33628. *
  33629. * @type {Object3D}
  33630. */
  33631. this.target = new Object3D();
  33632. /**
  33633. * Maximum range of the light. `0` means no limit.
  33634. *
  33635. * @type {number}
  33636. * @default 0
  33637. */
  33638. this.distance = distance;
  33639. /**
  33640. * Maximum angle of light dispersion from its direction whose upper bound is `Math.PI/2`.
  33641. *
  33642. * @type {number}
  33643. * @default Math.PI/3
  33644. */
  33645. this.angle = angle;
  33646. /**
  33647. * Percent of the spotlight cone that is attenuated due to penumbra.
  33648. * Value range is `[0,1]`.
  33649. *
  33650. * @type {number}
  33651. * @default 0
  33652. */
  33653. this.penumbra = penumbra;
  33654. /**
  33655. * The amount the light dims along the distance of the light. In context of
  33656. * physically-correct rendering the default value should not be changed.
  33657. *
  33658. * @type {number}
  33659. * @default 2
  33660. */
  33661. this.decay = decay;
  33662. /**
  33663. * A texture used to modulate the color of the light. The spot light
  33664. * color is mixed with the RGB value of this texture, with a ratio
  33665. * corresponding to its alpha value. The cookie-like masking effect is
  33666. * reproduced using pixel values (0, 0, 0, 1-cookie_value).
  33667. *
  33668. * *Warning*: This property is disabled if {@link Object3D#castShadow} is set to `false`.
  33669. *
  33670. * @type {?Texture}
  33671. * @default null
  33672. */
  33673. this.map = null;
  33674. /**
  33675. * This property holds the light's shadow configuration.
  33676. *
  33677. * @type {SpotLightShadow}
  33678. */
  33679. this.shadow = new SpotLightShadow();
  33680. }
  33681. /**
  33682. * The light's power. Power is the luminous power of the light measured in lumens (lm).
  33683. * Changing the power will also change the light's intensity.
  33684. *
  33685. * @type {number}
  33686. */
  33687. get power() {
  33688. // compute the light's luminous power (in lumens) from its intensity (in candela)
  33689. // by convention for a spotlight, luminous power (lm) = π * luminous intensity (cd)
  33690. return this.intensity * Math.PI;
  33691. }
  33692. set power( power ) {
  33693. // set the light's intensity (in candela) from the desired luminous power (in lumens)
  33694. this.intensity = power / Math.PI;
  33695. }
  33696. dispose() {
  33697. super.dispose();
  33698. this.shadow.dispose();
  33699. }
  33700. copy( source, recursive ) {
  33701. super.copy( source, recursive );
  33702. this.distance = source.distance;
  33703. this.angle = source.angle;
  33704. this.penumbra = source.penumbra;
  33705. this.decay = source.decay;
  33706. this.target = source.target.clone();
  33707. this.map = source.map;
  33708. this.shadow = source.shadow.clone();
  33709. return this;
  33710. }
  33711. toJSON( meta ) {
  33712. const data = super.toJSON( meta );
  33713. data.object.distance = this.distance;
  33714. data.object.angle = this.angle;
  33715. data.object.decay = this.decay;
  33716. data.object.penumbra = this.penumbra;
  33717. data.object.target = this.target.uuid;
  33718. if ( this.map && this.map.isTexture ) data.object.map = this.map.toJSON( meta ).uuid;
  33719. data.object.shadow = this.shadow.toJSON();
  33720. return data;
  33721. }
  33722. }
  33723. /**
  33724. * Represents the shadow configuration of point lights.
  33725. *
  33726. * @augments LightShadow
  33727. */
  33728. class PointLightShadow extends LightShadow {
  33729. /**
  33730. * Constructs a new point light shadow.
  33731. */
  33732. constructor() {
  33733. super( new PerspectiveCamera( 90, 1, 0.5, 500 ) );
  33734. /**
  33735. * This flag can be used for type testing.
  33736. *
  33737. * @type {boolean}
  33738. * @readonly
  33739. * @default true
  33740. */
  33741. this.isPointLightShadow = true;
  33742. }
  33743. }
  33744. /**
  33745. * A light that gets emitted from a single point in all directions. A common
  33746. * use case for this is to replicate the light emitted from a bare
  33747. * lightbulb.
  33748. *
  33749. * This light can cast shadows - see the {@link PointLightShadow} for details.
  33750. *
  33751. * ```js
  33752. * const light = new THREE.PointLight( 0xff0000, 1, 100 );
  33753. * light.position.set( 50, 50, 50 );
  33754. * scene.add( light );
  33755. * ```
  33756. *
  33757. * @augments Light
  33758. */
  33759. class PointLight extends Light {
  33760. /**
  33761. * Constructs a new point light.
  33762. *
  33763. * @param {(number|Color|string)} [color=0xffffff] - The light's color.
  33764. * @param {number} [intensity=1] - The light's strength/intensity measured in candela (cd).
  33765. * @param {number} [distance=0] - Maximum range of the light. `0` means no limit.
  33766. * @param {number} [decay=2] - The amount the light dims along the distance of the light.
  33767. */
  33768. constructor( color, intensity, distance = 0, decay = 2 ) {
  33769. super( color, intensity );
  33770. /**
  33771. * This flag can be used for type testing.
  33772. *
  33773. * @type {boolean}
  33774. * @readonly
  33775. * @default true
  33776. */
  33777. this.isPointLight = true;
  33778. this.type = 'PointLight';
  33779. /**
  33780. * When distance is zero, light will attenuate according to inverse-square
  33781. * law to infinite distance. When distance is non-zero, light will attenuate
  33782. * according to inverse-square law until near the distance cutoff, where it
  33783. * will then attenuate quickly and smoothly to 0. Inherently, cutoffs are not
  33784. * physically correct.
  33785. *
  33786. * @type {number}
  33787. * @default 0
  33788. */
  33789. this.distance = distance;
  33790. /**
  33791. * The amount the light dims along the distance of the light. In context of
  33792. * physically-correct rendering the default value should not be changed.
  33793. *
  33794. * @type {number}
  33795. * @default 2
  33796. */
  33797. this.decay = decay;
  33798. /**
  33799. * This property holds the light's shadow configuration.
  33800. *
  33801. * @type {PointLightShadow}
  33802. */
  33803. this.shadow = new PointLightShadow();
  33804. }
  33805. /**
  33806. * The light's power. Power is the luminous power of the light measured in lumens (lm).
  33807. * Changing the power will also change the light's intensity.
  33808. *
  33809. * @type {number}
  33810. */
  33811. get power() {
  33812. // compute the light's luminous power (in lumens) from its intensity (in candela)
  33813. // for an isotropic light source, luminous power (lm) = 4 π luminous intensity (cd)
  33814. return this.intensity * 4 * Math.PI;
  33815. }
  33816. set power( power ) {
  33817. // set the light's intensity (in candela) from the desired luminous power (in lumens)
  33818. this.intensity = power / ( 4 * Math.PI );
  33819. }
  33820. dispose() {
  33821. super.dispose();
  33822. this.shadow.dispose();
  33823. }
  33824. copy( source, recursive ) {
  33825. super.copy( source, recursive );
  33826. this.distance = source.distance;
  33827. this.decay = source.decay;
  33828. this.shadow = source.shadow.clone();
  33829. return this;
  33830. }
  33831. toJSON( meta ) {
  33832. const data = super.toJSON( meta );
  33833. data.object.distance = this.distance;
  33834. data.object.decay = this.decay;
  33835. data.object.shadow = this.shadow.toJSON();
  33836. return data;
  33837. }
  33838. }
  33839. /**
  33840. * Camera that uses [orthographic projection](https://en.wikipedia.org/wiki/Orthographic_projection).
  33841. *
  33842. * In this projection mode, an object's size in the rendered image stays
  33843. * constant regardless of its distance from the camera. This can be useful
  33844. * for rendering 2D scenes and UI elements, amongst other things.
  33845. *
  33846. * ```js
  33847. * const camera = new THREE.OrthographicCamera( width / - 2, width / 2, height / 2, height / - 2, 1, 1000 );
  33848. * scene.add( camera );
  33849. * ```
  33850. *
  33851. * @augments Camera
  33852. */
  33853. class OrthographicCamera extends Camera {
  33854. /**
  33855. * Constructs a new orthographic camera.
  33856. *
  33857. * @param {number} [left=-1] - The left plane of the camera's frustum.
  33858. * @param {number} [right=1] - The right plane of the camera's frustum.
  33859. * @param {number} [top=1] - The top plane of the camera's frustum.
  33860. * @param {number} [bottom=-1] - The bottom plane of the camera's frustum.
  33861. * @param {number} [near=0.1] - The camera's near plane.
  33862. * @param {number} [far=2000] - The camera's far plane.
  33863. */
  33864. constructor( left = -1, right = 1, top = 1, bottom = -1, near = 0.1, far = 2000 ) {
  33865. super();
  33866. /**
  33867. * This flag can be used for type testing.
  33868. *
  33869. * @type {boolean}
  33870. * @readonly
  33871. * @default true
  33872. */
  33873. this.isOrthographicCamera = true;
  33874. this.type = 'OrthographicCamera';
  33875. /**
  33876. * The zoom factor of the camera.
  33877. *
  33878. * @type {number}
  33879. * @default 1
  33880. */
  33881. this.zoom = 1;
  33882. /**
  33883. * Represents the frustum window specification. This property should not be edited
  33884. * directly but via {@link PerspectiveCamera#setViewOffset} and {@link PerspectiveCamera#clearViewOffset}.
  33885. *
  33886. * @type {?Object}
  33887. * @default null
  33888. */
  33889. this.view = null;
  33890. /**
  33891. * The left plane of the camera's frustum.
  33892. *
  33893. * @type {number}
  33894. * @default -1
  33895. */
  33896. this.left = left;
  33897. /**
  33898. * The right plane of the camera's frustum.
  33899. *
  33900. * @type {number}
  33901. * @default 1
  33902. */
  33903. this.right = right;
  33904. /**
  33905. * The top plane of the camera's frustum.
  33906. *
  33907. * @type {number}
  33908. * @default 1
  33909. */
  33910. this.top = top;
  33911. /**
  33912. * The bottom plane of the camera's frustum.
  33913. *
  33914. * @type {number}
  33915. * @default -1
  33916. */
  33917. this.bottom = bottom;
  33918. /**
  33919. * The camera's near plane. The valid range is greater than `0`
  33920. * and less than the current value of {@link OrthographicCamera#far}.
  33921. *
  33922. * Note that, unlike for the {@link PerspectiveCamera}, `0` is a
  33923. * valid value for an orthographic camera's near plane.
  33924. *
  33925. * @type {number}
  33926. * @default 0.1
  33927. */
  33928. this.near = near;
  33929. /**
  33930. * The camera's far plane. Must be greater than the
  33931. * current value of {@link OrthographicCamera#near}.
  33932. *
  33933. * @type {number}
  33934. * @default 2000
  33935. */
  33936. this.far = far;
  33937. this.updateProjectionMatrix();
  33938. }
  33939. copy( source, recursive ) {
  33940. super.copy( source, recursive );
  33941. this.left = source.left;
  33942. this.right = source.right;
  33943. this.top = source.top;
  33944. this.bottom = source.bottom;
  33945. this.near = source.near;
  33946. this.far = source.far;
  33947. this.zoom = source.zoom;
  33948. this.view = source.view === null ? null : Object.assign( {}, source.view );
  33949. return this;
  33950. }
  33951. /**
  33952. * Sets an offset in a larger frustum. This is useful for multi-window or
  33953. * multi-monitor/multi-machine setups.
  33954. *
  33955. * @param {number} fullWidth - The full width of multiview setup.
  33956. * @param {number} fullHeight - The full height of multiview setup.
  33957. * @param {number} x - The horizontal offset of the subcamera.
  33958. * @param {number} y - The vertical offset of the subcamera.
  33959. * @param {number} width - The width of subcamera.
  33960. * @param {number} height - The height of subcamera.
  33961. * @see {@link PerspectiveCamera#setViewOffset}
  33962. */
  33963. setViewOffset( fullWidth, fullHeight, x, y, width, height ) {
  33964. if ( this.view === null ) {
  33965. this.view = {
  33966. enabled: true,
  33967. fullWidth: 1,
  33968. fullHeight: 1,
  33969. offsetX: 0,
  33970. offsetY: 0,
  33971. width: 1,
  33972. height: 1
  33973. };
  33974. }
  33975. this.view.enabled = true;
  33976. this.view.fullWidth = fullWidth;
  33977. this.view.fullHeight = fullHeight;
  33978. this.view.offsetX = x;
  33979. this.view.offsetY = y;
  33980. this.view.width = width;
  33981. this.view.height = height;
  33982. this.updateProjectionMatrix();
  33983. }
  33984. /**
  33985. * Removes the view offset from the projection matrix.
  33986. */
  33987. clearViewOffset() {
  33988. if ( this.view !== null ) {
  33989. this.view.enabled = false;
  33990. }
  33991. this.updateProjectionMatrix();
  33992. }
  33993. /**
  33994. * Updates the camera's projection matrix. Must be called after any change of
  33995. * camera properties.
  33996. */
  33997. updateProjectionMatrix() {
  33998. const dx = ( this.right - this.left ) / ( 2 * this.zoom );
  33999. const dy = ( this.top - this.bottom ) / ( 2 * this.zoom );
  34000. const cx = ( this.right + this.left ) / 2;
  34001. const cy = ( this.top + this.bottom ) / 2;
  34002. let left = cx - dx;
  34003. let right = cx + dx;
  34004. let top = cy + dy;
  34005. let bottom = cy - dy;
  34006. if ( this.view !== null && this.view.enabled ) {
  34007. const scaleW = ( this.right - this.left ) / this.view.fullWidth / this.zoom;
  34008. const scaleH = ( this.top - this.bottom ) / this.view.fullHeight / this.zoom;
  34009. left += scaleW * this.view.offsetX;
  34010. right = left + scaleW * this.view.width;
  34011. top -= scaleH * this.view.offsetY;
  34012. bottom = top - scaleH * this.view.height;
  34013. }
  34014. this.projectionMatrix.makeOrthographic( left, right, top, bottom, this.near, this.far, this.coordinateSystem, this.reversedDepth );
  34015. this.projectionMatrixInverse.copy( this.projectionMatrix ).invert();
  34016. }
  34017. toJSON( meta ) {
  34018. const data = super.toJSON( meta );
  34019. data.object.zoom = this.zoom;
  34020. data.object.left = this.left;
  34021. data.object.right = this.right;
  34022. data.object.top = this.top;
  34023. data.object.bottom = this.bottom;
  34024. data.object.near = this.near;
  34025. data.object.far = this.far;
  34026. if ( this.view !== null ) data.object.view = Object.assign( {}, this.view );
  34027. return data;
  34028. }
  34029. }
  34030. /**
  34031. * Represents the shadow configuration of directional lights.
  34032. *
  34033. * @augments LightShadow
  34034. */
  34035. class DirectionalLightShadow extends LightShadow {
  34036. /**
  34037. * Constructs a new directional light shadow.
  34038. */
  34039. constructor() {
  34040. super( new OrthographicCamera( -5, 5, 5, -5, 0.5, 500 ) );
  34041. /**
  34042. * This flag can be used for type testing.
  34043. *
  34044. * @type {boolean}
  34045. * @readonly
  34046. * @default true
  34047. */
  34048. this.isDirectionalLightShadow = true;
  34049. }
  34050. }
  34051. /**
  34052. * A light that gets emitted in a specific direction. This light will behave
  34053. * as though it is infinitely far away and the rays produced from it are all
  34054. * parallel. The common use case for this is to simulate daylight; the sun is
  34055. * far enough away that its position can be considered to be infinite, and
  34056. * all light rays coming from it are parallel.
  34057. *
  34058. * A common point of confusion for directional lights is that setting the
  34059. * rotation has no effect. This is because three.js's DirectionalLight is the
  34060. * equivalent to what is often called a 'Target Direct Light' in other
  34061. * applications.
  34062. *
  34063. * This means that its direction is calculated as pointing from the light's
  34064. * {@link Object3D#position} to the {@link DirectionalLight#target} position
  34065. * (as opposed to a 'Free Direct Light' that just has a rotation
  34066. * component).
  34067. *
  34068. * This light can cast shadows - see the {@link DirectionalLightShadow} for details.
  34069. *
  34070. * ```js
  34071. * // White directional light at half intensity shining from the top.
  34072. * const directionalLight = new THREE.DirectionalLight( 0xffffff, 0.5 );
  34073. * scene.add( directionalLight );
  34074. * ```
  34075. *
  34076. * @augments Light
  34077. */
  34078. class DirectionalLight extends Light {
  34079. /**
  34080. * Constructs a new directional light.
  34081. *
  34082. * @param {(number|Color|string)} [color=0xffffff] - The light's color.
  34083. * @param {number} [intensity=1] - The light's strength/intensity.
  34084. */
  34085. constructor( color, intensity ) {
  34086. super( color, intensity );
  34087. /**
  34088. * This flag can be used for type testing.
  34089. *
  34090. * @type {boolean}
  34091. * @readonly
  34092. * @default true
  34093. */
  34094. this.isDirectionalLight = true;
  34095. this.type = 'DirectionalLight';
  34096. this.position.copy( Object3D.DEFAULT_UP );
  34097. this.updateMatrix();
  34098. /**
  34099. * The directional light points from its position to the
  34100. * target's position.
  34101. *
  34102. * For the target's position to be changed to anything other
  34103. * than the default, it must be added to the scene.
  34104. *
  34105. * It is also possible to set the target to be another 3D object
  34106. * in the scene. The light will now track the target object.
  34107. *
  34108. * @type {Object3D}
  34109. */
  34110. this.target = new Object3D();
  34111. /**
  34112. * This property holds the light's shadow configuration.
  34113. *
  34114. * @type {DirectionalLightShadow}
  34115. */
  34116. this.shadow = new DirectionalLightShadow();
  34117. }
  34118. dispose() {
  34119. super.dispose();
  34120. this.shadow.dispose();
  34121. }
  34122. copy( source ) {
  34123. super.copy( source );
  34124. this.target = source.target.clone();
  34125. this.shadow = source.shadow.clone();
  34126. return this;
  34127. }
  34128. toJSON( meta ) {
  34129. const data = super.toJSON( meta );
  34130. data.object.shadow = this.shadow.toJSON();
  34131. data.object.target = this.target.uuid;
  34132. return data;
  34133. }
  34134. }
  34135. /**
  34136. * This light globally illuminates all objects in the scene equally.
  34137. *
  34138. * It cannot be used to cast shadows as it does not have a direction.
  34139. *
  34140. * ```js
  34141. * const light = new THREE.AmbientLight( 0x404040 ); // soft white light
  34142. * scene.add( light );
  34143. * ```
  34144. *
  34145. * @augments Light
  34146. */
  34147. class AmbientLight extends Light {
  34148. /**
  34149. * Constructs a new ambient light.
  34150. *
  34151. * @param {(number|Color|string)} [color=0xffffff] - The light's color.
  34152. * @param {number} [intensity=1] - The light's strength/intensity.
  34153. */
  34154. constructor( color, intensity ) {
  34155. super( color, intensity );
  34156. /**
  34157. * This flag can be used for type testing.
  34158. *
  34159. * @type {boolean}
  34160. * @readonly
  34161. * @default true
  34162. */
  34163. this.isAmbientLight = true;
  34164. this.type = 'AmbientLight';
  34165. }
  34166. }
  34167. /**
  34168. * This class emits light uniformly across the face a rectangular plane.
  34169. * This light type can be used to simulate light sources such as bright
  34170. * windows or strip lighting.
  34171. *
  34172. * Important Notes:
  34173. *
  34174. * - There is no shadow support.
  34175. * - Only PBR materials are supported.
  34176. * - You have to include `RectAreaLightUniformsLib` (`WebGLRenderer`) or `RectAreaLightTexturesLib` (`WebGPURenderer`)
  34177. * into your app and init the uniforms/textures.
  34178. *
  34179. * ```js
  34180. * RectAreaLightUniformsLib.init(); // only relevant for WebGLRenderer
  34181. * THREE.RectAreaLightNode.setLTC( RectAreaLightTexturesLib.init() ); // only relevant for WebGPURenderer
  34182. *
  34183. * const intensity = 1; const width = 10; const height = 10;
  34184. * const rectLight = new THREE.RectAreaLight( 0xffffff, intensity, width, height );
  34185. * rectLight.position.set( 5, 5, 0 );
  34186. * rectLight.lookAt( 0, 0, 0 );
  34187. * scene.add( rectLight )
  34188. * ```
  34189. *
  34190. * @augments Light
  34191. */
  34192. class RectAreaLight extends Light {
  34193. /**
  34194. * Constructs a new area light.
  34195. *
  34196. * @param {(number|Color|string)} [color=0xffffff] - The light's color.
  34197. * @param {number} [intensity=1] - The light's strength/intensity.
  34198. * @param {number} [width=10] - The width of the light.
  34199. * @param {number} [height=10] - The height of the light.
  34200. */
  34201. constructor( color, intensity, width = 10, height = 10 ) {
  34202. super( color, intensity );
  34203. /**
  34204. * This flag can be used for type testing.
  34205. *
  34206. * @type {boolean}
  34207. * @readonly
  34208. * @default true
  34209. */
  34210. this.isRectAreaLight = true;
  34211. this.type = 'RectAreaLight';
  34212. /**
  34213. * The width of the light.
  34214. *
  34215. * @type {number}
  34216. * @default 10
  34217. */
  34218. this.width = width;
  34219. /**
  34220. * The height of the light.
  34221. *
  34222. * @type {number}
  34223. * @default 10
  34224. */
  34225. this.height = height;
  34226. }
  34227. /**
  34228. * The light's power. Power is the luminous power of the light measured in lumens (lm).
  34229. * Changing the power will also change the light's intensity.
  34230. *
  34231. * @type {number}
  34232. */
  34233. get power() {
  34234. // compute the light's luminous power (in lumens) from its intensity (in nits)
  34235. return this.intensity * this.width * this.height * Math.PI;
  34236. }
  34237. set power( power ) {
  34238. // set the light's intensity (in nits) from the desired luminous power (in lumens)
  34239. this.intensity = power / ( this.width * this.height * Math.PI );
  34240. }
  34241. copy( source ) {
  34242. super.copy( source );
  34243. this.width = source.width;
  34244. this.height = source.height;
  34245. return this;
  34246. }
  34247. toJSON( meta ) {
  34248. const data = super.toJSON( meta );
  34249. data.object.width = this.width;
  34250. data.object.height = this.height;
  34251. return data;
  34252. }
  34253. }
  34254. /**
  34255. * Represents a third-order spherical harmonics (SH). Light probes use this class
  34256. * to encode lighting information.
  34257. *
  34258. * - Primary reference: {@link https://graphics.stanford.edu/papers/envmap/envmap.pdf}
  34259. * - Secondary reference: {@link https://www.ppsloan.org/publications/StupidSH36.pdf}
  34260. */
  34261. class SphericalHarmonics3 {
  34262. /**
  34263. * Constructs a new spherical harmonics.
  34264. */
  34265. constructor() {
  34266. /**
  34267. * This flag can be used for type testing.
  34268. *
  34269. * @type {boolean}
  34270. * @readonly
  34271. * @default true
  34272. */
  34273. this.isSphericalHarmonics3 = true;
  34274. /**
  34275. * An array holding the (9) SH coefficients.
  34276. *
  34277. * @type {Array<Vector3>}
  34278. */
  34279. this.coefficients = [];
  34280. for ( let i = 0; i < 9; i ++ ) {
  34281. this.coefficients.push( new Vector3() );
  34282. }
  34283. }
  34284. /**
  34285. * Sets the given SH coefficients to this instance by copying
  34286. * the values.
  34287. *
  34288. * @param {Array<Vector3>} coefficients - The SH coefficients.
  34289. * @return {SphericalHarmonics3} A reference to this spherical harmonics.
  34290. */
  34291. set( coefficients ) {
  34292. for ( let i = 0; i < 9; i ++ ) {
  34293. this.coefficients[ i ].copy( coefficients[ i ] );
  34294. }
  34295. return this;
  34296. }
  34297. /**
  34298. * Sets all SH coefficients to `0`.
  34299. *
  34300. * @return {SphericalHarmonics3} A reference to this spherical harmonics.
  34301. */
  34302. zero() {
  34303. for ( let i = 0; i < 9; i ++ ) {
  34304. this.coefficients[ i ].set( 0, 0, 0 );
  34305. }
  34306. return this;
  34307. }
  34308. /**
  34309. * Returns the radiance in the direction of the given normal.
  34310. *
  34311. * @param {Vector3} normal - The normal vector (assumed to be unit length)
  34312. * @param {Vector3} target - The target vector that is used to store the method's result.
  34313. * @return {Vector3} The radiance.
  34314. */
  34315. getAt( normal, target ) {
  34316. // normal is assumed to be unit length
  34317. const x = normal.x, y = normal.y, z = normal.z;
  34318. const coeff = this.coefficients;
  34319. // band 0
  34320. target.copy( coeff[ 0 ] ).multiplyScalar( 0.282095 );
  34321. // band 1
  34322. target.addScaledVector( coeff[ 1 ], 0.488603 * y );
  34323. target.addScaledVector( coeff[ 2 ], 0.488603 * z );
  34324. target.addScaledVector( coeff[ 3 ], 0.488603 * x );
  34325. // band 2
  34326. target.addScaledVector( coeff[ 4 ], 1.092548 * ( x * y ) );
  34327. target.addScaledVector( coeff[ 5 ], 1.092548 * ( y * z ) );
  34328. target.addScaledVector( coeff[ 6 ], 0.315392 * ( 3.0 * z * z - 1.0 ) );
  34329. target.addScaledVector( coeff[ 7 ], 1.092548 * ( x * z ) );
  34330. target.addScaledVector( coeff[ 8 ], 0.546274 * ( x * x - y * y ) );
  34331. return target;
  34332. }
  34333. /**
  34334. * Returns the irradiance (radiance convolved with cosine lobe) in the
  34335. * direction of the given normal.
  34336. *
  34337. * @param {Vector3} normal - The normal vector (assumed to be unit length)
  34338. * @param {Vector3} target - The target vector that is used to store the method's result.
  34339. * @return {Vector3} The irradiance.
  34340. */
  34341. getIrradianceAt( normal, target ) {
  34342. // normal is assumed to be unit length
  34343. const x = normal.x, y = normal.y, z = normal.z;
  34344. const coeff = this.coefficients;
  34345. // band 0
  34346. target.copy( coeff[ 0 ] ).multiplyScalar( 0.886227 ); // π * 0.282095
  34347. // band 1
  34348. target.addScaledVector( coeff[ 1 ], 2.0 * 0.511664 * y ); // ( 2 * π / 3 ) * 0.488603
  34349. target.addScaledVector( coeff[ 2 ], 2.0 * 0.511664 * z );
  34350. target.addScaledVector( coeff[ 3 ], 2.0 * 0.511664 * x );
  34351. // band 2
  34352. target.addScaledVector( coeff[ 4 ], 2.0 * 0.429043 * x * y ); // ( π / 4 ) * 1.092548
  34353. target.addScaledVector( coeff[ 5 ], 2.0 * 0.429043 * y * z );
  34354. target.addScaledVector( coeff[ 6 ], 0.743125 * z * z - 0.247708 ); // ( π / 4 ) * 0.315392 * 3
  34355. target.addScaledVector( coeff[ 7 ], 2.0 * 0.429043 * x * z );
  34356. target.addScaledVector( coeff[ 8 ], 0.429043 * ( x * x - y * y ) ); // ( π / 4 ) * 0.546274
  34357. return target;
  34358. }
  34359. /**
  34360. * Adds the given SH to this instance.
  34361. *
  34362. * @param {SphericalHarmonics3} sh - The SH to add.
  34363. * @return {SphericalHarmonics3} A reference to this spherical harmonics.
  34364. */
  34365. add( sh ) {
  34366. for ( let i = 0; i < 9; i ++ ) {
  34367. this.coefficients[ i ].add( sh.coefficients[ i ] );
  34368. }
  34369. return this;
  34370. }
  34371. /**
  34372. * A convenience method for performing {@link SphericalHarmonics3#add} and
  34373. * {@link SphericalHarmonics3#scale} at once.
  34374. *
  34375. * @param {SphericalHarmonics3} sh - The SH to add.
  34376. * @param {number} s - The scale factor.
  34377. * @return {SphericalHarmonics3} A reference to this spherical harmonics.
  34378. */
  34379. addScaledSH( sh, s ) {
  34380. for ( let i = 0; i < 9; i ++ ) {
  34381. this.coefficients[ i ].addScaledVector( sh.coefficients[ i ], s );
  34382. }
  34383. return this;
  34384. }
  34385. /**
  34386. * Scales this SH by the given scale factor.
  34387. *
  34388. * @param {number} s - The scale factor.
  34389. * @return {SphericalHarmonics3} A reference to this spherical harmonics.
  34390. */
  34391. scale( s ) {
  34392. for ( let i = 0; i < 9; i ++ ) {
  34393. this.coefficients[ i ].multiplyScalar( s );
  34394. }
  34395. return this;
  34396. }
  34397. /**
  34398. * Linear interpolates between the given SH and this instance by the given
  34399. * alpha factor.
  34400. *
  34401. * @param {SphericalHarmonics3} sh - The SH to interpolate with.
  34402. * @param {number} alpha - The alpha factor.
  34403. * @return {SphericalHarmonics3} A reference to this spherical harmonics.
  34404. */
  34405. lerp( sh, alpha ) {
  34406. for ( let i = 0; i < 9; i ++ ) {
  34407. this.coefficients[ i ].lerp( sh.coefficients[ i ], alpha );
  34408. }
  34409. return this;
  34410. }
  34411. /**
  34412. * Returns `true` if this spherical harmonics is equal with the given one.
  34413. *
  34414. * @param {SphericalHarmonics3} sh - The spherical harmonics to test for equality.
  34415. * @return {boolean} Whether this spherical harmonics is equal with the given one.
  34416. */
  34417. equals( sh ) {
  34418. for ( let i = 0; i < 9; i ++ ) {
  34419. if ( ! this.coefficients[ i ].equals( sh.coefficients[ i ] ) ) {
  34420. return false;
  34421. }
  34422. }
  34423. return true;
  34424. }
  34425. /**
  34426. * Copies the values of the given spherical harmonics to this instance.
  34427. *
  34428. * @param {SphericalHarmonics3} sh - The spherical harmonics to copy.
  34429. * @return {SphericalHarmonics3} A reference to this spherical harmonics.
  34430. */
  34431. copy( sh ) {
  34432. return this.set( sh.coefficients );
  34433. }
  34434. /**
  34435. * Returns a new spherical harmonics with copied values from this instance.
  34436. *
  34437. * @return {SphericalHarmonics3} A clone of this instance.
  34438. */
  34439. clone() {
  34440. return new this.constructor().copy( this );
  34441. }
  34442. /**
  34443. * Sets the SH coefficients of this instance from the given array.
  34444. *
  34445. * @param {Array<number>} array - An array holding the SH coefficients.
  34446. * @param {number} [offset=0] - The array offset where to start copying.
  34447. * @return {SphericalHarmonics3} A clone of this instance.
  34448. */
  34449. fromArray( array, offset = 0 ) {
  34450. const coefficients = this.coefficients;
  34451. for ( let i = 0; i < 9; i ++ ) {
  34452. coefficients[ i ].fromArray( array, offset + ( i * 3 ) );
  34453. }
  34454. return this;
  34455. }
  34456. /**
  34457. * Returns an array with the SH coefficients, or copies them into the provided
  34458. * array. The coefficients are represented as numbers.
  34459. *
  34460. * @param {Array<number>} [array=[]] - The target array.
  34461. * @param {number} [offset=0] - The array offset where to start copying.
  34462. * @return {Array<number>} An array with flat SH coefficients.
  34463. */
  34464. toArray( array = [], offset = 0 ) {
  34465. const coefficients = this.coefficients;
  34466. for ( let i = 0; i < 9; i ++ ) {
  34467. coefficients[ i ].toArray( array, offset + ( i * 3 ) );
  34468. }
  34469. return array;
  34470. }
  34471. /**
  34472. * Computes the SH basis for the given normal vector.
  34473. *
  34474. * @param {Vector3} normal - The normal.
  34475. * @param {Array<number>} shBasis - The target array holding the SH basis.
  34476. */
  34477. static getBasisAt( normal, shBasis ) {
  34478. // normal is assumed to be unit length
  34479. const x = normal.x, y = normal.y, z = normal.z;
  34480. // band 0
  34481. shBasis[ 0 ] = 0.282095;
  34482. // band 1
  34483. shBasis[ 1 ] = 0.488603 * y;
  34484. shBasis[ 2 ] = 0.488603 * z;
  34485. shBasis[ 3 ] = 0.488603 * x;
  34486. // band 2
  34487. shBasis[ 4 ] = 1.092548 * x * y;
  34488. shBasis[ 5 ] = 1.092548 * y * z;
  34489. shBasis[ 6 ] = 0.315392 * ( 3 * z * z - 1 );
  34490. shBasis[ 7 ] = 1.092548 * x * z;
  34491. shBasis[ 8 ] = 0.546274 * ( x * x - y * y );
  34492. }
  34493. }
  34494. /**
  34495. * Light probes are an alternative way of adding light to a 3D scene. Unlike
  34496. * classical light sources (e.g. directional, point or spot lights), light
  34497. * probes do not emit light. Instead they store information about light
  34498. * passing through 3D space. During rendering, the light that hits a 3D
  34499. * object is approximated by using the data from the light probe.
  34500. *
  34501. * Light probes are usually created from (radiance) environment maps. The
  34502. * class {@link LightProbeGenerator} can be used to create light probes from
  34503. * cube textures or render targets. However, light estimation data could also
  34504. * be provided in other forms e.g. by WebXR. This enables the rendering of
  34505. * augmented reality content that reacts to real world lighting.
  34506. *
  34507. * The current probe implementation in three.js supports so-called diffuse
  34508. * light probes. This type of light probe is functionally equivalent to an
  34509. * irradiance environment map.
  34510. *
  34511. * @augments Light
  34512. */
  34513. class LightProbe extends Light {
  34514. /**
  34515. * Constructs a new light probe.
  34516. *
  34517. * @param {SphericalHarmonics3} sh - The spherical harmonics which represents encoded lighting information.
  34518. * @param {number} [intensity=1] - The light's strength/intensity.
  34519. */
  34520. constructor( sh = new SphericalHarmonics3(), intensity = 1 ) {
  34521. super( undefined, intensity );
  34522. /**
  34523. * This flag can be used for type testing.
  34524. *
  34525. * @type {boolean}
  34526. * @readonly
  34527. * @default true
  34528. */
  34529. this.isLightProbe = true;
  34530. /**
  34531. * A light probe uses spherical harmonics to encode lighting information.
  34532. *
  34533. * @type {SphericalHarmonics3}
  34534. */
  34535. this.sh = sh;
  34536. }
  34537. copy( source ) {
  34538. super.copy( source );
  34539. this.sh.copy( source.sh );
  34540. return this;
  34541. }
  34542. toJSON( meta ) {
  34543. const data = super.toJSON( meta );
  34544. data.object.sh = this.sh.toArray();
  34545. return data;
  34546. }
  34547. }
  34548. /**
  34549. * Class for loading materials. The files are internally
  34550. * loaded via {@link FileLoader}.
  34551. *
  34552. * ```js
  34553. * const loader = new THREE.MaterialLoader();
  34554. * const material = await loader.loadAsync( 'material.json' );
  34555. * ```
  34556. * This loader does not support node materials. Use {@link NodeMaterialLoader} instead.
  34557. *
  34558. * @augments Loader
  34559. */
  34560. class MaterialLoader extends Loader {
  34561. /**
  34562. * Constructs a new material loader.
  34563. *
  34564. * @param {LoadingManager} [manager] - The loading manager.
  34565. */
  34566. constructor( manager ) {
  34567. super( manager );
  34568. /**
  34569. * A dictionary holding textures used by the material.
  34570. *
  34571. * @type {Object<string,Texture>}
  34572. */
  34573. this.textures = {};
  34574. }
  34575. /**
  34576. * Starts loading from the given URL and pass the loaded material to the `onLoad()` callback.
  34577. *
  34578. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  34579. * @param {function(Material)} onLoad - Executed when the loading process has been finished.
  34580. * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
  34581. * @param {onErrorCallback} onError - Executed when errors occur.
  34582. */
  34583. load( url, onLoad, onProgress, onError ) {
  34584. const scope = this;
  34585. const loader = new FileLoader( scope.manager );
  34586. loader.setPath( scope.path );
  34587. loader.setRequestHeader( scope.requestHeader );
  34588. loader.setWithCredentials( scope.withCredentials );
  34589. loader.load( url, function ( text ) {
  34590. try {
  34591. onLoad( scope.parse( JSON.parse( text ) ) );
  34592. } catch ( e ) {
  34593. if ( onError ) {
  34594. onError( e );
  34595. } else {
  34596. error( e );
  34597. }
  34598. scope.manager.itemError( url );
  34599. }
  34600. }, onProgress, onError );
  34601. }
  34602. /**
  34603. * Parses the given JSON object and returns a material.
  34604. *
  34605. * @param {Object} json - The serialized material.
  34606. * @return {Material} The parsed material.
  34607. */
  34608. parse( json ) {
  34609. const textures = this.textures;
  34610. function getTexture( name ) {
  34611. if ( textures[ name ] === undefined ) {
  34612. warn( 'MaterialLoader: Undefined texture', name );
  34613. }
  34614. return textures[ name ];
  34615. }
  34616. const material = this.createMaterialFromType( json.type );
  34617. if ( json.uuid !== undefined ) material.uuid = json.uuid;
  34618. if ( json.name !== undefined ) material.name = json.name;
  34619. if ( json.color !== undefined && material.color !== undefined ) material.color.setHex( json.color );
  34620. if ( json.roughness !== undefined ) material.roughness = json.roughness;
  34621. if ( json.metalness !== undefined ) material.metalness = json.metalness;
  34622. if ( json.sheen !== undefined ) material.sheen = json.sheen;
  34623. if ( json.sheenColor !== undefined ) material.sheenColor = new Color().setHex( json.sheenColor );
  34624. if ( json.sheenRoughness !== undefined ) material.sheenRoughness = json.sheenRoughness;
  34625. if ( json.emissive !== undefined && material.emissive !== undefined ) material.emissive.setHex( json.emissive );
  34626. if ( json.specular !== undefined && material.specular !== undefined ) material.specular.setHex( json.specular );
  34627. if ( json.specularIntensity !== undefined ) material.specularIntensity = json.specularIntensity;
  34628. if ( json.specularColor !== undefined && material.specularColor !== undefined ) material.specularColor.setHex( json.specularColor );
  34629. if ( json.shininess !== undefined ) material.shininess = json.shininess;
  34630. if ( json.clearcoat !== undefined ) material.clearcoat = json.clearcoat;
  34631. if ( json.clearcoatRoughness !== undefined ) material.clearcoatRoughness = json.clearcoatRoughness;
  34632. if ( json.dispersion !== undefined ) material.dispersion = json.dispersion;
  34633. if ( json.iridescence !== undefined ) material.iridescence = json.iridescence;
  34634. if ( json.iridescenceIOR !== undefined ) material.iridescenceIOR = json.iridescenceIOR;
  34635. if ( json.iridescenceThicknessRange !== undefined ) material.iridescenceThicknessRange = json.iridescenceThicknessRange;
  34636. if ( json.transmission !== undefined ) material.transmission = json.transmission;
  34637. if ( json.thickness !== undefined ) material.thickness = json.thickness;
  34638. if ( json.attenuationDistance !== undefined ) material.attenuationDistance = json.attenuationDistance;
  34639. if ( json.attenuationColor !== undefined && material.attenuationColor !== undefined ) material.attenuationColor.setHex( json.attenuationColor );
  34640. if ( json.anisotropy !== undefined ) material.anisotropy = json.anisotropy;
  34641. if ( json.anisotropyRotation !== undefined ) material.anisotropyRotation = json.anisotropyRotation;
  34642. if ( json.fog !== undefined ) material.fog = json.fog;
  34643. if ( json.flatShading !== undefined ) material.flatShading = json.flatShading;
  34644. if ( json.blending !== undefined ) material.blending = json.blending;
  34645. if ( json.combine !== undefined ) material.combine = json.combine;
  34646. if ( json.side !== undefined ) material.side = json.side;
  34647. if ( json.shadowSide !== undefined ) material.shadowSide = json.shadowSide;
  34648. if ( json.opacity !== undefined ) material.opacity = json.opacity;
  34649. if ( json.transparent !== undefined ) material.transparent = json.transparent;
  34650. if ( json.alphaTest !== undefined ) material.alphaTest = json.alphaTest;
  34651. if ( json.alphaHash !== undefined ) material.alphaHash = json.alphaHash;
  34652. if ( json.depthFunc !== undefined ) material.depthFunc = json.depthFunc;
  34653. if ( json.depthTest !== undefined ) material.depthTest = json.depthTest;
  34654. if ( json.depthWrite !== undefined ) material.depthWrite = json.depthWrite;
  34655. if ( json.colorWrite !== undefined ) material.colorWrite = json.colorWrite;
  34656. if ( json.blendSrc !== undefined ) material.blendSrc = json.blendSrc;
  34657. if ( json.blendDst !== undefined ) material.blendDst = json.blendDst;
  34658. if ( json.blendEquation !== undefined ) material.blendEquation = json.blendEquation;
  34659. if ( json.blendSrcAlpha !== undefined ) material.blendSrcAlpha = json.blendSrcAlpha;
  34660. if ( json.blendDstAlpha !== undefined ) material.blendDstAlpha = json.blendDstAlpha;
  34661. if ( json.blendEquationAlpha !== undefined ) material.blendEquationAlpha = json.blendEquationAlpha;
  34662. if ( json.blendColor !== undefined && material.blendColor !== undefined ) material.blendColor.setHex( json.blendColor );
  34663. if ( json.blendAlpha !== undefined ) material.blendAlpha = json.blendAlpha;
  34664. if ( json.stencilWriteMask !== undefined ) material.stencilWriteMask = json.stencilWriteMask;
  34665. if ( json.stencilFunc !== undefined ) material.stencilFunc = json.stencilFunc;
  34666. if ( json.stencilRef !== undefined ) material.stencilRef = json.stencilRef;
  34667. if ( json.stencilFuncMask !== undefined ) material.stencilFuncMask = json.stencilFuncMask;
  34668. if ( json.stencilFail !== undefined ) material.stencilFail = json.stencilFail;
  34669. if ( json.stencilZFail !== undefined ) material.stencilZFail = json.stencilZFail;
  34670. if ( json.stencilZPass !== undefined ) material.stencilZPass = json.stencilZPass;
  34671. if ( json.stencilWrite !== undefined ) material.stencilWrite = json.stencilWrite;
  34672. if ( json.wireframe !== undefined ) material.wireframe = json.wireframe;
  34673. if ( json.wireframeLinewidth !== undefined ) material.wireframeLinewidth = json.wireframeLinewidth;
  34674. if ( json.wireframeLinecap !== undefined ) material.wireframeLinecap = json.wireframeLinecap;
  34675. if ( json.wireframeLinejoin !== undefined ) material.wireframeLinejoin = json.wireframeLinejoin;
  34676. if ( json.rotation !== undefined ) material.rotation = json.rotation;
  34677. if ( json.linewidth !== undefined ) material.linewidth = json.linewidth;
  34678. if ( json.dashSize !== undefined ) material.dashSize = json.dashSize;
  34679. if ( json.gapSize !== undefined ) material.gapSize = json.gapSize;
  34680. if ( json.scale !== undefined ) material.scale = json.scale;
  34681. if ( json.polygonOffset !== undefined ) material.polygonOffset = json.polygonOffset;
  34682. if ( json.polygonOffsetFactor !== undefined ) material.polygonOffsetFactor = json.polygonOffsetFactor;
  34683. if ( json.polygonOffsetUnits !== undefined ) material.polygonOffsetUnits = json.polygonOffsetUnits;
  34684. if ( json.dithering !== undefined ) material.dithering = json.dithering;
  34685. if ( json.alphaToCoverage !== undefined ) material.alphaToCoverage = json.alphaToCoverage;
  34686. if ( json.premultipliedAlpha !== undefined ) material.premultipliedAlpha = json.premultipliedAlpha;
  34687. if ( json.forceSinglePass !== undefined ) material.forceSinglePass = json.forceSinglePass;
  34688. if ( json.allowOverride !== undefined ) material.allowOverride = json.allowOverride;
  34689. if ( json.visible !== undefined ) material.visible = json.visible;
  34690. if ( json.toneMapped !== undefined ) material.toneMapped = json.toneMapped;
  34691. if ( json.userData !== undefined ) material.userData = json.userData;
  34692. if ( json.vertexColors !== undefined ) {
  34693. if ( typeof json.vertexColors === 'number' ) {
  34694. material.vertexColors = ( json.vertexColors > 0 ) ? true : false;
  34695. } else {
  34696. material.vertexColors = json.vertexColors;
  34697. }
  34698. }
  34699. // Shader Material
  34700. if ( json.uniforms !== undefined ) {
  34701. for ( const name in json.uniforms ) {
  34702. const uniform = json.uniforms[ name ];
  34703. material.uniforms[ name ] = {};
  34704. switch ( uniform.type ) {
  34705. case 't':
  34706. material.uniforms[ name ].value = getTexture( uniform.value );
  34707. break;
  34708. case 'c':
  34709. material.uniforms[ name ].value = new Color().setHex( uniform.value );
  34710. break;
  34711. case 'v2':
  34712. material.uniforms[ name ].value = new Vector2().fromArray( uniform.value );
  34713. break;
  34714. case 'v3':
  34715. material.uniforms[ name ].value = new Vector3().fromArray( uniform.value );
  34716. break;
  34717. case 'v4':
  34718. material.uniforms[ name ].value = new Vector4().fromArray( uniform.value );
  34719. break;
  34720. case 'm3':
  34721. material.uniforms[ name ].value = new Matrix3().fromArray( uniform.value );
  34722. break;
  34723. case 'm4':
  34724. material.uniforms[ name ].value = new Matrix4().fromArray( uniform.value );
  34725. break;
  34726. default:
  34727. material.uniforms[ name ].value = uniform.value;
  34728. }
  34729. }
  34730. }
  34731. if ( json.defines !== undefined ) material.defines = json.defines;
  34732. if ( json.vertexShader !== undefined ) material.vertexShader = json.vertexShader;
  34733. if ( json.fragmentShader !== undefined ) material.fragmentShader = json.fragmentShader;
  34734. if ( json.glslVersion !== undefined ) material.glslVersion = json.glslVersion;
  34735. if ( json.extensions !== undefined ) {
  34736. for ( const key in json.extensions ) {
  34737. material.extensions[ key ] = json.extensions[ key ];
  34738. }
  34739. }
  34740. if ( json.lights !== undefined ) material.lights = json.lights;
  34741. if ( json.clipping !== undefined ) material.clipping = json.clipping;
  34742. // for PointsMaterial
  34743. if ( json.size !== undefined ) material.size = json.size;
  34744. if ( json.sizeAttenuation !== undefined ) material.sizeAttenuation = json.sizeAttenuation;
  34745. // maps
  34746. if ( json.map !== undefined ) material.map = getTexture( json.map );
  34747. if ( json.matcap !== undefined ) material.matcap = getTexture( json.matcap );
  34748. if ( json.alphaMap !== undefined ) material.alphaMap = getTexture( json.alphaMap );
  34749. if ( json.bumpMap !== undefined ) material.bumpMap = getTexture( json.bumpMap );
  34750. if ( json.bumpScale !== undefined ) material.bumpScale = json.bumpScale;
  34751. if ( json.normalMap !== undefined ) material.normalMap = getTexture( json.normalMap );
  34752. if ( json.normalMapType !== undefined ) material.normalMapType = json.normalMapType;
  34753. if ( json.normalScale !== undefined ) {
  34754. let normalScale = json.normalScale;
  34755. if ( Array.isArray( normalScale ) === false ) {
  34756. // Blender exporter used to export a scalar. See #7459
  34757. normalScale = [ normalScale, normalScale ];
  34758. }
  34759. material.normalScale = new Vector2().fromArray( normalScale );
  34760. }
  34761. if ( json.displacementMap !== undefined ) material.displacementMap = getTexture( json.displacementMap );
  34762. if ( json.displacementScale !== undefined ) material.displacementScale = json.displacementScale;
  34763. if ( json.displacementBias !== undefined ) material.displacementBias = json.displacementBias;
  34764. if ( json.roughnessMap !== undefined ) material.roughnessMap = getTexture( json.roughnessMap );
  34765. if ( json.metalnessMap !== undefined ) material.metalnessMap = getTexture( json.metalnessMap );
  34766. if ( json.emissiveMap !== undefined ) material.emissiveMap = getTexture( json.emissiveMap );
  34767. if ( json.emissiveIntensity !== undefined ) material.emissiveIntensity = json.emissiveIntensity;
  34768. if ( json.specularMap !== undefined ) material.specularMap = getTexture( json.specularMap );
  34769. if ( json.specularIntensityMap !== undefined ) material.specularIntensityMap = getTexture( json.specularIntensityMap );
  34770. if ( json.specularColorMap !== undefined ) material.specularColorMap = getTexture( json.specularColorMap );
  34771. if ( json.envMap !== undefined ) material.envMap = getTexture( json.envMap );
  34772. if ( json.envMapRotation !== undefined ) material.envMapRotation.fromArray( json.envMapRotation );
  34773. if ( json.envMapIntensity !== undefined ) material.envMapIntensity = json.envMapIntensity;
  34774. if ( json.reflectivity !== undefined ) material.reflectivity = json.reflectivity;
  34775. if ( json.refractionRatio !== undefined ) material.refractionRatio = json.refractionRatio;
  34776. if ( json.lightMap !== undefined ) material.lightMap = getTexture( json.lightMap );
  34777. if ( json.lightMapIntensity !== undefined ) material.lightMapIntensity = json.lightMapIntensity;
  34778. if ( json.aoMap !== undefined ) material.aoMap = getTexture( json.aoMap );
  34779. if ( json.aoMapIntensity !== undefined ) material.aoMapIntensity = json.aoMapIntensity;
  34780. if ( json.gradientMap !== undefined ) material.gradientMap = getTexture( json.gradientMap );
  34781. if ( json.clearcoatMap !== undefined ) material.clearcoatMap = getTexture( json.clearcoatMap );
  34782. if ( json.clearcoatRoughnessMap !== undefined ) material.clearcoatRoughnessMap = getTexture( json.clearcoatRoughnessMap );
  34783. if ( json.clearcoatNormalMap !== undefined ) material.clearcoatNormalMap = getTexture( json.clearcoatNormalMap );
  34784. if ( json.clearcoatNormalScale !== undefined ) material.clearcoatNormalScale = new Vector2().fromArray( json.clearcoatNormalScale );
  34785. if ( json.iridescenceMap !== undefined ) material.iridescenceMap = getTexture( json.iridescenceMap );
  34786. if ( json.iridescenceThicknessMap !== undefined ) material.iridescenceThicknessMap = getTexture( json.iridescenceThicknessMap );
  34787. if ( json.transmissionMap !== undefined ) material.transmissionMap = getTexture( json.transmissionMap );
  34788. if ( json.thicknessMap !== undefined ) material.thicknessMap = getTexture( json.thicknessMap );
  34789. if ( json.anisotropyMap !== undefined ) material.anisotropyMap = getTexture( json.anisotropyMap );
  34790. if ( json.sheenColorMap !== undefined ) material.sheenColorMap = getTexture( json.sheenColorMap );
  34791. if ( json.sheenRoughnessMap !== undefined ) material.sheenRoughnessMap = getTexture( json.sheenRoughnessMap );
  34792. return material;
  34793. }
  34794. /**
  34795. * Textures are not embedded in the material JSON so they have
  34796. * to be injected before the loading process starts.
  34797. *
  34798. * @param {Object} value - A dictionary holding textures for material properties.
  34799. * @return {MaterialLoader} A reference to this material loader.
  34800. */
  34801. setTextures( value ) {
  34802. this.textures = value;
  34803. return this;
  34804. }
  34805. /**
  34806. * Creates a material for the given type.
  34807. *
  34808. * @param {string} type - The material type.
  34809. * @return {Material} The new material.
  34810. */
  34811. createMaterialFromType( type ) {
  34812. return MaterialLoader.createMaterialFromType( type );
  34813. }
  34814. /**
  34815. * Creates a material for the given type.
  34816. *
  34817. * @static
  34818. * @param {string} type - The material type.
  34819. * @return {Material} The new material.
  34820. */
  34821. static createMaterialFromType( type ) {
  34822. const materialLib = {
  34823. ShadowMaterial,
  34824. SpriteMaterial,
  34825. RawShaderMaterial,
  34826. ShaderMaterial,
  34827. PointsMaterial,
  34828. MeshPhysicalMaterial,
  34829. MeshStandardMaterial,
  34830. MeshPhongMaterial,
  34831. MeshToonMaterial,
  34832. MeshNormalMaterial,
  34833. MeshLambertMaterial,
  34834. MeshDepthMaterial,
  34835. MeshDistanceMaterial,
  34836. MeshBasicMaterial,
  34837. MeshMatcapMaterial,
  34838. LineDashedMaterial,
  34839. LineBasicMaterial,
  34840. Material
  34841. };
  34842. return new materialLib[ type ]();
  34843. }
  34844. }
  34845. /**
  34846. * A class with loader utility functions.
  34847. */
  34848. class LoaderUtils {
  34849. /**
  34850. * Extracts the base URL from the given URL.
  34851. *
  34852. * @param {string} url -The URL to extract the base URL from.
  34853. * @return {string} The extracted base URL.
  34854. */
  34855. static extractUrlBase( url ) {
  34856. const index = url.lastIndexOf( '/' );
  34857. if ( index === -1 ) return './';
  34858. return url.slice( 0, index + 1 );
  34859. }
  34860. /**
  34861. * Resolves relative URLs against the given path. Absolute paths, data urls,
  34862. * and blob URLs will be returned as is. Invalid URLs will return an empty
  34863. * string.
  34864. *
  34865. * @param {string} url -The URL to resolve.
  34866. * @param {string} path - The base path for relative URLs to be resolved against.
  34867. * @return {string} The resolved URL.
  34868. */
  34869. static resolveURL( url, path ) {
  34870. // Invalid URL
  34871. if ( typeof url !== 'string' || url === '' ) return '';
  34872. // Host Relative URL
  34873. if ( /^https?:\/\//i.test( path ) && /^\//.test( url ) ) {
  34874. path = path.replace( /(^https?:\/\/[^\/]+).*/i, '$1' );
  34875. }
  34876. // Absolute URL http://,https://,//
  34877. if ( /^(https?:)?\/\//i.test( url ) ) return url;
  34878. // Data URI
  34879. if ( /^data:.*,.*$/i.test( url ) ) return url;
  34880. // Blob URL
  34881. if ( /^blob:.*$/i.test( url ) ) return url;
  34882. // Relative URL
  34883. return path + url;
  34884. }
  34885. }
  34886. /**
  34887. * An instanced version of a geometry.
  34888. */
  34889. class InstancedBufferGeometry extends BufferGeometry {
  34890. /**
  34891. * Constructs a new instanced buffer geometry.
  34892. */
  34893. constructor() {
  34894. super();
  34895. /**
  34896. * This flag can be used for type testing.
  34897. *
  34898. * @type {boolean}
  34899. * @readonly
  34900. * @default true
  34901. */
  34902. this.isInstancedBufferGeometry = true;
  34903. this.type = 'InstancedBufferGeometry';
  34904. /**
  34905. * The instance count.
  34906. *
  34907. * @type {number}
  34908. * @default Infinity
  34909. */
  34910. this.instanceCount = Infinity;
  34911. }
  34912. copy( source ) {
  34913. super.copy( source );
  34914. this.instanceCount = source.instanceCount;
  34915. return this;
  34916. }
  34917. toJSON() {
  34918. const data = super.toJSON();
  34919. data.instanceCount = this.instanceCount;
  34920. data.isInstancedBufferGeometry = true;
  34921. return data;
  34922. }
  34923. }
  34924. /**
  34925. * Class for loading geometries. The files are internally
  34926. * loaded via {@link FileLoader}.
  34927. *
  34928. * ```js
  34929. * const loader = new THREE.BufferGeometryLoader();
  34930. * const geometry = await loader.loadAsync( 'models/json/pressure.json' );
  34931. *
  34932. * const material = new THREE.MeshBasicMaterial( { color: 0xF5F5F5 } );
  34933. * const object = new THREE.Mesh( geometry, material );
  34934. * scene.add( object );
  34935. * ```
  34936. *
  34937. * @augments Loader
  34938. */
  34939. class BufferGeometryLoader extends Loader {
  34940. /**
  34941. * Constructs a new geometry loader.
  34942. *
  34943. * @param {LoadingManager} [manager] - The loading manager.
  34944. */
  34945. constructor( manager ) {
  34946. super( manager );
  34947. }
  34948. /**
  34949. * Starts loading from the given URL and pass the loaded geometry to the `onLoad()` callback.
  34950. *
  34951. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  34952. * @param {function(BufferGeometry)} onLoad - Executed when the loading process has been finished.
  34953. * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
  34954. * @param {onErrorCallback} onError - Executed when errors occur.
  34955. */
  34956. load( url, onLoad, onProgress, onError ) {
  34957. const scope = this;
  34958. const loader = new FileLoader( scope.manager );
  34959. loader.setPath( scope.path );
  34960. loader.setRequestHeader( scope.requestHeader );
  34961. loader.setWithCredentials( scope.withCredentials );
  34962. loader.load( url, function ( text ) {
  34963. try {
  34964. onLoad( scope.parse( JSON.parse( text ) ) );
  34965. } catch ( e ) {
  34966. if ( onError ) {
  34967. onError( e );
  34968. } else {
  34969. error( e );
  34970. }
  34971. scope.manager.itemError( url );
  34972. }
  34973. }, onProgress, onError );
  34974. }
  34975. /**
  34976. * Parses the given JSON object and returns a geometry.
  34977. *
  34978. * @param {Object} json - The serialized geometry.
  34979. * @return {BufferGeometry} The parsed geometry.
  34980. */
  34981. parse( json ) {
  34982. const interleavedBufferMap = {};
  34983. const arrayBufferMap = {};
  34984. function getInterleavedBuffer( json, uuid ) {
  34985. if ( interleavedBufferMap[ uuid ] !== undefined ) return interleavedBufferMap[ uuid ];
  34986. const interleavedBuffers = json.interleavedBuffers;
  34987. const interleavedBuffer = interleavedBuffers[ uuid ];
  34988. const buffer = getArrayBuffer( json, interleavedBuffer.buffer );
  34989. const array = getTypedArray( interleavedBuffer.type, buffer );
  34990. const ib = new InterleavedBuffer( array, interleavedBuffer.stride );
  34991. ib.uuid = interleavedBuffer.uuid;
  34992. interleavedBufferMap[ uuid ] = ib;
  34993. return ib;
  34994. }
  34995. function getArrayBuffer( json, uuid ) {
  34996. if ( arrayBufferMap[ uuid ] !== undefined ) return arrayBufferMap[ uuid ];
  34997. const arrayBuffers = json.arrayBuffers;
  34998. const arrayBuffer = arrayBuffers[ uuid ];
  34999. const ab = new Uint32Array( arrayBuffer ).buffer;
  35000. arrayBufferMap[ uuid ] = ab;
  35001. return ab;
  35002. }
  35003. const geometry = json.isInstancedBufferGeometry ? new InstancedBufferGeometry() : new BufferGeometry();
  35004. const index = json.data.index;
  35005. if ( index !== undefined ) {
  35006. const typedArray = getTypedArray( index.type, index.array );
  35007. geometry.setIndex( new BufferAttribute( typedArray, 1 ) );
  35008. }
  35009. const attributes = json.data.attributes;
  35010. for ( const key in attributes ) {
  35011. const attribute = attributes[ key ];
  35012. let bufferAttribute;
  35013. if ( attribute.isInterleavedBufferAttribute ) {
  35014. const interleavedBuffer = getInterleavedBuffer( json.data, attribute.data );
  35015. bufferAttribute = new InterleavedBufferAttribute( interleavedBuffer, attribute.itemSize, attribute.offset, attribute.normalized );
  35016. } else {
  35017. const typedArray = getTypedArray( attribute.type, attribute.array );
  35018. const bufferAttributeConstr = attribute.isInstancedBufferAttribute ? InstancedBufferAttribute : BufferAttribute;
  35019. bufferAttribute = new bufferAttributeConstr( typedArray, attribute.itemSize, attribute.normalized );
  35020. }
  35021. if ( attribute.name !== undefined ) bufferAttribute.name = attribute.name;
  35022. if ( attribute.usage !== undefined ) bufferAttribute.setUsage( attribute.usage );
  35023. geometry.setAttribute( key, bufferAttribute );
  35024. }
  35025. const morphAttributes = json.data.morphAttributes;
  35026. if ( morphAttributes ) {
  35027. for ( const key in morphAttributes ) {
  35028. const attributeArray = morphAttributes[ key ];
  35029. const array = [];
  35030. for ( let i = 0, il = attributeArray.length; i < il; i ++ ) {
  35031. const attribute = attributeArray[ i ];
  35032. let bufferAttribute;
  35033. if ( attribute.isInterleavedBufferAttribute ) {
  35034. const interleavedBuffer = getInterleavedBuffer( json.data, attribute.data );
  35035. bufferAttribute = new InterleavedBufferAttribute( interleavedBuffer, attribute.itemSize, attribute.offset, attribute.normalized );
  35036. } else {
  35037. const typedArray = getTypedArray( attribute.type, attribute.array );
  35038. bufferAttribute = new BufferAttribute( typedArray, attribute.itemSize, attribute.normalized );
  35039. }
  35040. if ( attribute.name !== undefined ) bufferAttribute.name = attribute.name;
  35041. array.push( bufferAttribute );
  35042. }
  35043. geometry.morphAttributes[ key ] = array;
  35044. }
  35045. }
  35046. const morphTargetsRelative = json.data.morphTargetsRelative;
  35047. if ( morphTargetsRelative ) {
  35048. geometry.morphTargetsRelative = true;
  35049. }
  35050. const groups = json.data.groups || json.data.drawcalls || json.data.offsets;
  35051. if ( groups !== undefined ) {
  35052. for ( let i = 0, n = groups.length; i !== n; ++ i ) {
  35053. const group = groups[ i ];
  35054. geometry.addGroup( group.start, group.count, group.materialIndex );
  35055. }
  35056. }
  35057. const boundingSphere = json.data.boundingSphere;
  35058. if ( boundingSphere !== undefined ) {
  35059. geometry.boundingSphere = new Sphere().fromJSON( boundingSphere );
  35060. }
  35061. if ( json.name ) geometry.name = json.name;
  35062. if ( json.userData ) geometry.userData = json.userData;
  35063. return geometry;
  35064. }
  35065. }
  35066. /**
  35067. * A loader for loading a JSON resource in the [JSON Object/Scene format](https://github.com/mrdoob/three.js/wiki/JSON-Object-Scene-format-4).
  35068. * The files are internally loaded via {@link FileLoader}.
  35069. *
  35070. * ```js
  35071. * const loader = new THREE.ObjectLoader();
  35072. * const obj = await loader.loadAsync( 'models/json/example.json' );
  35073. * scene.add( obj );
  35074. *
  35075. * // Alternatively, to parse a previously loaded JSON structure
  35076. * const object = await loader.parseAsync( a_json_object );
  35077. * scene.add( object );
  35078. * ```
  35079. *
  35080. * @augments Loader
  35081. */
  35082. class ObjectLoader extends Loader {
  35083. /**
  35084. * Constructs a new object loader.
  35085. *
  35086. * @param {LoadingManager} [manager] - The loading manager.
  35087. */
  35088. constructor( manager ) {
  35089. super( manager );
  35090. }
  35091. /**
  35092. * Starts loading from the given URL and pass the loaded 3D object to the `onLoad()` callback.
  35093. *
  35094. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  35095. * @param {function(Object3D)} onLoad - Executed when the loading process has been finished.
  35096. * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
  35097. * @param {onErrorCallback} onError - Executed when errors occur.
  35098. */
  35099. load( url, onLoad, onProgress, onError ) {
  35100. const scope = this;
  35101. const path = ( this.path === '' ) ? LoaderUtils.extractUrlBase( url ) : this.path;
  35102. this.resourcePath = this.resourcePath || path;
  35103. const loader = new FileLoader( this.manager );
  35104. loader.setPath( this.path );
  35105. loader.setRequestHeader( this.requestHeader );
  35106. loader.setWithCredentials( this.withCredentials );
  35107. loader.load( url, function ( text ) {
  35108. let json = null;
  35109. try {
  35110. json = JSON.parse( text );
  35111. } catch ( error ) {
  35112. if ( onError !== undefined ) onError( error );
  35113. error( 'ObjectLoader: Can\'t parse ' + url + '.', error.message );
  35114. return;
  35115. }
  35116. const metadata = json.metadata;
  35117. if ( metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry' ) {
  35118. if ( onError !== undefined ) onError( new Error( 'THREE.ObjectLoader: Can\'t load ' + url ) );
  35119. error( 'ObjectLoader: Can\'t load ' + url );
  35120. return;
  35121. }
  35122. scope.parse( json, onLoad );
  35123. }, onProgress, onError );
  35124. }
  35125. /**
  35126. * Async version of {@link ObjectLoader#load}.
  35127. *
  35128. * @async
  35129. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  35130. * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
  35131. * @return {Promise<Object3D>} A Promise that resolves with the loaded 3D object.
  35132. */
  35133. async loadAsync( url, onProgress ) {
  35134. const scope = this;
  35135. const path = ( this.path === '' ) ? LoaderUtils.extractUrlBase( url ) : this.path;
  35136. this.resourcePath = this.resourcePath || path;
  35137. const loader = new FileLoader( this.manager );
  35138. loader.setPath( this.path );
  35139. loader.setRequestHeader( this.requestHeader );
  35140. loader.setWithCredentials( this.withCredentials );
  35141. const text = await loader.loadAsync( url, onProgress );
  35142. const json = JSON.parse( text );
  35143. const metadata = json.metadata;
  35144. if ( metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry' ) {
  35145. throw new Error( 'THREE.ObjectLoader: Can\'t load ' + url );
  35146. }
  35147. return await scope.parseAsync( json );
  35148. }
  35149. /**
  35150. * Parses the given JSON. This is used internally by {@link ObjectLoader#load}
  35151. * but can also be used directly to parse a previously loaded JSON structure.
  35152. *
  35153. * @param {Object} json - The serialized 3D object.
  35154. * @param {onLoad} onLoad - Executed when all resources (e.g. textures) have been fully loaded.
  35155. * @return {Object3D} The parsed 3D object.
  35156. */
  35157. parse( json, onLoad ) {
  35158. const animations = this.parseAnimations( json.animations );
  35159. const shapes = this.parseShapes( json.shapes );
  35160. const geometries = this.parseGeometries( json.geometries, shapes );
  35161. const images = this.parseImages( json.images, function () {
  35162. if ( onLoad !== undefined ) onLoad( object );
  35163. } );
  35164. const textures = this.parseTextures( json.textures, images );
  35165. const materials = this.parseMaterials( json.materials, textures );
  35166. const object = this.parseObject( json.object, geometries, materials, textures, animations );
  35167. const skeletons = this.parseSkeletons( json.skeletons, object );
  35168. this.bindSkeletons( object, skeletons );
  35169. this.bindLightTargets( object );
  35170. //
  35171. if ( onLoad !== undefined ) {
  35172. let hasImages = false;
  35173. for ( const uuid in images ) {
  35174. if ( images[ uuid ].data instanceof HTMLImageElement ) {
  35175. hasImages = true;
  35176. break;
  35177. }
  35178. }
  35179. if ( hasImages === false ) onLoad( object );
  35180. }
  35181. return object;
  35182. }
  35183. /**
  35184. * Async version of {@link ObjectLoader#parse}.
  35185. *
  35186. * @param {Object} json - The serialized 3D object.
  35187. * @return {Promise<Object3D>} A Promise that resolves with the parsed 3D object.
  35188. */
  35189. async parseAsync( json ) {
  35190. const animations = this.parseAnimations( json.animations );
  35191. const shapes = this.parseShapes( json.shapes );
  35192. const geometries = this.parseGeometries( json.geometries, shapes );
  35193. const images = await this.parseImagesAsync( json.images );
  35194. const textures = this.parseTextures( json.textures, images );
  35195. const materials = this.parseMaterials( json.materials, textures );
  35196. const object = this.parseObject( json.object, geometries, materials, textures, animations );
  35197. const skeletons = this.parseSkeletons( json.skeletons, object );
  35198. this.bindSkeletons( object, skeletons );
  35199. this.bindLightTargets( object );
  35200. return object;
  35201. }
  35202. // internals
  35203. parseShapes( json ) {
  35204. const shapes = {};
  35205. if ( json !== undefined ) {
  35206. for ( let i = 0, l = json.length; i < l; i ++ ) {
  35207. const shape = new Shape().fromJSON( json[ i ] );
  35208. shapes[ shape.uuid ] = shape;
  35209. }
  35210. }
  35211. return shapes;
  35212. }
  35213. parseSkeletons( json, object ) {
  35214. const skeletons = {};
  35215. const bones = {};
  35216. // generate bone lookup table
  35217. object.traverse( function ( child ) {
  35218. if ( child.isBone ) bones[ child.uuid ] = child;
  35219. } );
  35220. // create skeletons
  35221. if ( json !== undefined ) {
  35222. for ( let i = 0, l = json.length; i < l; i ++ ) {
  35223. const skeleton = new Skeleton().fromJSON( json[ i ], bones );
  35224. skeletons[ skeleton.uuid ] = skeleton;
  35225. }
  35226. }
  35227. return skeletons;
  35228. }
  35229. parseGeometries( json, shapes ) {
  35230. const geometries = {};
  35231. if ( json !== undefined ) {
  35232. const bufferGeometryLoader = new BufferGeometryLoader();
  35233. for ( let i = 0, l = json.length; i < l; i ++ ) {
  35234. let geometry;
  35235. const data = json[ i ];
  35236. switch ( data.type ) {
  35237. case 'BufferGeometry':
  35238. case 'InstancedBufferGeometry':
  35239. geometry = bufferGeometryLoader.parse( data );
  35240. break;
  35241. default:
  35242. if ( data.type in Geometries ) {
  35243. geometry = Geometries[ data.type ].fromJSON( data, shapes );
  35244. } else {
  35245. warn( `ObjectLoader: Unsupported geometry type "${ data.type }"` );
  35246. }
  35247. }
  35248. geometry.uuid = data.uuid;
  35249. if ( data.name !== undefined ) geometry.name = data.name;
  35250. if ( data.userData !== undefined ) geometry.userData = data.userData;
  35251. geometries[ data.uuid ] = geometry;
  35252. }
  35253. }
  35254. return geometries;
  35255. }
  35256. parseMaterials( json, textures ) {
  35257. const cache = {}; // MultiMaterial
  35258. const materials = {};
  35259. if ( json !== undefined ) {
  35260. const loader = new MaterialLoader();
  35261. loader.setTextures( textures );
  35262. for ( let i = 0, l = json.length; i < l; i ++ ) {
  35263. const data = json[ i ];
  35264. if ( cache[ data.uuid ] === undefined ) {
  35265. cache[ data.uuid ] = loader.parse( data );
  35266. }
  35267. materials[ data.uuid ] = cache[ data.uuid ];
  35268. }
  35269. }
  35270. return materials;
  35271. }
  35272. parseAnimations( json ) {
  35273. const animations = {};
  35274. if ( json !== undefined ) {
  35275. for ( let i = 0; i < json.length; i ++ ) {
  35276. const data = json[ i ];
  35277. const clip = AnimationClip.parse( data );
  35278. animations[ clip.uuid ] = clip;
  35279. }
  35280. }
  35281. return animations;
  35282. }
  35283. parseImages( json, onLoad ) {
  35284. const scope = this;
  35285. const images = {};
  35286. let loader;
  35287. function loadImage( url ) {
  35288. scope.manager.itemStart( url );
  35289. return loader.load( url, function () {
  35290. scope.manager.itemEnd( url );
  35291. }, undefined, function () {
  35292. scope.manager.itemError( url );
  35293. scope.manager.itemEnd( url );
  35294. } );
  35295. }
  35296. function deserializeImage( image ) {
  35297. if ( typeof image === 'string' ) {
  35298. const url = image;
  35299. const path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test( url ) ? url : scope.resourcePath + url;
  35300. return loadImage( path );
  35301. } else {
  35302. if ( image.data ) {
  35303. return {
  35304. data: getTypedArray( image.type, image.data ),
  35305. width: image.width,
  35306. height: image.height
  35307. };
  35308. } else {
  35309. return null;
  35310. }
  35311. }
  35312. }
  35313. if ( json !== undefined && json.length > 0 ) {
  35314. const manager = new LoadingManager( onLoad );
  35315. loader = new ImageLoader( manager );
  35316. loader.setCrossOrigin( this.crossOrigin );
  35317. for ( let i = 0, il = json.length; i < il; i ++ ) {
  35318. const image = json[ i ];
  35319. const url = image.url;
  35320. if ( Array.isArray( url ) ) {
  35321. // load array of images e.g CubeTexture
  35322. const imageArray = [];
  35323. for ( let j = 0, jl = url.length; j < jl; j ++ ) {
  35324. const currentUrl = url[ j ];
  35325. const deserializedImage = deserializeImage( currentUrl );
  35326. if ( deserializedImage !== null ) {
  35327. if ( deserializedImage instanceof HTMLImageElement ) {
  35328. imageArray.push( deserializedImage );
  35329. } else {
  35330. // special case: handle array of data textures for cube textures
  35331. imageArray.push( new DataTexture( deserializedImage.data, deserializedImage.width, deserializedImage.height ) );
  35332. }
  35333. }
  35334. }
  35335. images[ image.uuid ] = new Source( imageArray );
  35336. } else {
  35337. // load single image
  35338. const deserializedImage = deserializeImage( image.url );
  35339. images[ image.uuid ] = new Source( deserializedImage );
  35340. }
  35341. }
  35342. }
  35343. return images;
  35344. }
  35345. async parseImagesAsync( json ) {
  35346. const scope = this;
  35347. const images = {};
  35348. let loader;
  35349. async function deserializeImage( image ) {
  35350. if ( typeof image === 'string' ) {
  35351. const url = image;
  35352. const path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test( url ) ? url : scope.resourcePath + url;
  35353. return await loader.loadAsync( path );
  35354. } else {
  35355. if ( image.data ) {
  35356. return {
  35357. data: getTypedArray( image.type, image.data ),
  35358. width: image.width,
  35359. height: image.height
  35360. };
  35361. } else {
  35362. return null;
  35363. }
  35364. }
  35365. }
  35366. if ( json !== undefined && json.length > 0 ) {
  35367. loader = new ImageLoader( this.manager );
  35368. loader.setCrossOrigin( this.crossOrigin );
  35369. for ( let i = 0, il = json.length; i < il; i ++ ) {
  35370. const image = json[ i ];
  35371. const url = image.url;
  35372. if ( Array.isArray( url ) ) {
  35373. // load array of images e.g CubeTexture
  35374. const imageArray = [];
  35375. for ( let j = 0, jl = url.length; j < jl; j ++ ) {
  35376. const currentUrl = url[ j ];
  35377. const deserializedImage = await deserializeImage( currentUrl );
  35378. if ( deserializedImage !== null ) {
  35379. if ( deserializedImage instanceof HTMLImageElement ) {
  35380. imageArray.push( deserializedImage );
  35381. } else {
  35382. // special case: handle array of data textures for cube textures
  35383. imageArray.push( new DataTexture( deserializedImage.data, deserializedImage.width, deserializedImage.height ) );
  35384. }
  35385. }
  35386. }
  35387. images[ image.uuid ] = new Source( imageArray );
  35388. } else {
  35389. // load single image
  35390. const deserializedImage = await deserializeImage( image.url );
  35391. images[ image.uuid ] = new Source( deserializedImage );
  35392. }
  35393. }
  35394. }
  35395. return images;
  35396. }
  35397. parseTextures( json, images ) {
  35398. function parseConstant( value, type ) {
  35399. if ( typeof value === 'number' ) return value;
  35400. warn( 'ObjectLoader.parseTexture: Constant should be in numeric form.', value );
  35401. return type[ value ];
  35402. }
  35403. const textures = {};
  35404. if ( json !== undefined ) {
  35405. for ( let i = 0, l = json.length; i < l; i ++ ) {
  35406. const data = json[ i ];
  35407. if ( data.image === undefined ) {
  35408. warn( 'ObjectLoader: No "image" specified for', data.uuid );
  35409. }
  35410. if ( images[ data.image ] === undefined ) {
  35411. warn( 'ObjectLoader: Undefined image', data.image );
  35412. }
  35413. const source = images[ data.image ];
  35414. const image = source.data;
  35415. let texture;
  35416. if ( Array.isArray( image ) ) {
  35417. texture = new CubeTexture();
  35418. if ( image.length === 6 ) texture.needsUpdate = true;
  35419. } else {
  35420. if ( image && image.data ) {
  35421. texture = new DataTexture();
  35422. } else {
  35423. texture = new Texture();
  35424. }
  35425. if ( image ) texture.needsUpdate = true; // textures can have undefined image data
  35426. }
  35427. texture.source = source;
  35428. texture.uuid = data.uuid;
  35429. if ( data.name !== undefined ) texture.name = data.name;
  35430. if ( data.mapping !== undefined ) texture.mapping = parseConstant( data.mapping, TEXTURE_MAPPING );
  35431. if ( data.channel !== undefined ) texture.channel = data.channel;
  35432. if ( data.offset !== undefined ) texture.offset.fromArray( data.offset );
  35433. if ( data.repeat !== undefined ) texture.repeat.fromArray( data.repeat );
  35434. if ( data.center !== undefined ) texture.center.fromArray( data.center );
  35435. if ( data.rotation !== undefined ) texture.rotation = data.rotation;
  35436. if ( data.wrap !== undefined ) {
  35437. texture.wrapS = parseConstant( data.wrap[ 0 ], TEXTURE_WRAPPING );
  35438. texture.wrapT = parseConstant( data.wrap[ 1 ], TEXTURE_WRAPPING );
  35439. }
  35440. if ( data.format !== undefined ) texture.format = data.format;
  35441. if ( data.internalFormat !== undefined ) texture.internalFormat = data.internalFormat;
  35442. if ( data.type !== undefined ) texture.type = data.type;
  35443. if ( data.colorSpace !== undefined ) texture.colorSpace = data.colorSpace;
  35444. if ( data.minFilter !== undefined ) texture.minFilter = parseConstant( data.minFilter, TEXTURE_FILTER );
  35445. if ( data.magFilter !== undefined ) texture.magFilter = parseConstant( data.magFilter, TEXTURE_FILTER );
  35446. if ( data.anisotropy !== undefined ) texture.anisotropy = data.anisotropy;
  35447. if ( data.flipY !== undefined ) texture.flipY = data.flipY;
  35448. if ( data.generateMipmaps !== undefined ) texture.generateMipmaps = data.generateMipmaps;
  35449. if ( data.premultiplyAlpha !== undefined ) texture.premultiplyAlpha = data.premultiplyAlpha;
  35450. if ( data.unpackAlignment !== undefined ) texture.unpackAlignment = data.unpackAlignment;
  35451. if ( data.compareFunction !== undefined ) texture.compareFunction = data.compareFunction;
  35452. if ( data.userData !== undefined ) texture.userData = data.userData;
  35453. textures[ data.uuid ] = texture;
  35454. }
  35455. }
  35456. return textures;
  35457. }
  35458. parseObject( data, geometries, materials, textures, animations ) {
  35459. let object;
  35460. function getGeometry( name ) {
  35461. if ( geometries[ name ] === undefined ) {
  35462. warn( 'ObjectLoader: Undefined geometry', name );
  35463. }
  35464. return geometries[ name ];
  35465. }
  35466. function getMaterial( name ) {
  35467. if ( name === undefined ) return undefined;
  35468. if ( Array.isArray( name ) ) {
  35469. const array = [];
  35470. for ( let i = 0, l = name.length; i < l; i ++ ) {
  35471. const uuid = name[ i ];
  35472. if ( materials[ uuid ] === undefined ) {
  35473. warn( 'ObjectLoader: Undefined material', uuid );
  35474. }
  35475. array.push( materials[ uuid ] );
  35476. }
  35477. return array;
  35478. }
  35479. if ( materials[ name ] === undefined ) {
  35480. warn( 'ObjectLoader: Undefined material', name );
  35481. }
  35482. return materials[ name ];
  35483. }
  35484. function getTexture( uuid ) {
  35485. if ( textures[ uuid ] === undefined ) {
  35486. warn( 'ObjectLoader: Undefined texture', uuid );
  35487. }
  35488. return textures[ uuid ];
  35489. }
  35490. let geometry, material;
  35491. switch ( data.type ) {
  35492. case 'Scene':
  35493. object = new Scene();
  35494. if ( data.background !== undefined ) {
  35495. if ( Number.isInteger( data.background ) ) {
  35496. object.background = new Color( data.background );
  35497. } else {
  35498. object.background = getTexture( data.background );
  35499. }
  35500. }
  35501. if ( data.environment !== undefined ) {
  35502. object.environment = getTexture( data.environment );
  35503. }
  35504. if ( data.fog !== undefined ) {
  35505. if ( data.fog.type === 'Fog' ) {
  35506. object.fog = new Fog( data.fog.color, data.fog.near, data.fog.far );
  35507. } else if ( data.fog.type === 'FogExp2' ) {
  35508. object.fog = new FogExp2( data.fog.color, data.fog.density );
  35509. }
  35510. if ( data.fog.name !== '' ) {
  35511. object.fog.name = data.fog.name;
  35512. }
  35513. }
  35514. if ( data.backgroundBlurriness !== undefined ) object.backgroundBlurriness = data.backgroundBlurriness;
  35515. if ( data.backgroundIntensity !== undefined ) object.backgroundIntensity = data.backgroundIntensity;
  35516. if ( data.backgroundRotation !== undefined ) object.backgroundRotation.fromArray( data.backgroundRotation );
  35517. if ( data.environmentIntensity !== undefined ) object.environmentIntensity = data.environmentIntensity;
  35518. if ( data.environmentRotation !== undefined ) object.environmentRotation.fromArray( data.environmentRotation );
  35519. break;
  35520. case 'PerspectiveCamera':
  35521. object = new PerspectiveCamera( data.fov, data.aspect, data.near, data.far );
  35522. if ( data.focus !== undefined ) object.focus = data.focus;
  35523. if ( data.zoom !== undefined ) object.zoom = data.zoom;
  35524. if ( data.filmGauge !== undefined ) object.filmGauge = data.filmGauge;
  35525. if ( data.filmOffset !== undefined ) object.filmOffset = data.filmOffset;
  35526. if ( data.view !== undefined ) object.view = Object.assign( {}, data.view );
  35527. break;
  35528. case 'OrthographicCamera':
  35529. object = new OrthographicCamera( data.left, data.right, data.top, data.bottom, data.near, data.far );
  35530. if ( data.zoom !== undefined ) object.zoom = data.zoom;
  35531. if ( data.view !== undefined ) object.view = Object.assign( {}, data.view );
  35532. break;
  35533. case 'AmbientLight':
  35534. object = new AmbientLight( data.color, data.intensity );
  35535. break;
  35536. case 'DirectionalLight':
  35537. object = new DirectionalLight( data.color, data.intensity );
  35538. object.target = data.target || '';
  35539. break;
  35540. case 'PointLight':
  35541. object = new PointLight( data.color, data.intensity, data.distance, data.decay );
  35542. break;
  35543. case 'RectAreaLight':
  35544. object = new RectAreaLight( data.color, data.intensity, data.width, data.height );
  35545. break;
  35546. case 'SpotLight':
  35547. object = new SpotLight( data.color, data.intensity, data.distance, data.angle, data.penumbra, data.decay );
  35548. object.target = data.target || '';
  35549. break;
  35550. case 'HemisphereLight':
  35551. object = new HemisphereLight( data.color, data.groundColor, data.intensity );
  35552. break;
  35553. case 'LightProbe':
  35554. const sh = new SphericalHarmonics3().fromArray( data.sh );
  35555. object = new LightProbe( sh, data.intensity );
  35556. break;
  35557. case 'SkinnedMesh':
  35558. geometry = getGeometry( data.geometry );
  35559. material = getMaterial( data.material );
  35560. object = new SkinnedMesh( geometry, material );
  35561. if ( data.bindMode !== undefined ) object.bindMode = data.bindMode;
  35562. if ( data.bindMatrix !== undefined ) object.bindMatrix.fromArray( data.bindMatrix );
  35563. if ( data.skeleton !== undefined ) object.skeleton = data.skeleton;
  35564. break;
  35565. case 'Mesh':
  35566. geometry = getGeometry( data.geometry );
  35567. material = getMaterial( data.material );
  35568. object = new Mesh( geometry, material );
  35569. break;
  35570. case 'InstancedMesh':
  35571. geometry = getGeometry( data.geometry );
  35572. material = getMaterial( data.material );
  35573. const count = data.count;
  35574. const instanceMatrix = data.instanceMatrix;
  35575. const instanceColor = data.instanceColor;
  35576. object = new InstancedMesh( geometry, material, count );
  35577. object.instanceMatrix = new InstancedBufferAttribute( new Float32Array( instanceMatrix.array ), 16 );
  35578. if ( instanceColor !== undefined ) object.instanceColor = new InstancedBufferAttribute( new Float32Array( instanceColor.array ), instanceColor.itemSize );
  35579. break;
  35580. case 'BatchedMesh':
  35581. geometry = getGeometry( data.geometry );
  35582. material = getMaterial( data.material );
  35583. object = new BatchedMesh( data.maxInstanceCount, data.maxVertexCount, data.maxIndexCount, material );
  35584. object.geometry = geometry;
  35585. object.perObjectFrustumCulled = data.perObjectFrustumCulled;
  35586. object.sortObjects = data.sortObjects;
  35587. object._drawRanges = data.drawRanges;
  35588. object._reservedRanges = data.reservedRanges;
  35589. object._geometryInfo = data.geometryInfo.map( info => {
  35590. let box = null;
  35591. let sphere = null;
  35592. if ( info.boundingBox !== undefined ) {
  35593. box = new Box3().fromJSON( info.boundingBox );
  35594. }
  35595. if ( info.boundingSphere !== undefined ) {
  35596. sphere = new Sphere().fromJSON( info.boundingSphere );
  35597. }
  35598. return {
  35599. ...info,
  35600. boundingBox: box,
  35601. boundingSphere: sphere
  35602. };
  35603. } );
  35604. object._instanceInfo = data.instanceInfo;
  35605. object._availableInstanceIds = data._availableInstanceIds;
  35606. object._availableGeometryIds = data._availableGeometryIds;
  35607. object._nextIndexStart = data.nextIndexStart;
  35608. object._nextVertexStart = data.nextVertexStart;
  35609. object._geometryCount = data.geometryCount;
  35610. object._maxInstanceCount = data.maxInstanceCount;
  35611. object._maxVertexCount = data.maxVertexCount;
  35612. object._maxIndexCount = data.maxIndexCount;
  35613. object._geometryInitialized = data.geometryInitialized;
  35614. object._matricesTexture = getTexture( data.matricesTexture.uuid );
  35615. object._indirectTexture = getTexture( data.indirectTexture.uuid );
  35616. if ( data.colorsTexture !== undefined ) {
  35617. object._colorsTexture = getTexture( data.colorsTexture.uuid );
  35618. }
  35619. if ( data.boundingSphere !== undefined ) {
  35620. object.boundingSphere = new Sphere().fromJSON( data.boundingSphere );
  35621. }
  35622. if ( data.boundingBox !== undefined ) {
  35623. object.boundingBox = new Box3().fromJSON( data.boundingBox );
  35624. }
  35625. break;
  35626. case 'LOD':
  35627. object = new LOD();
  35628. break;
  35629. case 'Line':
  35630. object = new Line( getGeometry( data.geometry ), getMaterial( data.material ) );
  35631. break;
  35632. case 'LineLoop':
  35633. object = new LineLoop( getGeometry( data.geometry ), getMaterial( data.material ) );
  35634. break;
  35635. case 'LineSegments':
  35636. object = new LineSegments( getGeometry( data.geometry ), getMaterial( data.material ) );
  35637. break;
  35638. case 'PointCloud':
  35639. case 'Points':
  35640. object = new Points( getGeometry( data.geometry ), getMaterial( data.material ) );
  35641. break;
  35642. case 'Sprite':
  35643. object = new Sprite( getMaterial( data.material ) );
  35644. break;
  35645. case 'Group':
  35646. object = new Group();
  35647. break;
  35648. case 'Bone':
  35649. object = new Bone();
  35650. break;
  35651. default:
  35652. object = new Object3D();
  35653. }
  35654. object.uuid = data.uuid;
  35655. if ( data.name !== undefined ) object.name = data.name;
  35656. if ( data.matrix !== undefined ) {
  35657. object.matrix.fromArray( data.matrix );
  35658. if ( data.matrixAutoUpdate !== undefined ) object.matrixAutoUpdate = data.matrixAutoUpdate;
  35659. if ( object.matrixAutoUpdate ) object.matrix.decompose( object.position, object.quaternion, object.scale );
  35660. } else {
  35661. if ( data.position !== undefined ) object.position.fromArray( data.position );
  35662. if ( data.rotation !== undefined ) object.rotation.fromArray( data.rotation );
  35663. if ( data.quaternion !== undefined ) object.quaternion.fromArray( data.quaternion );
  35664. if ( data.scale !== undefined ) object.scale.fromArray( data.scale );
  35665. }
  35666. if ( data.up !== undefined ) object.up.fromArray( data.up );
  35667. if ( data.castShadow !== undefined ) object.castShadow = data.castShadow;
  35668. if ( data.receiveShadow !== undefined ) object.receiveShadow = data.receiveShadow;
  35669. if ( data.shadow ) {
  35670. if ( data.shadow.intensity !== undefined ) object.shadow.intensity = data.shadow.intensity;
  35671. if ( data.shadow.bias !== undefined ) object.shadow.bias = data.shadow.bias;
  35672. if ( data.shadow.normalBias !== undefined ) object.shadow.normalBias = data.shadow.normalBias;
  35673. if ( data.shadow.radius !== undefined ) object.shadow.radius = data.shadow.radius;
  35674. if ( data.shadow.mapSize !== undefined ) object.shadow.mapSize.fromArray( data.shadow.mapSize );
  35675. if ( data.shadow.camera !== undefined ) object.shadow.camera = this.parseObject( data.shadow.camera );
  35676. }
  35677. if ( data.visible !== undefined ) object.visible = data.visible;
  35678. if ( data.frustumCulled !== undefined ) object.frustumCulled = data.frustumCulled;
  35679. if ( data.renderOrder !== undefined ) object.renderOrder = data.renderOrder;
  35680. if ( data.userData !== undefined ) object.userData = data.userData;
  35681. if ( data.layers !== undefined ) object.layers.mask = data.layers;
  35682. if ( data.children !== undefined ) {
  35683. const children = data.children;
  35684. for ( let i = 0; i < children.length; i ++ ) {
  35685. object.add( this.parseObject( children[ i ], geometries, materials, textures, animations ) );
  35686. }
  35687. }
  35688. if ( data.animations !== undefined ) {
  35689. const objectAnimations = data.animations;
  35690. for ( let i = 0; i < objectAnimations.length; i ++ ) {
  35691. const uuid = objectAnimations[ i ];
  35692. object.animations.push( animations[ uuid ] );
  35693. }
  35694. }
  35695. if ( data.type === 'LOD' ) {
  35696. if ( data.autoUpdate !== undefined ) object.autoUpdate = data.autoUpdate;
  35697. const levels = data.levels;
  35698. for ( let l = 0; l < levels.length; l ++ ) {
  35699. const level = levels[ l ];
  35700. const child = object.getObjectByProperty( 'uuid', level.object );
  35701. if ( child !== undefined ) {
  35702. object.addLevel( child, level.distance, level.hysteresis );
  35703. }
  35704. }
  35705. }
  35706. return object;
  35707. }
  35708. bindSkeletons( object, skeletons ) {
  35709. if ( Object.keys( skeletons ).length === 0 ) return;
  35710. object.traverse( function ( child ) {
  35711. if ( child.isSkinnedMesh === true && child.skeleton !== undefined ) {
  35712. const skeleton = skeletons[ child.skeleton ];
  35713. if ( skeleton === undefined ) {
  35714. warn( 'ObjectLoader: No skeleton found with UUID:', child.skeleton );
  35715. } else {
  35716. child.bind( skeleton, child.bindMatrix );
  35717. }
  35718. }
  35719. } );
  35720. }
  35721. bindLightTargets( object ) {
  35722. object.traverse( function ( child ) {
  35723. if ( child.isDirectionalLight || child.isSpotLight ) {
  35724. const uuid = child.target;
  35725. const target = object.getObjectByProperty( 'uuid', uuid );
  35726. if ( target !== undefined ) {
  35727. child.target = target;
  35728. } else {
  35729. child.target = new Object3D();
  35730. }
  35731. }
  35732. } );
  35733. }
  35734. }
  35735. const TEXTURE_MAPPING = {
  35736. UVMapping: UVMapping,
  35737. CubeReflectionMapping: CubeReflectionMapping,
  35738. CubeRefractionMapping: CubeRefractionMapping,
  35739. EquirectangularReflectionMapping: EquirectangularReflectionMapping,
  35740. EquirectangularRefractionMapping: EquirectangularRefractionMapping,
  35741. CubeUVReflectionMapping: CubeUVReflectionMapping
  35742. };
  35743. const TEXTURE_WRAPPING = {
  35744. RepeatWrapping: RepeatWrapping,
  35745. ClampToEdgeWrapping: ClampToEdgeWrapping,
  35746. MirroredRepeatWrapping: MirroredRepeatWrapping
  35747. };
  35748. const TEXTURE_FILTER = {
  35749. NearestFilter: NearestFilter,
  35750. NearestMipmapNearestFilter: NearestMipmapNearestFilter,
  35751. NearestMipmapLinearFilter: NearestMipmapLinearFilter,
  35752. LinearFilter: LinearFilter,
  35753. LinearMipmapNearestFilter: LinearMipmapNearestFilter,
  35754. LinearMipmapLinearFilter: LinearMipmapLinearFilter
  35755. };
  35756. const _errorMap = new WeakMap();
  35757. /**
  35758. * A loader for loading images as an [ImageBitmap](https://developer.mozilla.org/en-US/docs/Web/API/ImageBitmap).
  35759. * An `ImageBitmap` provides an asynchronous and resource efficient pathway to prepare
  35760. * textures for rendering.
  35761. *
  35762. * Note that {@link Texture#flipY} and {@link Texture#premultiplyAlpha} are ignored with image bitmaps.
  35763. * These options need to be configured via {@link ImageBitmapLoader#setOptions} prior to loading,
  35764. * unlike regular images which can be configured on the Texture to set these options on GPU upload instead.
  35765. *
  35766. * To match the default behaviour of {@link Texture}, the following options are needed:
  35767. *
  35768. * ```js
  35769. * { imageOrientation: 'flipY', premultiplyAlpha: 'none' }
  35770. * ```
  35771. *
  35772. * Also note that unlike {@link FileLoader}, this loader will only avoid multiple concurrent requests to the same URL if {@link Cache} is enabled.
  35773. *
  35774. * ```js
  35775. * const loader = new THREE.ImageBitmapLoader();
  35776. * loader.setOptions( { imageOrientation: 'flipY' } ); // set options if needed
  35777. * const imageBitmap = await loader.loadAsync( 'image.png' );
  35778. *
  35779. * const texture = new THREE.Texture( imageBitmap );
  35780. * texture.needsUpdate = true;
  35781. * ```
  35782. *
  35783. * @augments Loader
  35784. */
  35785. class ImageBitmapLoader extends Loader {
  35786. /**
  35787. * Constructs a new image bitmap loader.
  35788. *
  35789. * @param {LoadingManager} [manager] - The loading manager.
  35790. */
  35791. constructor( manager ) {
  35792. super( manager );
  35793. /**
  35794. * This flag can be used for type testing.
  35795. *
  35796. * @type {boolean}
  35797. * @readonly
  35798. * @default true
  35799. */
  35800. this.isImageBitmapLoader = true;
  35801. if ( typeof createImageBitmap === 'undefined' ) {
  35802. warn( 'ImageBitmapLoader: createImageBitmap() not supported.' );
  35803. }
  35804. if ( typeof fetch === 'undefined' ) {
  35805. warn( 'ImageBitmapLoader: fetch() not supported.' );
  35806. }
  35807. /**
  35808. * Represents the loader options.
  35809. *
  35810. * @type {Object}
  35811. * @default {premultiplyAlpha:'none'}
  35812. */
  35813. this.options = { premultiplyAlpha: 'none' };
  35814. /**
  35815. * Used for aborting requests.
  35816. *
  35817. * @private
  35818. * @type {AbortController}
  35819. */
  35820. this._abortController = new AbortController();
  35821. }
  35822. /**
  35823. * Sets the given loader options. The structure of the object must match the `options` parameter of
  35824. * [createImageBitmap](https://developer.mozilla.org/en-US/docs/Web/API/Window/createImageBitmap).
  35825. *
  35826. * @param {Object} options - The loader options to set.
  35827. * @return {ImageBitmapLoader} A reference to this image bitmap loader.
  35828. */
  35829. setOptions( options ) {
  35830. this.options = options;
  35831. return this;
  35832. }
  35833. /**
  35834. * Starts loading from the given URL and pass the loaded image bitmap to the `onLoad()` callback.
  35835. *
  35836. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  35837. * @param {function(ImageBitmap)} onLoad - Executed when the loading process has been finished.
  35838. * @param {onProgressCallback} onProgress - Unsupported in this loader.
  35839. * @param {onErrorCallback} onError - Executed when errors occur.
  35840. * @return {ImageBitmap|undefined} The image bitmap.
  35841. */
  35842. load( url, onLoad, onProgress, onError ) {
  35843. if ( url === undefined ) url = '';
  35844. if ( this.path !== undefined ) url = this.path + url;
  35845. url = this.manager.resolveURL( url );
  35846. const scope = this;
  35847. const cached = Cache.get( `image-bitmap:${url}` );
  35848. if ( cached !== undefined ) {
  35849. scope.manager.itemStart( url );
  35850. // If cached is a promise, wait for it to resolve
  35851. if ( cached.then ) {
  35852. cached.then( imageBitmap => {
  35853. // check if there is an error for the cached promise
  35854. if ( _errorMap.has( cached ) === true ) {
  35855. if ( onError ) onError( _errorMap.get( cached ) );
  35856. scope.manager.itemError( url );
  35857. scope.manager.itemEnd( url );
  35858. } else {
  35859. if ( onLoad ) onLoad( imageBitmap );
  35860. scope.manager.itemEnd( url );
  35861. return imageBitmap;
  35862. }
  35863. } );
  35864. return;
  35865. }
  35866. // If cached is not a promise (i.e., it's already an imageBitmap)
  35867. setTimeout( function () {
  35868. if ( onLoad ) onLoad( cached );
  35869. scope.manager.itemEnd( url );
  35870. }, 0 );
  35871. return cached;
  35872. }
  35873. const fetchOptions = {};
  35874. fetchOptions.credentials = ( this.crossOrigin === 'anonymous' ) ? 'same-origin' : 'include';
  35875. fetchOptions.headers = this.requestHeader;
  35876. fetchOptions.signal = ( typeof AbortSignal.any === 'function' ) ? AbortSignal.any( [ this._abortController.signal, this.manager.abortController.signal ] ) : this._abortController.signal;
  35877. const promise = fetch( url, fetchOptions ).then( function ( res ) {
  35878. return res.blob();
  35879. } ).then( function ( blob ) {
  35880. return createImageBitmap( blob, Object.assign( scope.options, { colorSpaceConversion: 'none' } ) );
  35881. } ).then( function ( imageBitmap ) {
  35882. Cache.add( `image-bitmap:${url}`, imageBitmap );
  35883. if ( onLoad ) onLoad( imageBitmap );
  35884. scope.manager.itemEnd( url );
  35885. return imageBitmap;
  35886. } ).catch( function ( e ) {
  35887. if ( onError ) onError( e );
  35888. _errorMap.set( promise, e );
  35889. Cache.remove( `image-bitmap:${url}` );
  35890. scope.manager.itemError( url );
  35891. scope.manager.itemEnd( url );
  35892. } );
  35893. Cache.add( `image-bitmap:${url}`, promise );
  35894. scope.manager.itemStart( url );
  35895. }
  35896. /**
  35897. * Aborts ongoing fetch requests.
  35898. *
  35899. * @return {ImageBitmapLoader} A reference to this instance.
  35900. */
  35901. abort() {
  35902. this._abortController.abort();
  35903. this._abortController = new AbortController();
  35904. return this;
  35905. }
  35906. }
  35907. let _context;
  35908. /**
  35909. * Manages the global audio context in the engine.
  35910. *
  35911. * @hideconstructor
  35912. */
  35913. class AudioContext {
  35914. /**
  35915. * Returns the global native audio context.
  35916. *
  35917. * @return {AudioContext} The native audio context.
  35918. */
  35919. static getContext() {
  35920. if ( _context === undefined ) {
  35921. _context = new ( window.AudioContext || window.webkitAudioContext )();
  35922. }
  35923. return _context;
  35924. }
  35925. /**
  35926. * Allows to set the global native audio context from outside.
  35927. *
  35928. * @param {AudioContext} value - The native context to set.
  35929. */
  35930. static setContext( value ) {
  35931. _context = value;
  35932. }
  35933. }
  35934. /**
  35935. * Class for loading audio buffers. Audios are internally
  35936. * loaded via {@link FileLoader}.
  35937. *
  35938. * ```js
  35939. * const audioListener = new THREE.AudioListener();
  35940. * const ambientSound = new THREE.Audio( audioListener );
  35941. *
  35942. * const loader = new THREE.AudioLoader();
  35943. * const audioBuffer = await loader.loadAsync( 'audio/ambient_ocean.ogg' );
  35944. *
  35945. * ambientSound.setBuffer( audioBuffer );
  35946. * ambientSound.play();
  35947. * ```
  35948. *
  35949. * @augments Loader
  35950. */
  35951. class AudioLoader extends Loader {
  35952. /**
  35953. * Constructs a new audio loader.
  35954. *
  35955. * @param {LoadingManager} [manager] - The loading manager.
  35956. */
  35957. constructor( manager ) {
  35958. super( manager );
  35959. }
  35960. /**
  35961. * Starts loading from the given URL and passes the loaded audio buffer
  35962. * to the `onLoad()` callback.
  35963. *
  35964. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  35965. * @param {function(AudioBuffer)} onLoad - Executed when the loading process has been finished.
  35966. * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
  35967. * @param {onErrorCallback} onError - Executed when errors occur.
  35968. */
  35969. load( url, onLoad, onProgress, onError ) {
  35970. const scope = this;
  35971. const loader = new FileLoader( this.manager );
  35972. loader.setResponseType( 'arraybuffer' );
  35973. loader.setPath( this.path );
  35974. loader.setRequestHeader( this.requestHeader );
  35975. loader.setWithCredentials( this.withCredentials );
  35976. loader.load( url, function ( buffer ) {
  35977. try {
  35978. // Create a copy of the buffer. The `decodeAudioData` method
  35979. // detaches the buffer when complete, preventing reuse.
  35980. const bufferCopy = buffer.slice( 0 );
  35981. const context = AudioContext.getContext();
  35982. context.decodeAudioData( bufferCopy, function ( audioBuffer ) {
  35983. onLoad( audioBuffer );
  35984. } ).catch( handleError );
  35985. } catch ( e ) {
  35986. handleError( e );
  35987. }
  35988. }, onProgress, onError );
  35989. function handleError( e ) {
  35990. if ( onError ) {
  35991. onError( e );
  35992. } else {
  35993. error( e );
  35994. }
  35995. scope.manager.itemError( url );
  35996. }
  35997. }
  35998. }
  35999. const _eyeRight = /*@__PURE__*/ new Matrix4();
  36000. const _eyeLeft = /*@__PURE__*/ new Matrix4();
  36001. const _projectionMatrix = /*@__PURE__*/ new Matrix4();
  36002. /**
  36003. * A special type of camera that uses two perspective cameras with
  36004. * stereoscopic projection. Can be used for rendering stereo effects
  36005. * like [3D Anaglyph](https://en.wikipedia.org/wiki/Anaglyph_3D) or
  36006. * [Parallax Barrier](https://en.wikipedia.org/wiki/parallax_barrier).
  36007. */
  36008. class StereoCamera {
  36009. /**
  36010. * Constructs a new stereo camera.
  36011. */
  36012. constructor() {
  36013. /**
  36014. * The type property is used for detecting the object type
  36015. * in context of serialization/deserialization.
  36016. *
  36017. * @type {string}
  36018. * @readonly
  36019. */
  36020. this.type = 'StereoCamera';
  36021. /**
  36022. * The aspect.
  36023. *
  36024. * @type {number}
  36025. * @default 1
  36026. */
  36027. this.aspect = 1;
  36028. /**
  36029. * The eye separation which represents the distance
  36030. * between the left and right camera.
  36031. *
  36032. * @type {number}
  36033. * @default 0.064
  36034. */
  36035. this.eyeSep = 0.064;
  36036. /**
  36037. * The camera representing the left eye. This is added to layer `1` so objects to be
  36038. * rendered by the left camera must also be added to this layer.
  36039. *
  36040. * @type {PerspectiveCamera}
  36041. */
  36042. this.cameraL = new PerspectiveCamera();
  36043. this.cameraL.layers.enable( 1 );
  36044. this.cameraL.matrixAutoUpdate = false;
  36045. /**
  36046. * The camera representing the right eye. This is added to layer `2` so objects to be
  36047. * rendered by the right camera must also be added to this layer.
  36048. *
  36049. * @type {PerspectiveCamera}
  36050. */
  36051. this.cameraR = new PerspectiveCamera();
  36052. this.cameraR.layers.enable( 2 );
  36053. this.cameraR.matrixAutoUpdate = false;
  36054. this._cache = {
  36055. focus: null,
  36056. fov: null,
  36057. aspect: null,
  36058. near: null,
  36059. far: null,
  36060. zoom: null,
  36061. eyeSep: null
  36062. };
  36063. }
  36064. /**
  36065. * Updates the stereo camera based on the given perspective camera.
  36066. *
  36067. * @param {PerspectiveCamera} camera - The perspective camera.
  36068. */
  36069. update( camera ) {
  36070. const cache = this._cache;
  36071. const needsUpdate = cache.focus !== camera.focus || cache.fov !== camera.fov ||
  36072. cache.aspect !== camera.aspect * this.aspect || cache.near !== camera.near ||
  36073. cache.far !== camera.far || cache.zoom !== camera.zoom || cache.eyeSep !== this.eyeSep;
  36074. if ( needsUpdate ) {
  36075. cache.focus = camera.focus;
  36076. cache.fov = camera.fov;
  36077. cache.aspect = camera.aspect * this.aspect;
  36078. cache.near = camera.near;
  36079. cache.far = camera.far;
  36080. cache.zoom = camera.zoom;
  36081. cache.eyeSep = this.eyeSep;
  36082. // Off-axis stereoscopic effect based on
  36083. // http://paulbourke.net/stereographics/stereorender/
  36084. _projectionMatrix.copy( camera.projectionMatrix );
  36085. const eyeSepHalf = cache.eyeSep / 2;
  36086. const eyeSepOnProjection = eyeSepHalf * cache.near / cache.focus;
  36087. const ymax = ( cache.near * Math.tan( DEG2RAD * cache.fov * 0.5 ) ) / cache.zoom;
  36088. let xmin, xmax;
  36089. // translate xOffset
  36090. _eyeLeft.elements[ 12 ] = - eyeSepHalf;
  36091. _eyeRight.elements[ 12 ] = eyeSepHalf;
  36092. // for left eye
  36093. xmin = - ymax * cache.aspect + eyeSepOnProjection;
  36094. xmax = ymax * cache.aspect + eyeSepOnProjection;
  36095. _projectionMatrix.elements[ 0 ] = 2 * cache.near / ( xmax - xmin );
  36096. _projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin );
  36097. this.cameraL.projectionMatrix.copy( _projectionMatrix );
  36098. // for right eye
  36099. xmin = - ymax * cache.aspect - eyeSepOnProjection;
  36100. xmax = ymax * cache.aspect - eyeSepOnProjection;
  36101. _projectionMatrix.elements[ 0 ] = 2 * cache.near / ( xmax - xmin );
  36102. _projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin );
  36103. this.cameraR.projectionMatrix.copy( _projectionMatrix );
  36104. }
  36105. this.cameraL.matrixWorld.copy( camera.matrixWorld ).multiply( _eyeLeft );
  36106. this.cameraR.matrixWorld.copy( camera.matrixWorld ).multiply( _eyeRight );
  36107. }
  36108. }
  36109. /**
  36110. * This type of camera can be used in order to efficiently render a scene with a
  36111. * predefined set of cameras. This is an important performance aspect for
  36112. * rendering VR scenes.
  36113. *
  36114. * An instance of `ArrayCamera` always has an array of sub cameras. It's mandatory
  36115. * to define for each sub camera the `viewport` property which determines the
  36116. * part of the viewport that is rendered with this camera.
  36117. *
  36118. * @augments PerspectiveCamera
  36119. */
  36120. class ArrayCamera extends PerspectiveCamera {
  36121. /**
  36122. * Constructs a new array camera.
  36123. *
  36124. * @param {Array<PerspectiveCamera>} [array=[]] - An array of perspective sub cameras.
  36125. */
  36126. constructor( array = [] ) {
  36127. super();
  36128. /**
  36129. * This flag can be used for type testing.
  36130. *
  36131. * @type {boolean}
  36132. * @readonly
  36133. * @default true
  36134. */
  36135. this.isArrayCamera = true;
  36136. /**
  36137. * Whether this camera is used with multiview rendering or not.
  36138. *
  36139. * @type {boolean}
  36140. * @readonly
  36141. * @default false
  36142. */
  36143. this.isMultiViewCamera = false;
  36144. /**
  36145. * An array of perspective sub cameras.
  36146. *
  36147. * @type {Array<PerspectiveCamera>}
  36148. */
  36149. this.cameras = array;
  36150. }
  36151. }
  36152. /**
  36153. * Class for keeping track of time.
  36154. */
  36155. class Clock {
  36156. /**
  36157. * Constructs a new clock.
  36158. *
  36159. * @param {boolean} [autoStart=true] - Whether to automatically start the clock when
  36160. * `getDelta()` is called for the first time.
  36161. */
  36162. constructor( autoStart = true ) {
  36163. /**
  36164. * If set to `true`, the clock starts automatically when `getDelta()` is called
  36165. * for the first time.
  36166. *
  36167. * @type {boolean}
  36168. * @default true
  36169. */
  36170. this.autoStart = autoStart;
  36171. /**
  36172. * Holds the time at which the clock's `start()` method was last called.
  36173. *
  36174. * @type {number}
  36175. * @default 0
  36176. */
  36177. this.startTime = 0;
  36178. /**
  36179. * Holds the time at which the clock's `start()`, `getElapsedTime()` or
  36180. * `getDelta()` methods were last called.
  36181. *
  36182. * @type {number}
  36183. * @default 0
  36184. */
  36185. this.oldTime = 0;
  36186. /**
  36187. * Keeps track of the total time that the clock has been running.
  36188. *
  36189. * @type {number}
  36190. * @default 0
  36191. */
  36192. this.elapsedTime = 0;
  36193. /**
  36194. * Whether the clock is running or not.
  36195. *
  36196. * @type {boolean}
  36197. * @default true
  36198. */
  36199. this.running = false;
  36200. }
  36201. /**
  36202. * Starts the clock. When `autoStart` is set to `true`, the method is automatically
  36203. * called by the class.
  36204. */
  36205. start() {
  36206. this.startTime = performance.now();
  36207. this.oldTime = this.startTime;
  36208. this.elapsedTime = 0;
  36209. this.running = true;
  36210. }
  36211. /**
  36212. * Stops the clock.
  36213. */
  36214. stop() {
  36215. this.getElapsedTime();
  36216. this.running = false;
  36217. this.autoStart = false;
  36218. }
  36219. /**
  36220. * Returns the elapsed time in seconds.
  36221. *
  36222. * @return {number} The elapsed time.
  36223. */
  36224. getElapsedTime() {
  36225. this.getDelta();
  36226. return this.elapsedTime;
  36227. }
  36228. /**
  36229. * Returns the delta time in seconds.
  36230. *
  36231. * @return {number} The delta time.
  36232. */
  36233. getDelta() {
  36234. let diff = 0;
  36235. if ( this.autoStart && ! this.running ) {
  36236. this.start();
  36237. return 0;
  36238. }
  36239. if ( this.running ) {
  36240. const newTime = performance.now();
  36241. diff = ( newTime - this.oldTime ) / 1000;
  36242. this.oldTime = newTime;
  36243. this.elapsedTime += diff;
  36244. }
  36245. return diff;
  36246. }
  36247. }
  36248. const _position$1 = /*@__PURE__*/ new Vector3();
  36249. const _quaternion$1 = /*@__PURE__*/ new Quaternion();
  36250. const _scale$1 = /*@__PURE__*/ new Vector3();
  36251. const _forward = /*@__PURE__*/ new Vector3();
  36252. const _up = /*@__PURE__*/ new Vector3();
  36253. /**
  36254. * The class represents a virtual listener of the all positional and non-positional audio effects
  36255. * in the scene. A three.js application usually creates a single listener. It is a mandatory
  36256. * constructor parameter for audios entities like {@link Audio} and {@link PositionalAudio}.
  36257. *
  36258. * In most cases, the listener object is a child of the camera. So the 3D transformation of the
  36259. * camera represents the 3D transformation of the listener.
  36260. *
  36261. * @augments Object3D
  36262. */
  36263. class AudioListener extends Object3D {
  36264. /**
  36265. * Constructs a new audio listener.
  36266. */
  36267. constructor() {
  36268. super();
  36269. this.type = 'AudioListener';
  36270. /**
  36271. * The native audio context.
  36272. *
  36273. * @type {AudioContext}
  36274. * @readonly
  36275. */
  36276. this.context = AudioContext.getContext();
  36277. /**
  36278. * The gain node used for volume control.
  36279. *
  36280. * @type {GainNode}
  36281. * @readonly
  36282. */
  36283. this.gain = this.context.createGain();
  36284. this.gain.connect( this.context.destination );
  36285. /**
  36286. * An optional filter.
  36287. *
  36288. * Defined via {@link AudioListener#setFilter}.
  36289. *
  36290. * @type {?AudioNode}
  36291. * @default null
  36292. * @readonly
  36293. */
  36294. this.filter = null;
  36295. /**
  36296. * Time delta values required for `linearRampToValueAtTime()` usage.
  36297. *
  36298. * @type {number}
  36299. * @default 0
  36300. * @readonly
  36301. */
  36302. this.timeDelta = 0;
  36303. // private
  36304. this._clock = new Clock();
  36305. }
  36306. /**
  36307. * Returns the listener's input node.
  36308. *
  36309. * This method is used by other audio nodes to connect to this listener.
  36310. *
  36311. * @return {GainNode} The input node.
  36312. */
  36313. getInput() {
  36314. return this.gain;
  36315. }
  36316. /**
  36317. * Removes the current filter from this listener.
  36318. *
  36319. * @return {AudioListener} A reference to this listener.
  36320. */
  36321. removeFilter() {
  36322. if ( this.filter !== null ) {
  36323. this.gain.disconnect( this.filter );
  36324. this.filter.disconnect( this.context.destination );
  36325. this.gain.connect( this.context.destination );
  36326. this.filter = null;
  36327. }
  36328. return this;
  36329. }
  36330. /**
  36331. * Returns the current set filter.
  36332. *
  36333. * @return {?AudioNode} The filter.
  36334. */
  36335. getFilter() {
  36336. return this.filter;
  36337. }
  36338. /**
  36339. * Sets the given filter to this listener.
  36340. *
  36341. * @param {AudioNode} value - The filter to set.
  36342. * @return {AudioListener} A reference to this listener.
  36343. */
  36344. setFilter( value ) {
  36345. if ( this.filter !== null ) {
  36346. this.gain.disconnect( this.filter );
  36347. this.filter.disconnect( this.context.destination );
  36348. } else {
  36349. this.gain.disconnect( this.context.destination );
  36350. }
  36351. this.filter = value;
  36352. this.gain.connect( this.filter );
  36353. this.filter.connect( this.context.destination );
  36354. return this;
  36355. }
  36356. /**
  36357. * Returns the applications master volume.
  36358. *
  36359. * @return {number} The master volume.
  36360. */
  36361. getMasterVolume() {
  36362. return this.gain.gain.value;
  36363. }
  36364. /**
  36365. * Sets the applications master volume. This volume setting affects
  36366. * all audio nodes in the scene.
  36367. *
  36368. * @param {number} value - The master volume to set.
  36369. * @return {AudioListener} A reference to this listener.
  36370. */
  36371. setMasterVolume( value ) {
  36372. this.gain.gain.setTargetAtTime( value, this.context.currentTime, 0.01 );
  36373. return this;
  36374. }
  36375. updateMatrixWorld( force ) {
  36376. super.updateMatrixWorld( force );
  36377. const listener = this.context.listener;
  36378. this.timeDelta = this._clock.getDelta();
  36379. this.matrixWorld.decompose( _position$1, _quaternion$1, _scale$1 );
  36380. // the initial forward and up directions must be orthogonal
  36381. _forward.set( 0, 0, -1 ).applyQuaternion( _quaternion$1 );
  36382. _up.set( 0, 1, 0 ).applyQuaternion( _quaternion$1 );
  36383. if ( listener.positionX ) {
  36384. // code path for Chrome (see #14393)
  36385. const endTime = this.context.currentTime + this.timeDelta;
  36386. listener.positionX.linearRampToValueAtTime( _position$1.x, endTime );
  36387. listener.positionY.linearRampToValueAtTime( _position$1.y, endTime );
  36388. listener.positionZ.linearRampToValueAtTime( _position$1.z, endTime );
  36389. listener.forwardX.linearRampToValueAtTime( _forward.x, endTime );
  36390. listener.forwardY.linearRampToValueAtTime( _forward.y, endTime );
  36391. listener.forwardZ.linearRampToValueAtTime( _forward.z, endTime );
  36392. listener.upX.linearRampToValueAtTime( _up.x, endTime );
  36393. listener.upY.linearRampToValueAtTime( _up.y, endTime );
  36394. listener.upZ.linearRampToValueAtTime( _up.z, endTime );
  36395. } else {
  36396. listener.setPosition( _position$1.x, _position$1.y, _position$1.z );
  36397. listener.setOrientation( _forward.x, _forward.y, _forward.z, _up.x, _up.y, _up.z );
  36398. }
  36399. }
  36400. }
  36401. /**
  36402. * Represents a non-positional ( global ) audio object.
  36403. *
  36404. * This and related audio modules make use of the [Web Audio API](https://www.w3.org/TR/webaudio-1.1/).
  36405. *
  36406. * ```js
  36407. * // create an AudioListener and add it to the camera
  36408. * const listener = new THREE.AudioListener();
  36409. * camera.add( listener );
  36410. *
  36411. * // create a global audio source
  36412. * const sound = new THREE.Audio( listener );
  36413. *
  36414. * // load a sound and set it as the Audio object's buffer
  36415. * const audioLoader = new THREE.AudioLoader();
  36416. * audioLoader.load( 'sounds/ambient.ogg', function( buffer ) {
  36417. * sound.setBuffer( buffer );
  36418. * sound.setLoop( true );
  36419. * sound.setVolume( 0.5 );
  36420. * sound.play();
  36421. * });
  36422. * ```
  36423. *
  36424. * @augments Object3D
  36425. */
  36426. class Audio extends Object3D {
  36427. /**
  36428. * Constructs a new audio.
  36429. *
  36430. * @param {AudioListener} listener - The global audio listener.
  36431. */
  36432. constructor( listener ) {
  36433. super();
  36434. this.type = 'Audio';
  36435. /**
  36436. * The global audio listener.
  36437. *
  36438. * @type {AudioListener}
  36439. * @readonly
  36440. */
  36441. this.listener = listener;
  36442. /**
  36443. * The audio context.
  36444. *
  36445. * @type {AudioContext}
  36446. * @readonly
  36447. */
  36448. this.context = listener.context;
  36449. /**
  36450. * The gain node used for volume control.
  36451. *
  36452. * @type {GainNode}
  36453. * @readonly
  36454. */
  36455. this.gain = this.context.createGain();
  36456. this.gain.connect( listener.getInput() );
  36457. /**
  36458. * Whether to start playback automatically or not.
  36459. *
  36460. * @type {boolean}
  36461. * @default false
  36462. */
  36463. this.autoplay = false;
  36464. /**
  36465. * A reference to an audio buffer.
  36466. *
  36467. * Defined via {@link Audio#setBuffer}.
  36468. *
  36469. * @type {?AudioBuffer}
  36470. * @default null
  36471. * @readonly
  36472. */
  36473. this.buffer = null;
  36474. /**
  36475. * Modify pitch, measured in cents. +/- 100 is a semitone.
  36476. * +/- 1200 is an octave.
  36477. *
  36478. * Defined via {@link Audio#setDetune}.
  36479. *
  36480. * @type {number}
  36481. * @default 0
  36482. * @readonly
  36483. */
  36484. this.detune = 0;
  36485. /**
  36486. * Whether the audio should loop or not.
  36487. *
  36488. * Defined via {@link Audio#setLoop}.
  36489. *
  36490. * @type {boolean}
  36491. * @default false
  36492. * @readonly
  36493. */
  36494. this.loop = false;
  36495. /**
  36496. * Defines where in the audio buffer the replay should
  36497. * start, in seconds.
  36498. *
  36499. * @type {number}
  36500. * @default 0
  36501. */
  36502. this.loopStart = 0;
  36503. /**
  36504. * Defines where in the audio buffer the replay should
  36505. * stop, in seconds.
  36506. *
  36507. * @type {number}
  36508. * @default 0
  36509. */
  36510. this.loopEnd = 0;
  36511. /**
  36512. * An offset to the time within the audio buffer the playback
  36513. * should begin, in seconds.
  36514. *
  36515. * @type {number}
  36516. * @default 0
  36517. */
  36518. this.offset = 0;
  36519. /**
  36520. * Overrides the default duration of the audio.
  36521. *
  36522. * @type {undefined|number}
  36523. * @default undefined
  36524. */
  36525. this.duration = undefined;
  36526. /**
  36527. * The playback speed.
  36528. *
  36529. * Defined via {@link Audio#setPlaybackRate}.
  36530. *
  36531. * @type {number}
  36532. * @readonly
  36533. * @default 1
  36534. */
  36535. this.playbackRate = 1;
  36536. /**
  36537. * Indicates whether the audio is playing or not.
  36538. *
  36539. * This flag will be automatically set when using {@link Audio#play},
  36540. * {@link Audio#pause}, {@link Audio#stop}.
  36541. *
  36542. * @type {boolean}
  36543. * @readonly
  36544. * @default false
  36545. */
  36546. this.isPlaying = false;
  36547. /**
  36548. * Indicates whether the audio playback can be controlled
  36549. * with method like {@link Audio#play} or {@link Audio#pause}.
  36550. *
  36551. * This flag will be automatically set when audio sources are
  36552. * defined.
  36553. *
  36554. * @type {boolean}
  36555. * @readonly
  36556. * @default true
  36557. */
  36558. this.hasPlaybackControl = true;
  36559. /**
  36560. * Holds a reference to the current audio source.
  36561. *
  36562. * The property is automatically by one of the `set*()` methods.
  36563. *
  36564. * @type {?AudioNode}
  36565. * @readonly
  36566. * @default null
  36567. */
  36568. this.source = null;
  36569. /**
  36570. * Defines the source type.
  36571. *
  36572. * The property is automatically set by one of the `set*()` methods.
  36573. *
  36574. * @type {('empty'|'audioNode'|'mediaNode'|'mediaStreamNode'|'buffer')}
  36575. * @readonly
  36576. * @default 'empty'
  36577. */
  36578. this.sourceType = 'empty';
  36579. this._startedAt = 0;
  36580. this._progress = 0;
  36581. this._connected = false;
  36582. /**
  36583. * Can be used to apply a variety of low-order filters to create
  36584. * more complex sound effects e.g. via `BiquadFilterNode`.
  36585. *
  36586. * The property is automatically set by {@link Audio#setFilters}.
  36587. *
  36588. * @type {Array<AudioNode>}
  36589. * @readonly
  36590. */
  36591. this.filters = [];
  36592. }
  36593. /**
  36594. * Returns the output audio node.
  36595. *
  36596. * @return {GainNode} The output node.
  36597. */
  36598. getOutput() {
  36599. return this.gain;
  36600. }
  36601. /**
  36602. * Sets the given audio node as the source of this instance.
  36603. *
  36604. * {@link Audio#sourceType} is set to `audioNode` and {@link Audio#hasPlaybackControl} to `false`.
  36605. *
  36606. * @param {AudioNode} audioNode - The audio node like an instance of `OscillatorNode`.
  36607. * @return {Audio} A reference to this instance.
  36608. */
  36609. setNodeSource( audioNode ) {
  36610. this.hasPlaybackControl = false;
  36611. this.sourceType = 'audioNode';
  36612. this.source = audioNode;
  36613. this.connect();
  36614. return this;
  36615. }
  36616. /**
  36617. * Sets the given media element as the source of this instance.
  36618. *
  36619. * {@link Audio#sourceType} is set to `mediaNode` and {@link Audio#hasPlaybackControl} to `false`.
  36620. *
  36621. * @param {HTMLMediaElement} mediaElement - The media element.
  36622. * @return {Audio} A reference to this instance.
  36623. */
  36624. setMediaElementSource( mediaElement ) {
  36625. this.hasPlaybackControl = false;
  36626. this.sourceType = 'mediaNode';
  36627. this.source = this.context.createMediaElementSource( mediaElement );
  36628. this.connect();
  36629. return this;
  36630. }
  36631. /**
  36632. * Sets the given media stream as the source of this instance.
  36633. *
  36634. * {@link Audio#sourceType} is set to `mediaStreamNode` and {@link Audio#hasPlaybackControl} to `false`.
  36635. *
  36636. * @param {MediaStream} mediaStream - The media stream.
  36637. * @return {Audio} A reference to this instance.
  36638. */
  36639. setMediaStreamSource( mediaStream ) {
  36640. this.hasPlaybackControl = false;
  36641. this.sourceType = 'mediaStreamNode';
  36642. this.source = this.context.createMediaStreamSource( mediaStream );
  36643. this.connect();
  36644. return this;
  36645. }
  36646. /**
  36647. * Sets the given audio buffer as the source of this instance.
  36648. *
  36649. * {@link Audio#sourceType} is set to `buffer` and {@link Audio#hasPlaybackControl} to `true`.
  36650. *
  36651. * @param {AudioBuffer} audioBuffer - The audio buffer.
  36652. * @return {Audio} A reference to this instance.
  36653. */
  36654. setBuffer( audioBuffer ) {
  36655. this.buffer = audioBuffer;
  36656. this.sourceType = 'buffer';
  36657. if ( this.autoplay ) this.play();
  36658. return this;
  36659. }
  36660. /**
  36661. * Starts the playback of the audio.
  36662. *
  36663. * Can only be used with compatible audio sources that allow playback control.
  36664. *
  36665. * @param {number} [delay=0] - The delay, in seconds, at which the audio should start playing.
  36666. * @return {Audio|undefined} A reference to this instance.
  36667. */
  36668. play( delay = 0 ) {
  36669. if ( this.isPlaying === true ) {
  36670. warn( 'Audio: Audio is already playing.' );
  36671. return;
  36672. }
  36673. if ( this.hasPlaybackControl === false ) {
  36674. warn( 'Audio: this Audio has no playback control.' );
  36675. return;
  36676. }
  36677. this._startedAt = this.context.currentTime + delay;
  36678. const source = this.context.createBufferSource();
  36679. source.buffer = this.buffer;
  36680. source.loop = this.loop;
  36681. source.loopStart = this.loopStart;
  36682. source.loopEnd = this.loopEnd;
  36683. source.onended = this.onEnded.bind( this );
  36684. source.start( this._startedAt, this._progress + this.offset, this.duration );
  36685. this.isPlaying = true;
  36686. this.source = source;
  36687. this.setDetune( this.detune );
  36688. this.setPlaybackRate( this.playbackRate );
  36689. return this.connect();
  36690. }
  36691. /**
  36692. * Pauses the playback of the audio.
  36693. *
  36694. * Can only be used with compatible audio sources that allow playback control.
  36695. *
  36696. * @return {Audio|undefined} A reference to this instance.
  36697. */
  36698. pause() {
  36699. if ( this.hasPlaybackControl === false ) {
  36700. warn( 'Audio: this Audio has no playback control.' );
  36701. return;
  36702. }
  36703. if ( this.isPlaying === true ) {
  36704. // update current progress
  36705. this._progress += Math.max( this.context.currentTime - this._startedAt, 0 ) * this.playbackRate;
  36706. if ( this.loop === true ) {
  36707. // ensure _progress does not exceed duration with looped audios
  36708. this._progress = this._progress % ( this.duration || this.buffer.duration );
  36709. }
  36710. this.source.stop();
  36711. this.source.onended = null;
  36712. this.isPlaying = false;
  36713. }
  36714. return this;
  36715. }
  36716. /**
  36717. * Stops the playback of the audio.
  36718. *
  36719. * Can only be used with compatible audio sources that allow playback control.
  36720. *
  36721. * @param {number} [delay=0] - The delay, in seconds, at which the audio should stop playing.
  36722. * @return {Audio|undefined} A reference to this instance.
  36723. */
  36724. stop( delay = 0 ) {
  36725. if ( this.hasPlaybackControl === false ) {
  36726. warn( 'Audio: this Audio has no playback control.' );
  36727. return;
  36728. }
  36729. this._progress = 0;
  36730. if ( this.source !== null ) {
  36731. this.source.stop( this.context.currentTime + delay );
  36732. this.source.onended = null;
  36733. }
  36734. this.isPlaying = false;
  36735. return this;
  36736. }
  36737. /**
  36738. * Connects to the audio source. This is used internally on
  36739. * initialisation and when setting / removing filters.
  36740. *
  36741. * @return {Audio} A reference to this instance.
  36742. */
  36743. connect() {
  36744. if ( this.filters.length > 0 ) {
  36745. this.source.connect( this.filters[ 0 ] );
  36746. for ( let i = 1, l = this.filters.length; i < l; i ++ ) {
  36747. this.filters[ i - 1 ].connect( this.filters[ i ] );
  36748. }
  36749. this.filters[ this.filters.length - 1 ].connect( this.getOutput() );
  36750. } else {
  36751. this.source.connect( this.getOutput() );
  36752. }
  36753. this._connected = true;
  36754. return this;
  36755. }
  36756. /**
  36757. * Disconnects to the audio source. This is used internally on
  36758. * initialisation and when setting / removing filters.
  36759. *
  36760. * @return {Audio|undefined} A reference to this instance.
  36761. */
  36762. disconnect() {
  36763. if ( this._connected === false ) {
  36764. return;
  36765. }
  36766. if ( this.filters.length > 0 ) {
  36767. this.source.disconnect( this.filters[ 0 ] );
  36768. for ( let i = 1, l = this.filters.length; i < l; i ++ ) {
  36769. this.filters[ i - 1 ].disconnect( this.filters[ i ] );
  36770. }
  36771. this.filters[ this.filters.length - 1 ].disconnect( this.getOutput() );
  36772. } else {
  36773. this.source.disconnect( this.getOutput() );
  36774. }
  36775. this._connected = false;
  36776. return this;
  36777. }
  36778. /**
  36779. * Returns the current set filters.
  36780. *
  36781. * @return {Array<AudioNode>} The list of filters.
  36782. */
  36783. getFilters() {
  36784. return this.filters;
  36785. }
  36786. /**
  36787. * Sets an array of filters and connects them with the audio source.
  36788. *
  36789. * @param {Array<AudioNode>} [value] - A list of filters.
  36790. * @return {Audio} A reference to this instance.
  36791. */
  36792. setFilters( value ) {
  36793. if ( ! value ) value = [];
  36794. if ( this._connected === true ) {
  36795. this.disconnect();
  36796. this.filters = value.slice();
  36797. this.connect();
  36798. } else {
  36799. this.filters = value.slice();
  36800. }
  36801. return this;
  36802. }
  36803. /**
  36804. * Defines the detuning of oscillation in cents.
  36805. *
  36806. * @param {number} value - The detuning of oscillation in cents.
  36807. * @return {Audio} A reference to this instance.
  36808. */
  36809. setDetune( value ) {
  36810. this.detune = value;
  36811. if ( this.isPlaying === true && this.source.detune !== undefined ) {
  36812. this.source.detune.setTargetAtTime( this.detune, this.context.currentTime, 0.01 );
  36813. }
  36814. return this;
  36815. }
  36816. /**
  36817. * Returns the detuning of oscillation in cents.
  36818. *
  36819. * @return {number} The detuning of oscillation in cents.
  36820. */
  36821. getDetune() {
  36822. return this.detune;
  36823. }
  36824. /**
  36825. * Returns the first filter in the list of filters.
  36826. *
  36827. * @return {AudioNode|undefined} The first filter in the list of filters.
  36828. */
  36829. getFilter() {
  36830. return this.getFilters()[ 0 ];
  36831. }
  36832. /**
  36833. * Applies a single filter node to the audio.
  36834. *
  36835. * @param {AudioNode} [filter] - The filter to set.
  36836. * @return {Audio} A reference to this instance.
  36837. */
  36838. setFilter( filter ) {
  36839. return this.setFilters( filter ? [ filter ] : [] );
  36840. }
  36841. /**
  36842. * Sets the playback rate.
  36843. *
  36844. * Can only be used with compatible audio sources that allow playback control.
  36845. *
  36846. * @param {number} [value] - The playback rate to set.
  36847. * @return {Audio|undefined} A reference to this instance.
  36848. */
  36849. setPlaybackRate( value ) {
  36850. if ( this.hasPlaybackControl === false ) {
  36851. warn( 'Audio: this Audio has no playback control.' );
  36852. return;
  36853. }
  36854. this.playbackRate = value;
  36855. if ( this.isPlaying === true ) {
  36856. this.source.playbackRate.setTargetAtTime( this.playbackRate, this.context.currentTime, 0.01 );
  36857. }
  36858. return this;
  36859. }
  36860. /**
  36861. * Returns the current playback rate.
  36862. * @return {number} The playback rate.
  36863. */
  36864. getPlaybackRate() {
  36865. return this.playbackRate;
  36866. }
  36867. /**
  36868. * Automatically called when playback finished.
  36869. */
  36870. onEnded() {
  36871. this.isPlaying = false;
  36872. this._progress = 0;
  36873. }
  36874. /**
  36875. * Returns the loop flag.
  36876. *
  36877. * Can only be used with compatible audio sources that allow playback control.
  36878. *
  36879. * @return {boolean} Whether the audio should loop or not.
  36880. */
  36881. getLoop() {
  36882. if ( this.hasPlaybackControl === false ) {
  36883. warn( 'Audio: this Audio has no playback control.' );
  36884. return false;
  36885. }
  36886. return this.loop;
  36887. }
  36888. /**
  36889. * Sets the loop flag.
  36890. *
  36891. * Can only be used with compatible audio sources that allow playback control.
  36892. *
  36893. * @param {boolean} value - Whether the audio should loop or not.
  36894. * @return {Audio|undefined} A reference to this instance.
  36895. */
  36896. setLoop( value ) {
  36897. if ( this.hasPlaybackControl === false ) {
  36898. warn( 'Audio: this Audio has no playback control.' );
  36899. return;
  36900. }
  36901. this.loop = value;
  36902. if ( this.isPlaying === true ) {
  36903. this.source.loop = this.loop;
  36904. }
  36905. return this;
  36906. }
  36907. /**
  36908. * Sets the loop start value which defines where in the audio buffer the replay should
  36909. * start, in seconds.
  36910. *
  36911. * @param {number} value - The loop start value.
  36912. * @return {Audio} A reference to this instance.
  36913. */
  36914. setLoopStart( value ) {
  36915. this.loopStart = value;
  36916. return this;
  36917. }
  36918. /**
  36919. * Sets the loop end value which defines where in the audio buffer the replay should
  36920. * stop, in seconds.
  36921. *
  36922. * @param {number} value - The loop end value.
  36923. * @return {Audio} A reference to this instance.
  36924. */
  36925. setLoopEnd( value ) {
  36926. this.loopEnd = value;
  36927. return this;
  36928. }
  36929. /**
  36930. * Returns the volume.
  36931. *
  36932. * @return {number} The volume.
  36933. */
  36934. getVolume() {
  36935. return this.gain.gain.value;
  36936. }
  36937. /**
  36938. * Sets the volume.
  36939. *
  36940. * @param {number} value - The volume to set.
  36941. * @return {Audio} A reference to this instance.
  36942. */
  36943. setVolume( value ) {
  36944. this.gain.gain.setTargetAtTime( value, this.context.currentTime, 0.01 );
  36945. return this;
  36946. }
  36947. copy( source, recursive ) {
  36948. super.copy( source, recursive );
  36949. if ( source.sourceType !== 'buffer' ) {
  36950. warn( 'Audio: Audio source type cannot be copied.' );
  36951. return this;
  36952. }
  36953. this.autoplay = source.autoplay;
  36954. this.buffer = source.buffer;
  36955. this.detune = source.detune;
  36956. this.loop = source.loop;
  36957. this.loopStart = source.loopStart;
  36958. this.loopEnd = source.loopEnd;
  36959. this.offset = source.offset;
  36960. this.duration = source.duration;
  36961. this.playbackRate = source.playbackRate;
  36962. this.hasPlaybackControl = source.hasPlaybackControl;
  36963. this.sourceType = source.sourceType;
  36964. this.filters = source.filters.slice();
  36965. return this;
  36966. }
  36967. clone( recursive ) {
  36968. return new this.constructor( this.listener ).copy( this, recursive );
  36969. }
  36970. }
  36971. const _position = /*@__PURE__*/ new Vector3();
  36972. const _quaternion = /*@__PURE__*/ new Quaternion();
  36973. const _scale = /*@__PURE__*/ new Vector3();
  36974. const _orientation = /*@__PURE__*/ new Vector3();
  36975. /**
  36976. * Represents a positional audio object.
  36977. *
  36978. * ```js
  36979. * // create an AudioListener and add it to the camera
  36980. * const listener = new THREE.AudioListener();
  36981. * camera.add( listener );
  36982. *
  36983. * // create the PositionalAudio object (passing in the listener)
  36984. * const sound = new THREE.PositionalAudio( listener );
  36985. *
  36986. * // load a sound and set it as the PositionalAudio object's buffer
  36987. * const audioLoader = new THREE.AudioLoader();
  36988. * audioLoader.load( 'sounds/song.ogg', function( buffer ) {
  36989. * sound.setBuffer( buffer );
  36990. * sound.setRefDistance( 20 );
  36991. * sound.play();
  36992. * });
  36993. *
  36994. * // create an object for the sound to play from
  36995. * const sphere = new THREE.SphereGeometry( 20, 32, 16 );
  36996. * const material = new THREE.MeshPhongMaterial( { color: 0xff2200 } );
  36997. * const mesh = new THREE.Mesh( sphere, material );
  36998. * scene.add( mesh );
  36999. *
  37000. * // finally add the sound to the mesh
  37001. * mesh.add( sound );
  37002. *
  37003. * @augments Audio
  37004. */
  37005. class PositionalAudio extends Audio {
  37006. /**
  37007. * Constructs a positional audio.
  37008. *
  37009. * @param {AudioListener} listener - The global audio listener.
  37010. */
  37011. constructor( listener ) {
  37012. super( listener );
  37013. /**
  37014. * The panner node represents the location, direction, and behavior of an audio
  37015. * source in 3D space.
  37016. *
  37017. * @type {PannerNode}
  37018. * @readonly
  37019. */
  37020. this.panner = this.context.createPanner();
  37021. this.panner.panningModel = 'HRTF';
  37022. this.panner.connect( this.gain );
  37023. }
  37024. connect() {
  37025. super.connect();
  37026. this.panner.connect( this.gain );
  37027. return this;
  37028. }
  37029. disconnect() {
  37030. super.disconnect();
  37031. this.panner.disconnect( this.gain );
  37032. return this;
  37033. }
  37034. getOutput() {
  37035. return this.panner;
  37036. }
  37037. /**
  37038. * Returns the current reference distance.
  37039. *
  37040. * @return {number} The reference distance.
  37041. */
  37042. getRefDistance() {
  37043. return this.panner.refDistance;
  37044. }
  37045. /**
  37046. * Defines the reference distance for reducing volume as the audio source moves
  37047. * further from the listener – i.e. the distance at which the volume reduction
  37048. * starts taking effect.
  37049. *
  37050. * @param {number} value - The reference distance to set.
  37051. * @return {PositionalAudio} A reference to this instance.
  37052. */
  37053. setRefDistance( value ) {
  37054. this.panner.refDistance = value;
  37055. return this;
  37056. }
  37057. /**
  37058. * Returns the current rolloff factor.
  37059. *
  37060. * @return {number} The rolloff factor.
  37061. */
  37062. getRolloffFactor() {
  37063. return this.panner.rolloffFactor;
  37064. }
  37065. /**
  37066. * Defines how quickly the volume is reduced as the source moves away from the listener.
  37067. *
  37068. * @param {number} value - The rolloff factor.
  37069. * @return {PositionalAudio} A reference to this instance.
  37070. */
  37071. setRolloffFactor( value ) {
  37072. this.panner.rolloffFactor = value;
  37073. return this;
  37074. }
  37075. /**
  37076. * Returns the current distance model.
  37077. *
  37078. * @return {('linear'|'inverse'|'exponential')} The distance model.
  37079. */
  37080. getDistanceModel() {
  37081. return this.panner.distanceModel;
  37082. }
  37083. /**
  37084. * Defines which algorithm to use to reduce the volume of the audio source
  37085. * as it moves away from the listener.
  37086. *
  37087. * Read [the spec](https://www.w3.org/TR/webaudio-1.1/#enumdef-distancemodeltype)
  37088. * for more details.
  37089. *
  37090. * @param {('linear'|'inverse'|'exponential')} value - The distance model to set.
  37091. * @return {PositionalAudio} A reference to this instance.
  37092. */
  37093. setDistanceModel( value ) {
  37094. this.panner.distanceModel = value;
  37095. return this;
  37096. }
  37097. /**
  37098. * Returns the current max distance.
  37099. *
  37100. * @return {number} The max distance.
  37101. */
  37102. getMaxDistance() {
  37103. return this.panner.maxDistance;
  37104. }
  37105. /**
  37106. * Defines the maximum distance between the audio source and the listener,
  37107. * after which the volume is not reduced any further.
  37108. *
  37109. * This value is used only by the `linear` distance model.
  37110. *
  37111. * @param {number} value - The max distance.
  37112. * @return {PositionalAudio} A reference to this instance.
  37113. */
  37114. setMaxDistance( value ) {
  37115. this.panner.maxDistance = value;
  37116. return this;
  37117. }
  37118. /**
  37119. * Sets the directional cone in which the audio can be listened.
  37120. *
  37121. * @param {number} coneInnerAngle - An angle, in degrees, of a cone inside of which there will be no volume reduction.
  37122. * @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.
  37123. * @param {number} coneOuterGain - The amount of volume reduction outside the cone defined by the `coneOuterAngle`. When set to `0`, no sound can be heard.
  37124. * @return {PositionalAudio} A reference to this instance.
  37125. */
  37126. setDirectionalCone( coneInnerAngle, coneOuterAngle, coneOuterGain ) {
  37127. this.panner.coneInnerAngle = coneInnerAngle;
  37128. this.panner.coneOuterAngle = coneOuterAngle;
  37129. this.panner.coneOuterGain = coneOuterGain;
  37130. return this;
  37131. }
  37132. updateMatrixWorld( force ) {
  37133. super.updateMatrixWorld( force );
  37134. if ( this.hasPlaybackControl === true && this.isPlaying === false ) return;
  37135. this.matrixWorld.decompose( _position, _quaternion, _scale );
  37136. _orientation.set( 0, 0, 1 ).applyQuaternion( _quaternion );
  37137. const panner = this.panner;
  37138. if ( panner.positionX ) {
  37139. // code path for Chrome and Firefox (see #14393)
  37140. const endTime = this.context.currentTime + this.listener.timeDelta;
  37141. panner.positionX.linearRampToValueAtTime( _position.x, endTime );
  37142. panner.positionY.linearRampToValueAtTime( _position.y, endTime );
  37143. panner.positionZ.linearRampToValueAtTime( _position.z, endTime );
  37144. panner.orientationX.linearRampToValueAtTime( _orientation.x, endTime );
  37145. panner.orientationY.linearRampToValueAtTime( _orientation.y, endTime );
  37146. panner.orientationZ.linearRampToValueAtTime( _orientation.z, endTime );
  37147. } else {
  37148. panner.setPosition( _position.x, _position.y, _position.z );
  37149. panner.setOrientation( _orientation.x, _orientation.y, _orientation.z );
  37150. }
  37151. }
  37152. }
  37153. /**
  37154. * This class can be used to analyse audio data.
  37155. *
  37156. * ```js
  37157. * // create an AudioListener and add it to the camera
  37158. * const listener = new THREE.AudioListener();
  37159. * camera.add( listener );
  37160. *
  37161. * // create an Audio source
  37162. * const sound = new THREE.Audio( listener );
  37163. *
  37164. * // load a sound and set it as the Audio object's buffer
  37165. * const audioLoader = new THREE.AudioLoader();
  37166. * audioLoader.load( 'sounds/ambient.ogg', function( buffer ) {
  37167. * sound.setBuffer( buffer );
  37168. * sound.setLoop(true);
  37169. * sound.setVolume(0.5);
  37170. * sound.play();
  37171. * });
  37172. *
  37173. * // create an AudioAnalyser, passing in the sound and desired fftSize
  37174. * const analyser = new THREE.AudioAnalyser( sound, 32 );
  37175. *
  37176. * // get the average frequency of the sound
  37177. * const data = analyser.getAverageFrequency();
  37178. * ```
  37179. */
  37180. class AudioAnalyser {
  37181. /**
  37182. * Constructs a new audio analyzer.
  37183. *
  37184. * @param {Audio} audio - The audio to analyze.
  37185. * @param {number} [fftSize=2048] - The window size in samples that is used when performing a Fast Fourier Transform (FFT) to get frequency domain data.
  37186. */
  37187. constructor( audio, fftSize = 2048 ) {
  37188. /**
  37189. * The global audio listener.
  37190. *
  37191. * @type {AnalyserNode}
  37192. */
  37193. this.analyser = audio.context.createAnalyser();
  37194. this.analyser.fftSize = fftSize;
  37195. /**
  37196. * Holds the analyzed data.
  37197. *
  37198. * @type {Uint8Array}
  37199. */
  37200. this.data = new Uint8Array( this.analyser.frequencyBinCount );
  37201. audio.getOutput().connect( this.analyser );
  37202. }
  37203. /**
  37204. * Returns an array with frequency data of the audio.
  37205. *
  37206. * Each item in the array represents the decibel value for a specific frequency.
  37207. * The frequencies are spread linearly from 0 to 1/2 of the sample rate.
  37208. * For example, for 48000 sample rate, the last item of the array will represent
  37209. * the decibel value for 24000 Hz.
  37210. *
  37211. * @return {Uint8Array} The frequency data.
  37212. */
  37213. getFrequencyData() {
  37214. this.analyser.getByteFrequencyData( this.data );
  37215. return this.data;
  37216. }
  37217. /**
  37218. * Returns the average of the frequencies returned by {@link AudioAnalyser#getFrequencyData}.
  37219. *
  37220. * @return {number} The average frequency.
  37221. */
  37222. getAverageFrequency() {
  37223. let value = 0;
  37224. const data = this.getFrequencyData();
  37225. for ( let i = 0; i < data.length; i ++ ) {
  37226. value += data[ i ];
  37227. }
  37228. return value / data.length;
  37229. }
  37230. }
  37231. /**
  37232. * Buffered scene graph property that allows weighted accumulation; used internally.
  37233. */
  37234. class PropertyMixer {
  37235. /**
  37236. * Constructs a new property mixer.
  37237. *
  37238. * @param {PropertyBinding} binding - The property binding.
  37239. * @param {string} typeName - The keyframe track type name.
  37240. * @param {number} valueSize - The keyframe track value size.
  37241. */
  37242. constructor( binding, typeName, valueSize ) {
  37243. /**
  37244. * The property binding.
  37245. *
  37246. * @type {PropertyBinding}
  37247. */
  37248. this.binding = binding;
  37249. /**
  37250. * The keyframe track value size.
  37251. *
  37252. * @type {number}
  37253. */
  37254. this.valueSize = valueSize;
  37255. let mixFunction,
  37256. mixFunctionAdditive,
  37257. setIdentity;
  37258. // buffer layout: [ incoming | accu0 | accu1 | orig | addAccu | (optional work) ]
  37259. //
  37260. // interpolators can use .buffer as their .result
  37261. // the data then goes to 'incoming'
  37262. //
  37263. // 'accu0' and 'accu1' are used frame-interleaved for
  37264. // the cumulative result and are compared to detect
  37265. // changes
  37266. //
  37267. // 'orig' stores the original state of the property
  37268. //
  37269. // 'add' is used for additive cumulative results
  37270. //
  37271. // 'work' is optional and is only present for quaternion types. It is used
  37272. // to store intermediate quaternion multiplication results
  37273. switch ( typeName ) {
  37274. case 'quaternion':
  37275. mixFunction = this._slerp;
  37276. mixFunctionAdditive = this._slerpAdditive;
  37277. setIdentity = this._setAdditiveIdentityQuaternion;
  37278. this.buffer = new Float64Array( valueSize * 6 );
  37279. this._workIndex = 5;
  37280. break;
  37281. case 'string':
  37282. case 'bool':
  37283. mixFunction = this._select;
  37284. // Use the regular mix function and for additive on these types,
  37285. // additive is not relevant for non-numeric types
  37286. mixFunctionAdditive = this._select;
  37287. setIdentity = this._setAdditiveIdentityOther;
  37288. this.buffer = new Array( valueSize * 5 );
  37289. break;
  37290. default:
  37291. mixFunction = this._lerp;
  37292. mixFunctionAdditive = this._lerpAdditive;
  37293. setIdentity = this._setAdditiveIdentityNumeric;
  37294. this.buffer = new Float64Array( valueSize * 5 );
  37295. }
  37296. this._mixBufferRegion = mixFunction;
  37297. this._mixBufferRegionAdditive = mixFunctionAdditive;
  37298. this._setIdentity = setIdentity;
  37299. this._origIndex = 3;
  37300. this._addIndex = 4;
  37301. /**
  37302. * TODO
  37303. *
  37304. * @type {number}
  37305. * @default 0
  37306. */
  37307. this.cumulativeWeight = 0;
  37308. /**
  37309. * TODO
  37310. *
  37311. * @type {number}
  37312. * @default 0
  37313. */
  37314. this.cumulativeWeightAdditive = 0;
  37315. /**
  37316. * TODO
  37317. *
  37318. * @type {number}
  37319. * @default 0
  37320. */
  37321. this.useCount = 0;
  37322. /**
  37323. * TODO
  37324. *
  37325. * @type {number}
  37326. * @default 0
  37327. */
  37328. this.referenceCount = 0;
  37329. }
  37330. /**
  37331. * Accumulates data in the `incoming` region into `accu<i>`.
  37332. *
  37333. * @param {number} accuIndex - The accumulation index.
  37334. * @param {number} weight - The weight.
  37335. */
  37336. accumulate( accuIndex, weight ) {
  37337. // note: happily accumulating nothing when weight = 0, the caller knows
  37338. // the weight and shouldn't have made the call in the first place
  37339. const buffer = this.buffer,
  37340. stride = this.valueSize,
  37341. offset = accuIndex * stride + stride;
  37342. let currentWeight = this.cumulativeWeight;
  37343. if ( currentWeight === 0 ) {
  37344. // accuN := incoming * weight
  37345. for ( let i = 0; i !== stride; ++ i ) {
  37346. buffer[ offset + i ] = buffer[ i ];
  37347. }
  37348. currentWeight = weight;
  37349. } else {
  37350. // accuN := accuN + incoming * weight
  37351. currentWeight += weight;
  37352. const mix = weight / currentWeight;
  37353. this._mixBufferRegion( buffer, offset, 0, mix, stride );
  37354. }
  37355. this.cumulativeWeight = currentWeight;
  37356. }
  37357. /**
  37358. * Accumulates data in the `incoming` region into `add`.
  37359. *
  37360. * @param {number} weight - The weight.
  37361. */
  37362. accumulateAdditive( weight ) {
  37363. const buffer = this.buffer,
  37364. stride = this.valueSize,
  37365. offset = stride * this._addIndex;
  37366. if ( this.cumulativeWeightAdditive === 0 ) {
  37367. // add = identity
  37368. this._setIdentity();
  37369. }
  37370. // add := add + incoming * weight
  37371. this._mixBufferRegionAdditive( buffer, offset, 0, weight, stride );
  37372. this.cumulativeWeightAdditive += weight;
  37373. }
  37374. /**
  37375. * Applies the state of `accu<i>` to the binding when accus differ.
  37376. *
  37377. * @param {number} accuIndex - The accumulation index.
  37378. */
  37379. apply( accuIndex ) {
  37380. const stride = this.valueSize,
  37381. buffer = this.buffer,
  37382. offset = accuIndex * stride + stride,
  37383. weight = this.cumulativeWeight,
  37384. weightAdditive = this.cumulativeWeightAdditive,
  37385. binding = this.binding;
  37386. this.cumulativeWeight = 0;
  37387. this.cumulativeWeightAdditive = 0;
  37388. if ( weight < 1 ) {
  37389. // accuN := accuN + original * ( 1 - cumulativeWeight )
  37390. const originalValueOffset = stride * this._origIndex;
  37391. this._mixBufferRegion(
  37392. buffer, offset, originalValueOffset, 1 - weight, stride );
  37393. }
  37394. if ( weightAdditive > 0 ) {
  37395. // accuN := accuN + additive accuN
  37396. this._mixBufferRegionAdditive( buffer, offset, this._addIndex * stride, 1, stride );
  37397. }
  37398. for ( let i = stride, e = stride + stride; i !== e; ++ i ) {
  37399. if ( buffer[ i ] !== buffer[ i + stride ] ) {
  37400. // value has changed -> update scene graph
  37401. binding.setValue( buffer, offset );
  37402. break;
  37403. }
  37404. }
  37405. }
  37406. /**
  37407. * Remembers the state of the bound property and copy it to both accus.
  37408. */
  37409. saveOriginalState() {
  37410. const binding = this.binding;
  37411. const buffer = this.buffer,
  37412. stride = this.valueSize,
  37413. originalValueOffset = stride * this._origIndex;
  37414. binding.getValue( buffer, originalValueOffset );
  37415. // accu[0..1] := orig -- initially detect changes against the original
  37416. for ( let i = stride, e = originalValueOffset; i !== e; ++ i ) {
  37417. buffer[ i ] = buffer[ originalValueOffset + ( i % stride ) ];
  37418. }
  37419. // Add to identity for additive
  37420. this._setIdentity();
  37421. this.cumulativeWeight = 0;
  37422. this.cumulativeWeightAdditive = 0;
  37423. }
  37424. /**
  37425. * Applies the state previously taken via {@link PropertyMixer#saveOriginalState} to the binding.
  37426. */
  37427. restoreOriginalState() {
  37428. const originalValueOffset = this.valueSize * 3;
  37429. this.binding.setValue( this.buffer, originalValueOffset );
  37430. }
  37431. // internals
  37432. _setAdditiveIdentityNumeric() {
  37433. const startIndex = this._addIndex * this.valueSize;
  37434. const endIndex = startIndex + this.valueSize;
  37435. for ( let i = startIndex; i < endIndex; i ++ ) {
  37436. this.buffer[ i ] = 0;
  37437. }
  37438. }
  37439. _setAdditiveIdentityQuaternion() {
  37440. this._setAdditiveIdentityNumeric();
  37441. this.buffer[ this._addIndex * this.valueSize + 3 ] = 1;
  37442. }
  37443. _setAdditiveIdentityOther() {
  37444. const startIndex = this._origIndex * this.valueSize;
  37445. const targetIndex = this._addIndex * this.valueSize;
  37446. for ( let i = 0; i < this.valueSize; i ++ ) {
  37447. this.buffer[ targetIndex + i ] = this.buffer[ startIndex + i ];
  37448. }
  37449. }
  37450. // mix functions
  37451. _select( buffer, dstOffset, srcOffset, t, stride ) {
  37452. if ( t >= 0.5 ) {
  37453. for ( let i = 0; i !== stride; ++ i ) {
  37454. buffer[ dstOffset + i ] = buffer[ srcOffset + i ];
  37455. }
  37456. }
  37457. }
  37458. _slerp( buffer, dstOffset, srcOffset, t ) {
  37459. Quaternion.slerpFlat( buffer, dstOffset, buffer, dstOffset, buffer, srcOffset, t );
  37460. }
  37461. _slerpAdditive( buffer, dstOffset, srcOffset, t, stride ) {
  37462. const workOffset = this._workIndex * stride;
  37463. // Store result in intermediate buffer offset
  37464. Quaternion.multiplyQuaternionsFlat( buffer, workOffset, buffer, dstOffset, buffer, srcOffset );
  37465. // Slerp to the intermediate result
  37466. Quaternion.slerpFlat( buffer, dstOffset, buffer, dstOffset, buffer, workOffset, t );
  37467. }
  37468. _lerp( buffer, dstOffset, srcOffset, t, stride ) {
  37469. const s = 1 - t;
  37470. for ( let i = 0; i !== stride; ++ i ) {
  37471. const j = dstOffset + i;
  37472. buffer[ j ] = buffer[ j ] * s + buffer[ srcOffset + i ] * t;
  37473. }
  37474. }
  37475. _lerpAdditive( buffer, dstOffset, srcOffset, t, stride ) {
  37476. for ( let i = 0; i !== stride; ++ i ) {
  37477. const j = dstOffset + i;
  37478. buffer[ j ] = buffer[ j ] + buffer[ srcOffset + i ] * t;
  37479. }
  37480. }
  37481. }
  37482. // Characters [].:/ are reserved for track binding syntax.
  37483. const _RESERVED_CHARS_RE = '\\[\\]\\.:\\/';
  37484. const _reservedRe = new RegExp( '[' + _RESERVED_CHARS_RE + ']', 'g' );
  37485. // Attempts to allow node names from any language. ES5's `\w` regexp matches
  37486. // only latin characters, and the unicode \p{L} is not yet supported. So
  37487. // instead, we exclude reserved characters and match everything else.
  37488. const _wordChar = '[^' + _RESERVED_CHARS_RE + ']';
  37489. const _wordCharOrDot = '[^' + _RESERVED_CHARS_RE.replace( '\\.', '' ) + ']';
  37490. // Parent directories, delimited by '/' or ':'. Currently unused, but must
  37491. // be matched to parse the rest of the track name.
  37492. const _directoryRe = /*@__PURE__*/ /((?:WC+[\/:])*)/.source.replace( 'WC', _wordChar );
  37493. // Target node. May contain word characters (a-zA-Z0-9_) and '.' or '-'.
  37494. const _nodeRe = /*@__PURE__*/ /(WCOD+)?/.source.replace( 'WCOD', _wordCharOrDot );
  37495. // Object on target node, and accessor. May not contain reserved
  37496. // characters. Accessor may contain any character except closing bracket.
  37497. const _objectRe = /*@__PURE__*/ /(?:\.(WC+)(?:\[(.+)\])?)?/.source.replace( 'WC', _wordChar );
  37498. // Property and accessor. May not contain reserved characters. Accessor may
  37499. // contain any non-bracket characters.
  37500. const _propertyRe = /*@__PURE__*/ /\.(WC+)(?:\[(.+)\])?/.source.replace( 'WC', _wordChar );
  37501. const _trackRe = new RegExp( ''
  37502. + '^'
  37503. + _directoryRe
  37504. + _nodeRe
  37505. + _objectRe
  37506. + _propertyRe
  37507. + '$'
  37508. );
  37509. const _supportedObjectNames = [ 'material', 'materials', 'bones', 'map' ];
  37510. class Composite {
  37511. constructor( targetGroup, path, optionalParsedPath ) {
  37512. const parsedPath = optionalParsedPath || PropertyBinding.parseTrackName( path );
  37513. this._targetGroup = targetGroup;
  37514. this._bindings = targetGroup.subscribe_( path, parsedPath );
  37515. }
  37516. getValue( array, offset ) {
  37517. this.bind(); // bind all binding
  37518. const firstValidIndex = this._targetGroup.nCachedObjects_,
  37519. binding = this._bindings[ firstValidIndex ];
  37520. // and only call .getValue on the first
  37521. if ( binding !== undefined ) binding.getValue( array, offset );
  37522. }
  37523. setValue( array, offset ) {
  37524. const bindings = this._bindings;
  37525. for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  37526. bindings[ i ].setValue( array, offset );
  37527. }
  37528. }
  37529. bind() {
  37530. const bindings = this._bindings;
  37531. for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  37532. bindings[ i ].bind();
  37533. }
  37534. }
  37535. unbind() {
  37536. const bindings = this._bindings;
  37537. for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  37538. bindings[ i ].unbind();
  37539. }
  37540. }
  37541. }
  37542. // Note: This class uses a State pattern on a per-method basis:
  37543. // 'bind' sets 'this.getValue' / 'setValue' and shadows the
  37544. // prototype version of these methods with one that represents
  37545. // the bound state. When the property is not found, the methods
  37546. // become no-ops.
  37547. /**
  37548. * This holds a reference to a real property in the scene graph; used internally.
  37549. */
  37550. class PropertyBinding {
  37551. /**
  37552. * Constructs a new property binding.
  37553. *
  37554. * @param {Object} rootNode - The root node.
  37555. * @param {string} path - The path.
  37556. * @param {?Object} [parsedPath] - The parsed path.
  37557. */
  37558. constructor( rootNode, path, parsedPath ) {
  37559. /**
  37560. * The object path to the animated property.
  37561. *
  37562. * @type {string}
  37563. */
  37564. this.path = path;
  37565. /**
  37566. * An object holding information about the path.
  37567. *
  37568. * @type {Object}
  37569. */
  37570. this.parsedPath = parsedPath || PropertyBinding.parseTrackName( path );
  37571. /**
  37572. * The object owns the animated property.
  37573. *
  37574. * @type {?Object}
  37575. */
  37576. this.node = PropertyBinding.findNode( rootNode, this.parsedPath.nodeName );
  37577. /**
  37578. * The root node.
  37579. *
  37580. * @type {Object3D|Skeleton}
  37581. */
  37582. this.rootNode = rootNode;
  37583. // initial state of these methods that calls 'bind'
  37584. this.getValue = this._getValue_unbound;
  37585. this.setValue = this._setValue_unbound;
  37586. }
  37587. /**
  37588. * Factory method for creating a property binding from the given parameters.
  37589. *
  37590. * @static
  37591. * @param {Object} root - The root node.
  37592. * @param {string} path - The path.
  37593. * @param {?Object} [parsedPath] - The parsed path.
  37594. * @return {PropertyBinding|Composite} The created property binding or composite.
  37595. */
  37596. static create( root, path, parsedPath ) {
  37597. if ( ! ( root && root.isAnimationObjectGroup ) ) {
  37598. return new PropertyBinding( root, path, parsedPath );
  37599. } else {
  37600. return new PropertyBinding.Composite( root, path, parsedPath );
  37601. }
  37602. }
  37603. /**
  37604. * Replaces spaces with underscores and removes unsupported characters from
  37605. * node names, to ensure compatibility with parseTrackName().
  37606. *
  37607. * @param {string} name - Node name to be sanitized.
  37608. * @return {string} The sanitized node name.
  37609. */
  37610. static sanitizeNodeName( name ) {
  37611. return name.replace( /\s/g, '_' ).replace( _reservedRe, '' );
  37612. }
  37613. /**
  37614. * Parses the given track name (an object path to an animated property) and
  37615. * returns an object with information about the path. Matches strings in the following forms:
  37616. *
  37617. * - nodeName.property
  37618. * - nodeName.property[accessor]
  37619. * - nodeName.material.property[accessor]
  37620. * - uuid.property[accessor]
  37621. * - uuid.objectName[objectIndex].propertyName[propertyIndex]
  37622. * - parentName/nodeName.property
  37623. * - parentName/parentName/nodeName.property[index]
  37624. * - .bone[Armature.DEF_cog].position
  37625. * - scene:helium_balloon_model:helium_balloon_model.position
  37626. *
  37627. * @static
  37628. * @param {string} trackName - The track name to parse.
  37629. * @return {Object} The parsed track name as an object.
  37630. */
  37631. static parseTrackName( trackName ) {
  37632. const matches = _trackRe.exec( trackName );
  37633. if ( matches === null ) {
  37634. throw new Error( 'PropertyBinding: Cannot parse trackName: ' + trackName );
  37635. }
  37636. const results = {
  37637. // directoryName: matches[ 1 ], // (tschw) currently unused
  37638. nodeName: matches[ 2 ],
  37639. objectName: matches[ 3 ],
  37640. objectIndex: matches[ 4 ],
  37641. propertyName: matches[ 5 ], // required
  37642. propertyIndex: matches[ 6 ]
  37643. };
  37644. const lastDot = results.nodeName && results.nodeName.lastIndexOf( '.' );
  37645. if ( lastDot !== undefined && lastDot !== -1 ) {
  37646. const objectName = results.nodeName.substring( lastDot + 1 );
  37647. // Object names must be checked against an allowlist. Otherwise, there
  37648. // is no way to parse 'foo.bar.baz': 'baz' must be a property, but
  37649. // 'bar' could be the objectName, or part of a nodeName (which can
  37650. // include '.' characters).
  37651. if ( _supportedObjectNames.indexOf( objectName ) !== -1 ) {
  37652. results.nodeName = results.nodeName.substring( 0, lastDot );
  37653. results.objectName = objectName;
  37654. }
  37655. }
  37656. if ( results.propertyName === null || results.propertyName.length === 0 ) {
  37657. throw new Error( 'PropertyBinding: can not parse propertyName from trackName: ' + trackName );
  37658. }
  37659. return results;
  37660. }
  37661. /**
  37662. * Searches for a node in the hierarchy of the given root object by the given
  37663. * node name.
  37664. *
  37665. * @static
  37666. * @param {Object} root - The root object.
  37667. * @param {string|number} nodeName - The name of the node.
  37668. * @return {?Object} The found node. Returns `null` if no object was found.
  37669. */
  37670. static findNode( root, nodeName ) {
  37671. if ( nodeName === undefined || nodeName === '' || nodeName === '.' || nodeName === -1 || nodeName === root.name || nodeName === root.uuid ) {
  37672. return root;
  37673. }
  37674. // search into skeleton bones.
  37675. if ( root.skeleton ) {
  37676. const bone = root.skeleton.getBoneByName( nodeName );
  37677. if ( bone !== undefined ) {
  37678. return bone;
  37679. }
  37680. }
  37681. // search into node subtree.
  37682. if ( root.children ) {
  37683. const searchNodeSubtree = function ( children ) {
  37684. for ( let i = 0; i < children.length; i ++ ) {
  37685. const childNode = children[ i ];
  37686. if ( childNode.name === nodeName || childNode.uuid === nodeName ) {
  37687. return childNode;
  37688. }
  37689. const result = searchNodeSubtree( childNode.children );
  37690. if ( result ) return result;
  37691. }
  37692. return null;
  37693. };
  37694. const subTreeNode = searchNodeSubtree( root.children );
  37695. if ( subTreeNode ) {
  37696. return subTreeNode;
  37697. }
  37698. }
  37699. return null;
  37700. }
  37701. // these are used to "bind" a nonexistent property
  37702. _getValue_unavailable() {}
  37703. _setValue_unavailable() {}
  37704. // Getters
  37705. _getValue_direct( buffer, offset ) {
  37706. buffer[ offset ] = this.targetObject[ this.propertyName ];
  37707. }
  37708. _getValue_array( buffer, offset ) {
  37709. const source = this.resolvedProperty;
  37710. for ( let i = 0, n = source.length; i !== n; ++ i ) {
  37711. buffer[ offset ++ ] = source[ i ];
  37712. }
  37713. }
  37714. _getValue_arrayElement( buffer, offset ) {
  37715. buffer[ offset ] = this.resolvedProperty[ this.propertyIndex ];
  37716. }
  37717. _getValue_toArray( buffer, offset ) {
  37718. this.resolvedProperty.toArray( buffer, offset );
  37719. }
  37720. // Direct
  37721. _setValue_direct( buffer, offset ) {
  37722. this.targetObject[ this.propertyName ] = buffer[ offset ];
  37723. }
  37724. _setValue_direct_setNeedsUpdate( buffer, offset ) {
  37725. this.targetObject[ this.propertyName ] = buffer[ offset ];
  37726. this.targetObject.needsUpdate = true;
  37727. }
  37728. _setValue_direct_setMatrixWorldNeedsUpdate( buffer, offset ) {
  37729. this.targetObject[ this.propertyName ] = buffer[ offset ];
  37730. this.targetObject.matrixWorldNeedsUpdate = true;
  37731. }
  37732. // EntireArray
  37733. _setValue_array( buffer, offset ) {
  37734. const dest = this.resolvedProperty;
  37735. for ( let i = 0, n = dest.length; i !== n; ++ i ) {
  37736. dest[ i ] = buffer[ offset ++ ];
  37737. }
  37738. }
  37739. _setValue_array_setNeedsUpdate( buffer, offset ) {
  37740. const dest = this.resolvedProperty;
  37741. for ( let i = 0, n = dest.length; i !== n; ++ i ) {
  37742. dest[ i ] = buffer[ offset ++ ];
  37743. }
  37744. this.targetObject.needsUpdate = true;
  37745. }
  37746. _setValue_array_setMatrixWorldNeedsUpdate( buffer, offset ) {
  37747. const dest = this.resolvedProperty;
  37748. for ( let i = 0, n = dest.length; i !== n; ++ i ) {
  37749. dest[ i ] = buffer[ offset ++ ];
  37750. }
  37751. this.targetObject.matrixWorldNeedsUpdate = true;
  37752. }
  37753. // ArrayElement
  37754. _setValue_arrayElement( buffer, offset ) {
  37755. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  37756. }
  37757. _setValue_arrayElement_setNeedsUpdate( buffer, offset ) {
  37758. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  37759. this.targetObject.needsUpdate = true;
  37760. }
  37761. _setValue_arrayElement_setMatrixWorldNeedsUpdate( buffer, offset ) {
  37762. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  37763. this.targetObject.matrixWorldNeedsUpdate = true;
  37764. }
  37765. // HasToFromArray
  37766. _setValue_fromArray( buffer, offset ) {
  37767. this.resolvedProperty.fromArray( buffer, offset );
  37768. }
  37769. _setValue_fromArray_setNeedsUpdate( buffer, offset ) {
  37770. this.resolvedProperty.fromArray( buffer, offset );
  37771. this.targetObject.needsUpdate = true;
  37772. }
  37773. _setValue_fromArray_setMatrixWorldNeedsUpdate( buffer, offset ) {
  37774. this.resolvedProperty.fromArray( buffer, offset );
  37775. this.targetObject.matrixWorldNeedsUpdate = true;
  37776. }
  37777. _getValue_unbound( targetArray, offset ) {
  37778. this.bind();
  37779. this.getValue( targetArray, offset );
  37780. }
  37781. _setValue_unbound( sourceArray, offset ) {
  37782. this.bind();
  37783. this.setValue( sourceArray, offset );
  37784. }
  37785. /**
  37786. * Creates a getter / setter pair for the property tracked by this binding.
  37787. */
  37788. bind() {
  37789. let targetObject = this.node;
  37790. const parsedPath = this.parsedPath;
  37791. const objectName = parsedPath.objectName;
  37792. const propertyName = parsedPath.propertyName;
  37793. let propertyIndex = parsedPath.propertyIndex;
  37794. if ( ! targetObject ) {
  37795. targetObject = PropertyBinding.findNode( this.rootNode, parsedPath.nodeName );
  37796. this.node = targetObject;
  37797. }
  37798. // set fail state so we can just 'return' on error
  37799. this.getValue = this._getValue_unavailable;
  37800. this.setValue = this._setValue_unavailable;
  37801. // ensure there is a value node
  37802. if ( ! targetObject ) {
  37803. warn( 'PropertyBinding: No target node found for track: ' + this.path + '.' );
  37804. return;
  37805. }
  37806. if ( objectName ) {
  37807. let objectIndex = parsedPath.objectIndex;
  37808. // special cases were we need to reach deeper into the hierarchy to get the face materials....
  37809. switch ( objectName ) {
  37810. case 'materials':
  37811. if ( ! targetObject.material ) {
  37812. error( 'PropertyBinding: Can not bind to material as node does not have a material.', this );
  37813. return;
  37814. }
  37815. if ( ! targetObject.material.materials ) {
  37816. error( 'PropertyBinding: Can not bind to material.materials as node.material does not have a materials array.', this );
  37817. return;
  37818. }
  37819. targetObject = targetObject.material.materials;
  37820. break;
  37821. case 'bones':
  37822. if ( ! targetObject.skeleton ) {
  37823. error( 'PropertyBinding: Can not bind to bones as node does not have a skeleton.', this );
  37824. return;
  37825. }
  37826. // potential future optimization: skip this if propertyIndex is already an integer
  37827. // and convert the integer string to a true integer.
  37828. targetObject = targetObject.skeleton.bones;
  37829. // support resolving morphTarget names into indices.
  37830. for ( let i = 0; i < targetObject.length; i ++ ) {
  37831. if ( targetObject[ i ].name === objectIndex ) {
  37832. objectIndex = i;
  37833. break;
  37834. }
  37835. }
  37836. break;
  37837. case 'map':
  37838. if ( 'map' in targetObject ) {
  37839. targetObject = targetObject.map;
  37840. break;
  37841. }
  37842. if ( ! targetObject.material ) {
  37843. error( 'PropertyBinding: Can not bind to material as node does not have a material.', this );
  37844. return;
  37845. }
  37846. if ( ! targetObject.material.map ) {
  37847. error( 'PropertyBinding: Can not bind to material.map as node.material does not have a map.', this );
  37848. return;
  37849. }
  37850. targetObject = targetObject.material.map;
  37851. break;
  37852. default:
  37853. if ( targetObject[ objectName ] === undefined ) {
  37854. error( 'PropertyBinding: Can not bind to objectName of node undefined.', this );
  37855. return;
  37856. }
  37857. targetObject = targetObject[ objectName ];
  37858. }
  37859. if ( objectIndex !== undefined ) {
  37860. if ( targetObject[ objectIndex ] === undefined ) {
  37861. error( 'PropertyBinding: Trying to bind to objectIndex of objectName, but is undefined.', this, targetObject );
  37862. return;
  37863. }
  37864. targetObject = targetObject[ objectIndex ];
  37865. }
  37866. }
  37867. // resolve property
  37868. const nodeProperty = targetObject[ propertyName ];
  37869. if ( nodeProperty === undefined ) {
  37870. const nodeName = parsedPath.nodeName;
  37871. error( 'PropertyBinding: Trying to update property for track: ' + nodeName +
  37872. '.' + propertyName + ' but it wasn\'t found.', targetObject );
  37873. return;
  37874. }
  37875. // determine versioning scheme
  37876. let versioning = this.Versioning.None;
  37877. this.targetObject = targetObject;
  37878. if ( targetObject.isMaterial === true ) {
  37879. versioning = this.Versioning.NeedsUpdate;
  37880. } else if ( targetObject.isObject3D === true ) {
  37881. versioning = this.Versioning.MatrixWorldNeedsUpdate;
  37882. }
  37883. // determine how the property gets bound
  37884. let bindingType = this.BindingType.Direct;
  37885. if ( propertyIndex !== undefined ) {
  37886. // access a sub element of the property array (only primitives are supported right now)
  37887. if ( propertyName === 'morphTargetInfluences' ) {
  37888. // potential optimization, skip this if propertyIndex is already an integer, and convert the integer string to a true integer.
  37889. // support resolving morphTarget names into indices.
  37890. if ( ! targetObject.geometry ) {
  37891. error( 'PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.', this );
  37892. return;
  37893. }
  37894. if ( ! targetObject.geometry.morphAttributes ) {
  37895. error( 'PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.morphAttributes.', this );
  37896. return;
  37897. }
  37898. if ( targetObject.morphTargetDictionary[ propertyIndex ] !== undefined ) {
  37899. propertyIndex = targetObject.morphTargetDictionary[ propertyIndex ];
  37900. }
  37901. }
  37902. bindingType = this.BindingType.ArrayElement;
  37903. this.resolvedProperty = nodeProperty;
  37904. this.propertyIndex = propertyIndex;
  37905. } else if ( nodeProperty.fromArray !== undefined && nodeProperty.toArray !== undefined ) {
  37906. // must use copy for Object3D.Euler/Quaternion
  37907. bindingType = this.BindingType.HasFromToArray;
  37908. this.resolvedProperty = nodeProperty;
  37909. } else if ( Array.isArray( nodeProperty ) ) {
  37910. bindingType = this.BindingType.EntireArray;
  37911. this.resolvedProperty = nodeProperty;
  37912. } else {
  37913. this.propertyName = propertyName;
  37914. }
  37915. // select getter / setter
  37916. this.getValue = this.GetterByBindingType[ bindingType ];
  37917. this.setValue = this.SetterByBindingTypeAndVersioning[ bindingType ][ versioning ];
  37918. }
  37919. /**
  37920. * Unbinds the property.
  37921. */
  37922. unbind() {
  37923. this.node = null;
  37924. // back to the prototype version of getValue / setValue
  37925. // note: avoiding to mutate the shape of 'this' via 'delete'
  37926. this.getValue = this._getValue_unbound;
  37927. this.setValue = this._setValue_unbound;
  37928. }
  37929. }
  37930. PropertyBinding.Composite = Composite;
  37931. PropertyBinding.prototype.BindingType = {
  37932. Direct: 0,
  37933. EntireArray: 1,
  37934. ArrayElement: 2,
  37935. HasFromToArray: 3
  37936. };
  37937. PropertyBinding.prototype.Versioning = {
  37938. None: 0,
  37939. NeedsUpdate: 1,
  37940. MatrixWorldNeedsUpdate: 2
  37941. };
  37942. PropertyBinding.prototype.GetterByBindingType = [
  37943. PropertyBinding.prototype._getValue_direct,
  37944. PropertyBinding.prototype._getValue_array,
  37945. PropertyBinding.prototype._getValue_arrayElement,
  37946. PropertyBinding.prototype._getValue_toArray,
  37947. ];
  37948. PropertyBinding.prototype.SetterByBindingTypeAndVersioning = [
  37949. [
  37950. // Direct
  37951. PropertyBinding.prototype._setValue_direct,
  37952. PropertyBinding.prototype._setValue_direct_setNeedsUpdate,
  37953. PropertyBinding.prototype._setValue_direct_setMatrixWorldNeedsUpdate,
  37954. ], [
  37955. // EntireArray
  37956. PropertyBinding.prototype._setValue_array,
  37957. PropertyBinding.prototype._setValue_array_setNeedsUpdate,
  37958. PropertyBinding.prototype._setValue_array_setMatrixWorldNeedsUpdate,
  37959. ], [
  37960. // ArrayElement
  37961. PropertyBinding.prototype._setValue_arrayElement,
  37962. PropertyBinding.prototype._setValue_arrayElement_setNeedsUpdate,
  37963. PropertyBinding.prototype._setValue_arrayElement_setMatrixWorldNeedsUpdate,
  37964. ], [
  37965. // HasToFromArray
  37966. PropertyBinding.prototype._setValue_fromArray,
  37967. PropertyBinding.prototype._setValue_fromArray_setNeedsUpdate,
  37968. PropertyBinding.prototype._setValue_fromArray_setMatrixWorldNeedsUpdate,
  37969. ]
  37970. ];
  37971. /**
  37972. * A group of objects that receives a shared animation state.
  37973. *
  37974. * Usage:
  37975. *
  37976. * - Add objects you would otherwise pass as 'root' to the
  37977. * constructor or the .clipAction method of AnimationMixer.
  37978. * - Instead pass this object as 'root'.
  37979. * - You can also add and remove objects later when the mixer is running.
  37980. *
  37981. * Note:
  37982. *
  37983. * - Objects of this class appear as one object to the mixer,
  37984. * so cache control of the individual objects must be done on the group.
  37985. *
  37986. * Limitation:
  37987. *
  37988. * - The animated properties must be compatible among the all objects in the group.
  37989. * - A single property can either be controlled through a target group or directly, but not both.
  37990. */
  37991. class AnimationObjectGroup {
  37992. /**
  37993. * Constructs a new animation group.
  37994. *
  37995. * @param {...Object3D} arguments - An arbitrary number of 3D objects that share the same animation state.
  37996. */
  37997. constructor() {
  37998. /**
  37999. * This flag can be used for type testing.
  38000. *
  38001. * @type {boolean}
  38002. * @readonly
  38003. * @default true
  38004. */
  38005. this.isAnimationObjectGroup = true;
  38006. /**
  38007. * The UUID of the 3D object.
  38008. *
  38009. * @type {string}
  38010. * @readonly
  38011. */
  38012. this.uuid = generateUUID();
  38013. // cached objects followed by the active ones
  38014. this._objects = Array.prototype.slice.call( arguments );
  38015. this.nCachedObjects_ = 0; // threshold
  38016. // note: read by PropertyBinding.Composite
  38017. const indices = {};
  38018. this._indicesByUUID = indices; // for bookkeeping
  38019. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  38020. indices[ arguments[ i ].uuid ] = i;
  38021. }
  38022. this._paths = []; // inside: string
  38023. this._parsedPaths = []; // inside: { we don't care, here }
  38024. this._bindings = []; // inside: Array< PropertyBinding >
  38025. this._bindingsIndicesByPath = {}; // inside: indices in these arrays
  38026. const scope = this;
  38027. this.stats = {
  38028. objects: {
  38029. get total() {
  38030. return scope._objects.length;
  38031. },
  38032. get inUse() {
  38033. return this.total - scope.nCachedObjects_;
  38034. }
  38035. },
  38036. get bindingsPerObject() {
  38037. return scope._bindings.length;
  38038. }
  38039. };
  38040. }
  38041. /**
  38042. * Adds an arbitrary number of objects to this animation group.
  38043. *
  38044. * @param {...Object3D} arguments - The 3D objects to add.
  38045. */
  38046. add() {
  38047. const objects = this._objects,
  38048. indicesByUUID = this._indicesByUUID,
  38049. paths = this._paths,
  38050. parsedPaths = this._parsedPaths,
  38051. bindings = this._bindings,
  38052. nBindings = bindings.length;
  38053. let knownObject = undefined,
  38054. nObjects = objects.length,
  38055. nCachedObjects = this.nCachedObjects_;
  38056. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  38057. const object = arguments[ i ],
  38058. uuid = object.uuid;
  38059. let index = indicesByUUID[ uuid ];
  38060. if ( index === undefined ) {
  38061. // unknown object -> add it to the ACTIVE region
  38062. index = nObjects ++;
  38063. indicesByUUID[ uuid ] = index;
  38064. objects.push( object );
  38065. // accounting is done, now do the same for all bindings
  38066. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  38067. bindings[ j ].push( new PropertyBinding( object, paths[ j ], parsedPaths[ j ] ) );
  38068. }
  38069. } else if ( index < nCachedObjects ) {
  38070. knownObject = objects[ index ];
  38071. // move existing object to the ACTIVE region
  38072. const firstActiveIndex = -- nCachedObjects,
  38073. lastCachedObject = objects[ firstActiveIndex ];
  38074. indicesByUUID[ lastCachedObject.uuid ] = index;
  38075. objects[ index ] = lastCachedObject;
  38076. indicesByUUID[ uuid ] = firstActiveIndex;
  38077. objects[ firstActiveIndex ] = object;
  38078. // accounting is done, now do the same for all bindings
  38079. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  38080. const bindingsForPath = bindings[ j ],
  38081. lastCached = bindingsForPath[ firstActiveIndex ];
  38082. let binding = bindingsForPath[ index ];
  38083. bindingsForPath[ index ] = lastCached;
  38084. if ( binding === undefined ) {
  38085. // since we do not bother to create new bindings
  38086. // for objects that are cached, the binding may
  38087. // or may not exist
  38088. binding = new PropertyBinding( object, paths[ j ], parsedPaths[ j ] );
  38089. }
  38090. bindingsForPath[ firstActiveIndex ] = binding;
  38091. }
  38092. } else if ( objects[ index ] !== knownObject ) {
  38093. error( 'AnimationObjectGroup: Different objects with the same UUID ' +
  38094. 'detected. Clean the caches or recreate your infrastructure when reloading scenes.' );
  38095. } // else the object is already where we want it to be
  38096. } // for arguments
  38097. this.nCachedObjects_ = nCachedObjects;
  38098. }
  38099. /**
  38100. * Removes an arbitrary number of objects to this animation group
  38101. *
  38102. * @param {...Object3D} arguments - The 3D objects to remove.
  38103. */
  38104. remove() {
  38105. const objects = this._objects,
  38106. indicesByUUID = this._indicesByUUID,
  38107. bindings = this._bindings,
  38108. nBindings = bindings.length;
  38109. let nCachedObjects = this.nCachedObjects_;
  38110. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  38111. const object = arguments[ i ],
  38112. uuid = object.uuid,
  38113. index = indicesByUUID[ uuid ];
  38114. if ( index !== undefined && index >= nCachedObjects ) {
  38115. // move existing object into the CACHED region
  38116. const lastCachedIndex = nCachedObjects ++,
  38117. firstActiveObject = objects[ lastCachedIndex ];
  38118. indicesByUUID[ firstActiveObject.uuid ] = index;
  38119. objects[ index ] = firstActiveObject;
  38120. indicesByUUID[ uuid ] = lastCachedIndex;
  38121. objects[ lastCachedIndex ] = object;
  38122. // accounting is done, now do the same for all bindings
  38123. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  38124. const bindingsForPath = bindings[ j ],
  38125. firstActive = bindingsForPath[ lastCachedIndex ],
  38126. binding = bindingsForPath[ index ];
  38127. bindingsForPath[ index ] = firstActive;
  38128. bindingsForPath[ lastCachedIndex ] = binding;
  38129. }
  38130. }
  38131. } // for arguments
  38132. this.nCachedObjects_ = nCachedObjects;
  38133. }
  38134. /**
  38135. * Deallocates all memory resources for the passed 3D objects of this animation group.
  38136. *
  38137. * @param {...Object3D} arguments - The 3D objects to uncache.
  38138. */
  38139. uncache() {
  38140. const objects = this._objects,
  38141. indicesByUUID = this._indicesByUUID,
  38142. bindings = this._bindings,
  38143. nBindings = bindings.length;
  38144. let nCachedObjects = this.nCachedObjects_,
  38145. nObjects = objects.length;
  38146. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  38147. const object = arguments[ i ],
  38148. uuid = object.uuid,
  38149. index = indicesByUUID[ uuid ];
  38150. if ( index !== undefined ) {
  38151. delete indicesByUUID[ uuid ];
  38152. if ( index < nCachedObjects ) {
  38153. // object is cached, shrink the CACHED region
  38154. const firstActiveIndex = -- nCachedObjects,
  38155. lastCachedObject = objects[ firstActiveIndex ],
  38156. lastIndex = -- nObjects,
  38157. lastObject = objects[ lastIndex ];
  38158. // last cached object takes this object's place
  38159. indicesByUUID[ lastCachedObject.uuid ] = index;
  38160. objects[ index ] = lastCachedObject;
  38161. // last object goes to the activated slot and pop
  38162. indicesByUUID[ lastObject.uuid ] = firstActiveIndex;
  38163. objects[ firstActiveIndex ] = lastObject;
  38164. objects.pop();
  38165. // accounting is done, now do the same for all bindings
  38166. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  38167. const bindingsForPath = bindings[ j ],
  38168. lastCached = bindingsForPath[ firstActiveIndex ],
  38169. last = bindingsForPath[ lastIndex ];
  38170. bindingsForPath[ index ] = lastCached;
  38171. bindingsForPath[ firstActiveIndex ] = last;
  38172. bindingsForPath.pop();
  38173. }
  38174. } else {
  38175. // object is active, just swap with the last and pop
  38176. const lastIndex = -- nObjects,
  38177. lastObject = objects[ lastIndex ];
  38178. if ( lastIndex > 0 ) {
  38179. indicesByUUID[ lastObject.uuid ] = index;
  38180. }
  38181. objects[ index ] = lastObject;
  38182. objects.pop();
  38183. // accounting is done, now do the same for all bindings
  38184. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  38185. const bindingsForPath = bindings[ j ];
  38186. bindingsForPath[ index ] = bindingsForPath[ lastIndex ];
  38187. bindingsForPath.pop();
  38188. }
  38189. } // cached or active
  38190. } // if object is known
  38191. } // for arguments
  38192. this.nCachedObjects_ = nCachedObjects;
  38193. }
  38194. // Internal interface used by befriended PropertyBinding.Composite:
  38195. subscribe_( path, parsedPath ) {
  38196. // returns an array of bindings for the given path that is changed
  38197. // according to the contained objects in the group
  38198. const indicesByPath = this._bindingsIndicesByPath;
  38199. let index = indicesByPath[ path ];
  38200. const bindings = this._bindings;
  38201. if ( index !== undefined ) return bindings[ index ];
  38202. const paths = this._paths,
  38203. parsedPaths = this._parsedPaths,
  38204. objects = this._objects,
  38205. nObjects = objects.length,
  38206. nCachedObjects = this.nCachedObjects_,
  38207. bindingsForPath = new Array( nObjects );
  38208. index = bindings.length;
  38209. indicesByPath[ path ] = index;
  38210. paths.push( path );
  38211. parsedPaths.push( parsedPath );
  38212. bindings.push( bindingsForPath );
  38213. for ( let i = nCachedObjects, n = objects.length; i !== n; ++ i ) {
  38214. const object = objects[ i ];
  38215. bindingsForPath[ i ] = new PropertyBinding( object, path, parsedPath );
  38216. }
  38217. return bindingsForPath;
  38218. }
  38219. unsubscribe_( path ) {
  38220. // tells the group to forget about a property path and no longer
  38221. // update the array previously obtained with 'subscribe_'
  38222. const indicesByPath = this._bindingsIndicesByPath,
  38223. index = indicesByPath[ path ];
  38224. if ( index !== undefined ) {
  38225. const paths = this._paths,
  38226. parsedPaths = this._parsedPaths,
  38227. bindings = this._bindings,
  38228. lastBindingsIndex = bindings.length - 1,
  38229. lastBindings = bindings[ lastBindingsIndex ],
  38230. lastBindingsPath = path[ lastBindingsIndex ];
  38231. indicesByPath[ lastBindingsPath ] = index;
  38232. bindings[ index ] = lastBindings;
  38233. bindings.pop();
  38234. parsedPaths[ index ] = parsedPaths[ lastBindingsIndex ];
  38235. parsedPaths.pop();
  38236. paths[ index ] = paths[ lastBindingsIndex ];
  38237. paths.pop();
  38238. }
  38239. }
  38240. }
  38241. /**
  38242. * An instance of `AnimationAction` schedules the playback of an animation which is
  38243. * stored in {@link AnimationClip}.
  38244. */
  38245. class AnimationAction {
  38246. /**
  38247. * Constructs a new animation action.
  38248. *
  38249. * @param {AnimationMixer} mixer - The mixer that is controlled by this action.
  38250. * @param {AnimationClip} clip - The animation clip that holds the actual keyframes.
  38251. * @param {?Object3D} [localRoot=null] - The root object on which this action is performed.
  38252. * @param {(NormalAnimationBlendMode|AdditiveAnimationBlendMode)} [blendMode] - The blend mode.
  38253. */
  38254. constructor( mixer, clip, localRoot = null, blendMode = clip.blendMode ) {
  38255. this._mixer = mixer;
  38256. this._clip = clip;
  38257. this._localRoot = localRoot;
  38258. /**
  38259. * Defines how the animation is blended/combined when two or more animations
  38260. * are simultaneously played.
  38261. *
  38262. * @type {(NormalAnimationBlendMode|AdditiveAnimationBlendMode)}
  38263. */
  38264. this.blendMode = blendMode;
  38265. const tracks = clip.tracks,
  38266. nTracks = tracks.length,
  38267. interpolants = new Array( nTracks );
  38268. const interpolantSettings = {
  38269. endingStart: ZeroCurvatureEnding,
  38270. endingEnd: ZeroCurvatureEnding
  38271. };
  38272. for ( let i = 0; i !== nTracks; ++ i ) {
  38273. const interpolant = tracks[ i ].createInterpolant( null );
  38274. interpolants[ i ] = interpolant;
  38275. interpolant.settings = interpolantSettings;
  38276. }
  38277. this._interpolantSettings = interpolantSettings;
  38278. this._interpolants = interpolants; // bound by the mixer
  38279. // inside: PropertyMixer (managed by the mixer)
  38280. this._propertyBindings = new Array( nTracks );
  38281. this._cacheIndex = null; // for the memory manager
  38282. this._byClipCacheIndex = null; // for the memory manager
  38283. this._timeScaleInterpolant = null;
  38284. this._weightInterpolant = null;
  38285. /**
  38286. * The loop mode, set via {@link AnimationAction#setLoop}.
  38287. *
  38288. * @type {(LoopRepeat|LoopOnce|LoopPingPong)}
  38289. * @default LoopRepeat
  38290. */
  38291. this.loop = LoopRepeat;
  38292. this._loopCount = -1;
  38293. // global mixer time when the action is to be started
  38294. // it's set back to 'null' upon start of the action
  38295. this._startTime = null;
  38296. /**
  38297. * The local time of this action (in seconds, starting with `0`).
  38298. *
  38299. * The value gets clamped or wrapped to `[0,clip.duration]` (according to the
  38300. * loop state).
  38301. *
  38302. * @type {number}
  38303. * @default Infinity
  38304. */
  38305. this.time = 0;
  38306. /**
  38307. * Scaling factor for the {@link AnimationAction#time}. A value of `0` causes the
  38308. * animation to pause. Negative values cause the animation to play backwards.
  38309. *
  38310. * @type {number}
  38311. * @default 1
  38312. */
  38313. this.timeScale = 1;
  38314. this._effectiveTimeScale = 1;
  38315. /**
  38316. * The degree of influence of this action (in the interval `[0, 1]`). Values
  38317. * between `0` (no impact) and `1` (full impact) can be used to blend between
  38318. * several actions.
  38319. *
  38320. * @type {number}
  38321. * @default 1
  38322. */
  38323. this.weight = 1;
  38324. this._effectiveWeight = 1;
  38325. /**
  38326. * The number of repetitions of the performed clip over the course of this action.
  38327. * Can be set via {@link AnimationAction#setLoop}.
  38328. *
  38329. * Setting this number has no effect if {@link AnimationAction#loop} is set to
  38330. * `THREE:LoopOnce`.
  38331. *
  38332. * @type {number}
  38333. * @default Infinity
  38334. */
  38335. this.repetitions = Infinity;
  38336. /**
  38337. * If set to `true`, the playback of the action is paused.
  38338. *
  38339. * @type {boolean}
  38340. * @default false
  38341. */
  38342. this.paused = false;
  38343. /**
  38344. * If set to `false`, the action is disabled so it has no impact.
  38345. *
  38346. * When the action is re-enabled, the animation continues from its current
  38347. * time (setting `enabled` to `false` doesn't reset the action).
  38348. *
  38349. * @type {boolean}
  38350. * @default true
  38351. */
  38352. this.enabled = true;
  38353. /**
  38354. * If set to true the animation will automatically be paused on its last frame.
  38355. *
  38356. * If set to false, {@link AnimationAction#enabled} will automatically be switched
  38357. * to `false` when the last loop of the action has finished, so that this action has
  38358. * no further impact.
  38359. *
  38360. * Note: This member has no impact if the action is interrupted (it
  38361. * has only an effect if its last loop has really finished).
  38362. *
  38363. * @type {boolean}
  38364. * @default false
  38365. */
  38366. this.clampWhenFinished = false;
  38367. /**
  38368. * Enables smooth interpolation without separate clips for start, loop and end.
  38369. *
  38370. * @type {boolean}
  38371. * @default true
  38372. */
  38373. this.zeroSlopeAtStart = true;
  38374. /**
  38375. * Enables smooth interpolation without separate clips for start, loop and end.
  38376. *
  38377. * @type {boolean}
  38378. * @default true
  38379. */
  38380. this.zeroSlopeAtEnd = true;
  38381. }
  38382. /**
  38383. * Starts the playback of the animation.
  38384. *
  38385. * @return {AnimationAction} A reference to this animation action.
  38386. */
  38387. play() {
  38388. this._mixer._activateAction( this );
  38389. return this;
  38390. }
  38391. /**
  38392. * Stops the playback of the animation.
  38393. *
  38394. * @return {AnimationAction} A reference to this animation action.
  38395. */
  38396. stop() {
  38397. this._mixer._deactivateAction( this );
  38398. return this.reset();
  38399. }
  38400. /**
  38401. * Resets the playback of the animation.
  38402. *
  38403. * @return {AnimationAction} A reference to this animation action.
  38404. */
  38405. reset() {
  38406. this.paused = false;
  38407. this.enabled = true;
  38408. this.time = 0; // restart clip
  38409. this._loopCount = -1;// forget previous loops
  38410. this._startTime = null;// forget scheduling
  38411. return this.stopFading().stopWarping();
  38412. }
  38413. /**
  38414. * Returns `true` if the animation is running.
  38415. *
  38416. * @return {boolean} Whether the animation is running or not.
  38417. */
  38418. isRunning() {
  38419. return this.enabled && ! this.paused && this.timeScale !== 0 &&
  38420. this._startTime === null && this._mixer._isActiveAction( this );
  38421. }
  38422. /**
  38423. * Returns `true` when {@link AnimationAction#play} has been called.
  38424. *
  38425. * @return {boolean} Whether the animation is scheduled or not.
  38426. */
  38427. isScheduled() {
  38428. return this._mixer._isActiveAction( this );
  38429. }
  38430. /**
  38431. * Defines the time when the animation should start.
  38432. *
  38433. * @param {number} time - The start time in seconds.
  38434. * @return {AnimationAction} A reference to this animation action.
  38435. */
  38436. startAt( time ) {
  38437. this._startTime = time;
  38438. return this;
  38439. }
  38440. /**
  38441. * Configures the loop settings for this action.
  38442. *
  38443. * @param {(LoopRepeat|LoopOnce|LoopPingPong)} mode - The loop mode.
  38444. * @param {number} repetitions - The number of repetitions.
  38445. * @return {AnimationAction} A reference to this animation action.
  38446. */
  38447. setLoop( mode, repetitions ) {
  38448. this.loop = mode;
  38449. this.repetitions = repetitions;
  38450. return this;
  38451. }
  38452. /**
  38453. * Sets the effective weight of this action.
  38454. *
  38455. * An action has no effect and thus an effective weight of zero when the
  38456. * action is disabled.
  38457. *
  38458. * @param {number} weight - The weight to set.
  38459. * @return {AnimationAction} A reference to this animation action.
  38460. */
  38461. setEffectiveWeight( weight ) {
  38462. this.weight = weight;
  38463. // note: same logic as when updated at runtime
  38464. this._effectiveWeight = this.enabled ? weight : 0;
  38465. return this.stopFading();
  38466. }
  38467. /**
  38468. * Returns the effective weight of this action.
  38469. *
  38470. * @return {number} The effective weight.
  38471. */
  38472. getEffectiveWeight() {
  38473. return this._effectiveWeight;
  38474. }
  38475. /**
  38476. * Fades the animation in by increasing its weight gradually from `0` to `1`,
  38477. * within the passed time interval.
  38478. *
  38479. * @param {number} duration - The duration of the fade.
  38480. * @return {AnimationAction} A reference to this animation action.
  38481. */
  38482. fadeIn( duration ) {
  38483. return this._scheduleFading( duration, 0, 1 );
  38484. }
  38485. /**
  38486. * Fades the animation out by decreasing its weight gradually from `1` to `0`,
  38487. * within the passed time interval.
  38488. *
  38489. * @param {number} duration - The duration of the fade.
  38490. * @return {AnimationAction} A reference to this animation action.
  38491. */
  38492. fadeOut( duration ) {
  38493. return this._scheduleFading( duration, 1, 0 );
  38494. }
  38495. /**
  38496. * Causes this action to fade in and the given action to fade out,
  38497. * within the passed time interval.
  38498. *
  38499. * @param {AnimationAction} fadeOutAction - The animation action to fade out.
  38500. * @param {number} duration - The duration of the fade.
  38501. * @param {boolean} [warp=false] - Whether warping should be used or not.
  38502. * @return {AnimationAction} A reference to this animation action.
  38503. */
  38504. crossFadeFrom( fadeOutAction, duration, warp = false ) {
  38505. fadeOutAction.fadeOut( duration );
  38506. this.fadeIn( duration );
  38507. if ( warp === true ) {
  38508. const fadeInDuration = this._clip.duration,
  38509. fadeOutDuration = fadeOutAction._clip.duration,
  38510. startEndRatio = fadeOutDuration / fadeInDuration,
  38511. endStartRatio = fadeInDuration / fadeOutDuration;
  38512. fadeOutAction.warp( 1.0, startEndRatio, duration );
  38513. this.warp( endStartRatio, 1.0, duration );
  38514. }
  38515. return this;
  38516. }
  38517. /**
  38518. * Causes this action to fade out and the given action to fade in,
  38519. * within the passed time interval.
  38520. *
  38521. * @param {AnimationAction} fadeInAction - The animation action to fade in.
  38522. * @param {number} duration - The duration of the fade.
  38523. * @param {boolean} [warp=false] - Whether warping should be used or not.
  38524. * @return {AnimationAction} A reference to this animation action.
  38525. */
  38526. crossFadeTo( fadeInAction, duration, warp = false ) {
  38527. return fadeInAction.crossFadeFrom( this, duration, warp );
  38528. }
  38529. /**
  38530. * Stops any fading which is applied to this action.
  38531. *
  38532. * @return {AnimationAction} A reference to this animation action.
  38533. */
  38534. stopFading() {
  38535. const weightInterpolant = this._weightInterpolant;
  38536. if ( weightInterpolant !== null ) {
  38537. this._weightInterpolant = null;
  38538. this._mixer._takeBackControlInterpolant( weightInterpolant );
  38539. }
  38540. return this;
  38541. }
  38542. /**
  38543. * Sets the effective time scale of this action.
  38544. *
  38545. * An action has no effect and thus an effective time scale of zero when the
  38546. * action is paused.
  38547. *
  38548. * @param {number} timeScale - The time scale to set.
  38549. * @return {AnimationAction} A reference to this animation action.
  38550. */
  38551. setEffectiveTimeScale( timeScale ) {
  38552. this.timeScale = timeScale;
  38553. this._effectiveTimeScale = this.paused ? 0 : timeScale;
  38554. return this.stopWarping();
  38555. }
  38556. /**
  38557. * Returns the effective time scale of this action.
  38558. *
  38559. * @return {number} The effective time scale.
  38560. */
  38561. getEffectiveTimeScale() {
  38562. return this._effectiveTimeScale;
  38563. }
  38564. /**
  38565. * Sets the duration for a single loop of this action.
  38566. *
  38567. * @param {number} duration - The duration to set.
  38568. * @return {AnimationAction} A reference to this animation action.
  38569. */
  38570. setDuration( duration ) {
  38571. this.timeScale = this._clip.duration / duration;
  38572. return this.stopWarping();
  38573. }
  38574. /**
  38575. * Synchronizes this action with the passed other action.
  38576. *
  38577. * @param {AnimationAction} action - The action to sync with.
  38578. * @return {AnimationAction} A reference to this animation action.
  38579. */
  38580. syncWith( action ) {
  38581. this.time = action.time;
  38582. this.timeScale = action.timeScale;
  38583. return this.stopWarping();
  38584. }
  38585. /**
  38586. * Decelerates this animation's speed to `0` within the passed time interval.
  38587. *
  38588. * @param {number} duration - The duration.
  38589. * @return {AnimationAction} A reference to this animation action.
  38590. */
  38591. halt( duration ) {
  38592. return this.warp( this._effectiveTimeScale, 0, duration );
  38593. }
  38594. /**
  38595. * Changes the playback speed, within the passed time interval, by modifying
  38596. * {@link AnimationAction#timeScale} gradually from `startTimeScale` to
  38597. * `endTimeScale`.
  38598. *
  38599. * @param {number} startTimeScale - The start time scale.
  38600. * @param {number} endTimeScale - The end time scale.
  38601. * @param {number} duration - The duration.
  38602. * @return {AnimationAction} A reference to this animation action.
  38603. */
  38604. warp( startTimeScale, endTimeScale, duration ) {
  38605. const mixer = this._mixer,
  38606. now = mixer.time,
  38607. timeScale = this.timeScale;
  38608. let interpolant = this._timeScaleInterpolant;
  38609. if ( interpolant === null ) {
  38610. interpolant = mixer._lendControlInterpolant();
  38611. this._timeScaleInterpolant = interpolant;
  38612. }
  38613. const times = interpolant.parameterPositions,
  38614. values = interpolant.sampleValues;
  38615. times[ 0 ] = now;
  38616. times[ 1 ] = now + duration;
  38617. values[ 0 ] = startTimeScale / timeScale;
  38618. values[ 1 ] = endTimeScale / timeScale;
  38619. return this;
  38620. }
  38621. /**
  38622. * Stops any scheduled warping which is applied to this action.
  38623. *
  38624. * @return {AnimationAction} A reference to this animation action.
  38625. */
  38626. stopWarping() {
  38627. const timeScaleInterpolant = this._timeScaleInterpolant;
  38628. if ( timeScaleInterpolant !== null ) {
  38629. this._timeScaleInterpolant = null;
  38630. this._mixer._takeBackControlInterpolant( timeScaleInterpolant );
  38631. }
  38632. return this;
  38633. }
  38634. /**
  38635. * Returns the animation mixer of this animation action.
  38636. *
  38637. * @return {AnimationMixer} The animation mixer.
  38638. */
  38639. getMixer() {
  38640. return this._mixer;
  38641. }
  38642. /**
  38643. * Returns the animation clip of this animation action.
  38644. *
  38645. * @return {AnimationClip} The animation clip.
  38646. */
  38647. getClip() {
  38648. return this._clip;
  38649. }
  38650. /**
  38651. * Returns the root object of this animation action.
  38652. *
  38653. * @return {Object3D} The root object.
  38654. */
  38655. getRoot() {
  38656. return this._localRoot || this._mixer._root;
  38657. }
  38658. // Interna
  38659. _update( time, deltaTime, timeDirection, accuIndex ) {
  38660. // called by the mixer
  38661. if ( ! this.enabled ) {
  38662. // call ._updateWeight() to update ._effectiveWeight
  38663. this._updateWeight( time );
  38664. return;
  38665. }
  38666. const startTime = this._startTime;
  38667. if ( startTime !== null ) {
  38668. // check for scheduled start of action
  38669. const timeRunning = ( time - startTime ) * timeDirection;
  38670. if ( timeRunning < 0 || timeDirection === 0 ) {
  38671. deltaTime = 0;
  38672. } else {
  38673. this._startTime = null; // unschedule
  38674. deltaTime = timeDirection * timeRunning;
  38675. }
  38676. }
  38677. // apply time scale and advance time
  38678. deltaTime *= this._updateTimeScale( time );
  38679. const clipTime = this._updateTime( deltaTime );
  38680. // note: _updateTime may disable the action resulting in
  38681. // an effective weight of 0
  38682. const weight = this._updateWeight( time );
  38683. if ( weight > 0 ) {
  38684. const interpolants = this._interpolants;
  38685. const propertyMixers = this._propertyBindings;
  38686. switch ( this.blendMode ) {
  38687. case AdditiveAnimationBlendMode:
  38688. for ( let j = 0, m = interpolants.length; j !== m; ++ j ) {
  38689. interpolants[ j ].evaluate( clipTime );
  38690. propertyMixers[ j ].accumulateAdditive( weight );
  38691. }
  38692. break;
  38693. case NormalAnimationBlendMode:
  38694. default:
  38695. for ( let j = 0, m = interpolants.length; j !== m; ++ j ) {
  38696. interpolants[ j ].evaluate( clipTime );
  38697. propertyMixers[ j ].accumulate( accuIndex, weight );
  38698. }
  38699. }
  38700. }
  38701. }
  38702. _updateWeight( time ) {
  38703. let weight = 0;
  38704. if ( this.enabled ) {
  38705. weight = this.weight;
  38706. const interpolant = this._weightInterpolant;
  38707. if ( interpolant !== null ) {
  38708. const interpolantValue = interpolant.evaluate( time )[ 0 ];
  38709. weight *= interpolantValue;
  38710. if ( time > interpolant.parameterPositions[ 1 ] ) {
  38711. this.stopFading();
  38712. if ( interpolantValue === 0 ) {
  38713. // faded out, disable
  38714. this.enabled = false;
  38715. }
  38716. }
  38717. }
  38718. }
  38719. this._effectiveWeight = weight;
  38720. return weight;
  38721. }
  38722. _updateTimeScale( time ) {
  38723. let timeScale = 0;
  38724. if ( ! this.paused ) {
  38725. timeScale = this.timeScale;
  38726. const interpolant = this._timeScaleInterpolant;
  38727. if ( interpolant !== null ) {
  38728. const interpolantValue = interpolant.evaluate( time )[ 0 ];
  38729. timeScale *= interpolantValue;
  38730. if ( time > interpolant.parameterPositions[ 1 ] ) {
  38731. this.stopWarping();
  38732. if ( timeScale === 0 ) {
  38733. // motion has halted, pause
  38734. this.paused = true;
  38735. } else {
  38736. // warp done - apply final time scale
  38737. this.timeScale = timeScale;
  38738. }
  38739. }
  38740. }
  38741. }
  38742. this._effectiveTimeScale = timeScale;
  38743. return timeScale;
  38744. }
  38745. _updateTime( deltaTime ) {
  38746. const duration = this._clip.duration;
  38747. const loop = this.loop;
  38748. let time = this.time + deltaTime;
  38749. let loopCount = this._loopCount;
  38750. const pingPong = ( loop === LoopPingPong );
  38751. if ( deltaTime === 0 ) {
  38752. if ( loopCount === -1 ) return time;
  38753. return ( pingPong && ( loopCount & 1 ) === 1 ) ? duration - time : time;
  38754. }
  38755. if ( loop === LoopOnce ) {
  38756. if ( loopCount === -1 ) {
  38757. // just started
  38758. this._loopCount = 0;
  38759. this._setEndings( true, true, false );
  38760. }
  38761. handle_stop: {
  38762. if ( time >= duration ) {
  38763. time = duration;
  38764. } else if ( time < 0 ) {
  38765. time = 0;
  38766. } else {
  38767. this.time = time;
  38768. break handle_stop;
  38769. }
  38770. if ( this.clampWhenFinished ) this.paused = true;
  38771. else this.enabled = false;
  38772. this.time = time;
  38773. this._mixer.dispatchEvent( {
  38774. type: 'finished', action: this,
  38775. direction: deltaTime < 0 ? -1 : 1
  38776. } );
  38777. }
  38778. } else { // repetitive Repeat or PingPong
  38779. if ( loopCount === -1 ) {
  38780. // just started
  38781. if ( deltaTime >= 0 ) {
  38782. loopCount = 0;
  38783. this._setEndings( true, this.repetitions === 0, pingPong );
  38784. } else {
  38785. // when looping in reverse direction, the initial
  38786. // transition through zero counts as a repetition,
  38787. // so leave loopCount at -1
  38788. this._setEndings( this.repetitions === 0, true, pingPong );
  38789. }
  38790. }
  38791. if ( time >= duration || time < 0 ) {
  38792. // wrap around
  38793. const loopDelta = Math.floor( time / duration ); // signed
  38794. time -= duration * loopDelta;
  38795. loopCount += Math.abs( loopDelta );
  38796. const pending = this.repetitions - loopCount;
  38797. if ( pending <= 0 ) {
  38798. // have to stop (switch state, clamp time, fire event)
  38799. if ( this.clampWhenFinished ) this.paused = true;
  38800. else this.enabled = false;
  38801. time = deltaTime > 0 ? duration : 0;
  38802. this.time = time;
  38803. this._mixer.dispatchEvent( {
  38804. type: 'finished', action: this,
  38805. direction: deltaTime > 0 ? 1 : -1
  38806. } );
  38807. } else {
  38808. // keep running
  38809. if ( pending === 1 ) {
  38810. // entering the last round
  38811. const atStart = deltaTime < 0;
  38812. this._setEndings( atStart, ! atStart, pingPong );
  38813. } else {
  38814. this._setEndings( false, false, pingPong );
  38815. }
  38816. this._loopCount = loopCount;
  38817. this.time = time;
  38818. this._mixer.dispatchEvent( {
  38819. type: 'loop', action: this, loopDelta: loopDelta
  38820. } );
  38821. }
  38822. } else {
  38823. this.time = time;
  38824. }
  38825. if ( pingPong && ( loopCount & 1 ) === 1 ) {
  38826. // invert time for the "pong round"
  38827. return duration - time;
  38828. }
  38829. }
  38830. return time;
  38831. }
  38832. _setEndings( atStart, atEnd, pingPong ) {
  38833. const settings = this._interpolantSettings;
  38834. if ( pingPong ) {
  38835. settings.endingStart = ZeroSlopeEnding;
  38836. settings.endingEnd = ZeroSlopeEnding;
  38837. } else {
  38838. // assuming for LoopOnce atStart == atEnd == true
  38839. if ( atStart ) {
  38840. settings.endingStart = this.zeroSlopeAtStart ? ZeroSlopeEnding : ZeroCurvatureEnding;
  38841. } else {
  38842. settings.endingStart = WrapAroundEnding;
  38843. }
  38844. if ( atEnd ) {
  38845. settings.endingEnd = this.zeroSlopeAtEnd ? ZeroSlopeEnding : ZeroCurvatureEnding;
  38846. } else {
  38847. settings.endingEnd = WrapAroundEnding;
  38848. }
  38849. }
  38850. }
  38851. _scheduleFading( duration, weightNow, weightThen ) {
  38852. const mixer = this._mixer, now = mixer.time;
  38853. let interpolant = this._weightInterpolant;
  38854. if ( interpolant === null ) {
  38855. interpolant = mixer._lendControlInterpolant();
  38856. this._weightInterpolant = interpolant;
  38857. }
  38858. const times = interpolant.parameterPositions,
  38859. values = interpolant.sampleValues;
  38860. times[ 0 ] = now;
  38861. values[ 0 ] = weightNow;
  38862. times[ 1 ] = now + duration;
  38863. values[ 1 ] = weightThen;
  38864. return this;
  38865. }
  38866. }
  38867. const _controlInterpolantsResultBuffer = new Float32Array( 1 );
  38868. /**
  38869. * `AnimationMixer` is a player for animations on a particular object in
  38870. * the scene. When multiple objects in the scene are animated independently,
  38871. * one `AnimationMixer` may be used for each object.
  38872. */
  38873. class AnimationMixer extends EventDispatcher {
  38874. /**
  38875. * Constructs a new animation mixer.
  38876. *
  38877. * @param {Object3D} root - The object whose animations shall be played by this mixer.
  38878. */
  38879. constructor( root ) {
  38880. super();
  38881. this._root = root;
  38882. this._initMemoryManager();
  38883. this._accuIndex = 0;
  38884. /**
  38885. * The global mixer time (in seconds; starting with `0` on the mixer's creation).
  38886. *
  38887. * @type {number}
  38888. * @default 0
  38889. */
  38890. this.time = 0;
  38891. /**
  38892. * A scaling factor for the global time.
  38893. *
  38894. * Note: Setting this member to `0` and later back to `1` is a
  38895. * possibility to pause/unpause all actions that are controlled by this
  38896. * mixer.
  38897. *
  38898. * @type {number}
  38899. * @default 1
  38900. */
  38901. this.timeScale = 1.0;
  38902. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  38903. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'observe', { detail: this } ) );
  38904. }
  38905. }
  38906. _bindAction( action, prototypeAction ) {
  38907. const root = action._localRoot || this._root,
  38908. tracks = action._clip.tracks,
  38909. nTracks = tracks.length,
  38910. bindings = action._propertyBindings,
  38911. interpolants = action._interpolants,
  38912. rootUuid = root.uuid,
  38913. bindingsByRoot = this._bindingsByRootAndName;
  38914. let bindingsByName = bindingsByRoot[ rootUuid ];
  38915. if ( bindingsByName === undefined ) {
  38916. bindingsByName = {};
  38917. bindingsByRoot[ rootUuid ] = bindingsByName;
  38918. }
  38919. for ( let i = 0; i !== nTracks; ++ i ) {
  38920. const track = tracks[ i ],
  38921. trackName = track.name;
  38922. let binding = bindingsByName[ trackName ];
  38923. if ( binding !== undefined ) {
  38924. ++ binding.referenceCount;
  38925. bindings[ i ] = binding;
  38926. } else {
  38927. binding = bindings[ i ];
  38928. if ( binding !== undefined ) {
  38929. // existing binding, make sure the cache knows
  38930. if ( binding._cacheIndex === null ) {
  38931. ++ binding.referenceCount;
  38932. this._addInactiveBinding( binding, rootUuid, trackName );
  38933. }
  38934. continue;
  38935. }
  38936. const path = prototypeAction && prototypeAction.
  38937. _propertyBindings[ i ].binding.parsedPath;
  38938. binding = new PropertyMixer(
  38939. PropertyBinding.create( root, trackName, path ),
  38940. track.ValueTypeName, track.getValueSize() );
  38941. ++ binding.referenceCount;
  38942. this._addInactiveBinding( binding, rootUuid, trackName );
  38943. bindings[ i ] = binding;
  38944. }
  38945. interpolants[ i ].resultBuffer = binding.buffer;
  38946. }
  38947. }
  38948. _activateAction( action ) {
  38949. if ( ! this._isActiveAction( action ) ) {
  38950. if ( action._cacheIndex === null ) {
  38951. // this action has been forgotten by the cache, but the user
  38952. // appears to be still using it -> rebind
  38953. const rootUuid = ( action._localRoot || this._root ).uuid,
  38954. clipUuid = action._clip.uuid,
  38955. actionsForClip = this._actionsByClip[ clipUuid ];
  38956. this._bindAction( action,
  38957. actionsForClip && actionsForClip.knownActions[ 0 ] );
  38958. this._addInactiveAction( action, clipUuid, rootUuid );
  38959. }
  38960. const bindings = action._propertyBindings;
  38961. // increment reference counts / sort out state
  38962. for ( let i = 0, n = bindings.length; i !== n; ++ i ) {
  38963. const binding = bindings[ i ];
  38964. if ( binding.useCount ++ === 0 ) {
  38965. this._lendBinding( binding );
  38966. binding.saveOriginalState();
  38967. }
  38968. }
  38969. this._lendAction( action );
  38970. }
  38971. }
  38972. _deactivateAction( action ) {
  38973. if ( this._isActiveAction( action ) ) {
  38974. const bindings = action._propertyBindings;
  38975. // decrement reference counts / sort out state
  38976. for ( let i = 0, n = bindings.length; i !== n; ++ i ) {
  38977. const binding = bindings[ i ];
  38978. if ( -- binding.useCount === 0 ) {
  38979. binding.restoreOriginalState();
  38980. this._takeBackBinding( binding );
  38981. }
  38982. }
  38983. this._takeBackAction( action );
  38984. }
  38985. }
  38986. // Memory manager
  38987. _initMemoryManager() {
  38988. this._actions = []; // 'nActiveActions' followed by inactive ones
  38989. this._nActiveActions = 0;
  38990. this._actionsByClip = {};
  38991. // inside:
  38992. // {
  38993. // knownActions: Array< AnimationAction > - used as prototypes
  38994. // actionByRoot: AnimationAction - lookup
  38995. // }
  38996. this._bindings = []; // 'nActiveBindings' followed by inactive ones
  38997. this._nActiveBindings = 0;
  38998. this._bindingsByRootAndName = {}; // inside: Map< name, PropertyMixer >
  38999. this._controlInterpolants = []; // same game as above
  39000. this._nActiveControlInterpolants = 0;
  39001. const scope = this;
  39002. this.stats = {
  39003. actions: {
  39004. get total() {
  39005. return scope._actions.length;
  39006. },
  39007. get inUse() {
  39008. return scope._nActiveActions;
  39009. }
  39010. },
  39011. bindings: {
  39012. get total() {
  39013. return scope._bindings.length;
  39014. },
  39015. get inUse() {
  39016. return scope._nActiveBindings;
  39017. }
  39018. },
  39019. controlInterpolants: {
  39020. get total() {
  39021. return scope._controlInterpolants.length;
  39022. },
  39023. get inUse() {
  39024. return scope._nActiveControlInterpolants;
  39025. }
  39026. }
  39027. };
  39028. }
  39029. // Memory management for AnimationAction objects
  39030. _isActiveAction( action ) {
  39031. const index = action._cacheIndex;
  39032. return index !== null && index < this._nActiveActions;
  39033. }
  39034. _addInactiveAction( action, clipUuid, rootUuid ) {
  39035. const actions = this._actions,
  39036. actionsByClip = this._actionsByClip;
  39037. let actionsForClip = actionsByClip[ clipUuid ];
  39038. if ( actionsForClip === undefined ) {
  39039. actionsForClip = {
  39040. knownActions: [ action ],
  39041. actionByRoot: {}
  39042. };
  39043. action._byClipCacheIndex = 0;
  39044. actionsByClip[ clipUuid ] = actionsForClip;
  39045. } else {
  39046. const knownActions = actionsForClip.knownActions;
  39047. action._byClipCacheIndex = knownActions.length;
  39048. knownActions.push( action );
  39049. }
  39050. action._cacheIndex = actions.length;
  39051. actions.push( action );
  39052. actionsForClip.actionByRoot[ rootUuid ] = action;
  39053. }
  39054. _removeInactiveAction( action ) {
  39055. const actions = this._actions,
  39056. lastInactiveAction = actions[ actions.length - 1 ],
  39057. cacheIndex = action._cacheIndex;
  39058. lastInactiveAction._cacheIndex = cacheIndex;
  39059. actions[ cacheIndex ] = lastInactiveAction;
  39060. actions.pop();
  39061. action._cacheIndex = null;
  39062. const clipUuid = action._clip.uuid,
  39063. actionsByClip = this._actionsByClip,
  39064. actionsForClip = actionsByClip[ clipUuid ],
  39065. knownActionsForClip = actionsForClip.knownActions,
  39066. lastKnownAction =
  39067. knownActionsForClip[ knownActionsForClip.length - 1 ],
  39068. byClipCacheIndex = action._byClipCacheIndex;
  39069. lastKnownAction._byClipCacheIndex = byClipCacheIndex;
  39070. knownActionsForClip[ byClipCacheIndex ] = lastKnownAction;
  39071. knownActionsForClip.pop();
  39072. action._byClipCacheIndex = null;
  39073. const actionByRoot = actionsForClip.actionByRoot,
  39074. rootUuid = ( action._localRoot || this._root ).uuid;
  39075. delete actionByRoot[ rootUuid ];
  39076. if ( knownActionsForClip.length === 0 ) {
  39077. delete actionsByClip[ clipUuid ];
  39078. }
  39079. this._removeInactiveBindingsForAction( action );
  39080. }
  39081. _removeInactiveBindingsForAction( action ) {
  39082. const bindings = action._propertyBindings;
  39083. for ( let i = 0, n = bindings.length; i !== n; ++ i ) {
  39084. const binding = bindings[ i ];
  39085. if ( -- binding.referenceCount === 0 ) {
  39086. this._removeInactiveBinding( binding );
  39087. }
  39088. }
  39089. }
  39090. _lendAction( action ) {
  39091. // [ active actions | inactive actions ]
  39092. // [ active actions >| inactive actions ]
  39093. // s a
  39094. // <-swap->
  39095. // a s
  39096. const actions = this._actions,
  39097. prevIndex = action._cacheIndex,
  39098. lastActiveIndex = this._nActiveActions ++,
  39099. firstInactiveAction = actions[ lastActiveIndex ];
  39100. action._cacheIndex = lastActiveIndex;
  39101. actions[ lastActiveIndex ] = action;
  39102. firstInactiveAction._cacheIndex = prevIndex;
  39103. actions[ prevIndex ] = firstInactiveAction;
  39104. }
  39105. _takeBackAction( action ) {
  39106. // [ active actions | inactive actions ]
  39107. // [ active actions |< inactive actions ]
  39108. // a s
  39109. // <-swap->
  39110. // s a
  39111. const actions = this._actions,
  39112. prevIndex = action._cacheIndex,
  39113. firstInactiveIndex = -- this._nActiveActions,
  39114. lastActiveAction = actions[ firstInactiveIndex ];
  39115. action._cacheIndex = firstInactiveIndex;
  39116. actions[ firstInactiveIndex ] = action;
  39117. lastActiveAction._cacheIndex = prevIndex;
  39118. actions[ prevIndex ] = lastActiveAction;
  39119. }
  39120. // Memory management for PropertyMixer objects
  39121. _addInactiveBinding( binding, rootUuid, trackName ) {
  39122. const bindingsByRoot = this._bindingsByRootAndName,
  39123. bindings = this._bindings;
  39124. let bindingByName = bindingsByRoot[ rootUuid ];
  39125. if ( bindingByName === undefined ) {
  39126. bindingByName = {};
  39127. bindingsByRoot[ rootUuid ] = bindingByName;
  39128. }
  39129. bindingByName[ trackName ] = binding;
  39130. binding._cacheIndex = bindings.length;
  39131. bindings.push( binding );
  39132. }
  39133. _removeInactiveBinding( binding ) {
  39134. const bindings = this._bindings,
  39135. propBinding = binding.binding,
  39136. rootUuid = propBinding.rootNode.uuid,
  39137. trackName = propBinding.path,
  39138. bindingsByRoot = this._bindingsByRootAndName,
  39139. bindingByName = bindingsByRoot[ rootUuid ],
  39140. lastInactiveBinding = bindings[ bindings.length - 1 ],
  39141. cacheIndex = binding._cacheIndex;
  39142. lastInactiveBinding._cacheIndex = cacheIndex;
  39143. bindings[ cacheIndex ] = lastInactiveBinding;
  39144. bindings.pop();
  39145. delete bindingByName[ trackName ];
  39146. if ( Object.keys( bindingByName ).length === 0 ) {
  39147. delete bindingsByRoot[ rootUuid ];
  39148. }
  39149. }
  39150. _lendBinding( binding ) {
  39151. const bindings = this._bindings,
  39152. prevIndex = binding._cacheIndex,
  39153. lastActiveIndex = this._nActiveBindings ++,
  39154. firstInactiveBinding = bindings[ lastActiveIndex ];
  39155. binding._cacheIndex = lastActiveIndex;
  39156. bindings[ lastActiveIndex ] = binding;
  39157. firstInactiveBinding._cacheIndex = prevIndex;
  39158. bindings[ prevIndex ] = firstInactiveBinding;
  39159. }
  39160. _takeBackBinding( binding ) {
  39161. const bindings = this._bindings,
  39162. prevIndex = binding._cacheIndex,
  39163. firstInactiveIndex = -- this._nActiveBindings,
  39164. lastActiveBinding = bindings[ firstInactiveIndex ];
  39165. binding._cacheIndex = firstInactiveIndex;
  39166. bindings[ firstInactiveIndex ] = binding;
  39167. lastActiveBinding._cacheIndex = prevIndex;
  39168. bindings[ prevIndex ] = lastActiveBinding;
  39169. }
  39170. // Memory management of Interpolants for weight and time scale
  39171. _lendControlInterpolant() {
  39172. const interpolants = this._controlInterpolants,
  39173. lastActiveIndex = this._nActiveControlInterpolants ++;
  39174. let interpolant = interpolants[ lastActiveIndex ];
  39175. if ( interpolant === undefined ) {
  39176. interpolant = new LinearInterpolant(
  39177. new Float32Array( 2 ), new Float32Array( 2 ),
  39178. 1, _controlInterpolantsResultBuffer );
  39179. interpolant.__cacheIndex = lastActiveIndex;
  39180. interpolants[ lastActiveIndex ] = interpolant;
  39181. }
  39182. return interpolant;
  39183. }
  39184. _takeBackControlInterpolant( interpolant ) {
  39185. const interpolants = this._controlInterpolants,
  39186. prevIndex = interpolant.__cacheIndex,
  39187. firstInactiveIndex = -- this._nActiveControlInterpolants,
  39188. lastActiveInterpolant = interpolants[ firstInactiveIndex ];
  39189. interpolant.__cacheIndex = firstInactiveIndex;
  39190. interpolants[ firstInactiveIndex ] = interpolant;
  39191. lastActiveInterpolant.__cacheIndex = prevIndex;
  39192. interpolants[ prevIndex ] = lastActiveInterpolant;
  39193. }
  39194. /**
  39195. * Returns an instance of {@link AnimationAction} for the passed clip.
  39196. *
  39197. * If an action fitting the clip and root parameters doesn't yet exist, it
  39198. * will be created by this method. Calling this method several times with the
  39199. * same clip and root parameters always returns the same action.
  39200. *
  39201. * @param {AnimationClip|string} clip - An animation clip or alternatively the name of the animation clip.
  39202. * @param {Object3D} [optionalRoot] - An alternative root object.
  39203. * @param {(NormalAnimationBlendMode|AdditiveAnimationBlendMode)} [blendMode] - The blend mode.
  39204. * @return {?AnimationAction} The animation action.
  39205. */
  39206. clipAction( clip, optionalRoot, blendMode ) {
  39207. const root = optionalRoot || this._root,
  39208. rootUuid = root.uuid;
  39209. let clipObject = typeof clip === 'string' ? AnimationClip.findByName( root, clip ) : clip;
  39210. const clipUuid = clipObject !== null ? clipObject.uuid : clip;
  39211. const actionsForClip = this._actionsByClip[ clipUuid ];
  39212. let prototypeAction = null;
  39213. if ( blendMode === undefined ) {
  39214. if ( clipObject !== null ) {
  39215. blendMode = clipObject.blendMode;
  39216. } else {
  39217. blendMode = NormalAnimationBlendMode;
  39218. }
  39219. }
  39220. if ( actionsForClip !== undefined ) {
  39221. const existingAction = actionsForClip.actionByRoot[ rootUuid ];
  39222. if ( existingAction !== undefined && existingAction.blendMode === blendMode ) {
  39223. return existingAction;
  39224. }
  39225. // we know the clip, so we don't have to parse all
  39226. // the bindings again but can just copy
  39227. prototypeAction = actionsForClip.knownActions[ 0 ];
  39228. // also, take the clip from the prototype action
  39229. if ( clipObject === null )
  39230. clipObject = prototypeAction._clip;
  39231. }
  39232. // clip must be known when specified via string
  39233. if ( clipObject === null ) return null;
  39234. // allocate all resources required to run it
  39235. const newAction = new AnimationAction( this, clipObject, optionalRoot, blendMode );
  39236. this._bindAction( newAction, prototypeAction );
  39237. // and make the action known to the memory manager
  39238. this._addInactiveAction( newAction, clipUuid, rootUuid );
  39239. return newAction;
  39240. }
  39241. /**
  39242. * Returns an existing animation action for the passed clip.
  39243. *
  39244. * @param {AnimationClip|string} clip - An animation clip or alternatively the name of the animation clip.
  39245. * @param {Object3D} [optionalRoot] - An alternative root object.
  39246. * @return {?AnimationAction} The animation action. Returns `null` if no action was found.
  39247. */
  39248. existingAction( clip, optionalRoot ) {
  39249. const root = optionalRoot || this._root,
  39250. rootUuid = root.uuid,
  39251. clipObject = typeof clip === 'string' ?
  39252. AnimationClip.findByName( root, clip ) : clip,
  39253. clipUuid = clipObject ? clipObject.uuid : clip,
  39254. actionsForClip = this._actionsByClip[ clipUuid ];
  39255. if ( actionsForClip !== undefined ) {
  39256. return actionsForClip.actionByRoot[ rootUuid ] || null;
  39257. }
  39258. return null;
  39259. }
  39260. /**
  39261. * Deactivates all previously scheduled actions on this mixer.
  39262. *
  39263. * @return {AnimationMixer} A reference to this animation mixer.
  39264. */
  39265. stopAllAction() {
  39266. const actions = this._actions,
  39267. nActions = this._nActiveActions;
  39268. for ( let i = nActions - 1; i >= 0; -- i ) {
  39269. actions[ i ].stop();
  39270. }
  39271. return this;
  39272. }
  39273. /**
  39274. * Advances the global mixer time and updates the animation.
  39275. *
  39276. * This is usually done in the render loop by passing the delta
  39277. * time from {@link Clock} or {@link Timer}.
  39278. *
  39279. * @param {number} deltaTime - The delta time in seconds.
  39280. * @return {AnimationMixer} A reference to this animation mixer.
  39281. */
  39282. update( deltaTime ) {
  39283. deltaTime *= this.timeScale;
  39284. const actions = this._actions,
  39285. nActions = this._nActiveActions,
  39286. time = this.time += deltaTime,
  39287. timeDirection = Math.sign( deltaTime ),
  39288. accuIndex = this._accuIndex ^= 1;
  39289. // run active actions
  39290. for ( let i = 0; i !== nActions; ++ i ) {
  39291. const action = actions[ i ];
  39292. action._update( time, deltaTime, timeDirection, accuIndex );
  39293. }
  39294. // update scene graph
  39295. const bindings = this._bindings,
  39296. nBindings = this._nActiveBindings;
  39297. for ( let i = 0; i !== nBindings; ++ i ) {
  39298. bindings[ i ].apply( accuIndex );
  39299. }
  39300. return this;
  39301. }
  39302. /**
  39303. * Sets the global mixer to a specific time and updates the animation accordingly.
  39304. *
  39305. * This is useful when you need to jump to an exact time in an animation. The
  39306. * input parameter will be scaled by {@link AnimationMixer#timeScale}
  39307. *
  39308. * @param {number} time - The time to set in seconds.
  39309. * @return {AnimationMixer} A reference to this animation mixer.
  39310. */
  39311. setTime( time ) {
  39312. this.time = 0; // Zero out time attribute for AnimationMixer object;
  39313. for ( let i = 0; i < this._actions.length; i ++ ) {
  39314. this._actions[ i ].time = 0; // Zero out time attribute for all associated AnimationAction objects.
  39315. }
  39316. return this.update( time ); // Update used to set exact time. Returns "this" AnimationMixer object.
  39317. }
  39318. /**
  39319. * Returns this mixer's root object.
  39320. *
  39321. * @return {Object3D} The mixer's root object.
  39322. */
  39323. getRoot() {
  39324. return this._root;
  39325. }
  39326. /**
  39327. * Deallocates all memory resources for a clip. Before using this method make
  39328. * sure to call {@link AnimationAction#stop} for all related actions.
  39329. *
  39330. * @param {AnimationClip} clip - The clip to uncache.
  39331. */
  39332. uncacheClip( clip ) {
  39333. const actions = this._actions,
  39334. clipUuid = clip.uuid,
  39335. actionsByClip = this._actionsByClip,
  39336. actionsForClip = actionsByClip[ clipUuid ];
  39337. if ( actionsForClip !== undefined ) {
  39338. // note: just calling _removeInactiveAction would mess up the
  39339. // iteration state and also require updating the state we can
  39340. // just throw away
  39341. const actionsToRemove = actionsForClip.knownActions;
  39342. for ( let i = 0, n = actionsToRemove.length; i !== n; ++ i ) {
  39343. const action = actionsToRemove[ i ];
  39344. this._deactivateAction( action );
  39345. const cacheIndex = action._cacheIndex,
  39346. lastInactiveAction = actions[ actions.length - 1 ];
  39347. action._cacheIndex = null;
  39348. action._byClipCacheIndex = null;
  39349. lastInactiveAction._cacheIndex = cacheIndex;
  39350. actions[ cacheIndex ] = lastInactiveAction;
  39351. actions.pop();
  39352. this._removeInactiveBindingsForAction( action );
  39353. }
  39354. delete actionsByClip[ clipUuid ];
  39355. }
  39356. }
  39357. /**
  39358. * Deallocates all memory resources for a root object. Before using this
  39359. * method make sure to call {@link AnimationAction#stop} for all related
  39360. * actions or alternatively {@link AnimationMixer#stopAllAction} when the
  39361. * mixer operates on a single root.
  39362. *
  39363. * @param {Object3D} root - The root object to uncache.
  39364. */
  39365. uncacheRoot( root ) {
  39366. const rootUuid = root.uuid,
  39367. actionsByClip = this._actionsByClip;
  39368. for ( const clipUuid in actionsByClip ) {
  39369. const actionByRoot = actionsByClip[ clipUuid ].actionByRoot,
  39370. action = actionByRoot[ rootUuid ];
  39371. if ( action !== undefined ) {
  39372. this._deactivateAction( action );
  39373. this._removeInactiveAction( action );
  39374. }
  39375. }
  39376. const bindingsByRoot = this._bindingsByRootAndName,
  39377. bindingByName = bindingsByRoot[ rootUuid ];
  39378. if ( bindingByName !== undefined ) {
  39379. for ( const trackName in bindingByName ) {
  39380. const binding = bindingByName[ trackName ];
  39381. binding.restoreOriginalState();
  39382. this._removeInactiveBinding( binding );
  39383. }
  39384. }
  39385. }
  39386. /**
  39387. * Deallocates all memory resources for an action. The action is identified by the
  39388. * given clip and an optional root object. Before using this method make
  39389. * sure to call {@link AnimationAction#stop} to deactivate the action.
  39390. *
  39391. * @param {AnimationClip|string} clip - An animation clip or alternatively the name of the animation clip.
  39392. * @param {Object3D} [optionalRoot] - An alternative root object.
  39393. */
  39394. uncacheAction( clip, optionalRoot ) {
  39395. const action = this.existingAction( clip, optionalRoot );
  39396. if ( action !== null ) {
  39397. this._deactivateAction( action );
  39398. this._removeInactiveAction( action );
  39399. }
  39400. }
  39401. }
  39402. /**
  39403. * Represents a 3D render target.
  39404. *
  39405. * @augments RenderTarget
  39406. */
  39407. class RenderTarget3D extends RenderTarget {
  39408. /**
  39409. * Constructs a new 3D render target.
  39410. *
  39411. * @param {number} [width=1] - The width of the render target.
  39412. * @param {number} [height=1] - The height of the render target.
  39413. * @param {number} [depth=1] - The height of the render target.
  39414. * @param {RenderTarget~Options} [options] - The configuration object.
  39415. */
  39416. constructor( width = 1, height = 1, depth = 1, options = {} ) {
  39417. super( width, height, options );
  39418. /**
  39419. * This flag can be used for type testing.
  39420. *
  39421. * @type {boolean}
  39422. * @readonly
  39423. * @default true
  39424. */
  39425. this.isRenderTarget3D = true;
  39426. this.depth = depth;
  39427. /**
  39428. * Overwritten with a different texture type.
  39429. *
  39430. * @type {Data3DTexture}
  39431. */
  39432. this.texture = new Data3DTexture( null, width, height, depth );
  39433. this._setTextureOptions( options );
  39434. this.texture.isRenderTargetTexture = true;
  39435. }
  39436. }
  39437. /**
  39438. * Represents a uniform which is a global shader variable. They are passed to shader programs.
  39439. *
  39440. * When declaring a uniform of a {@link ShaderMaterial}, it is declared by value or by object.
  39441. * ```js
  39442. * uniforms: {
  39443. * time: { value: 1.0 },
  39444. * resolution: new Uniform( new Vector2() )
  39445. * };
  39446. * ```
  39447. * Since this class can only be used in context of {@link ShaderMaterial}, it is only supported
  39448. * in {@link WebGLRenderer}.
  39449. */
  39450. class Uniform {
  39451. /**
  39452. * Constructs a new uniform.
  39453. *
  39454. * @param {any} value - The uniform value.
  39455. */
  39456. constructor( value ) {
  39457. /**
  39458. * The uniform value.
  39459. *
  39460. * @type {any}
  39461. */
  39462. this.value = value;
  39463. }
  39464. /**
  39465. * Returns a new uniform with copied values from this instance.
  39466. * If the value has a `clone()` method, the value is cloned as well.
  39467. *
  39468. * @return {Uniform} A clone of this instance.
  39469. */
  39470. clone() {
  39471. return new Uniform( this.value.clone === undefined ? this.value : this.value.clone() );
  39472. }
  39473. }
  39474. let _id = 0;
  39475. /**
  39476. * A class for managing multiple uniforms in a single group. The renderer will process
  39477. * such a definition as a single UBO.
  39478. *
  39479. * Since this class can only be used in context of {@link ShaderMaterial}, it is only supported
  39480. * in {@link WebGLRenderer}.
  39481. *
  39482. * @augments EventDispatcher
  39483. */
  39484. class UniformsGroup extends EventDispatcher {
  39485. /**
  39486. * Constructs a new uniforms group.
  39487. */
  39488. constructor() {
  39489. super();
  39490. /**
  39491. * This flag can be used for type testing.
  39492. *
  39493. * @type {boolean}
  39494. * @readonly
  39495. * @default true
  39496. */
  39497. this.isUniformsGroup = true;
  39498. /**
  39499. * The ID of the 3D object.
  39500. *
  39501. * @name UniformsGroup#id
  39502. * @type {number}
  39503. * @readonly
  39504. */
  39505. Object.defineProperty( this, 'id', { value: _id ++ } );
  39506. /**
  39507. * The name of the uniforms group.
  39508. *
  39509. * @type {string}
  39510. */
  39511. this.name = '';
  39512. /**
  39513. * The buffer usage.
  39514. *
  39515. * @type {(StaticDrawUsage|DynamicDrawUsage|StreamDrawUsage|StaticReadUsage|DynamicReadUsage|StreamReadUsage|StaticCopyUsage|DynamicCopyUsage|StreamCopyUsage)}
  39516. * @default StaticDrawUsage
  39517. */
  39518. this.usage = StaticDrawUsage;
  39519. /**
  39520. * An array holding the uniforms.
  39521. *
  39522. * @type {Array<Uniform>}
  39523. */
  39524. this.uniforms = [];
  39525. }
  39526. /**
  39527. * Adds the given uniform to this uniforms group.
  39528. *
  39529. * @param {Uniform} uniform - The uniform to add.
  39530. * @return {UniformsGroup} A reference to this uniforms group.
  39531. */
  39532. add( uniform ) {
  39533. this.uniforms.push( uniform );
  39534. return this;
  39535. }
  39536. /**
  39537. * Removes the given uniform from this uniforms group.
  39538. *
  39539. * @param {Uniform} uniform - The uniform to remove.
  39540. * @return {UniformsGroup} A reference to this uniforms group.
  39541. */
  39542. remove( uniform ) {
  39543. const index = this.uniforms.indexOf( uniform );
  39544. if ( index !== -1 ) this.uniforms.splice( index, 1 );
  39545. return this;
  39546. }
  39547. /**
  39548. * Sets the name of this uniforms group.
  39549. *
  39550. * @param {string} name - The name to set.
  39551. * @return {UniformsGroup} A reference to this uniforms group.
  39552. */
  39553. setName( name ) {
  39554. this.name = name;
  39555. return this;
  39556. }
  39557. /**
  39558. * Sets the usage of this uniforms group.
  39559. *
  39560. * @param {(StaticDrawUsage|DynamicDrawUsage|StreamDrawUsage|StaticReadUsage|DynamicReadUsage|StreamReadUsage|StaticCopyUsage|DynamicCopyUsage|StreamCopyUsage)} value - The usage to set.
  39561. * @return {UniformsGroup} A reference to this uniforms group.
  39562. */
  39563. setUsage( value ) {
  39564. this.usage = value;
  39565. return this;
  39566. }
  39567. /**
  39568. * Frees the GPU-related resources allocated by this instance. Call this
  39569. * method whenever this instance is no longer used in your app.
  39570. *
  39571. * @fires Texture#dispose
  39572. */
  39573. dispose() {
  39574. this.dispatchEvent( { type: 'dispose' } );
  39575. }
  39576. /**
  39577. * Copies the values of the given uniforms group to this instance.
  39578. *
  39579. * @param {UniformsGroup} source - The uniforms group to copy.
  39580. * @return {UniformsGroup} A reference to this uniforms group.
  39581. */
  39582. copy( source ) {
  39583. this.name = source.name;
  39584. this.usage = source.usage;
  39585. const uniformsSource = source.uniforms;
  39586. this.uniforms.length = 0;
  39587. for ( let i = 0, l = uniformsSource.length; i < l; i ++ ) {
  39588. const uniforms = Array.isArray( uniformsSource[ i ] ) ? uniformsSource[ i ] : [ uniformsSource[ i ] ];
  39589. for ( let j = 0; j < uniforms.length; j ++ ) {
  39590. this.uniforms.push( uniforms[ j ].clone() );
  39591. }
  39592. }
  39593. return this;
  39594. }
  39595. /**
  39596. * Returns a new uniforms group with copied values from this instance.
  39597. *
  39598. * @return {UniformsGroup} A clone of this instance.
  39599. */
  39600. clone() {
  39601. return new this.constructor().copy( this );
  39602. }
  39603. }
  39604. /**
  39605. * An instanced version of an interleaved buffer.
  39606. *
  39607. * @augments InterleavedBuffer
  39608. */
  39609. class InstancedInterleavedBuffer extends InterleavedBuffer {
  39610. /**
  39611. * Constructs a new instanced interleaved buffer.
  39612. *
  39613. * @param {TypedArray} array - A typed array with a shared buffer storing attribute data.
  39614. * @param {number} stride - The number of typed-array elements per vertex.
  39615. * @param {number} [meshPerAttribute=1] - Defines how often a value of this interleaved buffer should be repeated.
  39616. */
  39617. constructor( array, stride, meshPerAttribute = 1 ) {
  39618. super( array, stride );
  39619. /**
  39620. * This flag can be used for type testing.
  39621. *
  39622. * @type {boolean}
  39623. * @readonly
  39624. * @default true
  39625. */
  39626. this.isInstancedInterleavedBuffer = true;
  39627. /**
  39628. * Defines how often a value of this buffer attribute should be repeated,
  39629. * see {@link InstancedBufferAttribute#meshPerAttribute}.
  39630. *
  39631. * @type {number}
  39632. * @default 1
  39633. */
  39634. this.meshPerAttribute = meshPerAttribute;
  39635. }
  39636. copy( source ) {
  39637. super.copy( source );
  39638. this.meshPerAttribute = source.meshPerAttribute;
  39639. return this;
  39640. }
  39641. clone( data ) {
  39642. const ib = super.clone( data );
  39643. ib.meshPerAttribute = this.meshPerAttribute;
  39644. return ib;
  39645. }
  39646. toJSON( data ) {
  39647. const json = super.toJSON( data );
  39648. json.isInstancedInterleavedBuffer = true;
  39649. json.meshPerAttribute = this.meshPerAttribute;
  39650. return json;
  39651. }
  39652. }
  39653. /**
  39654. * An alternative version of a buffer attribute with more control over the VBO.
  39655. *
  39656. * The renderer does not construct a VBO for this kind of attribute. Instead, it uses
  39657. * whatever VBO is passed in constructor and can later be altered via the `buffer` property.
  39658. *
  39659. * The most common use case for this class is when some kind of GPGPU calculation interferes
  39660. * or even produces the VBOs in question.
  39661. *
  39662. * Notice that this class can only be used with {@link WebGLRenderer}.
  39663. */
  39664. class GLBufferAttribute {
  39665. /**
  39666. * Constructs a new GL buffer attribute.
  39667. *
  39668. * @param {WebGLBuffer} buffer - The native WebGL buffer.
  39669. * @param {number} type - The native data type (e.g. `gl.FLOAT`).
  39670. * @param {number} itemSize - The item size.
  39671. * @param {number} elementSize - The corresponding size (in bytes) for the given `type` parameter.
  39672. * @param {number} count - The expected number of vertices in VBO.
  39673. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  39674. */
  39675. constructor( buffer, type, itemSize, elementSize, count, normalized = false ) {
  39676. /**
  39677. * This flag can be used for type testing.
  39678. *
  39679. * @type {boolean}
  39680. * @readonly
  39681. * @default true
  39682. */
  39683. this.isGLBufferAttribute = true;
  39684. /**
  39685. * The name of the buffer attribute.
  39686. *
  39687. * @type {string}
  39688. */
  39689. this.name = '';
  39690. /**
  39691. * The native WebGL buffer.
  39692. *
  39693. * @type {WebGLBuffer}
  39694. */
  39695. this.buffer = buffer;
  39696. /**
  39697. * The native data type.
  39698. *
  39699. * @type {number}
  39700. */
  39701. this.type = type;
  39702. /**
  39703. * The item size, see {@link BufferAttribute#itemSize}.
  39704. *
  39705. * @type {number}
  39706. */
  39707. this.itemSize = itemSize;
  39708. /**
  39709. * The corresponding size (in bytes) for the given `type` parameter.
  39710. *
  39711. * @type {number}
  39712. */
  39713. this.elementSize = elementSize;
  39714. /**
  39715. * The expected number of vertices in VBO.
  39716. *
  39717. * @type {number}
  39718. */
  39719. this.count = count;
  39720. /**
  39721. * Applies to integer data only. Indicates how the underlying data in the buffer maps to
  39722. * the values in the GLSL code. For instance, if `buffer` contains data of `gl.UNSIGNED_SHORT`,
  39723. * and `normalized` is `true`, the values `0 - +65535` in the buffer data will be mapped to
  39724. * `0.0f - +1.0f` in the GLSL attribute. If `normalized` is `false`, the values will be converted
  39725. * to floats unmodified, i.e. `65535` becomes `65535.0f`.
  39726. *
  39727. * @type {boolean}
  39728. */
  39729. this.normalized = normalized;
  39730. /**
  39731. * A version number, incremented every time the `needsUpdate` is set to `true`.
  39732. *
  39733. * @type {number}
  39734. */
  39735. this.version = 0;
  39736. }
  39737. /**
  39738. * Flag to indicate that this attribute has changed and should be re-sent to
  39739. * the GPU. Set this to `true` when you modify the value of the array.
  39740. *
  39741. * @type {number}
  39742. * @default false
  39743. * @param {boolean} value
  39744. */
  39745. set needsUpdate( value ) {
  39746. if ( value === true ) this.version ++;
  39747. }
  39748. /**
  39749. * Sets the given native WebGL buffer.
  39750. *
  39751. * @param {WebGLBuffer} buffer - The buffer to set.
  39752. * @return {BufferAttribute} A reference to this instance.
  39753. */
  39754. setBuffer( buffer ) {
  39755. this.buffer = buffer;
  39756. return this;
  39757. }
  39758. /**
  39759. * Sets the given native data type and element size.
  39760. *
  39761. * @param {number} type - The native data type (e.g. `gl.FLOAT`).
  39762. * @param {number} elementSize - The corresponding size (in bytes) for the given `type` parameter.
  39763. * @return {BufferAttribute} A reference to this instance.
  39764. */
  39765. setType( type, elementSize ) {
  39766. this.type = type;
  39767. this.elementSize = elementSize;
  39768. return this;
  39769. }
  39770. /**
  39771. * Sets the item size.
  39772. *
  39773. * @param {number} itemSize - The item size.
  39774. * @return {BufferAttribute} A reference to this instance.
  39775. */
  39776. setItemSize( itemSize ) {
  39777. this.itemSize = itemSize;
  39778. return this;
  39779. }
  39780. /**
  39781. * Sets the count (the expected number of vertices in VBO).
  39782. *
  39783. * @param {number} count - The count.
  39784. * @return {BufferAttribute} A reference to this instance.
  39785. */
  39786. setCount( count ) {
  39787. this.count = count;
  39788. return this;
  39789. }
  39790. }
  39791. const _matrix = /*@__PURE__*/ new Matrix4();
  39792. /**
  39793. * This class is designed to assist with raycasting. Raycasting is used for
  39794. * mouse picking (working out what objects in the 3d space the mouse is over)
  39795. * amongst other things.
  39796. */
  39797. class Raycaster {
  39798. /**
  39799. * Constructs a new raycaster.
  39800. *
  39801. * @param {Vector3} origin - The origin vector where the ray casts from.
  39802. * @param {Vector3} direction - The (normalized) direction vector that gives direction to the ray.
  39803. * @param {number} [near=0] - All results returned are further away than near. Near can't be negative.
  39804. * @param {number} [far=Infinity] - All results returned are closer than far. Far can't be lower than near.
  39805. */
  39806. constructor( origin, direction, near = 0, far = Infinity ) {
  39807. /**
  39808. * The ray used for raycasting.
  39809. *
  39810. * @type {Ray}
  39811. */
  39812. this.ray = new Ray( origin, direction );
  39813. /**
  39814. * All results returned are further away than near. Near can't be negative.
  39815. *
  39816. * @type {number}
  39817. * @default 0
  39818. */
  39819. this.near = near;
  39820. /**
  39821. * All results returned are closer than far. Far can't be lower than near.
  39822. *
  39823. * @type {number}
  39824. * @default Infinity
  39825. */
  39826. this.far = far;
  39827. /**
  39828. * The camera to use when raycasting against view-dependent objects such as
  39829. * billboarded objects like sprites. This field can be set manually or
  39830. * is set when calling `setFromCamera()`.
  39831. *
  39832. * @type {?Camera}
  39833. * @default null
  39834. */
  39835. this.camera = null;
  39836. /**
  39837. * Allows to selectively ignore 3D objects when performing intersection tests.
  39838. * The following code example ensures that only 3D objects on layer `1` will be
  39839. * honored by raycaster.
  39840. * ```js
  39841. * raycaster.layers.set( 1 );
  39842. * object.layers.enable( 1 );
  39843. * ```
  39844. *
  39845. * @type {Layers}
  39846. */
  39847. this.layers = new Layers();
  39848. /**
  39849. * A parameter object that configures the raycasting. It has the structure:
  39850. *
  39851. * ```
  39852. * {
  39853. * Mesh: {},
  39854. * Line: { threshold: 1 },
  39855. * LOD: {},
  39856. * Points: { threshold: 1 },
  39857. * Sprite: {}
  39858. * }
  39859. * ```
  39860. * Where `threshold` is the precision of the raycaster when intersecting objects, in world units.
  39861. *
  39862. * @type {Object}
  39863. */
  39864. this.params = {
  39865. Mesh: {},
  39866. Line: { threshold: 1 },
  39867. LOD: {},
  39868. Points: { threshold: 1 },
  39869. Sprite: {}
  39870. };
  39871. }
  39872. /**
  39873. * Updates the ray with a new origin and direction by copying the values from the arguments.
  39874. *
  39875. * @param {Vector3} origin - The origin vector where the ray casts from.
  39876. * @param {Vector3} direction - The (normalized) direction vector that gives direction to the ray.
  39877. */
  39878. set( origin, direction ) {
  39879. // direction is assumed to be normalized (for accurate distance calculations)
  39880. this.ray.set( origin, direction );
  39881. }
  39882. /**
  39883. * Uses the given coordinates and camera to compute a new origin and direction for the internal ray.
  39884. *
  39885. * @param {Vector2} coords - 2D coordinates of the mouse, in normalized device coordinates (NDC).
  39886. * X and Y components should be between `-1` and `1`.
  39887. * @param {Camera} camera - The camera from which the ray should originate.
  39888. */
  39889. setFromCamera( coords, camera ) {
  39890. if ( camera.isPerspectiveCamera ) {
  39891. this.ray.origin.setFromMatrixPosition( camera.matrixWorld );
  39892. this.ray.direction.set( coords.x, coords.y, 0.5 ).unproject( camera ).sub( this.ray.origin ).normalize();
  39893. this.camera = camera;
  39894. } else if ( camera.isOrthographicCamera ) {
  39895. this.ray.origin.set( coords.x, coords.y, ( camera.near + camera.far ) / ( camera.near - camera.far ) ).unproject( camera ); // set origin in plane of camera
  39896. this.ray.direction.set( 0, 0, -1 ).transformDirection( camera.matrixWorld );
  39897. this.camera = camera;
  39898. } else {
  39899. error( 'Raycaster: Unsupported camera type: ' + camera.type );
  39900. }
  39901. }
  39902. /**
  39903. * Uses the given WebXR controller to compute a new origin and direction for the internal ray.
  39904. *
  39905. * @param {WebXRController} controller - The controller to copy the position and direction from.
  39906. * @return {Raycaster} A reference to this raycaster.
  39907. */
  39908. setFromXRController( controller ) {
  39909. _matrix.identity().extractRotation( controller.matrixWorld );
  39910. this.ray.origin.setFromMatrixPosition( controller.matrixWorld );
  39911. this.ray.direction.set( 0, 0, -1 ).applyMatrix4( _matrix );
  39912. return this;
  39913. }
  39914. /**
  39915. * The intersection point of a raycaster intersection test.
  39916. * @typedef {Object} Raycaster~Intersection
  39917. * @property {number} distance - The distance from the ray's origin to the intersection point.
  39918. * @property {number} distanceToRay - Some 3D objects e.g. {@link Points} provide the distance of the
  39919. * intersection to the nearest point on the ray. For other objects it will be `undefined`.
  39920. * @property {Vector3} point - The intersection point, in world coordinates.
  39921. * @property {Object} face - The face that has been intersected.
  39922. * @property {number} faceIndex - The face index.
  39923. * @property {Object3D} object - The 3D object that has been intersected.
  39924. * @property {Vector2} uv - U,V coordinates at point of intersection.
  39925. * @property {Vector2} uv1 - Second set of U,V coordinates at point of intersection.
  39926. * @property {Vector3} normal - Interpolated normal vector at point of intersection.
  39927. * @property {number} instanceId - The index number of the instance where the ray
  39928. * intersects the {@link InstancedMesh}.
  39929. */
  39930. /**
  39931. * Checks all intersection between the ray and the object with or without the
  39932. * descendants. Intersections are returned sorted by distance, closest first.
  39933. *
  39934. * `Raycaster` delegates to the `raycast()` method of the passed 3D object, when
  39935. * evaluating whether the ray intersects the object or not. This allows meshes to respond
  39936. * differently to ray casting than lines or points.
  39937. *
  39938. * Note that for meshes, faces must be pointed towards the origin of the ray in order
  39939. * to be detected; intersections of the ray passing through the back of a face will not
  39940. * be detected. To raycast against both faces of an object, you'll want to set {@link Material#side}
  39941. * to `THREE.DoubleSide`.
  39942. *
  39943. * @param {Object3D} object - The 3D object to check for intersection with the ray.
  39944. * @param {boolean} [recursive=true] - If set to `true`, it also checks all descendants.
  39945. * Otherwise it only checks intersection with the object.
  39946. * @param {Array<Raycaster~Intersection>} [intersects=[]] The target array that holds the result of the method.
  39947. * @return {Array<Raycaster~Intersection>} An array holding the intersection points.
  39948. */
  39949. intersectObject( object, recursive = true, intersects = [] ) {
  39950. intersect( object, this, intersects, recursive );
  39951. intersects.sort( ascSort );
  39952. return intersects;
  39953. }
  39954. /**
  39955. * Checks all intersection between the ray and the objects with or without
  39956. * the descendants. Intersections are returned sorted by distance, closest first.
  39957. *
  39958. * @param {Array<Object3D>} objects - The 3D objects to check for intersection with the ray.
  39959. * @param {boolean} [recursive=true] - If set to `true`, it also checks all descendants.
  39960. * Otherwise it only checks intersection with the object.
  39961. * @param {Array<Raycaster~Intersection>} [intersects=[]] The target array that holds the result of the method.
  39962. * @return {Array<Raycaster~Intersection>} An array holding the intersection points.
  39963. */
  39964. intersectObjects( objects, recursive = true, intersects = [] ) {
  39965. for ( let i = 0, l = objects.length; i < l; i ++ ) {
  39966. intersect( objects[ i ], this, intersects, recursive );
  39967. }
  39968. intersects.sort( ascSort );
  39969. return intersects;
  39970. }
  39971. }
  39972. function ascSort( a, b ) {
  39973. return a.distance - b.distance;
  39974. }
  39975. function intersect( object, raycaster, intersects, recursive ) {
  39976. let propagate = true;
  39977. if ( object.layers.test( raycaster.layers ) ) {
  39978. const result = object.raycast( raycaster, intersects );
  39979. if ( result === false ) propagate = false;
  39980. }
  39981. if ( propagate === true && recursive === true ) {
  39982. const children = object.children;
  39983. for ( let i = 0, l = children.length; i < l; i ++ ) {
  39984. intersect( children[ i ], raycaster, intersects, true );
  39985. }
  39986. }
  39987. }
  39988. /**
  39989. * This class is an alternative to {@link Clock} with a different API design and behavior.
  39990. * The goal is to avoid the conceptual flaws that became apparent in `Clock` over time.
  39991. *
  39992. * - `Timer` has an `update()` method that updates its internal state. That makes it possible to
  39993. * call `getDelta()` and `getElapsed()` multiple times per simulation step without getting different values.
  39994. * - The class can make use of the Page Visibility API to avoid large time delta values when the app
  39995. * is inactive (e.g. tab switched or browser hidden).
  39996. *
  39997. * ```js
  39998. * const timer = new Timer();
  39999. * timer.connect( document ); // use Page Visibility API
  40000. * ```
  40001. */
  40002. class Timer {
  40003. /**
  40004. * Constructs a new timer.
  40005. */
  40006. constructor() {
  40007. this._previousTime = 0;
  40008. this._currentTime = 0;
  40009. this._startTime = performance.now();
  40010. this._delta = 0;
  40011. this._elapsed = 0;
  40012. this._timescale = 1;
  40013. this._document = null;
  40014. this._pageVisibilityHandler = null;
  40015. }
  40016. /**
  40017. * Connect the timer to the given document.Calling this method is not mandatory to
  40018. * use the timer but enables the usage of the Page Visibility API to avoid large time
  40019. * delta values.
  40020. *
  40021. * @param {Document} document - The document.
  40022. */
  40023. connect( document ) {
  40024. this._document = document;
  40025. // use Page Visibility API to avoid large time delta values
  40026. if ( document.hidden !== undefined ) {
  40027. this._pageVisibilityHandler = handleVisibilityChange.bind( this );
  40028. document.addEventListener( 'visibilitychange', this._pageVisibilityHandler, false );
  40029. }
  40030. }
  40031. /**
  40032. * Disconnects the timer from the DOM and also disables the usage of the Page Visibility API.
  40033. */
  40034. disconnect() {
  40035. if ( this._pageVisibilityHandler !== null ) {
  40036. this._document.removeEventListener( 'visibilitychange', this._pageVisibilityHandler );
  40037. this._pageVisibilityHandler = null;
  40038. }
  40039. this._document = null;
  40040. }
  40041. /**
  40042. * Returns the time delta in seconds.
  40043. *
  40044. * @return {number} The time delta in second.
  40045. */
  40046. getDelta() {
  40047. return this._delta / 1000;
  40048. }
  40049. /**
  40050. * Returns the elapsed time in seconds.
  40051. *
  40052. * @return {number} The elapsed time in second.
  40053. */
  40054. getElapsed() {
  40055. return this._elapsed / 1000;
  40056. }
  40057. /**
  40058. * Returns the timescale.
  40059. *
  40060. * @return {number} The timescale.
  40061. */
  40062. getTimescale() {
  40063. return this._timescale;
  40064. }
  40065. /**
  40066. * Sets the given timescale which scale the time delta computation
  40067. * in `update()`.
  40068. *
  40069. * @param {number} timescale - The timescale to set.
  40070. * @return {Timer} A reference to this timer.
  40071. */
  40072. setTimescale( timescale ) {
  40073. this._timescale = timescale;
  40074. return this;
  40075. }
  40076. /**
  40077. * Resets the time computation for the current simulation step.
  40078. *
  40079. * @return {Timer} A reference to this timer.
  40080. */
  40081. reset() {
  40082. this._currentTime = performance.now() - this._startTime;
  40083. return this;
  40084. }
  40085. /**
  40086. * Can be used to free all internal resources. Usually called when
  40087. * the timer instance isn't required anymore.
  40088. */
  40089. dispose() {
  40090. this.disconnect();
  40091. }
  40092. /**
  40093. * Updates the internal state of the timer. This method should be called
  40094. * once per simulation step and before you perform queries against the timer
  40095. * (e.g. via `getDelta()`).
  40096. *
  40097. * @param {number} timestamp - The current time in milliseconds. Can be obtained
  40098. * from the `requestAnimationFrame` callback argument. If not provided, the current
  40099. * time will be determined with `performance.now`.
  40100. * @return {Timer} A reference to this timer.
  40101. */
  40102. update( timestamp ) {
  40103. if ( this._pageVisibilityHandler !== null && this._document.hidden === true ) {
  40104. this._delta = 0;
  40105. } else {
  40106. this._previousTime = this._currentTime;
  40107. this._currentTime = ( timestamp !== undefined ? timestamp : performance.now() ) - this._startTime;
  40108. this._delta = ( this._currentTime - this._previousTime ) * this._timescale;
  40109. this._elapsed += this._delta; // _elapsed is the accumulation of all previous deltas
  40110. }
  40111. return this;
  40112. }
  40113. }
  40114. function handleVisibilityChange() {
  40115. if ( this._document.hidden === false ) this.reset();
  40116. }
  40117. /**
  40118. * This class can be used to represent points in 3D space as
  40119. * [Spherical coordinates](https://en.wikipedia.org/wiki/Spherical_coordinate_system).
  40120. */
  40121. class Spherical {
  40122. /**
  40123. * Constructs a new spherical.
  40124. *
  40125. * @param {number} [radius=1] - The radius, or the Euclidean distance (straight-line distance) from the point to the origin.
  40126. * @param {number} [phi=0] - The polar angle in radians from the y (up) axis.
  40127. * @param {number} [theta=0] - The equator/azimuthal angle in radians around the y (up) axis.
  40128. */
  40129. constructor( radius = 1, phi = 0, theta = 0 ) {
  40130. /**
  40131. * The radius, or the Euclidean distance (straight-line distance) from the point to the origin.
  40132. *
  40133. * @type {number}
  40134. * @default 1
  40135. */
  40136. this.radius = radius;
  40137. /**
  40138. * The polar angle in radians from the y (up) axis.
  40139. *
  40140. * @type {number}
  40141. * @default 0
  40142. */
  40143. this.phi = phi;
  40144. /**
  40145. * The equator/azimuthal angle in radians around the y (up) axis.
  40146. *
  40147. * @type {number}
  40148. * @default 0
  40149. */
  40150. this.theta = theta;
  40151. }
  40152. /**
  40153. * Sets the spherical components by copying the given values.
  40154. *
  40155. * @param {number} radius - The radius.
  40156. * @param {number} phi - The polar angle.
  40157. * @param {number} theta - The azimuthal angle.
  40158. * @return {Spherical} A reference to this spherical.
  40159. */
  40160. set( radius, phi, theta ) {
  40161. this.radius = radius;
  40162. this.phi = phi;
  40163. this.theta = theta;
  40164. return this;
  40165. }
  40166. /**
  40167. * Copies the values of the given spherical to this instance.
  40168. *
  40169. * @param {Spherical} other - The spherical to copy.
  40170. * @return {Spherical} A reference to this spherical.
  40171. */
  40172. copy( other ) {
  40173. this.radius = other.radius;
  40174. this.phi = other.phi;
  40175. this.theta = other.theta;
  40176. return this;
  40177. }
  40178. /**
  40179. * Restricts the polar angle [page:.phi phi] to be between `0.000001` and pi -
  40180. * `0.000001`.
  40181. *
  40182. * @return {Spherical} A reference to this spherical.
  40183. */
  40184. makeSafe() {
  40185. const EPS = 0.000001;
  40186. this.phi = clamp( this.phi, EPS, Math.PI - EPS );
  40187. return this;
  40188. }
  40189. /**
  40190. * Sets the spherical components from the given vector which is assumed to hold
  40191. * Cartesian coordinates.
  40192. *
  40193. * @param {Vector3} v - The vector to set.
  40194. * @return {Spherical} A reference to this spherical.
  40195. */
  40196. setFromVector3( v ) {
  40197. return this.setFromCartesianCoords( v.x, v.y, v.z );
  40198. }
  40199. /**
  40200. * Sets the spherical components from the given Cartesian coordinates.
  40201. *
  40202. * @param {number} x - The x value.
  40203. * @param {number} y - The y value.
  40204. * @param {number} z - The z value.
  40205. * @return {Spherical} A reference to this spherical.
  40206. */
  40207. setFromCartesianCoords( x, y, z ) {
  40208. this.radius = Math.sqrt( x * x + y * y + z * z );
  40209. if ( this.radius === 0 ) {
  40210. this.theta = 0;
  40211. this.phi = 0;
  40212. } else {
  40213. this.theta = Math.atan2( x, z );
  40214. this.phi = Math.acos( clamp( y / this.radius, -1, 1 ) );
  40215. }
  40216. return this;
  40217. }
  40218. /**
  40219. * Returns a new spherical with copied values from this instance.
  40220. *
  40221. * @return {Spherical} A clone of this instance.
  40222. */
  40223. clone() {
  40224. return new this.constructor().copy( this );
  40225. }
  40226. }
  40227. /**
  40228. * This class can be used to represent points in 3D space as
  40229. * [Cylindrical coordinates](https://en.wikipedia.org/wiki/Cylindrical_coordinate_system).
  40230. */
  40231. class Cylindrical {
  40232. /**
  40233. * Constructs a new cylindrical.
  40234. *
  40235. * @param {number} [radius=1] - The distance from the origin to a point in the x-z plane.
  40236. * @param {number} [theta=0] - A counterclockwise angle in the x-z plane measured in radians from the positive z-axis.
  40237. * @param {number} [y=0] - The height above the x-z plane.
  40238. */
  40239. constructor( radius = 1, theta = 0, y = 0 ) {
  40240. /**
  40241. * The distance from the origin to a point in the x-z plane.
  40242. *
  40243. * @type {number}
  40244. * @default 1
  40245. */
  40246. this.radius = radius;
  40247. /**
  40248. * A counterclockwise angle in the x-z plane measured in radians from the positive z-axis.
  40249. *
  40250. * @type {number}
  40251. * @default 0
  40252. */
  40253. this.theta = theta;
  40254. /**
  40255. * The height above the x-z plane.
  40256. *
  40257. * @type {number}
  40258. * @default 0
  40259. */
  40260. this.y = y;
  40261. }
  40262. /**
  40263. * Sets the cylindrical components by copying the given values.
  40264. *
  40265. * @param {number} radius - The radius.
  40266. * @param {number} theta - The theta angle.
  40267. * @param {number} y - The height value.
  40268. * @return {Cylindrical} A reference to this cylindrical.
  40269. */
  40270. set( radius, theta, y ) {
  40271. this.radius = radius;
  40272. this.theta = theta;
  40273. this.y = y;
  40274. return this;
  40275. }
  40276. /**
  40277. * Copies the values of the given cylindrical to this instance.
  40278. *
  40279. * @param {Cylindrical} other - The cylindrical to copy.
  40280. * @return {Cylindrical} A reference to this cylindrical.
  40281. */
  40282. copy( other ) {
  40283. this.radius = other.radius;
  40284. this.theta = other.theta;
  40285. this.y = other.y;
  40286. return this;
  40287. }
  40288. /**
  40289. * Sets the cylindrical components from the given vector which is assumed to hold
  40290. * Cartesian coordinates.
  40291. *
  40292. * @param {Vector3} v - The vector to set.
  40293. * @return {Cylindrical} A reference to this cylindrical.
  40294. */
  40295. setFromVector3( v ) {
  40296. return this.setFromCartesianCoords( v.x, v.y, v.z );
  40297. }
  40298. /**
  40299. * Sets the cylindrical components from the given Cartesian coordinates.
  40300. *
  40301. * @param {number} x - The x value.
  40302. * @param {number} y - The x value.
  40303. * @param {number} z - The x value.
  40304. * @return {Cylindrical} A reference to this cylindrical.
  40305. */
  40306. setFromCartesianCoords( x, y, z ) {
  40307. this.radius = Math.sqrt( x * x + z * z );
  40308. this.theta = Math.atan2( x, z );
  40309. this.y = y;
  40310. return this;
  40311. }
  40312. /**
  40313. * Returns a new cylindrical with copied values from this instance.
  40314. *
  40315. * @return {Cylindrical} A clone of this instance.
  40316. */
  40317. clone() {
  40318. return new this.constructor().copy( this );
  40319. }
  40320. }
  40321. /**
  40322. * Represents a 2x2 matrix.
  40323. *
  40324. * A Note on Row-Major and Column-Major Ordering:
  40325. *
  40326. * The constructor and {@link Matrix2#set} method take arguments in
  40327. * [row-major](https://en.wikipedia.org/wiki/Row-_and_column-major_order#Column-major_order)
  40328. * order, while internally they are stored in the {@link Matrix2#elements} array in column-major order.
  40329. * This means that calling:
  40330. * ```js
  40331. * const m = new THREE.Matrix2();
  40332. * m.set( 11, 12,
  40333. * 21, 22 );
  40334. * ```
  40335. * will result in the elements array containing:
  40336. * ```js
  40337. * m.elements = [ 11, 21,
  40338. * 12, 22 ];
  40339. * ```
  40340. * and internally all calculations are performed using column-major ordering.
  40341. * However, as the actual ordering makes no difference mathematically and
  40342. * most people are used to thinking about matrices in row-major order, the
  40343. * three.js documentation shows matrices in row-major order. Just bear in
  40344. * mind that if you are reading the source code, you'll have to take the
  40345. * transpose of any matrices outlined here to make sense of the calculations.
  40346. */
  40347. class Matrix2 {
  40348. /**
  40349. * Constructs a new 2x2 matrix. The arguments are supposed to be
  40350. * in row-major order. If no arguments are provided, the constructor
  40351. * initializes the matrix as an identity matrix.
  40352. *
  40353. * @param {number} [n11] - 1-1 matrix element.
  40354. * @param {number} [n12] - 1-2 matrix element.
  40355. * @param {number} [n21] - 2-1 matrix element.
  40356. * @param {number} [n22] - 2-2 matrix element.
  40357. */
  40358. constructor( n11, n12, n21, n22 ) {
  40359. /**
  40360. * This flag can be used for type testing.
  40361. *
  40362. * @type {boolean}
  40363. * @readonly
  40364. * @default true
  40365. */
  40366. Matrix2.prototype.isMatrix2 = true;
  40367. /**
  40368. * A column-major list of matrix values.
  40369. *
  40370. * @type {Array<number>}
  40371. */
  40372. this.elements = [
  40373. 1, 0,
  40374. 0, 1,
  40375. ];
  40376. if ( n11 !== undefined ) {
  40377. this.set( n11, n12, n21, n22 );
  40378. }
  40379. }
  40380. /**
  40381. * Sets this matrix to the 2x2 identity matrix.
  40382. *
  40383. * @return {Matrix2} A reference to this matrix.
  40384. */
  40385. identity() {
  40386. this.set(
  40387. 1, 0,
  40388. 0, 1,
  40389. );
  40390. return this;
  40391. }
  40392. /**
  40393. * Sets the elements of the matrix from the given array.
  40394. *
  40395. * @param {Array<number>} array - The matrix elements in column-major order.
  40396. * @param {number} [offset=0] - Index of the first element in the array.
  40397. * @return {Matrix2} A reference to this matrix.
  40398. */
  40399. fromArray( array, offset = 0 ) {
  40400. for ( let i = 0; i < 4; i ++ ) {
  40401. this.elements[ i ] = array[ i + offset ];
  40402. }
  40403. return this;
  40404. }
  40405. /**
  40406. * Sets the elements of the matrix.The arguments are supposed to be
  40407. * in row-major order.
  40408. *
  40409. * @param {number} n11 - 1-1 matrix element.
  40410. * @param {number} n12 - 1-2 matrix element.
  40411. * @param {number} n21 - 2-1 matrix element.
  40412. * @param {number} n22 - 2-2 matrix element.
  40413. * @return {Matrix2} A reference to this matrix.
  40414. */
  40415. set( n11, n12, n21, n22 ) {
  40416. const te = this.elements;
  40417. te[ 0 ] = n11; te[ 2 ] = n12;
  40418. te[ 1 ] = n21; te[ 3 ] = n22;
  40419. return this;
  40420. }
  40421. }
  40422. const _vector$4 = /*@__PURE__*/ new Vector2();
  40423. /**
  40424. * Represents an axis-aligned bounding box (AABB) in 2D space.
  40425. */
  40426. class Box2 {
  40427. /**
  40428. * Constructs a new bounding box.
  40429. *
  40430. * @param {Vector2} [min=(Infinity,Infinity)] - A vector representing the lower boundary of the box.
  40431. * @param {Vector2} [max=(-Infinity,-Infinity)] - A vector representing the upper boundary of the box.
  40432. */
  40433. constructor( min = new Vector2( + Infinity, + Infinity ), max = new Vector2( - Infinity, - Infinity ) ) {
  40434. /**
  40435. * This flag can be used for type testing.
  40436. *
  40437. * @type {boolean}
  40438. * @readonly
  40439. * @default true
  40440. */
  40441. this.isBox2 = true;
  40442. /**
  40443. * The lower boundary of the box.
  40444. *
  40445. * @type {Vector2}
  40446. */
  40447. this.min = min;
  40448. /**
  40449. * The upper boundary of the box.
  40450. *
  40451. * @type {Vector2}
  40452. */
  40453. this.max = max;
  40454. }
  40455. /**
  40456. * Sets the lower and upper boundaries of this box.
  40457. * Please note that this method only copies the values from the given objects.
  40458. *
  40459. * @param {Vector2} min - The lower boundary of the box.
  40460. * @param {Vector2} max - The upper boundary of the box.
  40461. * @return {Box2} A reference to this bounding box.
  40462. */
  40463. set( min, max ) {
  40464. this.min.copy( min );
  40465. this.max.copy( max );
  40466. return this;
  40467. }
  40468. /**
  40469. * Sets the upper and lower bounds of this box so it encloses the position data
  40470. * in the given array.
  40471. *
  40472. * @param {Array<Vector2>} points - An array holding 2D position data as instances of {@link Vector2}.
  40473. * @return {Box2} A reference to this bounding box.
  40474. */
  40475. setFromPoints( points ) {
  40476. this.makeEmpty();
  40477. for ( let i = 0, il = points.length; i < il; i ++ ) {
  40478. this.expandByPoint( points[ i ] );
  40479. }
  40480. return this;
  40481. }
  40482. /**
  40483. * Centers this box on the given center vector and sets this box's width, height and
  40484. * depth to the given size values.
  40485. *
  40486. * @param {Vector2} center - The center of the box.
  40487. * @param {Vector2} size - The x and y dimensions of the box.
  40488. * @return {Box2} A reference to this bounding box.
  40489. */
  40490. setFromCenterAndSize( center, size ) {
  40491. const halfSize = _vector$4.copy( size ).multiplyScalar( 0.5 );
  40492. this.min.copy( center ).sub( halfSize );
  40493. this.max.copy( center ).add( halfSize );
  40494. return this;
  40495. }
  40496. /**
  40497. * Returns a new box with copied values from this instance.
  40498. *
  40499. * @return {Box2} A clone of this instance.
  40500. */
  40501. clone() {
  40502. return new this.constructor().copy( this );
  40503. }
  40504. /**
  40505. * Copies the values of the given box to this instance.
  40506. *
  40507. * @param {Box2} box - The box to copy.
  40508. * @return {Box2} A reference to this bounding box.
  40509. */
  40510. copy( box ) {
  40511. this.min.copy( box.min );
  40512. this.max.copy( box.max );
  40513. return this;
  40514. }
  40515. /**
  40516. * Makes this box empty which means in encloses a zero space in 2D.
  40517. *
  40518. * @return {Box2} A reference to this bounding box.
  40519. */
  40520. makeEmpty() {
  40521. this.min.x = this.min.y = + Infinity;
  40522. this.max.x = this.max.y = - Infinity;
  40523. return this;
  40524. }
  40525. /**
  40526. * Returns true if this box includes zero points within its bounds.
  40527. * Note that a box with equal lower and upper bounds still includes one
  40528. * point, the one both bounds share.
  40529. *
  40530. * @return {boolean} Whether this box is empty or not.
  40531. */
  40532. isEmpty() {
  40533. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  40534. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y );
  40535. }
  40536. /**
  40537. * Returns the center point of this box.
  40538. *
  40539. * @param {Vector2} target - The target vector that is used to store the method's result.
  40540. * @return {Vector2} The center point.
  40541. */
  40542. getCenter( target ) {
  40543. return this.isEmpty() ? target.set( 0, 0 ) : target.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  40544. }
  40545. /**
  40546. * Returns the dimensions of this box.
  40547. *
  40548. * @param {Vector2} target - The target vector that is used to store the method's result.
  40549. * @return {Vector2} The size.
  40550. */
  40551. getSize( target ) {
  40552. return this.isEmpty() ? target.set( 0, 0 ) : target.subVectors( this.max, this.min );
  40553. }
  40554. /**
  40555. * Expands the boundaries of this box to include the given point.
  40556. *
  40557. * @param {Vector2} point - The point that should be included by the bounding box.
  40558. * @return {Box2} A reference to this bounding box.
  40559. */
  40560. expandByPoint( point ) {
  40561. this.min.min( point );
  40562. this.max.max( point );
  40563. return this;
  40564. }
  40565. /**
  40566. * Expands this box equilaterally by the given vector. The width of this
  40567. * box will be expanded by the x component of the vector in both
  40568. * directions. The height of this box will be expanded by the y component of
  40569. * the vector in both directions.
  40570. *
  40571. * @param {Vector2} vector - The vector that should expand the bounding box.
  40572. * @return {Box2} A reference to this bounding box.
  40573. */
  40574. expandByVector( vector ) {
  40575. this.min.sub( vector );
  40576. this.max.add( vector );
  40577. return this;
  40578. }
  40579. /**
  40580. * Expands each dimension of the box by the given scalar. If negative, the
  40581. * dimensions of the box will be contracted.
  40582. *
  40583. * @param {number} scalar - The scalar value that should expand the bounding box.
  40584. * @return {Box2} A reference to this bounding box.
  40585. */
  40586. expandByScalar( scalar ) {
  40587. this.min.addScalar( - scalar );
  40588. this.max.addScalar( scalar );
  40589. return this;
  40590. }
  40591. /**
  40592. * Returns `true` if the given point lies within or on the boundaries of this box.
  40593. *
  40594. * @param {Vector2} point - The point to test.
  40595. * @return {boolean} Whether the bounding box contains the given point or not.
  40596. */
  40597. containsPoint( point ) {
  40598. return point.x >= this.min.x && point.x <= this.max.x &&
  40599. point.y >= this.min.y && point.y <= this.max.y;
  40600. }
  40601. /**
  40602. * Returns `true` if this bounding box includes the entirety of the given bounding box.
  40603. * If this box and the given one are identical, this function also returns `true`.
  40604. *
  40605. * @param {Box2} box - The bounding box to test.
  40606. * @return {boolean} Whether the bounding box contains the given bounding box or not.
  40607. */
  40608. containsBox( box ) {
  40609. return this.min.x <= box.min.x && box.max.x <= this.max.x &&
  40610. this.min.y <= box.min.y && box.max.y <= this.max.y;
  40611. }
  40612. /**
  40613. * Returns a point as a proportion of this box's width and height.
  40614. *
  40615. * @param {Vector2} point - A point in 2D space.
  40616. * @param {Vector2} target - The target vector that is used to store the method's result.
  40617. * @return {Vector2} A point as a proportion of this box's width and height.
  40618. */
  40619. getParameter( point, target ) {
  40620. // This can potentially have a divide by zero if the box
  40621. // has a size dimension of 0.
  40622. return target.set(
  40623. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  40624. ( point.y - this.min.y ) / ( this.max.y - this.min.y )
  40625. );
  40626. }
  40627. /**
  40628. * Returns `true` if the given bounding box intersects with this bounding box.
  40629. *
  40630. * @param {Box2} box - The bounding box to test.
  40631. * @return {boolean} Whether the given bounding box intersects with this bounding box.
  40632. */
  40633. intersectsBox( box ) {
  40634. // using 4 splitting planes to rule out intersections
  40635. return box.max.x >= this.min.x && box.min.x <= this.max.x &&
  40636. box.max.y >= this.min.y && box.min.y <= this.max.y;
  40637. }
  40638. /**
  40639. * Clamps the given point within the bounds of this box.
  40640. *
  40641. * @param {Vector2} point - The point to clamp.
  40642. * @param {Vector2} target - The target vector that is used to store the method's result.
  40643. * @return {Vector2} The clamped point.
  40644. */
  40645. clampPoint( point, target ) {
  40646. return target.copy( point ).clamp( this.min, this.max );
  40647. }
  40648. /**
  40649. * Returns the euclidean distance from any edge of this box to the specified point. If
  40650. * the given point lies inside of this box, the distance will be `0`.
  40651. *
  40652. * @param {Vector2} point - The point to compute the distance to.
  40653. * @return {number} The euclidean distance.
  40654. */
  40655. distanceToPoint( point ) {
  40656. return this.clampPoint( point, _vector$4 ).distanceTo( point );
  40657. }
  40658. /**
  40659. * Computes the intersection of this bounding box and the given one, setting the upper
  40660. * bound of this box to the lesser of the two boxes' upper bounds and the
  40661. * lower bound of this box to the greater of the two boxes' lower bounds. If
  40662. * there's no overlap, makes this box empty.
  40663. *
  40664. * @param {Box2} box - The bounding box to intersect with.
  40665. * @return {Box2} A reference to this bounding box.
  40666. */
  40667. intersect( box ) {
  40668. this.min.max( box.min );
  40669. this.max.min( box.max );
  40670. if ( this.isEmpty() ) this.makeEmpty();
  40671. return this;
  40672. }
  40673. /**
  40674. * Computes the union of this box and another and the given one, setting the upper
  40675. * bound of this box to the greater of the two boxes' upper bounds and the
  40676. * lower bound of this box to the lesser of the two boxes' lower bounds.
  40677. *
  40678. * @param {Box2} box - The bounding box that will be unioned with this instance.
  40679. * @return {Box2} A reference to this bounding box.
  40680. */
  40681. union( box ) {
  40682. this.min.min( box.min );
  40683. this.max.max( box.max );
  40684. return this;
  40685. }
  40686. /**
  40687. * Adds the given offset to both the upper and lower bounds of this bounding box,
  40688. * effectively moving it in 2D space.
  40689. *
  40690. * @param {Vector2} offset - The offset that should be used to translate the bounding box.
  40691. * @return {Box2} A reference to this bounding box.
  40692. */
  40693. translate( offset ) {
  40694. this.min.add( offset );
  40695. this.max.add( offset );
  40696. return this;
  40697. }
  40698. /**
  40699. * Returns `true` if this bounding box is equal with the given one.
  40700. *
  40701. * @param {Box2} box - The box to test for equality.
  40702. * @return {boolean} Whether this bounding box is equal with the given one.
  40703. */
  40704. equals( box ) {
  40705. return box.min.equals( this.min ) && box.max.equals( this.max );
  40706. }
  40707. }
  40708. const _startP = /*@__PURE__*/ new Vector3();
  40709. const _startEnd = /*@__PURE__*/ new Vector3();
  40710. const _d1 = /*@__PURE__*/ new Vector3();
  40711. const _d2 = /*@__PURE__*/ new Vector3();
  40712. const _r = /*@__PURE__*/ new Vector3();
  40713. const _c1 = /*@__PURE__*/ new Vector3();
  40714. const _c2 = /*@__PURE__*/ new Vector3();
  40715. /**
  40716. * An analytical line segment in 3D space represented by a start and end point.
  40717. */
  40718. class Line3 {
  40719. /**
  40720. * Constructs a new line segment.
  40721. *
  40722. * @param {Vector3} [start=(0,0,0)] - Start of the line segment.
  40723. * @param {Vector3} [end=(0,0,0)] - End of the line segment.
  40724. */
  40725. constructor( start = new Vector3(), end = new Vector3() ) {
  40726. /**
  40727. * Start of the line segment.
  40728. *
  40729. * @type {Vector3}
  40730. */
  40731. this.start = start;
  40732. /**
  40733. * End of the line segment.
  40734. *
  40735. * @type {Vector3}
  40736. */
  40737. this.end = end;
  40738. }
  40739. /**
  40740. * Sets the start and end values by copying the given vectors.
  40741. *
  40742. * @param {Vector3} start - The start point.
  40743. * @param {Vector3} end - The end point.
  40744. * @return {Line3} A reference to this line segment.
  40745. */
  40746. set( start, end ) {
  40747. this.start.copy( start );
  40748. this.end.copy( end );
  40749. return this;
  40750. }
  40751. /**
  40752. * Copies the values of the given line segment to this instance.
  40753. *
  40754. * @param {Line3} line - The line segment to copy.
  40755. * @return {Line3} A reference to this line segment.
  40756. */
  40757. copy( line ) {
  40758. this.start.copy( line.start );
  40759. this.end.copy( line.end );
  40760. return this;
  40761. }
  40762. /**
  40763. * Returns the center of the line segment.
  40764. *
  40765. * @param {Vector3} target - The target vector that is used to store the method's result.
  40766. * @return {Vector3} The center point.
  40767. */
  40768. getCenter( target ) {
  40769. return target.addVectors( this.start, this.end ).multiplyScalar( 0.5 );
  40770. }
  40771. /**
  40772. * Returns the delta vector of the line segment's start and end point.
  40773. *
  40774. * @param {Vector3} target - The target vector that is used to store the method's result.
  40775. * @return {Vector3} The delta vector.
  40776. */
  40777. delta( target ) {
  40778. return target.subVectors( this.end, this.start );
  40779. }
  40780. /**
  40781. * Returns the squared Euclidean distance between the line' start and end point.
  40782. *
  40783. * @return {number} The squared Euclidean distance.
  40784. */
  40785. distanceSq() {
  40786. return this.start.distanceToSquared( this.end );
  40787. }
  40788. /**
  40789. * Returns the Euclidean distance between the line' start and end point.
  40790. *
  40791. * @return {number} The Euclidean distance.
  40792. */
  40793. distance() {
  40794. return this.start.distanceTo( this.end );
  40795. }
  40796. /**
  40797. * Returns a vector at a certain position along the line segment.
  40798. *
  40799. * @param {number} t - A value between `[0,1]` to represent a position along the line segment.
  40800. * @param {Vector3} target - The target vector that is used to store the method's result.
  40801. * @return {Vector3} The delta vector.
  40802. */
  40803. at( t, target ) {
  40804. return this.delta( target ).multiplyScalar( t ).add( this.start );
  40805. }
  40806. /**
  40807. * Returns a point parameter based on the closest point as projected on the line segment.
  40808. *
  40809. * @param {Vector3} point - The point for which to return a point parameter.
  40810. * @param {boolean} clampToLine - Whether to clamp the result to the range `[0,1]` or not.
  40811. * @return {number} The point parameter.
  40812. */
  40813. closestPointToPointParameter( point, clampToLine ) {
  40814. _startP.subVectors( point, this.start );
  40815. _startEnd.subVectors( this.end, this.start );
  40816. const startEnd2 = _startEnd.dot( _startEnd );
  40817. const startEnd_startP = _startEnd.dot( _startP );
  40818. let t = startEnd_startP / startEnd2;
  40819. if ( clampToLine ) {
  40820. t = clamp( t, 0, 1 );
  40821. }
  40822. return t;
  40823. }
  40824. /**
  40825. * Returns the closest point on the line for a given point.
  40826. *
  40827. * @param {Vector3} point - The point to compute the closest point on the line for.
  40828. * @param {boolean} clampToLine - Whether to clamp the result to the range `[0,1]` or not.
  40829. * @param {Vector3} target - The target vector that is used to store the method's result.
  40830. * @return {Vector3} The closest point on the line.
  40831. */
  40832. closestPointToPoint( point, clampToLine, target ) {
  40833. const t = this.closestPointToPointParameter( point, clampToLine );
  40834. return this.delta( target ).multiplyScalar( t ).add( this.start );
  40835. }
  40836. /**
  40837. * Returns the closest squared distance between this line segment and the given one.
  40838. *
  40839. * @param {Line3} line - The line segment to compute the closest squared distance to.
  40840. * @param {Vector3} [c1] - The closest point on this line segment.
  40841. * @param {Vector3} [c2] - The closest point on the given line segment.
  40842. * @return {number} The squared distance between this line segment and the given one.
  40843. */
  40844. distanceSqToLine3( line, c1 = _c1, c2 = _c2 ) {
  40845. // from Real-Time Collision Detection by Christer Ericson, chapter 5.1.9
  40846. // Computes closest points C1 and C2 of S1(s)=P1+s*(Q1-P1) and
  40847. // S2(t)=P2+t*(Q2-P2), returning s and t. Function result is squared
  40848. // distance between between S1(s) and S2(t)
  40849. const EPSILON = 1e-8 * 1e-8; // must be squared since we compare squared length
  40850. let s, t;
  40851. const p1 = this.start;
  40852. const p2 = line.start;
  40853. const q1 = this.end;
  40854. const q2 = line.end;
  40855. _d1.subVectors( q1, p1 ); // Direction vector of segment S1
  40856. _d2.subVectors( q2, p2 ); // Direction vector of segment S2
  40857. _r.subVectors( p1, p2 );
  40858. const a = _d1.dot( _d1 ); // Squared length of segment S1, always nonnegative
  40859. const e = _d2.dot( _d2 ); // Squared length of segment S2, always nonnegative
  40860. const f = _d2.dot( _r );
  40861. // Check if either or both segments degenerate into points
  40862. if ( a <= EPSILON && e <= EPSILON ) {
  40863. // Both segments degenerate into points
  40864. c1.copy( p1 );
  40865. c2.copy( p2 );
  40866. c1.sub( c2 );
  40867. return c1.dot( c1 );
  40868. }
  40869. if ( a <= EPSILON ) {
  40870. // First segment degenerates into a point
  40871. s = 0;
  40872. t = f / e; // s = 0 => t = (b*s + f) / e = f / e
  40873. t = clamp( t, 0, 1 );
  40874. } else {
  40875. const c = _d1.dot( _r );
  40876. if ( e <= EPSILON ) {
  40877. // Second segment degenerates into a point
  40878. t = 0;
  40879. s = clamp( - c / a, 0, 1 ); // t = 0 => s = (b*t - c) / a = -c / a
  40880. } else {
  40881. // The general nondegenerate case starts here
  40882. const b = _d1.dot( _d2 );
  40883. const denom = a * e - b * b; // Always nonnegative
  40884. // If segments not parallel, compute closest point on L1 to L2 and
  40885. // clamp to segment S1. Else pick arbitrary s (here 0)
  40886. if ( denom !== 0 ) {
  40887. s = clamp( ( b * f - c * e ) / denom, 0, 1 );
  40888. } else {
  40889. s = 0;
  40890. }
  40891. // Compute point on L2 closest to S1(s) using
  40892. // t = Dot((P1 + D1*s) - P2,D2) / Dot(D2,D2) = (b*s + f) / e
  40893. t = ( b * s + f ) / e;
  40894. // If t in [0,1] done. Else clamp t, recompute s for the new value
  40895. // of t using s = Dot((P2 + D2*t) - P1,D1) / Dot(D1,D1)= (t*b - c) / a
  40896. // and clamp s to [0, 1]
  40897. if ( t < 0 ) {
  40898. t = 0.;
  40899. s = clamp( - c / a, 0, 1 );
  40900. } else if ( t > 1 ) {
  40901. t = 1;
  40902. s = clamp( ( b - c ) / a, 0, 1 );
  40903. }
  40904. }
  40905. }
  40906. c1.copy( p1 ).add( _d1.multiplyScalar( s ) );
  40907. c2.copy( p2 ).add( _d2.multiplyScalar( t ) );
  40908. c1.sub( c2 );
  40909. return c1.dot( c1 );
  40910. }
  40911. /**
  40912. * Applies a 4x4 transformation matrix to this line segment.
  40913. *
  40914. * @param {Matrix4} matrix - The transformation matrix.
  40915. * @return {Line3} A reference to this line segment.
  40916. */
  40917. applyMatrix4( matrix ) {
  40918. this.start.applyMatrix4( matrix );
  40919. this.end.applyMatrix4( matrix );
  40920. return this;
  40921. }
  40922. /**
  40923. * Returns `true` if this line segment is equal with the given one.
  40924. *
  40925. * @param {Line3} line - The line segment to test for equality.
  40926. * @return {boolean} Whether this line segment is equal with the given one.
  40927. */
  40928. equals( line ) {
  40929. return line.start.equals( this.start ) && line.end.equals( this.end );
  40930. }
  40931. /**
  40932. * Returns a new line segment with copied values from this instance.
  40933. *
  40934. * @return {Line3} A clone of this instance.
  40935. */
  40936. clone() {
  40937. return new this.constructor().copy( this );
  40938. }
  40939. }
  40940. const _vector$3 = /*@__PURE__*/ new Vector3();
  40941. /**
  40942. * This displays a cone shaped helper object for a {@link SpotLight}.
  40943. *
  40944. * ```js
  40945. * const spotLight = new THREE.SpotLight( 0xffffff );
  40946. * spotLight.position.set( 10, 10, 10 );
  40947. * scene.add( spotLight );
  40948. *
  40949. * const spotLightHelper = new THREE.SpotLightHelper( spotLight );
  40950. * scene.add( spotLightHelper );
  40951. * ```
  40952. *
  40953. * @augments Object3D
  40954. */
  40955. class SpotLightHelper extends Object3D {
  40956. /**
  40957. * Constructs a new spot light helper.
  40958. *
  40959. * @param {HemisphereLight} light - The light to be visualized.
  40960. * @param {number|Color|string} [color] - The helper's color. If not set, the helper will take
  40961. * the color of the light.
  40962. */
  40963. constructor( light, color ) {
  40964. super();
  40965. /**
  40966. * The light being visualized.
  40967. *
  40968. * @type {SpotLight}
  40969. */
  40970. this.light = light;
  40971. this.matrixAutoUpdate = false;
  40972. /**
  40973. * The color parameter passed in the constructor.
  40974. * If not set, the helper will take the color of the light.
  40975. *
  40976. * @type {number|Color|string}
  40977. */
  40978. this.color = color;
  40979. this.type = 'SpotLightHelper';
  40980. const geometry = new BufferGeometry();
  40981. const positions = [
  40982. 0, 0, 0, 0, 0, 1,
  40983. 0, 0, 0, 1, 0, 1,
  40984. 0, 0, 0, -1, 0, 1,
  40985. 0, 0, 0, 0, 1, 1,
  40986. 0, 0, 0, 0, -1, 1
  40987. ];
  40988. for ( let i = 0, j = 1, l = 32; i < l; i ++, j ++ ) {
  40989. const p1 = ( i / l ) * Math.PI * 2;
  40990. const p2 = ( j / l ) * Math.PI * 2;
  40991. positions.push(
  40992. Math.cos( p1 ), Math.sin( p1 ), 1,
  40993. Math.cos( p2 ), Math.sin( p2 ), 1
  40994. );
  40995. }
  40996. geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  40997. const material = new LineBasicMaterial( { fog: false, toneMapped: false } );
  40998. this.cone = new LineSegments( geometry, material );
  40999. this.add( this.cone );
  41000. this.update();
  41001. }
  41002. /**
  41003. * Frees the GPU-related resources allocated by this instance. Call this
  41004. * method whenever this instance is no longer used in your app.
  41005. */
  41006. dispose() {
  41007. this.cone.geometry.dispose();
  41008. this.cone.material.dispose();
  41009. }
  41010. /**
  41011. * Updates the helper to match the position and direction of the
  41012. * light being visualized.
  41013. */
  41014. update() {
  41015. this.light.updateWorldMatrix( true, false );
  41016. this.light.target.updateWorldMatrix( true, false );
  41017. // update the local matrix based on the parent and light target transforms
  41018. if ( this.parent ) {
  41019. this.parent.updateWorldMatrix( true );
  41020. this.matrix
  41021. .copy( this.parent.matrixWorld )
  41022. .invert()
  41023. .multiply( this.light.matrixWorld );
  41024. } else {
  41025. this.matrix.copy( this.light.matrixWorld );
  41026. }
  41027. this.matrixWorld.copy( this.light.matrixWorld );
  41028. const coneLength = this.light.distance ? this.light.distance : 1000;
  41029. const coneWidth = coneLength * Math.tan( this.light.angle );
  41030. this.cone.scale.set( coneWidth, coneWidth, coneLength );
  41031. _vector$3.setFromMatrixPosition( this.light.target.matrixWorld );
  41032. this.cone.lookAt( _vector$3 );
  41033. if ( this.color !== undefined ) {
  41034. this.cone.material.color.set( this.color );
  41035. } else {
  41036. this.cone.material.color.copy( this.light.color );
  41037. }
  41038. }
  41039. }
  41040. const _vector$2 = /*@__PURE__*/ new Vector3();
  41041. const _boneMatrix = /*@__PURE__*/ new Matrix4();
  41042. const _matrixWorldInv = /*@__PURE__*/ new Matrix4();
  41043. /**
  41044. * A helper object to assist with visualizing a {@link Skeleton}.
  41045. *
  41046. * ```js
  41047. * const helper = new THREE.SkeletonHelper( skinnedMesh );
  41048. * scene.add( helper );
  41049. * ```
  41050. *
  41051. * @augments LineSegments
  41052. */
  41053. class SkeletonHelper extends LineSegments {
  41054. /**
  41055. * Constructs a new skeleton helper.
  41056. *
  41057. * @param {Object3D} object - Usually an instance of {@link SkinnedMesh}. However, any 3D object
  41058. * can be used if it represents a hierarchy of bones (see {@link Bone}).
  41059. */
  41060. constructor( object ) {
  41061. const bones = getBoneList( object );
  41062. const geometry = new BufferGeometry();
  41063. const vertices = [];
  41064. const colors = [];
  41065. for ( let i = 0; i < bones.length; i ++ ) {
  41066. const bone = bones[ i ];
  41067. if ( bone.parent && bone.parent.isBone ) {
  41068. vertices.push( 0, 0, 0 );
  41069. vertices.push( 0, 0, 0 );
  41070. colors.push( 0, 0, 0 );
  41071. colors.push( 0, 0, 0 );
  41072. }
  41073. }
  41074. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  41075. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  41076. const material = new LineBasicMaterial( { vertexColors: true, depthTest: false, depthWrite: false, toneMapped: false, transparent: true } );
  41077. super( geometry, material );
  41078. /**
  41079. * This flag can be used for type testing.
  41080. *
  41081. * @type {boolean}
  41082. * @readonly
  41083. * @default true
  41084. */
  41085. this.isSkeletonHelper = true;
  41086. this.type = 'SkeletonHelper';
  41087. /**
  41088. * The object being visualized.
  41089. *
  41090. * @type {Object3D}
  41091. */
  41092. this.root = object;
  41093. /**
  41094. * The list of bones that the helper visualizes.
  41095. *
  41096. * @type {Array<Bone>}
  41097. */
  41098. this.bones = bones;
  41099. this.matrix = object.matrixWorld;
  41100. this.matrixAutoUpdate = false;
  41101. // colors
  41102. const color1 = new Color( 0x0000ff );
  41103. const color2 = new Color( 0x00ff00 );
  41104. this.setColors( color1, color2 );
  41105. }
  41106. updateMatrixWorld( force ) {
  41107. const bones = this.bones;
  41108. const geometry = this.geometry;
  41109. const position = geometry.getAttribute( 'position' );
  41110. _matrixWorldInv.copy( this.root.matrixWorld ).invert();
  41111. for ( let i = 0, j = 0; i < bones.length; i ++ ) {
  41112. const bone = bones[ i ];
  41113. if ( bone.parent && bone.parent.isBone ) {
  41114. _boneMatrix.multiplyMatrices( _matrixWorldInv, bone.matrixWorld );
  41115. _vector$2.setFromMatrixPosition( _boneMatrix );
  41116. position.setXYZ( j, _vector$2.x, _vector$2.y, _vector$2.z );
  41117. _boneMatrix.multiplyMatrices( _matrixWorldInv, bone.parent.matrixWorld );
  41118. _vector$2.setFromMatrixPosition( _boneMatrix );
  41119. position.setXYZ( j + 1, _vector$2.x, _vector$2.y, _vector$2.z );
  41120. j += 2;
  41121. }
  41122. }
  41123. geometry.getAttribute( 'position' ).needsUpdate = true;
  41124. super.updateMatrixWorld( force );
  41125. }
  41126. /**
  41127. * Defines the colors of the helper.
  41128. *
  41129. * @param {Color} color1 - The first line color for each bone.
  41130. * @param {Color} color2 - The second line color for each bone.
  41131. * @return {SkeletonHelper} A reference to this helper.
  41132. */
  41133. setColors( color1, color2 ) {
  41134. const geometry = this.geometry;
  41135. const colorAttribute = geometry.getAttribute( 'color' );
  41136. for ( let i = 0; i < colorAttribute.count; i += 2 ) {
  41137. colorAttribute.setXYZ( i, color1.r, color1.g, color1.b );
  41138. colorAttribute.setXYZ( i + 1, color2.r, color2.g, color2.b );
  41139. }
  41140. colorAttribute.needsUpdate = true;
  41141. return this;
  41142. }
  41143. /**
  41144. * Frees the GPU-related resources allocated by this instance. Call this
  41145. * method whenever this instance is no longer used in your app.
  41146. */
  41147. dispose() {
  41148. this.geometry.dispose();
  41149. this.material.dispose();
  41150. }
  41151. }
  41152. function getBoneList( object ) {
  41153. const boneList = [];
  41154. if ( object.isBone === true ) {
  41155. boneList.push( object );
  41156. }
  41157. for ( let i = 0; i < object.children.length; i ++ ) {
  41158. boneList.push( ...getBoneList( object.children[ i ] ) );
  41159. }
  41160. return boneList;
  41161. }
  41162. /**
  41163. * This displays a helper object consisting of a spherical mesh for
  41164. * visualizing an instance of {@link PointLight}.
  41165. *
  41166. * ```js
  41167. * const pointLight = new THREE.PointLight( 0xff0000, 1, 100 );
  41168. * pointLight.position.set( 10, 10, 10 );
  41169. * scene.add( pointLight );
  41170. *
  41171. * const sphereSize = 1;
  41172. * const pointLightHelper = new THREE.PointLightHelper( pointLight, sphereSize );
  41173. * scene.add( pointLightHelper );
  41174. * ```
  41175. *
  41176. * @augments Mesh
  41177. */
  41178. class PointLightHelper extends Mesh {
  41179. /**
  41180. * Constructs a new point light helper.
  41181. *
  41182. * @param {PointLight} light - The light to be visualized.
  41183. * @param {number} [sphereSize=1] - The size of the sphere helper.
  41184. * @param {number|Color|string} [color] - The helper's color. If not set, the helper will take
  41185. * the color of the light.
  41186. */
  41187. constructor( light, sphereSize, color ) {
  41188. const geometry = new SphereGeometry( sphereSize, 4, 2 );
  41189. const material = new MeshBasicMaterial( { wireframe: true, fog: false, toneMapped: false } );
  41190. super( geometry, material );
  41191. /**
  41192. * The light being visualized.
  41193. *
  41194. * @type {PointLight}
  41195. */
  41196. this.light = light;
  41197. /**
  41198. * The color parameter passed in the constructor.
  41199. * If not set, the helper will take the color of the light.
  41200. *
  41201. * @type {number|Color|string}
  41202. */
  41203. this.color = color;
  41204. this.type = 'PointLightHelper';
  41205. this.matrix = this.light.matrixWorld;
  41206. this.matrixAutoUpdate = false;
  41207. this.update();
  41208. /*
  41209. // TODO: delete this comment?
  41210. const distanceGeometry = new THREE.IcosahedronGeometry( 1, 2 );
  41211. const distanceMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false, wireframe: true, opacity: 0.1, transparent: true } );
  41212. this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial );
  41213. this.lightDistance = new THREE.Mesh( distanceGeometry, distanceMaterial );
  41214. const d = light.distance;
  41215. if ( d === 0.0 ) {
  41216. this.lightDistance.visible = false;
  41217. } else {
  41218. this.lightDistance.scale.set( d, d, d );
  41219. }
  41220. this.add( this.lightDistance );
  41221. */
  41222. }
  41223. /**
  41224. * Frees the GPU-related resources allocated by this instance. Call this
  41225. * method whenever this instance is no longer used in your app.
  41226. */
  41227. dispose() {
  41228. this.geometry.dispose();
  41229. this.material.dispose();
  41230. }
  41231. /**
  41232. * Updates the helper to match the position of the
  41233. * light being visualized.
  41234. */
  41235. update() {
  41236. this.light.updateWorldMatrix( true, false );
  41237. if ( this.color !== undefined ) {
  41238. this.material.color.set( this.color );
  41239. } else {
  41240. this.material.color.copy( this.light.color );
  41241. }
  41242. /*
  41243. const d = this.light.distance;
  41244. if ( d === 0.0 ) {
  41245. this.lightDistance.visible = false;
  41246. } else {
  41247. this.lightDistance.visible = true;
  41248. this.lightDistance.scale.set( d, d, d );
  41249. }
  41250. */
  41251. }
  41252. }
  41253. const _vector$1 = /*@__PURE__*/ new Vector3();
  41254. const _color1 = /*@__PURE__*/ new Color();
  41255. const _color2 = /*@__PURE__*/ new Color();
  41256. /**
  41257. * Creates a visual aid consisting of a spherical mesh for a
  41258. * given {@link HemisphereLight}.
  41259. *
  41260. * ```js
  41261. * const light = new THREE.HemisphereLight( 0xffffbb, 0x080820, 1 );
  41262. * const helper = new THREE.HemisphereLightHelper( light, 5 );
  41263. * scene.add( helper );
  41264. * ```
  41265. *
  41266. * @augments Object3D
  41267. */
  41268. class HemisphereLightHelper extends Object3D {
  41269. /**
  41270. * Constructs a new hemisphere light helper.
  41271. *
  41272. * @param {HemisphereLight} light - The light to be visualized.
  41273. * @param {number} [size=1] - The size of the mesh used to visualize the light.
  41274. * @param {number|Color|string} [color] - The helper's color. If not set, the helper will take
  41275. * the color of the light.
  41276. */
  41277. constructor( light, size, color ) {
  41278. super();
  41279. /**
  41280. * The light being visualized.
  41281. *
  41282. * @type {HemisphereLight}
  41283. */
  41284. this.light = light;
  41285. this.matrix = light.matrixWorld;
  41286. this.matrixAutoUpdate = false;
  41287. /**
  41288. * The color parameter passed in the constructor.
  41289. * If not set, the helper will take the color of the light.
  41290. *
  41291. * @type {number|Color|string}
  41292. */
  41293. this.color = color;
  41294. this.type = 'HemisphereLightHelper';
  41295. const geometry = new OctahedronGeometry( size );
  41296. geometry.rotateY( Math.PI * 0.5 );
  41297. this.material = new MeshBasicMaterial( { wireframe: true, fog: false, toneMapped: false } );
  41298. if ( this.color === undefined ) this.material.vertexColors = true;
  41299. const position = geometry.getAttribute( 'position' );
  41300. const colors = new Float32Array( position.count * 3 );
  41301. geometry.setAttribute( 'color', new BufferAttribute( colors, 3 ) );
  41302. this.add( new Mesh( geometry, this.material ) );
  41303. this.update();
  41304. }
  41305. /**
  41306. * Frees the GPU-related resources allocated by this instance. Call this
  41307. * method whenever this instance is no longer used in your app.
  41308. */
  41309. dispose() {
  41310. this.children[ 0 ].geometry.dispose();
  41311. this.children[ 0 ].material.dispose();
  41312. }
  41313. /**
  41314. * Updates the helper to match the position and direction of the
  41315. * light being visualized.
  41316. */
  41317. update() {
  41318. const mesh = this.children[ 0 ];
  41319. if ( this.color !== undefined ) {
  41320. this.material.color.set( this.color );
  41321. } else {
  41322. const colors = mesh.geometry.getAttribute( 'color' );
  41323. _color1.copy( this.light.color );
  41324. _color2.copy( this.light.groundColor );
  41325. for ( let i = 0, l = colors.count; i < l; i ++ ) {
  41326. const color = ( i < ( l / 2 ) ) ? _color1 : _color2;
  41327. colors.setXYZ( i, color.r, color.g, color.b );
  41328. }
  41329. colors.needsUpdate = true;
  41330. }
  41331. this.light.updateWorldMatrix( true, false );
  41332. mesh.lookAt( _vector$1.setFromMatrixPosition( this.light.matrixWorld ).negate() );
  41333. }
  41334. }
  41335. /**
  41336. * The helper is an object to define grids. Grids are two-dimensional
  41337. * arrays of lines.
  41338. *
  41339. * ```js
  41340. * const size = 10;
  41341. * const divisions = 10;
  41342. *
  41343. * const gridHelper = new THREE.GridHelper( size, divisions );
  41344. * scene.add( gridHelper );
  41345. * ```
  41346. *
  41347. * @augments LineSegments
  41348. */
  41349. class GridHelper extends LineSegments {
  41350. /**
  41351. * Constructs a new grid helper.
  41352. *
  41353. * @param {number} [size=10] - The size of the grid.
  41354. * @param {number} [divisions=10] - The number of divisions across the grid.
  41355. * @param {number|Color|string} [color1=0x444444] - The color of the center line.
  41356. * @param {number|Color|string} [color2=0x888888] - The color of the lines of the grid.
  41357. */
  41358. constructor( size = 10, divisions = 10, color1 = 0x444444, color2 = 0x888888 ) {
  41359. color1 = new Color( color1 );
  41360. color2 = new Color( color2 );
  41361. const center = divisions / 2;
  41362. const step = size / divisions;
  41363. const halfSize = size / 2;
  41364. const vertices = [], colors = [];
  41365. for ( let i = 0, j = 0, k = - halfSize; i <= divisions; i ++, k += step ) {
  41366. vertices.push( - halfSize, 0, k, halfSize, 0, k );
  41367. vertices.push( k, 0, - halfSize, k, 0, halfSize );
  41368. const color = i === center ? color1 : color2;
  41369. color.toArray( colors, j ); j += 3;
  41370. color.toArray( colors, j ); j += 3;
  41371. color.toArray( colors, j ); j += 3;
  41372. color.toArray( colors, j ); j += 3;
  41373. }
  41374. const geometry = new BufferGeometry();
  41375. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  41376. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  41377. const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
  41378. super( geometry, material );
  41379. this.type = 'GridHelper';
  41380. }
  41381. /**
  41382. * Frees the GPU-related resources allocated by this instance. Call this
  41383. * method whenever this instance is no longer used in your app.
  41384. */
  41385. dispose() {
  41386. this.geometry.dispose();
  41387. this.material.dispose();
  41388. }
  41389. }
  41390. /**
  41391. * This helper is an object to define polar grids. Grids are
  41392. * two-dimensional arrays of lines.
  41393. *
  41394. * ```js
  41395. * const radius = 10;
  41396. * const sectors = 16;
  41397. * const rings = 8;
  41398. * const divisions = 64;
  41399. *
  41400. * const helper = new THREE.PolarGridHelper( radius, sectors, rings, divisions );
  41401. * scene.add( helper );
  41402. * ```
  41403. *
  41404. * @augments LineSegments
  41405. */
  41406. class PolarGridHelper extends LineSegments {
  41407. /**
  41408. * Constructs a new polar grid helper.
  41409. *
  41410. * @param {number} [radius=10] - The radius of the polar grid. This can be any positive number.
  41411. * @param {number} [sectors=16] - The number of sectors the grid will be divided into. This can be any positive integer.
  41412. * @param {number} [rings=16] - The number of rings. This can be any positive integer.
  41413. * @param {number} [divisions=64] - The number of line segments used for each circle. This can be any positive integer.
  41414. * @param {number|Color|string} [color1=0x444444] - The first color used for grid elements.
  41415. * @param {number|Color|string} [color2=0x888888] - The second color used for grid elements.
  41416. */
  41417. constructor( radius = 10, sectors = 16, rings = 8, divisions = 64, color1 = 0x444444, color2 = 0x888888 ) {
  41418. color1 = new Color( color1 );
  41419. color2 = new Color( color2 );
  41420. const vertices = [];
  41421. const colors = [];
  41422. // create the sectors
  41423. if ( sectors > 1 ) {
  41424. for ( let i = 0; i < sectors; i ++ ) {
  41425. const v = ( i / sectors ) * ( Math.PI * 2 );
  41426. const x = Math.sin( v ) * radius;
  41427. const z = Math.cos( v ) * radius;
  41428. vertices.push( 0, 0, 0 );
  41429. vertices.push( x, 0, z );
  41430. const color = ( i & 1 ) ? color1 : color2;
  41431. colors.push( color.r, color.g, color.b );
  41432. colors.push( color.r, color.g, color.b );
  41433. }
  41434. }
  41435. // create the rings
  41436. for ( let i = 0; i < rings; i ++ ) {
  41437. const color = ( i & 1 ) ? color1 : color2;
  41438. const r = radius - ( radius / rings * i );
  41439. for ( let j = 0; j < divisions; j ++ ) {
  41440. // first vertex
  41441. let v = ( j / divisions ) * ( Math.PI * 2 );
  41442. let x = Math.sin( v ) * r;
  41443. let z = Math.cos( v ) * r;
  41444. vertices.push( x, 0, z );
  41445. colors.push( color.r, color.g, color.b );
  41446. // second vertex
  41447. v = ( ( j + 1 ) / divisions ) * ( Math.PI * 2 );
  41448. x = Math.sin( v ) * r;
  41449. z = Math.cos( v ) * r;
  41450. vertices.push( x, 0, z );
  41451. colors.push( color.r, color.g, color.b );
  41452. }
  41453. }
  41454. const geometry = new BufferGeometry();
  41455. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  41456. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  41457. const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
  41458. super( geometry, material );
  41459. this.type = 'PolarGridHelper';
  41460. }
  41461. /**
  41462. * Frees the GPU-related resources allocated by this instance. Call this
  41463. * method whenever this instance is no longer used in your app.
  41464. */
  41465. dispose() {
  41466. this.geometry.dispose();
  41467. this.material.dispose();
  41468. }
  41469. }
  41470. const _v1 = /*@__PURE__*/ new Vector3();
  41471. const _v2 = /*@__PURE__*/ new Vector3();
  41472. const _v3 = /*@__PURE__*/ new Vector3();
  41473. /**
  41474. * Helper object to assist with visualizing a {@link DirectionalLight}'s
  41475. * effect on the scene. This consists of plane and a line representing the
  41476. * light's position and direction.
  41477. *
  41478. * ```js
  41479. * const light = new THREE.DirectionalLight( 0xFFFFFF );
  41480. * scene.add( light );
  41481. *
  41482. * const helper = new THREE.DirectionalLightHelper( light, 5 );
  41483. * scene.add( helper );
  41484. * ```
  41485. *
  41486. * @augments Object3D
  41487. */
  41488. class DirectionalLightHelper extends Object3D {
  41489. /**
  41490. * Constructs a new directional light helper.
  41491. *
  41492. * @param {DirectionalLight} light - The light to be visualized.
  41493. * @param {number} [size=1] - The dimensions of the plane.
  41494. * @param {number|Color|string} [color] - The helper's color. If not set, the helper will take
  41495. * the color of the light.
  41496. */
  41497. constructor( light, size, color ) {
  41498. super();
  41499. /**
  41500. * The light being visualized.
  41501. *
  41502. * @type {DirectionalLight}
  41503. */
  41504. this.light = light;
  41505. this.matrix = light.matrixWorld;
  41506. this.matrixAutoUpdate = false;
  41507. /**
  41508. * The color parameter passed in the constructor.
  41509. * If not set, the helper will take the color of the light.
  41510. *
  41511. * @type {number|Color|string}
  41512. */
  41513. this.color = color;
  41514. this.type = 'DirectionalLightHelper';
  41515. if ( size === undefined ) size = 1;
  41516. let geometry = new BufferGeometry();
  41517. geometry.setAttribute( 'position', new Float32BufferAttribute( [
  41518. - size, size, 0,
  41519. size, size, 0,
  41520. size, - size, 0,
  41521. - size, - size, 0,
  41522. - size, size, 0
  41523. ], 3 ) );
  41524. const material = new LineBasicMaterial( { fog: false, toneMapped: false } );
  41525. /**
  41526. * Contains the line showing the location of the directional light.
  41527. *
  41528. * @type {Line}
  41529. */
  41530. this.lightPlane = new Line( geometry, material );
  41531. this.add( this.lightPlane );
  41532. geometry = new BufferGeometry();
  41533. geometry.setAttribute( 'position', new Float32BufferAttribute( [ 0, 0, 0, 0, 0, 1 ], 3 ) );
  41534. /**
  41535. * Represents the target line of the directional light.
  41536. *
  41537. * @type {Line}
  41538. */
  41539. this.targetLine = new Line( geometry, material );
  41540. this.add( this.targetLine );
  41541. this.update();
  41542. }
  41543. /**
  41544. * Frees the GPU-related resources allocated by this instance. Call this
  41545. * method whenever this instance is no longer used in your app.
  41546. */
  41547. dispose() {
  41548. this.lightPlane.geometry.dispose();
  41549. this.lightPlane.material.dispose();
  41550. this.targetLine.geometry.dispose();
  41551. this.targetLine.material.dispose();
  41552. }
  41553. /**
  41554. * Updates the helper to match the position and direction of the
  41555. * light being visualized.
  41556. */
  41557. update() {
  41558. this.light.updateWorldMatrix( true, false );
  41559. this.light.target.updateWorldMatrix( true, false );
  41560. _v1.setFromMatrixPosition( this.light.matrixWorld );
  41561. _v2.setFromMatrixPosition( this.light.target.matrixWorld );
  41562. _v3.subVectors( _v2, _v1 );
  41563. this.lightPlane.lookAt( _v2 );
  41564. if ( this.color !== undefined ) {
  41565. this.lightPlane.material.color.set( this.color );
  41566. this.targetLine.material.color.set( this.color );
  41567. } else {
  41568. this.lightPlane.material.color.copy( this.light.color );
  41569. this.targetLine.material.color.copy( this.light.color );
  41570. }
  41571. this.targetLine.lookAt( _v2 );
  41572. this.targetLine.scale.z = _v3.length();
  41573. }
  41574. }
  41575. const _vector = /*@__PURE__*/ new Vector3();
  41576. const _camera = /*@__PURE__*/ new Camera();
  41577. /**
  41578. * This helps with visualizing what a camera contains in its frustum. It
  41579. * visualizes the frustum of a camera using a line segments.
  41580. *
  41581. * Based on frustum visualization in [lightgl.js shadowmap example](https://github.com/evanw/lightgl.js/blob/master/tests/shadowmap.html).
  41582. *
  41583. * `CameraHelper` must be a child of the scene.
  41584. *
  41585. * ```js
  41586. * const camera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 0.1, 1000 );
  41587. * const helper = new THREE.CameraHelper( camera );
  41588. * scene.add( helper );
  41589. * ```
  41590. *
  41591. * @augments LineSegments
  41592. */
  41593. class CameraHelper extends LineSegments {
  41594. /**
  41595. * Constructs a new arrow helper.
  41596. *
  41597. * @param {Camera} camera - The camera to visualize.
  41598. */
  41599. constructor( camera ) {
  41600. const geometry = new BufferGeometry();
  41601. const material = new LineBasicMaterial( { color: 0xffffff, vertexColors: true, toneMapped: false } );
  41602. const vertices = [];
  41603. const colors = [];
  41604. const pointMap = {};
  41605. // near
  41606. addLine( 'n1', 'n2' );
  41607. addLine( 'n2', 'n4' );
  41608. addLine( 'n4', 'n3' );
  41609. addLine( 'n3', 'n1' );
  41610. // far
  41611. addLine( 'f1', 'f2' );
  41612. addLine( 'f2', 'f4' );
  41613. addLine( 'f4', 'f3' );
  41614. addLine( 'f3', 'f1' );
  41615. // sides
  41616. addLine( 'n1', 'f1' );
  41617. addLine( 'n2', 'f2' );
  41618. addLine( 'n3', 'f3' );
  41619. addLine( 'n4', 'f4' );
  41620. // cone
  41621. addLine( 'p', 'n1' );
  41622. addLine( 'p', 'n2' );
  41623. addLine( 'p', 'n3' );
  41624. addLine( 'p', 'n4' );
  41625. // up
  41626. addLine( 'u1', 'u2' );
  41627. addLine( 'u2', 'u3' );
  41628. addLine( 'u3', 'u1' );
  41629. // target
  41630. addLine( 'c', 't' );
  41631. addLine( 'p', 'c' );
  41632. // cross
  41633. addLine( 'cn1', 'cn2' );
  41634. addLine( 'cn3', 'cn4' );
  41635. addLine( 'cf1', 'cf2' );
  41636. addLine( 'cf3', 'cf4' );
  41637. function addLine( a, b ) {
  41638. addPoint( a );
  41639. addPoint( b );
  41640. }
  41641. function addPoint( id ) {
  41642. vertices.push( 0, 0, 0 );
  41643. colors.push( 0, 0, 0 );
  41644. if ( pointMap[ id ] === undefined ) {
  41645. pointMap[ id ] = [];
  41646. }
  41647. pointMap[ id ].push( ( vertices.length / 3 ) - 1 );
  41648. }
  41649. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  41650. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  41651. super( geometry, material );
  41652. this.type = 'CameraHelper';
  41653. /**
  41654. * The camera being visualized.
  41655. *
  41656. * @type {Camera}
  41657. */
  41658. this.camera = camera;
  41659. if ( this.camera.updateProjectionMatrix ) this.camera.updateProjectionMatrix();
  41660. this.matrix = camera.matrixWorld;
  41661. this.matrixAutoUpdate = false;
  41662. /**
  41663. * This contains the points used to visualize the camera.
  41664. *
  41665. * @type {Object<string,Array<number>>}
  41666. */
  41667. this.pointMap = pointMap;
  41668. this.update();
  41669. // colors
  41670. const colorFrustum = new Color( 0xffaa00 );
  41671. const colorCone = new Color( 0xff0000 );
  41672. const colorUp = new Color( 0x00aaff );
  41673. const colorTarget = new Color( 0xffffff );
  41674. const colorCross = new Color( 0x333333 );
  41675. this.setColors( colorFrustum, colorCone, colorUp, colorTarget, colorCross );
  41676. }
  41677. /**
  41678. * Defines the colors of the helper.
  41679. *
  41680. * @param {Color} frustum - The frustum line color.
  41681. * @param {Color} cone - The cone line color.
  41682. * @param {Color} up - The up line color.
  41683. * @param {Color} target - The target line color.
  41684. * @param {Color} cross - The cross line color.
  41685. * @return {CameraHelper} A reference to this helper.
  41686. */
  41687. setColors( frustum, cone, up, target, cross ) {
  41688. const geometry = this.geometry;
  41689. const colorAttribute = geometry.getAttribute( 'color' );
  41690. // near
  41691. colorAttribute.setXYZ( 0, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 1, frustum.r, frustum.g, frustum.b ); // n1, n2
  41692. colorAttribute.setXYZ( 2, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 3, frustum.r, frustum.g, frustum.b ); // n2, n4
  41693. colorAttribute.setXYZ( 4, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 5, frustum.r, frustum.g, frustum.b ); // n4, n3
  41694. colorAttribute.setXYZ( 6, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 7, frustum.r, frustum.g, frustum.b ); // n3, n1
  41695. // far
  41696. colorAttribute.setXYZ( 8, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 9, frustum.r, frustum.g, frustum.b ); // f1, f2
  41697. colorAttribute.setXYZ( 10, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 11, frustum.r, frustum.g, frustum.b ); // f2, f4
  41698. colorAttribute.setXYZ( 12, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 13, frustum.r, frustum.g, frustum.b ); // f4, f3
  41699. colorAttribute.setXYZ( 14, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 15, frustum.r, frustum.g, frustum.b ); // f3, f1
  41700. // sides
  41701. colorAttribute.setXYZ( 16, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 17, frustum.r, frustum.g, frustum.b ); // n1, f1
  41702. colorAttribute.setXYZ( 18, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 19, frustum.r, frustum.g, frustum.b ); // n2, f2
  41703. colorAttribute.setXYZ( 20, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 21, frustum.r, frustum.g, frustum.b ); // n3, f3
  41704. colorAttribute.setXYZ( 22, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 23, frustum.r, frustum.g, frustum.b ); // n4, f4
  41705. // cone
  41706. colorAttribute.setXYZ( 24, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 25, cone.r, cone.g, cone.b ); // p, n1
  41707. colorAttribute.setXYZ( 26, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 27, cone.r, cone.g, cone.b ); // p, n2
  41708. colorAttribute.setXYZ( 28, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 29, cone.r, cone.g, cone.b ); // p, n3
  41709. colorAttribute.setXYZ( 30, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 31, cone.r, cone.g, cone.b ); // p, n4
  41710. // up
  41711. colorAttribute.setXYZ( 32, up.r, up.g, up.b ); colorAttribute.setXYZ( 33, up.r, up.g, up.b ); // u1, u2
  41712. colorAttribute.setXYZ( 34, up.r, up.g, up.b ); colorAttribute.setXYZ( 35, up.r, up.g, up.b ); // u2, u3
  41713. colorAttribute.setXYZ( 36, up.r, up.g, up.b ); colorAttribute.setXYZ( 37, up.r, up.g, up.b ); // u3, u1
  41714. // target
  41715. colorAttribute.setXYZ( 38, target.r, target.g, target.b ); colorAttribute.setXYZ( 39, target.r, target.g, target.b ); // c, t
  41716. colorAttribute.setXYZ( 40, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 41, cross.r, cross.g, cross.b ); // p, c
  41717. // cross
  41718. colorAttribute.setXYZ( 42, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 43, cross.r, cross.g, cross.b ); // cn1, cn2
  41719. colorAttribute.setXYZ( 44, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 45, cross.r, cross.g, cross.b ); // cn3, cn4
  41720. colorAttribute.setXYZ( 46, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 47, cross.r, cross.g, cross.b ); // cf1, cf2
  41721. colorAttribute.setXYZ( 48, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 49, cross.r, cross.g, cross.b ); // cf3, cf4
  41722. colorAttribute.needsUpdate = true;
  41723. return this;
  41724. }
  41725. /**
  41726. * Updates the helper based on the projection matrix of the camera.
  41727. */
  41728. update() {
  41729. const geometry = this.geometry;
  41730. const pointMap = this.pointMap;
  41731. const w = 1, h = 1;
  41732. let nearZ, farZ;
  41733. // we need just camera projection matrix inverse
  41734. // world matrix must be identity
  41735. _camera.projectionMatrixInverse.copy( this.camera.projectionMatrixInverse );
  41736. // Adjust z values based on coordinate system
  41737. if ( this.camera.reversedDepth === true ) {
  41738. nearZ = 1;
  41739. farZ = 0;
  41740. } else {
  41741. if ( this.camera.coordinateSystem === WebGLCoordinateSystem ) {
  41742. nearZ = -1;
  41743. farZ = 1;
  41744. } else if ( this.camera.coordinateSystem === WebGPUCoordinateSystem ) {
  41745. nearZ = 0;
  41746. farZ = 1;
  41747. } else {
  41748. throw new Error( 'THREE.CameraHelper.update(): Invalid coordinate system: ' + this.camera.coordinateSystem );
  41749. }
  41750. }
  41751. // center / target
  41752. setPoint( 'c', pointMap, geometry, _camera, 0, 0, nearZ );
  41753. setPoint( 't', pointMap, geometry, _camera, 0, 0, farZ );
  41754. // near
  41755. setPoint( 'n1', pointMap, geometry, _camera, - w, - h, nearZ );
  41756. setPoint( 'n2', pointMap, geometry, _camera, w, - h, nearZ );
  41757. setPoint( 'n3', pointMap, geometry, _camera, - w, h, nearZ );
  41758. setPoint( 'n4', pointMap, geometry, _camera, w, h, nearZ );
  41759. // far
  41760. setPoint( 'f1', pointMap, geometry, _camera, - w, - h, farZ );
  41761. setPoint( 'f2', pointMap, geometry, _camera, w, - h, farZ );
  41762. setPoint( 'f3', pointMap, geometry, _camera, - w, h, farZ );
  41763. setPoint( 'f4', pointMap, geometry, _camera, w, h, farZ );
  41764. // up
  41765. setPoint( 'u1', pointMap, geometry, _camera, w * 0.7, h * 1.1, nearZ );
  41766. setPoint( 'u2', pointMap, geometry, _camera, - w * 0.7, h * 1.1, nearZ );
  41767. setPoint( 'u3', pointMap, geometry, _camera, 0, h * 2, nearZ );
  41768. // cross
  41769. setPoint( 'cf1', pointMap, geometry, _camera, - w, 0, farZ );
  41770. setPoint( 'cf2', pointMap, geometry, _camera, w, 0, farZ );
  41771. setPoint( 'cf3', pointMap, geometry, _camera, 0, - h, farZ );
  41772. setPoint( 'cf4', pointMap, geometry, _camera, 0, h, farZ );
  41773. setPoint( 'cn1', pointMap, geometry, _camera, - w, 0, nearZ );
  41774. setPoint( 'cn2', pointMap, geometry, _camera, w, 0, nearZ );
  41775. setPoint( 'cn3', pointMap, geometry, _camera, 0, - h, nearZ );
  41776. setPoint( 'cn4', pointMap, geometry, _camera, 0, h, nearZ );
  41777. geometry.getAttribute( 'position' ).needsUpdate = true;
  41778. }
  41779. /**
  41780. * Frees the GPU-related resources allocated by this instance. Call this
  41781. * method whenever this instance is no longer used in your app.
  41782. */
  41783. dispose() {
  41784. this.geometry.dispose();
  41785. this.material.dispose();
  41786. }
  41787. }
  41788. function setPoint( point, pointMap, geometry, camera, x, y, z ) {
  41789. _vector.set( x, y, z ).unproject( camera );
  41790. const points = pointMap[ point ];
  41791. if ( points !== undefined ) {
  41792. const position = geometry.getAttribute( 'position' );
  41793. for ( let i = 0, l = points.length; i < l; i ++ ) {
  41794. position.setXYZ( points[ i ], _vector.x, _vector.y, _vector.z );
  41795. }
  41796. }
  41797. }
  41798. const _box = /*@__PURE__*/ new Box3();
  41799. /**
  41800. * Helper object to graphically show the world-axis-aligned bounding box
  41801. * around an object. The actual bounding box is handled with {@link Box3},
  41802. * this is just a visual helper for debugging. It can be automatically
  41803. * resized with {@link BoxHelper#update} when the object it's created from
  41804. * is transformed. Note that the object must have a geometry for this to work,
  41805. * so it won't work with sprites.
  41806. *
  41807. * ```js
  41808. * const sphere = new THREE.SphereGeometry();
  41809. * const object = new THREE.Mesh( sphere, new THREE.MeshBasicMaterial( 0xff0000 ) );
  41810. * const box = new THREE.BoxHelper( object, 0xffff00 );
  41811. * scene.add( box );
  41812. * ```
  41813. *
  41814. * @augments LineSegments
  41815. */
  41816. class BoxHelper extends LineSegments {
  41817. /**
  41818. * Constructs a new box helper.
  41819. *
  41820. * @param {Object3D} [object] - The 3D object to show the world-axis-aligned bounding box.
  41821. * @param {number|Color|string} [color=0xffff00] - The box's color.
  41822. */
  41823. constructor( object, color = 0xffff00 ) {
  41824. 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 ] );
  41825. const positions = new Float32Array( 8 * 3 );
  41826. const geometry = new BufferGeometry();
  41827. geometry.setIndex( new BufferAttribute( indices, 1 ) );
  41828. geometry.setAttribute( 'position', new BufferAttribute( positions, 3 ) );
  41829. super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  41830. /**
  41831. * The 3D object being visualized.
  41832. *
  41833. * @type {Object3D}
  41834. */
  41835. this.object = object;
  41836. this.type = 'BoxHelper';
  41837. this.matrixAutoUpdate = false;
  41838. this.update();
  41839. }
  41840. /**
  41841. * Updates the helper's geometry to match the dimensions of the object,
  41842. * including any children.
  41843. */
  41844. update() {
  41845. if ( this.object !== undefined ) {
  41846. _box.setFromObject( this.object );
  41847. }
  41848. if ( _box.isEmpty() ) return;
  41849. const min = _box.min;
  41850. const max = _box.max;
  41851. /*
  41852. 5____4
  41853. 1/___0/|
  41854. | 6__|_7
  41855. 2/___3/
  41856. 0: max.x, max.y, max.z
  41857. 1: min.x, max.y, max.z
  41858. 2: min.x, min.y, max.z
  41859. 3: max.x, min.y, max.z
  41860. 4: max.x, max.y, min.z
  41861. 5: min.x, max.y, min.z
  41862. 6: min.x, min.y, min.z
  41863. 7: max.x, min.y, min.z
  41864. */
  41865. const position = this.geometry.attributes.position;
  41866. const array = position.array;
  41867. array[ 0 ] = max.x; array[ 1 ] = max.y; array[ 2 ] = max.z;
  41868. array[ 3 ] = min.x; array[ 4 ] = max.y; array[ 5 ] = max.z;
  41869. array[ 6 ] = min.x; array[ 7 ] = min.y; array[ 8 ] = max.z;
  41870. array[ 9 ] = max.x; array[ 10 ] = min.y; array[ 11 ] = max.z;
  41871. array[ 12 ] = max.x; array[ 13 ] = max.y; array[ 14 ] = min.z;
  41872. array[ 15 ] = min.x; array[ 16 ] = max.y; array[ 17 ] = min.z;
  41873. array[ 18 ] = min.x; array[ 19 ] = min.y; array[ 20 ] = min.z;
  41874. array[ 21 ] = max.x; array[ 22 ] = min.y; array[ 23 ] = min.z;
  41875. position.needsUpdate = true;
  41876. this.geometry.computeBoundingSphere();
  41877. }
  41878. /**
  41879. * Updates the wireframe box for the passed object.
  41880. *
  41881. * @param {Object3D} object - The 3D object to create the helper for.
  41882. * @return {BoxHelper} A reference to this instance.
  41883. */
  41884. setFromObject( object ) {
  41885. this.object = object;
  41886. this.update();
  41887. return this;
  41888. }
  41889. copy( source, recursive ) {
  41890. super.copy( source, recursive );
  41891. this.object = source.object;
  41892. return this;
  41893. }
  41894. /**
  41895. * Frees the GPU-related resources allocated by this instance. Call this
  41896. * method whenever this instance is no longer used in your app.
  41897. */
  41898. dispose() {
  41899. this.geometry.dispose();
  41900. this.material.dispose();
  41901. }
  41902. }
  41903. /**
  41904. * A helper object to visualize an instance of {@link Box3}.
  41905. *
  41906. * ```js
  41907. * const box = new THREE.Box3();
  41908. * box.setFromCenterAndSize( new THREE.Vector3( 1, 1, 1 ), new THREE.Vector3( 2, 1, 3 ) );
  41909. *
  41910. * const helper = new THREE.Box3Helper( box, 0xffff00 );
  41911. * scene.add( helper )
  41912. * ```
  41913. *
  41914. * @augments LineSegments
  41915. */
  41916. class Box3Helper extends LineSegments {
  41917. /**
  41918. * Constructs a new box3 helper.
  41919. *
  41920. * @param {Box3} box - The box to visualize.
  41921. * @param {number|Color|string} [color=0xffff00] - The box's color.
  41922. */
  41923. constructor( box, color = 0xffff00 ) {
  41924. 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 ] );
  41925. 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 ];
  41926. const geometry = new BufferGeometry();
  41927. geometry.setIndex( new BufferAttribute( indices, 1 ) );
  41928. geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  41929. super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  41930. /**
  41931. * The box being visualized.
  41932. *
  41933. * @type {Box3}
  41934. */
  41935. this.box = box;
  41936. this.type = 'Box3Helper';
  41937. this.geometry.computeBoundingSphere();
  41938. }
  41939. updateMatrixWorld( force ) {
  41940. const box = this.box;
  41941. if ( box.isEmpty() ) return;
  41942. box.getCenter( this.position );
  41943. box.getSize( this.scale );
  41944. this.scale.multiplyScalar( 0.5 );
  41945. super.updateMatrixWorld( force );
  41946. }
  41947. /**
  41948. * Frees the GPU-related resources allocated by this instance. Call this
  41949. * method whenever this instance is no longer used in your app.
  41950. */
  41951. dispose() {
  41952. this.geometry.dispose();
  41953. this.material.dispose();
  41954. }
  41955. }
  41956. /**
  41957. * A helper object to visualize an instance of {@link Plane}.
  41958. *
  41959. * ```js
  41960. * const plane = new THREE.Plane( new THREE.Vector3( 1, 1, 0.2 ), 3 );
  41961. * const helper = new THREE.PlaneHelper( plane, 1, 0xffff00 );
  41962. * scene.add( helper );
  41963. * ```
  41964. *
  41965. * @augments Line
  41966. */
  41967. class PlaneHelper extends Line {
  41968. /**
  41969. * Constructs a new plane helper.
  41970. *
  41971. * @param {Plane} plane - The plane to be visualized.
  41972. * @param {number} [size=1] - The side length of plane helper.
  41973. * @param {number|Color|string} [hex=0xffff00] - The helper's color.
  41974. */
  41975. constructor( plane, size = 1, hex = 0xffff00 ) {
  41976. const color = hex;
  41977. 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 ];
  41978. const geometry = new BufferGeometry();
  41979. geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  41980. geometry.computeBoundingSphere();
  41981. super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  41982. this.type = 'PlaneHelper';
  41983. /**
  41984. * The plane being visualized.
  41985. *
  41986. * @type {Plane}
  41987. */
  41988. this.plane = plane;
  41989. /**
  41990. * The side length of plane helper.
  41991. *
  41992. * @type {number}
  41993. * @default 1
  41994. */
  41995. this.size = size;
  41996. const positions2 = [ 1, 1, 0, -1, 1, 0, -1, -1, 0, 1, 1, 0, -1, -1, 0, 1, -1, 0 ];
  41997. const geometry2 = new BufferGeometry();
  41998. geometry2.setAttribute( 'position', new Float32BufferAttribute( positions2, 3 ) );
  41999. geometry2.computeBoundingSphere();
  42000. this.add( new Mesh( geometry2, new MeshBasicMaterial( { color: color, opacity: 0.2, transparent: true, depthWrite: false, toneMapped: false } ) ) );
  42001. }
  42002. updateMatrixWorld( force ) {
  42003. this.position.set( 0, 0, 0 );
  42004. this.scale.set( 0.5 * this.size, 0.5 * this.size, 1 );
  42005. this.lookAt( this.plane.normal );
  42006. this.translateZ( - this.plane.constant );
  42007. super.updateMatrixWorld( force );
  42008. }
  42009. /**
  42010. * Updates the helper to match the position and direction of the
  42011. * light being visualized.
  42012. */
  42013. dispose() {
  42014. this.geometry.dispose();
  42015. this.material.dispose();
  42016. this.children[ 0 ].geometry.dispose();
  42017. this.children[ 0 ].material.dispose();
  42018. }
  42019. }
  42020. const _axis = /*@__PURE__*/ new Vector3();
  42021. let _lineGeometry, _coneGeometry;
  42022. /**
  42023. * An 3D arrow object for visualizing directions.
  42024. *
  42025. * ```js
  42026. * const dir = new THREE.Vector3( 1, 2, 0 );
  42027. *
  42028. * //normalize the direction vector (convert to vector of length 1)
  42029. * dir.normalize();
  42030. *
  42031. * const origin = new THREE.Vector3( 0, 0, 0 );
  42032. * const length = 1;
  42033. * const hex = 0xffff00;
  42034. *
  42035. * const arrowHelper = new THREE.ArrowHelper( dir, origin, length, hex );
  42036. * scene.add( arrowHelper );
  42037. * ```
  42038. *
  42039. * @augments Object3D
  42040. */
  42041. class ArrowHelper extends Object3D {
  42042. /**
  42043. * Constructs a new arrow helper.
  42044. *
  42045. * @param {Vector3} [dir=(0, 0, 1)] - The (normalized) direction vector.
  42046. * @param {Vector3} [origin=(0, 0, 0)] - Point at which the arrow starts.
  42047. * @param {number} [length=1] - Length of the arrow in world units.
  42048. * @param {(number|Color|string)} [color=0xffff00] - Color of the arrow.
  42049. * @param {number} [headLength=length*0.2] - The length of the head of the arrow.
  42050. * @param {number} [headWidth=headLength*0.2] - The width of the head of the arrow.
  42051. */
  42052. 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 ) {
  42053. super();
  42054. this.type = 'ArrowHelper';
  42055. if ( _lineGeometry === undefined ) {
  42056. _lineGeometry = new BufferGeometry();
  42057. _lineGeometry.setAttribute( 'position', new Float32BufferAttribute( [ 0, 0, 0, 0, 1, 0 ], 3 ) );
  42058. _coneGeometry = new ConeGeometry( 0.5, 1, 5, 1 );
  42059. _coneGeometry.translate( 0, -0.5, 0 );
  42060. }
  42061. this.position.copy( origin );
  42062. /**
  42063. * The line part of the arrow helper.
  42064. *
  42065. * @type {Line}
  42066. */
  42067. this.line = new Line( _lineGeometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  42068. this.line.matrixAutoUpdate = false;
  42069. this.add( this.line );
  42070. /**
  42071. * The cone part of the arrow helper.
  42072. *
  42073. * @type {Mesh}
  42074. */
  42075. this.cone = new Mesh( _coneGeometry, new MeshBasicMaterial( { color: color, toneMapped: false } ) );
  42076. this.cone.matrixAutoUpdate = false;
  42077. this.add( this.cone );
  42078. this.setDirection( dir );
  42079. this.setLength( length, headLength, headWidth );
  42080. }
  42081. /**
  42082. * Sets the direction of the helper.
  42083. *
  42084. * @param {Vector3} dir - The normalized direction vector.
  42085. */
  42086. setDirection( dir ) {
  42087. // dir is assumed to be normalized
  42088. if ( dir.y > 0.99999 ) {
  42089. this.quaternion.set( 0, 0, 0, 1 );
  42090. } else if ( dir.y < -0.99999 ) {
  42091. this.quaternion.set( 1, 0, 0, 0 );
  42092. } else {
  42093. _axis.set( dir.z, 0, - dir.x ).normalize();
  42094. const radians = Math.acos( dir.y );
  42095. this.quaternion.setFromAxisAngle( _axis, radians );
  42096. }
  42097. }
  42098. /**
  42099. * Sets the length of the helper.
  42100. *
  42101. * @param {number} length - Length of the arrow in world units.
  42102. * @param {number} [headLength=length*0.2] - The length of the head of the arrow.
  42103. * @param {number} [headWidth=headLength*0.2] - The width of the head of the arrow.
  42104. */
  42105. setLength( length, headLength = length * 0.2, headWidth = headLength * 0.2 ) {
  42106. this.line.scale.set( 1, Math.max( 0.0001, length - headLength ), 1 ); // see #17458
  42107. this.line.updateMatrix();
  42108. this.cone.scale.set( headWidth, headLength, headWidth );
  42109. this.cone.position.y = length;
  42110. this.cone.updateMatrix();
  42111. }
  42112. /**
  42113. * Sets the color of the helper.
  42114. *
  42115. * @param {number|Color|string} color - The color to set.
  42116. */
  42117. setColor( color ) {
  42118. this.line.material.color.set( color );
  42119. this.cone.material.color.set( color );
  42120. }
  42121. copy( source ) {
  42122. super.copy( source, false );
  42123. this.line.copy( source.line );
  42124. this.cone.copy( source.cone );
  42125. return this;
  42126. }
  42127. /**
  42128. * Frees the GPU-related resources allocated by this instance. Call this
  42129. * method whenever this instance is no longer used in your app.
  42130. */
  42131. dispose() {
  42132. this.line.geometry.dispose();
  42133. this.line.material.dispose();
  42134. this.cone.geometry.dispose();
  42135. this.cone.material.dispose();
  42136. }
  42137. }
  42138. /**
  42139. * An axis object to visualize the 3 axes in a simple way.
  42140. * The X axis is red. The Y axis is green. The Z axis is blue.
  42141. *
  42142. * ```js
  42143. * const axesHelper = new THREE.AxesHelper( 5 );
  42144. * scene.add( axesHelper );
  42145. * ```
  42146. *
  42147. * @augments LineSegments
  42148. */
  42149. class AxesHelper extends LineSegments {
  42150. /**
  42151. * Constructs a new axes helper.
  42152. *
  42153. * @param {number} [size=1] - Size of the lines representing the axes.
  42154. */
  42155. constructor( size = 1 ) {
  42156. const vertices = [
  42157. 0, 0, 0, size, 0, 0,
  42158. 0, 0, 0, 0, size, 0,
  42159. 0, 0, 0, 0, 0, size
  42160. ];
  42161. const colors = [
  42162. 1, 0, 0, 1, 0.6, 0,
  42163. 0, 1, 0, 0.6, 1, 0,
  42164. 0, 0, 1, 0, 0.6, 1
  42165. ];
  42166. const geometry = new BufferGeometry();
  42167. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  42168. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  42169. const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
  42170. super( geometry, material );
  42171. this.type = 'AxesHelper';
  42172. }
  42173. /**
  42174. * Defines the colors of the axes helper.
  42175. *
  42176. * @param {number|Color|string} xAxisColor - The color for the x axis.
  42177. * @param {number|Color|string} yAxisColor - The color for the y axis.
  42178. * @param {number|Color|string} zAxisColor - The color for the z axis.
  42179. * @return {AxesHelper} A reference to this axes helper.
  42180. */
  42181. setColors( xAxisColor, yAxisColor, zAxisColor ) {
  42182. const color = new Color();
  42183. const array = this.geometry.attributes.color.array;
  42184. color.set( xAxisColor );
  42185. color.toArray( array, 0 );
  42186. color.toArray( array, 3 );
  42187. color.set( yAxisColor );
  42188. color.toArray( array, 6 );
  42189. color.toArray( array, 9 );
  42190. color.set( zAxisColor );
  42191. color.toArray( array, 12 );
  42192. color.toArray( array, 15 );
  42193. this.geometry.attributes.color.needsUpdate = true;
  42194. return this;
  42195. }
  42196. /**
  42197. * Frees the GPU-related resources allocated by this instance. Call this
  42198. * method whenever this instance is no longer used in your app.
  42199. */
  42200. dispose() {
  42201. this.geometry.dispose();
  42202. this.material.dispose();
  42203. }
  42204. }
  42205. /**
  42206. * This class is used to convert a series of paths to an array of
  42207. * shapes. It is specifically used in context of fonts and SVG.
  42208. */
  42209. class ShapePath {
  42210. /**
  42211. * Constructs a new shape path.
  42212. */
  42213. constructor() {
  42214. this.type = 'ShapePath';
  42215. /**
  42216. * The color of the shape.
  42217. *
  42218. * @type {Color}
  42219. */
  42220. this.color = new Color();
  42221. /**
  42222. * The paths that have been generated for this shape.
  42223. *
  42224. * @type {Array<Path>}
  42225. * @default null
  42226. */
  42227. this.subPaths = [];
  42228. /**
  42229. * The current path that is being generated.
  42230. *
  42231. * @type {?Path}
  42232. * @default null
  42233. */
  42234. this.currentPath = null;
  42235. }
  42236. /**
  42237. * Creates a new path and moves it current point to the given one.
  42238. *
  42239. * @param {number} x - The x coordinate.
  42240. * @param {number} y - The y coordinate.
  42241. * @return {ShapePath} A reference to this shape path.
  42242. */
  42243. moveTo( x, y ) {
  42244. this.currentPath = new Path();
  42245. this.subPaths.push( this.currentPath );
  42246. this.currentPath.moveTo( x, y );
  42247. return this;
  42248. }
  42249. /**
  42250. * Adds an instance of {@link LineCurve} to the path by connecting
  42251. * the current point with the given one.
  42252. *
  42253. * @param {number} x - The x coordinate of the end point.
  42254. * @param {number} y - The y coordinate of the end point.
  42255. * @return {ShapePath} A reference to this shape path.
  42256. */
  42257. lineTo( x, y ) {
  42258. this.currentPath.lineTo( x, y );
  42259. return this;
  42260. }
  42261. /**
  42262. * Adds an instance of {@link QuadraticBezierCurve} to the path by connecting
  42263. * the current point with the given one.
  42264. *
  42265. * @param {number} aCPx - The x coordinate of the control point.
  42266. * @param {number} aCPy - The y coordinate of the control point.
  42267. * @param {number} aX - The x coordinate of the end point.
  42268. * @param {number} aY - The y coordinate of the end point.
  42269. * @return {ShapePath} A reference to this shape path.
  42270. */
  42271. quadraticCurveTo( aCPx, aCPy, aX, aY ) {
  42272. this.currentPath.quadraticCurveTo( aCPx, aCPy, aX, aY );
  42273. return this;
  42274. }
  42275. /**
  42276. * Adds an instance of {@link CubicBezierCurve} to the path by connecting
  42277. * the current point with the given one.
  42278. *
  42279. * @param {number} aCP1x - The x coordinate of the first control point.
  42280. * @param {number} aCP1y - The y coordinate of the first control point.
  42281. * @param {number} aCP2x - The x coordinate of the second control point.
  42282. * @param {number} aCP2y - The y coordinate of the second control point.
  42283. * @param {number} aX - The x coordinate of the end point.
  42284. * @param {number} aY - The y coordinate of the end point.
  42285. * @return {ShapePath} A reference to this shape path.
  42286. */
  42287. bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) {
  42288. this.currentPath.bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY );
  42289. return this;
  42290. }
  42291. /**
  42292. * Adds an instance of {@link SplineCurve} to the path by connecting
  42293. * the current point with the given list of points.
  42294. *
  42295. * @param {Array<Vector2>} pts - An array of points in 2D space.
  42296. * @return {ShapePath} A reference to this shape path.
  42297. */
  42298. splineThru( pts ) {
  42299. this.currentPath.splineThru( pts );
  42300. return this;
  42301. }
  42302. /**
  42303. * Converts the paths into an array of shapes.
  42304. *
  42305. * @param {boolean} isCCW - By default solid shapes are defined clockwise (CW) and holes are defined counterclockwise (CCW).
  42306. * If this flag is set to `true`, then those are flipped.
  42307. * @return {Array<Shape>} An array of shapes.
  42308. */
  42309. toShapes( isCCW ) {
  42310. function toShapesNoHoles( inSubpaths ) {
  42311. const shapes = [];
  42312. for ( let i = 0, l = inSubpaths.length; i < l; i ++ ) {
  42313. const tmpPath = inSubpaths[ i ];
  42314. const tmpShape = new Shape();
  42315. tmpShape.curves = tmpPath.curves;
  42316. shapes.push( tmpShape );
  42317. }
  42318. return shapes;
  42319. }
  42320. function isPointInsidePolygon( inPt, inPolygon ) {
  42321. const polyLen = inPolygon.length;
  42322. // inPt on polygon contour => immediate success or
  42323. // toggling of inside/outside at every single! intersection point of an edge
  42324. // with the horizontal line through inPt, left of inPt
  42325. // not counting lowerY endpoints of edges and whole edges on that line
  42326. let inside = false;
  42327. for ( let p = polyLen - 1, q = 0; q < polyLen; p = q ++ ) {
  42328. let edgeLowPt = inPolygon[ p ];
  42329. let edgeHighPt = inPolygon[ q ];
  42330. let edgeDx = edgeHighPt.x - edgeLowPt.x;
  42331. let edgeDy = edgeHighPt.y - edgeLowPt.y;
  42332. if ( Math.abs( edgeDy ) > Number.EPSILON ) {
  42333. // not parallel
  42334. if ( edgeDy < 0 ) {
  42335. edgeLowPt = inPolygon[ q ]; edgeDx = - edgeDx;
  42336. edgeHighPt = inPolygon[ p ]; edgeDy = - edgeDy;
  42337. }
  42338. if ( ( inPt.y < edgeLowPt.y ) || ( inPt.y > edgeHighPt.y ) ) continue;
  42339. if ( inPt.y === edgeLowPt.y ) {
  42340. if ( inPt.x === edgeLowPt.x ) return true; // inPt is on contour ?
  42341. // continue; // no intersection or edgeLowPt => doesn't count !!!
  42342. } else {
  42343. const perpEdge = edgeDy * ( inPt.x - edgeLowPt.x ) - edgeDx * ( inPt.y - edgeLowPt.y );
  42344. if ( perpEdge === 0 ) return true; // inPt is on contour ?
  42345. if ( perpEdge < 0 ) continue;
  42346. inside = ! inside; // true intersection left of inPt
  42347. }
  42348. } else {
  42349. // parallel or collinear
  42350. if ( inPt.y !== edgeLowPt.y ) continue; // parallel
  42351. // edge lies on the same horizontal line as inPt
  42352. if ( ( ( edgeHighPt.x <= inPt.x ) && ( inPt.x <= edgeLowPt.x ) ) ||
  42353. ( ( edgeLowPt.x <= inPt.x ) && ( inPt.x <= edgeHighPt.x ) ) ) return true; // inPt: Point on contour !
  42354. // continue;
  42355. }
  42356. }
  42357. return inside;
  42358. }
  42359. const isClockWise = ShapeUtils.isClockWise;
  42360. const subPaths = this.subPaths;
  42361. if ( subPaths.length === 0 ) return [];
  42362. let solid, tmpPath, tmpShape;
  42363. const shapes = [];
  42364. if ( subPaths.length === 1 ) {
  42365. tmpPath = subPaths[ 0 ];
  42366. tmpShape = new Shape();
  42367. tmpShape.curves = tmpPath.curves;
  42368. shapes.push( tmpShape );
  42369. return shapes;
  42370. }
  42371. let holesFirst = ! isClockWise( subPaths[ 0 ].getPoints() );
  42372. holesFirst = isCCW ? ! holesFirst : holesFirst;
  42373. // log("Holes first", holesFirst);
  42374. const betterShapeHoles = [];
  42375. const newShapes = [];
  42376. let newShapeHoles = [];
  42377. let mainIdx = 0;
  42378. let tmpPoints;
  42379. newShapes[ mainIdx ] = undefined;
  42380. newShapeHoles[ mainIdx ] = [];
  42381. for ( let i = 0, l = subPaths.length; i < l; i ++ ) {
  42382. tmpPath = subPaths[ i ];
  42383. tmpPoints = tmpPath.getPoints();
  42384. solid = isClockWise( tmpPoints );
  42385. solid = isCCW ? ! solid : solid;
  42386. if ( solid ) {
  42387. if ( ( ! holesFirst ) && ( newShapes[ mainIdx ] ) ) mainIdx ++;
  42388. newShapes[ mainIdx ] = { s: new Shape(), p: tmpPoints };
  42389. newShapes[ mainIdx ].s.curves = tmpPath.curves;
  42390. if ( holesFirst ) mainIdx ++;
  42391. newShapeHoles[ mainIdx ] = [];
  42392. //log('cw', i);
  42393. } else {
  42394. newShapeHoles[ mainIdx ].push( { h: tmpPath, p: tmpPoints[ 0 ] } );
  42395. //log('ccw', i);
  42396. }
  42397. }
  42398. // only Holes? -> probably all Shapes with wrong orientation
  42399. if ( ! newShapes[ 0 ] ) return toShapesNoHoles( subPaths );
  42400. if ( newShapes.length > 1 ) {
  42401. let ambiguous = false;
  42402. let toChange = 0;
  42403. for ( let sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) {
  42404. betterShapeHoles[ sIdx ] = [];
  42405. }
  42406. for ( let sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) {
  42407. const sho = newShapeHoles[ sIdx ];
  42408. for ( let hIdx = 0; hIdx < sho.length; hIdx ++ ) {
  42409. const ho = sho[ hIdx ];
  42410. let hole_unassigned = true;
  42411. for ( let s2Idx = 0; s2Idx < newShapes.length; s2Idx ++ ) {
  42412. if ( isPointInsidePolygon( ho.p, newShapes[ s2Idx ].p ) ) {
  42413. if ( sIdx !== s2Idx ) toChange ++;
  42414. if ( hole_unassigned ) {
  42415. hole_unassigned = false;
  42416. betterShapeHoles[ s2Idx ].push( ho );
  42417. } else {
  42418. ambiguous = true;
  42419. }
  42420. }
  42421. }
  42422. if ( hole_unassigned ) {
  42423. betterShapeHoles[ sIdx ].push( ho );
  42424. }
  42425. }
  42426. }
  42427. if ( toChange > 0 && ambiguous === false ) {
  42428. newShapeHoles = betterShapeHoles;
  42429. }
  42430. }
  42431. let tmpHoles;
  42432. for ( let i = 0, il = newShapes.length; i < il; i ++ ) {
  42433. tmpShape = newShapes[ i ].s;
  42434. shapes.push( tmpShape );
  42435. tmpHoles = newShapeHoles[ i ];
  42436. for ( let j = 0, jl = tmpHoles.length; j < jl; j ++ ) {
  42437. tmpShape.holes.push( tmpHoles[ j ].h );
  42438. }
  42439. }
  42440. //log("shape", shapes);
  42441. return shapes;
  42442. }
  42443. }
  42444. /**
  42445. * Abstract base class for controls.
  42446. *
  42447. * @abstract
  42448. * @augments EventDispatcher
  42449. */
  42450. class Controls extends EventDispatcher {
  42451. /**
  42452. * Constructs a new controls instance.
  42453. *
  42454. * @param {Object3D} object - The object that is managed by the controls.
  42455. * @param {?HTMLElement} domElement - The HTML element used for event listeners.
  42456. */
  42457. constructor( object, domElement = null ) {
  42458. super();
  42459. /**
  42460. * The object that is managed by the controls.
  42461. *
  42462. * @type {Object3D}
  42463. */
  42464. this.object = object;
  42465. /**
  42466. * The HTML element used for event listeners.
  42467. *
  42468. * @type {?HTMLElement}
  42469. * @default null
  42470. */
  42471. this.domElement = domElement;
  42472. /**
  42473. * Whether the controls responds to user input or not.
  42474. *
  42475. * @type {boolean}
  42476. * @default true
  42477. */
  42478. this.enabled = true;
  42479. /**
  42480. * The internal state of the controls.
  42481. *
  42482. * @type {number}
  42483. * @default -1
  42484. */
  42485. this.state = -1;
  42486. /**
  42487. * This object defines the keyboard input of the controls.
  42488. *
  42489. * @type {Object}
  42490. */
  42491. this.keys = {};
  42492. /**
  42493. * This object defines what type of actions are assigned to the available mouse buttons.
  42494. * It depends on the control implementation what kind of mouse buttons and actions are supported.
  42495. *
  42496. * @type {{LEFT: ?number, MIDDLE: ?number, RIGHT: ?number}}
  42497. */
  42498. this.mouseButtons = { LEFT: null, MIDDLE: null, RIGHT: null };
  42499. /**
  42500. * This object defines what type of actions are assigned to what kind of touch interaction.
  42501. * It depends on the control implementation what kind of touch interaction and actions are supported.
  42502. *
  42503. * @type {{ONE: ?number, TWO: ?number}}
  42504. */
  42505. this.touches = { ONE: null, TWO: null };
  42506. }
  42507. /**
  42508. * Connects the controls to the DOM. This method has so called "side effects" since
  42509. * it adds the module's event listeners to the DOM.
  42510. *
  42511. * @param {HTMLElement} element - The DOM element to connect to.
  42512. */
  42513. connect( element ) {
  42514. if ( element === undefined ) {
  42515. warn( 'Controls: connect() now requires an element.' ); // @deprecated, the warning can be removed with r185
  42516. return;
  42517. }
  42518. if ( this.domElement !== null ) this.disconnect();
  42519. this.domElement = element;
  42520. }
  42521. /**
  42522. * Disconnects the controls from the DOM.
  42523. */
  42524. disconnect() {}
  42525. /**
  42526. * Call this method if you no longer want use to the controls. It frees all internal
  42527. * resources and removes all event listeners.
  42528. */
  42529. dispose() {}
  42530. /**
  42531. * Controls should implement this method if they have to update their internal state
  42532. * per simulation step.
  42533. *
  42534. * @param {number} [delta] - The time delta in seconds.
  42535. */
  42536. update( /* delta */ ) {}
  42537. }
  42538. /**
  42539. * Scales the texture as large as possible within its surface without cropping
  42540. * or stretching the texture. The method preserves the original aspect ratio of
  42541. * the texture. Akin to CSS `object-fit: contain`
  42542. *
  42543. * @param {Texture} texture - The texture.
  42544. * @param {number} aspect - The texture's aspect ratio.
  42545. * @return {Texture} The updated texture.
  42546. */
  42547. function contain( texture, aspect ) {
  42548. const imageAspect = ( texture.image && texture.image.width ) ? texture.image.width / texture.image.height : 1;
  42549. if ( imageAspect > aspect ) {
  42550. texture.repeat.x = 1;
  42551. texture.repeat.y = imageAspect / aspect;
  42552. texture.offset.x = 0;
  42553. texture.offset.y = ( 1 - texture.repeat.y ) / 2;
  42554. } else {
  42555. texture.repeat.x = aspect / imageAspect;
  42556. texture.repeat.y = 1;
  42557. texture.offset.x = ( 1 - texture.repeat.x ) / 2;
  42558. texture.offset.y = 0;
  42559. }
  42560. return texture;
  42561. }
  42562. /**
  42563. * Scales the texture to the smallest possible size to fill the surface, leaving
  42564. * no empty space. The method preserves the original aspect ratio of the texture.
  42565. * Akin to CSS `object-fit: cover`.
  42566. *
  42567. * @param {Texture} texture - The texture.
  42568. * @param {number} aspect - The texture's aspect ratio.
  42569. * @return {Texture} The updated texture.
  42570. */
  42571. function cover( texture, aspect ) {
  42572. const imageAspect = ( texture.image && texture.image.width ) ? texture.image.width / texture.image.height : 1;
  42573. if ( imageAspect > aspect ) {
  42574. texture.repeat.x = aspect / imageAspect;
  42575. texture.repeat.y = 1;
  42576. texture.offset.x = ( 1 - texture.repeat.x ) / 2;
  42577. texture.offset.y = 0;
  42578. } else {
  42579. texture.repeat.x = 1;
  42580. texture.repeat.y = imageAspect / aspect;
  42581. texture.offset.x = 0;
  42582. texture.offset.y = ( 1 - texture.repeat.y ) / 2;
  42583. }
  42584. return texture;
  42585. }
  42586. /**
  42587. * Configures the texture to the default transformation. Akin to CSS `object-fit: fill`.
  42588. *
  42589. * @param {Texture} texture - The texture.
  42590. * @return {Texture} The updated texture.
  42591. */
  42592. function fill( texture ) {
  42593. texture.repeat.x = 1;
  42594. texture.repeat.y = 1;
  42595. texture.offset.x = 0;
  42596. texture.offset.y = 0;
  42597. return texture;
  42598. }
  42599. /**
  42600. * Determines how many bytes must be used to represent the texture.
  42601. *
  42602. * @param {number} width - The width of the texture.
  42603. * @param {number} height - The height of the texture.
  42604. * @param {number} format - The texture's format.
  42605. * @param {number} type - The texture's type.
  42606. * @return {number} The byte length.
  42607. */
  42608. function getByteLength( width, height, format, type ) {
  42609. const typeByteLength = getTextureTypeByteLength( type );
  42610. switch ( format ) {
  42611. // https://registry.khronos.org/OpenGL-Refpages/es3.0/html/glTexImage2D.xhtml
  42612. case AlphaFormat:
  42613. return width * height;
  42614. case RedFormat:
  42615. return ( ( width * height ) / typeByteLength.components ) * typeByteLength.byteLength;
  42616. case RedIntegerFormat:
  42617. return ( ( width * height ) / typeByteLength.components ) * typeByteLength.byteLength;
  42618. case RGFormat:
  42619. return ( ( width * height * 2 ) / typeByteLength.components ) * typeByteLength.byteLength;
  42620. case RGIntegerFormat:
  42621. return ( ( width * height * 2 ) / typeByteLength.components ) * typeByteLength.byteLength;
  42622. case RGBFormat:
  42623. return ( ( width * height * 3 ) / typeByteLength.components ) * typeByteLength.byteLength;
  42624. case RGBAFormat:
  42625. return ( ( width * height * 4 ) / typeByteLength.components ) * typeByteLength.byteLength;
  42626. case RGBAIntegerFormat:
  42627. return ( ( width * height * 4 ) / typeByteLength.components ) * typeByteLength.byteLength;
  42628. // https://registry.khronos.org/webgl/extensions/WEBGL_compressed_texture_s3tc_srgb/
  42629. case RGB_S3TC_DXT1_Format:
  42630. case RGBA_S3TC_DXT1_Format:
  42631. return Math.floor( ( width + 3 ) / 4 ) * Math.floor( ( height + 3 ) / 4 ) * 8;
  42632. case RGBA_S3TC_DXT3_Format:
  42633. case RGBA_S3TC_DXT5_Format:
  42634. return Math.floor( ( width + 3 ) / 4 ) * Math.floor( ( height + 3 ) / 4 ) * 16;
  42635. // https://registry.khronos.org/webgl/extensions/WEBGL_compressed_texture_pvrtc/
  42636. case RGB_PVRTC_2BPPV1_Format:
  42637. case RGBA_PVRTC_2BPPV1_Format:
  42638. return ( Math.max( width, 16 ) * Math.max( height, 8 ) ) / 4;
  42639. case RGB_PVRTC_4BPPV1_Format:
  42640. case RGBA_PVRTC_4BPPV1_Format:
  42641. return ( Math.max( width, 8 ) * Math.max( height, 8 ) ) / 2;
  42642. // https://registry.khronos.org/webgl/extensions/WEBGL_compressed_texture_etc/
  42643. case RGB_ETC1_Format:
  42644. case RGB_ETC2_Format:
  42645. case R11_EAC_Format:
  42646. case SIGNED_R11_EAC_Format:
  42647. return Math.floor( ( width + 3 ) / 4 ) * Math.floor( ( height + 3 ) / 4 ) * 8;
  42648. case RGBA_ETC2_EAC_Format:
  42649. case RG11_EAC_Format:
  42650. case SIGNED_RG11_EAC_Format:
  42651. return Math.floor( ( width + 3 ) / 4 ) * Math.floor( ( height + 3 ) / 4 ) * 16;
  42652. // https://registry.khronos.org/webgl/extensions/WEBGL_compressed_texture_astc/
  42653. case RGBA_ASTC_4x4_Format:
  42654. return Math.floor( ( width + 3 ) / 4 ) * Math.floor( ( height + 3 ) / 4 ) * 16;
  42655. case RGBA_ASTC_5x4_Format:
  42656. return Math.floor( ( width + 4 ) / 5 ) * Math.floor( ( height + 3 ) / 4 ) * 16;
  42657. case RGBA_ASTC_5x5_Format:
  42658. return Math.floor( ( width + 4 ) / 5 ) * Math.floor( ( height + 4 ) / 5 ) * 16;
  42659. case RGBA_ASTC_6x5_Format:
  42660. return Math.floor( ( width + 5 ) / 6 ) * Math.floor( ( height + 4 ) / 5 ) * 16;
  42661. case RGBA_ASTC_6x6_Format:
  42662. return Math.floor( ( width + 5 ) / 6 ) * Math.floor( ( height + 5 ) / 6 ) * 16;
  42663. case RGBA_ASTC_8x5_Format:
  42664. return Math.floor( ( width + 7 ) / 8 ) * Math.floor( ( height + 4 ) / 5 ) * 16;
  42665. case RGBA_ASTC_8x6_Format:
  42666. return Math.floor( ( width + 7 ) / 8 ) * Math.floor( ( height + 5 ) / 6 ) * 16;
  42667. case RGBA_ASTC_8x8_Format:
  42668. return Math.floor( ( width + 7 ) / 8 ) * Math.floor( ( height + 7 ) / 8 ) * 16;
  42669. case RGBA_ASTC_10x5_Format:
  42670. return Math.floor( ( width + 9 ) / 10 ) * Math.floor( ( height + 4 ) / 5 ) * 16;
  42671. case RGBA_ASTC_10x6_Format:
  42672. return Math.floor( ( width + 9 ) / 10 ) * Math.floor( ( height + 5 ) / 6 ) * 16;
  42673. case RGBA_ASTC_10x8_Format:
  42674. return Math.floor( ( width + 9 ) / 10 ) * Math.floor( ( height + 7 ) / 8 ) * 16;
  42675. case RGBA_ASTC_10x10_Format:
  42676. return Math.floor( ( width + 9 ) / 10 ) * Math.floor( ( height + 9 ) / 10 ) * 16;
  42677. case RGBA_ASTC_12x10_Format:
  42678. return Math.floor( ( width + 11 ) / 12 ) * Math.floor( ( height + 9 ) / 10 ) * 16;
  42679. case RGBA_ASTC_12x12_Format:
  42680. return Math.floor( ( width + 11 ) / 12 ) * Math.floor( ( height + 11 ) / 12 ) * 16;
  42681. // https://registry.khronos.org/webgl/extensions/EXT_texture_compression_bptc/
  42682. case RGBA_BPTC_Format:
  42683. case RGB_BPTC_SIGNED_Format:
  42684. case RGB_BPTC_UNSIGNED_Format:
  42685. return Math.ceil( width / 4 ) * Math.ceil( height / 4 ) * 16;
  42686. // https://registry.khronos.org/webgl/extensions/EXT_texture_compression_rgtc/
  42687. case RED_RGTC1_Format:
  42688. case SIGNED_RED_RGTC1_Format:
  42689. return Math.ceil( width / 4 ) * Math.ceil( height / 4 ) * 8;
  42690. case RED_GREEN_RGTC2_Format:
  42691. case SIGNED_RED_GREEN_RGTC2_Format:
  42692. return Math.ceil( width / 4 ) * Math.ceil( height / 4 ) * 16;
  42693. }
  42694. throw new Error(
  42695. `Unable to determine texture byte length for ${format} format.`,
  42696. );
  42697. }
  42698. function getTextureTypeByteLength( type ) {
  42699. switch ( type ) {
  42700. case UnsignedByteType:
  42701. case ByteType:
  42702. return { byteLength: 1, components: 1 };
  42703. case UnsignedShortType:
  42704. case ShortType:
  42705. case HalfFloatType:
  42706. return { byteLength: 2, components: 1 };
  42707. case UnsignedShort4444Type:
  42708. case UnsignedShort5551Type:
  42709. return { byteLength: 2, components: 4 };
  42710. case UnsignedIntType:
  42711. case IntType:
  42712. case FloatType:
  42713. return { byteLength: 4, components: 1 };
  42714. case UnsignedInt5999Type:
  42715. case UnsignedInt101111Type:
  42716. return { byteLength: 4, components: 3 };
  42717. }
  42718. throw new Error( `Unknown texture type ${type}.` );
  42719. }
  42720. /**
  42721. * A class containing utility functions for textures.
  42722. *
  42723. * @hideconstructor
  42724. */
  42725. class TextureUtils {
  42726. /**
  42727. * Scales the texture as large as possible within its surface without cropping
  42728. * or stretching the texture. The method preserves the original aspect ratio of
  42729. * the texture. Akin to CSS `object-fit: contain`
  42730. *
  42731. * @param {Texture} texture - The texture.
  42732. * @param {number} aspect - The texture's aspect ratio.
  42733. * @return {Texture} The updated texture.
  42734. */
  42735. static contain( texture, aspect ) {
  42736. return contain( texture, aspect );
  42737. }
  42738. /**
  42739. * Scales the texture to the smallest possible size to fill the surface, leaving
  42740. * no empty space. The method preserves the original aspect ratio of the texture.
  42741. * Akin to CSS `object-fit: cover`.
  42742. *
  42743. * @param {Texture} texture - The texture.
  42744. * @param {number} aspect - The texture's aspect ratio.
  42745. * @return {Texture} The updated texture.
  42746. */
  42747. static cover( texture, aspect ) {
  42748. return cover( texture, aspect );
  42749. }
  42750. /**
  42751. * Configures the texture to the default transformation. Akin to CSS `object-fit: fill`.
  42752. *
  42753. * @param {Texture} texture - The texture.
  42754. * @return {Texture} The updated texture.
  42755. */
  42756. static fill( texture ) {
  42757. return fill( texture );
  42758. }
  42759. /**
  42760. * Determines how many bytes must be used to represent the texture.
  42761. *
  42762. * @param {number} width - The width of the texture.
  42763. * @param {number} height - The height of the texture.
  42764. * @param {number} format - The texture's format.
  42765. * @param {number} type - The texture's type.
  42766. * @return {number} The byte length.
  42767. */
  42768. static getByteLength( width, height, format, type ) {
  42769. return getByteLength( width, height, format, type );
  42770. }
  42771. }
  42772. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  42773. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'register', { detail: {
  42774. revision: REVISION,
  42775. } } ) );
  42776. }
  42777. if ( typeof window !== 'undefined' ) {
  42778. if ( window.__THREE__ ) {
  42779. warn( 'WARNING: Multiple instances of Three.js being imported.' );
  42780. } else {
  42781. window.__THREE__ = REVISION;
  42782. }
  42783. }
  42784. 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, Compatibility, CompressedArrayTexture, CompressedCubeTexture, CompressedTexture, CompressedTextureLoader, ConeGeometry, ConstantAlphaFactor, ConstantColorFactor, Controls, CubeCamera, CubeDepthTexture, CubeReflectionMapping, CubeRefractionMapping, CubeTexture, CubeTextureLoader, CubeUVReflectionMapping, CubicBezierCurve, CubicBezierCurve3, CubicInterpolant, CullFaceBack, CullFaceFront, CullFaceFrontBack, CullFaceNone, Curve, CurvePath, CustomBlending, CustomToneMapping, CylinderGeometry, Cylindrical, Data3DTexture, DataArrayTexture, DataTexture, DataTextureLoader, DataUtils, DecrementStencilOp, DecrementWrapStencilOp, DefaultLoadingManager, DepthFormat, DepthStencilFormat, DepthTexture, DetachedBindMode, DirectionalLight, DirectionalLightHelper, DiscreteInterpolant, DodecahedronGeometry, DoubleSide, DstAlphaFactor, DstColorFactor, DynamicCopyUsage, DynamicDrawUsage, DynamicReadUsage, EdgesGeometry, EllipseCurve, EqualCompare, EqualDepth, EqualStencilFunc, EquirectangularReflectionMapping, EquirectangularRefractionMapping, Euler, EventDispatcher, ExternalTexture, ExtrudeGeometry, FileLoader, Float16BufferAttribute, Float32BufferAttribute, FloatType, Fog, FogExp2, FramebufferTexture, FrontSide, Frustum, FrustumArray, GLBufferAttribute, GLSL1, GLSL3, GreaterCompare, GreaterDepth, GreaterEqualCompare, GreaterEqualDepth, GreaterEqualStencilFunc, GreaterStencilFunc, GridHelper, Group, HalfFloatType, HemisphereLight, HemisphereLightHelper, IcosahedronGeometry, ImageBitmapLoader, ImageLoader, ImageUtils, IncrementStencilOp, IncrementWrapStencilOp, InstancedBufferAttribute, InstancedBufferGeometry, InstancedInterleavedBuffer, InstancedMesh, Int16BufferAttribute, Int32BufferAttribute, Int8BufferAttribute, IntType, InterleavedBuffer, InterleavedBufferAttribute, Interpolant, 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, NoNormalPacking, NoToneMapping, NormalAnimationBlendMode, NormalBlending, NormalGAPacking, NormalRGPacking, NotEqualCompare, NotEqualDepth, NotEqualStencilFunc, NumberKeyframeTrack, Object3D, ObjectLoader, ObjectSpaceNormalMap, OctahedronGeometry, OneFactor, OneMinusConstantAlphaFactor, OneMinusConstantColorFactor, OneMinusDstAlphaFactor, OneMinusDstColorFactor, OneMinusSrcAlphaFactor, OneMinusSrcColorFactor, OrthographicCamera, PCFShadowMap, PCFSoftShadowMap, Path, PerspectiveCamera, Plane, PlaneGeometry, PlaneHelper, PointLight, PointLightHelper, Points, PointsMaterial, PolarGridHelper, PolyhedronGeometry, PositionalAudio, PropertyBinding, PropertyMixer, QuadraticBezierCurve, QuadraticBezierCurve3, Quaternion, QuaternionKeyframeTrack, QuaternionLinearInterpolant, R11_EAC_Format, RAD2DEG, RED_GREEN_RGTC2_Format, RED_RGTC1_Format, REVISION, RG11_EAC_Format, RGBADepthPacking, RGBAFormat, RGBAIntegerFormat, RGBA_ASTC_10x10_Format, RGBA_ASTC_10x5_Format, RGBA_ASTC_10x6_Format, RGBA_ASTC_10x8_Format, RGBA_ASTC_12x10_Format, RGBA_ASTC_12x12_Format, RGBA_ASTC_4x4_Format, RGBA_ASTC_5x4_Format, RGBA_ASTC_5x5_Format, RGBA_ASTC_6x5_Format, RGBA_ASTC_6x6_Format, RGBA_ASTC_8x5_Format, RGBA_ASTC_8x6_Format, RGBA_ASTC_8x8_Format, RGBA_BPTC_Format, RGBA_ETC2_EAC_Format, RGBA_PVRTC_2BPPV1_Format, RGBA_PVRTC_4BPPV1_Format, RGBA_S3TC_DXT1_Format, RGBA_S3TC_DXT3_Format, RGBA_S3TC_DXT5_Format, RGBDepthPacking, RGBFormat, RGBIntegerFormat, RGB_BPTC_SIGNED_Format, RGB_BPTC_UNSIGNED_Format, RGB_ETC1_Format, RGB_ETC2_Format, RGB_PVRTC_2BPPV1_Format, RGB_PVRTC_4BPPV1_Format, RGB_S3TC_DXT1_Format, RGDepthPacking, RGFormat, RGIntegerFormat, RawShaderMaterial, Ray, Raycaster, RectAreaLight, RedFormat, RedIntegerFormat, ReinhardToneMapping, RenderTarget, RenderTarget3D, RepeatWrapping, ReplaceStencilOp, ReverseSubtractEquation, RingGeometry, SIGNED_R11_EAC_Format, SIGNED_RED_GREEN_RGTC2_Format, SIGNED_RED_RGTC1_Format, SIGNED_RG11_EAC_Format, SRGBColorSpace, SRGBTransfer, Scene, ShaderMaterial, ShadowMaterial, Shape, ShapeGeometry, ShapePath, ShapeUtils, ShortType, Skeleton, SkeletonHelper, SkinnedMesh, Source, Sphere, SphereGeometry, Spherical, SphericalHarmonics3, SplineCurve, SpotLight, SpotLightHelper, Sprite, SpriteMaterial, SrcAlphaFactor, SrcAlphaSaturateFactor, SrcColorFactor, StaticCopyUsage, StaticDrawUsage, StaticReadUsage, StereoCamera, StreamCopyUsage, StreamDrawUsage, StreamReadUsage, StringKeyframeTrack, SubtractEquation, SubtractiveBlending, TOUCH, TangentSpaceNormalMap, TetrahedronGeometry, Texture, TextureLoader, TextureUtils, Timer, TimestampQuery, TorusGeometry, TorusKnotGeometry, Triangle, TriangleFanDrawMode, TriangleStripDrawMode, TrianglesDrawMode, TubeGeometry, UVMapping, Uint16BufferAttribute, Uint32BufferAttribute, Uint8BufferAttribute, Uint8ClampedBufferAttribute, Uniform, UniformsGroup, UniformsUtils, UnsignedByteType, UnsignedInt101111Type, UnsignedInt248Type, UnsignedInt5999Type, UnsignedIntType, UnsignedShort4444Type, UnsignedShort5551Type, UnsignedShortType, VSMShadowMap, Vector2, Vector3, Vector4, VectorKeyframeTrack, VideoFrameTexture, VideoTexture, WebGL3DRenderTarget, WebGLArrayRenderTarget, WebGLCoordinateSystem, WebGLCubeRenderTarget, WebGLRenderTarget, WebGPUCoordinateSystem, WebXRController, WireframeGeometry, WrapAroundEnding, ZeroCurvatureEnding, ZeroFactor, ZeroSlopeEnding, ZeroStencilOp, arrayNeedsUint32, cloneUniforms, createCanvasElement, createElementNS, error, getByteLength, getConsoleFunction, getUnlitUniformColorSpace, isTypedArray, log, mergeUniforms, probeAsync, setConsoleFunction, warn, warnOnce };
粤ICP备19079148号