three.core.js 1007 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777
  1. /**
  2. * @license
  3. * Copyright 2010-2025 Three.js Authors
  4. * SPDX-License-Identifier: MIT
  5. */
  6. const REVISION = '174dev';
  7. const MOUSE = { LEFT: 0, MIDDLE: 1, RIGHT: 2, ROTATE: 0, DOLLY: 1, PAN: 2 };
  8. const TOUCH = { ROTATE: 0, PAN: 1, DOLLY_PAN: 2, DOLLY_ROTATE: 3 };
  9. const CullFaceNone = 0;
  10. const CullFaceBack = 1;
  11. const CullFaceFront = 2;
  12. const CullFaceFrontBack = 3;
  13. const BasicShadowMap = 0;
  14. const PCFShadowMap = 1;
  15. const PCFSoftShadowMap = 2;
  16. const VSMShadowMap = 3;
  17. const FrontSide = 0;
  18. const BackSide = 1;
  19. const DoubleSide = 2;
  20. const NoBlending = 0;
  21. const NormalBlending = 1;
  22. const AdditiveBlending = 2;
  23. const SubtractiveBlending = 3;
  24. const MultiplyBlending = 4;
  25. const CustomBlending = 5;
  26. const AddEquation = 100;
  27. const SubtractEquation = 101;
  28. const ReverseSubtractEquation = 102;
  29. const MinEquation = 103;
  30. const MaxEquation = 104;
  31. const ZeroFactor = 200;
  32. const OneFactor = 201;
  33. const SrcColorFactor = 202;
  34. const OneMinusSrcColorFactor = 203;
  35. const SrcAlphaFactor = 204;
  36. const OneMinusSrcAlphaFactor = 205;
  37. const DstAlphaFactor = 206;
  38. const OneMinusDstAlphaFactor = 207;
  39. const DstColorFactor = 208;
  40. const OneMinusDstColorFactor = 209;
  41. const SrcAlphaSaturateFactor = 210;
  42. const ConstantColorFactor = 211;
  43. const OneMinusConstantColorFactor = 212;
  44. const ConstantAlphaFactor = 213;
  45. const OneMinusConstantAlphaFactor = 214;
  46. const NeverDepth = 0;
  47. const AlwaysDepth = 1;
  48. const LessDepth = 2;
  49. const LessEqualDepth = 3;
  50. const EqualDepth = 4;
  51. const GreaterEqualDepth = 5;
  52. const GreaterDepth = 6;
  53. const NotEqualDepth = 7;
  54. const MultiplyOperation = 0;
  55. const MixOperation = 1;
  56. const AddOperation = 2;
  57. const NoToneMapping = 0;
  58. const LinearToneMapping = 1;
  59. const ReinhardToneMapping = 2;
  60. const CineonToneMapping = 3;
  61. const ACESFilmicToneMapping = 4;
  62. const CustomToneMapping = 5;
  63. const AgXToneMapping = 6;
  64. const NeutralToneMapping = 7;
  65. const AttachedBindMode = 'attached';
  66. const DetachedBindMode = 'detached';
  67. const UVMapping = 300;
  68. const CubeReflectionMapping = 301;
  69. const CubeRefractionMapping = 302;
  70. const EquirectangularReflectionMapping = 303;
  71. const EquirectangularRefractionMapping = 304;
  72. const CubeUVReflectionMapping = 306;
  73. const RepeatWrapping = 1000;
  74. const ClampToEdgeWrapping = 1001;
  75. const MirroredRepeatWrapping = 1002;
  76. const NearestFilter = 1003;
  77. const NearestMipmapNearestFilter = 1004;
  78. const NearestMipMapNearestFilter = 1004;
  79. const NearestMipmapLinearFilter = 1005;
  80. const NearestMipMapLinearFilter = 1005;
  81. const LinearFilter = 1006;
  82. const LinearMipmapNearestFilter = 1007;
  83. const LinearMipMapNearestFilter = 1007;
  84. const LinearMipmapLinearFilter = 1008;
  85. const LinearMipMapLinearFilter = 1008;
  86. const UnsignedByteType = 1009;
  87. const ByteType = 1010;
  88. const ShortType = 1011;
  89. const UnsignedShortType = 1012;
  90. const IntType = 1013;
  91. const UnsignedIntType = 1014;
  92. const FloatType = 1015;
  93. const HalfFloatType = 1016;
  94. const UnsignedShort4444Type = 1017;
  95. const UnsignedShort5551Type = 1018;
  96. const UnsignedInt248Type = 1020;
  97. const UnsignedInt5999Type = 35902;
  98. const AlphaFormat = 1021;
  99. const RGBFormat = 1022;
  100. const RGBAFormat = 1023;
  101. const LuminanceFormat = 1024;
  102. const LuminanceAlphaFormat = 1025;
  103. const DepthFormat = 1026;
  104. const DepthStencilFormat = 1027;
  105. const RedFormat = 1028;
  106. const RedIntegerFormat = 1029;
  107. const RGFormat = 1030;
  108. const RGIntegerFormat = 1031;
  109. const RGBIntegerFormat = 1032;
  110. const RGBAIntegerFormat = 1033;
  111. const RGB_S3TC_DXT1_Format = 33776;
  112. const RGBA_S3TC_DXT1_Format = 33777;
  113. const RGBA_S3TC_DXT3_Format = 33778;
  114. const RGBA_S3TC_DXT5_Format = 33779;
  115. const RGB_PVRTC_4BPPV1_Format = 35840;
  116. const RGB_PVRTC_2BPPV1_Format = 35841;
  117. const RGBA_PVRTC_4BPPV1_Format = 35842;
  118. const RGBA_PVRTC_2BPPV1_Format = 35843;
  119. const RGB_ETC1_Format = 36196;
  120. const RGB_ETC2_Format = 37492;
  121. const RGBA_ETC2_EAC_Format = 37496;
  122. const RGBA_ASTC_4x4_Format = 37808;
  123. const RGBA_ASTC_5x4_Format = 37809;
  124. const RGBA_ASTC_5x5_Format = 37810;
  125. const RGBA_ASTC_6x5_Format = 37811;
  126. const RGBA_ASTC_6x6_Format = 37812;
  127. const RGBA_ASTC_8x5_Format = 37813;
  128. const RGBA_ASTC_8x6_Format = 37814;
  129. const RGBA_ASTC_8x8_Format = 37815;
  130. const RGBA_ASTC_10x5_Format = 37816;
  131. const RGBA_ASTC_10x6_Format = 37817;
  132. const RGBA_ASTC_10x8_Format = 37818;
  133. const RGBA_ASTC_10x10_Format = 37819;
  134. const RGBA_ASTC_12x10_Format = 37820;
  135. const RGBA_ASTC_12x12_Format = 37821;
  136. const RGBA_BPTC_Format = 36492;
  137. const RGB_BPTC_SIGNED_Format = 36494;
  138. const RGB_BPTC_UNSIGNED_Format = 36495;
  139. const RED_RGTC1_Format = 36283;
  140. const SIGNED_RED_RGTC1_Format = 36284;
  141. const RED_GREEN_RGTC2_Format = 36285;
  142. const SIGNED_RED_GREEN_RGTC2_Format = 36286;
  143. const LoopOnce = 2200;
  144. const LoopRepeat = 2201;
  145. const LoopPingPong = 2202;
  146. const InterpolateDiscrete = 2300;
  147. const InterpolateLinear = 2301;
  148. const InterpolateSmooth = 2302;
  149. const ZeroCurvatureEnding = 2400;
  150. const ZeroSlopeEnding = 2401;
  151. const WrapAroundEnding = 2402;
  152. const NormalAnimationBlendMode = 2500;
  153. const AdditiveAnimationBlendMode = 2501;
  154. const TrianglesDrawMode = 0;
  155. const TriangleStripDrawMode = 1;
  156. const TriangleFanDrawMode = 2;
  157. const BasicDepthPacking = 3200;
  158. const RGBADepthPacking = 3201;
  159. const RGBDepthPacking = 3202;
  160. const RGDepthPacking = 3203;
  161. const TangentSpaceNormalMap = 0;
  162. const ObjectSpaceNormalMap = 1;
  163. // Color space string identifiers, matching CSS Color Module Level 4 and WebGPU names where available.
  164. const NoColorSpace = '';
  165. const SRGBColorSpace = 'srgb';
  166. const LinearSRGBColorSpace = 'srgb-linear';
  167. const LinearTransfer = 'linear';
  168. const SRGBTransfer = 'srgb';
  169. const ZeroStencilOp = 0;
  170. const KeepStencilOp = 7680;
  171. const ReplaceStencilOp = 7681;
  172. const IncrementStencilOp = 7682;
  173. const DecrementStencilOp = 7683;
  174. const IncrementWrapStencilOp = 34055;
  175. const DecrementWrapStencilOp = 34056;
  176. const InvertStencilOp = 5386;
  177. const NeverStencilFunc = 512;
  178. const LessStencilFunc = 513;
  179. const EqualStencilFunc = 514;
  180. const LessEqualStencilFunc = 515;
  181. const GreaterStencilFunc = 516;
  182. const NotEqualStencilFunc = 517;
  183. const GreaterEqualStencilFunc = 518;
  184. const AlwaysStencilFunc = 519;
  185. const NeverCompare = 512;
  186. const LessCompare = 513;
  187. const EqualCompare = 514;
  188. const LessEqualCompare = 515;
  189. const GreaterCompare = 516;
  190. const NotEqualCompare = 517;
  191. const GreaterEqualCompare = 518;
  192. const AlwaysCompare = 519;
  193. const StaticDrawUsage = 35044;
  194. const DynamicDrawUsage = 35048;
  195. const StreamDrawUsage = 35040;
  196. const StaticReadUsage = 35045;
  197. const DynamicReadUsage = 35049;
  198. const StreamReadUsage = 35041;
  199. const StaticCopyUsage = 35046;
  200. const DynamicCopyUsage = 35050;
  201. const StreamCopyUsage = 35042;
  202. const GLSL1 = '100';
  203. const GLSL3 = '300 es';
  204. const WebGLCoordinateSystem = 2000;
  205. const WebGPUCoordinateSystem = 2001;
  206. const TimestampQuery = {
  207. COMPUTE: 'compute',
  208. RENDER: 'render'
  209. };
  210. /**
  211. * This modules allows to dispatch event objects on custom JavaScript objects.
  212. *
  213. * Main repository: [eventdispatcher.js]{@link https://github.com/mrdoob/eventdispatcher.js/}
  214. *
  215. * Code Example:
  216. * ```js
  217. * class Car extends EventDispatcher {
  218. * start() {
  219. * this.dispatchEvent( { type: 'start', message: 'vroom vroom!' } );
  220. * }
  221. *};
  222. *
  223. * // Using events with the custom object
  224. * const car = new Car();
  225. * car.addEventListener( 'start', function ( event ) {
  226. * alert( event.message );
  227. * } );
  228. *
  229. * car.start();
  230. * ```
  231. */
  232. class EventDispatcher {
  233. /**
  234. * Adds the given event listener to the given event type.
  235. *
  236. * @param {string} type - The type of event to listen to.
  237. * @param {Function} listener - The function that gets called when the event is fired.
  238. */
  239. addEventListener( type, listener ) {
  240. if ( this._listeners === undefined ) this._listeners = {};
  241. const listeners = this._listeners;
  242. if ( listeners[ type ] === undefined ) {
  243. listeners[ type ] = [];
  244. }
  245. if ( listeners[ type ].indexOf( listener ) === -1 ) {
  246. listeners[ type ].push( listener );
  247. }
  248. }
  249. /**
  250. * Returns `true` if the given event listener has been added to the given event type.
  251. *
  252. * @param {string} type - The type of event.
  253. * @param {Function} listener - The listener to check.
  254. * @return {boolean} Whether the given event listener has been added to the given event type.
  255. */
  256. hasEventListener( type, listener ) {
  257. const listeners = this._listeners;
  258. if ( listeners === undefined ) return false;
  259. return listeners[ type ] !== undefined && listeners[ type ].indexOf( listener ) !== -1;
  260. }
  261. /**
  262. * Removes the given event listener from the given event type.
  263. *
  264. * @param {string} type - The type of event.
  265. * @param {Function} listener - The listener to remove.
  266. */
  267. removeEventListener( type, listener ) {
  268. const listeners = this._listeners;
  269. if ( listeners === undefined ) return;
  270. const listenerArray = listeners[ type ];
  271. if ( listenerArray !== undefined ) {
  272. const index = listenerArray.indexOf( listener );
  273. if ( index !== -1 ) {
  274. listenerArray.splice( index, 1 );
  275. }
  276. }
  277. }
  278. /**
  279. * Dispatches an event object.
  280. *
  281. * @param {Object} event - The event that gets fired.
  282. */
  283. dispatchEvent( event ) {
  284. const listeners = this._listeners;
  285. if ( listeners === undefined ) return;
  286. const listenerArray = listeners[ event.type ];
  287. if ( listenerArray !== undefined ) {
  288. event.target = this;
  289. // Make a copy, in case listeners are removed while iterating.
  290. const array = listenerArray.slice( 0 );
  291. for ( let i = 0, l = array.length; i < l; i ++ ) {
  292. array[ i ].call( this, event );
  293. }
  294. event.target = null;
  295. }
  296. }
  297. }
  298. 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' ];
  299. let _seed = 1234567;
  300. const DEG2RAD = Math.PI / 180;
  301. const RAD2DEG = 180 / Math.PI;
  302. /**
  303. * Generate a [UUID]{@link https://en.wikipedia.org/wiki/Universally_unique_identifier}
  304. * (universally unique identifier).
  305. *
  306. * @return {string} The UUID.
  307. */
  308. function generateUUID() {
  309. // http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/21963136#21963136
  310. const d0 = Math.random() * 0xffffffff | 0;
  311. const d1 = Math.random() * 0xffffffff | 0;
  312. const d2 = Math.random() * 0xffffffff | 0;
  313. const d3 = Math.random() * 0xffffffff | 0;
  314. const uuid = _lut[ d0 & 0xff ] + _lut[ d0 >> 8 & 0xff ] + _lut[ d0 >> 16 & 0xff ] + _lut[ d0 >> 24 & 0xff ] + '-' +
  315. _lut[ d1 & 0xff ] + _lut[ d1 >> 8 & 0xff ] + '-' + _lut[ d1 >> 16 & 0x0f | 0x40 ] + _lut[ d1 >> 24 & 0xff ] + '-' +
  316. _lut[ d2 & 0x3f | 0x80 ] + _lut[ d2 >> 8 & 0xff ] + '-' + _lut[ d2 >> 16 & 0xff ] + _lut[ d2 >> 24 & 0xff ] +
  317. _lut[ d3 & 0xff ] + _lut[ d3 >> 8 & 0xff ] + _lut[ d3 >> 16 & 0xff ] + _lut[ d3 >> 24 & 0xff ];
  318. // .toLowerCase() here flattens concatenated strings to save heap memory space.
  319. return uuid.toLowerCase();
  320. }
  321. /**
  322. * Clamps the given value between min and max.
  323. *
  324. * @param {number} value - The value to clamp.
  325. * @param {number} min - The min value.
  326. * @param {number} max - The max value.
  327. * @return {number} The clamped value.
  328. */
  329. function clamp( value, min, max ) {
  330. return Math.max( min, Math.min( max, value ) );
  331. }
  332. /**
  333. * Computes the Euclidean modulo of the given parameters that
  334. * is `( ( n % m ) + m ) % m`.
  335. *
  336. * @param {number} n - The first parameter.
  337. * @param {number} m - The second parameter.
  338. * @return {number} The Euclidean modulo.
  339. */
  340. function euclideanModulo( n, m ) {
  341. // https://en.wikipedia.org/wiki/Modulo_operation
  342. return ( ( n % m ) + m ) % m;
  343. }
  344. /**
  345. * Performs a linear mapping from range `<a1, a2>` to range `<b1, b2>`
  346. * for the given value.
  347. *
  348. * @param {number} x - The value to be mapped.
  349. * @param {number} a1 - Minimum value for range A.
  350. * @param {number} a2 - Maximum value for range A.
  351. * @param {number} b1 - Minimum value for range B.
  352. * @param {number} b2 - Maximum value for range B.
  353. * @return {number} The mapped value.
  354. */
  355. function mapLinear( x, a1, a2, b1, b2 ) {
  356. return b1 + ( x - a1 ) * ( b2 - b1 ) / ( a2 - a1 );
  357. }
  358. /**
  359. * Returns the percentage in the closed interval `[0, 1]` of the given value
  360. * between the start and end point.
  361. *
  362. * @param {number} x - The start point
  363. * @param {number} y - The end point.
  364. * @param {number} value - A value between start and end.
  365. * @return {number} The interpolation factor.
  366. */
  367. function inverseLerp( x, y, value ) {
  368. // https://www.gamedev.net/tutorials/programming/general-and-gameplay-programming/inverse-lerp-a-super-useful-yet-often-overlooked-function-r5230/
  369. if ( x !== y ) {
  370. return ( value - x ) / ( y - x );
  371. } else {
  372. return 0;
  373. }
  374. }
  375. /**
  376. * Returns a value linearly interpolated from two known points based on the given interval -
  377. * `t = 0` will return `x` and `t = 1` will return `y`.
  378. *
  379. * @param {number} x - The start point
  380. * @param {number} y - The end point.
  381. * @param {number} t - The interpolation factor in the closed interval `[0, 1]`.
  382. * @return {number} The interpolated value.
  383. */
  384. function lerp( x, y, t ) {
  385. return ( 1 - t ) * x + t * y;
  386. }
  387. /**
  388. * Smoothly interpolate a number from `x` to `y` in a spring-like manner using a delta
  389. * time to maintain frame rate independent movement. For details, see
  390. * [Frame rate independent damping using lerp]{@link http://www.rorydriscoll.com/2016/03/07/frame-rate-independent-damping-using-lerp/}.
  391. *
  392. * @param {number} x - The current point.
  393. * @param {number} y - The target point.
  394. * @param {number} lambda - A higher lambda value will make the movement more sudden,
  395. * and a lower value will make the movement more gradual.
  396. * @param {number} dt - Delta time in seconds.
  397. * @return {number} The interpolated value.
  398. */
  399. function damp( x, y, lambda, dt ) {
  400. return lerp( x, y, 1 - Math.exp( - lambda * dt ) );
  401. }
  402. /**
  403. * Returns a value that alternates between `0` and the given `length` parameter.
  404. *
  405. * @param {number} x - The value to pingpong.
  406. * @param {number} [length=1] - The positive value the function will pingpong to.
  407. * @return {number} The alternated value.
  408. */
  409. function pingpong( x, length = 1 ) {
  410. // https://www.desmos.com/calculator/vcsjnyz7x4
  411. return length - Math.abs( euclideanModulo( x, length * 2 ) - length );
  412. }
  413. /**
  414. * Returns a value in the range `[0,1]` that represents the percentage that `x` has
  415. * moved between `min` and `max`, but smoothed or slowed down the closer `x` is to
  416. * the `min` and `max`.
  417. *
  418. * See [Smoothstep]{@link http://en.wikipedia.org/wiki/Smoothstep} for more details.
  419. *
  420. * @param {number} x - The value to evaluate based on its position between min and max.
  421. * @param {number} min - The min value. Any x value below min will be `0`.
  422. * @param {number} max - The max value. Any x value above max will be `1`.
  423. * @return {number} The alternated value.
  424. */
  425. function smoothstep( x, min, max ) {
  426. if ( x <= min ) return 0;
  427. if ( x >= max ) return 1;
  428. x = ( x - min ) / ( max - min );
  429. return x * x * ( 3 - 2 * x );
  430. }
  431. /**
  432. * A [variation on smoothstep]{@link https://en.wikipedia.org/wiki/Smoothstep#Variations}
  433. * that has zero 1st and 2nd order derivatives at x=0 and x=1.
  434. *
  435. * @param {number} x - The value to evaluate based on its position between min and max.
  436. * @param {number} min - The min value. Any x value below min will be `0`.
  437. * @param {number} max - The max value. Any x value above max will be `1`.
  438. * @return {number} The alternated value.
  439. */
  440. function smootherstep( x, min, max ) {
  441. if ( x <= min ) return 0;
  442. if ( x >= max ) return 1;
  443. x = ( x - min ) / ( max - min );
  444. return x * x * x * ( x * ( x * 6 - 15 ) + 10 );
  445. }
  446. /**
  447. * Returns a random integer from `<low, high>` interval.
  448. *
  449. * @param {number} low - The lower value boundary.
  450. * @param {number} high - The upper value boundary
  451. * @return {number} A random integer.
  452. */
  453. function randInt( low, high ) {
  454. return low + Math.floor( Math.random() * ( high - low + 1 ) );
  455. }
  456. /**
  457. * Returns a random float from `<low, high>` interval.
  458. *
  459. * @param {number} low - The lower value boundary.
  460. * @param {number} high - The upper value boundary
  461. * @return {number} A random float.
  462. */
  463. function randFloat( low, high ) {
  464. return low + Math.random() * ( high - low );
  465. }
  466. /**
  467. * Returns a random integer from `<-range/2, range/2>` interval.
  468. *
  469. * @param {number} range - Defines the value range.
  470. * @return {number} A random float.
  471. */
  472. function randFloatSpread( range ) {
  473. return range * ( 0.5 - Math.random() );
  474. }
  475. /**
  476. * Returns a deterministic pseudo-random float in the interval `[0, 1]`.
  477. *
  478. * @param {number} [s] - The integer seed.
  479. * @return {number} A random float.
  480. */
  481. function seededRandom( s ) {
  482. if ( s !== undefined ) _seed = s;
  483. // Mulberry32 generator
  484. let t = _seed += 0x6D2B79F5;
  485. t = Math.imul( t ^ t >>> 15, t | 1 );
  486. t ^= t + Math.imul( t ^ t >>> 7, t | 61 );
  487. return ( ( t ^ t >>> 14 ) >>> 0 ) / 4294967296;
  488. }
  489. /**
  490. * Converts degrees to radians.
  491. *
  492. * @param {number} degrees - A value in degrees.
  493. * @return {number} The converted value in radians.
  494. */
  495. function degToRad( degrees ) {
  496. return degrees * DEG2RAD;
  497. }
  498. /**
  499. * Converts radians to degrees.
  500. *
  501. * @param {number} radians - A value in radians.
  502. * @return {number} The converted value in degrees.
  503. */
  504. function radToDeg( radians ) {
  505. return radians * RAD2DEG;
  506. }
  507. /**
  508. * Returns `true` if the given number is a power of two.
  509. *
  510. * @param {number} value - The value to check.
  511. * @return {boolean} Whether the given number is a power of two or not.
  512. */
  513. function isPowerOfTwo( value ) {
  514. return ( value & ( value - 1 ) ) === 0 && value !== 0;
  515. }
  516. /**
  517. * Returns the smallest power of two that is greater than or equal to the given number.
  518. *
  519. * @param {number} value - The value to find a POT for.
  520. * @return {number} The smallest power of two that is greater than or equal to the given number.
  521. */
  522. function ceilPowerOfTwo( value ) {
  523. return Math.pow( 2, Math.ceil( Math.log( value ) / Math.LN2 ) );
  524. }
  525. /**
  526. * Returns the largest power of two that is less than or equal to the given number.
  527. *
  528. * @param {number} value - The value to find a POT for.
  529. * @return {number} The largest power of two that is less than or equal to the given number.
  530. */
  531. function floorPowerOfTwo( value ) {
  532. return Math.pow( 2, Math.floor( Math.log( value ) / Math.LN2 ) );
  533. }
  534. /**
  535. * Sets the given quaternion from the [Intrinsic Proper Euler Angles]{@link https://en.wikipedia.org/wiki/Euler_angles}
  536. * defined by the given angles and order.
  537. *
  538. * Rotations are applied to the axes in the order specified by order:
  539. * rotation by angle `a` is applied first, then by angle `b`, then by angle `c`.
  540. *
  541. * @param {Quaternion} q - The quaternion to set.
  542. * @param {number} a - The rotation applied to the first axis, in radians.
  543. * @param {number} b - The rotation applied to the second axis, in radians.
  544. * @param {number} c - The rotation applied to the third axis, in radians.
  545. * @param {('XYX'|'XZX'|'YXY'|'YZY'|'ZXZ'|'ZYZ')} order - A string specifying the axes order.
  546. */
  547. function setQuaternionFromProperEuler( q, a, b, c, order ) {
  548. const cos = Math.cos;
  549. const sin = Math.sin;
  550. const c2 = cos( b / 2 );
  551. const s2 = sin( b / 2 );
  552. const c13 = cos( ( a + c ) / 2 );
  553. const s13 = sin( ( a + c ) / 2 );
  554. const c1_3 = cos( ( a - c ) / 2 );
  555. const s1_3 = sin( ( a - c ) / 2 );
  556. const c3_1 = cos( ( c - a ) / 2 );
  557. const s3_1 = sin( ( c - a ) / 2 );
  558. switch ( order ) {
  559. case 'XYX':
  560. q.set( c2 * s13, s2 * c1_3, s2 * s1_3, c2 * c13 );
  561. break;
  562. case 'YZY':
  563. q.set( s2 * s1_3, c2 * s13, s2 * c1_3, c2 * c13 );
  564. break;
  565. case 'ZXZ':
  566. q.set( s2 * c1_3, s2 * s1_3, c2 * s13, c2 * c13 );
  567. break;
  568. case 'XZX':
  569. q.set( c2 * s13, s2 * s3_1, s2 * c3_1, c2 * c13 );
  570. break;
  571. case 'YXY':
  572. q.set( s2 * c3_1, c2 * s13, s2 * s3_1, c2 * c13 );
  573. break;
  574. case 'ZYZ':
  575. q.set( s2 * s3_1, s2 * c3_1, c2 * s13, c2 * c13 );
  576. break;
  577. default:
  578. console.warn( 'THREE.MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: ' + order );
  579. }
  580. }
  581. /**
  582. * Denormalizes the given value according to the given typed array.
  583. *
  584. * @param {number} value - The value to denormalize.
  585. * @param {TypedArray} array - The typed array that defines the data type of the value.
  586. * @return {number} The denormalize (float) value in the range `[0,1]`.
  587. */
  588. function denormalize( value, array ) {
  589. switch ( array.constructor ) {
  590. case Float32Array:
  591. return value;
  592. case Uint32Array:
  593. return value / 4294967295.0;
  594. case Uint16Array:
  595. return value / 65535.0;
  596. case Uint8Array:
  597. return value / 255.0;
  598. case Int32Array:
  599. return Math.max( value / 2147483647.0, -1 );
  600. case Int16Array:
  601. return Math.max( value / 32767.0, -1 );
  602. case Int8Array:
  603. return Math.max( value / 127.0, -1 );
  604. default:
  605. throw new Error( 'Invalid component type.' );
  606. }
  607. }
  608. /**
  609. * Normalizes the given value according to the given typed array.
  610. *
  611. * @param {number} value - The float value in the range `[0,1]` to normalize.
  612. * @param {TypedArray} array - The typed array that defines the data type of the value.
  613. * @return {number} The normalize value.
  614. */
  615. function normalize( value, array ) {
  616. switch ( array.constructor ) {
  617. case Float32Array:
  618. return value;
  619. case Uint32Array:
  620. return Math.round( value * 4294967295.0 );
  621. case Uint16Array:
  622. return Math.round( value * 65535.0 );
  623. case Uint8Array:
  624. return Math.round( value * 255.0 );
  625. case Int32Array:
  626. return Math.round( value * 2147483647.0 );
  627. case Int16Array:
  628. return Math.round( value * 32767.0 );
  629. case Int8Array:
  630. return Math.round( value * 127.0 );
  631. default:
  632. throw new Error( 'Invalid component type.' );
  633. }
  634. }
  635. const MathUtils = {
  636. DEG2RAD: DEG2RAD,
  637. RAD2DEG: RAD2DEG,
  638. generateUUID: generateUUID,
  639. clamp: clamp,
  640. euclideanModulo: euclideanModulo,
  641. mapLinear: mapLinear,
  642. inverseLerp: inverseLerp,
  643. lerp: lerp,
  644. damp: damp,
  645. pingpong: pingpong,
  646. smoothstep: smoothstep,
  647. smootherstep: smootherstep,
  648. randInt: randInt,
  649. randFloat: randFloat,
  650. randFloatSpread: randFloatSpread,
  651. seededRandom: seededRandom,
  652. degToRad: degToRad,
  653. radToDeg: radToDeg,
  654. isPowerOfTwo: isPowerOfTwo,
  655. ceilPowerOfTwo: ceilPowerOfTwo,
  656. floorPowerOfTwo: floorPowerOfTwo,
  657. setQuaternionFromProperEuler: setQuaternionFromProperEuler,
  658. normalize: normalize,
  659. denormalize: denormalize
  660. };
  661. /**
  662. * Class representing a 2D vector. A 2D vector is an ordered pair of numbers
  663. * (labeled x and y), which can be used to represent a number of things, such as:
  664. *
  665. * - A point in 2D space (i.e. a position on a plane).
  666. * - A direction and length across a plane. In three.js the length will
  667. * always be the Euclidean distance(straight-line distance) from `(0, 0)` to `(x, y)`
  668. * and the direction is also measured from `(0, 0)` towards `(x, y)`.
  669. * - Any arbitrary ordered pair of numbers.
  670. *
  671. * There are other things a 2D vector can be used to represent, such as
  672. * momentum vectors, complex numbers and so on, however these are the most
  673. * common uses in three.js.
  674. *
  675. * Iterating through a vector instance will yield its components `(x, y)` in
  676. * the corresponding order.
  677. * ```js
  678. * const a = new THREE.Vector2( 0, 1 );
  679. *
  680. * //no arguments; will be initialised to (0, 0)
  681. * const b = new THREE.Vector2( );
  682. *
  683. * const d = a.distanceTo( b );
  684. * ```
  685. */
  686. class Vector2 {
  687. /**
  688. * Constructs a new 2D vector.
  689. *
  690. * @param {number} [x=0] - The x value of this vector.
  691. * @param {number} [y=0] - The y value of this vector.
  692. */
  693. constructor( x = 0, y = 0 ) {
  694. /**
  695. * This flag can be used for type testing.
  696. *
  697. * @type {boolean}
  698. * @readonly
  699. * @default true
  700. */
  701. Vector2.prototype.isVector2 = true;
  702. /**
  703. * The x value of this vector.
  704. *
  705. * @type {number}
  706. */
  707. this.x = x;
  708. /**
  709. * The y value of this vector.
  710. *
  711. * @type {number}
  712. */
  713. this.y = y;
  714. }
  715. /**
  716. * Alias for {@link Vector2#x}.
  717. *
  718. * @type {number}
  719. */
  720. get width() {
  721. return this.x;
  722. }
  723. set width( value ) {
  724. this.x = value;
  725. }
  726. /**
  727. * Alias for {@link Vector2#y}.
  728. *
  729. * @type {number}
  730. */
  731. get height() {
  732. return this.y;
  733. }
  734. set height( value ) {
  735. this.y = value;
  736. }
  737. /**
  738. * Sets the vector components.
  739. *
  740. * @param {number} x - The value of the x component.
  741. * @param {number} y - The value of the y component.
  742. * @return {Vector2} A reference to this vector.
  743. */
  744. set( x, y ) {
  745. this.x = x;
  746. this.y = y;
  747. return this;
  748. }
  749. /**
  750. * Sets the vector components to the same value.
  751. *
  752. * @param {number} scalar - The value to set for all vector components.
  753. * @return {Vector2} A reference to this vector.
  754. */
  755. setScalar( scalar ) {
  756. this.x = scalar;
  757. this.y = scalar;
  758. return this;
  759. }
  760. /**
  761. * Sets the vector's x component to the given value
  762. *
  763. * @param {number} x - The value to set.
  764. * @return {Vector2} A reference to this vector.
  765. */
  766. setX( x ) {
  767. this.x = x;
  768. return this;
  769. }
  770. /**
  771. * Sets the vector's y component to the given value
  772. *
  773. * @param {number} y - The value to set.
  774. * @return {Vector2} A reference to this vector.
  775. */
  776. setY( y ) {
  777. this.y = y;
  778. return this;
  779. }
  780. /**
  781. * Allows to set a vector component with an index.
  782. *
  783. * @param {number} index - The component index. `0` equals to x, `1` equals to y.
  784. * @param {number} value - The value to set.
  785. * @return {Vector2} A reference to this vector.
  786. */
  787. setComponent( index, value ) {
  788. switch ( index ) {
  789. case 0: this.x = value; break;
  790. case 1: this.y = value; break;
  791. default: throw new Error( 'index is out of range: ' + index );
  792. }
  793. return this;
  794. }
  795. /**
  796. * Returns the value of the vector component which matches the given index.
  797. *
  798. * @param {number} index - The component index. `0` equals to x, `1` equals to y.
  799. * @return {number} A vector component value.
  800. */
  801. getComponent( index ) {
  802. switch ( index ) {
  803. case 0: return this.x;
  804. case 1: return this.y;
  805. default: throw new Error( 'index is out of range: ' + index );
  806. }
  807. }
  808. /**
  809. * Returns a new vector with copied values from this instance.
  810. *
  811. * @return {Vector2} A clone of this instance.
  812. */
  813. clone() {
  814. return new this.constructor( this.x, this.y );
  815. }
  816. /**
  817. * Copies the values of the given vector to this instance.
  818. *
  819. * @param {Vector2} v - The vector to copy.
  820. * @return {Vector2} A reference to this vector.
  821. */
  822. copy( v ) {
  823. this.x = v.x;
  824. this.y = v.y;
  825. return this;
  826. }
  827. /**
  828. * Adds the given vector to this instance.
  829. *
  830. * @param {Vector2} v - The vector to add.
  831. * @return {Vector2} A reference to this vector.
  832. */
  833. add( v ) {
  834. this.x += v.x;
  835. this.y += v.y;
  836. return this;
  837. }
  838. /**
  839. * Adds the given scalar value to all components of this instance.
  840. *
  841. * @param {number} s - The scalar to add.
  842. * @return {Vector2} A reference to this vector.
  843. */
  844. addScalar( s ) {
  845. this.x += s;
  846. this.y += s;
  847. return this;
  848. }
  849. /**
  850. * Adds the given vectors and stores the result in this instance.
  851. *
  852. * @param {Vector2} a - The first vector.
  853. * @param {Vector2} b - The second vector.
  854. * @return {Vector2} A reference to this vector.
  855. */
  856. addVectors( a, b ) {
  857. this.x = a.x + b.x;
  858. this.y = a.y + b.y;
  859. return this;
  860. }
  861. /**
  862. * Adds the given vector scaled by the given factor to this instance.
  863. *
  864. * @param {Vector2} v - The vector.
  865. * @param {number} s - The factor that scales `v`.
  866. * @return {Vector2} A reference to this vector.
  867. */
  868. addScaledVector( v, s ) {
  869. this.x += v.x * s;
  870. this.y += v.y * s;
  871. return this;
  872. }
  873. /**
  874. * Subtracts the given vector from this instance.
  875. *
  876. * @param {Vector2} v - The vector to subtract.
  877. * @return {Vector2} A reference to this vector.
  878. */
  879. sub( v ) {
  880. this.x -= v.x;
  881. this.y -= v.y;
  882. return this;
  883. }
  884. /**
  885. * Subtracts the given scalar value from all components of this instance.
  886. *
  887. * @param {number} s - The scalar to subtract.
  888. * @return {Vector2} A reference to this vector.
  889. */
  890. subScalar( s ) {
  891. this.x -= s;
  892. this.y -= s;
  893. return this;
  894. }
  895. /**
  896. * Subtracts the given vectors and stores the result in this instance.
  897. *
  898. * @param {Vector2} a - The first vector.
  899. * @param {Vector2} b - The second vector.
  900. * @return {Vector2} A reference to this vector.
  901. */
  902. subVectors( a, b ) {
  903. this.x = a.x - b.x;
  904. this.y = a.y - b.y;
  905. return this;
  906. }
  907. /**
  908. * Multiplies the given vector with this instance.
  909. *
  910. * @param {Vector2} v - The vector to multiply.
  911. * @return {Vector2} A reference to this vector.
  912. */
  913. multiply( v ) {
  914. this.x *= v.x;
  915. this.y *= v.y;
  916. return this;
  917. }
  918. /**
  919. * Multiplies the given scalar value with all components of this instance.
  920. *
  921. * @param {number} scalar - The scalar to multiply.
  922. * @return {Vector2} A reference to this vector.
  923. */
  924. multiplyScalar( scalar ) {
  925. this.x *= scalar;
  926. this.y *= scalar;
  927. return this;
  928. }
  929. /**
  930. * Divides this instance by the given vector.
  931. *
  932. * @param {Vector2} v - The vector to divide.
  933. * @return {Vector2} A reference to this vector.
  934. */
  935. divide( v ) {
  936. this.x /= v.x;
  937. this.y /= v.y;
  938. return this;
  939. }
  940. /**
  941. * Divides this vector by the given scalar.
  942. *
  943. * @param {number} scalar - The scalar to divide.
  944. * @return {Vector2} A reference to this vector.
  945. */
  946. divideScalar( scalar ) {
  947. return this.multiplyScalar( 1 / scalar );
  948. }
  949. /**
  950. * Multiplies this vector (with an implicit 1 as the 3rd component) by
  951. * the given 3x3 matrix.
  952. *
  953. * @param {Matrix3} m - The matrix to apply.
  954. * @return {Vector2} A reference to this vector.
  955. */
  956. applyMatrix3( m ) {
  957. const x = this.x, y = this.y;
  958. const e = m.elements;
  959. this.x = e[ 0 ] * x + e[ 3 ] * y + e[ 6 ];
  960. this.y = e[ 1 ] * x + e[ 4 ] * y + e[ 7 ];
  961. return this;
  962. }
  963. /**
  964. * If this vector's x or y value is greater than the given vector's x or y
  965. * value, replace that value with the corresponding min value.
  966. *
  967. * @param {Vector2} v - The vector.
  968. * @return {Vector2} A reference to this vector.
  969. */
  970. min( v ) {
  971. this.x = Math.min( this.x, v.x );
  972. this.y = Math.min( this.y, v.y );
  973. return this;
  974. }
  975. /**
  976. * If this vector's x or y value is less than the given vector's x or y
  977. * value, replace that value with the corresponding max value.
  978. *
  979. * @param {Vector2} v - The vector.
  980. * @return {Vector2} A reference to this vector.
  981. */
  982. max( v ) {
  983. this.x = Math.max( this.x, v.x );
  984. this.y = Math.max( this.y, v.y );
  985. return this;
  986. }
  987. /**
  988. * If this vector's x or y value is greater than the max vector's x or y
  989. * value, it is replaced by the corresponding value.
  990. * If this vector's x or y value is less than the min vector's x or y value,
  991. * it is replaced by the corresponding value.
  992. *
  993. * @param {Vector2} min - The minimum x and y values.
  994. * @param {Vector2} max - The maximum x and y values in the desired range.
  995. * @return {Vector2} A reference to this vector.
  996. */
  997. clamp( min, max ) {
  998. // assumes min < max, componentwise
  999. this.x = clamp( this.x, min.x, max.x );
  1000. this.y = clamp( this.y, min.y, max.y );
  1001. return this;
  1002. }
  1003. /**
  1004. * If this vector's x or y values are greater than the max value, they are
  1005. * replaced by the max value.
  1006. * If this vector's x or y values are less than the min value, they are
  1007. * replaced by the min value.
  1008. *
  1009. * @param {number} minVal - The minimum value the components will be clamped to.
  1010. * @param {number} maxVal - The maximum value the components will be clamped to.
  1011. * @return {Vector2} A reference to this vector.
  1012. */
  1013. clampScalar( minVal, maxVal ) {
  1014. this.x = clamp( this.x, minVal, maxVal );
  1015. this.y = clamp( this.y, minVal, maxVal );
  1016. return this;
  1017. }
  1018. /**
  1019. * If this vector's length is greater than the max value, it is replaced by
  1020. * the max value.
  1021. * If this vector's length is less than the min value, it is replaced by the
  1022. * min value.
  1023. *
  1024. * @param {number} min - The minimum value the vector length will be clamped to.
  1025. * @param {number} max - The maximum value the vector length will be clamped to.
  1026. * @return {Vector2} A reference to this vector.
  1027. */
  1028. clampLength( min, max ) {
  1029. const length = this.length();
  1030. return this.divideScalar( length || 1 ).multiplyScalar( clamp( length, min, max ) );
  1031. }
  1032. /**
  1033. * The components of this vector are rounded down to the nearest integer value.
  1034. *
  1035. * @return {Vector2} A reference to this vector.
  1036. */
  1037. floor() {
  1038. this.x = Math.floor( this.x );
  1039. this.y = Math.floor( this.y );
  1040. return this;
  1041. }
  1042. /**
  1043. * The components of this vector are rounded up to the nearest integer value.
  1044. *
  1045. * @return {Vector2} A reference to this vector.
  1046. */
  1047. ceil() {
  1048. this.x = Math.ceil( this.x );
  1049. this.y = Math.ceil( this.y );
  1050. return this;
  1051. }
  1052. /**
  1053. * The components of this vector are rounded to the nearest integer value
  1054. *
  1055. * @return {Vector2} A reference to this vector.
  1056. */
  1057. round() {
  1058. this.x = Math.round( this.x );
  1059. this.y = Math.round( this.y );
  1060. return this;
  1061. }
  1062. /**
  1063. * The components of this vector are rounded towards zero (up if negative,
  1064. * down if positive) to an integer value.
  1065. *
  1066. * @return {Vector2} A reference to this vector.
  1067. */
  1068. roundToZero() {
  1069. this.x = Math.trunc( this.x );
  1070. this.y = Math.trunc( this.y );
  1071. return this;
  1072. }
  1073. /**
  1074. * Inverts this vector - i.e. sets x = -x and y = -y.
  1075. *
  1076. * @return {Vector2} A reference to this vector.
  1077. */
  1078. negate() {
  1079. this.x = - this.x;
  1080. this.y = - this.y;
  1081. return this;
  1082. }
  1083. /**
  1084. * Calculates the dot product of the given vector with this instance.
  1085. *
  1086. * @param {Vector2} v - The vector to compute the dot product with.
  1087. * @return {number} The result of the dot product.
  1088. */
  1089. dot( v ) {
  1090. return this.x * v.x + this.y * v.y;
  1091. }
  1092. /**
  1093. * Calculates the cross product of the given vector with this instance.
  1094. *
  1095. * @param {Vector2} v - The vector to compute the cross product with.
  1096. * @return {Vector2} The result of the cross product.
  1097. */
  1098. cross( v ) {
  1099. return this.x * v.y - this.y * v.x;
  1100. }
  1101. /**
  1102. * Computes the square of the Euclidean length (straight-line length) from
  1103. * (0, 0) to (x, y). If you are comparing the lengths of vectors, you should
  1104. * compare the length squared instead as it is slightly more efficient to calculate.
  1105. *
  1106. * @return {number} The square length of this vector.
  1107. */
  1108. lengthSq() {
  1109. return this.x * this.x + this.y * this.y;
  1110. }
  1111. /**
  1112. * Computes the Euclidean length (straight-line length) from (0, 0) to (x, y).
  1113. *
  1114. * @return {number} The length of this vector.
  1115. */
  1116. length() {
  1117. return Math.sqrt( this.x * this.x + this.y * this.y );
  1118. }
  1119. /**
  1120. * Computes the Manhattan length of this vector.
  1121. *
  1122. * @return {number} The length of this vector.
  1123. */
  1124. manhattanLength() {
  1125. return Math.abs( this.x ) + Math.abs( this.y );
  1126. }
  1127. /**
  1128. * Converts this vector to a unit vector - that is, sets it equal to a vector
  1129. * with the same direction as this one, but with a vector length of `1`.
  1130. *
  1131. * @return {Vector2} A reference to this vector.
  1132. */
  1133. normalize() {
  1134. return this.divideScalar( this.length() || 1 );
  1135. }
  1136. /**
  1137. * Computes the angle in radians of this vector with respect to the positive x-axis.
  1138. *
  1139. * @return {number} The angle in radians.
  1140. */
  1141. angle() {
  1142. const angle = Math.atan2( - this.y, - this.x ) + Math.PI;
  1143. return angle;
  1144. }
  1145. /**
  1146. * Returns the angle between the given vector and this instance in radians.
  1147. *
  1148. * @param {Vector2} v - The vector to compute the angle with.
  1149. * @return {number} The angle in radians.
  1150. */
  1151. angleTo( v ) {
  1152. const denominator = Math.sqrt( this.lengthSq() * v.lengthSq() );
  1153. if ( denominator === 0 ) return Math.PI / 2;
  1154. const theta = this.dot( v ) / denominator;
  1155. // clamp, to handle numerical problems
  1156. return Math.acos( clamp( theta, -1, 1 ) );
  1157. }
  1158. /**
  1159. * Computes the distance from the given vector to this instance.
  1160. *
  1161. * @param {Vector2} v - The vector to compute the distance to.
  1162. * @return {number} The distance.
  1163. */
  1164. distanceTo( v ) {
  1165. return Math.sqrt( this.distanceToSquared( v ) );
  1166. }
  1167. /**
  1168. * Computes the squared distance from the given vector to this instance.
  1169. * If you are just comparing the distance with another distance, you should compare
  1170. * the distance squared instead as it is slightly more efficient to calculate.
  1171. *
  1172. * @param {Vector2} v - The vector to compute the squared distance to.
  1173. * @return {number} The squared distance.
  1174. */
  1175. distanceToSquared( v ) {
  1176. const dx = this.x - v.x, dy = this.y - v.y;
  1177. return dx * dx + dy * dy;
  1178. }
  1179. /**
  1180. * Computes the Manhattan distance from the given vector to this instance.
  1181. *
  1182. * @param {Vector2} v - The vector to compute the Manhattan distance to.
  1183. * @return {number} The Manhattan distance.
  1184. */
  1185. manhattanDistanceTo( v ) {
  1186. return Math.abs( this.x - v.x ) + Math.abs( this.y - v.y );
  1187. }
  1188. /**
  1189. * Sets this vector to a vector with the same direction as this one, but
  1190. * with the specified length.
  1191. *
  1192. * @param {number} length - The new length of this vector.
  1193. * @return {Vector2} A reference to this vector.
  1194. */
  1195. setLength( length ) {
  1196. return this.normalize().multiplyScalar( length );
  1197. }
  1198. /**
  1199. * Linearly interpolates between the given vector and this instance, where
  1200. * alpha is the percent distance along the line - alpha = 0 will be this
  1201. * vector, and alpha = 1 will be the given one.
  1202. *
  1203. * @param {Vector2} v - The vector to interpolate towards.
  1204. * @param {number} alpha - The interpolation factor, typically in the closed interval `[0, 1]`.
  1205. * @return {Vector2} A reference to this vector.
  1206. */
  1207. lerp( v, alpha ) {
  1208. this.x += ( v.x - this.x ) * alpha;
  1209. this.y += ( v.y - this.y ) * alpha;
  1210. return this;
  1211. }
  1212. /**
  1213. * Linearly interpolates between the given vectors, where alpha is the percent
  1214. * distance along the line - alpha = 0 will be first vector, and alpha = 1 will
  1215. * be the second one. The result is stored in this instance.
  1216. *
  1217. * @param {Vector2} v1 - The first vector.
  1218. * @param {Vector2} v2 - The second vector.
  1219. * @param {number} alpha - The interpolation factor, typically in the closed interval `[0, 1]`.
  1220. * @return {Vector2} A reference to this vector.
  1221. */
  1222. lerpVectors( v1, v2, alpha ) {
  1223. this.x = v1.x + ( v2.x - v1.x ) * alpha;
  1224. this.y = v1.y + ( v2.y - v1.y ) * alpha;
  1225. return this;
  1226. }
  1227. /**
  1228. * Returns `true` if this vector is equal with the given one.
  1229. *
  1230. * @param {Vector2} v - The vector to test for equality.
  1231. * @return {boolean} Whether this vector is equal with the given one.
  1232. */
  1233. equals( v ) {
  1234. return ( ( v.x === this.x ) && ( v.y === this.y ) );
  1235. }
  1236. /**
  1237. * Sets this vector's x value to be `array[ offset ]` and y
  1238. * value to be `array[ offset + 1 ]`.
  1239. *
  1240. * @param {Array<number>} array - An array holding the vector component values.
  1241. * @param {number} [offset=0] - The offset into the array.
  1242. * @return {Vector2} A reference to this vector.
  1243. */
  1244. fromArray( array, offset = 0 ) {
  1245. this.x = array[ offset ];
  1246. this.y = array[ offset + 1 ];
  1247. return this;
  1248. }
  1249. /**
  1250. * Writes the components of this vector to the given array. If no array is provided,
  1251. * the method returns a new instance.
  1252. *
  1253. * @param {Array<number>} [array=[]] - The target array holding the vector components.
  1254. * @param {number} [offset=0] - Index of the first element in the array.
  1255. * @return {Array<number>} The vector components.
  1256. */
  1257. toArray( array = [], offset = 0 ) {
  1258. array[ offset ] = this.x;
  1259. array[ offset + 1 ] = this.y;
  1260. return array;
  1261. }
  1262. /**
  1263. * Sets the components of this vector from the given buffer attribute.
  1264. *
  1265. * @param {BufferAttribute} attribute - The buffer attribute holding vector data.
  1266. * @param {number} index - The index into the attribute.
  1267. * @return {Vector2} A reference to this vector.
  1268. */
  1269. fromBufferAttribute( attribute, index ) {
  1270. this.x = attribute.getX( index );
  1271. this.y = attribute.getY( index );
  1272. return this;
  1273. }
  1274. /**
  1275. * Rotates this vector around the given center by the given angle.
  1276. *
  1277. * @param {Vector2} center - The point around which to rotate.
  1278. * @param {number} angle - The angle to rotate, in radians.
  1279. * @return {Vector2} A reference to this vector.
  1280. */
  1281. rotateAround( center, angle ) {
  1282. const c = Math.cos( angle ), s = Math.sin( angle );
  1283. const x = this.x - center.x;
  1284. const y = this.y - center.y;
  1285. this.x = x * c - y * s + center.x;
  1286. this.y = x * s + y * c + center.y;
  1287. return this;
  1288. }
  1289. /**
  1290. * Sets each component of this vector to a pseudo-random value between `0` and
  1291. * `1`, excluding `1`.
  1292. *
  1293. * @return {Vector2} A reference to this vector.
  1294. */
  1295. random() {
  1296. this.x = Math.random();
  1297. this.y = Math.random();
  1298. return this;
  1299. }
  1300. *[ Symbol.iterator ]() {
  1301. yield this.x;
  1302. yield this.y;
  1303. }
  1304. }
  1305. /**
  1306. * Represents a 3x3 matrix.
  1307. *
  1308. * A Note on Row-Major and Column-Major Ordering:
  1309. *
  1310. * The constructor and {@link Matrix3#set} method take arguments in
  1311. * [row-major]{@link https://en.wikipedia.org/wiki/Row-_and_column-major_order#Column-major_order}
  1312. * order, while internally they are stored in the {@link Matrix3#elements} array in column-major order.
  1313. * This means that calling:
  1314. * ```js
  1315. * const m = new THREE.Matrix();
  1316. * m.set( 11, 12, 13,
  1317. * 21, 22, 23,
  1318. * 31, 32, 33 );
  1319. * ```
  1320. * will result in the elements array containing:
  1321. * ```js
  1322. * m.elements = [ 11, 21, 31,
  1323. * 12, 22, 32,
  1324. * 13, 23, 33 ];
  1325. * ```
  1326. * and internally all calculations are performed using column-major ordering.
  1327. * However, as the actual ordering makes no difference mathematically and
  1328. * most people are used to thinking about matrices in row-major order, the
  1329. * three.js documentation shows matrices in row-major order. Just bear in
  1330. * mind that if you are reading the source code, you'll have to take the
  1331. * transpose of any matrices outlined here to make sense of the calculations.
  1332. */
  1333. class Matrix3 {
  1334. /**
  1335. * Constructs a new 3x3 matrix. The arguments are supposed to be
  1336. * in row-major order. If no arguments are provided, the constructor
  1337. * initializes the matrix as an identity matrix.
  1338. *
  1339. * @param {number} [n11] - 1-1 matrix element.
  1340. * @param {number} [n12] - 1-2 matrix element.
  1341. * @param {number} [n13] - 1-3 matrix element.
  1342. * @param {number} [n21] - 2-1 matrix element.
  1343. * @param {number} [n22] - 2-2 matrix element.
  1344. * @param {number} [n23] - 2-3 matrix element.
  1345. * @param {number} [n31] - 3-1 matrix element.
  1346. * @param {number} [n32] - 3-2 matrix element.
  1347. * @param {number} [n33] - 3-3 matrix element.
  1348. */
  1349. constructor( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) {
  1350. /**
  1351. * This flag can be used for type testing.
  1352. *
  1353. * @type {boolean}
  1354. * @readonly
  1355. * @default true
  1356. */
  1357. Matrix3.prototype.isMatrix3 = true;
  1358. /**
  1359. * A column-major list of matrix values.
  1360. *
  1361. * @type {Array<number>}
  1362. */
  1363. this.elements = [
  1364. 1, 0, 0,
  1365. 0, 1, 0,
  1366. 0, 0, 1
  1367. ];
  1368. if ( n11 !== undefined ) {
  1369. this.set( n11, n12, n13, n21, n22, n23, n31, n32, n33 );
  1370. }
  1371. }
  1372. /**
  1373. * Sets the elements of the matrix.The arguments are supposed to be
  1374. * in row-major order.
  1375. *
  1376. * @param {number} [n11] - 1-1 matrix element.
  1377. * @param {number} [n12] - 1-2 matrix element.
  1378. * @param {number} [n13] - 1-3 matrix element.
  1379. * @param {number} [n21] - 2-1 matrix element.
  1380. * @param {number} [n22] - 2-2 matrix element.
  1381. * @param {number} [n23] - 2-3 matrix element.
  1382. * @param {number} [n31] - 3-1 matrix element.
  1383. * @param {number} [n32] - 3-2 matrix element.
  1384. * @param {number} [n33] - 3-3 matrix element.
  1385. * @return {Matrix3} A reference to this matrix.
  1386. */
  1387. set( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) {
  1388. const te = this.elements;
  1389. te[ 0 ] = n11; te[ 1 ] = n21; te[ 2 ] = n31;
  1390. te[ 3 ] = n12; te[ 4 ] = n22; te[ 5 ] = n32;
  1391. te[ 6 ] = n13; te[ 7 ] = n23; te[ 8 ] = n33;
  1392. return this;
  1393. }
  1394. /**
  1395. * Sets this matrix to the 3x3 identity matrix.
  1396. *
  1397. * @return {Matrix3} A reference to this matrix.
  1398. */
  1399. identity() {
  1400. this.set(
  1401. 1, 0, 0,
  1402. 0, 1, 0,
  1403. 0, 0, 1
  1404. );
  1405. return this;
  1406. }
  1407. /**
  1408. * Copies the values of the given matrix to this instance.
  1409. *
  1410. * @param {Matrix3} m - The matrix to copy.
  1411. * @return {Matrix3} A reference to this matrix.
  1412. */
  1413. copy( m ) {
  1414. const te = this.elements;
  1415. const me = m.elements;
  1416. te[ 0 ] = me[ 0 ]; te[ 1 ] = me[ 1 ]; te[ 2 ] = me[ 2 ];
  1417. te[ 3 ] = me[ 3 ]; te[ 4 ] = me[ 4 ]; te[ 5 ] = me[ 5 ];
  1418. te[ 6 ] = me[ 6 ]; te[ 7 ] = me[ 7 ]; te[ 8 ] = me[ 8 ];
  1419. return this;
  1420. }
  1421. /**
  1422. * Extracts the basis of this matrix into the three axis vectors provided.
  1423. *
  1424. * @param {Vector3} xAxis - The basis's x axis.
  1425. * @param {Vector3} yAxis - The basis's y axis.
  1426. * @param {Vector3} zAxis - The basis's z axis.
  1427. * @return {Matrix3} A reference to this matrix.
  1428. */
  1429. extractBasis( xAxis, yAxis, zAxis ) {
  1430. xAxis.setFromMatrix3Column( this, 0 );
  1431. yAxis.setFromMatrix3Column( this, 1 );
  1432. zAxis.setFromMatrix3Column( this, 2 );
  1433. return this;
  1434. }
  1435. /**
  1436. * Set this matrix to the upper 3x3 matrix of the given 4x4 matrix.
  1437. *
  1438. * @param {Matrix4} m - The 4x4 matrix.
  1439. * @return {Matrix3} A reference to this matrix.
  1440. */
  1441. setFromMatrix4( m ) {
  1442. const me = m.elements;
  1443. this.set(
  1444. me[ 0 ], me[ 4 ], me[ 8 ],
  1445. me[ 1 ], me[ 5 ], me[ 9 ],
  1446. me[ 2 ], me[ 6 ], me[ 10 ]
  1447. );
  1448. return this;
  1449. }
  1450. /**
  1451. * Post-multiplies this matrix by the given 3x3 matrix.
  1452. *
  1453. * @param {Matrix3} m - The matrix to multiply with.
  1454. * @return {Matrix3} A reference to this matrix.
  1455. */
  1456. multiply( m ) {
  1457. return this.multiplyMatrices( this, m );
  1458. }
  1459. /**
  1460. * Pre-multiplies this matrix by the given 3x3 matrix.
  1461. *
  1462. * @param {Matrix3} m - The matrix to multiply with.
  1463. * @return {Matrix3} A reference to this matrix.
  1464. */
  1465. premultiply( m ) {
  1466. return this.multiplyMatrices( m, this );
  1467. }
  1468. /**
  1469. * Multiples the given 3x3 matrices and stores the result
  1470. * in this matrix.
  1471. *
  1472. * @param {Matrix3} a - The first matrix.
  1473. * @param {Matrix3} b - The second matrix.
  1474. * @return {Matrix3} A reference to this matrix.
  1475. */
  1476. multiplyMatrices( a, b ) {
  1477. const ae = a.elements;
  1478. const be = b.elements;
  1479. const te = this.elements;
  1480. const a11 = ae[ 0 ], a12 = ae[ 3 ], a13 = ae[ 6 ];
  1481. const a21 = ae[ 1 ], a22 = ae[ 4 ], a23 = ae[ 7 ];
  1482. const a31 = ae[ 2 ], a32 = ae[ 5 ], a33 = ae[ 8 ];
  1483. const b11 = be[ 0 ], b12 = be[ 3 ], b13 = be[ 6 ];
  1484. const b21 = be[ 1 ], b22 = be[ 4 ], b23 = be[ 7 ];
  1485. const b31 = be[ 2 ], b32 = be[ 5 ], b33 = be[ 8 ];
  1486. te[ 0 ] = a11 * b11 + a12 * b21 + a13 * b31;
  1487. te[ 3 ] = a11 * b12 + a12 * b22 + a13 * b32;
  1488. te[ 6 ] = a11 * b13 + a12 * b23 + a13 * b33;
  1489. te[ 1 ] = a21 * b11 + a22 * b21 + a23 * b31;
  1490. te[ 4 ] = a21 * b12 + a22 * b22 + a23 * b32;
  1491. te[ 7 ] = a21 * b13 + a22 * b23 + a23 * b33;
  1492. te[ 2 ] = a31 * b11 + a32 * b21 + a33 * b31;
  1493. te[ 5 ] = a31 * b12 + a32 * b22 + a33 * b32;
  1494. te[ 8 ] = a31 * b13 + a32 * b23 + a33 * b33;
  1495. return this;
  1496. }
  1497. /**
  1498. * Multiplies every component of the matrix by the given scalar.
  1499. *
  1500. * @param {number} s - The scalar.
  1501. * @return {Matrix3} A reference to this matrix.
  1502. */
  1503. multiplyScalar( s ) {
  1504. const te = this.elements;
  1505. te[ 0 ] *= s; te[ 3 ] *= s; te[ 6 ] *= s;
  1506. te[ 1 ] *= s; te[ 4 ] *= s; te[ 7 ] *= s;
  1507. te[ 2 ] *= s; te[ 5 ] *= s; te[ 8 ] *= s;
  1508. return this;
  1509. }
  1510. /**
  1511. * Computes and returns the determinant of this matrix.
  1512. *
  1513. * @return {number} The determinant.
  1514. */
  1515. determinant() {
  1516. const te = this.elements;
  1517. const a = te[ 0 ], b = te[ 1 ], c = te[ 2 ],
  1518. d = te[ 3 ], e = te[ 4 ], f = te[ 5 ],
  1519. g = te[ 6 ], h = te[ 7 ], i = te[ 8 ];
  1520. return a * e * i - a * f * h - b * d * i + b * f * g + c * d * h - c * e * g;
  1521. }
  1522. /**
  1523. * Inverts this matrix, using the [analytic method]{@link https://en.wikipedia.org/wiki/Invertible_matrix#Analytic_solution}.
  1524. * You can not invert with a determinant of zero. If you attempt this, the method produces
  1525. * a zero matrix instead.
  1526. *
  1527. * @return {Matrix3} A reference to this matrix.
  1528. */
  1529. invert() {
  1530. const te = this.elements,
  1531. n11 = te[ 0 ], n21 = te[ 1 ], n31 = te[ 2 ],
  1532. n12 = te[ 3 ], n22 = te[ 4 ], n32 = te[ 5 ],
  1533. n13 = te[ 6 ], n23 = te[ 7 ], n33 = te[ 8 ],
  1534. t11 = n33 * n22 - n32 * n23,
  1535. t12 = n32 * n13 - n33 * n12,
  1536. t13 = n23 * n12 - n22 * n13,
  1537. det = n11 * t11 + n21 * t12 + n31 * t13;
  1538. if ( det === 0 ) return this.set( 0, 0, 0, 0, 0, 0, 0, 0, 0 );
  1539. const detInv = 1 / det;
  1540. te[ 0 ] = t11 * detInv;
  1541. te[ 1 ] = ( n31 * n23 - n33 * n21 ) * detInv;
  1542. te[ 2 ] = ( n32 * n21 - n31 * n22 ) * detInv;
  1543. te[ 3 ] = t12 * detInv;
  1544. te[ 4 ] = ( n33 * n11 - n31 * n13 ) * detInv;
  1545. te[ 5 ] = ( n31 * n12 - n32 * n11 ) * detInv;
  1546. te[ 6 ] = t13 * detInv;
  1547. te[ 7 ] = ( n21 * n13 - n23 * n11 ) * detInv;
  1548. te[ 8 ] = ( n22 * n11 - n21 * n12 ) * detInv;
  1549. return this;
  1550. }
  1551. /**
  1552. * Transposes this matrix in place.
  1553. *
  1554. * @return {Matrix3} A reference to this matrix.
  1555. */
  1556. transpose() {
  1557. let tmp;
  1558. const m = this.elements;
  1559. tmp = m[ 1 ]; m[ 1 ] = m[ 3 ]; m[ 3 ] = tmp;
  1560. tmp = m[ 2 ]; m[ 2 ] = m[ 6 ]; m[ 6 ] = tmp;
  1561. tmp = m[ 5 ]; m[ 5 ] = m[ 7 ]; m[ 7 ] = tmp;
  1562. return this;
  1563. }
  1564. /**
  1565. * Computes the normal matrix which is the inverse transpose of the upper
  1566. * left 3x3 portion of the given 4x4 matrix.
  1567. *
  1568. * @param {Matrix4} matrix4 - The 4x4 matrix.
  1569. * @return {Matrix3} A reference to this matrix.
  1570. */
  1571. getNormalMatrix( matrix4 ) {
  1572. return this.setFromMatrix4( matrix4 ).invert().transpose();
  1573. }
  1574. /**
  1575. * Transposes this matrix into the supplied array, and returns itself unchanged.
  1576. *
  1577. * @param {Array<number>} r - An arry to store the transposed matrix elements.
  1578. * @return {Matrix3} A reference to this matrix.
  1579. */
  1580. transposeIntoArray( r ) {
  1581. const m = this.elements;
  1582. r[ 0 ] = m[ 0 ];
  1583. r[ 1 ] = m[ 3 ];
  1584. r[ 2 ] = m[ 6 ];
  1585. r[ 3 ] = m[ 1 ];
  1586. r[ 4 ] = m[ 4 ];
  1587. r[ 5 ] = m[ 7 ];
  1588. r[ 6 ] = m[ 2 ];
  1589. r[ 7 ] = m[ 5 ];
  1590. r[ 8 ] = m[ 8 ];
  1591. return this;
  1592. }
  1593. /**
  1594. * Sets the UV transform matrix from offset, repeat, rotation, and center.
  1595. *
  1596. * @param {number} tx - Offset x.
  1597. * @param {number} ty - Offset y.
  1598. * @param {number} sx - Repeat x.
  1599. * @param {number} sy - Repeat y.
  1600. * @param {number} rotation - Rotation, in radians. Positive values rotate counterclockwise.
  1601. * @param {number} cx - Center x of rotation.
  1602. * @param {number} cy - Center y of rotation
  1603. * @return {Matrix3} A reference to this matrix.
  1604. */
  1605. setUvTransform( tx, ty, sx, sy, rotation, cx, cy ) {
  1606. const c = Math.cos( rotation );
  1607. const s = Math.sin( rotation );
  1608. this.set(
  1609. sx * c, sx * s, - sx * ( c * cx + s * cy ) + cx + tx,
  1610. - sy * s, sy * c, - sy * ( - s * cx + c * cy ) + cy + ty,
  1611. 0, 0, 1
  1612. );
  1613. return this;
  1614. }
  1615. /**
  1616. * Scales this matrix with the given scalar values.
  1617. *
  1618. * @param {number} sx - The amount to scale in the X axis.
  1619. * @param {number} sy - The amount to scale in the Y axis.
  1620. * @return {Matrix3} A reference to this matrix.
  1621. */
  1622. scale( sx, sy ) {
  1623. this.premultiply( _m3.makeScale( sx, sy ) );
  1624. return this;
  1625. }
  1626. /**
  1627. * Rotates this matrix by the given angle.
  1628. *
  1629. * @param {number} theta - The rotation in radians.
  1630. * @return {Matrix3} A reference to this matrix.
  1631. */
  1632. rotate( theta ) {
  1633. this.premultiply( _m3.makeRotation( - theta ) );
  1634. return this;
  1635. }
  1636. /**
  1637. * Translates this matrix by the given scalar values.
  1638. *
  1639. * @param {number} tx - The amount to translate in the X axis.
  1640. * @param {number} ty - The amount to translate in the Y axis.
  1641. * @return {Matrix3} A reference to this matrix.
  1642. */
  1643. translate( tx, ty ) {
  1644. this.premultiply( _m3.makeTranslation( tx, ty ) );
  1645. return this;
  1646. }
  1647. // for 2D Transforms
  1648. /**
  1649. * Sets this matrix as a 2D translation transform.
  1650. *
  1651. * @param {number|Vector2} x - The amount to translate in the X axis or alternatively a translation vector.
  1652. * @param {number} y - The amount to translate in the Y axis.
  1653. * @return {Matrix3} A reference to this matrix.
  1654. */
  1655. makeTranslation( x, y ) {
  1656. if ( x.isVector2 ) {
  1657. this.set(
  1658. 1, 0, x.x,
  1659. 0, 1, x.y,
  1660. 0, 0, 1
  1661. );
  1662. } else {
  1663. this.set(
  1664. 1, 0, x,
  1665. 0, 1, y,
  1666. 0, 0, 1
  1667. );
  1668. }
  1669. return this;
  1670. }
  1671. /**
  1672. * Sets this matrix as a 2D rotational transformation.
  1673. *
  1674. * @param {number} theta - The rotation in radians.
  1675. * @return {Matrix3} A reference to this matrix.
  1676. */
  1677. makeRotation( theta ) {
  1678. // counterclockwise
  1679. const c = Math.cos( theta );
  1680. const s = Math.sin( theta );
  1681. this.set(
  1682. c, - s, 0,
  1683. s, c, 0,
  1684. 0, 0, 1
  1685. );
  1686. return this;
  1687. }
  1688. /**
  1689. * Sets this matrix as a 2D scale transform.
  1690. *
  1691. * @param {number} x - The amount to scale in the X axis.
  1692. * @param {number} y - The amount to scale in the Y axis.
  1693. * @return {Matrix3} A reference to this matrix.
  1694. */
  1695. makeScale( x, y ) {
  1696. this.set(
  1697. x, 0, 0,
  1698. 0, y, 0,
  1699. 0, 0, 1
  1700. );
  1701. return this;
  1702. }
  1703. /**
  1704. * Returns `true` if this matrix is equal with the given one.
  1705. *
  1706. * @param {Matrix3} matrix - The matrix to test for equality.
  1707. * @return {boolean} Whether this matrix is equal with the given one.
  1708. */
  1709. equals( matrix ) {
  1710. const te = this.elements;
  1711. const me = matrix.elements;
  1712. for ( let i = 0; i < 9; i ++ ) {
  1713. if ( te[ i ] !== me[ i ] ) return false;
  1714. }
  1715. return true;
  1716. }
  1717. /**
  1718. * Sets the elements of the matrix from the given array.
  1719. *
  1720. * @param {Array<number>} array - The matrix elements in column-major order.
  1721. * @param {number} [offset=0] - Index of the first element in the array.
  1722. * @return {Matrix3} A reference to this matrix.
  1723. */
  1724. fromArray( array, offset = 0 ) {
  1725. for ( let i = 0; i < 9; i ++ ) {
  1726. this.elements[ i ] = array[ i + offset ];
  1727. }
  1728. return this;
  1729. }
  1730. /**
  1731. * Writes the elements of this matrix to the given array. If no array is provided,
  1732. * the method returns a new instance.
  1733. *
  1734. * @param {Array<number>} [array=[]] - The target array holding the matrix elements in column-major order.
  1735. * @param {number} [offset=0] - Index of the first element in the array.
  1736. * @return {Array<number>} The matrix elements in column-major order.
  1737. */
  1738. toArray( array = [], offset = 0 ) {
  1739. const te = this.elements;
  1740. array[ offset ] = te[ 0 ];
  1741. array[ offset + 1 ] = te[ 1 ];
  1742. array[ offset + 2 ] = te[ 2 ];
  1743. array[ offset + 3 ] = te[ 3 ];
  1744. array[ offset + 4 ] = te[ 4 ];
  1745. array[ offset + 5 ] = te[ 5 ];
  1746. array[ offset + 6 ] = te[ 6 ];
  1747. array[ offset + 7 ] = te[ 7 ];
  1748. array[ offset + 8 ] = te[ 8 ];
  1749. return array;
  1750. }
  1751. /**
  1752. * Returns a matrix with copied values from this instance.
  1753. *
  1754. * @return {Matrix3} A clone of this instance.
  1755. */
  1756. clone() {
  1757. return new this.constructor().fromArray( this.elements );
  1758. }
  1759. }
  1760. const _m3 = /*@__PURE__*/ new Matrix3();
  1761. function arrayNeedsUint32( array ) {
  1762. // assumes larger values usually on last
  1763. for ( let i = array.length - 1; i >= 0; -- i ) {
  1764. if ( array[ i ] >= 65535 ) return true; // account for PRIMITIVE_RESTART_FIXED_INDEX, #24565
  1765. }
  1766. return false;
  1767. }
  1768. const TYPED_ARRAYS = {
  1769. Int8Array: Int8Array,
  1770. Uint8Array: Uint8Array,
  1771. Uint8ClampedArray: Uint8ClampedArray,
  1772. Int16Array: Int16Array,
  1773. Uint16Array: Uint16Array,
  1774. Int32Array: Int32Array,
  1775. Uint32Array: Uint32Array,
  1776. Float32Array: Float32Array,
  1777. Float64Array: Float64Array
  1778. };
  1779. function getTypedArray( type, buffer ) {
  1780. return new TYPED_ARRAYS[ type ]( buffer );
  1781. }
  1782. function createElementNS( name ) {
  1783. return document.createElementNS( 'http://www.w3.org/1999/xhtml', name );
  1784. }
  1785. function createCanvasElement() {
  1786. const canvas = createElementNS( 'canvas' );
  1787. canvas.style.display = 'block';
  1788. return canvas;
  1789. }
  1790. const _cache = {};
  1791. function warnOnce( message ) {
  1792. if ( message in _cache ) return;
  1793. _cache[ message ] = true;
  1794. console.warn( message );
  1795. }
  1796. function probeAsync( gl, sync, interval ) {
  1797. return new Promise( function ( resolve, reject ) {
  1798. function probe() {
  1799. switch ( gl.clientWaitSync( sync, gl.SYNC_FLUSH_COMMANDS_BIT, 0 ) ) {
  1800. case gl.WAIT_FAILED:
  1801. reject();
  1802. break;
  1803. case gl.TIMEOUT_EXPIRED:
  1804. setTimeout( probe, interval );
  1805. break;
  1806. default:
  1807. resolve();
  1808. }
  1809. }
  1810. setTimeout( probe, interval );
  1811. } );
  1812. }
  1813. function toNormalizedProjectionMatrix( projectionMatrix ) {
  1814. const m = projectionMatrix.elements;
  1815. // Convert [-1, 1] to [0, 1] projection matrix
  1816. m[ 2 ] = 0.5 * m[ 2 ] + 0.5 * m[ 3 ];
  1817. m[ 6 ] = 0.5 * m[ 6 ] + 0.5 * m[ 7 ];
  1818. m[ 10 ] = 0.5 * m[ 10 ] + 0.5 * m[ 11 ];
  1819. m[ 14 ] = 0.5 * m[ 14 ] + 0.5 * m[ 15 ];
  1820. }
  1821. function toReversedProjectionMatrix( projectionMatrix ) {
  1822. const m = projectionMatrix.elements;
  1823. const isPerspectiveMatrix = m[ 11 ] === -1;
  1824. // Reverse [0, 1] projection matrix
  1825. if ( isPerspectiveMatrix ) {
  1826. m[ 10 ] = - m[ 10 ] - 1;
  1827. m[ 14 ] = - m[ 14 ];
  1828. } else {
  1829. m[ 10 ] = - m[ 10 ];
  1830. m[ 14 ] = - m[ 14 ] + 1;
  1831. }
  1832. }
  1833. const LINEAR_REC709_TO_XYZ = /*@__PURE__*/ new Matrix3().set(
  1834. 0.4123908, 0.3575843, 0.1804808,
  1835. 0.2126390, 0.7151687, 0.0721923,
  1836. 0.0193308, 0.1191948, 0.9505322
  1837. );
  1838. const XYZ_TO_LINEAR_REC709 = /*@__PURE__*/ new Matrix3().set(
  1839. 3.2409699, -1.5373832, -0.4986108,
  1840. -0.9692436, 1.8759675, 0.0415551,
  1841. 0.0556301, -0.203977, 1.0569715
  1842. );
  1843. function createColorManagement() {
  1844. const ColorManagement = {
  1845. enabled: true,
  1846. workingColorSpace: LinearSRGBColorSpace,
  1847. /**
  1848. * Implementations of supported color spaces.
  1849. *
  1850. * Required:
  1851. * - primaries: chromaticity coordinates [ rx ry gx gy bx by ]
  1852. * - whitePoint: reference white [ x y ]
  1853. * - transfer: transfer function (pre-defined)
  1854. * - toXYZ: Matrix3 RGB to XYZ transform
  1855. * - fromXYZ: Matrix3 XYZ to RGB transform
  1856. * - luminanceCoefficients: RGB luminance coefficients
  1857. *
  1858. * Optional:
  1859. * - outputColorSpaceConfig: { drawingBufferColorSpace: ColorSpace }
  1860. * - workingColorSpaceConfig: { unpackColorSpace: ColorSpace }
  1861. *
  1862. * Reference:
  1863. * - https://www.russellcottrell.com/photo/matrixCalculator.htm
  1864. */
  1865. spaces: {},
  1866. convert: function ( color, sourceColorSpace, targetColorSpace ) {
  1867. if ( this.enabled === false || sourceColorSpace === targetColorSpace || ! sourceColorSpace || ! targetColorSpace ) {
  1868. return color;
  1869. }
  1870. if ( this.spaces[ sourceColorSpace ].transfer === SRGBTransfer ) {
  1871. color.r = SRGBToLinear( color.r );
  1872. color.g = SRGBToLinear( color.g );
  1873. color.b = SRGBToLinear( color.b );
  1874. }
  1875. if ( this.spaces[ sourceColorSpace ].primaries !== this.spaces[ targetColorSpace ].primaries ) {
  1876. color.applyMatrix3( this.spaces[ sourceColorSpace ].toXYZ );
  1877. color.applyMatrix3( this.spaces[ targetColorSpace ].fromXYZ );
  1878. }
  1879. if ( this.spaces[ targetColorSpace ].transfer === SRGBTransfer ) {
  1880. color.r = LinearToSRGB( color.r );
  1881. color.g = LinearToSRGB( color.g );
  1882. color.b = LinearToSRGB( color.b );
  1883. }
  1884. return color;
  1885. },
  1886. fromWorkingColorSpace: function ( color, targetColorSpace ) {
  1887. return this.convert( color, this.workingColorSpace, targetColorSpace );
  1888. },
  1889. toWorkingColorSpace: function ( color, sourceColorSpace ) {
  1890. return this.convert( color, sourceColorSpace, this.workingColorSpace );
  1891. },
  1892. getPrimaries: function ( colorSpace ) {
  1893. return this.spaces[ colorSpace ].primaries;
  1894. },
  1895. getTransfer: function ( colorSpace ) {
  1896. if ( colorSpace === NoColorSpace ) return LinearTransfer;
  1897. return this.spaces[ colorSpace ].transfer;
  1898. },
  1899. getLuminanceCoefficients: function ( target, colorSpace = this.workingColorSpace ) {
  1900. return target.fromArray( this.spaces[ colorSpace ].luminanceCoefficients );
  1901. },
  1902. define: function ( colorSpaces ) {
  1903. Object.assign( this.spaces, colorSpaces );
  1904. },
  1905. // Internal APIs
  1906. _getMatrix: function ( targetMatrix, sourceColorSpace, targetColorSpace ) {
  1907. return targetMatrix
  1908. .copy( this.spaces[ sourceColorSpace ].toXYZ )
  1909. .multiply( this.spaces[ targetColorSpace ].fromXYZ );
  1910. },
  1911. _getDrawingBufferColorSpace: function ( colorSpace ) {
  1912. return this.spaces[ colorSpace ].outputColorSpaceConfig.drawingBufferColorSpace;
  1913. },
  1914. _getUnpackColorSpace: function ( colorSpace = this.workingColorSpace ) {
  1915. return this.spaces[ colorSpace ].workingColorSpaceConfig.unpackColorSpace;
  1916. }
  1917. };
  1918. /******************************************************************************
  1919. * sRGB definitions
  1920. */
  1921. const REC709_PRIMARIES = [ 0.640, 0.330, 0.300, 0.600, 0.150, 0.060 ];
  1922. const REC709_LUMINANCE_COEFFICIENTS = [ 0.2126, 0.7152, 0.0722 ];
  1923. const D65 = [ 0.3127, 0.3290 ];
  1924. ColorManagement.define( {
  1925. [ LinearSRGBColorSpace ]: {
  1926. primaries: REC709_PRIMARIES,
  1927. whitePoint: D65,
  1928. transfer: LinearTransfer,
  1929. toXYZ: LINEAR_REC709_TO_XYZ,
  1930. fromXYZ: XYZ_TO_LINEAR_REC709,
  1931. luminanceCoefficients: REC709_LUMINANCE_COEFFICIENTS,
  1932. workingColorSpaceConfig: { unpackColorSpace: SRGBColorSpace },
  1933. outputColorSpaceConfig: { drawingBufferColorSpace: SRGBColorSpace }
  1934. },
  1935. [ SRGBColorSpace ]: {
  1936. primaries: REC709_PRIMARIES,
  1937. whitePoint: D65,
  1938. transfer: SRGBTransfer,
  1939. toXYZ: LINEAR_REC709_TO_XYZ,
  1940. fromXYZ: XYZ_TO_LINEAR_REC709,
  1941. luminanceCoefficients: REC709_LUMINANCE_COEFFICIENTS,
  1942. outputColorSpaceConfig: { drawingBufferColorSpace: SRGBColorSpace }
  1943. },
  1944. } );
  1945. return ColorManagement;
  1946. }
  1947. const ColorManagement = /*@__PURE__*/ createColorManagement();
  1948. function SRGBToLinear( c ) {
  1949. return ( c < 0.04045 ) ? c * 0.0773993808 : Math.pow( c * 0.9478672986 + 0.0521327014, 2.4 );
  1950. }
  1951. function LinearToSRGB( c ) {
  1952. return ( c < 0.0031308 ) ? c * 12.92 : 1.055 * ( Math.pow( c, 0.41666 ) ) - 0.055;
  1953. }
  1954. let _canvas;
  1955. /**
  1956. * A class containing utility functions for images.
  1957. *
  1958. * @hideconstructor
  1959. */
  1960. class ImageUtils {
  1961. /**
  1962. * Returns a data URI containing a representation of the given image.
  1963. *
  1964. * @param {(HTMLImageElement|HTMLCanvasElement)} image - The image object.
  1965. * @return {string} The data URI.
  1966. */
  1967. static getDataURL( image ) {
  1968. if ( /^data:/i.test( image.src ) ) {
  1969. return image.src;
  1970. }
  1971. if ( typeof HTMLCanvasElement === 'undefined' ) {
  1972. return image.src;
  1973. }
  1974. let canvas;
  1975. if ( image instanceof HTMLCanvasElement ) {
  1976. canvas = image;
  1977. } else {
  1978. if ( _canvas === undefined ) _canvas = createElementNS( 'canvas' );
  1979. _canvas.width = image.width;
  1980. _canvas.height = image.height;
  1981. const context = _canvas.getContext( '2d' );
  1982. if ( image instanceof ImageData ) {
  1983. context.putImageData( image, 0, 0 );
  1984. } else {
  1985. context.drawImage( image, 0, 0, image.width, image.height );
  1986. }
  1987. canvas = _canvas;
  1988. }
  1989. return canvas.toDataURL( 'image/png' );
  1990. }
  1991. /**
  1992. * Converts the given sRGB image data to linear color space.
  1993. *
  1994. * @param {(HTMLImageElement|HTMLCanvasElement|ImageBitmap|Object)} image - The image object.
  1995. * @return {HTMLCanvasElement|Object} The converted image.
  1996. */
  1997. static sRGBToLinear( image ) {
  1998. if ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) ||
  1999. ( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) ||
  2000. ( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) ) {
  2001. const canvas = createElementNS( 'canvas' );
  2002. canvas.width = image.width;
  2003. canvas.height = image.height;
  2004. const context = canvas.getContext( '2d' );
  2005. context.drawImage( image, 0, 0, image.width, image.height );
  2006. const imageData = context.getImageData( 0, 0, image.width, image.height );
  2007. const data = imageData.data;
  2008. for ( let i = 0; i < data.length; i ++ ) {
  2009. data[ i ] = SRGBToLinear( data[ i ] / 255 ) * 255;
  2010. }
  2011. context.putImageData( imageData, 0, 0 );
  2012. return canvas;
  2013. } else if ( image.data ) {
  2014. const data = image.data.slice( 0 );
  2015. for ( let i = 0; i < data.length; i ++ ) {
  2016. if ( data instanceof Uint8Array || data instanceof Uint8ClampedArray ) {
  2017. data[ i ] = Math.floor( SRGBToLinear( data[ i ] / 255 ) * 255 );
  2018. } else {
  2019. // assuming float
  2020. data[ i ] = SRGBToLinear( data[ i ] );
  2021. }
  2022. }
  2023. return {
  2024. data: data,
  2025. width: image.width,
  2026. height: image.height
  2027. };
  2028. } else {
  2029. console.warn( 'THREE.ImageUtils.sRGBToLinear(): Unsupported image type. No color space conversion applied.' );
  2030. return image;
  2031. }
  2032. }
  2033. }
  2034. let _sourceId = 0;
  2035. class Source {
  2036. constructor( data = null ) {
  2037. this.isSource = true;
  2038. Object.defineProperty( this, 'id', { value: _sourceId ++ } );
  2039. this.uuid = generateUUID();
  2040. this.data = data;
  2041. this.dataReady = true;
  2042. this.version = 0;
  2043. }
  2044. set needsUpdate( value ) {
  2045. if ( value === true ) this.version ++;
  2046. }
  2047. toJSON( meta ) {
  2048. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  2049. if ( ! isRootObject && meta.images[ this.uuid ] !== undefined ) {
  2050. return meta.images[ this.uuid ];
  2051. }
  2052. const output = {
  2053. uuid: this.uuid,
  2054. url: ''
  2055. };
  2056. const data = this.data;
  2057. if ( data !== null ) {
  2058. let url;
  2059. if ( Array.isArray( data ) ) {
  2060. // cube texture
  2061. url = [];
  2062. for ( let i = 0, l = data.length; i < l; i ++ ) {
  2063. if ( data[ i ].isDataTexture ) {
  2064. url.push( serializeImage( data[ i ].image ) );
  2065. } else {
  2066. url.push( serializeImage( data[ i ] ) );
  2067. }
  2068. }
  2069. } else {
  2070. // texture
  2071. url = serializeImage( data );
  2072. }
  2073. output.url = url;
  2074. }
  2075. if ( ! isRootObject ) {
  2076. meta.images[ this.uuid ] = output;
  2077. }
  2078. return output;
  2079. }
  2080. }
  2081. function serializeImage( image ) {
  2082. if ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) ||
  2083. ( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) ||
  2084. ( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) ) {
  2085. // default images
  2086. return ImageUtils.getDataURL( image );
  2087. } else {
  2088. if ( image.data ) {
  2089. // images of DataTexture
  2090. return {
  2091. data: Array.from( image.data ),
  2092. width: image.width,
  2093. height: image.height,
  2094. type: image.data.constructor.name
  2095. };
  2096. } else {
  2097. console.warn( 'THREE.Texture: Unable to serialize Texture.' );
  2098. return {};
  2099. }
  2100. }
  2101. }
  2102. let _textureId = 0;
  2103. /**
  2104. * Base class for all textures.
  2105. *
  2106. * Note: After the initial use of a texture, its dimensions, format, and type
  2107. * cannot be changed. Instead, call {@link Texture#dispose} on the texture and instantiate a new one.
  2108. *
  2109. * @augments EventDispatcher
  2110. */
  2111. class Texture extends EventDispatcher {
  2112. /**
  2113. * Constructs a new texture.
  2114. *
  2115. * @param {?Object} [image=Texture.DEFAULT_IMAGE] - The image holding the texture data.
  2116. * @param {number} [mapping=Texture.DEFAULT_MAPPING] - The texture mapping.
  2117. * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value.
  2118. * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value.
  2119. * @param {number} [magFilter=LinearFilter] - The mag filter value.
  2120. * @param {number} [minFilter=LinearFilter] - The min filter value.
  2121. * @param {number} [format=RGABFormat] - The min filter value.
  2122. * @param {number} [type=UnsignedByteType] - The min filter value.
  2123. * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The min filter value.
  2124. * @param {string} [colorSpace=NoColorSpace] - The min filter value.
  2125. */
  2126. 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 ) {
  2127. super();
  2128. /**
  2129. * This flag can be used for type testing.
  2130. *
  2131. * @type {boolean}
  2132. * @readonly
  2133. * @default true
  2134. */
  2135. this.isTexture = true;
  2136. /**
  2137. * The ID of the texture.
  2138. *
  2139. * @name Texture#id
  2140. * @type {number}
  2141. * @readonly
  2142. */
  2143. Object.defineProperty( this, 'id', { value: _textureId ++ } );
  2144. /**
  2145. * The UUID of the material.
  2146. *
  2147. * @type {string}
  2148. * @readonly
  2149. */
  2150. this.uuid = generateUUID();
  2151. /**
  2152. * The name of the material.
  2153. *
  2154. * @type {string}
  2155. */
  2156. this.name = '';
  2157. /**
  2158. * The data definition of a texture. A reference to the data source can be
  2159. * shared across textures. This is often useful in context of spritesheets
  2160. * where multiple textures render the same data but with different texture
  2161. * transformations.
  2162. *
  2163. * @type {Source}
  2164. */
  2165. this.source = new Source( image );
  2166. /**
  2167. * An array holding user-defined mipmaps.
  2168. *
  2169. * @type {Array<Object>}
  2170. */
  2171. this.mipmaps = [];
  2172. /**
  2173. * How the texture is applied to the object. The value `UVMapping`
  2174. * is the default, where texture or uv coordinates are used to apply the map.
  2175. *
  2176. * @type {(UVMapping|CubeReflectionMapping|CubeRefractionMapping|EquirectangularReflectionMapping|EquirectangularRefractionMapping|CubeUVReflectionMapping)}
  2177. * @default UVMapping
  2178. */
  2179. this.mapping = mapping;
  2180. /**
  2181. * Lets you select the uv attribute to map the texture to. `0` for `uv`,
  2182. * `1` for `uv1`, `2` for `uv2` and `3` for `uv3`.
  2183. *
  2184. * @type {number}
  2185. * @default 0
  2186. */
  2187. this.channel = 0;
  2188. /**
  2189. * This defines how the texture is wrapped horizontally and corresponds to
  2190. * *U* in UV mapping.
  2191. *
  2192. * @type {(RepeatWrapping|ClampToEdgeWrapping|MirroredRepeatWrapping)}
  2193. * @default ClampToEdgeWrapping
  2194. */
  2195. this.wrapS = wrapS;
  2196. /**
  2197. * This defines how the texture is wrapped horizontally and corresponds to
  2198. * *V* in UV mapping.
  2199. *
  2200. * @type {(RepeatWrapping|ClampToEdgeWrapping|MirroredRepeatWrapping)}
  2201. * @default ClampToEdgeWrapping
  2202. */
  2203. this.wrapT = wrapT;
  2204. /**
  2205. * How the texture is sampled when a texel covers more than one pixel.
  2206. *
  2207. * @type {(NearestFilter|NearestMipmapNearestFilter|NearestMipmapLinearFilter|LinearFilter|LinearMipmapNearestFilter|LinearMipmapLinearFilter)}
  2208. * @default LinearFilter
  2209. */
  2210. this.magFilter = magFilter;
  2211. /**
  2212. * How the texture is sampled when a texel covers less than one pixel.
  2213. *
  2214. * @type {(NearestFilter|NearestMipmapNearestFilter|NearestMipmapLinearFilter|LinearFilter|LinearMipmapNearestFilter|LinearMipmapLinearFilter)}
  2215. * @default LinearMipmapLinearFilter
  2216. */
  2217. this.minFilter = minFilter;
  2218. /**
  2219. * The number of samples taken along the axis through the pixel that has the
  2220. * highest density of texels. By default, this value is `1`. A higher value
  2221. * gives a less blurry result than a basic mipmap, at the cost of more
  2222. * texture samples being used.
  2223. *
  2224. * @type {number}
  2225. * @default 0
  2226. */
  2227. this.anisotropy = anisotropy;
  2228. /**
  2229. * The format of the texture.
  2230. *
  2231. * @type {number}
  2232. * @default RGBAFormat
  2233. */
  2234. this.format = format;
  2235. /**
  2236. * The default internal format is derived from {@link Texture#format} and {@link Texture#type} and
  2237. * defines how the texture data is going to be stored on the GPU.
  2238. *
  2239. * This property allows to overwrite the default format.
  2240. *
  2241. * @type {?string}
  2242. * @default null
  2243. */
  2244. this.internalFormat = null;
  2245. /**
  2246. * The data type of the texture.
  2247. *
  2248. * @type {number}
  2249. * @default UnsignedByteType
  2250. */
  2251. this.type = type;
  2252. /**
  2253. * How much a single repetition of the texture is offset from the beginning,
  2254. * in each direction U and V. Typical range is `0.0` to `1.0`.
  2255. *
  2256. * @type {Vector2}
  2257. * @default (0,0)
  2258. */
  2259. this.offset = new Vector2( 0, 0 );
  2260. /**
  2261. * How many times the texture is repeated across the surface, in each
  2262. * direction U and V. If repeat is set greater than `1` in either direction,
  2263. * the corresponding wrap parameter should also be set to `RepeatWrapping`
  2264. * or `MirroredRepeatWrapping` to achieve the desired tiling effect.
  2265. *
  2266. * @type {Vector2}
  2267. * @default (1,1)
  2268. */
  2269. this.repeat = new Vector2( 1, 1 );
  2270. /**
  2271. * The point around which rotation occurs. A value of `(0.5, 0.5)` corresponds
  2272. * to the center of the texture. Default is `(0, 0)`, the lower left.
  2273. *
  2274. * @type {Vector2}
  2275. * @default (0,0)
  2276. */
  2277. this.center = new Vector2( 0, 0 );
  2278. /**
  2279. * How much the texture is rotated around the center point, in radians.
  2280. * Positive values are counter-clockwise.
  2281. *
  2282. * @type {number}
  2283. * @default 0
  2284. */
  2285. this.rotation = 0;
  2286. /**
  2287. * Whether to update the texture's uv-transformation {@link Texture#matrix}
  2288. * from the properties {@link Texture#offset}, {@link Texture#repeat},
  2289. * {@link Texture#rotation}, and {@link Texture#center}.
  2290. *
  2291. * Set this to `false` if you are specifying the uv-transform matrix directly.
  2292. *
  2293. * @type {boolean}
  2294. * @default true
  2295. */
  2296. this.matrixAutoUpdate = true;
  2297. /**
  2298. * The uv-transformation matrix of the texture.
  2299. *
  2300. * @type {Matrix3}
  2301. */
  2302. this.matrix = new Matrix3();
  2303. /**
  2304. * Whether to generate mipmaps (if possible) for a texture.
  2305. *
  2306. * Set this to `false` if you are creating mipmaps manually.
  2307. *
  2308. * @type {boolean}
  2309. * @default true
  2310. */
  2311. this.generateMipmaps = true;
  2312. /**
  2313. * If set to `true`, the alpha channel, if present, is multiplied into the
  2314. * color channels when the texture is uploaded to the GPU.
  2315. *
  2316. * Note that this property has no effect when using `ImageBitmap`. You need to
  2317. * configure premultiply alpha on bitmap creation instead.
  2318. *
  2319. * @type {boolean}
  2320. * @default false
  2321. */
  2322. this.premultiplyAlpha = false;
  2323. /**
  2324. * If set to `true`, the texture is flipped along the vertical axis when
  2325. * uploaded to the GPU.
  2326. *
  2327. * Note that this property has no effect when using `ImageBitmap`. You need to
  2328. * configure the flip on bitmap creation instead.
  2329. *
  2330. * @type {boolean}
  2331. * @default true
  2332. */
  2333. this.flipY = true;
  2334. /**
  2335. * Specifies the alignment requirements for the start of each pixel row in memory.
  2336. * The allowable values are `1` (byte-alignment), `2` (rows aligned to even-numbered bytes),
  2337. * `4` (word-alignment), and `8` (rows start on double-word boundaries).
  2338. *
  2339. * @type {number}
  2340. * @default 4
  2341. */
  2342. this.unpackAlignment = 4; // valid values: 1, 2, 4, 8 (see http://www.khronos.org/opengles/sdk/docs/man/xhtml/glPixelStorei.xml)
  2343. /**
  2344. * Textures containing color data should be annotated with `SRGBColorSpace` or `LinearSRGBColorSpace`.
  2345. *
  2346. * @type {string}
  2347. * @default NoColorSpace
  2348. */
  2349. this.colorSpace = colorSpace;
  2350. /**
  2351. * An object that can be used to store custom data about the texture. It
  2352. * should not hold references to functions as these will not be cloned.
  2353. *
  2354. * @type {Object}
  2355. */
  2356. this.userData = {};
  2357. /**
  2358. * This starts at `0` and counts how many times {@link Texture#needsUpdate} is set to `true`.
  2359. *
  2360. * @type {number}
  2361. * @readonly
  2362. * @default 0
  2363. */
  2364. this.version = 0;
  2365. /**
  2366. * A callback function, called when the texture is updated (e.g., when
  2367. * {@link Texture#needsUpdate} has been set to true and then the texture is used).
  2368. *
  2369. * @type {?Function}
  2370. * @default null
  2371. */
  2372. this.onUpdate = null;
  2373. /**
  2374. * An optional back reference to the textures render target.
  2375. *
  2376. * @type {?(RenderTarget|WebGLRenderTarget)}
  2377. * @default null
  2378. */
  2379. this.renderTarget = null;
  2380. /**
  2381. * Indicates whether a texture belongs to a render target or not.
  2382. *
  2383. * @type {boolean}
  2384. * @readonly
  2385. * @default false
  2386. */
  2387. this.isRenderTargetTexture = false;
  2388. /**
  2389. * Indicates whether this texture should be processed by `PMREMGenerator` or not
  2390. * (only relevant for render target textures).
  2391. *
  2392. * @type {number}
  2393. * @readonly
  2394. * @default 0
  2395. */
  2396. this.pmremVersion = 0;
  2397. }
  2398. /**
  2399. * The image object holding the texture data.
  2400. *
  2401. * @type {?Object}
  2402. */
  2403. get image() {
  2404. return this.source.data;
  2405. }
  2406. set image( value = null ) {
  2407. this.source.data = value;
  2408. }
  2409. /**
  2410. * Updates the texture transformation matrix from the from the properties {@link Texture#offset},
  2411. * {@link Texture#repeat}, {@link Texture#rotation}, and {@link Texture#center}.
  2412. */
  2413. updateMatrix() {
  2414. this.matrix.setUvTransform( this.offset.x, this.offset.y, this.repeat.x, this.repeat.y, this.rotation, this.center.x, this.center.y );
  2415. }
  2416. /**
  2417. * Returns a new texture with copied values from this instance.
  2418. *
  2419. * @return {Texture} A clone of this instance.
  2420. */
  2421. clone() {
  2422. return new this.constructor().copy( this );
  2423. }
  2424. /**
  2425. * Copies the values of the given texture to this instance.
  2426. *
  2427. * @param {Texture} source - The texture to copy.
  2428. * @return {Texture} A reference to this instance.
  2429. */
  2430. copy( source ) {
  2431. this.name = source.name;
  2432. this.source = source.source;
  2433. this.mipmaps = source.mipmaps.slice( 0 );
  2434. this.mapping = source.mapping;
  2435. this.channel = source.channel;
  2436. this.wrapS = source.wrapS;
  2437. this.wrapT = source.wrapT;
  2438. this.magFilter = source.magFilter;
  2439. this.minFilter = source.minFilter;
  2440. this.anisotropy = source.anisotropy;
  2441. this.format = source.format;
  2442. this.internalFormat = source.internalFormat;
  2443. this.type = source.type;
  2444. this.offset.copy( source.offset );
  2445. this.repeat.copy( source.repeat );
  2446. this.center.copy( source.center );
  2447. this.rotation = source.rotation;
  2448. this.matrixAutoUpdate = source.matrixAutoUpdate;
  2449. this.matrix.copy( source.matrix );
  2450. this.generateMipmaps = source.generateMipmaps;
  2451. this.premultiplyAlpha = source.premultiplyAlpha;
  2452. this.flipY = source.flipY;
  2453. this.unpackAlignment = source.unpackAlignment;
  2454. this.colorSpace = source.colorSpace;
  2455. this.renderTarget = source.renderTarget;
  2456. this.isRenderTargetTexture = source.isRenderTargetTexture;
  2457. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  2458. this.needsUpdate = true;
  2459. return this;
  2460. }
  2461. /**
  2462. * Serializes the texture into JSON.
  2463. *
  2464. * @param {?(Object|string)} meta - An optional value holding meta information about the serialization.
  2465. * @return {Object} A JSON object representing the serialized texture.
  2466. * @see {@link ObjectLoader#parse}
  2467. */
  2468. toJSON( meta ) {
  2469. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  2470. if ( ! isRootObject && meta.textures[ this.uuid ] !== undefined ) {
  2471. return meta.textures[ this.uuid ];
  2472. }
  2473. const output = {
  2474. metadata: {
  2475. version: 4.6,
  2476. type: 'Texture',
  2477. generator: 'Texture.toJSON'
  2478. },
  2479. uuid: this.uuid,
  2480. name: this.name,
  2481. image: this.source.toJSON( meta ).uuid,
  2482. mapping: this.mapping,
  2483. channel: this.channel,
  2484. repeat: [ this.repeat.x, this.repeat.y ],
  2485. offset: [ this.offset.x, this.offset.y ],
  2486. center: [ this.center.x, this.center.y ],
  2487. rotation: this.rotation,
  2488. wrap: [ this.wrapS, this.wrapT ],
  2489. format: this.format,
  2490. internalFormat: this.internalFormat,
  2491. type: this.type,
  2492. colorSpace: this.colorSpace,
  2493. minFilter: this.minFilter,
  2494. magFilter: this.magFilter,
  2495. anisotropy: this.anisotropy,
  2496. flipY: this.flipY,
  2497. generateMipmaps: this.generateMipmaps,
  2498. premultiplyAlpha: this.premultiplyAlpha,
  2499. unpackAlignment: this.unpackAlignment
  2500. };
  2501. if ( Object.keys( this.userData ).length > 0 ) output.userData = this.userData;
  2502. if ( ! isRootObject ) {
  2503. meta.textures[ this.uuid ] = output;
  2504. }
  2505. return output;
  2506. }
  2507. /**
  2508. * Frees the GPU-related resources allocated by this instance. Call this
  2509. * method whenever this instance is no longer used in your app.
  2510. *
  2511. * @fires Texture#dispose
  2512. */
  2513. dispose() {
  2514. /**
  2515. * Fires when the texture has been disposed of.
  2516. *
  2517. * @event Texture#dispose
  2518. * @type {Object}
  2519. */
  2520. this.dispatchEvent( { type: 'dispose' } );
  2521. }
  2522. /**
  2523. * Transforms the given uv vector with the textures uv transformation matrix.
  2524. *
  2525. * @param {Vector2} uv - The uv vector.
  2526. * @return {Vector2} The transformed uv vector.
  2527. */
  2528. transformUv( uv ) {
  2529. if ( this.mapping !== UVMapping ) return uv;
  2530. uv.applyMatrix3( this.matrix );
  2531. if ( uv.x < 0 || uv.x > 1 ) {
  2532. switch ( this.wrapS ) {
  2533. case RepeatWrapping:
  2534. uv.x = uv.x - Math.floor( uv.x );
  2535. break;
  2536. case ClampToEdgeWrapping:
  2537. uv.x = uv.x < 0 ? 0 : 1;
  2538. break;
  2539. case MirroredRepeatWrapping:
  2540. if ( Math.abs( Math.floor( uv.x ) % 2 ) === 1 ) {
  2541. uv.x = Math.ceil( uv.x ) - uv.x;
  2542. } else {
  2543. uv.x = uv.x - Math.floor( uv.x );
  2544. }
  2545. break;
  2546. }
  2547. }
  2548. if ( uv.y < 0 || uv.y > 1 ) {
  2549. switch ( this.wrapT ) {
  2550. case RepeatWrapping:
  2551. uv.y = uv.y - Math.floor( uv.y );
  2552. break;
  2553. case ClampToEdgeWrapping:
  2554. uv.y = uv.y < 0 ? 0 : 1;
  2555. break;
  2556. case MirroredRepeatWrapping:
  2557. if ( Math.abs( Math.floor( uv.y ) % 2 ) === 1 ) {
  2558. uv.y = Math.ceil( uv.y ) - uv.y;
  2559. } else {
  2560. uv.y = uv.y - Math.floor( uv.y );
  2561. }
  2562. break;
  2563. }
  2564. }
  2565. if ( this.flipY ) {
  2566. uv.y = 1 - uv.y;
  2567. }
  2568. return uv;
  2569. }
  2570. /**
  2571. * Setting this property to `true` indicates the engine the texture
  2572. * must be updated in the next render. This triggers a texture upload
  2573. * to the GPU and ensures correct texture parameter configuration.
  2574. *
  2575. * @type {boolean}
  2576. * @default false
  2577. * @param {boolean} value
  2578. */
  2579. set needsUpdate( value ) {
  2580. if ( value === true ) {
  2581. this.version ++;
  2582. this.source.needsUpdate = true;
  2583. }
  2584. }
  2585. /**
  2586. * Setting this property to `true` indicates the engine the PMREM
  2587. * must be regenerated.
  2588. *
  2589. * @type {boolean}
  2590. * @default false
  2591. * @param {boolean} value
  2592. */
  2593. set needsPMREMUpdate( value ) {
  2594. if ( value === true ) {
  2595. this.pmremVersion ++;
  2596. }
  2597. }
  2598. }
  2599. /**
  2600. * The default image for all textures.
  2601. *
  2602. * @static
  2603. * @type {?Image}
  2604. * @default null
  2605. */
  2606. Texture.DEFAULT_IMAGE = null;
  2607. /**
  2608. * The default mapping for all textures.
  2609. *
  2610. * @static
  2611. * @type {number}
  2612. * @default UVMapping
  2613. */
  2614. Texture.DEFAULT_MAPPING = UVMapping;
  2615. /**
  2616. * The default anisotropy value for all textures.
  2617. *
  2618. * @static
  2619. * @type {number}
  2620. * @default 1
  2621. */
  2622. Texture.DEFAULT_ANISOTROPY = 1;
  2623. /**
  2624. * Class representing a 4D vector. A 4D vector is an ordered quadruplet of numbers
  2625. * (labeled x, y, z and w), which can be used to represent a number of things, such as:
  2626. *
  2627. * - A point in 4D space.
  2628. * - A direction and length in 4D space. In three.js the length will
  2629. * always be the Euclidean distance(straight-line distance) from `(0, 0, 0, 0)` to `(x, y, z, w)`
  2630. * and the direction is also measured from `(0, 0, 0, 0)` towards `(x, y, z, w)`.
  2631. * - Any arbitrary ordered quadruplet of numbers.
  2632. *
  2633. * There are other things a 4D vector can be used to represent, however these
  2634. * are the most common uses in *three.js*.
  2635. *
  2636. * Iterating through a vector instance will yield its components `(x, y, z, w)` in
  2637. * the corresponding order.
  2638. * ```js
  2639. * const a = new THREE.Vector4( 0, 1, 0, 0 );
  2640. *
  2641. * //no arguments; will be initialised to (0, 0, 0, 1)
  2642. * const b = new THREE.Vector4( );
  2643. *
  2644. * const d = a.dot( b );
  2645. * ```
  2646. */
  2647. class Vector4 {
  2648. /**
  2649. * Constructs a new 4D vector.
  2650. *
  2651. * @param {number} [x=0] - The x value of this vector.
  2652. * @param {number} [y=0] - The y value of this vector.
  2653. * @param {number} [z=0] - The z value of this vector.
  2654. * @param {number} [w=1] - The w value of this vector.
  2655. */
  2656. constructor( x = 0, y = 0, z = 0, w = 1 ) {
  2657. /**
  2658. * This flag can be used for type testing.
  2659. *
  2660. * @type {boolean}
  2661. * @readonly
  2662. * @default true
  2663. */
  2664. Vector4.prototype.isVector4 = true;
  2665. /**
  2666. * The x value of this vector.
  2667. *
  2668. * @type {number}
  2669. */
  2670. this.x = x;
  2671. /**
  2672. * The y value of this vector.
  2673. *
  2674. * @type {number}
  2675. */
  2676. this.y = y;
  2677. /**
  2678. * The z value of this vector.
  2679. *
  2680. * @type {number}
  2681. */
  2682. this.z = z;
  2683. /**
  2684. * The w value of this vector.
  2685. *
  2686. * @type {number}
  2687. */
  2688. this.w = w;
  2689. }
  2690. /**
  2691. * Alias for {@link Vector4#z}.
  2692. *
  2693. * @type {number}
  2694. */
  2695. get width() {
  2696. return this.z;
  2697. }
  2698. set width( value ) {
  2699. this.z = value;
  2700. }
  2701. /**
  2702. * Alias for {@link Vector4#w}.
  2703. *
  2704. * @type {number}
  2705. */
  2706. get height() {
  2707. return this.w;
  2708. }
  2709. set height( value ) {
  2710. this.w = value;
  2711. }
  2712. /**
  2713. * Sets the vector components.
  2714. *
  2715. * @param {number} x - The value of the x component.
  2716. * @param {number} y - The value of the y component.
  2717. * @param {number} z - The value of the z component.
  2718. * @param {number} w - The value of the w component.
  2719. * @return {Vector4} A reference to this vector.
  2720. */
  2721. set( x, y, z, w ) {
  2722. this.x = x;
  2723. this.y = y;
  2724. this.z = z;
  2725. this.w = w;
  2726. return this;
  2727. }
  2728. /**
  2729. * Sets the vector components to the same value.
  2730. *
  2731. * @param {number} scalar - The value to set for all vector components.
  2732. * @return {Vector4} A reference to this vector.
  2733. */
  2734. setScalar( scalar ) {
  2735. this.x = scalar;
  2736. this.y = scalar;
  2737. this.z = scalar;
  2738. this.w = scalar;
  2739. return this;
  2740. }
  2741. /**
  2742. * Sets the vector's x component to the given value
  2743. *
  2744. * @param {number} x - The value to set.
  2745. * @return {Vector4} A reference to this vector.
  2746. */
  2747. setX( x ) {
  2748. this.x = x;
  2749. return this;
  2750. }
  2751. /**
  2752. * Sets the vector's y component to the given value
  2753. *
  2754. * @param {number} y - The value to set.
  2755. * @return {Vector4} A reference to this vector.
  2756. */
  2757. setY( y ) {
  2758. this.y = y;
  2759. return this;
  2760. }
  2761. /**
  2762. * Sets the vector's z component to the given value
  2763. *
  2764. * @param {number} z - The value to set.
  2765. * @return {Vector4} A reference to this vector.
  2766. */
  2767. setZ( z ) {
  2768. this.z = z;
  2769. return this;
  2770. }
  2771. /**
  2772. * Sets the vector's w component to the given value
  2773. *
  2774. * @param {number} w - The value to set.
  2775. * @return {Vector4} A reference to this vector.
  2776. */
  2777. setW( w ) {
  2778. this.w = w;
  2779. return this;
  2780. }
  2781. /**
  2782. * Allows to set a vector component with an index.
  2783. *
  2784. * @param {number} index - The component index. `0` equals to x, `1` equals to y,
  2785. * `2` equals to z, `3` equals to w.
  2786. * @param {number} value - The value to set.
  2787. * @return {Vector4} A reference to this vector.
  2788. */
  2789. setComponent( index, value ) {
  2790. switch ( index ) {
  2791. case 0: this.x = value; break;
  2792. case 1: this.y = value; break;
  2793. case 2: this.z = value; break;
  2794. case 3: this.w = value; break;
  2795. default: throw new Error( 'index is out of range: ' + index );
  2796. }
  2797. return this;
  2798. }
  2799. /**
  2800. * Returns the value of the vector component which matches the given index.
  2801. *
  2802. * @param {number} index - The component index. `0` equals to x, `1` equals to y,
  2803. * `2` equals to z, `3` equals to w.
  2804. * @return {number} A vector component value.
  2805. */
  2806. getComponent( index ) {
  2807. switch ( index ) {
  2808. case 0: return this.x;
  2809. case 1: return this.y;
  2810. case 2: return this.z;
  2811. case 3: return this.w;
  2812. default: throw new Error( 'index is out of range: ' + index );
  2813. }
  2814. }
  2815. /**
  2816. * Returns a new vector with copied values from this instance.
  2817. *
  2818. * @return {Vector4} A clone of this instance.
  2819. */
  2820. clone() {
  2821. return new this.constructor( this.x, this.y, this.z, this.w );
  2822. }
  2823. /**
  2824. * Copies the values of the given vector to this instance.
  2825. *
  2826. * @param {Vector3|Vector4} v - The vector to copy.
  2827. * @return {Vector4} A reference to this vector.
  2828. */
  2829. copy( v ) {
  2830. this.x = v.x;
  2831. this.y = v.y;
  2832. this.z = v.z;
  2833. this.w = ( v.w !== undefined ) ? v.w : 1;
  2834. return this;
  2835. }
  2836. /**
  2837. * Adds the given vector to this instance.
  2838. *
  2839. * @param {Vector4} v - The vector to add.
  2840. * @return {Vector4} A reference to this vector.
  2841. */
  2842. add( v ) {
  2843. this.x += v.x;
  2844. this.y += v.y;
  2845. this.z += v.z;
  2846. this.w += v.w;
  2847. return this;
  2848. }
  2849. /**
  2850. * Adds the given scalar value to all components of this instance.
  2851. *
  2852. * @param {number} s - The scalar to add.
  2853. * @return {Vector4} A reference to this vector.
  2854. */
  2855. addScalar( s ) {
  2856. this.x += s;
  2857. this.y += s;
  2858. this.z += s;
  2859. this.w += s;
  2860. return this;
  2861. }
  2862. /**
  2863. * Adds the given vectors and stores the result in this instance.
  2864. *
  2865. * @param {Vector4} a - The first vector.
  2866. * @param {Vector4} b - The second vector.
  2867. * @return {Vector4} A reference to this vector.
  2868. */
  2869. addVectors( a, b ) {
  2870. this.x = a.x + b.x;
  2871. this.y = a.y + b.y;
  2872. this.z = a.z + b.z;
  2873. this.w = a.w + b.w;
  2874. return this;
  2875. }
  2876. /**
  2877. * Adds the given vector scaled by the given factor to this instance.
  2878. *
  2879. * @param {Vector4} v - The vector.
  2880. * @param {number} s - The factor that scales `v`.
  2881. * @return {Vector4} A reference to this vector.
  2882. */
  2883. addScaledVector( v, s ) {
  2884. this.x += v.x * s;
  2885. this.y += v.y * s;
  2886. this.z += v.z * s;
  2887. this.w += v.w * s;
  2888. return this;
  2889. }
  2890. /**
  2891. * Subtracts the given vector from this instance.
  2892. *
  2893. * @param {Vector4} v - The vector to subtract.
  2894. * @return {Vector4} A reference to this vector.
  2895. */
  2896. sub( v ) {
  2897. this.x -= v.x;
  2898. this.y -= v.y;
  2899. this.z -= v.z;
  2900. this.w -= v.w;
  2901. return this;
  2902. }
  2903. /**
  2904. * Subtracts the given scalar value from all components of this instance.
  2905. *
  2906. * @param {number} s - The scalar to subtract.
  2907. * @return {Vector4} A reference to this vector.
  2908. */
  2909. subScalar( s ) {
  2910. this.x -= s;
  2911. this.y -= s;
  2912. this.z -= s;
  2913. this.w -= s;
  2914. return this;
  2915. }
  2916. /**
  2917. * Subtracts the given vectors and stores the result in this instance.
  2918. *
  2919. * @param {Vector4} a - The first vector.
  2920. * @param {Vector4} b - The second vector.
  2921. * @return {Vector4} A reference to this vector.
  2922. */
  2923. subVectors( a, b ) {
  2924. this.x = a.x - b.x;
  2925. this.y = a.y - b.y;
  2926. this.z = a.z - b.z;
  2927. this.w = a.w - b.w;
  2928. return this;
  2929. }
  2930. /**
  2931. * Multiplies the given vector with this instance.
  2932. *
  2933. * @param {Vector4} v - The vector to multiply.
  2934. * @return {Vector4} A reference to this vector.
  2935. */
  2936. multiply( v ) {
  2937. this.x *= v.x;
  2938. this.y *= v.y;
  2939. this.z *= v.z;
  2940. this.w *= v.w;
  2941. return this;
  2942. }
  2943. /**
  2944. * Multiplies the given scalar value with all components of this instance.
  2945. *
  2946. * @param {number} scalar - The scalar to multiply.
  2947. * @return {Vector4} A reference to this vector.
  2948. */
  2949. multiplyScalar( scalar ) {
  2950. this.x *= scalar;
  2951. this.y *= scalar;
  2952. this.z *= scalar;
  2953. this.w *= scalar;
  2954. return this;
  2955. }
  2956. /**
  2957. * Multiplies this vector with the given 4x4 matrix.
  2958. *
  2959. * @param {Matrix4} m - The 4x4 matrix.
  2960. * @return {Vector4} A reference to this vector.
  2961. */
  2962. applyMatrix4( m ) {
  2963. const x = this.x, y = this.y, z = this.z, w = this.w;
  2964. const e = m.elements;
  2965. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] * w;
  2966. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] * w;
  2967. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] * w;
  2968. this.w = e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] * w;
  2969. return this;
  2970. }
  2971. /**
  2972. * Divides this instance by the given vector.
  2973. *
  2974. * @param {Vector4} v - The vector to divide.
  2975. * @return {Vector4} A reference to this vector.
  2976. */
  2977. divide( v ) {
  2978. this.x /= v.x;
  2979. this.y /= v.y;
  2980. this.z /= v.z;
  2981. this.w /= v.w;
  2982. return this;
  2983. }
  2984. /**
  2985. * Divides this vector by the given scalar.
  2986. *
  2987. * @param {number} scalar - The scalar to divide.
  2988. * @return {Vector4} A reference to this vector.
  2989. */
  2990. divideScalar( scalar ) {
  2991. return this.multiplyScalar( 1 / scalar );
  2992. }
  2993. /**
  2994. * Sets the x, y and z components of this
  2995. * vector to the quaternion's axis and w to the angle.
  2996. *
  2997. * @param {Quaternion} q - The Quaternion to set.
  2998. * @return {Vector4} A reference to this vector.
  2999. */
  3000. setAxisAngleFromQuaternion( q ) {
  3001. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToAngle/index.htm
  3002. // q is assumed to be normalized
  3003. this.w = 2 * Math.acos( q.w );
  3004. const s = Math.sqrt( 1 - q.w * q.w );
  3005. if ( s < 0.0001 ) {
  3006. this.x = 1;
  3007. this.y = 0;
  3008. this.z = 0;
  3009. } else {
  3010. this.x = q.x / s;
  3011. this.y = q.y / s;
  3012. this.z = q.z / s;
  3013. }
  3014. return this;
  3015. }
  3016. /**
  3017. * Sets the x, y and z components of this
  3018. * vector to the axis of rotation and w to the angle.
  3019. *
  3020. * @param {Matrix4} m - A 4x4 matrix of which the upper left 3x3 matrix is a pure rotation matrix.
  3021. * @return {Vector4} A reference to this vector.
  3022. */
  3023. setAxisAngleFromRotationMatrix( m ) {
  3024. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToAngle/index.htm
  3025. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  3026. let angle, x, y, z; // variables for result
  3027. const epsilon = 0.01, // margin to allow for rounding errors
  3028. epsilon2 = 0.1, // margin to distinguish between 0 and 180 degrees
  3029. te = m.elements,
  3030. m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ],
  3031. m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ],
  3032. m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];
  3033. if ( ( Math.abs( m12 - m21 ) < epsilon ) &&
  3034. ( Math.abs( m13 - m31 ) < epsilon ) &&
  3035. ( Math.abs( m23 - m32 ) < epsilon ) ) {
  3036. // singularity found
  3037. // first check for identity matrix which must have +1 for all terms
  3038. // in leading diagonal and zero in other terms
  3039. if ( ( Math.abs( m12 + m21 ) < epsilon2 ) &&
  3040. ( Math.abs( m13 + m31 ) < epsilon2 ) &&
  3041. ( Math.abs( m23 + m32 ) < epsilon2 ) &&
  3042. ( Math.abs( m11 + m22 + m33 - 3 ) < epsilon2 ) ) {
  3043. // this singularity is identity matrix so angle = 0
  3044. this.set( 1, 0, 0, 0 );
  3045. return this; // zero angle, arbitrary axis
  3046. }
  3047. // otherwise this singularity is angle = 180
  3048. angle = Math.PI;
  3049. const xx = ( m11 + 1 ) / 2;
  3050. const yy = ( m22 + 1 ) / 2;
  3051. const zz = ( m33 + 1 ) / 2;
  3052. const xy = ( m12 + m21 ) / 4;
  3053. const xz = ( m13 + m31 ) / 4;
  3054. const yz = ( m23 + m32 ) / 4;
  3055. if ( ( xx > yy ) && ( xx > zz ) ) {
  3056. // m11 is the largest diagonal term
  3057. if ( xx < epsilon ) {
  3058. x = 0;
  3059. y = 0.707106781;
  3060. z = 0.707106781;
  3061. } else {
  3062. x = Math.sqrt( xx );
  3063. y = xy / x;
  3064. z = xz / x;
  3065. }
  3066. } else if ( yy > zz ) {
  3067. // m22 is the largest diagonal term
  3068. if ( yy < epsilon ) {
  3069. x = 0.707106781;
  3070. y = 0;
  3071. z = 0.707106781;
  3072. } else {
  3073. y = Math.sqrt( yy );
  3074. x = xy / y;
  3075. z = yz / y;
  3076. }
  3077. } else {
  3078. // m33 is the largest diagonal term so base result on this
  3079. if ( zz < epsilon ) {
  3080. x = 0.707106781;
  3081. y = 0.707106781;
  3082. z = 0;
  3083. } else {
  3084. z = Math.sqrt( zz );
  3085. x = xz / z;
  3086. y = yz / z;
  3087. }
  3088. }
  3089. this.set( x, y, z, angle );
  3090. return this; // return 180 deg rotation
  3091. }
  3092. // as we have reached here there are no singularities so we can handle normally
  3093. let s = Math.sqrt( ( m32 - m23 ) * ( m32 - m23 ) +
  3094. ( m13 - m31 ) * ( m13 - m31 ) +
  3095. ( m21 - m12 ) * ( m21 - m12 ) ); // used to normalize
  3096. if ( Math.abs( s ) < 0.001 ) s = 1;
  3097. // prevent divide by zero, should not happen if matrix is orthogonal and should be
  3098. // caught by singularity test above, but I've left it in just in case
  3099. this.x = ( m32 - m23 ) / s;
  3100. this.y = ( m13 - m31 ) / s;
  3101. this.z = ( m21 - m12 ) / s;
  3102. this.w = Math.acos( ( m11 + m22 + m33 - 1 ) / 2 );
  3103. return this;
  3104. }
  3105. /**
  3106. * Sets the vector components to the position elements of the
  3107. * given transformation matrix.
  3108. *
  3109. * @param {Matrix4} m - The 4x4 matrix.
  3110. * @return {Vector4} A reference to this vector.
  3111. */
  3112. setFromMatrixPosition( m ) {
  3113. const e = m.elements;
  3114. this.x = e[ 12 ];
  3115. this.y = e[ 13 ];
  3116. this.z = e[ 14 ];
  3117. this.w = e[ 15 ];
  3118. return this;
  3119. }
  3120. /**
  3121. * If this vector's x, y, z or w value is greater than the given vector's x, y, z or w
  3122. * value, replace that value with the corresponding min value.
  3123. *
  3124. * @param {Vector4} v - The vector.
  3125. * @return {Vector4} A reference to this vector.
  3126. */
  3127. min( v ) {
  3128. this.x = Math.min( this.x, v.x );
  3129. this.y = Math.min( this.y, v.y );
  3130. this.z = Math.min( this.z, v.z );
  3131. this.w = Math.min( this.w, v.w );
  3132. return this;
  3133. }
  3134. /**
  3135. * If this vector's x, y, z or w value is less than the given vector's x, y, z or w
  3136. * value, replace that value with the corresponding max value.
  3137. *
  3138. * @param {Vector4} v - The vector.
  3139. * @return {Vector4} A reference to this vector.
  3140. */
  3141. max( v ) {
  3142. this.x = Math.max( this.x, v.x );
  3143. this.y = Math.max( this.y, v.y );
  3144. this.z = Math.max( this.z, v.z );
  3145. this.w = Math.max( this.w, v.w );
  3146. return this;
  3147. }
  3148. /**
  3149. * If this vector's x, y, z or w value is greater than the max vector's x, y, z or w
  3150. * value, it is replaced by the corresponding value.
  3151. * If this vector's x, y, z or w value is less than the min vector's x, y, z or w value,
  3152. * it is replaced by the corresponding value.
  3153. *
  3154. * @param {Vector4} min - The minimum x, y and z values.
  3155. * @param {Vector4} max - The maximum x, y and z values in the desired range.
  3156. * @return {Vector4} A reference to this vector.
  3157. */
  3158. clamp( min, max ) {
  3159. // assumes min < max, componentwise
  3160. this.x = clamp( this.x, min.x, max.x );
  3161. this.y = clamp( this.y, min.y, max.y );
  3162. this.z = clamp( this.z, min.z, max.z );
  3163. this.w = clamp( this.w, min.w, max.w );
  3164. return this;
  3165. }
  3166. /**
  3167. * If this vector's x, y, z or w values are greater than the max value, they are
  3168. * replaced by the max value.
  3169. * If this vector's x, y, z or w values are less than the min value, they are
  3170. * replaced by the min value.
  3171. *
  3172. * @param {number} minVal - The minimum value the components will be clamped to.
  3173. * @param {number} maxVal - The maximum value the components will be clamped to.
  3174. * @return {Vector4} A reference to this vector.
  3175. */
  3176. clampScalar( minVal, maxVal ) {
  3177. this.x = clamp( this.x, minVal, maxVal );
  3178. this.y = clamp( this.y, minVal, maxVal );
  3179. this.z = clamp( this.z, minVal, maxVal );
  3180. this.w = clamp( this.w, minVal, maxVal );
  3181. return this;
  3182. }
  3183. /**
  3184. * If this vector's length is greater than the max value, it is replaced by
  3185. * the max value.
  3186. * If this vector's length is less than the min value, it is replaced by the
  3187. * min value.
  3188. *
  3189. * @param {number} min - The minimum value the vector length will be clamped to.
  3190. * @param {number} max - The maximum value the vector length will be clamped to.
  3191. * @return {Vector4} A reference to this vector.
  3192. */
  3193. clampLength( min, max ) {
  3194. const length = this.length();
  3195. return this.divideScalar( length || 1 ).multiplyScalar( clamp( length, min, max ) );
  3196. }
  3197. /**
  3198. * The components of this vector are rounded down to the nearest integer value.
  3199. *
  3200. * @return {Vector4} A reference to this vector.
  3201. */
  3202. floor() {
  3203. this.x = Math.floor( this.x );
  3204. this.y = Math.floor( this.y );
  3205. this.z = Math.floor( this.z );
  3206. this.w = Math.floor( this.w );
  3207. return this;
  3208. }
  3209. /**
  3210. * The components of this vector are rounded up to the nearest integer value.
  3211. *
  3212. * @return {Vector4} A reference to this vector.
  3213. */
  3214. ceil() {
  3215. this.x = Math.ceil( this.x );
  3216. this.y = Math.ceil( this.y );
  3217. this.z = Math.ceil( this.z );
  3218. this.w = Math.ceil( this.w );
  3219. return this;
  3220. }
  3221. /**
  3222. * The components of this vector are rounded to the nearest integer value
  3223. *
  3224. * @return {Vector4} A reference to this vector.
  3225. */
  3226. round() {
  3227. this.x = Math.round( this.x );
  3228. this.y = Math.round( this.y );
  3229. this.z = Math.round( this.z );
  3230. this.w = Math.round( this.w );
  3231. return this;
  3232. }
  3233. /**
  3234. * The components of this vector are rounded towards zero (up if negative,
  3235. * down if positive) to an integer value.
  3236. *
  3237. * @return {Vector4} A reference to this vector.
  3238. */
  3239. roundToZero() {
  3240. this.x = Math.trunc( this.x );
  3241. this.y = Math.trunc( this.y );
  3242. this.z = Math.trunc( this.z );
  3243. this.w = Math.trunc( this.w );
  3244. return this;
  3245. }
  3246. /**
  3247. * Inverts this vector - i.e. sets x = -x, y = -y, z = -z, w = -w.
  3248. *
  3249. * @return {Vector4} A reference to this vector.
  3250. */
  3251. negate() {
  3252. this.x = - this.x;
  3253. this.y = - this.y;
  3254. this.z = - this.z;
  3255. this.w = - this.w;
  3256. return this;
  3257. }
  3258. /**
  3259. * Calculates the dot product of the given vector with this instance.
  3260. *
  3261. * @param {Vector4} v - The vector to compute the dot product with.
  3262. * @return {number} The result of the dot product.
  3263. */
  3264. dot( v ) {
  3265. return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w;
  3266. }
  3267. /**
  3268. * Computes the square of the Euclidean length (straight-line length) from
  3269. * (0, 0, 0, 0) to (x, y, z, w). If you are comparing the lengths of vectors, you should
  3270. * compare the length squared instead as it is slightly more efficient to calculate.
  3271. *
  3272. * @return {number} The square length of this vector.
  3273. */
  3274. lengthSq() {
  3275. return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w;
  3276. }
  3277. /**
  3278. * Computes the Euclidean length (straight-line length) from (0, 0, 0, 0) to (x, y, z, w).
  3279. *
  3280. * @return {number} The length of this vector.
  3281. */
  3282. length() {
  3283. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w );
  3284. }
  3285. /**
  3286. * Computes the Manhattan length of this vector.
  3287. *
  3288. * @return {number} The length of this vector.
  3289. */
  3290. manhattanLength() {
  3291. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z ) + Math.abs( this.w );
  3292. }
  3293. /**
  3294. * Converts this vector to a unit vector - that is, sets it equal to a vector
  3295. * with the same direction as this one, but with a vector length of `1`.
  3296. *
  3297. * @return {Vector4} A reference to this vector.
  3298. */
  3299. normalize() {
  3300. return this.divideScalar( this.length() || 1 );
  3301. }
  3302. /**
  3303. * Sets this vector to a vector with the same direction as this one, but
  3304. * with the specified length.
  3305. *
  3306. * @param {number} length - The new length of this vector.
  3307. * @return {Vector4} A reference to this vector.
  3308. */
  3309. setLength( length ) {
  3310. return this.normalize().multiplyScalar( length );
  3311. }
  3312. /**
  3313. * Linearly interpolates between the given vector and this instance, where
  3314. * alpha is the percent distance along the line - alpha = 0 will be this
  3315. * vector, and alpha = 1 will be the given one.
  3316. *
  3317. * @param {Vector4} v - The vector to interpolate towards.
  3318. * @param {number} alpha - The interpolation factor, typically in the closed interval `[0, 1]`.
  3319. * @return {Vector4} A reference to this vector.
  3320. */
  3321. lerp( v, alpha ) {
  3322. this.x += ( v.x - this.x ) * alpha;
  3323. this.y += ( v.y - this.y ) * alpha;
  3324. this.z += ( v.z - this.z ) * alpha;
  3325. this.w += ( v.w - this.w ) * alpha;
  3326. return this;
  3327. }
  3328. /**
  3329. * Linearly interpolates between the given vectors, where alpha is the percent
  3330. * distance along the line - alpha = 0 will be first vector, and alpha = 1 will
  3331. * be the second one. The result is stored in this instance.
  3332. *
  3333. * @param {Vector4} v1 - The first vector.
  3334. * @param {Vector4} v2 - The second vector.
  3335. * @param {number} alpha - The interpolation factor, typically in the closed interval `[0, 1]`.
  3336. * @return {Vector4} A reference to this vector.
  3337. */
  3338. lerpVectors( v1, v2, alpha ) {
  3339. this.x = v1.x + ( v2.x - v1.x ) * alpha;
  3340. this.y = v1.y + ( v2.y - v1.y ) * alpha;
  3341. this.z = v1.z + ( v2.z - v1.z ) * alpha;
  3342. this.w = v1.w + ( v2.w - v1.w ) * alpha;
  3343. return this;
  3344. }
  3345. /**
  3346. * Returns `true` if this vector is equal with the given one.
  3347. *
  3348. * @param {Vector4} v - The vector to test for equality.
  3349. * @return {boolean} Whether this vector is equal with the given one.
  3350. */
  3351. equals( v ) {
  3352. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) && ( v.w === this.w ) );
  3353. }
  3354. /**
  3355. * Sets this vector's x value to be `array[ offset ]`, y value to be `array[ offset + 1 ]`,
  3356. * z value to be `array[ offset + 2 ]`, w value to be `array[ offset + 3 ]`.
  3357. *
  3358. * @param {Array<number>} array - An array holding the vector component values.
  3359. * @param {number} [offset=0] - The offset into the array.
  3360. * @return {Vector4} A reference to this vector.
  3361. */
  3362. fromArray( array, offset = 0 ) {
  3363. this.x = array[ offset ];
  3364. this.y = array[ offset + 1 ];
  3365. this.z = array[ offset + 2 ];
  3366. this.w = array[ offset + 3 ];
  3367. return this;
  3368. }
  3369. /**
  3370. * Writes the components of this vector to the given array. If no array is provided,
  3371. * the method returns a new instance.
  3372. *
  3373. * @param {Array<number>} [array=[]] - The target array holding the vector components.
  3374. * @param {number} [offset=0] - Index of the first element in the array.
  3375. * @return {Array<number>} The vector components.
  3376. */
  3377. toArray( array = [], offset = 0 ) {
  3378. array[ offset ] = this.x;
  3379. array[ offset + 1 ] = this.y;
  3380. array[ offset + 2 ] = this.z;
  3381. array[ offset + 3 ] = this.w;
  3382. return array;
  3383. }
  3384. /**
  3385. * Sets the components of this vector from the given buffer attribute.
  3386. *
  3387. * @param {BufferAttribute} attribute - The buffer attribute holding vector data.
  3388. * @param {number} index - The index into the attribute.
  3389. * @return {Vector4} A reference to this vector.
  3390. */
  3391. fromBufferAttribute( attribute, index ) {
  3392. this.x = attribute.getX( index );
  3393. this.y = attribute.getY( index );
  3394. this.z = attribute.getZ( index );
  3395. this.w = attribute.getW( index );
  3396. return this;
  3397. }
  3398. /**
  3399. * Sets each component of this vector to a pseudo-random value between `0` and
  3400. * `1`, excluding `1`.
  3401. *
  3402. * @return {Vector4} A reference to this vector.
  3403. */
  3404. random() {
  3405. this.x = Math.random();
  3406. this.y = Math.random();
  3407. this.z = Math.random();
  3408. this.w = Math.random();
  3409. return this;
  3410. }
  3411. *[ Symbol.iterator ]() {
  3412. yield this.x;
  3413. yield this.y;
  3414. yield this.z;
  3415. yield this.w;
  3416. }
  3417. }
  3418. /*
  3419. In options, we can specify:
  3420. * Texture parameters for an auto-generated target texture
  3421. * depthBuffer/stencilBuffer: Booleans to indicate if we should generate these buffers
  3422. */
  3423. class RenderTarget extends EventDispatcher {
  3424. constructor( width = 1, height = 1, options = {} ) {
  3425. super();
  3426. this.isRenderTarget = true;
  3427. this.width = width;
  3428. this.height = height;
  3429. this.depth = 1;
  3430. this.scissor = new Vector4( 0, 0, width, height );
  3431. this.scissorTest = false;
  3432. this.viewport = new Vector4( 0, 0, width, height );
  3433. const image = { width: width, height: height, depth: 1 };
  3434. options = Object.assign( {
  3435. generateMipmaps: false,
  3436. internalFormat: null,
  3437. minFilter: LinearFilter,
  3438. depthBuffer: true,
  3439. stencilBuffer: false,
  3440. resolveDepthBuffer: true,
  3441. resolveStencilBuffer: true,
  3442. depthTexture: null,
  3443. samples: 0,
  3444. count: 1
  3445. }, options );
  3446. const texture = new Texture( image, options.mapping, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.colorSpace );
  3447. texture.flipY = false;
  3448. texture.generateMipmaps = options.generateMipmaps;
  3449. texture.internalFormat = options.internalFormat;
  3450. this.textures = [];
  3451. const count = options.count;
  3452. for ( let i = 0; i < count; i ++ ) {
  3453. this.textures[ i ] = texture.clone();
  3454. this.textures[ i ].isRenderTargetTexture = true;
  3455. this.textures[ i ].renderTarget = this;
  3456. }
  3457. this.depthBuffer = options.depthBuffer;
  3458. this.stencilBuffer = options.stencilBuffer;
  3459. this.resolveDepthBuffer = options.resolveDepthBuffer;
  3460. this.resolveStencilBuffer = options.resolveStencilBuffer;
  3461. this._depthTexture = null;
  3462. this.depthTexture = options.depthTexture;
  3463. this.samples = options.samples;
  3464. }
  3465. get texture() {
  3466. return this.textures[ 0 ];
  3467. }
  3468. set texture( value ) {
  3469. this.textures[ 0 ] = value;
  3470. }
  3471. set depthTexture( current ) {
  3472. if ( this._depthTexture !== null ) this._depthTexture.renderTarget = null;
  3473. if ( current !== null ) current.renderTarget = this;
  3474. this._depthTexture = current;
  3475. }
  3476. get depthTexture() {
  3477. return this._depthTexture;
  3478. }
  3479. setSize( width, height, depth = 1 ) {
  3480. if ( this.width !== width || this.height !== height || this.depth !== depth ) {
  3481. this.width = width;
  3482. this.height = height;
  3483. this.depth = depth;
  3484. for ( let i = 0, il = this.textures.length; i < il; i ++ ) {
  3485. this.textures[ i ].image.width = width;
  3486. this.textures[ i ].image.height = height;
  3487. this.textures[ i ].image.depth = depth;
  3488. }
  3489. this.dispose();
  3490. }
  3491. this.viewport.set( 0, 0, width, height );
  3492. this.scissor.set( 0, 0, width, height );
  3493. }
  3494. clone() {
  3495. return new this.constructor().copy( this );
  3496. }
  3497. copy( source ) {
  3498. this.width = source.width;
  3499. this.height = source.height;
  3500. this.depth = source.depth;
  3501. this.scissor.copy( source.scissor );
  3502. this.scissorTest = source.scissorTest;
  3503. this.viewport.copy( source.viewport );
  3504. this.textures.length = 0;
  3505. for ( let i = 0, il = source.textures.length; i < il; i ++ ) {
  3506. this.textures[ i ] = source.textures[ i ].clone();
  3507. this.textures[ i ].isRenderTargetTexture = true;
  3508. this.textures[ i ].renderTarget = this;
  3509. // ensure image object is not shared, see #20328
  3510. const image = Object.assign( {}, source.textures[ i ].image );
  3511. this.textures[ i ].source = new Source( image );
  3512. }
  3513. this.depthBuffer = source.depthBuffer;
  3514. this.stencilBuffer = source.stencilBuffer;
  3515. this.resolveDepthBuffer = source.resolveDepthBuffer;
  3516. this.resolveStencilBuffer = source.resolveStencilBuffer;
  3517. if ( source.depthTexture !== null ) this.depthTexture = source.depthTexture.clone();
  3518. this.samples = source.samples;
  3519. return this;
  3520. }
  3521. dispose() {
  3522. this.dispatchEvent( { type: 'dispose' } );
  3523. }
  3524. }
  3525. class WebGLRenderTarget extends RenderTarget {
  3526. constructor( width = 1, height = 1, options = {} ) {
  3527. super( width, height, options );
  3528. this.isWebGLRenderTarget = true;
  3529. }
  3530. }
  3531. class DataArrayTexture extends Texture {
  3532. constructor( data = null, width = 1, height = 1, depth = 1 ) {
  3533. super( null );
  3534. this.isDataArrayTexture = true;
  3535. this.image = { data, width, height, depth };
  3536. this.magFilter = NearestFilter;
  3537. this.minFilter = NearestFilter;
  3538. this.wrapR = ClampToEdgeWrapping;
  3539. this.generateMipmaps = false;
  3540. this.flipY = false;
  3541. this.unpackAlignment = 1;
  3542. this.layerUpdates = new Set();
  3543. }
  3544. addLayerUpdate( layerIndex ) {
  3545. this.layerUpdates.add( layerIndex );
  3546. }
  3547. clearLayerUpdates() {
  3548. this.layerUpdates.clear();
  3549. }
  3550. }
  3551. class WebGLArrayRenderTarget extends WebGLRenderTarget {
  3552. constructor( width = 1, height = 1, depth = 1, options = {} ) {
  3553. super( width, height, options );
  3554. this.isWebGLArrayRenderTarget = true;
  3555. this.depth = depth;
  3556. this.texture = new DataArrayTexture( null, width, height, depth );
  3557. this.texture.isRenderTargetTexture = true;
  3558. }
  3559. }
  3560. class Data3DTexture extends Texture {
  3561. constructor( data = null, width = 1, height = 1, depth = 1 ) {
  3562. // We're going to add .setXXX() methods for setting properties later.
  3563. // Users can still set in Data3DTexture directly.
  3564. //
  3565. // const texture = new THREE.Data3DTexture( data, width, height, depth );
  3566. // texture.anisotropy = 16;
  3567. //
  3568. // See #14839
  3569. super( null );
  3570. this.isData3DTexture = true;
  3571. this.image = { data, width, height, depth };
  3572. this.magFilter = NearestFilter;
  3573. this.minFilter = NearestFilter;
  3574. this.wrapR = ClampToEdgeWrapping;
  3575. this.generateMipmaps = false;
  3576. this.flipY = false;
  3577. this.unpackAlignment = 1;
  3578. }
  3579. }
  3580. class WebGL3DRenderTarget extends WebGLRenderTarget {
  3581. constructor( width = 1, height = 1, depth = 1, options = {} ) {
  3582. super( width, height, options );
  3583. this.isWebGL3DRenderTarget = true;
  3584. this.depth = depth;
  3585. this.texture = new Data3DTexture( null, width, height, depth );
  3586. this.texture.isRenderTargetTexture = true;
  3587. }
  3588. }
  3589. /**
  3590. * Class for representing a Quaternion. Quaternions are used in three.js to represent rotations.
  3591. *
  3592. * Iterating through a vector instance will yield its components `(x, y, z, w)` in
  3593. * the corresponding order.
  3594. *
  3595. * Note that three.js expects Quaternions to be normalized.
  3596. * ```js
  3597. * const quaternion = new THREE.Quaternion();
  3598. * quaternion.setFromAxisAngle( new THREE.Vector3( 0, 1, 0 ), Math.PI / 2 );
  3599. *
  3600. * const vector = new THREE.Vector3( 1, 0, 0 );
  3601. * vector.applyQuaternion( quaternion );
  3602. * ```
  3603. */
  3604. class Quaternion {
  3605. /**
  3606. * Constructs a new quaternion.
  3607. *
  3608. * @param {number} [x=0] - The x value of this quaternion.
  3609. * @param {number} [y=0] - The y value of this quaternion.
  3610. * @param {number} [z=0] - The z value of this quaternion.
  3611. * @param {number} [w=1] - The w value of this quaternion.
  3612. */
  3613. constructor( x = 0, y = 0, z = 0, w = 1 ) {
  3614. /**
  3615. * This flag can be used for type testing.
  3616. *
  3617. * @type {boolean}
  3618. * @readonly
  3619. * @default true
  3620. */
  3621. this.isQuaternion = true;
  3622. this._x = x;
  3623. this._y = y;
  3624. this._z = z;
  3625. this._w = w;
  3626. }
  3627. /**
  3628. * Interpolates between two quaternions via SLERP. This implementation assumes the
  3629. * quaternion data are managed in flat arrays.
  3630. *
  3631. * @param {Array<number>} dst - The destination array.
  3632. * @param {number} dstOffset - An offset into the destination array.
  3633. * @param {Array<number>} src0 - The source array of the first quaternion.
  3634. * @param {number} srcOffset0 - An offset into the first source array.
  3635. * @param {Array<number>} src1 - The source array of the second quaternion.
  3636. * @param {number} srcOffset1 - An offset into the second source array.
  3637. * @param {number} t - The interpolation factor in the range `[0,1]`.
  3638. * @see {@link Quaternion#slerp}
  3639. */
  3640. static slerpFlat( dst, dstOffset, src0, srcOffset0, src1, srcOffset1, t ) {
  3641. // fuzz-free, array-based Quaternion SLERP operation
  3642. let x0 = src0[ srcOffset0 + 0 ],
  3643. y0 = src0[ srcOffset0 + 1 ],
  3644. z0 = src0[ srcOffset0 + 2 ],
  3645. w0 = src0[ srcOffset0 + 3 ];
  3646. const x1 = src1[ srcOffset1 + 0 ],
  3647. y1 = src1[ srcOffset1 + 1 ],
  3648. z1 = src1[ srcOffset1 + 2 ],
  3649. w1 = src1[ srcOffset1 + 3 ];
  3650. if ( t === 0 ) {
  3651. dst[ dstOffset + 0 ] = x0;
  3652. dst[ dstOffset + 1 ] = y0;
  3653. dst[ dstOffset + 2 ] = z0;
  3654. dst[ dstOffset + 3 ] = w0;
  3655. return;
  3656. }
  3657. if ( t === 1 ) {
  3658. dst[ dstOffset + 0 ] = x1;
  3659. dst[ dstOffset + 1 ] = y1;
  3660. dst[ dstOffset + 2 ] = z1;
  3661. dst[ dstOffset + 3 ] = w1;
  3662. return;
  3663. }
  3664. if ( w0 !== w1 || x0 !== x1 || y0 !== y1 || z0 !== z1 ) {
  3665. let s = 1 - t;
  3666. const cos = x0 * x1 + y0 * y1 + z0 * z1 + w0 * w1,
  3667. dir = ( cos >= 0 ? 1 : -1 ),
  3668. sqrSin = 1 - cos * cos;
  3669. // Skip the Slerp for tiny steps to avoid numeric problems:
  3670. if ( sqrSin > Number.EPSILON ) {
  3671. const sin = Math.sqrt( sqrSin ),
  3672. len = Math.atan2( sin, cos * dir );
  3673. s = Math.sin( s * len ) / sin;
  3674. t = Math.sin( t * len ) / sin;
  3675. }
  3676. const tDir = t * dir;
  3677. x0 = x0 * s + x1 * tDir;
  3678. y0 = y0 * s + y1 * tDir;
  3679. z0 = z0 * s + z1 * tDir;
  3680. w0 = w0 * s + w1 * tDir;
  3681. // Normalize in case we just did a lerp:
  3682. if ( s === 1 - t ) {
  3683. const f = 1 / Math.sqrt( x0 * x0 + y0 * y0 + z0 * z0 + w0 * w0 );
  3684. x0 *= f;
  3685. y0 *= f;
  3686. z0 *= f;
  3687. w0 *= f;
  3688. }
  3689. }
  3690. dst[ dstOffset ] = x0;
  3691. dst[ dstOffset + 1 ] = y0;
  3692. dst[ dstOffset + 2 ] = z0;
  3693. dst[ dstOffset + 3 ] = w0;
  3694. }
  3695. /**
  3696. * Multiplies two quaternions. This implementation assumes the quaternion data are managed
  3697. * in flat arrays.
  3698. *
  3699. * @param {Array<number>} dst - The destination array.
  3700. * @param {number} dstOffset - An offset into the destination array.
  3701. * @param {Array<number>} src0 - The source array of the first quaternion.
  3702. * @param {number} srcOffset0 - An offset into the first source array.
  3703. * @param {Array<number>} src1 - The source array of the second quaternion.
  3704. * @param {number} srcOffset1 - An offset into the second source array.
  3705. * @return {Array<number>} The destination array.
  3706. * @see {@link Quaternion#multiplyQuaternions}.
  3707. */
  3708. static multiplyQuaternionsFlat( dst, dstOffset, src0, srcOffset0, src1, srcOffset1 ) {
  3709. const x0 = src0[ srcOffset0 ];
  3710. const y0 = src0[ srcOffset0 + 1 ];
  3711. const z0 = src0[ srcOffset0 + 2 ];
  3712. const w0 = src0[ srcOffset0 + 3 ];
  3713. const x1 = src1[ srcOffset1 ];
  3714. const y1 = src1[ srcOffset1 + 1 ];
  3715. const z1 = src1[ srcOffset1 + 2 ];
  3716. const w1 = src1[ srcOffset1 + 3 ];
  3717. dst[ dstOffset ] = x0 * w1 + w0 * x1 + y0 * z1 - z0 * y1;
  3718. dst[ dstOffset + 1 ] = y0 * w1 + w0 * y1 + z0 * x1 - x0 * z1;
  3719. dst[ dstOffset + 2 ] = z0 * w1 + w0 * z1 + x0 * y1 - y0 * x1;
  3720. dst[ dstOffset + 3 ] = w0 * w1 - x0 * x1 - y0 * y1 - z0 * z1;
  3721. return dst;
  3722. }
  3723. /**
  3724. * The x value of this quaternion.
  3725. *
  3726. * @type {number}
  3727. * @default 0
  3728. */
  3729. get x() {
  3730. return this._x;
  3731. }
  3732. set x( value ) {
  3733. this._x = value;
  3734. this._onChangeCallback();
  3735. }
  3736. /**
  3737. * The y value of this quaternion.
  3738. *
  3739. * @type {number}
  3740. * @default 0
  3741. */
  3742. get y() {
  3743. return this._y;
  3744. }
  3745. set y( value ) {
  3746. this._y = value;
  3747. this._onChangeCallback();
  3748. }
  3749. /**
  3750. * The z value of this quaternion.
  3751. *
  3752. * @type {number}
  3753. * @default 0
  3754. */
  3755. get z() {
  3756. return this._z;
  3757. }
  3758. set z( value ) {
  3759. this._z = value;
  3760. this._onChangeCallback();
  3761. }
  3762. /**
  3763. * The w value of this quaternion.
  3764. *
  3765. * @type {number}
  3766. * @default 1
  3767. */
  3768. get w() {
  3769. return this._w;
  3770. }
  3771. set w( value ) {
  3772. this._w = value;
  3773. this._onChangeCallback();
  3774. }
  3775. /**
  3776. * Sets the quaternion components.
  3777. *
  3778. * @param {number} x - The x value of this quaternion.
  3779. * @param {number} y - The y value of this quaternion.
  3780. * @param {number} z - The z value of this quaternion.
  3781. * @param {number} w - The w value of this quaternion.
  3782. * @return {Quaternion} A reference to this quaternion.
  3783. */
  3784. set( x, y, z, w ) {
  3785. this._x = x;
  3786. this._y = y;
  3787. this._z = z;
  3788. this._w = w;
  3789. this._onChangeCallback();
  3790. return this;
  3791. }
  3792. /**
  3793. * Returns a new quaternion with copied values from this instance.
  3794. *
  3795. * @return {Quaternion} A clone of this instance.
  3796. */
  3797. clone() {
  3798. return new this.constructor( this._x, this._y, this._z, this._w );
  3799. }
  3800. /**
  3801. * Copies the values of the given quaternion to this instance.
  3802. *
  3803. * @param {Quaternion} quaternion - The quaternion to copy.
  3804. * @return {Quaternion} A reference to this quaternion.
  3805. */
  3806. copy( quaternion ) {
  3807. this._x = quaternion.x;
  3808. this._y = quaternion.y;
  3809. this._z = quaternion.z;
  3810. this._w = quaternion.w;
  3811. this._onChangeCallback();
  3812. return this;
  3813. }
  3814. /**
  3815. * Sets this quaternion from the rotation specified by the given
  3816. * Euler angles.
  3817. *
  3818. * @param {Euler} euler - The Euler angles.
  3819. * @param {boolean} [update=true] - Whether the internal `onChange` callback should be executed or not.
  3820. * @return {Quaternion} A reference to this quaternion.
  3821. */
  3822. setFromEuler( euler, update = true ) {
  3823. const x = euler._x, y = euler._y, z = euler._z, order = euler._order;
  3824. // http://www.mathworks.com/matlabcentral/fileexchange/
  3825. // 20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/
  3826. // content/SpinCalc.m
  3827. const cos = Math.cos;
  3828. const sin = Math.sin;
  3829. const c1 = cos( x / 2 );
  3830. const c2 = cos( y / 2 );
  3831. const c3 = cos( z / 2 );
  3832. const s1 = sin( x / 2 );
  3833. const s2 = sin( y / 2 );
  3834. const s3 = sin( z / 2 );
  3835. switch ( order ) {
  3836. case 'XYZ':
  3837. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  3838. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  3839. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  3840. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  3841. break;
  3842. case 'YXZ':
  3843. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  3844. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  3845. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  3846. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  3847. break;
  3848. case 'ZXY':
  3849. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  3850. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  3851. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  3852. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  3853. break;
  3854. case 'ZYX':
  3855. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  3856. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  3857. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  3858. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  3859. break;
  3860. case 'YZX':
  3861. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  3862. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  3863. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  3864. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  3865. break;
  3866. case 'XZY':
  3867. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  3868. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  3869. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  3870. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  3871. break;
  3872. default:
  3873. console.warn( 'THREE.Quaternion: .setFromEuler() encountered an unknown order: ' + order );
  3874. }
  3875. if ( update === true ) this._onChangeCallback();
  3876. return this;
  3877. }
  3878. /**
  3879. * Sets this quaternion from the given axis and angle.
  3880. *
  3881. * @param {Vector3} axis - The normalized axis.
  3882. * @param {number} angle - The angle in radians.
  3883. * @return {Quaternion} A reference to this quaternion.
  3884. */
  3885. setFromAxisAngle( axis, angle ) {
  3886. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm
  3887. const halfAngle = angle / 2, s = Math.sin( halfAngle );
  3888. this._x = axis.x * s;
  3889. this._y = axis.y * s;
  3890. this._z = axis.z * s;
  3891. this._w = Math.cos( halfAngle );
  3892. this._onChangeCallback();
  3893. return this;
  3894. }
  3895. /**
  3896. * Sets this quaternion from the given rotation matrix.
  3897. *
  3898. * @param {Matrix4} m - A 4x4 matrix of which the upper 3x3 of matrix is a pure rotation matrix (i.e. unscaled).
  3899. * @return {Quaternion} A reference to this quaternion.
  3900. */
  3901. setFromRotationMatrix( m ) {
  3902. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm
  3903. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  3904. const te = m.elements,
  3905. m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ],
  3906. m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ],
  3907. m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ],
  3908. trace = m11 + m22 + m33;
  3909. if ( trace > 0 ) {
  3910. const s = 0.5 / Math.sqrt( trace + 1.0 );
  3911. this._w = 0.25 / s;
  3912. this._x = ( m32 - m23 ) * s;
  3913. this._y = ( m13 - m31 ) * s;
  3914. this._z = ( m21 - m12 ) * s;
  3915. } else if ( m11 > m22 && m11 > m33 ) {
  3916. const s = 2.0 * Math.sqrt( 1.0 + m11 - m22 - m33 );
  3917. this._w = ( m32 - m23 ) / s;
  3918. this._x = 0.25 * s;
  3919. this._y = ( m12 + m21 ) / s;
  3920. this._z = ( m13 + m31 ) / s;
  3921. } else if ( m22 > m33 ) {
  3922. const s = 2.0 * Math.sqrt( 1.0 + m22 - m11 - m33 );
  3923. this._w = ( m13 - m31 ) / s;
  3924. this._x = ( m12 + m21 ) / s;
  3925. this._y = 0.25 * s;
  3926. this._z = ( m23 + m32 ) / s;
  3927. } else {
  3928. const s = 2.0 * Math.sqrt( 1.0 + m33 - m11 - m22 );
  3929. this._w = ( m21 - m12 ) / s;
  3930. this._x = ( m13 + m31 ) / s;
  3931. this._y = ( m23 + m32 ) / s;
  3932. this._z = 0.25 * s;
  3933. }
  3934. this._onChangeCallback();
  3935. return this;
  3936. }
  3937. /**
  3938. * Sets this quaternion to the rotation required to rotate the direction vector
  3939. * `vFrom` to the direction vector `vTo`.
  3940. *
  3941. * @param {Vector3} vFrom - The first (normalized) direction vector.
  3942. * @param {Vector3} vTo - The second (normalized) direction vector.
  3943. * @return {Quaternion} A reference to this quaternion.
  3944. */
  3945. setFromUnitVectors( vFrom, vTo ) {
  3946. // assumes direction vectors vFrom and vTo are normalized
  3947. let r = vFrom.dot( vTo ) + 1;
  3948. if ( r < Number.EPSILON ) {
  3949. // vFrom and vTo point in opposite directions
  3950. r = 0;
  3951. if ( Math.abs( vFrom.x ) > Math.abs( vFrom.z ) ) {
  3952. this._x = - vFrom.y;
  3953. this._y = vFrom.x;
  3954. this._z = 0;
  3955. this._w = r;
  3956. } else {
  3957. this._x = 0;
  3958. this._y = - vFrom.z;
  3959. this._z = vFrom.y;
  3960. this._w = r;
  3961. }
  3962. } else {
  3963. // crossVectors( vFrom, vTo ); // inlined to avoid cyclic dependency on Vector3
  3964. this._x = vFrom.y * vTo.z - vFrom.z * vTo.y;
  3965. this._y = vFrom.z * vTo.x - vFrom.x * vTo.z;
  3966. this._z = vFrom.x * vTo.y - vFrom.y * vTo.x;
  3967. this._w = r;
  3968. }
  3969. return this.normalize();
  3970. }
  3971. /**
  3972. * Returns the angle between this quaternion and the given one in radians.
  3973. *
  3974. * @param {Quaternion} q - The quaternion to compute the angle with.
  3975. * @return {number} The angle in radians.
  3976. */
  3977. angleTo( q ) {
  3978. return 2 * Math.acos( Math.abs( clamp( this.dot( q ), -1, 1 ) ) );
  3979. }
  3980. /**
  3981. * Rotates this quaternion by a given angular step to the given quaterion.
  3982. * The method ensures that the final quaternion will not overshoot `q`.
  3983. *
  3984. * @param {Quaternion} q - The target quaternion.
  3985. * @param {number} step - The angular step in radians.
  3986. * @return {Quaternion} A reference to this quaternion.
  3987. */
  3988. rotateTowards( q, step ) {
  3989. const angle = this.angleTo( q );
  3990. if ( angle === 0 ) return this;
  3991. const t = Math.min( 1, step / angle );
  3992. this.slerp( q, t );
  3993. return this;
  3994. }
  3995. /**
  3996. * Sets this quaternion to the identity quaternion; that is, to the
  3997. * quaternion that represents "no rotation".
  3998. *
  3999. * @return {Quaternion} A reference to this quaternion.
  4000. */
  4001. identity() {
  4002. return this.set( 0, 0, 0, 1 );
  4003. }
  4004. /**
  4005. * Inverts this quaternion via {@link Quaternion#conjugate}. The
  4006. * quaternion is assumed to have unit length.
  4007. *
  4008. * @return {Quaternion} A reference to this quaternion.
  4009. */
  4010. invert() {
  4011. return this.conjugate();
  4012. }
  4013. /**
  4014. * Returns the rotational conjugate of this quaternion. The conjugate of a
  4015. * quaternion represents the same rotation in the opposite direction about
  4016. * the rotational axis.
  4017. *
  4018. * @return {Quaternion} A reference to this quaternion.
  4019. */
  4020. conjugate() {
  4021. this._x *= -1;
  4022. this._y *= -1;
  4023. this._z *= -1;
  4024. this._onChangeCallback();
  4025. return this;
  4026. }
  4027. /**
  4028. * Calculates the dot product of this quaternion and the given one.
  4029. *
  4030. * @param {Quaternion} v - The quaternion to compute the dot product with.
  4031. * @return {number} The result of the dot product.
  4032. */
  4033. dot( v ) {
  4034. return this._x * v._x + this._y * v._y + this._z * v._z + this._w * v._w;
  4035. }
  4036. /**
  4037. * Computes the squared Euclidean length (straight-line length) of this quaternion,
  4038. * considered as a 4 dimensional vector. This can be useful if you are comparing the
  4039. * lengths of two quaternions, as this is a slightly more efficient calculation than
  4040. * {@link Quaternion#length}.
  4041. *
  4042. * @return {number} The squared Euclidean length.
  4043. */
  4044. lengthSq() {
  4045. return this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w;
  4046. }
  4047. /**
  4048. * Computes the Euclidean length (straight-line length) of this quaternion,
  4049. * considered as a 4 dimensional vector.
  4050. *
  4051. * @return {number} The Euclidean length.
  4052. */
  4053. length() {
  4054. return Math.sqrt( this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w );
  4055. }
  4056. /**
  4057. * Normalizes this quaternion - that is, calculated the quaternion that performs
  4058. * the same rotation as this one, but has a length equal to `1`.
  4059. *
  4060. * @return {Quaternion} A reference to this quaternion.
  4061. */
  4062. normalize() {
  4063. let l = this.length();
  4064. if ( l === 0 ) {
  4065. this._x = 0;
  4066. this._y = 0;
  4067. this._z = 0;
  4068. this._w = 1;
  4069. } else {
  4070. l = 1 / l;
  4071. this._x = this._x * l;
  4072. this._y = this._y * l;
  4073. this._z = this._z * l;
  4074. this._w = this._w * l;
  4075. }
  4076. this._onChangeCallback();
  4077. return this;
  4078. }
  4079. /**
  4080. * Multiplies this quaternion by the given one.
  4081. *
  4082. * @param {Quaternion} q - The quaternion.
  4083. * @return {Quaternion} A reference to this quaternion.
  4084. */
  4085. multiply( q ) {
  4086. return this.multiplyQuaternions( this, q );
  4087. }
  4088. /**
  4089. * Pre-multiplies this quaternion by the given one.
  4090. *
  4091. * @param {Quaternion} q - The quaternion.
  4092. * @return {Quaternion} A reference to this quaternion.
  4093. */
  4094. premultiply( q ) {
  4095. return this.multiplyQuaternions( q, this );
  4096. }
  4097. /**
  4098. * Multiplies the given quaternions and stores the result in this instance.
  4099. *
  4100. * @param {Quaternion} a - The first quaternion.
  4101. * @param {Quaternion} b - The second quaternion.
  4102. * @return {Quaternion} A reference to this quaternion.
  4103. */
  4104. multiplyQuaternions( a, b ) {
  4105. // from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm
  4106. const qax = a._x, qay = a._y, qaz = a._z, qaw = a._w;
  4107. const qbx = b._x, qby = b._y, qbz = b._z, qbw = b._w;
  4108. this._x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby;
  4109. this._y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz;
  4110. this._z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx;
  4111. this._w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz;
  4112. this._onChangeCallback();
  4113. return this;
  4114. }
  4115. /**
  4116. * Performs a spherical linear interpolation between quaternions.
  4117. *
  4118. * @param {Quaternion} qb - The target quaternion.
  4119. * @param {number} t - The interpolation factor in the closed interval `[0, 1]`.
  4120. * @return {Quaternion} A reference to this quaternion.
  4121. */
  4122. slerp( qb, t ) {
  4123. if ( t === 0 ) return this;
  4124. if ( t === 1 ) return this.copy( qb );
  4125. const x = this._x, y = this._y, z = this._z, w = this._w;
  4126. // http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/
  4127. let cosHalfTheta = w * qb._w + x * qb._x + y * qb._y + z * qb._z;
  4128. if ( cosHalfTheta < 0 ) {
  4129. this._w = - qb._w;
  4130. this._x = - qb._x;
  4131. this._y = - qb._y;
  4132. this._z = - qb._z;
  4133. cosHalfTheta = - cosHalfTheta;
  4134. } else {
  4135. this.copy( qb );
  4136. }
  4137. if ( cosHalfTheta >= 1.0 ) {
  4138. this._w = w;
  4139. this._x = x;
  4140. this._y = y;
  4141. this._z = z;
  4142. return this;
  4143. }
  4144. const sqrSinHalfTheta = 1.0 - cosHalfTheta * cosHalfTheta;
  4145. if ( sqrSinHalfTheta <= Number.EPSILON ) {
  4146. const s = 1 - t;
  4147. this._w = s * w + t * this._w;
  4148. this._x = s * x + t * this._x;
  4149. this._y = s * y + t * this._y;
  4150. this._z = s * z + t * this._z;
  4151. this.normalize(); // normalize calls _onChangeCallback()
  4152. return this;
  4153. }
  4154. const sinHalfTheta = Math.sqrt( sqrSinHalfTheta );
  4155. const halfTheta = Math.atan2( sinHalfTheta, cosHalfTheta );
  4156. const ratioA = Math.sin( ( 1 - t ) * halfTheta ) / sinHalfTheta,
  4157. ratioB = Math.sin( t * halfTheta ) / sinHalfTheta;
  4158. this._w = ( w * ratioA + this._w * ratioB );
  4159. this._x = ( x * ratioA + this._x * ratioB );
  4160. this._y = ( y * ratioA + this._y * ratioB );
  4161. this._z = ( z * ratioA + this._z * ratioB );
  4162. this._onChangeCallback();
  4163. return this;
  4164. }
  4165. /**
  4166. * Performs a spherical linear interpolation between the given quaternions
  4167. * and stores the result in this quaternion.
  4168. *
  4169. * @param {Quaternion} qa - The source quaternion.
  4170. * @param {Quaternion} qb - The target quaternion.
  4171. * @param {number} t - The interpolation factor in the closed interval `[0, 1]`.
  4172. * @return {Quaternion} A reference to this quaternion.
  4173. */
  4174. slerpQuaternions( qa, qb, t ) {
  4175. return this.copy( qa ).slerp( qb, t );
  4176. }
  4177. /**
  4178. * Sets this quaternion to a uniformly random, normalized quaternion.
  4179. *
  4180. * @return {Quaternion} A reference to this quaternion.
  4181. */
  4182. random() {
  4183. // Ken Shoemake
  4184. // Uniform random rotations
  4185. // D. Kirk, editor, Graphics Gems III, pages 124-132. Academic Press, New York, 1992.
  4186. const theta1 = 2 * Math.PI * Math.random();
  4187. const theta2 = 2 * Math.PI * Math.random();
  4188. const x0 = Math.random();
  4189. const r1 = Math.sqrt( 1 - x0 );
  4190. const r2 = Math.sqrt( x0 );
  4191. return this.set(
  4192. r1 * Math.sin( theta1 ),
  4193. r1 * Math.cos( theta1 ),
  4194. r2 * Math.sin( theta2 ),
  4195. r2 * Math.cos( theta2 ),
  4196. );
  4197. }
  4198. /**
  4199. * Returns `true` if this quaternion is equal with the given one.
  4200. *
  4201. * @param {Quaternion} quaternion - The quaternion to test for equality.
  4202. * @return {boolean} Whether this quaternion is equal with the given one.
  4203. */
  4204. equals( quaternion ) {
  4205. return ( quaternion._x === this._x ) && ( quaternion._y === this._y ) && ( quaternion._z === this._z ) && ( quaternion._w === this._w );
  4206. }
  4207. /**
  4208. * Sets this quaternion's components from the given array.
  4209. *
  4210. * @param {Array<number>} array - An array holding the quaternion component values.
  4211. * @param {number} [offset=0] - The offset into the array.
  4212. * @return {Quaternion} A reference to this quaternion.
  4213. */
  4214. fromArray( array, offset = 0 ) {
  4215. this._x = array[ offset ];
  4216. this._y = array[ offset + 1 ];
  4217. this._z = array[ offset + 2 ];
  4218. this._w = array[ offset + 3 ];
  4219. this._onChangeCallback();
  4220. return this;
  4221. }
  4222. /**
  4223. * Writes the components of this quaternion to the given array. If no array is provided,
  4224. * the method returns a new instance.
  4225. *
  4226. * @param {Array<number>} [array=[]] - The target array holding the quaternion components.
  4227. * @param {number} [offset=0] - Index of the first element in the array.
  4228. * @return {Array<number>} The quaternion components.
  4229. */
  4230. toArray( array = [], offset = 0 ) {
  4231. array[ offset ] = this._x;
  4232. array[ offset + 1 ] = this._y;
  4233. array[ offset + 2 ] = this._z;
  4234. array[ offset + 3 ] = this._w;
  4235. return array;
  4236. }
  4237. /**
  4238. * Sets the components of this quaternion from the given buffer attribute.
  4239. *
  4240. * @param {BufferAttribute} attribute - The buffer attribute holding quaternion data.
  4241. * @param {number} index - The index into the attribute.
  4242. * @return {Quaternion} A reference to this quaternion.
  4243. */
  4244. fromBufferAttribute( attribute, index ) {
  4245. this._x = attribute.getX( index );
  4246. this._y = attribute.getY( index );
  4247. this._z = attribute.getZ( index );
  4248. this._w = attribute.getW( index );
  4249. this._onChangeCallback();
  4250. return this;
  4251. }
  4252. /**
  4253. * This methods defines the serialization result of this class. Returns the
  4254. * numerical elements of this quaternion in an array of format `[x, y, z, w]`.
  4255. *
  4256. * @return {Array<number>} The serialized quaternion.
  4257. */
  4258. toJSON() {
  4259. return this.toArray();
  4260. }
  4261. _onChange( callback ) {
  4262. this._onChangeCallback = callback;
  4263. return this;
  4264. }
  4265. _onChangeCallback() {}
  4266. *[ Symbol.iterator ]() {
  4267. yield this._x;
  4268. yield this._y;
  4269. yield this._z;
  4270. yield this._w;
  4271. }
  4272. }
  4273. /**
  4274. * Class representing a 3D vector. A 3D vector is an ordered triplet of numbers
  4275. * (labeled x, y and z), which can be used to represent a number of things, such as:
  4276. *
  4277. * - A point in 3D space.
  4278. * - A direction and length in 3D space. In three.js the length will
  4279. * always be the Euclidean distance(straight-line distance) from `(0, 0, 0)` to `(x, y, z)`
  4280. * and the direction is also measured from `(0, 0, 0)` towards `(x, y, z)`.
  4281. * - Any arbitrary ordered triplet of numbers.
  4282. *
  4283. * There are other things a 3D vector can be used to represent, such as
  4284. * momentum vectors and so on, however these are the most
  4285. * common uses in three.js.
  4286. *
  4287. * Iterating through a vector instance will yield its components `(x, y, z)` in
  4288. * the corresponding order.
  4289. * ```js
  4290. * const a = new THREE.Vector3( 0, 1, 0 );
  4291. *
  4292. * //no arguments; will be initialised to (0, 0, 0)
  4293. * const b = new THREE.Vector3( );
  4294. *
  4295. * const d = a.distanceTo( b );
  4296. * ```
  4297. */
  4298. class Vector3 {
  4299. /**
  4300. * Constructs a new 3D vector.
  4301. *
  4302. * @param {number} [x=0] - The x value of this vector.
  4303. * @param {number} [y=0] - The y value of this vector.
  4304. * @param {number} [z=0] - The z value of this vector.
  4305. */
  4306. constructor( x = 0, y = 0, z = 0 ) {
  4307. /**
  4308. * This flag can be used for type testing.
  4309. *
  4310. * @type {boolean}
  4311. * @readonly
  4312. * @default true
  4313. */
  4314. Vector3.prototype.isVector3 = true;
  4315. /**
  4316. * The x value of this vector.
  4317. *
  4318. * @type {number}
  4319. */
  4320. this.x = x;
  4321. /**
  4322. * The y value of this vector.
  4323. *
  4324. * @type {number}
  4325. */
  4326. this.y = y;
  4327. /**
  4328. * The z value of this vector.
  4329. *
  4330. * @type {number}
  4331. */
  4332. this.z = z;
  4333. }
  4334. /**
  4335. * Sets the vector components.
  4336. *
  4337. * @param {number} x - The value of the x component.
  4338. * @param {number} y - The value of the y component.
  4339. * @param {number} z - The value of the z component.
  4340. * @return {Vector3} A reference to this vector.
  4341. */
  4342. set( x, y, z ) {
  4343. if ( z === undefined ) z = this.z; // sprite.scale.set(x,y)
  4344. this.x = x;
  4345. this.y = y;
  4346. this.z = z;
  4347. return this;
  4348. }
  4349. /**
  4350. * Sets the vector components to the same value.
  4351. *
  4352. * @param {number} scalar - The value to set for all vector components.
  4353. * @return {Vector3} A reference to this vector.
  4354. */
  4355. setScalar( scalar ) {
  4356. this.x = scalar;
  4357. this.y = scalar;
  4358. this.z = scalar;
  4359. return this;
  4360. }
  4361. /**
  4362. * Sets the vector's x component to the given value
  4363. *
  4364. * @param {number} x - The value to set.
  4365. * @return {Vector3} A reference to this vector.
  4366. */
  4367. setX( x ) {
  4368. this.x = x;
  4369. return this;
  4370. }
  4371. /**
  4372. * Sets the vector's y component to the given value
  4373. *
  4374. * @param {number} y - The value to set.
  4375. * @return {Vector3} A reference to this vector.
  4376. */
  4377. setY( y ) {
  4378. this.y = y;
  4379. return this;
  4380. }
  4381. /**
  4382. * Sets the vector's z component to the given value
  4383. *
  4384. * @param {number} z - The value to set.
  4385. * @return {Vector3} A reference to this vector.
  4386. */
  4387. setZ( z ) {
  4388. this.z = z;
  4389. return this;
  4390. }
  4391. /**
  4392. * Allows to set a vector component with an index.
  4393. *
  4394. * @param {number} index - The component index. `0` equals to x, `1` equals to y, `2` equals to z.
  4395. * @param {number} value - The value to set.
  4396. * @return {Vector3} A reference to this vector.
  4397. */
  4398. setComponent( index, value ) {
  4399. switch ( index ) {
  4400. case 0: this.x = value; break;
  4401. case 1: this.y = value; break;
  4402. case 2: this.z = value; break;
  4403. default: throw new Error( 'index is out of range: ' + index );
  4404. }
  4405. return this;
  4406. }
  4407. /**
  4408. * Returns the value of the vector component which matches the given index.
  4409. *
  4410. * @param {number} index - The component index. `0` equals to x, `1` equals to y, `2` equals to z.
  4411. * @return {number} A vector component value.
  4412. */
  4413. getComponent( index ) {
  4414. switch ( index ) {
  4415. case 0: return this.x;
  4416. case 1: return this.y;
  4417. case 2: return this.z;
  4418. default: throw new Error( 'index is out of range: ' + index );
  4419. }
  4420. }
  4421. /**
  4422. * Returns a new vector with copied values from this instance.
  4423. *
  4424. * @return {Vector3} A clone of this instance.
  4425. */
  4426. clone() {
  4427. return new this.constructor( this.x, this.y, this.z );
  4428. }
  4429. /**
  4430. * Copies the values of the given vector to this instance.
  4431. *
  4432. * @param {Vector3} v - The vector to copy.
  4433. * @return {Vector3} A reference to this vector.
  4434. */
  4435. copy( v ) {
  4436. this.x = v.x;
  4437. this.y = v.y;
  4438. this.z = v.z;
  4439. return this;
  4440. }
  4441. /**
  4442. * Adds the given vector to this instance.
  4443. *
  4444. * @param {Vector3} v - The vector to add.
  4445. * @return {Vector3} A reference to this vector.
  4446. */
  4447. add( v ) {
  4448. this.x += v.x;
  4449. this.y += v.y;
  4450. this.z += v.z;
  4451. return this;
  4452. }
  4453. /**
  4454. * Adds the given scalar value to all components of this instance.
  4455. *
  4456. * @param {number} s - The scalar to add.
  4457. * @return {Vector3} A reference to this vector.
  4458. */
  4459. addScalar( s ) {
  4460. this.x += s;
  4461. this.y += s;
  4462. this.z += s;
  4463. return this;
  4464. }
  4465. /**
  4466. * Adds the given vectors and stores the result in this instance.
  4467. *
  4468. * @param {Vector3} a - The first vector.
  4469. * @param {Vector3} b - The second vector.
  4470. * @return {Vector3} A reference to this vector.
  4471. */
  4472. addVectors( a, b ) {
  4473. this.x = a.x + b.x;
  4474. this.y = a.y + b.y;
  4475. this.z = a.z + b.z;
  4476. return this;
  4477. }
  4478. /**
  4479. * Adds the given vector scaled by the given factor to this instance.
  4480. *
  4481. * @param {Vector3} v - The vector.
  4482. * @param {number} s - The factor that scales `v`.
  4483. * @return {Vector3} A reference to this vector.
  4484. */
  4485. addScaledVector( v, s ) {
  4486. this.x += v.x * s;
  4487. this.y += v.y * s;
  4488. this.z += v.z * s;
  4489. return this;
  4490. }
  4491. /**
  4492. * Subtracts the given vector from this instance.
  4493. *
  4494. * @param {Vector3} v - The vector to subtract.
  4495. * @return {Vector3} A reference to this vector.
  4496. */
  4497. sub( v ) {
  4498. this.x -= v.x;
  4499. this.y -= v.y;
  4500. this.z -= v.z;
  4501. return this;
  4502. }
  4503. /**
  4504. * Subtracts the given scalar value from all components of this instance.
  4505. *
  4506. * @param {number} s - The scalar to subtract.
  4507. * @return {Vector3} A reference to this vector.
  4508. */
  4509. subScalar( s ) {
  4510. this.x -= s;
  4511. this.y -= s;
  4512. this.z -= s;
  4513. return this;
  4514. }
  4515. /**
  4516. * Subtracts the given vectors and stores the result in this instance.
  4517. *
  4518. * @param {Vector3} a - The first vector.
  4519. * @param {Vector3} b - The second vector.
  4520. * @return {Vector3} A reference to this vector.
  4521. */
  4522. subVectors( a, b ) {
  4523. this.x = a.x - b.x;
  4524. this.y = a.y - b.y;
  4525. this.z = a.z - b.z;
  4526. return this;
  4527. }
  4528. /**
  4529. * Multiplies the given vector with this instance.
  4530. *
  4531. * @param {Vector3} v - The vector to multiply.
  4532. * @return {Vector3} A reference to this vector.
  4533. */
  4534. multiply( v ) {
  4535. this.x *= v.x;
  4536. this.y *= v.y;
  4537. this.z *= v.z;
  4538. return this;
  4539. }
  4540. /**
  4541. * Multiplies the given scalar value with all components of this instance.
  4542. *
  4543. * @param {number} scalar - The scalar to multiply.
  4544. * @return {Vector3} A reference to this vector.
  4545. */
  4546. multiplyScalar( scalar ) {
  4547. this.x *= scalar;
  4548. this.y *= scalar;
  4549. this.z *= scalar;
  4550. return this;
  4551. }
  4552. /**
  4553. * Multiplies the given vectors and stores the result in this instance.
  4554. *
  4555. * @param {Vector3} a - The first vector.
  4556. * @param {Vector3} b - The second vector.
  4557. * @return {Vector3} A reference to this vector.
  4558. */
  4559. multiplyVectors( a, b ) {
  4560. this.x = a.x * b.x;
  4561. this.y = a.y * b.y;
  4562. this.z = a.z * b.z;
  4563. return this;
  4564. }
  4565. /**
  4566. * Applies the given Euler rotation to this vector.
  4567. *
  4568. * @param {Euler} euler - The Euler angles.
  4569. * @return {Vector3} A reference to this vector.
  4570. */
  4571. applyEuler( euler ) {
  4572. return this.applyQuaternion( _quaternion$4.setFromEuler( euler ) );
  4573. }
  4574. /**
  4575. * Applies a rotation specified by an axis and an angle to this vector.
  4576. *
  4577. * @param {Vector3} axis - A normalized vector representing the rotation axis.
  4578. * @param {number} angle - The angle in radians.
  4579. * @return {Vector3} A reference to this vector.
  4580. */
  4581. applyAxisAngle( axis, angle ) {
  4582. return this.applyQuaternion( _quaternion$4.setFromAxisAngle( axis, angle ) );
  4583. }
  4584. /**
  4585. * Multiplies this vector with the given 3x3 matrix.
  4586. *
  4587. * @param {Matrix3} m - The 3x3 matrix.
  4588. * @return {Vector3} A reference to this vector.
  4589. */
  4590. applyMatrix3( m ) {
  4591. const x = this.x, y = this.y, z = this.z;
  4592. const e = m.elements;
  4593. this.x = e[ 0 ] * x + e[ 3 ] * y + e[ 6 ] * z;
  4594. this.y = e[ 1 ] * x + e[ 4 ] * y + e[ 7 ] * z;
  4595. this.z = e[ 2 ] * x + e[ 5 ] * y + e[ 8 ] * z;
  4596. return this;
  4597. }
  4598. /**
  4599. * Multiplies this vector by the given normal matrix and normalizes
  4600. * the result.
  4601. *
  4602. * @param {Matrix3} m - The normal matrix.
  4603. * @return {Vector3} A reference to this vector.
  4604. */
  4605. applyNormalMatrix( m ) {
  4606. return this.applyMatrix3( m ).normalize();
  4607. }
  4608. /**
  4609. * Multiplies this vector (with an implicit 1 in the 4th dimension) by m, and
  4610. * divides by perspective.
  4611. *
  4612. * @param {Matrix4} m - The matrix to apply.
  4613. * @return {Vector3} A reference to this vector.
  4614. */
  4615. applyMatrix4( m ) {
  4616. const x = this.x, y = this.y, z = this.z;
  4617. const e = m.elements;
  4618. const w = 1 / ( e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] );
  4619. this.x = ( e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] ) * w;
  4620. this.y = ( e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] ) * w;
  4621. this.z = ( e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] ) * w;
  4622. return this;
  4623. }
  4624. /**
  4625. * Applies the given Quaternion to this vector.
  4626. *
  4627. * @param {Quaternion} q - The Quaternion.
  4628. * @return {Vector3} A reference to this vector.
  4629. */
  4630. applyQuaternion( q ) {
  4631. // quaternion q is assumed to have unit length
  4632. const vx = this.x, vy = this.y, vz = this.z;
  4633. const qx = q.x, qy = q.y, qz = q.z, qw = q.w;
  4634. // t = 2 * cross( q.xyz, v );
  4635. const tx = 2 * ( qy * vz - qz * vy );
  4636. const ty = 2 * ( qz * vx - qx * vz );
  4637. const tz = 2 * ( qx * vy - qy * vx );
  4638. // v + q.w * t + cross( q.xyz, t );
  4639. this.x = vx + qw * tx + qy * tz - qz * ty;
  4640. this.y = vy + qw * ty + qz * tx - qx * tz;
  4641. this.z = vz + qw * tz + qx * ty - qy * tx;
  4642. return this;
  4643. }
  4644. /**
  4645. * Projects this vector from world space into the camera's normalized
  4646. * device coordinate (NDC) space.
  4647. *
  4648. * @param {Camera} camera - The camera.
  4649. * @return {Vector3} A reference to this vector.
  4650. */
  4651. project( camera ) {
  4652. return this.applyMatrix4( camera.matrixWorldInverse ).applyMatrix4( camera.projectionMatrix );
  4653. }
  4654. /**
  4655. * Unprojects this vector from the camera's normalized device coordinate (NDC)
  4656. * space into world space.
  4657. *
  4658. * @param {Camera} camera - The camera.
  4659. * @return {Vector3} A reference to this vector.
  4660. */
  4661. unproject( camera ) {
  4662. return this.applyMatrix4( camera.projectionMatrixInverse ).applyMatrix4( camera.matrixWorld );
  4663. }
  4664. /**
  4665. * Transforms the direction of this vector by a matrix (the upper left 3 x 3
  4666. * subset of the given 4x4 matrix and then normalizes the result.
  4667. *
  4668. * @param {Matrix4} m - The matrix.
  4669. * @return {Vector3} A reference to this vector.
  4670. */
  4671. transformDirection( m ) {
  4672. // input: THREE.Matrix4 affine matrix
  4673. // vector interpreted as a direction
  4674. const x = this.x, y = this.y, z = this.z;
  4675. const e = m.elements;
  4676. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z;
  4677. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z;
  4678. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z;
  4679. return this.normalize();
  4680. }
  4681. /**
  4682. * Divides this instance by the given vector.
  4683. *
  4684. * @param {Vector3} v - The vector to divide.
  4685. * @return {Vector3} A reference to this vector.
  4686. */
  4687. divide( v ) {
  4688. this.x /= v.x;
  4689. this.y /= v.y;
  4690. this.z /= v.z;
  4691. return this;
  4692. }
  4693. /**
  4694. * Divides this vector by the given scalar.
  4695. *
  4696. * @param {number} scalar - The scalar to divide.
  4697. * @return {Vector3} A reference to this vector.
  4698. */
  4699. divideScalar( scalar ) {
  4700. return this.multiplyScalar( 1 / scalar );
  4701. }
  4702. /**
  4703. * If this vector's x, y or z value is greater than the given vector's x, y or z
  4704. * value, replace that value with the corresponding min value.
  4705. *
  4706. * @param {Vector3} v - The vector.
  4707. * @return {Vector3} A reference to this vector.
  4708. */
  4709. min( v ) {
  4710. this.x = Math.min( this.x, v.x );
  4711. this.y = Math.min( this.y, v.y );
  4712. this.z = Math.min( this.z, v.z );
  4713. return this;
  4714. }
  4715. /**
  4716. * If this vector's x, y or z value is less than the given vector's x, y or z
  4717. * value, replace that value with the corresponding max value.
  4718. *
  4719. * @param {Vector3} v - The vector.
  4720. * @return {Vector3} A reference to this vector.
  4721. */
  4722. max( v ) {
  4723. this.x = Math.max( this.x, v.x );
  4724. this.y = Math.max( this.y, v.y );
  4725. this.z = Math.max( this.z, v.z );
  4726. return this;
  4727. }
  4728. /**
  4729. * If this vector's x, y or z value is greater than the max vector's x, y or z
  4730. * value, it is replaced by the corresponding value.
  4731. * If this vector's x, y or z value is less than the min vector's x, y or z value,
  4732. * it is replaced by the corresponding value.
  4733. *
  4734. * @param {Vector3} min - The minimum x, y and z values.
  4735. * @param {Vector3} max - The maximum x, y and z values in the desired range.
  4736. * @return {Vector3} A reference to this vector.
  4737. */
  4738. clamp( min, max ) {
  4739. // assumes min < max, componentwise
  4740. this.x = clamp( this.x, min.x, max.x );
  4741. this.y = clamp( this.y, min.y, max.y );
  4742. this.z = clamp( this.z, min.z, max.z );
  4743. return this;
  4744. }
  4745. /**
  4746. * If this vector's x, y or z values are greater than the max value, they are
  4747. * replaced by the max value.
  4748. * If this vector's x, y or z values are less than the min value, they are
  4749. * replaced by the min value.
  4750. *
  4751. * @param {number} minVal - The minimum value the components will be clamped to.
  4752. * @param {number} maxVal - The maximum value the components will be clamped to.
  4753. * @return {Vector3} A reference to this vector.
  4754. */
  4755. clampScalar( minVal, maxVal ) {
  4756. this.x = clamp( this.x, minVal, maxVal );
  4757. this.y = clamp( this.y, minVal, maxVal );
  4758. this.z = clamp( this.z, minVal, maxVal );
  4759. return this;
  4760. }
  4761. /**
  4762. * If this vector's length is greater than the max value, it is replaced by
  4763. * the max value.
  4764. * If this vector's length is less than the min value, it is replaced by the
  4765. * min value.
  4766. *
  4767. * @param {number} min - The minimum value the vector length will be clamped to.
  4768. * @param {number} max - The maximum value the vector length will be clamped to.
  4769. * @return {Vector3} A reference to this vector.
  4770. */
  4771. clampLength( min, max ) {
  4772. const length = this.length();
  4773. return this.divideScalar( length || 1 ).multiplyScalar( clamp( length, min, max ) );
  4774. }
  4775. /**
  4776. * The components of this vector are rounded down to the nearest integer value.
  4777. *
  4778. * @return {Vector3} A reference to this vector.
  4779. */
  4780. floor() {
  4781. this.x = Math.floor( this.x );
  4782. this.y = Math.floor( this.y );
  4783. this.z = Math.floor( this.z );
  4784. return this;
  4785. }
  4786. /**
  4787. * The components of this vector are rounded up to the nearest integer value.
  4788. *
  4789. * @return {Vector3} A reference to this vector.
  4790. */
  4791. ceil() {
  4792. this.x = Math.ceil( this.x );
  4793. this.y = Math.ceil( this.y );
  4794. this.z = Math.ceil( this.z );
  4795. return this;
  4796. }
  4797. /**
  4798. * The components of this vector are rounded to the nearest integer value
  4799. *
  4800. * @return {Vector3} A reference to this vector.
  4801. */
  4802. round() {
  4803. this.x = Math.round( this.x );
  4804. this.y = Math.round( this.y );
  4805. this.z = Math.round( this.z );
  4806. return this;
  4807. }
  4808. /**
  4809. * The components of this vector are rounded towards zero (up if negative,
  4810. * down if positive) to an integer value.
  4811. *
  4812. * @return {Vector3} A reference to this vector.
  4813. */
  4814. roundToZero() {
  4815. this.x = Math.trunc( this.x );
  4816. this.y = Math.trunc( this.y );
  4817. this.z = Math.trunc( this.z );
  4818. return this;
  4819. }
  4820. /**
  4821. * Inverts this vector - i.e. sets x = -x, y = -y and z = -z.
  4822. *
  4823. * @return {Vector3} A reference to this vector.
  4824. */
  4825. negate() {
  4826. this.x = - this.x;
  4827. this.y = - this.y;
  4828. this.z = - this.z;
  4829. return this;
  4830. }
  4831. /**
  4832. * Calculates the dot product of the given vector with this instance.
  4833. *
  4834. * @param {Vector3} v - The vector to compute the dot product with.
  4835. * @return {number} The result of the dot product.
  4836. */
  4837. dot( v ) {
  4838. return this.x * v.x + this.y * v.y + this.z * v.z;
  4839. }
  4840. // TODO lengthSquared?
  4841. /**
  4842. * Computes the square of the Euclidean length (straight-line length) from
  4843. * (0, 0, 0) to (x, y, z). If you are comparing the lengths of vectors, you should
  4844. * compare the length squared instead as it is slightly more efficient to calculate.
  4845. *
  4846. * @return {number} The square length of this vector.
  4847. */
  4848. lengthSq() {
  4849. return this.x * this.x + this.y * this.y + this.z * this.z;
  4850. }
  4851. /**
  4852. * Computes the Euclidean length (straight-line length) from (0, 0, 0) to (x, y, z).
  4853. *
  4854. * @return {number} The length of this vector.
  4855. */
  4856. length() {
  4857. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z );
  4858. }
  4859. /**
  4860. * Computes the Manhattan length of this vector.
  4861. *
  4862. * @return {number} The length of this vector.
  4863. */
  4864. manhattanLength() {
  4865. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z );
  4866. }
  4867. /**
  4868. * Converts this vector to a unit vector - that is, sets it equal to a vector
  4869. * with the same direction as this one, but with a vector length of `1`.
  4870. *
  4871. * @return {Vector3} A reference to this vector.
  4872. */
  4873. normalize() {
  4874. return this.divideScalar( this.length() || 1 );
  4875. }
  4876. /**
  4877. * Sets this vector to a vector with the same direction as this one, but
  4878. * with the specified length.
  4879. *
  4880. * @param {number} length - The new length of this vector.
  4881. * @return {Vector3} A reference to this vector.
  4882. */
  4883. setLength( length ) {
  4884. return this.normalize().multiplyScalar( length );
  4885. }
  4886. /**
  4887. * Linearly interpolates between the given vector and this instance, where
  4888. * alpha is the percent distance along the line - alpha = 0 will be this
  4889. * vector, and alpha = 1 will be the given one.
  4890. *
  4891. * @param {Vector3} v - The vector to interpolate towards.
  4892. * @param {number} alpha - The interpolation factor, typically in the closed interval `[0, 1]`.
  4893. * @return {Vector3} A reference to this vector.
  4894. */
  4895. lerp( v, alpha ) {
  4896. this.x += ( v.x - this.x ) * alpha;
  4897. this.y += ( v.y - this.y ) * alpha;
  4898. this.z += ( v.z - this.z ) * alpha;
  4899. return this;
  4900. }
  4901. /**
  4902. * Linearly interpolates between the given vectors, where alpha is the percent
  4903. * distance along the line - alpha = 0 will be first vector, and alpha = 1 will
  4904. * be the second one. The result is stored in this instance.
  4905. *
  4906. * @param {Vector3} v1 - The first vector.
  4907. * @param {Vector3} v2 - The second vector.
  4908. * @param {number} alpha - The interpolation factor, typically in the closed interval `[0, 1]`.
  4909. * @return {Vector3} A reference to this vector.
  4910. */
  4911. lerpVectors( v1, v2, alpha ) {
  4912. this.x = v1.x + ( v2.x - v1.x ) * alpha;
  4913. this.y = v1.y + ( v2.y - v1.y ) * alpha;
  4914. this.z = v1.z + ( v2.z - v1.z ) * alpha;
  4915. return this;
  4916. }
  4917. /**
  4918. * Calculates the cross product of the given vector with this instance.
  4919. *
  4920. * @param {Vector3} v - The vector to compute the cross product with.
  4921. * @return {Vector3} The result of the cross product.
  4922. */
  4923. cross( v ) {
  4924. return this.crossVectors( this, v );
  4925. }
  4926. /**
  4927. * Calculates the cross product of the given vectors and stores the result
  4928. * in this instance.
  4929. *
  4930. * @param {Vector3} a - The first vector.
  4931. * @param {Vector3} b - The second vector.
  4932. * @return {Vector3} A reference to this vector.
  4933. */
  4934. crossVectors( a, b ) {
  4935. const ax = a.x, ay = a.y, az = a.z;
  4936. const bx = b.x, by = b.y, bz = b.z;
  4937. this.x = ay * bz - az * by;
  4938. this.y = az * bx - ax * bz;
  4939. this.z = ax * by - ay * bx;
  4940. return this;
  4941. }
  4942. /**
  4943. * Projects this vector onto the given one.
  4944. *
  4945. * @param {Vector3} v - The vector to project to.
  4946. * @return {Vector3} A reference to this vector.
  4947. */
  4948. projectOnVector( v ) {
  4949. const denominator = v.lengthSq();
  4950. if ( denominator === 0 ) return this.set( 0, 0, 0 );
  4951. const scalar = v.dot( this ) / denominator;
  4952. return this.copy( v ).multiplyScalar( scalar );
  4953. }
  4954. /**
  4955. * Projects this vector onto a plane by subtracting this
  4956. * vector projected onto the plane's normal from this vector.
  4957. *
  4958. * @param {Vector3} planeNormal - The plane normal.
  4959. * @return {Vector3} A reference to this vector.
  4960. */
  4961. projectOnPlane( planeNormal ) {
  4962. _vector$c.copy( this ).projectOnVector( planeNormal );
  4963. return this.sub( _vector$c );
  4964. }
  4965. /**
  4966. * Reflects this vector off a plane orthogonal to the given normal vector.
  4967. *
  4968. * @param {Vector3} normal - The (normalized) normal vector.
  4969. * @return {Vector3} A reference to this vector.
  4970. */
  4971. reflect( normal ) {
  4972. return this.sub( _vector$c.copy( normal ).multiplyScalar( 2 * this.dot( normal ) ) );
  4973. }
  4974. /**
  4975. * Returns the angle between the given vector and this instance in radians.
  4976. *
  4977. * @param {Vector3} v - The vector to compute the angle with.
  4978. * @return {number} The angle in radians.
  4979. */
  4980. angleTo( v ) {
  4981. const denominator = Math.sqrt( this.lengthSq() * v.lengthSq() );
  4982. if ( denominator === 0 ) return Math.PI / 2;
  4983. const theta = this.dot( v ) / denominator;
  4984. // clamp, to handle numerical problems
  4985. return Math.acos( clamp( theta, -1, 1 ) );
  4986. }
  4987. /**
  4988. * Computes the distance from the given vector to this instance.
  4989. *
  4990. * @param {Vector3} v - The vector to compute the distance to.
  4991. * @return {number} The distance.
  4992. */
  4993. distanceTo( v ) {
  4994. return Math.sqrt( this.distanceToSquared( v ) );
  4995. }
  4996. /**
  4997. * Computes the squared distance from the given vector to this instance.
  4998. * If you are just comparing the distance with another distance, you should compare
  4999. * the distance squared instead as it is slightly more efficient to calculate.
  5000. *
  5001. * @param {Vector3} v - The vector to compute the squared distance to.
  5002. * @return {number} The squared distance.
  5003. */
  5004. distanceToSquared( v ) {
  5005. const dx = this.x - v.x, dy = this.y - v.y, dz = this.z - v.z;
  5006. return dx * dx + dy * dy + dz * dz;
  5007. }
  5008. /**
  5009. * Computes the Manhattan distance from the given vector to this instance.
  5010. *
  5011. * @param {Vector3} v - The vector to compute the Manhattan distance to.
  5012. * @return {number} The Manhattan distance.
  5013. */
  5014. manhattanDistanceTo( v ) {
  5015. return Math.abs( this.x - v.x ) + Math.abs( this.y - v.y ) + Math.abs( this.z - v.z );
  5016. }
  5017. /**
  5018. * Sets the vector components from the given spherical coordinates.
  5019. *
  5020. * @param {Spherical} s - The spherical coordinates.
  5021. * @return {Vector3} A reference to this vector.
  5022. */
  5023. setFromSpherical( s ) {
  5024. return this.setFromSphericalCoords( s.radius, s.phi, s.theta );
  5025. }
  5026. /**
  5027. * Sets the vector components from the given spherical coordinates.
  5028. *
  5029. * @param {number} radius - The radius.
  5030. * @param {number} phi - The phi angle in radians.
  5031. * @param {number} theta - The theta angle in radians.
  5032. * @return {Vector3} A reference to this vector.
  5033. */
  5034. setFromSphericalCoords( radius, phi, theta ) {
  5035. const sinPhiRadius = Math.sin( phi ) * radius;
  5036. this.x = sinPhiRadius * Math.sin( theta );
  5037. this.y = Math.cos( phi ) * radius;
  5038. this.z = sinPhiRadius * Math.cos( theta );
  5039. return this;
  5040. }
  5041. /**
  5042. * Sets the vector components from the given cylindrical coordinates.
  5043. *
  5044. * @param {Cylindrical} c - The cylindrical coordinates.
  5045. * @return {Vector3} A reference to this vector.
  5046. */
  5047. setFromCylindrical( c ) {
  5048. return this.setFromCylindricalCoords( c.radius, c.theta, c.y );
  5049. }
  5050. /**
  5051. * Sets the vector components from the given cylindrical coordinates.
  5052. *
  5053. * @param {number} radius - The radius.
  5054. * @param {number} theta - The theta angle in radians.
  5055. * @param {number} y - The y value.
  5056. * @return {Vector3} A reference to this vector.
  5057. */
  5058. setFromCylindricalCoords( radius, theta, y ) {
  5059. this.x = radius * Math.sin( theta );
  5060. this.y = y;
  5061. this.z = radius * Math.cos( theta );
  5062. return this;
  5063. }
  5064. /**
  5065. * Sets the vector components to the position elements of the
  5066. * given transformation matrix.
  5067. *
  5068. * @param {Matrix4} m - The 4x4 matrix.
  5069. * @return {Vector3} A reference to this vector.
  5070. */
  5071. setFromMatrixPosition( m ) {
  5072. const e = m.elements;
  5073. this.x = e[ 12 ];
  5074. this.y = e[ 13 ];
  5075. this.z = e[ 14 ];
  5076. return this;
  5077. }
  5078. /**
  5079. * Sets the vector components to the scale elements of the
  5080. * given transformation matrix.
  5081. *
  5082. * @param {Matrix4} m - The 4x4 matrix.
  5083. * @return {Vector3} A reference to this vector.
  5084. */
  5085. setFromMatrixScale( m ) {
  5086. const sx = this.setFromMatrixColumn( m, 0 ).length();
  5087. const sy = this.setFromMatrixColumn( m, 1 ).length();
  5088. const sz = this.setFromMatrixColumn( m, 2 ).length();
  5089. this.x = sx;
  5090. this.y = sy;
  5091. this.z = sz;
  5092. return this;
  5093. }
  5094. /**
  5095. * Sets the vector components from the specified matrix column.
  5096. *
  5097. * @param {Matrix4} m - The 4x4 matrix.
  5098. * @param {number} index - The column index.
  5099. * @return {Vector3} A reference to this vector.
  5100. */
  5101. setFromMatrixColumn( m, index ) {
  5102. return this.fromArray( m.elements, index * 4 );
  5103. }
  5104. /**
  5105. * Sets the vector components from the specified matrix column.
  5106. *
  5107. * @param {Matrix3} m - The 3x3 matrix.
  5108. * @param {number} index - The column index.
  5109. * @return {Vector3} A reference to this vector.
  5110. */
  5111. setFromMatrix3Column( m, index ) {
  5112. return this.fromArray( m.elements, index * 3 );
  5113. }
  5114. /**
  5115. * Sets the vector components from the given Euler angles.
  5116. *
  5117. * @param {Euler} e - The Euler angles to set.
  5118. * @return {Vector3} A reference to this vector.
  5119. */
  5120. setFromEuler( e ) {
  5121. this.x = e._x;
  5122. this.y = e._y;
  5123. this.z = e._z;
  5124. return this;
  5125. }
  5126. /**
  5127. * Sets the vector components from the RGB components of the
  5128. * given color.
  5129. *
  5130. * @param {Color} c - The color to set.
  5131. * @return {Vector3} A reference to this vector.
  5132. */
  5133. setFromColor( c ) {
  5134. this.x = c.r;
  5135. this.y = c.g;
  5136. this.z = c.b;
  5137. return this;
  5138. }
  5139. /**
  5140. * Returns `true` if this vector is equal with the given one.
  5141. *
  5142. * @param {Vector3} v - The vector to test for equality.
  5143. * @return {boolean} Whether this vector is equal with the given one.
  5144. */
  5145. equals( v ) {
  5146. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) );
  5147. }
  5148. /**
  5149. * Sets this vector's x value to be `array[ offset ]`, y value to be `array[ offset + 1 ]`
  5150. * and z value to be `array[ offset + 2 ]`.
  5151. *
  5152. * @param {Array<number>} array - An array holding the vector component values.
  5153. * @param {number} [offset=0] - The offset into the array.
  5154. * @return {Vector3} A reference to this vector.
  5155. */
  5156. fromArray( array, offset = 0 ) {
  5157. this.x = array[ offset ];
  5158. this.y = array[ offset + 1 ];
  5159. this.z = array[ offset + 2 ];
  5160. return this;
  5161. }
  5162. /**
  5163. * Writes the components of this vector to the given array. If no array is provided,
  5164. * the method returns a new instance.
  5165. *
  5166. * @param {Array<number>} [array=[]] - The target array holding the vector components.
  5167. * @param {number} [offset=0] - Index of the first element in the array.
  5168. * @return {Array<number>} The vector components.
  5169. */
  5170. toArray( array = [], offset = 0 ) {
  5171. array[ offset ] = this.x;
  5172. array[ offset + 1 ] = this.y;
  5173. array[ offset + 2 ] = this.z;
  5174. return array;
  5175. }
  5176. /**
  5177. * Sets the components of this vector from the given buffer attribute.
  5178. *
  5179. * @param {BufferAttribute} attribute - The buffer attribute holding vector data.
  5180. * @param {number} index - The index into the attribute.
  5181. * @return {Vector3} A reference to this vector.
  5182. */
  5183. fromBufferAttribute( attribute, index ) {
  5184. this.x = attribute.getX( index );
  5185. this.y = attribute.getY( index );
  5186. this.z = attribute.getZ( index );
  5187. return this;
  5188. }
  5189. /**
  5190. * Sets each component of this vector to a pseudo-random value between `0` and
  5191. * `1`, excluding `1`.
  5192. *
  5193. * @return {Vector3} A reference to this vector.
  5194. */
  5195. random() {
  5196. this.x = Math.random();
  5197. this.y = Math.random();
  5198. this.z = Math.random();
  5199. return this;
  5200. }
  5201. /**
  5202. * Sets this vector to a uniformly random point on a unit sphere.
  5203. *
  5204. * @return {Vector3} A reference to this vector.
  5205. */
  5206. randomDirection() {
  5207. // https://mathworld.wolfram.com/SpherePointPicking.html
  5208. const theta = Math.random() * Math.PI * 2;
  5209. const u = Math.random() * 2 - 1;
  5210. const c = Math.sqrt( 1 - u * u );
  5211. this.x = c * Math.cos( theta );
  5212. this.y = u;
  5213. this.z = c * Math.sin( theta );
  5214. return this;
  5215. }
  5216. *[ Symbol.iterator ]() {
  5217. yield this.x;
  5218. yield this.y;
  5219. yield this.z;
  5220. }
  5221. }
  5222. const _vector$c = /*@__PURE__*/ new Vector3();
  5223. const _quaternion$4 = /*@__PURE__*/ new Quaternion();
  5224. /**
  5225. * Represents an axis-aligned bounding box (AABB) in 3D space.
  5226. */
  5227. class Box3 {
  5228. /**
  5229. * Constructs a new bounding box.
  5230. *
  5231. * @param {Vector3} [min=(Infinity,Infinity,Infinity)] - A vector representing the lower boundary of the box.
  5232. * @param {Vector3} [max=(-Infinity,-Infinity,-Infinity)] - A vector representing the upper boundary of the box.
  5233. */
  5234. constructor( min = new Vector3( + Infinity, + Infinity, + Infinity ), max = new Vector3( - Infinity, - Infinity, - Infinity ) ) {
  5235. /**
  5236. * This flag can be used for type testing.
  5237. *
  5238. * @type {boolean}
  5239. * @readonly
  5240. * @default true
  5241. */
  5242. this.isBox3 = true;
  5243. /**
  5244. * The lower boundary of the box.
  5245. *
  5246. * @type {Vector3}
  5247. */
  5248. this.min = min;
  5249. /**
  5250. * The upper boundary of the box.
  5251. *
  5252. * @type {Vector3}
  5253. */
  5254. this.max = max;
  5255. }
  5256. /**
  5257. * Sets the lower and upper boundaries of this box.
  5258. * Please note that this method only copies the values from the given objects.
  5259. *
  5260. * @param {Vector3} min - The lower boundary of the box.
  5261. * @param {Vector3} max - The upper boundary of the box.
  5262. * @return {Box3} A reference to this bounding box.
  5263. */
  5264. set( min, max ) {
  5265. this.min.copy( min );
  5266. this.max.copy( max );
  5267. return this;
  5268. }
  5269. /**
  5270. * Sets the upper and lower bounds of this box so it encloses the position data
  5271. * in the given array.
  5272. *
  5273. * @param {Array<number>} array - An array holding 3D position data.
  5274. * @return {Box3} A reference to this bounding box.
  5275. */
  5276. setFromArray( array ) {
  5277. this.makeEmpty();
  5278. for ( let i = 0, il = array.length; i < il; i += 3 ) {
  5279. this.expandByPoint( _vector$b.fromArray( array, i ) );
  5280. }
  5281. return this;
  5282. }
  5283. /**
  5284. * Sets the upper and lower bounds of this box so it encloses the position data
  5285. * in the given buffer attribute.
  5286. *
  5287. * @param {BufferAttribute} attribute - A buffer attribute holding 3D position data.
  5288. * @return {Box3} A reference to this bounding box.
  5289. */
  5290. setFromBufferAttribute( attribute ) {
  5291. this.makeEmpty();
  5292. for ( let i = 0, il = attribute.count; i < il; i ++ ) {
  5293. this.expandByPoint( _vector$b.fromBufferAttribute( attribute, i ) );
  5294. }
  5295. return this;
  5296. }
  5297. /**
  5298. * Sets the upper and lower bounds of this box so it encloses the position data
  5299. * in the given array.
  5300. *
  5301. * @param {Array<Vector3>} points - An array holding 3D position data as instances of {@link Vector3}.
  5302. * @return {Box3} A reference to this bounding box.
  5303. */
  5304. setFromPoints( points ) {
  5305. this.makeEmpty();
  5306. for ( let i = 0, il = points.length; i < il; i ++ ) {
  5307. this.expandByPoint( points[ i ] );
  5308. }
  5309. return this;
  5310. }
  5311. /**
  5312. * Centers this box on the given center vector and sets this box's width, height and
  5313. * depth to the given size values.
  5314. *
  5315. * @param {Vector3} center - The center of the box.
  5316. * @param {Vector3} size - The x, y and z dimensions of the box.
  5317. * @return {Box3} A reference to this bounding box.
  5318. */
  5319. setFromCenterAndSize( center, size ) {
  5320. const halfSize = _vector$b.copy( size ).multiplyScalar( 0.5 );
  5321. this.min.copy( center ).sub( halfSize );
  5322. this.max.copy( center ).add( halfSize );
  5323. return this;
  5324. }
  5325. /**
  5326. * Computes the world-axis-aligned bounding box for the given 3D object
  5327. * (including its children), accounting for the object's, and children's,
  5328. * world transforms. The function may result in a larger box than strictly necessary.
  5329. *
  5330. * @param {Object3D} object - The 3D object to compute the bounding box for.
  5331. * @param {boolean} [precise=false] - If set to `true`, the method computes the smallest
  5332. * world-axis-aligned bounding box at the expense of more computation.
  5333. * @return {Box3} A reference to this bounding box.
  5334. */
  5335. setFromObject( object, precise = false ) {
  5336. this.makeEmpty();
  5337. return this.expandByObject( object, precise );
  5338. }
  5339. /**
  5340. * Returns a new box with copied values from this instance.
  5341. *
  5342. * @return {Box3} A clone of this instance.
  5343. */
  5344. clone() {
  5345. return new this.constructor().copy( this );
  5346. }
  5347. /**
  5348. * Copies the values of the given box to this instance.
  5349. *
  5350. * @param {Box3} box - The box to copy.
  5351. * @return {Box3} A reference to this bounding box.
  5352. */
  5353. copy( box ) {
  5354. this.min.copy( box.min );
  5355. this.max.copy( box.max );
  5356. return this;
  5357. }
  5358. /**
  5359. * Makes this box empty which means in encloses a zero space in 3D.
  5360. *
  5361. * @return {Box3} A reference to this bounding box.
  5362. */
  5363. makeEmpty() {
  5364. this.min.x = this.min.y = this.min.z = + Infinity;
  5365. this.max.x = this.max.y = this.max.z = - Infinity;
  5366. return this;
  5367. }
  5368. /**
  5369. * Returns true if this box includes zero points within its bounds.
  5370. * Note that a box with equal lower and upper bounds still includes one
  5371. * point, the one both bounds share.
  5372. *
  5373. * @return {boolean} Whether this box is empty or not.
  5374. */
  5375. isEmpty() {
  5376. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  5377. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y ) || ( this.max.z < this.min.z );
  5378. }
  5379. /**
  5380. * Returns the center point of this box.
  5381. *
  5382. * @param {Vector3} target - The target vector that is used to store the method's result.
  5383. * @return {Vector3} The center point.
  5384. */
  5385. getCenter( target ) {
  5386. return this.isEmpty() ? target.set( 0, 0, 0 ) : target.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  5387. }
  5388. /**
  5389. * Returns the dimensions of this box.
  5390. *
  5391. * @param {Vector3} target - The target vector that is used to store the method's result.
  5392. * @return {Vector3} The size.
  5393. */
  5394. getSize( target ) {
  5395. return this.isEmpty() ? target.set( 0, 0, 0 ) : target.subVectors( this.max, this.min );
  5396. }
  5397. /**
  5398. * Expands the boundaries of this box to include the given point.
  5399. *
  5400. * @param {Vector3} point - The point that should be included by the bounding box.
  5401. * @return {Box3} A reference to this bounding box.
  5402. */
  5403. expandByPoint( point ) {
  5404. this.min.min( point );
  5405. this.max.max( point );
  5406. return this;
  5407. }
  5408. /**
  5409. * Expands this box equilaterally by the given vector. The width of this
  5410. * box will be expanded by the x component of the vector in both
  5411. * directions. The height of this box will be expanded by the y component of
  5412. * the vector in both directions. The depth of this box will be
  5413. * expanded by the z component of the vector in both directions.
  5414. *
  5415. * @param {Vector3} vector - The vector that should expand the bounding box.
  5416. * @return {Box3} A reference to this bounding box.
  5417. */
  5418. expandByVector( vector ) {
  5419. this.min.sub( vector );
  5420. this.max.add( vector );
  5421. return this;
  5422. }
  5423. /**
  5424. * Expands each dimension of the box by the given scalar. If negative, the
  5425. * dimensions of the box will be contracted.
  5426. *
  5427. * @param {number} scalar - The scalar value that should expand the bounding box.
  5428. * @return {Box3} A reference to this bounding box.
  5429. */
  5430. expandByScalar( scalar ) {
  5431. this.min.addScalar( - scalar );
  5432. this.max.addScalar( scalar );
  5433. return this;
  5434. }
  5435. /**
  5436. * Expands the boundaries of this box to include the given 3D object and
  5437. * its children, accounting for the object's, and children's, world
  5438. * transforms. The function may result in a larger box than strictly
  5439. * necessary (unless the precise parameter is set to true).
  5440. *
  5441. * @param {Object3D} object - The 3D object that should expand the bounding box.
  5442. * @param {boolean} precise - If set to `true`, the method expands the bounding box
  5443. * as little as necessary at the expense of more computation.
  5444. * @return {Box3} A reference to this bounding box.
  5445. */
  5446. expandByObject( object, precise = false ) {
  5447. // Computes the world-axis-aligned bounding box of an object (including its children),
  5448. // accounting for both the object's, and children's, world transforms
  5449. object.updateWorldMatrix( false, false );
  5450. const geometry = object.geometry;
  5451. if ( geometry !== undefined ) {
  5452. const positionAttribute = geometry.getAttribute( 'position' );
  5453. // precise AABB computation based on vertex data requires at least a position attribute.
  5454. // instancing isn't supported so far and uses the normal (conservative) code path.
  5455. if ( precise === true && positionAttribute !== undefined && object.isInstancedMesh !== true ) {
  5456. for ( let i = 0, l = positionAttribute.count; i < l; i ++ ) {
  5457. if ( object.isMesh === true ) {
  5458. object.getVertexPosition( i, _vector$b );
  5459. } else {
  5460. _vector$b.fromBufferAttribute( positionAttribute, i );
  5461. }
  5462. _vector$b.applyMatrix4( object.matrixWorld );
  5463. this.expandByPoint( _vector$b );
  5464. }
  5465. } else {
  5466. if ( object.boundingBox !== undefined ) {
  5467. // object-level bounding box
  5468. if ( object.boundingBox === null ) {
  5469. object.computeBoundingBox();
  5470. }
  5471. _box$4.copy( object.boundingBox );
  5472. } else {
  5473. // geometry-level bounding box
  5474. if ( geometry.boundingBox === null ) {
  5475. geometry.computeBoundingBox();
  5476. }
  5477. _box$4.copy( geometry.boundingBox );
  5478. }
  5479. _box$4.applyMatrix4( object.matrixWorld );
  5480. this.union( _box$4 );
  5481. }
  5482. }
  5483. const children = object.children;
  5484. for ( let i = 0, l = children.length; i < l; i ++ ) {
  5485. this.expandByObject( children[ i ], precise );
  5486. }
  5487. return this;
  5488. }
  5489. /**
  5490. * Returns `true` if the given point lies within or on the boundaries of this box.
  5491. *
  5492. * @param {Vector3} point - The point to test.
  5493. * @return {boolean} Whether the bounding box contains the given point or not.
  5494. */
  5495. containsPoint( point ) {
  5496. return point.x >= this.min.x && point.x <= this.max.x &&
  5497. point.y >= this.min.y && point.y <= this.max.y &&
  5498. point.z >= this.min.z && point.z <= this.max.z;
  5499. }
  5500. /**
  5501. * Returns `true` if this bounding box includes the entirety of the given bounding box.
  5502. * If this box and the given one are identical, this function also returns `true`.
  5503. *
  5504. * @param {Box3} box - The bounding box to test.
  5505. * @return {boolean} Whether the bounding box contains the given bounding box or not.
  5506. */
  5507. containsBox( box ) {
  5508. return this.min.x <= box.min.x && box.max.x <= this.max.x &&
  5509. this.min.y <= box.min.y && box.max.y <= this.max.y &&
  5510. this.min.z <= box.min.z && box.max.z <= this.max.z;
  5511. }
  5512. /**
  5513. * Returns a point as a proportion of this box's width, height and depth.
  5514. *
  5515. * @param {Vector3} point - A point in 3D space.
  5516. * @param {Vector3} target - The target vector that is used to store the method's result.
  5517. * @return {Vector3} A point as a proportion of this box's width, height and depth.
  5518. */
  5519. getParameter( point, target ) {
  5520. // This can potentially have a divide by zero if the box
  5521. // has a size dimension of 0.
  5522. return target.set(
  5523. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  5524. ( point.y - this.min.y ) / ( this.max.y - this.min.y ),
  5525. ( point.z - this.min.z ) / ( this.max.z - this.min.z )
  5526. );
  5527. }
  5528. /**
  5529. * Returns `true` if the given bounding box intersects with this bounding box.
  5530. *
  5531. * @param {Box3} box - The bounding box to test.
  5532. * @return {boolean} Whether the given bounding box intersects with this bounding box.
  5533. */
  5534. intersectsBox( box ) {
  5535. // using 6 splitting planes to rule out intersections.
  5536. return box.max.x >= this.min.x && box.min.x <= this.max.x &&
  5537. box.max.y >= this.min.y && box.min.y <= this.max.y &&
  5538. box.max.z >= this.min.z && box.min.z <= this.max.z;
  5539. }
  5540. /**
  5541. * Returns `true` if the given bounding sphere intersects with this bounding box.
  5542. *
  5543. * @param {Sphere} sphere - The bounding sphere to test.
  5544. * @return {boolean} Whether the given bounding sphere intersects with this bounding box.
  5545. */
  5546. intersectsSphere( sphere ) {
  5547. // Find the point on the AABB closest to the sphere center.
  5548. this.clampPoint( sphere.center, _vector$b );
  5549. // If that point is inside the sphere, the AABB and sphere intersect.
  5550. return _vector$b.distanceToSquared( sphere.center ) <= ( sphere.radius * sphere.radius );
  5551. }
  5552. /**
  5553. * Returns `true` if the given plane intersects with this bounding box.
  5554. *
  5555. * @param {Plane} plane - The plane to test.
  5556. * @return {boolean} Whether the given plane intersects with this bounding box.
  5557. */
  5558. intersectsPlane( plane ) {
  5559. // We compute the minimum and maximum dot product values. If those values
  5560. // are on the same side (back or front) of the plane, then there is no intersection.
  5561. let min, max;
  5562. if ( plane.normal.x > 0 ) {
  5563. min = plane.normal.x * this.min.x;
  5564. max = plane.normal.x * this.max.x;
  5565. } else {
  5566. min = plane.normal.x * this.max.x;
  5567. max = plane.normal.x * this.min.x;
  5568. }
  5569. if ( plane.normal.y > 0 ) {
  5570. min += plane.normal.y * this.min.y;
  5571. max += plane.normal.y * this.max.y;
  5572. } else {
  5573. min += plane.normal.y * this.max.y;
  5574. max += plane.normal.y * this.min.y;
  5575. }
  5576. if ( plane.normal.z > 0 ) {
  5577. min += plane.normal.z * this.min.z;
  5578. max += plane.normal.z * this.max.z;
  5579. } else {
  5580. min += plane.normal.z * this.max.z;
  5581. max += plane.normal.z * this.min.z;
  5582. }
  5583. return ( min <= - plane.constant && max >= - plane.constant );
  5584. }
  5585. /**
  5586. * Returns `true` if the given triangle intersects with this bounding box.
  5587. *
  5588. * @param {Triangle} triangle - The triangle to test.
  5589. * @return {boolean} Whether the given triangle intersects with this bounding box.
  5590. */
  5591. intersectsTriangle( triangle ) {
  5592. if ( this.isEmpty() ) {
  5593. return false;
  5594. }
  5595. // compute box center and extents
  5596. this.getCenter( _center );
  5597. _extents.subVectors( this.max, _center );
  5598. // translate triangle to aabb origin
  5599. _v0$2.subVectors( triangle.a, _center );
  5600. _v1$7.subVectors( triangle.b, _center );
  5601. _v2$4.subVectors( triangle.c, _center );
  5602. // compute edge vectors for triangle
  5603. _f0.subVectors( _v1$7, _v0$2 );
  5604. _f1.subVectors( _v2$4, _v1$7 );
  5605. _f2.subVectors( _v0$2, _v2$4 );
  5606. // test against axes that are given by cross product combinations of the edges of the triangle and the edges of the aabb
  5607. // 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
  5608. // axis_ij = u_i x f_j (u0, u1, u2 = face normals of aabb = x,y,z axes vectors since aabb is axis aligned)
  5609. let axes = [
  5610. 0, - _f0.z, _f0.y, 0, - _f1.z, _f1.y, 0, - _f2.z, _f2.y,
  5611. _f0.z, 0, - _f0.x, _f1.z, 0, - _f1.x, _f2.z, 0, - _f2.x,
  5612. - _f0.y, _f0.x, 0, - _f1.y, _f1.x, 0, - _f2.y, _f2.x, 0
  5613. ];
  5614. if ( ! satForAxes( axes, _v0$2, _v1$7, _v2$4, _extents ) ) {
  5615. return false;
  5616. }
  5617. // test 3 face normals from the aabb
  5618. axes = [ 1, 0, 0, 0, 1, 0, 0, 0, 1 ];
  5619. if ( ! satForAxes( axes, _v0$2, _v1$7, _v2$4, _extents ) ) {
  5620. return false;
  5621. }
  5622. // finally testing the face normal of the triangle
  5623. // use already existing triangle edge vectors here
  5624. _triangleNormal.crossVectors( _f0, _f1 );
  5625. axes = [ _triangleNormal.x, _triangleNormal.y, _triangleNormal.z ];
  5626. return satForAxes( axes, _v0$2, _v1$7, _v2$4, _extents );
  5627. }
  5628. /**
  5629. * Clamps the given point within the bounds of this box.
  5630. *
  5631. * @param {Vector3} point - The point to clamp.
  5632. * @param {Vector3} target - The target vector that is used to store the method's result.
  5633. * @return {Vector3} The clamped point.
  5634. */
  5635. clampPoint( point, target ) {
  5636. return target.copy( point ).clamp( this.min, this.max );
  5637. }
  5638. /**
  5639. * Returns the euclidean distance from any edge of this box to the specified point. If
  5640. * the given point lies inside of this box, the distance will be `0`.
  5641. *
  5642. * @param {Vector3} point - The point to compute the distance to.
  5643. * @return {number} The euclidean distance.
  5644. */
  5645. distanceToPoint( point ) {
  5646. return this.clampPoint( point, _vector$b ).distanceTo( point );
  5647. }
  5648. /**
  5649. * Returns a bounding sphere that encloses this bounding box.
  5650. *
  5651. * @param {Sphere} target - The target sphere that is used to store the method's result.
  5652. * @return {Sphere} The bounding sphere that encloses this bounding box.
  5653. */
  5654. getBoundingSphere( target ) {
  5655. if ( this.isEmpty() ) {
  5656. target.makeEmpty();
  5657. } else {
  5658. this.getCenter( target.center );
  5659. target.radius = this.getSize( _vector$b ).length() * 0.5;
  5660. }
  5661. return target;
  5662. }
  5663. /**
  5664. * Computes the intersection of this bounding box and the given one, setting the upper
  5665. * bound of this box to the lesser of the two boxes' upper bounds and the
  5666. * lower bound of this box to the greater of the two boxes' lower bounds. If
  5667. * there's no overlap, makes this box empty.
  5668. *
  5669. * @param {Box3} box - The bounding box to intersect with.
  5670. * @return {Box3} A reference to this bounding box.
  5671. */
  5672. intersect( box ) {
  5673. this.min.max( box.min );
  5674. this.max.min( box.max );
  5675. // 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.
  5676. if ( this.isEmpty() ) this.makeEmpty();
  5677. return this;
  5678. }
  5679. /**
  5680. * Computes the union of this box and another and the given one, setting the upper
  5681. * bound of this box to the greater of the two boxes' upper bounds and the
  5682. * lower bound of this box to the lesser of the two boxes' lower bounds.
  5683. *
  5684. * @param {Box3} box - The bounding box that will be unioned with this instance.
  5685. * @return {Box3} A reference to this bounding box.
  5686. */
  5687. union( box ) {
  5688. this.min.min( box.min );
  5689. this.max.max( box.max );
  5690. return this;
  5691. }
  5692. /**
  5693. * Transforms this bounding box by the given 4x4 transformation matrix.
  5694. *
  5695. * @param {Matrix4} matrix - The transformation matrix.
  5696. * @return {Box3} A reference to this bounding box.
  5697. */
  5698. applyMatrix4( matrix ) {
  5699. // transform of empty box is an empty box.
  5700. if ( this.isEmpty() ) return this;
  5701. // NOTE: I am using a binary pattern to specify all 2^3 combinations below
  5702. _points[ 0 ].set( this.min.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 000
  5703. _points[ 1 ].set( this.min.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 001
  5704. _points[ 2 ].set( this.min.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 010
  5705. _points[ 3 ].set( this.min.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 011
  5706. _points[ 4 ].set( this.max.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 100
  5707. _points[ 5 ].set( this.max.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 101
  5708. _points[ 6 ].set( this.max.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 110
  5709. _points[ 7 ].set( this.max.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 111
  5710. this.setFromPoints( _points );
  5711. return this;
  5712. }
  5713. /**
  5714. * Adds the given offset to both the upper and lower bounds of this bounding box,
  5715. * effectively moving it in 3D space.
  5716. *
  5717. * @param {Vector3} offset - The offset that should be used to translate the bounding box.
  5718. * @return {Box3} A reference to this bounding box.
  5719. */
  5720. translate( offset ) {
  5721. this.min.add( offset );
  5722. this.max.add( offset );
  5723. return this;
  5724. }
  5725. /**
  5726. * Returns `true` if this bounding box is equal with the given one.
  5727. *
  5728. * @param {Box3} box - The box to test for equality.
  5729. * @return {boolean} Whether this bounding box is equal with the given one.
  5730. */
  5731. equals( box ) {
  5732. return box.min.equals( this.min ) && box.max.equals( this.max );
  5733. }
  5734. }
  5735. const _points = [
  5736. /*@__PURE__*/ new Vector3(),
  5737. /*@__PURE__*/ new Vector3(),
  5738. /*@__PURE__*/ new Vector3(),
  5739. /*@__PURE__*/ new Vector3(),
  5740. /*@__PURE__*/ new Vector3(),
  5741. /*@__PURE__*/ new Vector3(),
  5742. /*@__PURE__*/ new Vector3(),
  5743. /*@__PURE__*/ new Vector3()
  5744. ];
  5745. const _vector$b = /*@__PURE__*/ new Vector3();
  5746. const _box$4 = /*@__PURE__*/ new Box3();
  5747. // triangle centered vertices
  5748. const _v0$2 = /*@__PURE__*/ new Vector3();
  5749. const _v1$7 = /*@__PURE__*/ new Vector3();
  5750. const _v2$4 = /*@__PURE__*/ new Vector3();
  5751. // triangle edge vectors
  5752. const _f0 = /*@__PURE__*/ new Vector3();
  5753. const _f1 = /*@__PURE__*/ new Vector3();
  5754. const _f2 = /*@__PURE__*/ new Vector3();
  5755. const _center = /*@__PURE__*/ new Vector3();
  5756. const _extents = /*@__PURE__*/ new Vector3();
  5757. const _triangleNormal = /*@__PURE__*/ new Vector3();
  5758. const _testAxis = /*@__PURE__*/ new Vector3();
  5759. function satForAxes( axes, v0, v1, v2, extents ) {
  5760. for ( let i = 0, j = axes.length - 3; i <= j; i += 3 ) {
  5761. _testAxis.fromArray( axes, i );
  5762. // project the aabb onto the separating axis
  5763. const r = extents.x * Math.abs( _testAxis.x ) + extents.y * Math.abs( _testAxis.y ) + extents.z * Math.abs( _testAxis.z );
  5764. // project all 3 vertices of the triangle onto the separating axis
  5765. const p0 = v0.dot( _testAxis );
  5766. const p1 = v1.dot( _testAxis );
  5767. const p2 = v2.dot( _testAxis );
  5768. // actual test, basically see if either of the most extreme of the triangle points intersects r
  5769. if ( Math.max( - Math.max( p0, p1, p2 ), Math.min( p0, p1, p2 ) ) > r ) {
  5770. // points of the projected triangle are outside the projected half-length of the aabb
  5771. // the axis is separating and we can exit
  5772. return false;
  5773. }
  5774. }
  5775. return true;
  5776. }
  5777. const _box$3 = /*@__PURE__*/ new Box3();
  5778. const _v1$6 = /*@__PURE__*/ new Vector3();
  5779. const _v2$3 = /*@__PURE__*/ new Vector3();
  5780. /**
  5781. * An analytical 3D sphere defined by a center and radius. This class is mainly
  5782. * used as a Bounding Sphere for 3D objects.
  5783. */
  5784. class Sphere {
  5785. /**
  5786. * Constructs a new sphere.
  5787. *
  5788. * @param {Vector3} [center=(0,0,0)] - The center of the sphere
  5789. * @param {number} [radius=-1] - The radius of the sphere.
  5790. */
  5791. constructor( center = new Vector3(), radius = -1 ) {
  5792. /**
  5793. * This flag can be used for type testing.
  5794. *
  5795. * @type {boolean}
  5796. * @readonly
  5797. * @default true
  5798. */
  5799. this.isSphere = true;
  5800. /**
  5801. * The center of the sphere
  5802. *
  5803. * @type {Vector3}
  5804. */
  5805. this.center = center;
  5806. /**
  5807. * The radius of the sphere.
  5808. *
  5809. * @type {number}
  5810. */
  5811. this.radius = radius;
  5812. }
  5813. /**
  5814. * Sets the sphere's components by copying the given values.
  5815. *
  5816. * @param {Vector3} center - The center.
  5817. * @param {number} radius - The radius.
  5818. * @return {Sphere} A reference to this sphere.
  5819. */
  5820. set( center, radius ) {
  5821. this.center.copy( center );
  5822. this.radius = radius;
  5823. return this;
  5824. }
  5825. /**
  5826. * Computes the minimum bounding sphere for list of points.
  5827. * If the optional center point is given, it is used as the sphere's
  5828. * center. Otherwise, the center of the axis-aligned bounding box
  5829. * encompassing the points is calculated.
  5830. *
  5831. * @param {Array<Vector3>} points - A list of points in 3D space.
  5832. * @param {Vector3} [optionalCenter] - The center of the sphere.
  5833. * @return {Sphere} A reference to this sphere.
  5834. */
  5835. setFromPoints( points, optionalCenter ) {
  5836. const center = this.center;
  5837. if ( optionalCenter !== undefined ) {
  5838. center.copy( optionalCenter );
  5839. } else {
  5840. _box$3.setFromPoints( points ).getCenter( center );
  5841. }
  5842. let maxRadiusSq = 0;
  5843. for ( let i = 0, il = points.length; i < il; i ++ ) {
  5844. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( points[ i ] ) );
  5845. }
  5846. this.radius = Math.sqrt( maxRadiusSq );
  5847. return this;
  5848. }
  5849. /**
  5850. * Copies the values of the given sphere to this instance.
  5851. *
  5852. * @param {Sphere} sphere - The sphere to copy.
  5853. * @return {Sphere} A reference to this sphere.
  5854. */
  5855. copy( sphere ) {
  5856. this.center.copy( sphere.center );
  5857. this.radius = sphere.radius;
  5858. return this;
  5859. }
  5860. /**
  5861. * Returns `true` if the sphere is empty (the radius set to a negative number).
  5862. *
  5863. * Spheres with a radius of `0` contain only their center point and are not
  5864. * considered to be empty.
  5865. *
  5866. * @return {boolean} Whether this sphere is empty or not.
  5867. */
  5868. isEmpty() {
  5869. return ( this.radius < 0 );
  5870. }
  5871. /**
  5872. * Makes this sphere empty which means in encloses a zero space in 3D.
  5873. *
  5874. * @return {Sphere} A reference to this sphere.
  5875. */
  5876. makeEmpty() {
  5877. this.center.set( 0, 0, 0 );
  5878. this.radius = -1;
  5879. return this;
  5880. }
  5881. /**
  5882. * Returns `true` if this sphere contains the given point inclusive of
  5883. * the surface of the sphere.
  5884. *
  5885. * @param {Vector3} point - The point to check.
  5886. * @return {boolean} Whether this sphere contains the given point or not.
  5887. */
  5888. containsPoint( point ) {
  5889. return ( point.distanceToSquared( this.center ) <= ( this.radius * this.radius ) );
  5890. }
  5891. /**
  5892. * Returns the closest distance from the boundary of the sphere to the
  5893. * given point. If the sphere contains the point, the distance will
  5894. * be negative.
  5895. *
  5896. * @param {Vector3} point - The point to compute the distance to.
  5897. * @return {number} The distance to the point.
  5898. */
  5899. distanceToPoint( point ) {
  5900. return ( point.distanceTo( this.center ) - this.radius );
  5901. }
  5902. /**
  5903. * Returns `true` if this sphere intersects with the given one.
  5904. *
  5905. * @param {Sphere} sphere - The sphere to test.
  5906. * @return {boolean} Whether this sphere intersects with the given one or not.
  5907. */
  5908. intersectsSphere( sphere ) {
  5909. const radiusSum = this.radius + sphere.radius;
  5910. return sphere.center.distanceToSquared( this.center ) <= ( radiusSum * radiusSum );
  5911. }
  5912. /**
  5913. * Returns `true` if this sphere intersects with the given box.
  5914. *
  5915. * @param {Box3} box - The box to test.
  5916. * @return {boolean} Whether this sphere intersects with the given box or not.
  5917. */
  5918. intersectsBox( box ) {
  5919. return box.intersectsSphere( this );
  5920. }
  5921. /**
  5922. * Returns `true` if this sphere intersects with the given plane.
  5923. *
  5924. * @param {Plane} plane - The plane to test.
  5925. * @return {boolean} Whether this sphere intersects with the given plane or not.
  5926. */
  5927. intersectsPlane( plane ) {
  5928. return Math.abs( plane.distanceToPoint( this.center ) ) <= this.radius;
  5929. }
  5930. /**
  5931. * Clamps a point within the sphere. If the point is outside the sphere, it
  5932. * will clamp it to the closest point on the edge of the sphere. Points
  5933. * already inside the sphere will not be affected.
  5934. *
  5935. * @param {Vector3} point - The plane to clamp.
  5936. * @param {Vector3} target - The target vector that is used to store the method's result.
  5937. * @return {Vector3} The clamped point.
  5938. */
  5939. clampPoint( point, target ) {
  5940. const deltaLengthSq = this.center.distanceToSquared( point );
  5941. target.copy( point );
  5942. if ( deltaLengthSq > ( this.radius * this.radius ) ) {
  5943. target.sub( this.center ).normalize();
  5944. target.multiplyScalar( this.radius ).add( this.center );
  5945. }
  5946. return target;
  5947. }
  5948. /**
  5949. * Returns a bounding box that encloses this sphere.
  5950. *
  5951. * @param {Box3} target - The target box that is used to store the method's result.
  5952. * @return {Box3} The bounding box that encloses this sphere.
  5953. */
  5954. getBoundingBox( target ) {
  5955. if ( this.isEmpty() ) {
  5956. // Empty sphere produces empty bounding box
  5957. target.makeEmpty();
  5958. return target;
  5959. }
  5960. target.set( this.center, this.center );
  5961. target.expandByScalar( this.radius );
  5962. return target;
  5963. }
  5964. /**
  5965. * Transforms this sphere with the given 4x4 transformation matrix.
  5966. *
  5967. * @param {Matrix4} matrix - The transformation matrix.
  5968. * @return {Sphere} A reference to this sphere.
  5969. */
  5970. applyMatrix4( matrix ) {
  5971. this.center.applyMatrix4( matrix );
  5972. this.radius = this.radius * matrix.getMaxScaleOnAxis();
  5973. return this;
  5974. }
  5975. /**
  5976. * Translates the sphere's center by the given offset.
  5977. *
  5978. * @param {Vector3} offset - The offset.
  5979. * @return {Sphere} A reference to this sphere.
  5980. */
  5981. translate( offset ) {
  5982. this.center.add( offset );
  5983. return this;
  5984. }
  5985. /**
  5986. * Expands the boundaries of this sphere to include the given point.
  5987. *
  5988. * @param {Vector3} point - The point to include.
  5989. * @return {Sphere} A reference to this sphere.
  5990. */
  5991. expandByPoint( point ) {
  5992. if ( this.isEmpty() ) {
  5993. this.center.copy( point );
  5994. this.radius = 0;
  5995. return this;
  5996. }
  5997. _v1$6.subVectors( point, this.center );
  5998. const lengthSq = _v1$6.lengthSq();
  5999. if ( lengthSq > ( this.radius * this.radius ) ) {
  6000. // calculate the minimal sphere
  6001. const length = Math.sqrt( lengthSq );
  6002. const delta = ( length - this.radius ) * 0.5;
  6003. this.center.addScaledVector( _v1$6, delta / length );
  6004. this.radius += delta;
  6005. }
  6006. return this;
  6007. }
  6008. /**
  6009. * Expands this sphere to enclose both the original sphere and the given sphere.
  6010. *
  6011. * @param {Sphere} sphere - The sphere to include.
  6012. * @return {Sphere} A reference to this sphere.
  6013. */
  6014. union( sphere ) {
  6015. if ( sphere.isEmpty() ) {
  6016. return this;
  6017. }
  6018. if ( this.isEmpty() ) {
  6019. this.copy( sphere );
  6020. return this;
  6021. }
  6022. if ( this.center.equals( sphere.center ) === true ) {
  6023. this.radius = Math.max( this.radius, sphere.radius );
  6024. } else {
  6025. _v2$3.subVectors( sphere.center, this.center ).setLength( sphere.radius );
  6026. this.expandByPoint( _v1$6.copy( sphere.center ).add( _v2$3 ) );
  6027. this.expandByPoint( _v1$6.copy( sphere.center ).sub( _v2$3 ) );
  6028. }
  6029. return this;
  6030. }
  6031. /**
  6032. * Returns `true` if this sphere is equal with the given one.
  6033. *
  6034. * @param {Sphere} sphere - The sphere to test for equality.
  6035. * @return {boolean} Whether this bounding sphere is equal with the given one.
  6036. */
  6037. equals( sphere ) {
  6038. return sphere.center.equals( this.center ) && ( sphere.radius === this.radius );
  6039. }
  6040. /**
  6041. * Returns a new sphere with copied values from this instance.
  6042. *
  6043. * @return {Sphere} A clone of this instance.
  6044. */
  6045. clone() {
  6046. return new this.constructor().copy( this );
  6047. }
  6048. }
  6049. const _vector$a = /*@__PURE__*/ new Vector3();
  6050. const _segCenter = /*@__PURE__*/ new Vector3();
  6051. const _segDir = /*@__PURE__*/ new Vector3();
  6052. const _diff = /*@__PURE__*/ new Vector3();
  6053. const _edge1 = /*@__PURE__*/ new Vector3();
  6054. const _edge2 = /*@__PURE__*/ new Vector3();
  6055. const _normal$1 = /*@__PURE__*/ new Vector3();
  6056. /**
  6057. * A ray that emits from an origin in a certain direction. The class is used by
  6058. * {@link Raycaster} to assist with raycasting. Raycasting is used for
  6059. * mouse picking (working out what objects in the 3D space the mouse is over)
  6060. * amongst other things.
  6061. */
  6062. class Ray {
  6063. /**
  6064. * Constructs a new ray.
  6065. *
  6066. * @param {Vector3} [origin=(0,0,0)] - The origin of the ray.
  6067. * @param {Vector3} [direction=(0,0,-1)] - The (normalized) direction of the ray.
  6068. */
  6069. constructor( origin = new Vector3(), direction = new Vector3( 0, 0, -1 ) ) {
  6070. /**
  6071. * The origin of the ray.
  6072. *
  6073. * @type {Vector3}
  6074. */
  6075. this.origin = origin;
  6076. /**
  6077. * The (normalized) direction of the ray.
  6078. *
  6079. * @type {Vector3}
  6080. */
  6081. this.direction = direction;
  6082. }
  6083. /**
  6084. * Sets the ray's components by copying the given values.
  6085. *
  6086. * @param {Vector3} origin - The origin.
  6087. * @param {Vector3} direction - The direction.
  6088. * @return {Ray} A reference to this ray.
  6089. */
  6090. set( origin, direction ) {
  6091. this.origin.copy( origin );
  6092. this.direction.copy( direction );
  6093. return this;
  6094. }
  6095. /**
  6096. * Copies the values of the given ray to this instance.
  6097. *
  6098. * @param {Ray} ray - The ray to copy.
  6099. * @return {Ray} A reference to this ray.
  6100. */
  6101. copy( ray ) {
  6102. this.origin.copy( ray.origin );
  6103. this.direction.copy( ray.direction );
  6104. return this;
  6105. }
  6106. /**
  6107. * Returns a vector that is located at a given distance along this ray.
  6108. *
  6109. * @param {number} t - The distance along the ray to retrieve a position for.
  6110. * @param {Vector3} target - The target vector that is used to store the method's result.
  6111. * @return {Vector3} A position on the ray.
  6112. */
  6113. at( t, target ) {
  6114. return target.copy( this.origin ).addScaledVector( this.direction, t );
  6115. }
  6116. /**
  6117. * Adjusts the direction of the ray to point at the given vector in world space.
  6118. *
  6119. * @param {Vector3} v - The target position.
  6120. * @return {Ray} A reference to this ray.
  6121. */
  6122. lookAt( v ) {
  6123. this.direction.copy( v ).sub( this.origin ).normalize();
  6124. return this;
  6125. }
  6126. /**
  6127. * Shift the origin of this ray along its direction by the given distance.
  6128. *
  6129. * @param {number} t - The distance along the ray to interpolate.
  6130. * @return {Ray} A reference to this ray.
  6131. */
  6132. recast( t ) {
  6133. this.origin.copy( this.at( t, _vector$a ) );
  6134. return this;
  6135. }
  6136. /**
  6137. * Returns the point along this ray that is closest to the given point.
  6138. *
  6139. * @param {Vector3} point - A point in 3D space to get the closet location on the ray for.
  6140. * @param {Vector3} target - The target vector that is used to store the method's result.
  6141. * @return {Vector3} The closest point on this ray.
  6142. */
  6143. closestPointToPoint( point, target ) {
  6144. target.subVectors( point, this.origin );
  6145. const directionDistance = target.dot( this.direction );
  6146. if ( directionDistance < 0 ) {
  6147. return target.copy( this.origin );
  6148. }
  6149. return target.copy( this.origin ).addScaledVector( this.direction, directionDistance );
  6150. }
  6151. /**
  6152. * Returns the distance of the closest approach between this ray and the given point.
  6153. *
  6154. * @param {Vector3} point - A point in 3D space to compute the distance to.
  6155. * @return {number} The distance.
  6156. */
  6157. distanceToPoint( point ) {
  6158. return Math.sqrt( this.distanceSqToPoint( point ) );
  6159. }
  6160. /**
  6161. * Returns the squared distance of the closest approach between this ray and the given point.
  6162. *
  6163. * @param {Vector3} point - A point in 3D space to compute the distance to.
  6164. * @return {number} The squared distance.
  6165. */
  6166. distanceSqToPoint( point ) {
  6167. const directionDistance = _vector$a.subVectors( point, this.origin ).dot( this.direction );
  6168. // point behind the ray
  6169. if ( directionDistance < 0 ) {
  6170. return this.origin.distanceToSquared( point );
  6171. }
  6172. _vector$a.copy( this.origin ).addScaledVector( this.direction, directionDistance );
  6173. return _vector$a.distanceToSquared( point );
  6174. }
  6175. /**
  6176. * Returns the squared distance between this ray and the given line segment.
  6177. *
  6178. * @param {Vector3} v0 - The start point of the line segment.
  6179. * @param {Vector3} v1 - The end point of the line segment.
  6180. * @param {Vector3} [optionalPointOnRay] - When provided, it receives the point on this ray that is closest to the segment.
  6181. * @param {Vector3} [optionalPointOnSegment] - When provided, it receives the point on the line segment that is closest to this ray.
  6182. * @return {number} The squared distance.
  6183. */
  6184. distanceSqToSegment( v0, v1, optionalPointOnRay, optionalPointOnSegment ) {
  6185. // from https://github.com/pmjoniak/GeometricTools/blob/master/GTEngine/Include/Mathematics/GteDistRaySegment.h
  6186. // It returns the min distance between the ray and the segment
  6187. // defined by v0 and v1
  6188. // It can also set two optional targets :
  6189. // - The closest point on the ray
  6190. // - The closest point on the segment
  6191. _segCenter.copy( v0 ).add( v1 ).multiplyScalar( 0.5 );
  6192. _segDir.copy( v1 ).sub( v0 ).normalize();
  6193. _diff.copy( this.origin ).sub( _segCenter );
  6194. const segExtent = v0.distanceTo( v1 ) * 0.5;
  6195. const a01 = - this.direction.dot( _segDir );
  6196. const b0 = _diff.dot( this.direction );
  6197. const b1 = - _diff.dot( _segDir );
  6198. const c = _diff.lengthSq();
  6199. const det = Math.abs( 1 - a01 * a01 );
  6200. let s0, s1, sqrDist, extDet;
  6201. if ( det > 0 ) {
  6202. // The ray and segment are not parallel.
  6203. s0 = a01 * b1 - b0;
  6204. s1 = a01 * b0 - b1;
  6205. extDet = segExtent * det;
  6206. if ( s0 >= 0 ) {
  6207. if ( s1 >= - extDet ) {
  6208. if ( s1 <= extDet ) {
  6209. // region 0
  6210. // Minimum at interior points of ray and segment.
  6211. const invDet = 1 / det;
  6212. s0 *= invDet;
  6213. s1 *= invDet;
  6214. sqrDist = s0 * ( s0 + a01 * s1 + 2 * b0 ) + s1 * ( a01 * s0 + s1 + 2 * b1 ) + c;
  6215. } else {
  6216. // region 1
  6217. s1 = segExtent;
  6218. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  6219. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  6220. }
  6221. } else {
  6222. // region 5
  6223. s1 = - segExtent;
  6224. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  6225. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  6226. }
  6227. } else {
  6228. if ( s1 <= - extDet ) {
  6229. // region 4
  6230. s0 = Math.max( 0, - ( - a01 * segExtent + b0 ) );
  6231. s1 = ( s0 > 0 ) ? - segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  6232. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  6233. } else if ( s1 <= extDet ) {
  6234. // region 3
  6235. s0 = 0;
  6236. s1 = Math.min( Math.max( - segExtent, - b1 ), segExtent );
  6237. sqrDist = s1 * ( s1 + 2 * b1 ) + c;
  6238. } else {
  6239. // region 2
  6240. s0 = Math.max( 0, - ( a01 * segExtent + b0 ) );
  6241. s1 = ( s0 > 0 ) ? segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  6242. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  6243. }
  6244. }
  6245. } else {
  6246. // Ray and segment are parallel.
  6247. s1 = ( a01 > 0 ) ? - segExtent : segExtent;
  6248. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  6249. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  6250. }
  6251. if ( optionalPointOnRay ) {
  6252. optionalPointOnRay.copy( this.origin ).addScaledVector( this.direction, s0 );
  6253. }
  6254. if ( optionalPointOnSegment ) {
  6255. optionalPointOnSegment.copy( _segCenter ).addScaledVector( _segDir, s1 );
  6256. }
  6257. return sqrDist;
  6258. }
  6259. /**
  6260. * Intersects this ray with the given sphere, returning the intersection
  6261. * point or `null` if there is no intersection.
  6262. *
  6263. * @param {Sphere} sphere - The sphere to intersect.
  6264. * @param {Vector3} target - The target vector that is used to store the method's result.
  6265. * @return {?Vector3} The intersection point.
  6266. */
  6267. intersectSphere( sphere, target ) {
  6268. _vector$a.subVectors( sphere.center, this.origin );
  6269. const tca = _vector$a.dot( this.direction );
  6270. const d2 = _vector$a.dot( _vector$a ) - tca * tca;
  6271. const radius2 = sphere.radius * sphere.radius;
  6272. if ( d2 > radius2 ) return null;
  6273. const thc = Math.sqrt( radius2 - d2 );
  6274. // t0 = first intersect point - entrance on front of sphere
  6275. const t0 = tca - thc;
  6276. // t1 = second intersect point - exit point on back of sphere
  6277. const t1 = tca + thc;
  6278. // test to see if t1 is behind the ray - if so, return null
  6279. if ( t1 < 0 ) return null;
  6280. // test to see if t0 is behind the ray:
  6281. // if it is, the ray is inside the sphere, so return the second exit point scaled by t1,
  6282. // in order to always return an intersect point that is in front of the ray.
  6283. if ( t0 < 0 ) return this.at( t1, target );
  6284. // else t0 is in front of the ray, so return the first collision point scaled by t0
  6285. return this.at( t0, target );
  6286. }
  6287. /**
  6288. * Returns `true` if this ray intersects with the given sphere.
  6289. *
  6290. * @param {Sphere} sphere - The sphere to intersect.
  6291. * @return {boolean} Whether this ray intersects with the given sphere or not.
  6292. */
  6293. intersectsSphere( sphere ) {
  6294. return this.distanceSqToPoint( sphere.center ) <= ( sphere.radius * sphere.radius );
  6295. }
  6296. /**
  6297. * Computes the distance from the ray's origin to the given plane. Returns `null` if the ray
  6298. * does not intersect with the plane.
  6299. *
  6300. * @param {Plane} plane - The plane to compute the distance to.
  6301. * @return {?number} Whether this ray intersects with the given sphere or not.
  6302. */
  6303. distanceToPlane( plane ) {
  6304. const denominator = plane.normal.dot( this.direction );
  6305. if ( denominator === 0 ) {
  6306. // line is coplanar, return origin
  6307. if ( plane.distanceToPoint( this.origin ) === 0 ) {
  6308. return 0;
  6309. }
  6310. // Null is preferable to undefined since undefined means.... it is undefined
  6311. return null;
  6312. }
  6313. const t = - ( this.origin.dot( plane.normal ) + plane.constant ) / denominator;
  6314. // Return if the ray never intersects the plane
  6315. return t >= 0 ? t : null;
  6316. }
  6317. /**
  6318. * Intersects this ray with the given plane, returning the intersection
  6319. * point or `null` if there is no intersection.
  6320. *
  6321. * @param {Plane} plane - The plane to intersect.
  6322. * @param {Vector3} target - The target vector that is used to store the method's result.
  6323. * @return {?Vector3} The intersection point.
  6324. */
  6325. intersectPlane( plane, target ) {
  6326. const t = this.distanceToPlane( plane );
  6327. if ( t === null ) {
  6328. return null;
  6329. }
  6330. return this.at( t, target );
  6331. }
  6332. /**
  6333. * Returns `true` if this ray intersects with the given plane.
  6334. *
  6335. * @param {Plane} plane - The plane to intersect.
  6336. * @return {boolean} Whether this ray intersects with the given plane or not.
  6337. */
  6338. intersectsPlane( plane ) {
  6339. // check if the ray lies on the plane first
  6340. const distToPoint = plane.distanceToPoint( this.origin );
  6341. if ( distToPoint === 0 ) {
  6342. return true;
  6343. }
  6344. const denominator = plane.normal.dot( this.direction );
  6345. if ( denominator * distToPoint < 0 ) {
  6346. return true;
  6347. }
  6348. // ray origin is behind the plane (and is pointing behind it)
  6349. return false;
  6350. }
  6351. /**
  6352. * Intersects this ray with the given bounding box, returning the intersection
  6353. * point or `null` if there is no intersection.
  6354. *
  6355. * @param {Box3} box - The box to intersect.
  6356. * @param {Vector3} target - The target vector that is used to store the method's result.
  6357. * @return {?Vector3} The intersection point.
  6358. */
  6359. intersectBox( box, target ) {
  6360. let tmin, tmax, tymin, tymax, tzmin, tzmax;
  6361. const invdirx = 1 / this.direction.x,
  6362. invdiry = 1 / this.direction.y,
  6363. invdirz = 1 / this.direction.z;
  6364. const origin = this.origin;
  6365. if ( invdirx >= 0 ) {
  6366. tmin = ( box.min.x - origin.x ) * invdirx;
  6367. tmax = ( box.max.x - origin.x ) * invdirx;
  6368. } else {
  6369. tmin = ( box.max.x - origin.x ) * invdirx;
  6370. tmax = ( box.min.x - origin.x ) * invdirx;
  6371. }
  6372. if ( invdiry >= 0 ) {
  6373. tymin = ( box.min.y - origin.y ) * invdiry;
  6374. tymax = ( box.max.y - origin.y ) * invdiry;
  6375. } else {
  6376. tymin = ( box.max.y - origin.y ) * invdiry;
  6377. tymax = ( box.min.y - origin.y ) * invdiry;
  6378. }
  6379. if ( ( tmin > tymax ) || ( tymin > tmax ) ) return null;
  6380. if ( tymin > tmin || isNaN( tmin ) ) tmin = tymin;
  6381. if ( tymax < tmax || isNaN( tmax ) ) tmax = tymax;
  6382. if ( invdirz >= 0 ) {
  6383. tzmin = ( box.min.z - origin.z ) * invdirz;
  6384. tzmax = ( box.max.z - origin.z ) * invdirz;
  6385. } else {
  6386. tzmin = ( box.max.z - origin.z ) * invdirz;
  6387. tzmax = ( box.min.z - origin.z ) * invdirz;
  6388. }
  6389. if ( ( tmin > tzmax ) || ( tzmin > tmax ) ) return null;
  6390. if ( tzmin > tmin || tmin !== tmin ) tmin = tzmin;
  6391. if ( tzmax < tmax || tmax !== tmax ) tmax = tzmax;
  6392. //return point closest to the ray (positive side)
  6393. if ( tmax < 0 ) return null;
  6394. return this.at( tmin >= 0 ? tmin : tmax, target );
  6395. }
  6396. /**
  6397. * Returns `true` if this ray intersects with the given box.
  6398. *
  6399. * @param {Box3} box - The box to intersect.
  6400. * @return {boolean} Whether this ray intersects with the given box or not.
  6401. */
  6402. intersectsBox( box ) {
  6403. return this.intersectBox( box, _vector$a ) !== null;
  6404. }
  6405. /**
  6406. * Intersects this ray with the given triangle, returning the intersection
  6407. * point or `null` if there is no intersection.
  6408. *
  6409. * @param {Vector3} a - The first vertex of the triangle.
  6410. * @param {Vector3} b - The second vertex of the triangle.
  6411. * @param {Vector3} c - The third vertex of the triangle.
  6412. * @param {boolean} backfaceCulling - Whether to use backface culling or not.
  6413. * @param {Vector3} target - The target vector that is used to store the method's result.
  6414. * @return {?Vector3} The intersection point.
  6415. */
  6416. intersectTriangle( a, b, c, backfaceCulling, target ) {
  6417. // Compute the offset origin, edges, and normal.
  6418. // from https://github.com/pmjoniak/GeometricTools/blob/master/GTEngine/Include/Mathematics/GteIntrRay3Triangle3.h
  6419. _edge1.subVectors( b, a );
  6420. _edge2.subVectors( c, a );
  6421. _normal$1.crossVectors( _edge1, _edge2 );
  6422. // Solve Q + t*D = b1*E1 + b2*E2 (Q = kDiff, D = ray direction,
  6423. // E1 = kEdge1, E2 = kEdge2, N = Cross(E1,E2)) by
  6424. // |Dot(D,N)|*b1 = sign(Dot(D,N))*Dot(D,Cross(Q,E2))
  6425. // |Dot(D,N)|*b2 = sign(Dot(D,N))*Dot(D,Cross(E1,Q))
  6426. // |Dot(D,N)|*t = -sign(Dot(D,N))*Dot(Q,N)
  6427. let DdN = this.direction.dot( _normal$1 );
  6428. let sign;
  6429. if ( DdN > 0 ) {
  6430. if ( backfaceCulling ) return null;
  6431. sign = 1;
  6432. } else if ( DdN < 0 ) {
  6433. sign = -1;
  6434. DdN = - DdN;
  6435. } else {
  6436. return null;
  6437. }
  6438. _diff.subVectors( this.origin, a );
  6439. const DdQxE2 = sign * this.direction.dot( _edge2.crossVectors( _diff, _edge2 ) );
  6440. // b1 < 0, no intersection
  6441. if ( DdQxE2 < 0 ) {
  6442. return null;
  6443. }
  6444. const DdE1xQ = sign * this.direction.dot( _edge1.cross( _diff ) );
  6445. // b2 < 0, no intersection
  6446. if ( DdE1xQ < 0 ) {
  6447. return null;
  6448. }
  6449. // b1+b2 > 1, no intersection
  6450. if ( DdQxE2 + DdE1xQ > DdN ) {
  6451. return null;
  6452. }
  6453. // Line intersects triangle, check if ray does.
  6454. const QdN = - sign * _diff.dot( _normal$1 );
  6455. // t < 0, no intersection
  6456. if ( QdN < 0 ) {
  6457. return null;
  6458. }
  6459. // Ray intersects triangle.
  6460. return this.at( QdN / DdN, target );
  6461. }
  6462. /**
  6463. * Transforms this ray with the given 4x4 transformation matrix.
  6464. *
  6465. * @param {Matrix4} matrix4 - The transformation matrix.
  6466. * @return {Ray} A reference to this ray.
  6467. */
  6468. applyMatrix4( matrix4 ) {
  6469. this.origin.applyMatrix4( matrix4 );
  6470. this.direction.transformDirection( matrix4 );
  6471. return this;
  6472. }
  6473. /**
  6474. * Returns `true` if this ray is equal with the given one.
  6475. *
  6476. * @param {Ray} ray - The ray to test for equality.
  6477. * @return {boolean} Whether this ray is equal with the given one.
  6478. */
  6479. equals( ray ) {
  6480. return ray.origin.equals( this.origin ) && ray.direction.equals( this.direction );
  6481. }
  6482. /**
  6483. * Returns a new ray with copied values from this instance.
  6484. *
  6485. * @return {Ray} A clone of this instance.
  6486. */
  6487. clone() {
  6488. return new this.constructor().copy( this );
  6489. }
  6490. }
  6491. /**
  6492. * Represents a 4x4 matrix.
  6493. *
  6494. * The most common use of a 4x4 matrix in 3D computer graphics is as a transformation matrix.
  6495. * For an introduction to transformation matrices as used in WebGL, check out [this tutorial]{@link https://www.opengl-tutorial.org/beginners-tutorials/tutorial-3-matrices}
  6496. *
  6497. * This allows a 3D vector representing a point in 3D space to undergo
  6498. * transformations such as translation, rotation, shear, scale, reflection,
  6499. * orthogonal or perspective projection and so on, by being multiplied by the
  6500. * matrix. This is known as `applying` the matrix to the vector.
  6501. *
  6502. * A Note on Row-Major and Column-Major Ordering:
  6503. *
  6504. * The constructor and {@link Matrix3#set} method take arguments in
  6505. * [row-major]{@link https://en.wikipedia.org/wiki/Row-_and_column-major_order#Column-major_order}
  6506. * order, while internally they are stored in the {@link Matrix3#elements} array in column-major order.
  6507. * This means that calling:
  6508. * ```js
  6509. * const m = new THREE.Matrix4();
  6510. * m.set( 11, 12, 13, 14,
  6511. * 21, 22, 23, 24,
  6512. * 31, 32, 33, 34,
  6513. * 41, 42, 43, 44 );
  6514. * ```
  6515. * will result in the elements array containing:
  6516. * ```js
  6517. * m.elements = [ 11, 21, 31, 41,
  6518. * 12, 22, 32, 42,
  6519. * 13, 23, 33, 43,
  6520. * 14, 24, 34, 44 ];
  6521. * ```
  6522. * and internally all calculations are performed using column-major ordering.
  6523. * However, as the actual ordering makes no difference mathematically and
  6524. * most people are used to thinking about matrices in row-major order, the
  6525. * three.js documentation shows matrices in row-major order. Just bear in
  6526. * mind that if you are reading the source code, you'll have to take the
  6527. * transpose of any matrices outlined here to make sense of the calculations.
  6528. */
  6529. class Matrix4 {
  6530. /**
  6531. * Constructs a new 4x4 matrix. The arguments are supposed to be
  6532. * in row-major order. If no arguments are provided, the constructor
  6533. * initializes the matrix as an identity matrix.
  6534. *
  6535. * @param {number} [n11] - 1-1 matrix element.
  6536. * @param {number} [n12] - 1-2 matrix element.
  6537. * @param {number} [n13] - 1-3 matrix element.
  6538. * @param {number} [n14] - 1-4 matrix element.
  6539. * @param {number} [n21] - 2-1 matrix element.
  6540. * @param {number} [n22] - 2-2 matrix element.
  6541. * @param {number} [n23] - 2-3 matrix element.
  6542. * @param {number} [n24] - 2-4 matrix element.
  6543. * @param {number} [n31] - 3-1 matrix element.
  6544. * @param {number} [n32] - 3-2 matrix element.
  6545. * @param {number} [n33] - 3-3 matrix element.
  6546. * @param {number} [n34] - 3-4 matrix element.
  6547. * @param {number} [n41] - 4-1 matrix element.
  6548. * @param {number} [n42] - 4-2 matrix element.
  6549. * @param {number} [n43] - 4-3 matrix element.
  6550. * @param {number} [n44] - 4-4 matrix element.
  6551. */
  6552. constructor( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  6553. /**
  6554. * This flag can be used for type testing.
  6555. *
  6556. * @type {boolean}
  6557. * @readonly
  6558. * @default true
  6559. */
  6560. Matrix4.prototype.isMatrix4 = true;
  6561. /**
  6562. * A column-major list of matrix values.
  6563. *
  6564. * @type {Array<number>}
  6565. */
  6566. this.elements = [
  6567. 1, 0, 0, 0,
  6568. 0, 1, 0, 0,
  6569. 0, 0, 1, 0,
  6570. 0, 0, 0, 1
  6571. ];
  6572. if ( n11 !== undefined ) {
  6573. this.set( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 );
  6574. }
  6575. }
  6576. /**
  6577. * Sets the elements of the matrix.The arguments are supposed to be
  6578. * in row-major order.
  6579. *
  6580. * @param {number} [n11] - 1-1 matrix element.
  6581. * @param {number} [n12] - 1-2 matrix element.
  6582. * @param {number} [n13] - 1-3 matrix element.
  6583. * @param {number} [n14] - 1-4 matrix element.
  6584. * @param {number} [n21] - 2-1 matrix element.
  6585. * @param {number} [n22] - 2-2 matrix element.
  6586. * @param {number} [n23] - 2-3 matrix element.
  6587. * @param {number} [n24] - 2-4 matrix element.
  6588. * @param {number} [n31] - 3-1 matrix element.
  6589. * @param {number} [n32] - 3-2 matrix element.
  6590. * @param {number} [n33] - 3-3 matrix element.
  6591. * @param {number} [n34] - 3-4 matrix element.
  6592. * @param {number} [n41] - 4-1 matrix element.
  6593. * @param {number} [n42] - 4-2 matrix element.
  6594. * @param {number} [n43] - 4-3 matrix element.
  6595. * @param {number} [n44] - 4-4 matrix element.
  6596. * @return {Matrix4} A reference to this matrix.
  6597. */
  6598. set( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  6599. const te = this.elements;
  6600. te[ 0 ] = n11; te[ 4 ] = n12; te[ 8 ] = n13; te[ 12 ] = n14;
  6601. te[ 1 ] = n21; te[ 5 ] = n22; te[ 9 ] = n23; te[ 13 ] = n24;
  6602. te[ 2 ] = n31; te[ 6 ] = n32; te[ 10 ] = n33; te[ 14 ] = n34;
  6603. te[ 3 ] = n41; te[ 7 ] = n42; te[ 11 ] = n43; te[ 15 ] = n44;
  6604. return this;
  6605. }
  6606. /**
  6607. * Sets this matrix to the 4x4 identity matrix.
  6608. *
  6609. * @return {Matrix4} A reference to this matrix.
  6610. */
  6611. identity() {
  6612. this.set(
  6613. 1, 0, 0, 0,
  6614. 0, 1, 0, 0,
  6615. 0, 0, 1, 0,
  6616. 0, 0, 0, 1
  6617. );
  6618. return this;
  6619. }
  6620. /**
  6621. * Returns a matrix with copied values from this instance.
  6622. *
  6623. * @return {Matrix4} A clone of this instance.
  6624. */
  6625. clone() {
  6626. return new Matrix4().fromArray( this.elements );
  6627. }
  6628. /**
  6629. * Copies the values of the given matrix to this instance.
  6630. *
  6631. * @param {Matrix4} m - The matrix to copy.
  6632. * @return {Matrix4} A reference to this matrix.
  6633. */
  6634. copy( m ) {
  6635. const te = this.elements;
  6636. const me = m.elements;
  6637. te[ 0 ] = me[ 0 ]; te[ 1 ] = me[ 1 ]; te[ 2 ] = me[ 2 ]; te[ 3 ] = me[ 3 ];
  6638. te[ 4 ] = me[ 4 ]; te[ 5 ] = me[ 5 ]; te[ 6 ] = me[ 6 ]; te[ 7 ] = me[ 7 ];
  6639. te[ 8 ] = me[ 8 ]; te[ 9 ] = me[ 9 ]; te[ 10 ] = me[ 10 ]; te[ 11 ] = me[ 11 ];
  6640. te[ 12 ] = me[ 12 ]; te[ 13 ] = me[ 13 ]; te[ 14 ] = me[ 14 ]; te[ 15 ] = me[ 15 ];
  6641. return this;
  6642. }
  6643. /**
  6644. * Copies the translation component of the given matrix
  6645. * into this matrix's translation component.
  6646. *
  6647. * @param {Matrix4} m - The matrix to copy the translation component.
  6648. * @return {Matrix4} A reference to this matrix.
  6649. */
  6650. copyPosition( m ) {
  6651. const te = this.elements, me = m.elements;
  6652. te[ 12 ] = me[ 12 ];
  6653. te[ 13 ] = me[ 13 ];
  6654. te[ 14 ] = me[ 14 ];
  6655. return this;
  6656. }
  6657. /**
  6658. * Set the upper 3x3 elements of this matrix to the values of given 3x3 matrix.
  6659. *
  6660. * @param {Matrix3} m - The 3x3 matrix.
  6661. * @return {Matrix4} A reference to this matrix.
  6662. */
  6663. setFromMatrix3( m ) {
  6664. const me = m.elements;
  6665. this.set(
  6666. me[ 0 ], me[ 3 ], me[ 6 ], 0,
  6667. me[ 1 ], me[ 4 ], me[ 7 ], 0,
  6668. me[ 2 ], me[ 5 ], me[ 8 ], 0,
  6669. 0, 0, 0, 1
  6670. );
  6671. return this;
  6672. }
  6673. /**
  6674. * Extracts the basis of this matrix into the three axis vectors provided.
  6675. *
  6676. * @param {Vector3} xAxis - The basis's x axis.
  6677. * @param {Vector3} yAxis - The basis's y axis.
  6678. * @param {Vector3} zAxis - The basis's z axis.
  6679. * @return {Matrix4} A reference to this matrix.
  6680. */
  6681. extractBasis( xAxis, yAxis, zAxis ) {
  6682. xAxis.setFromMatrixColumn( this, 0 );
  6683. yAxis.setFromMatrixColumn( this, 1 );
  6684. zAxis.setFromMatrixColumn( this, 2 );
  6685. return this;
  6686. }
  6687. /**
  6688. * Sets the given basis vectors to this matrix.
  6689. *
  6690. * @param {Vector3} xAxis - The basis's x axis.
  6691. * @param {Vector3} yAxis - The basis's y axis.
  6692. * @param {Vector3} zAxis - The basis's z axis.
  6693. * @return {Matrix4} A reference to this matrix.
  6694. */
  6695. makeBasis( xAxis, yAxis, zAxis ) {
  6696. this.set(
  6697. xAxis.x, yAxis.x, zAxis.x, 0,
  6698. xAxis.y, yAxis.y, zAxis.y, 0,
  6699. xAxis.z, yAxis.z, zAxis.z, 0,
  6700. 0, 0, 0, 1
  6701. );
  6702. return this;
  6703. }
  6704. /**
  6705. * Extracts the rotation component of the given matrix
  6706. * into this matrix's rotation component.
  6707. *
  6708. * Note: This method does not support reflection matrices.
  6709. *
  6710. * @param {Matrix4} m - The matrix.
  6711. * @return {Matrix4} A reference to this matrix.
  6712. */
  6713. extractRotation( m ) {
  6714. const te = this.elements;
  6715. const me = m.elements;
  6716. const scaleX = 1 / _v1$5.setFromMatrixColumn( m, 0 ).length();
  6717. const scaleY = 1 / _v1$5.setFromMatrixColumn( m, 1 ).length();
  6718. const scaleZ = 1 / _v1$5.setFromMatrixColumn( m, 2 ).length();
  6719. te[ 0 ] = me[ 0 ] * scaleX;
  6720. te[ 1 ] = me[ 1 ] * scaleX;
  6721. te[ 2 ] = me[ 2 ] * scaleX;
  6722. te[ 3 ] = 0;
  6723. te[ 4 ] = me[ 4 ] * scaleY;
  6724. te[ 5 ] = me[ 5 ] * scaleY;
  6725. te[ 6 ] = me[ 6 ] * scaleY;
  6726. te[ 7 ] = 0;
  6727. te[ 8 ] = me[ 8 ] * scaleZ;
  6728. te[ 9 ] = me[ 9 ] * scaleZ;
  6729. te[ 10 ] = me[ 10 ] * scaleZ;
  6730. te[ 11 ] = 0;
  6731. te[ 12 ] = 0;
  6732. te[ 13 ] = 0;
  6733. te[ 14 ] = 0;
  6734. te[ 15 ] = 1;
  6735. return this;
  6736. }
  6737. /**
  6738. * Sets the rotation component (the upper left 3x3 matrix) of this matrix to
  6739. * the rotation specified by the given Euler angles. The rest of
  6740. * the matrix is set to the identity. Depending on the {@link Euler#order},
  6741. * there are six possible outcomes. See [this page]{@link https://en.wikipedia.org/wiki/Euler_angles#Rotation_matrix}
  6742. * for a complete list.
  6743. *
  6744. * @param {Euler} euler - The Euler angles.
  6745. * @return {Matrix4} A reference to this matrix.
  6746. */
  6747. makeRotationFromEuler( euler ) {
  6748. const te = this.elements;
  6749. const x = euler.x, y = euler.y, z = euler.z;
  6750. const a = Math.cos( x ), b = Math.sin( x );
  6751. const c = Math.cos( y ), d = Math.sin( y );
  6752. const e = Math.cos( z ), f = Math.sin( z );
  6753. if ( euler.order === 'XYZ' ) {
  6754. const ae = a * e, af = a * f, be = b * e, bf = b * f;
  6755. te[ 0 ] = c * e;
  6756. te[ 4 ] = - c * f;
  6757. te[ 8 ] = d;
  6758. te[ 1 ] = af + be * d;
  6759. te[ 5 ] = ae - bf * d;
  6760. te[ 9 ] = - b * c;
  6761. te[ 2 ] = bf - ae * d;
  6762. te[ 6 ] = be + af * d;
  6763. te[ 10 ] = a * c;
  6764. } else if ( euler.order === 'YXZ' ) {
  6765. const ce = c * e, cf = c * f, de = d * e, df = d * f;
  6766. te[ 0 ] = ce + df * b;
  6767. te[ 4 ] = de * b - cf;
  6768. te[ 8 ] = a * d;
  6769. te[ 1 ] = a * f;
  6770. te[ 5 ] = a * e;
  6771. te[ 9 ] = - b;
  6772. te[ 2 ] = cf * b - de;
  6773. te[ 6 ] = df + ce * b;
  6774. te[ 10 ] = a * c;
  6775. } else if ( euler.order === 'ZXY' ) {
  6776. const ce = c * e, cf = c * f, de = d * e, df = d * f;
  6777. te[ 0 ] = ce - df * b;
  6778. te[ 4 ] = - a * f;
  6779. te[ 8 ] = de + cf * b;
  6780. te[ 1 ] = cf + de * b;
  6781. te[ 5 ] = a * e;
  6782. te[ 9 ] = df - ce * b;
  6783. te[ 2 ] = - a * d;
  6784. te[ 6 ] = b;
  6785. te[ 10 ] = a * c;
  6786. } else if ( euler.order === 'ZYX' ) {
  6787. const ae = a * e, af = a * f, be = b * e, bf = b * f;
  6788. te[ 0 ] = c * e;
  6789. te[ 4 ] = be * d - af;
  6790. te[ 8 ] = ae * d + bf;
  6791. te[ 1 ] = c * f;
  6792. te[ 5 ] = bf * d + ae;
  6793. te[ 9 ] = af * d - be;
  6794. te[ 2 ] = - d;
  6795. te[ 6 ] = b * c;
  6796. te[ 10 ] = a * c;
  6797. } else if ( euler.order === 'YZX' ) {
  6798. const ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  6799. te[ 0 ] = c * e;
  6800. te[ 4 ] = bd - ac * f;
  6801. te[ 8 ] = bc * f + ad;
  6802. te[ 1 ] = f;
  6803. te[ 5 ] = a * e;
  6804. te[ 9 ] = - b * e;
  6805. te[ 2 ] = - d * e;
  6806. te[ 6 ] = ad * f + bc;
  6807. te[ 10 ] = ac - bd * f;
  6808. } else if ( euler.order === 'XZY' ) {
  6809. const ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  6810. te[ 0 ] = c * e;
  6811. te[ 4 ] = - f;
  6812. te[ 8 ] = d * e;
  6813. te[ 1 ] = ac * f + bd;
  6814. te[ 5 ] = a * e;
  6815. te[ 9 ] = ad * f - bc;
  6816. te[ 2 ] = bc * f - ad;
  6817. te[ 6 ] = b * e;
  6818. te[ 10 ] = bd * f + ac;
  6819. }
  6820. // bottom row
  6821. te[ 3 ] = 0;
  6822. te[ 7 ] = 0;
  6823. te[ 11 ] = 0;
  6824. // last column
  6825. te[ 12 ] = 0;
  6826. te[ 13 ] = 0;
  6827. te[ 14 ] = 0;
  6828. te[ 15 ] = 1;
  6829. return this;
  6830. }
  6831. /**
  6832. * Sets the rotation component of this matrix to the rotation specified by
  6833. * the given Quaternion as outlined [here]{@link https://en.wikipedia.org/wiki/Rotation_matrix#Quaternion}
  6834. * The rest of the matrix is set to the identity.
  6835. *
  6836. * @param {Quaternion} q - The Quaternion.
  6837. * @return {Matrix4} A reference to this matrix.
  6838. */
  6839. makeRotationFromQuaternion( q ) {
  6840. return this.compose( _zero, q, _one );
  6841. }
  6842. /**
  6843. * Sets the rotation component of the transformation matrix, looking from `eye` towards
  6844. * `target`, and oriented by the up-direction.
  6845. *
  6846. * @param {Vector3} eye - The eye vector.
  6847. * @param {Vector3} target - The target vector.
  6848. * @param {Vector3} up - The up vector.
  6849. * @return {Matrix4} A reference to this matrix.
  6850. */
  6851. lookAt( eye, target, up ) {
  6852. const te = this.elements;
  6853. _z.subVectors( eye, target );
  6854. if ( _z.lengthSq() === 0 ) {
  6855. // eye and target are in the same position
  6856. _z.z = 1;
  6857. }
  6858. _z.normalize();
  6859. _x.crossVectors( up, _z );
  6860. if ( _x.lengthSq() === 0 ) {
  6861. // up and z are parallel
  6862. if ( Math.abs( up.z ) === 1 ) {
  6863. _z.x += 0.0001;
  6864. } else {
  6865. _z.z += 0.0001;
  6866. }
  6867. _z.normalize();
  6868. _x.crossVectors( up, _z );
  6869. }
  6870. _x.normalize();
  6871. _y.crossVectors( _z, _x );
  6872. te[ 0 ] = _x.x; te[ 4 ] = _y.x; te[ 8 ] = _z.x;
  6873. te[ 1 ] = _x.y; te[ 5 ] = _y.y; te[ 9 ] = _z.y;
  6874. te[ 2 ] = _x.z; te[ 6 ] = _y.z; te[ 10 ] = _z.z;
  6875. return this;
  6876. }
  6877. /**
  6878. * Post-multiplies this matrix by the given 4x4 matrix.
  6879. *
  6880. * @param {Matrix4} m - The matrix to multiply with.
  6881. * @return {Matrix4} A reference to this matrix.
  6882. */
  6883. multiply( m ) {
  6884. return this.multiplyMatrices( this, m );
  6885. }
  6886. /**
  6887. * Pre-multiplies this matrix by the given 4x4 matrix.
  6888. *
  6889. * @param {Matrix4} m - The matrix to multiply with.
  6890. * @return {Matrix4} A reference to this matrix.
  6891. */
  6892. premultiply( m ) {
  6893. return this.multiplyMatrices( m, this );
  6894. }
  6895. /**
  6896. * Multiples the given 4x4 matrices and stores the result
  6897. * in this matrix.
  6898. *
  6899. * @param {Matrix4} a - The first matrix.
  6900. * @param {Matrix4} b - The second matrix.
  6901. * @return {Matrix4} A reference to this matrix.
  6902. */
  6903. multiplyMatrices( a, b ) {
  6904. const ae = a.elements;
  6905. const be = b.elements;
  6906. const te = this.elements;
  6907. const a11 = ae[ 0 ], a12 = ae[ 4 ], a13 = ae[ 8 ], a14 = ae[ 12 ];
  6908. const a21 = ae[ 1 ], a22 = ae[ 5 ], a23 = ae[ 9 ], a24 = ae[ 13 ];
  6909. const a31 = ae[ 2 ], a32 = ae[ 6 ], a33 = ae[ 10 ], a34 = ae[ 14 ];
  6910. const a41 = ae[ 3 ], a42 = ae[ 7 ], a43 = ae[ 11 ], a44 = ae[ 15 ];
  6911. const b11 = be[ 0 ], b12 = be[ 4 ], b13 = be[ 8 ], b14 = be[ 12 ];
  6912. const b21 = be[ 1 ], b22 = be[ 5 ], b23 = be[ 9 ], b24 = be[ 13 ];
  6913. const b31 = be[ 2 ], b32 = be[ 6 ], b33 = be[ 10 ], b34 = be[ 14 ];
  6914. const b41 = be[ 3 ], b42 = be[ 7 ], b43 = be[ 11 ], b44 = be[ 15 ];
  6915. te[ 0 ] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41;
  6916. te[ 4 ] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42;
  6917. te[ 8 ] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43;
  6918. te[ 12 ] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44;
  6919. te[ 1 ] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41;
  6920. te[ 5 ] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42;
  6921. te[ 9 ] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43;
  6922. te[ 13 ] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44;
  6923. te[ 2 ] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41;
  6924. te[ 6 ] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42;
  6925. te[ 10 ] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43;
  6926. te[ 14 ] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44;
  6927. te[ 3 ] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41;
  6928. te[ 7 ] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42;
  6929. te[ 11 ] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43;
  6930. te[ 15 ] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44;
  6931. return this;
  6932. }
  6933. /**
  6934. * Multiplies every component of the matrix by the given scalar.
  6935. *
  6936. * @param {number} s - The scalar.
  6937. * @return {Matrix4} A reference to this matrix.
  6938. */
  6939. multiplyScalar( s ) {
  6940. const te = this.elements;
  6941. te[ 0 ] *= s; te[ 4 ] *= s; te[ 8 ] *= s; te[ 12 ] *= s;
  6942. te[ 1 ] *= s; te[ 5 ] *= s; te[ 9 ] *= s; te[ 13 ] *= s;
  6943. te[ 2 ] *= s; te[ 6 ] *= s; te[ 10 ] *= s; te[ 14 ] *= s;
  6944. te[ 3 ] *= s; te[ 7 ] *= s; te[ 11 ] *= s; te[ 15 ] *= s;
  6945. return this;
  6946. }
  6947. /**
  6948. * Computes and returns the determinant of this matrix.
  6949. *
  6950. * Based on the method outlined [here]{@link http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.html}.
  6951. *
  6952. * @return {number} The determinant.
  6953. */
  6954. determinant() {
  6955. const te = this.elements;
  6956. const n11 = te[ 0 ], n12 = te[ 4 ], n13 = te[ 8 ], n14 = te[ 12 ];
  6957. const n21 = te[ 1 ], n22 = te[ 5 ], n23 = te[ 9 ], n24 = te[ 13 ];
  6958. const n31 = te[ 2 ], n32 = te[ 6 ], n33 = te[ 10 ], n34 = te[ 14 ];
  6959. const n41 = te[ 3 ], n42 = te[ 7 ], n43 = te[ 11 ], n44 = te[ 15 ];
  6960. //TODO: make this more efficient
  6961. return (
  6962. n41 * (
  6963. + n14 * n23 * n32
  6964. - n13 * n24 * n32
  6965. - n14 * n22 * n33
  6966. + n12 * n24 * n33
  6967. + n13 * n22 * n34
  6968. - n12 * n23 * n34
  6969. ) +
  6970. n42 * (
  6971. + n11 * n23 * n34
  6972. - n11 * n24 * n33
  6973. + n14 * n21 * n33
  6974. - n13 * n21 * n34
  6975. + n13 * n24 * n31
  6976. - n14 * n23 * n31
  6977. ) +
  6978. n43 * (
  6979. + n11 * n24 * n32
  6980. - n11 * n22 * n34
  6981. - n14 * n21 * n32
  6982. + n12 * n21 * n34
  6983. + n14 * n22 * n31
  6984. - n12 * n24 * n31
  6985. ) +
  6986. n44 * (
  6987. - n13 * n22 * n31
  6988. - n11 * n23 * n32
  6989. + n11 * n22 * n33
  6990. + n13 * n21 * n32
  6991. - n12 * n21 * n33
  6992. + n12 * n23 * n31
  6993. )
  6994. );
  6995. }
  6996. /**
  6997. * Transposes this matrix in place.
  6998. *
  6999. * @return {Matrix4} A reference to this matrix.
  7000. */
  7001. transpose() {
  7002. const te = this.elements;
  7003. let tmp;
  7004. tmp = te[ 1 ]; te[ 1 ] = te[ 4 ]; te[ 4 ] = tmp;
  7005. tmp = te[ 2 ]; te[ 2 ] = te[ 8 ]; te[ 8 ] = tmp;
  7006. tmp = te[ 6 ]; te[ 6 ] = te[ 9 ]; te[ 9 ] = tmp;
  7007. tmp = te[ 3 ]; te[ 3 ] = te[ 12 ]; te[ 12 ] = tmp;
  7008. tmp = te[ 7 ]; te[ 7 ] = te[ 13 ]; te[ 13 ] = tmp;
  7009. tmp = te[ 11 ]; te[ 11 ] = te[ 14 ]; te[ 14 ] = tmp;
  7010. return this;
  7011. }
  7012. /**
  7013. * Sets the position component for this matrix from the given vector,
  7014. * without affecting the rest of the matrix.
  7015. *
  7016. * @param {number|Vector3} x - The x component of the vector or alternativley the vector object.
  7017. * @param {number} y - The y component of the vector.
  7018. * @param {number} z - The z component of the vector.
  7019. * @return {Matrix4} A reference to this matrix.
  7020. */
  7021. setPosition( x, y, z ) {
  7022. const te = this.elements;
  7023. if ( x.isVector3 ) {
  7024. te[ 12 ] = x.x;
  7025. te[ 13 ] = x.y;
  7026. te[ 14 ] = x.z;
  7027. } else {
  7028. te[ 12 ] = x;
  7029. te[ 13 ] = y;
  7030. te[ 14 ] = z;
  7031. }
  7032. return this;
  7033. }
  7034. /**
  7035. * Inverts this matrix, using the [analytic method]{@link https://en.wikipedia.org/wiki/Invertible_matrix#Analytic_solution}.
  7036. * You can not invert with a determinant of zero. If you attempt this, the method produces
  7037. * a zero matrix instead.
  7038. *
  7039. * @return {Matrix4} A reference to this matrix.
  7040. */
  7041. invert() {
  7042. // based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm
  7043. const te = this.elements,
  7044. n11 = te[ 0 ], n21 = te[ 1 ], n31 = te[ 2 ], n41 = te[ 3 ],
  7045. n12 = te[ 4 ], n22 = te[ 5 ], n32 = te[ 6 ], n42 = te[ 7 ],
  7046. n13 = te[ 8 ], n23 = te[ 9 ], n33 = te[ 10 ], n43 = te[ 11 ],
  7047. n14 = te[ 12 ], n24 = te[ 13 ], n34 = te[ 14 ], n44 = te[ 15 ],
  7048. t11 = n23 * n34 * n42 - n24 * n33 * n42 + n24 * n32 * n43 - n22 * n34 * n43 - n23 * n32 * n44 + n22 * n33 * n44,
  7049. t12 = n14 * n33 * n42 - n13 * n34 * n42 - n14 * n32 * n43 + n12 * n34 * n43 + n13 * n32 * n44 - n12 * n33 * n44,
  7050. t13 = n13 * n24 * n42 - n14 * n23 * n42 + n14 * n22 * n43 - n12 * n24 * n43 - n13 * n22 * n44 + n12 * n23 * n44,
  7051. t14 = n14 * n23 * n32 - n13 * n24 * n32 - n14 * n22 * n33 + n12 * n24 * n33 + n13 * n22 * n34 - n12 * n23 * n34;
  7052. const det = n11 * t11 + n21 * t12 + n31 * t13 + n41 * t14;
  7053. if ( det === 0 ) return this.set( 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 );
  7054. const detInv = 1 / det;
  7055. te[ 0 ] = t11 * detInv;
  7056. te[ 1 ] = ( n24 * n33 * n41 - n23 * n34 * n41 - n24 * n31 * n43 + n21 * n34 * n43 + n23 * n31 * n44 - n21 * n33 * n44 ) * detInv;
  7057. te[ 2 ] = ( n22 * n34 * n41 - n24 * n32 * n41 + n24 * n31 * n42 - n21 * n34 * n42 - n22 * n31 * n44 + n21 * n32 * n44 ) * detInv;
  7058. te[ 3 ] = ( n23 * n32 * n41 - n22 * n33 * n41 - n23 * n31 * n42 + n21 * n33 * n42 + n22 * n31 * n43 - n21 * n32 * n43 ) * detInv;
  7059. te[ 4 ] = t12 * detInv;
  7060. te[ 5 ] = ( n13 * n34 * n41 - n14 * n33 * n41 + n14 * n31 * n43 - n11 * n34 * n43 - n13 * n31 * n44 + n11 * n33 * n44 ) * detInv;
  7061. te[ 6 ] = ( n14 * n32 * n41 - n12 * n34 * n41 - n14 * n31 * n42 + n11 * n34 * n42 + n12 * n31 * n44 - n11 * n32 * n44 ) * detInv;
  7062. te[ 7 ] = ( n12 * n33 * n41 - n13 * n32 * n41 + n13 * n31 * n42 - n11 * n33 * n42 - n12 * n31 * n43 + n11 * n32 * n43 ) * detInv;
  7063. te[ 8 ] = t13 * detInv;
  7064. te[ 9 ] = ( n14 * n23 * n41 - n13 * n24 * n41 - n14 * n21 * n43 + n11 * n24 * n43 + n13 * n21 * n44 - n11 * n23 * n44 ) * detInv;
  7065. te[ 10 ] = ( n12 * n24 * n41 - n14 * n22 * n41 + n14 * n21 * n42 - n11 * n24 * n42 - n12 * n21 * n44 + n11 * n22 * n44 ) * detInv;
  7066. te[ 11 ] = ( n13 * n22 * n41 - n12 * n23 * n41 - n13 * n21 * n42 + n11 * n23 * n42 + n12 * n21 * n43 - n11 * n22 * n43 ) * detInv;
  7067. te[ 12 ] = t14 * detInv;
  7068. te[ 13 ] = ( n13 * n24 * n31 - n14 * n23 * n31 + n14 * n21 * n33 - n11 * n24 * n33 - n13 * n21 * n34 + n11 * n23 * n34 ) * detInv;
  7069. te[ 14 ] = ( n14 * n22 * n31 - n12 * n24 * n31 - n14 * n21 * n32 + n11 * n24 * n32 + n12 * n21 * n34 - n11 * n22 * n34 ) * detInv;
  7070. te[ 15 ] = ( n12 * n23 * n31 - n13 * n22 * n31 + n13 * n21 * n32 - n11 * n23 * n32 - n12 * n21 * n33 + n11 * n22 * n33 ) * detInv;
  7071. return this;
  7072. }
  7073. /**
  7074. * Multiplies the columns of this matrix by the given vector.
  7075. *
  7076. * @param {Vector3} v - The scale vector.
  7077. * @return {Matrix4} A reference to this matrix.
  7078. */
  7079. scale( v ) {
  7080. const te = this.elements;
  7081. const x = v.x, y = v.y, z = v.z;
  7082. te[ 0 ] *= x; te[ 4 ] *= y; te[ 8 ] *= z;
  7083. te[ 1 ] *= x; te[ 5 ] *= y; te[ 9 ] *= z;
  7084. te[ 2 ] *= x; te[ 6 ] *= y; te[ 10 ] *= z;
  7085. te[ 3 ] *= x; te[ 7 ] *= y; te[ 11 ] *= z;
  7086. return this;
  7087. }
  7088. /**
  7089. * Gets the maximum scale value of the three axes.
  7090. *
  7091. * @return {number} The maxium scale.
  7092. */
  7093. getMaxScaleOnAxis() {
  7094. const te = this.elements;
  7095. const scaleXSq = te[ 0 ] * te[ 0 ] + te[ 1 ] * te[ 1 ] + te[ 2 ] * te[ 2 ];
  7096. const scaleYSq = te[ 4 ] * te[ 4 ] + te[ 5 ] * te[ 5 ] + te[ 6 ] * te[ 6 ];
  7097. const scaleZSq = te[ 8 ] * te[ 8 ] + te[ 9 ] * te[ 9 ] + te[ 10 ] * te[ 10 ];
  7098. return Math.sqrt( Math.max( scaleXSq, scaleYSq, scaleZSq ) );
  7099. }
  7100. /**
  7101. * Sets this matrix as a translation transform from the given vector.
  7102. *
  7103. * @param {number|Vector3} x - The amount to translate in the X axis or alternatively a translation vector.
  7104. * @param {number} y - The amount to translate in the Y axis.
  7105. * @param {number} z - The amount to translate in the z axis.
  7106. * @return {Matrix4} A reference to this matrix.
  7107. */
  7108. makeTranslation( x, y, z ) {
  7109. if ( x.isVector3 ) {
  7110. this.set(
  7111. 1, 0, 0, x.x,
  7112. 0, 1, 0, x.y,
  7113. 0, 0, 1, x.z,
  7114. 0, 0, 0, 1
  7115. );
  7116. } else {
  7117. this.set(
  7118. 1, 0, 0, x,
  7119. 0, 1, 0, y,
  7120. 0, 0, 1, z,
  7121. 0, 0, 0, 1
  7122. );
  7123. }
  7124. return this;
  7125. }
  7126. /**
  7127. * Sets this matrix as a rotational transformation around the X axis by
  7128. * the given angle.
  7129. *
  7130. * @param {number} theta - The rotation in radians.
  7131. * @return {Matrix4} A reference to this matrix.
  7132. */
  7133. makeRotationX( theta ) {
  7134. const c = Math.cos( theta ), s = Math.sin( theta );
  7135. this.set(
  7136. 1, 0, 0, 0,
  7137. 0, c, - s, 0,
  7138. 0, s, c, 0,
  7139. 0, 0, 0, 1
  7140. );
  7141. return this;
  7142. }
  7143. /**
  7144. * Sets this matrix as a rotational transformation around the Y axis by
  7145. * the given angle.
  7146. *
  7147. * @param {number} theta - The rotation in radians.
  7148. * @return {Matrix4} A reference to this matrix.
  7149. */
  7150. makeRotationY( theta ) {
  7151. const c = Math.cos( theta ), s = Math.sin( theta );
  7152. this.set(
  7153. c, 0, s, 0,
  7154. 0, 1, 0, 0,
  7155. - s, 0, c, 0,
  7156. 0, 0, 0, 1
  7157. );
  7158. return this;
  7159. }
  7160. /**
  7161. * Sets this matrix as a rotational transformation around the Z axis by
  7162. * the given angle.
  7163. *
  7164. * @param {number} theta - The rotation in radians.
  7165. * @return {Matrix4} A reference to this matrix.
  7166. */
  7167. makeRotationZ( theta ) {
  7168. const c = Math.cos( theta ), s = Math.sin( theta );
  7169. this.set(
  7170. c, - s, 0, 0,
  7171. s, c, 0, 0,
  7172. 0, 0, 1, 0,
  7173. 0, 0, 0, 1
  7174. );
  7175. return this;
  7176. }
  7177. /**
  7178. * Sets this matrix as a rotational transformation around the given axis by
  7179. * the given angle.
  7180. *
  7181. * This is a somewhat controversial but mathematically sound alternative to
  7182. * rotating via Quaternions. See the discussion [here]{@link https://www.gamedev.net/articles/programming/math-and-physics/do-we-really-need-quaternions-r1199}.
  7183. *
  7184. * @param {Vector3} axis - The normalized rotation axis.
  7185. * @param {number} angle - The rotation in radians.
  7186. * @return {Matrix4} A reference to this matrix.
  7187. */
  7188. makeRotationAxis( axis, angle ) {
  7189. // Based on http://www.gamedev.net/reference/articles/article1199.asp
  7190. const c = Math.cos( angle );
  7191. const s = Math.sin( angle );
  7192. const t = 1 - c;
  7193. const x = axis.x, y = axis.y, z = axis.z;
  7194. const tx = t * x, ty = t * y;
  7195. this.set(
  7196. tx * x + c, tx * y - s * z, tx * z + s * y, 0,
  7197. tx * y + s * z, ty * y + c, ty * z - s * x, 0,
  7198. tx * z - s * y, ty * z + s * x, t * z * z + c, 0,
  7199. 0, 0, 0, 1
  7200. );
  7201. return this;
  7202. }
  7203. /**
  7204. * Sets this matrix as a scale transformation.
  7205. *
  7206. * @param {number} x - The amount to scale in the X axis.
  7207. * @param {number} y - The amount to scale in the Y axis.
  7208. * @param {number} z - The amount to scale in the Z axis.
  7209. * @return {Matrix4} A reference to this matrix.
  7210. */
  7211. makeScale( x, y, z ) {
  7212. this.set(
  7213. x, 0, 0, 0,
  7214. 0, y, 0, 0,
  7215. 0, 0, z, 0,
  7216. 0, 0, 0, 1
  7217. );
  7218. return this;
  7219. }
  7220. /**
  7221. * Sets this matrix as a shear transformation.
  7222. *
  7223. * @param {number} xy - The amount to shear X by Y.
  7224. * @param {number} xz - The amount to shear X by Z.
  7225. * @param {number} yx - The amount to shear Y by X.
  7226. * @param {number} yz - The amount to shear Y by Z.
  7227. * @param {number} zx - The amount to shear Z by X.
  7228. * @param {number} zy - The amount to shear Z by Y.
  7229. * @return {Matrix4} A reference to this matrix.
  7230. */
  7231. makeShear( xy, xz, yx, yz, zx, zy ) {
  7232. this.set(
  7233. 1, yx, zx, 0,
  7234. xy, 1, zy, 0,
  7235. xz, yz, 1, 0,
  7236. 0, 0, 0, 1
  7237. );
  7238. return this;
  7239. }
  7240. /**
  7241. * Sets this matrix to the transformation composed of the given position,
  7242. * rotation (Quaternion) and scale.
  7243. *
  7244. * @param {Vector3} position - The position vector.
  7245. * @param {Quaternion} quaternion - The rotation as a Quaternion.
  7246. * @param {Vector3} scale - The scale vector.
  7247. * @return {Matrix4} A reference to this matrix.
  7248. */
  7249. compose( position, quaternion, scale ) {
  7250. const te = this.elements;
  7251. const x = quaternion._x, y = quaternion._y, z = quaternion._z, w = quaternion._w;
  7252. const x2 = x + x, y2 = y + y, z2 = z + z;
  7253. const xx = x * x2, xy = x * y2, xz = x * z2;
  7254. const yy = y * y2, yz = y * z2, zz = z * z2;
  7255. const wx = w * x2, wy = w * y2, wz = w * z2;
  7256. const sx = scale.x, sy = scale.y, sz = scale.z;
  7257. te[ 0 ] = ( 1 - ( yy + zz ) ) * sx;
  7258. te[ 1 ] = ( xy + wz ) * sx;
  7259. te[ 2 ] = ( xz - wy ) * sx;
  7260. te[ 3 ] = 0;
  7261. te[ 4 ] = ( xy - wz ) * sy;
  7262. te[ 5 ] = ( 1 - ( xx + zz ) ) * sy;
  7263. te[ 6 ] = ( yz + wx ) * sy;
  7264. te[ 7 ] = 0;
  7265. te[ 8 ] = ( xz + wy ) * sz;
  7266. te[ 9 ] = ( yz - wx ) * sz;
  7267. te[ 10 ] = ( 1 - ( xx + yy ) ) * sz;
  7268. te[ 11 ] = 0;
  7269. te[ 12 ] = position.x;
  7270. te[ 13 ] = position.y;
  7271. te[ 14 ] = position.z;
  7272. te[ 15 ] = 1;
  7273. return this;
  7274. }
  7275. /**
  7276. * Decomposes this matrix into its positon, rotation and scale components
  7277. * and provides the result in the given objects.
  7278. *
  7279. * Note: Not all matrices are decomposable in this way. For example, if an
  7280. * object has a non-uniformly scaled parent, then the object's world matrix
  7281. * may not be decomposable, and this method may not be appropriate.
  7282. *
  7283. * @param {Vector3} position - The position vector.
  7284. * @param {Quaternion} quaternion - The rotation as a Quaternion.
  7285. * @param {Vector3} scale - The scale vector.
  7286. * @return {Matrix4} A reference to this matrix.
  7287. */
  7288. decompose( position, quaternion, scale ) {
  7289. const te = this.elements;
  7290. let sx = _v1$5.set( te[ 0 ], te[ 1 ], te[ 2 ] ).length();
  7291. const sy = _v1$5.set( te[ 4 ], te[ 5 ], te[ 6 ] ).length();
  7292. const sz = _v1$5.set( te[ 8 ], te[ 9 ], te[ 10 ] ).length();
  7293. // if determine is negative, we need to invert one scale
  7294. const det = this.determinant();
  7295. if ( det < 0 ) sx = - sx;
  7296. position.x = te[ 12 ];
  7297. position.y = te[ 13 ];
  7298. position.z = te[ 14 ];
  7299. // scale the rotation part
  7300. _m1$2.copy( this );
  7301. const invSX = 1 / sx;
  7302. const invSY = 1 / sy;
  7303. const invSZ = 1 / sz;
  7304. _m1$2.elements[ 0 ] *= invSX;
  7305. _m1$2.elements[ 1 ] *= invSX;
  7306. _m1$2.elements[ 2 ] *= invSX;
  7307. _m1$2.elements[ 4 ] *= invSY;
  7308. _m1$2.elements[ 5 ] *= invSY;
  7309. _m1$2.elements[ 6 ] *= invSY;
  7310. _m1$2.elements[ 8 ] *= invSZ;
  7311. _m1$2.elements[ 9 ] *= invSZ;
  7312. _m1$2.elements[ 10 ] *= invSZ;
  7313. quaternion.setFromRotationMatrix( _m1$2 );
  7314. scale.x = sx;
  7315. scale.y = sy;
  7316. scale.z = sz;
  7317. return this;
  7318. }
  7319. /**
  7320. * Creates a perspective projection matrix. This is used internally by
  7321. * {@link PerspectiveCamera#updateProjectionMatrix}.
  7322. * @param {number} left - Left boundary of the viewing frustum at the near plane.
  7323. * @param {number} right - Right boundary of the viewing frustum at the near plane.
  7324. * @param {number} top - Top boundary of the viewing frustum at the near plane.
  7325. * @param {number} bottom - Bottom boundary of the viewing frustum at the near plane.
  7326. * @param {number} near - The distance from the camera to the near plane.
  7327. * @param {number} far - The distance from the camera to the far plane.
  7328. * @param {(WebGLCoordinateSystem|WebGPUCoordinateSystem)} [coordinateSystem=WebGLCoordinateSystem] - The coordinate system.
  7329. * @return {Matrix4} A reference to this matrix.
  7330. */
  7331. makePerspective( left, right, top, bottom, near, far, coordinateSystem = WebGLCoordinateSystem ) {
  7332. const te = this.elements;
  7333. const x = 2 * near / ( right - left );
  7334. const y = 2 * near / ( top - bottom );
  7335. const a = ( right + left ) / ( right - left );
  7336. const b = ( top + bottom ) / ( top - bottom );
  7337. let c, d;
  7338. if ( coordinateSystem === WebGLCoordinateSystem ) {
  7339. c = - ( far + near ) / ( far - near );
  7340. d = ( -2 * far * near ) / ( far - near );
  7341. } else if ( coordinateSystem === WebGPUCoordinateSystem ) {
  7342. c = - far / ( far - near );
  7343. d = ( - far * near ) / ( far - near );
  7344. } else {
  7345. throw new Error( 'THREE.Matrix4.makePerspective(): Invalid coordinate system: ' + coordinateSystem );
  7346. }
  7347. te[ 0 ] = x; te[ 4 ] = 0; te[ 8 ] = a; te[ 12 ] = 0;
  7348. te[ 1 ] = 0; te[ 5 ] = y; te[ 9 ] = b; te[ 13 ] = 0;
  7349. te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = c; te[ 14 ] = d;
  7350. te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = -1; te[ 15 ] = 0;
  7351. return this;
  7352. }
  7353. /**
  7354. * Creates a orthographic projection matrix. This is used internally by
  7355. * {@link OrthographicCamera#updateProjectionMatrix}.
  7356. * @param {number} left - Left boundary of the viewing frustum at the near plane.
  7357. * @param {number} right - Right boundary of the viewing frustum at the near plane.
  7358. * @param {number} top - Top boundary of the viewing frustum at the near plane.
  7359. * @param {number} bottom - Bottom boundary of the viewing frustum at the near plane.
  7360. * @param {number} near - The distance from the camera to the near plane.
  7361. * @param {number} far - The distance from the camera to the far plane.
  7362. * @param {(WebGLCoordinateSystem|WebGPUCoordinateSystem)} [coordinateSystem=WebGLCoordinateSystem] - The coordinate system.
  7363. * @return {Matrix4} A reference to this matrix.
  7364. */
  7365. makeOrthographic( left, right, top, bottom, near, far, coordinateSystem = WebGLCoordinateSystem ) {
  7366. const te = this.elements;
  7367. const w = 1.0 / ( right - left );
  7368. const h = 1.0 / ( top - bottom );
  7369. const p = 1.0 / ( far - near );
  7370. const x = ( right + left ) * w;
  7371. const y = ( top + bottom ) * h;
  7372. let z, zInv;
  7373. if ( coordinateSystem === WebGLCoordinateSystem ) {
  7374. z = ( far + near ) * p;
  7375. zInv = -2 * p;
  7376. } else if ( coordinateSystem === WebGPUCoordinateSystem ) {
  7377. z = near * p;
  7378. zInv = -1 * p;
  7379. } else {
  7380. throw new Error( 'THREE.Matrix4.makeOrthographic(): Invalid coordinate system: ' + coordinateSystem );
  7381. }
  7382. te[ 0 ] = 2 * w; te[ 4 ] = 0; te[ 8 ] = 0; te[ 12 ] = - x;
  7383. te[ 1 ] = 0; te[ 5 ] = 2 * h; te[ 9 ] = 0; te[ 13 ] = - y;
  7384. te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = zInv; te[ 14 ] = - z;
  7385. te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = 0; te[ 15 ] = 1;
  7386. return this;
  7387. }
  7388. /**
  7389. * Returns `true` if this matrix is equal with the given one.
  7390. *
  7391. * @param {Matrix4} matrix - The matrix to test for equality.
  7392. * @return {boolean} Whether this matrix is equal with the given one.
  7393. */
  7394. equals( matrix ) {
  7395. const te = this.elements;
  7396. const me = matrix.elements;
  7397. for ( let i = 0; i < 16; i ++ ) {
  7398. if ( te[ i ] !== me[ i ] ) return false;
  7399. }
  7400. return true;
  7401. }
  7402. /**
  7403. * Sets the elements of the matrix from the given array.
  7404. *
  7405. * @param {Array<number>} array - The matrix elements in column-major order.
  7406. * @param {number} [offset=0] - Index of the first element in the array.
  7407. * @return {Matrix4} A reference to this matrix.
  7408. */
  7409. fromArray( array, offset = 0 ) {
  7410. for ( let i = 0; i < 16; i ++ ) {
  7411. this.elements[ i ] = array[ i + offset ];
  7412. }
  7413. return this;
  7414. }
  7415. /**
  7416. * Writes the elements of this matrix to the given array. If no array is provided,
  7417. * the method returns a new instance.
  7418. *
  7419. * @param {Array<number>} [array=[]] - The target array holding the matrix elements in column-major order.
  7420. * @param {number} [offset=0] - Index of the first element in the array.
  7421. * @return {Array<number>} The matrix elements in column-major order.
  7422. */
  7423. toArray( array = [], offset = 0 ) {
  7424. const te = this.elements;
  7425. array[ offset ] = te[ 0 ];
  7426. array[ offset + 1 ] = te[ 1 ];
  7427. array[ offset + 2 ] = te[ 2 ];
  7428. array[ offset + 3 ] = te[ 3 ];
  7429. array[ offset + 4 ] = te[ 4 ];
  7430. array[ offset + 5 ] = te[ 5 ];
  7431. array[ offset + 6 ] = te[ 6 ];
  7432. array[ offset + 7 ] = te[ 7 ];
  7433. array[ offset + 8 ] = te[ 8 ];
  7434. array[ offset + 9 ] = te[ 9 ];
  7435. array[ offset + 10 ] = te[ 10 ];
  7436. array[ offset + 11 ] = te[ 11 ];
  7437. array[ offset + 12 ] = te[ 12 ];
  7438. array[ offset + 13 ] = te[ 13 ];
  7439. array[ offset + 14 ] = te[ 14 ];
  7440. array[ offset + 15 ] = te[ 15 ];
  7441. return array;
  7442. }
  7443. }
  7444. const _v1$5 = /*@__PURE__*/ new Vector3();
  7445. const _m1$2 = /*@__PURE__*/ new Matrix4();
  7446. const _zero = /*@__PURE__*/ new Vector3( 0, 0, 0 );
  7447. const _one = /*@__PURE__*/ new Vector3( 1, 1, 1 );
  7448. const _x = /*@__PURE__*/ new Vector3();
  7449. const _y = /*@__PURE__*/ new Vector3();
  7450. const _z = /*@__PURE__*/ new Vector3();
  7451. const _matrix$2 = /*@__PURE__*/ new Matrix4();
  7452. const _quaternion$3 = /*@__PURE__*/ new Quaternion();
  7453. /**
  7454. * A class representing Euler angles.
  7455. *
  7456. * Euler angles describe a rotational transformation by rotating an object on
  7457. * its various axes in specified amounts per axis, and a specified axis
  7458. * order.
  7459. *
  7460. * Iterating through an instance will yield its components (x, y, z,
  7461. * order) in the corresponding order.
  7462. *
  7463. * ```js
  7464. * const a = new THREE.Euler( 0, 1, 1.57, 'XYZ' );
  7465. * const b = new THREE.Vector3( 1, 0, 1 );
  7466. * b.applyEuler(a);
  7467. * ```
  7468. */
  7469. class Euler {
  7470. /**
  7471. * Constructs a new euler instance.
  7472. *
  7473. * @param {number} [x=0] - The angle of the x axis in radians.
  7474. * @param {number} [y=0] - The angle of the y axis in radians.
  7475. * @param {number} [z=0] - The angle of the z axis in radians.
  7476. * @param {string} [order=Euler.DEFAULT_ORDER] - A string representing the order that the rotations are applied.
  7477. */
  7478. constructor( x = 0, y = 0, z = 0, order = Euler.DEFAULT_ORDER ) {
  7479. /**
  7480. * This flag can be used for type testing.
  7481. *
  7482. * @type {boolean}
  7483. * @readonly
  7484. * @default true
  7485. */
  7486. this.isEuler = true;
  7487. this._x = x;
  7488. this._y = y;
  7489. this._z = z;
  7490. this._order = order;
  7491. }
  7492. /**
  7493. * The angle of the x axis in radians.
  7494. *
  7495. * @type {number}
  7496. * @default 0
  7497. */
  7498. get x() {
  7499. return this._x;
  7500. }
  7501. set x( value ) {
  7502. this._x = value;
  7503. this._onChangeCallback();
  7504. }
  7505. /**
  7506. * The angle of the y axis in radians.
  7507. *
  7508. * @type {number}
  7509. * @default 0
  7510. */
  7511. get y() {
  7512. return this._y;
  7513. }
  7514. set y( value ) {
  7515. this._y = value;
  7516. this._onChangeCallback();
  7517. }
  7518. /**
  7519. * The angle of the z axis in radians.
  7520. *
  7521. * @type {number}
  7522. * @default 0
  7523. */
  7524. get z() {
  7525. return this._z;
  7526. }
  7527. set z( value ) {
  7528. this._z = value;
  7529. this._onChangeCallback();
  7530. }
  7531. /**
  7532. * A string representing the order that the rotations are applied.
  7533. *
  7534. * @type {string}
  7535. * @default 'XYZ'
  7536. */
  7537. get order() {
  7538. return this._order;
  7539. }
  7540. set order( value ) {
  7541. this._order = value;
  7542. this._onChangeCallback();
  7543. }
  7544. /**
  7545. * Sets the Euler components.
  7546. *
  7547. * @param {number} x - The angle of the x axis in radians.
  7548. * @param {number} y - The angle of the y axis in radians.
  7549. * @param {number} z - The angle of the z axis in radians.
  7550. * @param {string} [order] - A string representing the order that the rotations are applied.
  7551. * @return {Euler} A reference to this Euler instance.
  7552. */
  7553. set( x, y, z, order = this._order ) {
  7554. this._x = x;
  7555. this._y = y;
  7556. this._z = z;
  7557. this._order = order;
  7558. this._onChangeCallback();
  7559. return this;
  7560. }
  7561. /**
  7562. * Returns a new Euler instance with copied values from this instance.
  7563. *
  7564. * @return {Euler} A clone of this instance.
  7565. */
  7566. clone() {
  7567. return new this.constructor( this._x, this._y, this._z, this._order );
  7568. }
  7569. /**
  7570. * Copies the values of the given Euler instance to this instance.
  7571. *
  7572. * @param {Euler} euler - The Euler instance to copy.
  7573. * @return {Euler} A reference to this Euler instance.
  7574. */
  7575. copy( euler ) {
  7576. this._x = euler._x;
  7577. this._y = euler._y;
  7578. this._z = euler._z;
  7579. this._order = euler._order;
  7580. this._onChangeCallback();
  7581. return this;
  7582. }
  7583. /**
  7584. * Sets the angles of this Euler instance from a pure rotation matrix.
  7585. *
  7586. * @param {Matrix4} m - A 4x4 matrix of which the upper 3x3 of matrix is a pure rotation matrix (i.e. unscaled).
  7587. * @param {string} [order] - A string representing the order that the rotations are applied.
  7588. * @param {boolean} [update=true] - Whether the internal `onChange` callback should be executed or not.
  7589. * @return {Euler} A reference to this Euler instance.
  7590. */
  7591. setFromRotationMatrix( m, order = this._order, update = true ) {
  7592. const te = m.elements;
  7593. const m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ];
  7594. const m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ];
  7595. const m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];
  7596. switch ( order ) {
  7597. case 'XYZ':
  7598. this._y = Math.asin( clamp( m13, -1, 1 ) );
  7599. if ( Math.abs( m13 ) < 0.9999999 ) {
  7600. this._x = Math.atan2( - m23, m33 );
  7601. this._z = Math.atan2( - m12, m11 );
  7602. } else {
  7603. this._x = Math.atan2( m32, m22 );
  7604. this._z = 0;
  7605. }
  7606. break;
  7607. case 'YXZ':
  7608. this._x = Math.asin( - clamp( m23, -1, 1 ) );
  7609. if ( Math.abs( m23 ) < 0.9999999 ) {
  7610. this._y = Math.atan2( m13, m33 );
  7611. this._z = Math.atan2( m21, m22 );
  7612. } else {
  7613. this._y = Math.atan2( - m31, m11 );
  7614. this._z = 0;
  7615. }
  7616. break;
  7617. case 'ZXY':
  7618. this._x = Math.asin( clamp( m32, -1, 1 ) );
  7619. if ( Math.abs( m32 ) < 0.9999999 ) {
  7620. this._y = Math.atan2( - m31, m33 );
  7621. this._z = Math.atan2( - m12, m22 );
  7622. } else {
  7623. this._y = 0;
  7624. this._z = Math.atan2( m21, m11 );
  7625. }
  7626. break;
  7627. case 'ZYX':
  7628. this._y = Math.asin( - clamp( m31, -1, 1 ) );
  7629. if ( Math.abs( m31 ) < 0.9999999 ) {
  7630. this._x = Math.atan2( m32, m33 );
  7631. this._z = Math.atan2( m21, m11 );
  7632. } else {
  7633. this._x = 0;
  7634. this._z = Math.atan2( - m12, m22 );
  7635. }
  7636. break;
  7637. case 'YZX':
  7638. this._z = Math.asin( clamp( m21, -1, 1 ) );
  7639. if ( Math.abs( m21 ) < 0.9999999 ) {
  7640. this._x = Math.atan2( - m23, m22 );
  7641. this._y = Math.atan2( - m31, m11 );
  7642. } else {
  7643. this._x = 0;
  7644. this._y = Math.atan2( m13, m33 );
  7645. }
  7646. break;
  7647. case 'XZY':
  7648. this._z = Math.asin( - clamp( m12, -1, 1 ) );
  7649. if ( Math.abs( m12 ) < 0.9999999 ) {
  7650. this._x = Math.atan2( m32, m22 );
  7651. this._y = Math.atan2( m13, m11 );
  7652. } else {
  7653. this._x = Math.atan2( - m23, m33 );
  7654. this._y = 0;
  7655. }
  7656. break;
  7657. default:
  7658. console.warn( 'THREE.Euler: .setFromRotationMatrix() encountered an unknown order: ' + order );
  7659. }
  7660. this._order = order;
  7661. if ( update === true ) this._onChangeCallback();
  7662. return this;
  7663. }
  7664. /**
  7665. * Sets the angles of this Euler instance from a normalized quaternion.
  7666. *
  7667. * @param {Quaternion} q - A normalized Quaternion.
  7668. * @param {string} [order] - A string representing the order that the rotations are applied.
  7669. * @param {boolean} [update=true] - Whether the internal `onChange` callback should be executed or not.
  7670. * @return {Euler} A reference to this Euler instance.
  7671. */
  7672. setFromQuaternion( q, order, update ) {
  7673. _matrix$2.makeRotationFromQuaternion( q );
  7674. return this.setFromRotationMatrix( _matrix$2, order, update );
  7675. }
  7676. /**
  7677. * Sets the angles of this Euler instance from the given vector.
  7678. *
  7679. * @param {Vector3} v - The vector.
  7680. * @param {string} [order] - A string representing the order that the rotations are applied.
  7681. * @return {Euler} A reference to this Euler instance.
  7682. */
  7683. setFromVector3( v, order = this._order ) {
  7684. return this.set( v.x, v.y, v.z, order );
  7685. }
  7686. /**
  7687. * Resets the euler angle with a new order by creating a quaternion from this
  7688. * euler angle and then setting this euler angle with the quaternion and the
  7689. * new order.
  7690. *
  7691. * Warning: This discards revolution information.
  7692. *
  7693. * @param {string} [newOrder] - A string representing the new order that the rotations are applied.
  7694. * @return {Euler} A reference to this Euler instance.
  7695. */
  7696. reorder( newOrder ) {
  7697. _quaternion$3.setFromEuler( this );
  7698. return this.setFromQuaternion( _quaternion$3, newOrder );
  7699. }
  7700. /**
  7701. * Returns `true` if this Euler instance is equal with the given one.
  7702. *
  7703. * @param {Euler} euler - The Euler instance to test for equality.
  7704. * @return {boolean} Whether this Euler instance is equal with the given one.
  7705. */
  7706. equals( euler ) {
  7707. return ( euler._x === this._x ) && ( euler._y === this._y ) && ( euler._z === this._z ) && ( euler._order === this._order );
  7708. }
  7709. /**
  7710. * Sets this Euler instance's components to values from the given array. The first three
  7711. * entries of the array are assign to the x,y and z components. An optinal fourth entry
  7712. * defines the Euler order.
  7713. *
  7714. * @param {Array<number,number,number,?string>} array - An array holding the Euler component values.
  7715. * @return {Euler} A reference to this Euler instance.
  7716. */
  7717. fromArray( array ) {
  7718. this._x = array[ 0 ];
  7719. this._y = array[ 1 ];
  7720. this._z = array[ 2 ];
  7721. if ( array[ 3 ] !== undefined ) this._order = array[ 3 ];
  7722. this._onChangeCallback();
  7723. return this;
  7724. }
  7725. /**
  7726. * Writes the components of this Euler instance to the given array. If no array is provided,
  7727. * the method returns a new instance.
  7728. *
  7729. * @param {Array<number,number,number,string>} [array=[]] - The target array holding the Euler components.
  7730. * @param {number} [offset=0] - Index of the first element in the array.
  7731. * @return {Array<number,number,number,string>} The Euler components.
  7732. */
  7733. toArray( array = [], offset = 0 ) {
  7734. array[ offset ] = this._x;
  7735. array[ offset + 1 ] = this._y;
  7736. array[ offset + 2 ] = this._z;
  7737. array[ offset + 3 ] = this._order;
  7738. return array;
  7739. }
  7740. _onChange( callback ) {
  7741. this._onChangeCallback = callback;
  7742. return this;
  7743. }
  7744. _onChangeCallback() {}
  7745. *[ Symbol.iterator ]() {
  7746. yield this._x;
  7747. yield this._y;
  7748. yield this._z;
  7749. yield this._order;
  7750. }
  7751. }
  7752. /**
  7753. * The default Euler angle order.
  7754. *
  7755. * @static
  7756. * @type {string}
  7757. * @default 'XYZ'
  7758. */
  7759. Euler.DEFAULT_ORDER = 'XYZ';
  7760. class Layers {
  7761. constructor() {
  7762. this.mask = 1 | 0;
  7763. }
  7764. set( channel ) {
  7765. this.mask = ( 1 << channel | 0 ) >>> 0;
  7766. }
  7767. enable( channel ) {
  7768. this.mask |= 1 << channel | 0;
  7769. }
  7770. enableAll() {
  7771. this.mask = 0xffffffff | 0;
  7772. }
  7773. toggle( channel ) {
  7774. this.mask ^= 1 << channel | 0;
  7775. }
  7776. disable( channel ) {
  7777. this.mask &= ~ ( 1 << channel | 0 );
  7778. }
  7779. disableAll() {
  7780. this.mask = 0;
  7781. }
  7782. test( layers ) {
  7783. return ( this.mask & layers.mask ) !== 0;
  7784. }
  7785. isEnabled( channel ) {
  7786. return ( this.mask & ( 1 << channel | 0 ) ) !== 0;
  7787. }
  7788. }
  7789. let _object3DId = 0;
  7790. const _v1$4 = /*@__PURE__*/ new Vector3();
  7791. const _q1 = /*@__PURE__*/ new Quaternion();
  7792. const _m1$1 = /*@__PURE__*/ new Matrix4();
  7793. const _target = /*@__PURE__*/ new Vector3();
  7794. const _position$3 = /*@__PURE__*/ new Vector3();
  7795. const _scale$2 = /*@__PURE__*/ new Vector3();
  7796. const _quaternion$2 = /*@__PURE__*/ new Quaternion();
  7797. const _xAxis = /*@__PURE__*/ new Vector3( 1, 0, 0 );
  7798. const _yAxis = /*@__PURE__*/ new Vector3( 0, 1, 0 );
  7799. const _zAxis = /*@__PURE__*/ new Vector3( 0, 0, 1 );
  7800. /**
  7801. * Fires when the object has been added to its parent object.
  7802. *
  7803. * @event Object3D#added
  7804. * @type {Object}
  7805. */
  7806. const _addedEvent = { type: 'added' };
  7807. /**
  7808. * Fires when the object has been removed from its parent object.
  7809. *
  7810. * @event Object3D#removed
  7811. * @type {Object}
  7812. */
  7813. const _removedEvent = { type: 'removed' };
  7814. /**
  7815. * Fires when a new child object has been added.
  7816. *
  7817. * @event Object3D#childadded
  7818. * @type {Object}
  7819. */
  7820. const _childaddedEvent = { type: 'childadded', child: null };
  7821. /**
  7822. * Fires when a new child object has been added.
  7823. *
  7824. * @event Object3D#childremoved
  7825. * @type {Object}
  7826. */
  7827. const _childremovedEvent = { type: 'childremoved', child: null };
  7828. /**
  7829. * This is the base class for most objects in three.js and provides a set of
  7830. * properties and methods for manipulating objects in 3D space.
  7831. *
  7832. * @augments EventDispatcher
  7833. */
  7834. class Object3D extends EventDispatcher {
  7835. /**
  7836. * Constructs a new 3D object.
  7837. */
  7838. constructor() {
  7839. super();
  7840. /**
  7841. * This flag can be used for type testing.
  7842. *
  7843. * @type {boolean}
  7844. * @readonly
  7845. * @default true
  7846. */
  7847. this.isObject3D = true;
  7848. /**
  7849. * The ID of the 3D object.
  7850. *
  7851. * @name Object3D#id
  7852. * @type {number}
  7853. * @readonly
  7854. */
  7855. Object.defineProperty( this, 'id', { value: _object3DId ++ } );
  7856. /**
  7857. * The UUID of the 3D object.
  7858. *
  7859. * @type {string}
  7860. * @readonly
  7861. */
  7862. this.uuid = generateUUID();
  7863. /**
  7864. * The name of the 3D object.
  7865. *
  7866. * @type {string}
  7867. */
  7868. this.name = '';
  7869. /**
  7870. * The type property is used for detecting the object type
  7871. * in context of serialization/deserialization.
  7872. *
  7873. * @type {string}
  7874. * @readonly
  7875. */
  7876. this.type = 'Object3D';
  7877. /**
  7878. * A reference to the parent object.
  7879. *
  7880. * @type {?Object3D}
  7881. * @default null
  7882. */
  7883. this.parent = null;
  7884. /**
  7885. * An array holding the child 3D objects of this instance.
  7886. *
  7887. * @type {Array<Object3D>}
  7888. */
  7889. this.children = [];
  7890. /**
  7891. * Defines the `up` direction of the 3D object which influences
  7892. * the orientation via methods like {@link Object3D#lookAt}.
  7893. *
  7894. * The default values for all 3D objects is defined by `Object3D.DEFAULT_UP`.
  7895. *
  7896. * @type {Vector3}
  7897. */
  7898. this.up = Object3D.DEFAULT_UP.clone();
  7899. const position = new Vector3();
  7900. const rotation = new Euler();
  7901. const quaternion = new Quaternion();
  7902. const scale = new Vector3( 1, 1, 1 );
  7903. function onRotationChange() {
  7904. quaternion.setFromEuler( rotation, false );
  7905. }
  7906. function onQuaternionChange() {
  7907. rotation.setFromQuaternion( quaternion, undefined, false );
  7908. }
  7909. rotation._onChange( onRotationChange );
  7910. quaternion._onChange( onQuaternionChange );
  7911. Object.defineProperties( this, {
  7912. /**
  7913. * Represents the object's local position.
  7914. *
  7915. * @name Object3D#position
  7916. * @type {Vector3}
  7917. * @default (0,0,0)
  7918. */
  7919. position: {
  7920. configurable: true,
  7921. enumerable: true,
  7922. value: position
  7923. },
  7924. /**
  7925. * Represents the object's local rotation as Euler angles, in radians.
  7926. *
  7927. * @name Object3D#rotation
  7928. * @type {Euler}
  7929. * @default (0,0,0)
  7930. */
  7931. rotation: {
  7932. configurable: true,
  7933. enumerable: true,
  7934. value: rotation
  7935. },
  7936. /**
  7937. * Represents the object's local rotation as Quaterions.
  7938. *
  7939. * @name Object3D#quaternion
  7940. * @type {Quaternion}
  7941. */
  7942. quaternion: {
  7943. configurable: true,
  7944. enumerable: true,
  7945. value: quaternion
  7946. },
  7947. /**
  7948. * Represents the object's local scale.
  7949. *
  7950. * @name Object3D#scale
  7951. * @type {Vector3}
  7952. * @default (1,1,1)
  7953. */
  7954. scale: {
  7955. configurable: true,
  7956. enumerable: true,
  7957. value: scale
  7958. },
  7959. /**
  7960. * Represents the object's model-view matrix.
  7961. *
  7962. * @name Object3D#modelViewMatrix
  7963. * @type {Matrix4}
  7964. */
  7965. modelViewMatrix: {
  7966. value: new Matrix4()
  7967. },
  7968. /**
  7969. * Represents the object's normal matrix.
  7970. *
  7971. * @name Object3D#normalMatrix
  7972. * @type {Matrix3}
  7973. */
  7974. normalMatrix: {
  7975. value: new Matrix3()
  7976. }
  7977. } );
  7978. /**
  7979. * Represents the object's transformation matrix in local space.
  7980. *
  7981. * @type {Matrix4}
  7982. */
  7983. this.matrix = new Matrix4();
  7984. /**
  7985. * Represents the object's transformation matrix in world space.
  7986. * If the 3D object has no parent, then it's identical to the local transformation matrix
  7987. *
  7988. * @type {Matrix4}
  7989. */
  7990. this.matrixWorld = new Matrix4();
  7991. /**
  7992. * When set to `true`, the engine automatically computes the local matrix from position,
  7993. * rotation and scale every frame.
  7994. *
  7995. * The default values for all 3D objects is defined by `Object3D.DEFAULT_MATRIX_AUTO_UPDATE`.
  7996. *
  7997. * @type {boolean}
  7998. * @default true
  7999. */
  8000. this.matrixAutoUpdate = Object3D.DEFAULT_MATRIX_AUTO_UPDATE;
  8001. /**
  8002. * When set to `true`, the engine automatically computes the world matrix from the current local
  8003. * matrix and the object's transformation hierarchy.
  8004. *
  8005. * The default values for all 3D objects is defined by `Object3D.DEFAULT_MATRIX_WORLD_AUTO_UPDATE`.
  8006. *
  8007. * @type {boolean}
  8008. * @default true
  8009. */
  8010. this.matrixWorldAutoUpdate = Object3D.DEFAULT_MATRIX_WORLD_AUTO_UPDATE; // checked by the renderer
  8011. /**
  8012. * When set to `true`, it calculates the world matrix in that frame and resets this property
  8013. * to `false`.
  8014. *
  8015. * @type {boolean}
  8016. * @default false
  8017. */
  8018. this.matrixWorldNeedsUpdate = false;
  8019. /**
  8020. * The layer membership of the 3D object. The 3D object is only visible if it has
  8021. * at least one layer in common with the camera in use. This property can also be
  8022. * used to filter out unwanted objects in ray-intersection tests when using {@link Raycaster}.
  8023. *
  8024. * @type {Layers}
  8025. */
  8026. this.layers = new Layers();
  8027. /**
  8028. * When set to `true`, the 3D object gets rendered.
  8029. *
  8030. * @type {boolean}
  8031. * @default true
  8032. */
  8033. this.visible = true;
  8034. /**
  8035. * When set to `true`, the 3D object gets rendered into shadow maps.
  8036. *
  8037. * @type {boolean}
  8038. * @default false
  8039. */
  8040. this.castShadow = false;
  8041. /**
  8042. * When set to `true`, the 3D object is affected by shadows in the scene.
  8043. *
  8044. * @type {boolean}
  8045. * @default false
  8046. */
  8047. this.receiveShadow = false;
  8048. /**
  8049. * When set to `true`, the 3D object is honored by view frustum culling.
  8050. *
  8051. * @type {boolean}
  8052. * @default true
  8053. */
  8054. this.frustumCulled = true;
  8055. /**
  8056. * This value allows the default rendering order of scene graph objects to be
  8057. * overridden although opaque and transparent objects remain sorted independently.
  8058. * When this property is set for an instance of {@link Group},all descendants
  8059. * objects will be sorted and rendered together. Sorting is from lowest to highest
  8060. * render order.
  8061. *
  8062. * @type {number}
  8063. * @default 0
  8064. */
  8065. this.renderOrder = 0;
  8066. /**
  8067. * An array holding the animation clips of the 3D object.
  8068. *
  8069. * @type {Array<AnimationClip>}
  8070. */
  8071. this.animations = [];
  8072. /**
  8073. * An object that can be used to store custom data about the 3D object. It
  8074. * should not hold references to functions as these will not be cloned.
  8075. *
  8076. * @type {Object}
  8077. */
  8078. this.userData = {};
  8079. }
  8080. /**
  8081. * A callback that is executed immediately before a 3D object is rendered to a shadow map.
  8082. *
  8083. * @param {Renderer|WebGLRenderer} renderer - The renderer.
  8084. * @param {Object3D} object - The 3D object.
  8085. * @param {Camera} camera - The camera that is used to render the scene.
  8086. * @param {Camera} shadowCamera - The shadow camera.
  8087. * @param {BufferGeometry} geometry - The 3D object's geometry.
  8088. * @param {Material} depthMaterial - The depth material.
  8089. * @param {Object} group - The geometry group data.
  8090. */
  8091. onBeforeShadow( /* renderer, object, camera, shadowCamera, geometry, depthMaterial, group */ ) {}
  8092. /**
  8093. * A callback that is executed immediately after a 3D object is rendered to a shadow map.
  8094. *
  8095. * @param {Renderer|WebGLRenderer} renderer - The renderer.
  8096. * @param {Object3D} object - The 3D object.
  8097. * @param {Camera} camera - The camera that is used to render the scene.
  8098. * @param {Camera} shadowCamera - The shadow camera.
  8099. * @param {BufferGeometry} geometry - The 3D object's geometry.
  8100. * @param {Material} depthMaterial - The depth material.
  8101. * @param {Object} group - The geometry group data.
  8102. */
  8103. onAfterShadow( /* renderer, object, camera, shadowCamera, geometry, depthMaterial, group */ ) {}
  8104. /**
  8105. * A callback that is executed immediately before a 3D object is rendered.
  8106. *
  8107. * @param {Renderer|WebGLRenderer} renderer - The renderer.
  8108. * @param {Object3D} object - The 3D object.
  8109. * @param {Camera} camera - The camera that is used to render the scene.
  8110. * @param {BufferGeometry} geometry - The 3D object's geometry.
  8111. * @param {Material} material - The 3D object's material.
  8112. * @param {Object} group - The geometry group data.
  8113. */
  8114. onBeforeRender( /* renderer, scene, camera, geometry, material, group */ ) {}
  8115. /**
  8116. * A callback that is executed immediately after a 3D object is rendered.
  8117. *
  8118. * @param {Renderer|WebGLRenderer} renderer - The renderer.
  8119. * @param {Object3D} object - The 3D object.
  8120. * @param {Camera} camera - The camera that is used to render the scene.
  8121. * @param {BufferGeometry} geometry - The 3D object's geometry.
  8122. * @param {Material} material - The 3D object's material.
  8123. * @param {Object} group - The geometry group data.
  8124. */
  8125. onAfterRender( /* renderer, scene, camera, geometry, material, group */ ) {}
  8126. /**
  8127. * Applies the given transformation matrix to the object and updates the object's position,
  8128. * rotation and scale.
  8129. *
  8130. * @param {Matrix4} matrix - The transformation matrix.
  8131. */
  8132. applyMatrix4( matrix ) {
  8133. if ( this.matrixAutoUpdate ) this.updateMatrix();
  8134. this.matrix.premultiply( matrix );
  8135. this.matrix.decompose( this.position, this.quaternion, this.scale );
  8136. }
  8137. /**
  8138. * Applies a rotation represented by given the quaternion to the 3D object.
  8139. *
  8140. * @param {Quaternion} q - The quaterion.
  8141. * @return {Object3D} A reference to this instance.
  8142. */
  8143. applyQuaternion( q ) {
  8144. this.quaternion.premultiply( q );
  8145. return this;
  8146. }
  8147. /**
  8148. * Sets the given rotation represented as an axis/angle couple to the 3D object.
  8149. *
  8150. * @param {Vector3} axis - The (normalized) axis vector.
  8151. * @param {number} angle - The angle in radians.
  8152. */
  8153. setRotationFromAxisAngle( axis, angle ) {
  8154. // assumes axis is normalized
  8155. this.quaternion.setFromAxisAngle( axis, angle );
  8156. }
  8157. /**
  8158. * Sets the given rotation represented as Euler angles to the 3D object.
  8159. *
  8160. * @param {Euler} euler - The Euler angles.
  8161. */
  8162. setRotationFromEuler( euler ) {
  8163. this.quaternion.setFromEuler( euler, true );
  8164. }
  8165. /**
  8166. * Sets the given rotation represented as rotation matrix to the 3D object.
  8167. *
  8168. * @param {Matrix4} m - Although a 4x4 matrix is expected, the upper 3x3 portion must be
  8169. * a pure rotation matrix (i.e, unscaled).
  8170. */
  8171. setRotationFromMatrix( m ) {
  8172. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  8173. this.quaternion.setFromRotationMatrix( m );
  8174. }
  8175. /**
  8176. * Sets the given rotation represented as a Quanterion to the 3D object.
  8177. *
  8178. * @param {Quaternion} q - The Quanterion
  8179. */
  8180. setRotationFromQuaternion( q ) {
  8181. // assumes q is normalized
  8182. this.quaternion.copy( q );
  8183. }
  8184. /**
  8185. * Rotates the 3D object along an axis in local space.
  8186. *
  8187. * @param {Vector3} axis - The (normalized) axis vector.
  8188. * @param {number} angle - The angle in radians.
  8189. * @return {Object3D} A reference to this instance.
  8190. */
  8191. rotateOnAxis( axis, angle ) {
  8192. // rotate object on axis in object space
  8193. // axis is assumed to be normalized
  8194. _q1.setFromAxisAngle( axis, angle );
  8195. this.quaternion.multiply( _q1 );
  8196. return this;
  8197. }
  8198. /**
  8199. * Rotates the 3D object along an axis in world space.
  8200. *
  8201. * @param {Vector3} axis - The (normalized) axis vector.
  8202. * @param {number} angle - The angle in radians.
  8203. * @return {Object3D} A reference to this instance.
  8204. */
  8205. rotateOnWorldAxis( axis, angle ) {
  8206. // rotate object on axis in world space
  8207. // axis is assumed to be normalized
  8208. // method assumes no rotated parent
  8209. _q1.setFromAxisAngle( axis, angle );
  8210. this.quaternion.premultiply( _q1 );
  8211. return this;
  8212. }
  8213. /**
  8214. * Rotates the 3D object around its X axis in local space.
  8215. *
  8216. * @param {number} angle - The angle in radians.
  8217. * @return {Object3D} A reference to this instance.
  8218. */
  8219. rotateX( angle ) {
  8220. return this.rotateOnAxis( _xAxis, angle );
  8221. }
  8222. /**
  8223. * Rotates the 3D object around its Y axis in local space.
  8224. *
  8225. * @param {number} angle - The angle in radians.
  8226. * @return {Object3D} A reference to this instance.
  8227. */
  8228. rotateY( angle ) {
  8229. return this.rotateOnAxis( _yAxis, angle );
  8230. }
  8231. /**
  8232. * Rotates the 3D object around its Z axis in local space.
  8233. *
  8234. * @param {number} angle - The angle in radians.
  8235. * @return {Object3D} A reference to this instance.
  8236. */
  8237. rotateZ( angle ) {
  8238. return this.rotateOnAxis( _zAxis, angle );
  8239. }
  8240. /**
  8241. * Translate the 3D object by a distance along the given axis in local space.
  8242. *
  8243. * @param {Vector3} axis - The (normalized) axis vector.
  8244. * @param {number} distance - The distance in world units.
  8245. * @return {Object3D} A reference to this instance.
  8246. */
  8247. translateOnAxis( axis, distance ) {
  8248. // translate object by distance along axis in object space
  8249. // axis is assumed to be normalized
  8250. _v1$4.copy( axis ).applyQuaternion( this.quaternion );
  8251. this.position.add( _v1$4.multiplyScalar( distance ) );
  8252. return this;
  8253. }
  8254. /**
  8255. * Translate the 3D object by a distance along its X-axis in local space.
  8256. *
  8257. * @param {number} distance - The distance in world units.
  8258. * @return {Object3D} A reference to this instance.
  8259. */
  8260. translateX( distance ) {
  8261. return this.translateOnAxis( _xAxis, distance );
  8262. }
  8263. /**
  8264. * Translate the 3D object by a distance along its Y-axis in local space.
  8265. *
  8266. * @param {number} distance - The distance in world units.
  8267. * @return {Object3D} A reference to this instance.
  8268. */
  8269. translateY( distance ) {
  8270. return this.translateOnAxis( _yAxis, distance );
  8271. }
  8272. /**
  8273. * Translate the 3D object by a distance along its Z-axis in local space.
  8274. *
  8275. * @param {number} distance - The distance in world units.
  8276. * @return {Object3D} A reference to this instance.
  8277. */
  8278. translateZ( distance ) {
  8279. return this.translateOnAxis( _zAxis, distance );
  8280. }
  8281. /**
  8282. * Converts the given vector from this 3D object's local space to world space.
  8283. *
  8284. * @param {Vector3} vector - The vector to convert.
  8285. * @return {Vector3} The converted vector.
  8286. */
  8287. localToWorld( vector ) {
  8288. this.updateWorldMatrix( true, false );
  8289. return vector.applyMatrix4( this.matrixWorld );
  8290. }
  8291. /**
  8292. * Converts the given vector from this 3D object's word space to local space.
  8293. *
  8294. * @param {Vector3} vector - The vector to convert.
  8295. * @return {Vector3} The converted vector.
  8296. */
  8297. worldToLocal( vector ) {
  8298. this.updateWorldMatrix( true, false );
  8299. return vector.applyMatrix4( _m1$1.copy( this.matrixWorld ).invert() );
  8300. }
  8301. /**
  8302. * Rotates the object to face a point in world space.
  8303. *
  8304. * This method does not support objects having non-uniformly-scaled parent(s).
  8305. *
  8306. * @param {number|Vector3} x - The x coordinate in world space. Alternatively, a vector representing a position in world space
  8307. * @param {number} [y] - The y coordinate in world space.
  8308. * @param {number} [z] - The z coordinate in world space.
  8309. */
  8310. lookAt( x, y, z ) {
  8311. // This method does not support objects having non-uniformly-scaled parent(s)
  8312. if ( x.isVector3 ) {
  8313. _target.copy( x );
  8314. } else {
  8315. _target.set( x, y, z );
  8316. }
  8317. const parent = this.parent;
  8318. this.updateWorldMatrix( true, false );
  8319. _position$3.setFromMatrixPosition( this.matrixWorld );
  8320. if ( this.isCamera || this.isLight ) {
  8321. _m1$1.lookAt( _position$3, _target, this.up );
  8322. } else {
  8323. _m1$1.lookAt( _target, _position$3, this.up );
  8324. }
  8325. this.quaternion.setFromRotationMatrix( _m1$1 );
  8326. if ( parent ) {
  8327. _m1$1.extractRotation( parent.matrixWorld );
  8328. _q1.setFromRotationMatrix( _m1$1 );
  8329. this.quaternion.premultiply( _q1.invert() );
  8330. }
  8331. }
  8332. /**
  8333. * Adds the given 3D object as a child to this 3D object. An arbitrary number of
  8334. * objects may be added. Any current parent on an object passed in here will be
  8335. * removed, since an object can have at most one parent.
  8336. *
  8337. * @fires Object3D#added
  8338. * @fires Object3D#childadded
  8339. * @param {Object3D} object - The 3D object to add.
  8340. * @return {Object3D} A reference to this instance.
  8341. */
  8342. add( object ) {
  8343. if ( arguments.length > 1 ) {
  8344. for ( let i = 0; i < arguments.length; i ++ ) {
  8345. this.add( arguments[ i ] );
  8346. }
  8347. return this;
  8348. }
  8349. if ( object === this ) {
  8350. console.error( 'THREE.Object3D.add: object can\'t be added as a child of itself.', object );
  8351. return this;
  8352. }
  8353. if ( object && object.isObject3D ) {
  8354. object.removeFromParent();
  8355. object.parent = this;
  8356. this.children.push( object );
  8357. object.dispatchEvent( _addedEvent );
  8358. _childaddedEvent.child = object;
  8359. this.dispatchEvent( _childaddedEvent );
  8360. _childaddedEvent.child = null;
  8361. } else {
  8362. console.error( 'THREE.Object3D.add: object not an instance of THREE.Object3D.', object );
  8363. }
  8364. return this;
  8365. }
  8366. /**
  8367. * Removes the given 3D object as child from this 3D object.
  8368. * An arbitrary number of objects may be removed.
  8369. *
  8370. * @fires Object3D#removed
  8371. * @fires Object3D#childremoved
  8372. * @param {Object3D} object - The 3D object to remove.
  8373. * @return {Object3D} A reference to this instance.
  8374. */
  8375. remove( object ) {
  8376. if ( arguments.length > 1 ) {
  8377. for ( let i = 0; i < arguments.length; i ++ ) {
  8378. this.remove( arguments[ i ] );
  8379. }
  8380. return this;
  8381. }
  8382. const index = this.children.indexOf( object );
  8383. if ( index !== -1 ) {
  8384. object.parent = null;
  8385. this.children.splice( index, 1 );
  8386. object.dispatchEvent( _removedEvent );
  8387. _childremovedEvent.child = object;
  8388. this.dispatchEvent( _childremovedEvent );
  8389. _childremovedEvent.child = null;
  8390. }
  8391. return this;
  8392. }
  8393. /**
  8394. * Removes this 3D object from its current parent.
  8395. *
  8396. * @fires Object3D#removed
  8397. * @fires Object3D#childremoved
  8398. * @return {Object3D} A reference to this instance.
  8399. */
  8400. removeFromParent() {
  8401. const parent = this.parent;
  8402. if ( parent !== null ) {
  8403. parent.remove( this );
  8404. }
  8405. return this;
  8406. }
  8407. /**
  8408. * Removes all child objects.
  8409. *
  8410. * @fires Object3D#removed
  8411. * @fires Object3D#childremoved
  8412. * @return {Object3D} A reference to this instance.
  8413. */
  8414. clear() {
  8415. return this.remove( ... this.children );
  8416. }
  8417. /**
  8418. * Adds the given 3D object as a child of this 3D object, while maintaining the object's world
  8419. * transform. This method does not support scene graphs having non-uniformly-scaled nodes(s).
  8420. *
  8421. * @fires Object3D#added
  8422. * @fires Object3D#childadded
  8423. * @param {Object3D} object - The 3D object to attach.
  8424. * @return {Object3D} A reference to this instance.
  8425. */
  8426. attach( object ) {
  8427. // adds object as a child of this, while maintaining the object's world transform
  8428. // Note: This method does not support scene graphs having non-uniformly-scaled nodes(s)
  8429. this.updateWorldMatrix( true, false );
  8430. _m1$1.copy( this.matrixWorld ).invert();
  8431. if ( object.parent !== null ) {
  8432. object.parent.updateWorldMatrix( true, false );
  8433. _m1$1.multiply( object.parent.matrixWorld );
  8434. }
  8435. object.applyMatrix4( _m1$1 );
  8436. object.removeFromParent();
  8437. object.parent = this;
  8438. this.children.push( object );
  8439. object.updateWorldMatrix( false, true );
  8440. object.dispatchEvent( _addedEvent );
  8441. _childaddedEvent.child = object;
  8442. this.dispatchEvent( _childaddedEvent );
  8443. _childaddedEvent.child = null;
  8444. return this;
  8445. }
  8446. /**
  8447. * Searches through the 3D object and its children, starting with the 3D object
  8448. * itself, and returns the first with a matching ID.
  8449. *
  8450. * @param {number} id - The id.
  8451. * @return {Object3D|undefined} The found 3D object. Returns `undefined` if no 3D object has been found.
  8452. */
  8453. getObjectById( id ) {
  8454. return this.getObjectByProperty( 'id', id );
  8455. }
  8456. /**
  8457. * Searches through the 3D object and its children, starting with the 3D object
  8458. * itself, and returns the first with a matching name.
  8459. *
  8460. * @param {string} name - The name.
  8461. * @return {Object3D|undefined} The found 3D object. Returns `undefined` if no 3D object has been found.
  8462. */
  8463. getObjectByName( name ) {
  8464. return this.getObjectByProperty( 'name', name );
  8465. }
  8466. /**
  8467. * Searches through the 3D object and its children, starting with the 3D object
  8468. * itself, and returns the first with a matching property value.
  8469. *
  8470. * @param {string} name - The name of the property.
  8471. * @param {any} value - The value.
  8472. * @return {Object3D|undefined} The found 3D object. Returns `undefined` if no 3D object has been found.
  8473. */
  8474. getObjectByProperty( name, value ) {
  8475. if ( this[ name ] === value ) return this;
  8476. for ( let i = 0, l = this.children.length; i < l; i ++ ) {
  8477. const child = this.children[ i ];
  8478. const object = child.getObjectByProperty( name, value );
  8479. if ( object !== undefined ) {
  8480. return object;
  8481. }
  8482. }
  8483. return undefined;
  8484. }
  8485. /**
  8486. * Searches through the 3D object and its children, starting with the 3D object
  8487. * itself, and returns all 3D objects with a matching property value.
  8488. *
  8489. * @param {string} name - The name of the property.
  8490. * @param {any} value - The value.
  8491. * @param {Array<Object3D>} result - The method stores the result in this array.
  8492. * @return {Array<Object3D>} The found 3D objects.
  8493. */
  8494. getObjectsByProperty( name, value, result = [] ) {
  8495. if ( this[ name ] === value ) result.push( this );
  8496. const children = this.children;
  8497. for ( let i = 0, l = children.length; i < l; i ++ ) {
  8498. children[ i ].getObjectsByProperty( name, value, result );
  8499. }
  8500. return result;
  8501. }
  8502. /**
  8503. * Returns a vector representing the position of the 3D object in world space.
  8504. *
  8505. * @param {Vector3} target - The target vector the result is stored to.
  8506. * @return {Vector3} The 3D object's position in world space.
  8507. */
  8508. getWorldPosition( target ) {
  8509. this.updateWorldMatrix( true, false );
  8510. return target.setFromMatrixPosition( this.matrixWorld );
  8511. }
  8512. /**
  8513. * Returns a Quaternion representing the position of the 3D object in world space.
  8514. *
  8515. * @param {Quaternion} target - The target Quaternion the result is stored to.
  8516. * @return {Quaternion} The 3D object's rotation in world space.
  8517. */
  8518. getWorldQuaternion( target ) {
  8519. this.updateWorldMatrix( true, false );
  8520. this.matrixWorld.decompose( _position$3, target, _scale$2 );
  8521. return target;
  8522. }
  8523. /**
  8524. * Returns a vector representing the scale of the 3D object in world space.
  8525. *
  8526. * @param {Vector3} target - The target vector the result is stored to.
  8527. * @return {Vector3} The 3D object's scale in world space.
  8528. */
  8529. getWorldScale( target ) {
  8530. this.updateWorldMatrix( true, false );
  8531. this.matrixWorld.decompose( _position$3, _quaternion$2, target );
  8532. return target;
  8533. }
  8534. /**
  8535. * Returns a vector representing the ("look") direction of the 3D object in world space.
  8536. *
  8537. * @param {Vector3} target - The target vector the result is stored to.
  8538. * @return {Vector3} The 3D object's direction in world space.
  8539. */
  8540. getWorldDirection( target ) {
  8541. this.updateWorldMatrix( true, false );
  8542. const e = this.matrixWorld.elements;
  8543. return target.set( e[ 8 ], e[ 9 ], e[ 10 ] ).normalize();
  8544. }
  8545. /**
  8546. * Abstract method to get intersections between a casted ray and this
  8547. * 3D object. Renderable 3D objects such as {@link Mesh}, {@link Line} or {@link Points}
  8548. * implement this method in order to use raycasting.
  8549. *
  8550. * @abstract
  8551. * @param {Raycaster} raycaster - The raycaster.
  8552. * @param {Array<Object>} intersects - An array holding the result of the method.
  8553. */
  8554. raycast( /* raycaster, intersects */ ) {}
  8555. /**
  8556. * Executes the callback on this 3D object and all descendants.
  8557. *
  8558. * Note: Modifying the scene graph inside the callback is discouraged.
  8559. *
  8560. * @param {Function} callback - A callback function that allows to process the current 3D object.
  8561. */
  8562. traverse( callback ) {
  8563. callback( this );
  8564. const children = this.children;
  8565. for ( let i = 0, l = children.length; i < l; i ++ ) {
  8566. children[ i ].traverse( callback );
  8567. }
  8568. }
  8569. /**
  8570. * Like {@link Object3D#traverse}, but the callback will only be executed for visible 3D objects.
  8571. * Descendants of invisible 3D objects are not traversed.
  8572. *
  8573. * Note: Modifying the scene graph inside the callback is discouraged.
  8574. *
  8575. * @param {Function} callback - A callback function that allows to process the current 3D object.
  8576. */
  8577. traverseVisible( callback ) {
  8578. if ( this.visible === false ) return;
  8579. callback( this );
  8580. const children = this.children;
  8581. for ( let i = 0, l = children.length; i < l; i ++ ) {
  8582. children[ i ].traverseVisible( callback );
  8583. }
  8584. }
  8585. /**
  8586. * Like {@link Object3D#traverse}, but the callback will only be executed for all ancestors.
  8587. *
  8588. * Note: Modifying the scene graph inside the callback is discouraged.
  8589. *
  8590. * @param {Function} callback - A callback function that allows to process the current 3D object.
  8591. */
  8592. traverseAncestors( callback ) {
  8593. const parent = this.parent;
  8594. if ( parent !== null ) {
  8595. callback( parent );
  8596. parent.traverseAncestors( callback );
  8597. }
  8598. }
  8599. /**
  8600. * Updates the transformation matrix in local space by computing it from the current
  8601. * positon, rotation and scale values.
  8602. */
  8603. updateMatrix() {
  8604. this.matrix.compose( this.position, this.quaternion, this.scale );
  8605. this.matrixWorldNeedsUpdate = true;
  8606. }
  8607. /**
  8608. * Updates the transformation matrix in world space of this 3D objects and its descendants.
  8609. *
  8610. * To ensure correct results, this method also recomputes the 3D object's transformation matrix in
  8611. * local space. The computation of the local and world matrix can be controlled with the
  8612. * {@link Object3D#matrixAutoUpdate} and {@link Object3D#matrixWorldAutoUpdate} flags which are both
  8613. * `true` by default. Set these flags to `false` if you need more control over the update matrix process.
  8614. *
  8615. * @param {boolean} [force=false] - When set to `true`, a recomputation of world matrices is forced even
  8616. * when {@link Object3D#matrixWorldAutoUpdate} is set to `false`.
  8617. */
  8618. updateMatrixWorld( force ) {
  8619. if ( this.matrixAutoUpdate ) this.updateMatrix();
  8620. if ( this.matrixWorldNeedsUpdate || force ) {
  8621. if ( this.matrixWorldAutoUpdate === true ) {
  8622. if ( this.parent === null ) {
  8623. this.matrixWorld.copy( this.matrix );
  8624. } else {
  8625. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  8626. }
  8627. }
  8628. this.matrixWorldNeedsUpdate = false;
  8629. force = true;
  8630. }
  8631. // make sure descendants are updated if required
  8632. const children = this.children;
  8633. for ( let i = 0, l = children.length; i < l; i ++ ) {
  8634. const child = children[ i ];
  8635. child.updateMatrixWorld( force );
  8636. }
  8637. }
  8638. /**
  8639. * An alternative version of {@link Object3D#updateMatrixWorld} with more control over the
  8640. * update of ancestor and descendant nodes.
  8641. *
  8642. * @param {boolean} [updateParents=false] Whether ancestor nodes should be updated or not.
  8643. * @param {boolean} [updateChildren=false] Whether descendant nodes should be updated or not.
  8644. */
  8645. updateWorldMatrix( updateParents, updateChildren ) {
  8646. const parent = this.parent;
  8647. if ( updateParents === true && parent !== null ) {
  8648. parent.updateWorldMatrix( true, false );
  8649. }
  8650. if ( this.matrixAutoUpdate ) this.updateMatrix();
  8651. if ( this.matrixWorldAutoUpdate === true ) {
  8652. if ( this.parent === null ) {
  8653. this.matrixWorld.copy( this.matrix );
  8654. } else {
  8655. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  8656. }
  8657. }
  8658. // make sure descendants are updated
  8659. if ( updateChildren === true ) {
  8660. const children = this.children;
  8661. for ( let i = 0, l = children.length; i < l; i ++ ) {
  8662. const child = children[ i ];
  8663. child.updateWorldMatrix( false, true );
  8664. }
  8665. }
  8666. }
  8667. /**
  8668. * Serializes the 3D object into JSON.
  8669. *
  8670. * @param {?(Object|string)} meta - An optional value holding meta information about the serialization.
  8671. * @return {Object} A JSON object representing the serialized 3D object.
  8672. * @see {@link ObjectLoader#parse}
  8673. */
  8674. toJSON( meta ) {
  8675. // meta is a string when called from JSON.stringify
  8676. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  8677. const output = {};
  8678. // meta is a hash used to collect geometries, materials.
  8679. // not providing it implies that this is the root object
  8680. // being serialized.
  8681. if ( isRootObject ) {
  8682. // initialize meta obj
  8683. meta = {
  8684. geometries: {},
  8685. materials: {},
  8686. textures: {},
  8687. images: {},
  8688. shapes: {},
  8689. skeletons: {},
  8690. animations: {},
  8691. nodes: {}
  8692. };
  8693. output.metadata = {
  8694. version: 4.6,
  8695. type: 'Object',
  8696. generator: 'Object3D.toJSON'
  8697. };
  8698. }
  8699. // standard Object3D serialization
  8700. const object = {};
  8701. object.uuid = this.uuid;
  8702. object.type = this.type;
  8703. if ( this.name !== '' ) object.name = this.name;
  8704. if ( this.castShadow === true ) object.castShadow = true;
  8705. if ( this.receiveShadow === true ) object.receiveShadow = true;
  8706. if ( this.visible === false ) object.visible = false;
  8707. if ( this.frustumCulled === false ) object.frustumCulled = false;
  8708. if ( this.renderOrder !== 0 ) object.renderOrder = this.renderOrder;
  8709. if ( Object.keys( this.userData ).length > 0 ) object.userData = this.userData;
  8710. object.layers = this.layers.mask;
  8711. object.matrix = this.matrix.toArray();
  8712. object.up = this.up.toArray();
  8713. if ( this.matrixAutoUpdate === false ) object.matrixAutoUpdate = false;
  8714. // object specific properties
  8715. if ( this.isInstancedMesh ) {
  8716. object.type = 'InstancedMesh';
  8717. object.count = this.count;
  8718. object.instanceMatrix = this.instanceMatrix.toJSON();
  8719. if ( this.instanceColor !== null ) object.instanceColor = this.instanceColor.toJSON();
  8720. }
  8721. if ( this.isBatchedMesh ) {
  8722. object.type = 'BatchedMesh';
  8723. object.perObjectFrustumCulled = this.perObjectFrustumCulled;
  8724. object.sortObjects = this.sortObjects;
  8725. object.drawRanges = this._drawRanges;
  8726. object.reservedRanges = this._reservedRanges;
  8727. object.visibility = this._visibility;
  8728. object.active = this._active;
  8729. object.bounds = this._bounds.map( bound => ( {
  8730. boxInitialized: bound.boxInitialized,
  8731. boxMin: bound.box.min.toArray(),
  8732. boxMax: bound.box.max.toArray(),
  8733. sphereInitialized: bound.sphereInitialized,
  8734. sphereRadius: bound.sphere.radius,
  8735. sphereCenter: bound.sphere.center.toArray()
  8736. } ) );
  8737. object.maxInstanceCount = this._maxInstanceCount;
  8738. object.maxVertexCount = this._maxVertexCount;
  8739. object.maxIndexCount = this._maxIndexCount;
  8740. object.geometryInitialized = this._geometryInitialized;
  8741. object.geometryCount = this._geometryCount;
  8742. object.matricesTexture = this._matricesTexture.toJSON( meta );
  8743. if ( this._colorsTexture !== null ) object.colorsTexture = this._colorsTexture.toJSON( meta );
  8744. if ( this.boundingSphere !== null ) {
  8745. object.boundingSphere = {
  8746. center: object.boundingSphere.center.toArray(),
  8747. radius: object.boundingSphere.radius
  8748. };
  8749. }
  8750. if ( this.boundingBox !== null ) {
  8751. object.boundingBox = {
  8752. min: object.boundingBox.min.toArray(),
  8753. max: object.boundingBox.max.toArray()
  8754. };
  8755. }
  8756. }
  8757. //
  8758. function serialize( library, element ) {
  8759. if ( library[ element.uuid ] === undefined ) {
  8760. library[ element.uuid ] = element.toJSON( meta );
  8761. }
  8762. return element.uuid;
  8763. }
  8764. if ( this.isScene ) {
  8765. if ( this.background ) {
  8766. if ( this.background.isColor ) {
  8767. object.background = this.background.toJSON();
  8768. } else if ( this.background.isTexture ) {
  8769. object.background = this.background.toJSON( meta ).uuid;
  8770. }
  8771. }
  8772. if ( this.environment && this.environment.isTexture && this.environment.isRenderTargetTexture !== true ) {
  8773. object.environment = this.environment.toJSON( meta ).uuid;
  8774. }
  8775. } else if ( this.isMesh || this.isLine || this.isPoints ) {
  8776. object.geometry = serialize( meta.geometries, this.geometry );
  8777. const parameters = this.geometry.parameters;
  8778. if ( parameters !== undefined && parameters.shapes !== undefined ) {
  8779. const shapes = parameters.shapes;
  8780. if ( Array.isArray( shapes ) ) {
  8781. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  8782. const shape = shapes[ i ];
  8783. serialize( meta.shapes, shape );
  8784. }
  8785. } else {
  8786. serialize( meta.shapes, shapes );
  8787. }
  8788. }
  8789. }
  8790. if ( this.isSkinnedMesh ) {
  8791. object.bindMode = this.bindMode;
  8792. object.bindMatrix = this.bindMatrix.toArray();
  8793. if ( this.skeleton !== undefined ) {
  8794. serialize( meta.skeletons, this.skeleton );
  8795. object.skeleton = this.skeleton.uuid;
  8796. }
  8797. }
  8798. if ( this.material !== undefined ) {
  8799. if ( Array.isArray( this.material ) ) {
  8800. const uuids = [];
  8801. for ( let i = 0, l = this.material.length; i < l; i ++ ) {
  8802. uuids.push( serialize( meta.materials, this.material[ i ] ) );
  8803. }
  8804. object.material = uuids;
  8805. } else {
  8806. object.material = serialize( meta.materials, this.material );
  8807. }
  8808. }
  8809. //
  8810. if ( this.children.length > 0 ) {
  8811. object.children = [];
  8812. for ( let i = 0; i < this.children.length; i ++ ) {
  8813. object.children.push( this.children[ i ].toJSON( meta ).object );
  8814. }
  8815. }
  8816. //
  8817. if ( this.animations.length > 0 ) {
  8818. object.animations = [];
  8819. for ( let i = 0; i < this.animations.length; i ++ ) {
  8820. const animation = this.animations[ i ];
  8821. object.animations.push( serialize( meta.animations, animation ) );
  8822. }
  8823. }
  8824. if ( isRootObject ) {
  8825. const geometries = extractFromCache( meta.geometries );
  8826. const materials = extractFromCache( meta.materials );
  8827. const textures = extractFromCache( meta.textures );
  8828. const images = extractFromCache( meta.images );
  8829. const shapes = extractFromCache( meta.shapes );
  8830. const skeletons = extractFromCache( meta.skeletons );
  8831. const animations = extractFromCache( meta.animations );
  8832. const nodes = extractFromCache( meta.nodes );
  8833. if ( geometries.length > 0 ) output.geometries = geometries;
  8834. if ( materials.length > 0 ) output.materials = materials;
  8835. if ( textures.length > 0 ) output.textures = textures;
  8836. if ( images.length > 0 ) output.images = images;
  8837. if ( shapes.length > 0 ) output.shapes = shapes;
  8838. if ( skeletons.length > 0 ) output.skeletons = skeletons;
  8839. if ( animations.length > 0 ) output.animations = animations;
  8840. if ( nodes.length > 0 ) output.nodes = nodes;
  8841. }
  8842. output.object = object;
  8843. return output;
  8844. // extract data from the cache hash
  8845. // remove metadata on each item
  8846. // and return as array
  8847. function extractFromCache( cache ) {
  8848. const values = [];
  8849. for ( const key in cache ) {
  8850. const data = cache[ key ];
  8851. delete data.metadata;
  8852. values.push( data );
  8853. }
  8854. return values;
  8855. }
  8856. }
  8857. /**
  8858. * Returns a new 3D object with copied values from this instance.
  8859. *
  8860. * @param {boolean} [recursive=true] - When set to `true`, descendants of the 3D object are also cloned.
  8861. * @return {Object3D} A clone of this instance.
  8862. */
  8863. clone( recursive ) {
  8864. return new this.constructor().copy( this, recursive );
  8865. }
  8866. /**
  8867. * Copies the values of the given 3D object to this instance.
  8868. *
  8869. * @param {Object3D} source - The 3D object to copy.
  8870. * @param {boolean} [recursive=true] - When set to `true`, descendants of the 3D object are cloned.
  8871. * @return {Object3D} A reference to this instance.
  8872. */
  8873. copy( source, recursive = true ) {
  8874. this.name = source.name;
  8875. this.up.copy( source.up );
  8876. this.position.copy( source.position );
  8877. this.rotation.order = source.rotation.order;
  8878. this.quaternion.copy( source.quaternion );
  8879. this.scale.copy( source.scale );
  8880. this.matrix.copy( source.matrix );
  8881. this.matrixWorld.copy( source.matrixWorld );
  8882. this.matrixAutoUpdate = source.matrixAutoUpdate;
  8883. this.matrixWorldAutoUpdate = source.matrixWorldAutoUpdate;
  8884. this.matrixWorldNeedsUpdate = source.matrixWorldNeedsUpdate;
  8885. this.layers.mask = source.layers.mask;
  8886. this.visible = source.visible;
  8887. this.castShadow = source.castShadow;
  8888. this.receiveShadow = source.receiveShadow;
  8889. this.frustumCulled = source.frustumCulled;
  8890. this.renderOrder = source.renderOrder;
  8891. this.animations = source.animations.slice();
  8892. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  8893. if ( recursive === true ) {
  8894. for ( let i = 0; i < source.children.length; i ++ ) {
  8895. const child = source.children[ i ];
  8896. this.add( child.clone() );
  8897. }
  8898. }
  8899. return this;
  8900. }
  8901. }
  8902. /**
  8903. * The default up direction for objects, also used as the default
  8904. * position for {@link DirectionalLight} and {@link HemisphereLight}.
  8905. *
  8906. * @static
  8907. * @type {Vector3}
  8908. * @default (0,1,0)
  8909. */
  8910. Object3D.DEFAULT_UP = /*@__PURE__*/ new Vector3( 0, 1, 0 );
  8911. /**
  8912. * The default setting for {@link Object3D#matrixAutoUpdate} for
  8913. * newly created 3D objects.
  8914. *
  8915. * @static
  8916. * @type {boolean}
  8917. * @default true
  8918. */
  8919. Object3D.DEFAULT_MATRIX_AUTO_UPDATE = true;
  8920. /**
  8921. * The default setting for {@link Object3D#matrixWorldAutoUpdate} for
  8922. * newly created 3D objects.
  8923. *
  8924. * @static
  8925. * @type {boolean}
  8926. * @default true
  8927. */
  8928. Object3D.DEFAULT_MATRIX_WORLD_AUTO_UPDATE = true;
  8929. const _v0$1 = /*@__PURE__*/ new Vector3();
  8930. const _v1$3 = /*@__PURE__*/ new Vector3();
  8931. const _v2$2 = /*@__PURE__*/ new Vector3();
  8932. const _v3$2 = /*@__PURE__*/ new Vector3();
  8933. const _vab = /*@__PURE__*/ new Vector3();
  8934. const _vac = /*@__PURE__*/ new Vector3();
  8935. const _vbc = /*@__PURE__*/ new Vector3();
  8936. const _vap = /*@__PURE__*/ new Vector3();
  8937. const _vbp = /*@__PURE__*/ new Vector3();
  8938. const _vcp = /*@__PURE__*/ new Vector3();
  8939. const _v40 = /*@__PURE__*/ new Vector4();
  8940. const _v41 = /*@__PURE__*/ new Vector4();
  8941. const _v42 = /*@__PURE__*/ new Vector4();
  8942. /**
  8943. * A geometric triangle as defined by three vectors representing its three corners.
  8944. */
  8945. class Triangle {
  8946. /**
  8947. * Constructs a new triangle.
  8948. *
  8949. * @param {Vector3} [a=(0,0,0)] - The first corner of the triangle.
  8950. * @param {Vector3} [b=(0,0,0)] - The second corner of the triangle.
  8951. * @param {Vector3} [c=(0,0,0)] - The third corner of the triangle.
  8952. */
  8953. constructor( a = new Vector3(), b = new Vector3(), c = new Vector3() ) {
  8954. /**
  8955. * The first corner of the triangle.
  8956. *
  8957. * @type {Vector3}
  8958. */
  8959. this.a = a;
  8960. /**
  8961. * The second corner of the triangle.
  8962. *
  8963. * @type {Vector3}
  8964. */
  8965. this.b = b;
  8966. /**
  8967. * The third corner of the triangle.
  8968. *
  8969. * @type {Vector3}
  8970. */
  8971. this.c = c;
  8972. }
  8973. /**
  8974. * Computes the normal vector of a triangle.
  8975. *
  8976. * @param {Vector3} a - The first corner of the triangle.
  8977. * @param {Vector3} b - The second corner of the triangle.
  8978. * @param {Vector3} c - The third corner of the triangle.
  8979. * @param {Vector3} target - The target vector that is used to store the method's result.
  8980. * @return {Vector3} The triangle's normal.
  8981. */
  8982. static getNormal( a, b, c, target ) {
  8983. target.subVectors( c, b );
  8984. _v0$1.subVectors( a, b );
  8985. target.cross( _v0$1 );
  8986. const targetLengthSq = target.lengthSq();
  8987. if ( targetLengthSq > 0 ) {
  8988. return target.multiplyScalar( 1 / Math.sqrt( targetLengthSq ) );
  8989. }
  8990. return target.set( 0, 0, 0 );
  8991. }
  8992. /**
  8993. * Copmutes a barycentric coordinates from the given vector.
  8994. * Returns `null` if the triangle is degenerate.
  8995. *
  8996. * @param {Vector3} point - A point in 3D space.
  8997. * @param {Vector3} a - The first corner of the triangle.
  8998. * @param {Vector3} b - The second corner of the triangle.
  8999. * @param {Vector3} c - The third corner of the triangle.
  9000. * @param {Vector3} target - The target vector that is used to store the method's result.
  9001. * @return {?Vector3} The barycentric coordinates for the given point
  9002. */
  9003. static getBarycoord( point, a, b, c, target ) {
  9004. // based on: http://www.blackpawn.com/texts/pointinpoly/default.html
  9005. _v0$1.subVectors( c, a );
  9006. _v1$3.subVectors( b, a );
  9007. _v2$2.subVectors( point, a );
  9008. const dot00 = _v0$1.dot( _v0$1 );
  9009. const dot01 = _v0$1.dot( _v1$3 );
  9010. const dot02 = _v0$1.dot( _v2$2 );
  9011. const dot11 = _v1$3.dot( _v1$3 );
  9012. const dot12 = _v1$3.dot( _v2$2 );
  9013. const denom = ( dot00 * dot11 - dot01 * dot01 );
  9014. // collinear or singular triangle
  9015. if ( denom === 0 ) {
  9016. target.set( 0, 0, 0 );
  9017. return null;
  9018. }
  9019. const invDenom = 1 / denom;
  9020. const u = ( dot11 * dot02 - dot01 * dot12 ) * invDenom;
  9021. const v = ( dot00 * dot12 - dot01 * dot02 ) * invDenom;
  9022. // barycentric coordinates must always sum to 1
  9023. return target.set( 1 - u - v, v, u );
  9024. }
  9025. /**
  9026. * Returns `true` if the given point, when projected onto the plane of the
  9027. * triangle, lies within the triangle.
  9028. *
  9029. * @param {Vector3} point - The point in 3D space to test.
  9030. * @param {Vector3} a - The first corner of the triangle.
  9031. * @param {Vector3} b - The second corner of the triangle.
  9032. * @param {Vector3} c - The third corner of the triangle.
  9033. * @return {boolean} Whether the given point, when projected onto the plane of the
  9034. * triangle, lies within the triangle or not.
  9035. */
  9036. static containsPoint( point, a, b, c ) {
  9037. // if the triangle is degenerate then we can't contain a point
  9038. if ( this.getBarycoord( point, a, b, c, _v3$2 ) === null ) {
  9039. return false;
  9040. }
  9041. return ( _v3$2.x >= 0 ) && ( _v3$2.y >= 0 ) && ( ( _v3$2.x + _v3$2.y ) <= 1 );
  9042. }
  9043. /**
  9044. * Computes the value barycentrically interpolated for the given point on the
  9045. * triangle. Returns `null` if the triangle is degenerate.
  9046. *
  9047. * @param {Vector3} point - Position of interpolated point.
  9048. * @param {Vector3} p1 - The first corner of the triangle.
  9049. * @param {Vector3} p2 - The second corner of the triangle.
  9050. * @param {Vector3} p3 - The third corner of the triangle.
  9051. * @param {Vector3} v1 - Value to interpolate of first vertex.
  9052. * @param {Vector3} v2 - Value to interpolate of second vertex.
  9053. * @param {Vector3} v3 - Value to interpolate of third vertex.
  9054. * @param {Vector3} target - The target vector that is used to store the method's result.
  9055. * @return {?Vector3} The interpolated value.
  9056. */
  9057. static getInterpolation( point, p1, p2, p3, v1, v2, v3, target ) {
  9058. if ( this.getBarycoord( point, p1, p2, p3, _v3$2 ) === null ) {
  9059. target.x = 0;
  9060. target.y = 0;
  9061. if ( 'z' in target ) target.z = 0;
  9062. if ( 'w' in target ) target.w = 0;
  9063. return null;
  9064. }
  9065. target.setScalar( 0 );
  9066. target.addScaledVector( v1, _v3$2.x );
  9067. target.addScaledVector( v2, _v3$2.y );
  9068. target.addScaledVector( v3, _v3$2.z );
  9069. return target;
  9070. }
  9071. /**
  9072. * Computes the value barycentrically interpolated for the given attribute and indices.
  9073. *
  9074. * @param {BufferAttribute} attr - The attribute to interpolate.
  9075. * @param {number} i1 - Index of first vertex.
  9076. * @param {number} i2 - Index of second vertex.
  9077. * @param {number} i3 - Index of third vertex.
  9078. * @param {Vector3} barycoord - The barycoordinate value to use to interpolate.
  9079. * @param {Vector3} target - The target vector that is used to store the method's result.
  9080. * @return {Vector3} The interpolated attribute value.
  9081. */
  9082. static getInterpolatedAttribute( attr, i1, i2, i3, barycoord, target ) {
  9083. _v40.setScalar( 0 );
  9084. _v41.setScalar( 0 );
  9085. _v42.setScalar( 0 );
  9086. _v40.fromBufferAttribute( attr, i1 );
  9087. _v41.fromBufferAttribute( attr, i2 );
  9088. _v42.fromBufferAttribute( attr, i3 );
  9089. target.setScalar( 0 );
  9090. target.addScaledVector( _v40, barycoord.x );
  9091. target.addScaledVector( _v41, barycoord.y );
  9092. target.addScaledVector( _v42, barycoord.z );
  9093. return target;
  9094. }
  9095. /**
  9096. * Returns `true` if the triangle is oriented towards the given direction.
  9097. *
  9098. * @param {Vector3} a - The first corner of the triangle.
  9099. * @param {Vector3} b - The second corner of the triangle.
  9100. * @param {Vector3} c - The third corner of the triangle.
  9101. * @param {Vector3} direction - The (normalized) direction vector.
  9102. * @return {boolean} Whether the triangle is oriented towards the given direction or not.
  9103. */
  9104. static isFrontFacing( a, b, c, direction ) {
  9105. _v0$1.subVectors( c, b );
  9106. _v1$3.subVectors( a, b );
  9107. // strictly front facing
  9108. return ( _v0$1.cross( _v1$3 ).dot( direction ) < 0 ) ? true : false;
  9109. }
  9110. /**
  9111. * Sets the triangle's vertices by copying the given values.
  9112. *
  9113. * @param {Vector3} a - The first corner of the triangle.
  9114. * @param {Vector3} b - The second corner of the triangle.
  9115. * @param {Vector3} c - The third corner of the triangle.
  9116. * @return {Triangle} A reference to this triangle.
  9117. */
  9118. set( a, b, c ) {
  9119. this.a.copy( a );
  9120. this.b.copy( b );
  9121. this.c.copy( c );
  9122. return this;
  9123. }
  9124. /**
  9125. * Sets the triangle's vertices by copying the given array values.
  9126. *
  9127. * @param {Array<Vector3>} points - An array with 3D points.
  9128. * @param {number} i0 - The array index representing the first corner of the triangle.
  9129. * @param {number} i1 - The array index representing the second corner of the triangle.
  9130. * @param {number} i2 - The array index representing the third corner of the triangle.
  9131. * @return {Triangle} A reference to this triangle.
  9132. */
  9133. setFromPointsAndIndices( points, i0, i1, i2 ) {
  9134. this.a.copy( points[ i0 ] );
  9135. this.b.copy( points[ i1 ] );
  9136. this.c.copy( points[ i2 ] );
  9137. return this;
  9138. }
  9139. /**
  9140. * Sets the triangle's vertices by copying the given attribute values.
  9141. *
  9142. * @param {BufferAttribute} attribute - A buffer attribute with 3D points data.
  9143. * @param {number} i0 - The attribute index representing the first corner of the triangle.
  9144. * @param {number} i1 - The attribute index representing the second corner of the triangle.
  9145. * @param {number} i2 - The attribute index representing the third corner of the triangle.
  9146. * @return {Triangle} A reference to this triangle.
  9147. */
  9148. setFromAttributeAndIndices( attribute, i0, i1, i2 ) {
  9149. this.a.fromBufferAttribute( attribute, i0 );
  9150. this.b.fromBufferAttribute( attribute, i1 );
  9151. this.c.fromBufferAttribute( attribute, i2 );
  9152. return this;
  9153. }
  9154. /**
  9155. * Returns a new triangle with copied values from this instance.
  9156. *
  9157. * @return {Triangle} A clone of this instance.
  9158. */
  9159. clone() {
  9160. return new this.constructor().copy( this );
  9161. }
  9162. /**
  9163. * Copies the values of the given triangle to this instance.
  9164. *
  9165. * @param {Triangle} triangle - The triangle to copy.
  9166. * @return {Triangle} A reference to this triangle.
  9167. */
  9168. copy( triangle ) {
  9169. this.a.copy( triangle.a );
  9170. this.b.copy( triangle.b );
  9171. this.c.copy( triangle.c );
  9172. return this;
  9173. }
  9174. /**
  9175. * Computes the area of the triangle.
  9176. *
  9177. * @return {number} The triangle's area.
  9178. */
  9179. getArea() {
  9180. _v0$1.subVectors( this.c, this.b );
  9181. _v1$3.subVectors( this.a, this.b );
  9182. return _v0$1.cross( _v1$3 ).length() * 0.5;
  9183. }
  9184. /**
  9185. * Computes the midpoint of the triangle.
  9186. *
  9187. * @param {Vector3} target - The target vector that is used to store the method's result.
  9188. * @return {Vector3} The triangle's midpoint.
  9189. */
  9190. getMidpoint( target ) {
  9191. return target.addVectors( this.a, this.b ).add( this.c ).multiplyScalar( 1 / 3 );
  9192. }
  9193. /**
  9194. * Computes the normal of the triangle.
  9195. *
  9196. * @param {Vector3} target - The target vector that is used to store the method's result.
  9197. * @return {Vector3} The triangle's normal.
  9198. */
  9199. getNormal( target ) {
  9200. return Triangle.getNormal( this.a, this.b, this.c, target );
  9201. }
  9202. /**
  9203. * Computes a plane the triangle lies within.
  9204. *
  9205. * @param {Plane} target - The target vector that is used to store the method's result.
  9206. * @return {Plane} The plane the triangle lies within.
  9207. */
  9208. getPlane( target ) {
  9209. return target.setFromCoplanarPoints( this.a, this.b, this.c );
  9210. }
  9211. /**
  9212. * Copmutes a barycentric coordinates from the given vector.
  9213. * Returns `null` if the triangle is degenerate.
  9214. *
  9215. * @param {Vector3} point - A point in 3D space.
  9216. * @param {Vector3} target - The target vector that is used to store the method's result.
  9217. * @return {?Vector3} The barycentric coordinates for the given point
  9218. */
  9219. getBarycoord( point, target ) {
  9220. return Triangle.getBarycoord( point, this.a, this.b, this.c, target );
  9221. }
  9222. /**
  9223. * Computes the value barycentrically interpolated for the given point on the
  9224. * triangle. Returns `null` if the triangle is degenerate.
  9225. *
  9226. * @param {Vector3} point - Position of interpolated point.
  9227. * @param {Vector3} v1 - Value to interpolate of first vertex.
  9228. * @param {Vector3} v2 - Value to interpolate of second vertex.
  9229. * @param {Vector3} v3 - Value to interpolate of third vertex.
  9230. * @param {Vector3} target - The target vector that is used to store the method's result.
  9231. * @return {?Vector3} The interpolated value.
  9232. */
  9233. getInterpolation( point, v1, v2, v3, target ) {
  9234. return Triangle.getInterpolation( point, this.a, this.b, this.c, v1, v2, v3, target );
  9235. }
  9236. /**
  9237. * Returns `true` if the given point, when projected onto the plane of the
  9238. * triangle, lies within the triangle.
  9239. *
  9240. * @param {Vector3} point - The point in 3D space to test.
  9241. * @return {boolean} Whether the given point, when projected onto the plane of the
  9242. * triangle, lies within the triangle or not.
  9243. */
  9244. containsPoint( point ) {
  9245. return Triangle.containsPoint( point, this.a, this.b, this.c );
  9246. }
  9247. /**
  9248. * Returns `true` if the triangle is oriented towards the given direction.
  9249. *
  9250. * @param {Vector3} direction - The (normalized) direction vector.
  9251. * @return {boolean} Whether the triangle is oriented towards the given direction or not.
  9252. */
  9253. isFrontFacing( direction ) {
  9254. return Triangle.isFrontFacing( this.a, this.b, this.c, direction );
  9255. }
  9256. /**
  9257. * Returns `true` if this triangle intersects with the given box.
  9258. *
  9259. * @param {Box3} box - The box to intersect.
  9260. * @return {boolean} Whether this triangle intersects with the given box or not.
  9261. */
  9262. intersectsBox( box ) {
  9263. return box.intersectsTriangle( this );
  9264. }
  9265. /**
  9266. * Returns the closest point on the triangle to the given point.
  9267. *
  9268. * @param {Vector3} p - The point to compute the closest point for.
  9269. * @param {Vector3} target - The target vector that is used to store the method's result.
  9270. * @return {Vector3} The closest point on the triangle.
  9271. */
  9272. closestPointToPoint( p, target ) {
  9273. const a = this.a, b = this.b, c = this.c;
  9274. let v, w;
  9275. // algorithm thanks to Real-Time Collision Detection by Christer Ericson,
  9276. // published by Morgan Kaufmann Publishers, (c) 2005 Elsevier Inc.,
  9277. // under the accompanying license; see chapter 5.1.5 for detailed explanation.
  9278. // basically, we're distinguishing which of the voronoi regions of the triangle
  9279. // the point lies in with the minimum amount of redundant computation.
  9280. _vab.subVectors( b, a );
  9281. _vac.subVectors( c, a );
  9282. _vap.subVectors( p, a );
  9283. const d1 = _vab.dot( _vap );
  9284. const d2 = _vac.dot( _vap );
  9285. if ( d1 <= 0 && d2 <= 0 ) {
  9286. // vertex region of A; barycentric coords (1, 0, 0)
  9287. return target.copy( a );
  9288. }
  9289. _vbp.subVectors( p, b );
  9290. const d3 = _vab.dot( _vbp );
  9291. const d4 = _vac.dot( _vbp );
  9292. if ( d3 >= 0 && d4 <= d3 ) {
  9293. // vertex region of B; barycentric coords (0, 1, 0)
  9294. return target.copy( b );
  9295. }
  9296. const vc = d1 * d4 - d3 * d2;
  9297. if ( vc <= 0 && d1 >= 0 && d3 <= 0 ) {
  9298. v = d1 / ( d1 - d3 );
  9299. // edge region of AB; barycentric coords (1-v, v, 0)
  9300. return target.copy( a ).addScaledVector( _vab, v );
  9301. }
  9302. _vcp.subVectors( p, c );
  9303. const d5 = _vab.dot( _vcp );
  9304. const d6 = _vac.dot( _vcp );
  9305. if ( d6 >= 0 && d5 <= d6 ) {
  9306. // vertex region of C; barycentric coords (0, 0, 1)
  9307. return target.copy( c );
  9308. }
  9309. const vb = d5 * d2 - d1 * d6;
  9310. if ( vb <= 0 && d2 >= 0 && d6 <= 0 ) {
  9311. w = d2 / ( d2 - d6 );
  9312. // edge region of AC; barycentric coords (1-w, 0, w)
  9313. return target.copy( a ).addScaledVector( _vac, w );
  9314. }
  9315. const va = d3 * d6 - d5 * d4;
  9316. if ( va <= 0 && ( d4 - d3 ) >= 0 && ( d5 - d6 ) >= 0 ) {
  9317. _vbc.subVectors( c, b );
  9318. w = ( d4 - d3 ) / ( ( d4 - d3 ) + ( d5 - d6 ) );
  9319. // edge region of BC; barycentric coords (0, 1-w, w)
  9320. return target.copy( b ).addScaledVector( _vbc, w ); // edge region of BC
  9321. }
  9322. // face region
  9323. const denom = 1 / ( va + vb + vc );
  9324. // u = va * denom
  9325. v = vb * denom;
  9326. w = vc * denom;
  9327. return target.copy( a ).addScaledVector( _vab, v ).addScaledVector( _vac, w );
  9328. }
  9329. /**
  9330. * Returns `true` if this triangle is equal with the given one.
  9331. *
  9332. * @param {Triangle} triangle - The triangle to test for equality.
  9333. * @return {boolean} Whether this triangle is equal with the given one.
  9334. */
  9335. equals( triangle ) {
  9336. return triangle.a.equals( this.a ) && triangle.b.equals( this.b ) && triangle.c.equals( this.c );
  9337. }
  9338. }
  9339. const _colorKeywords = { 'aliceblue': 0xF0F8FF, 'antiquewhite': 0xFAEBD7, 'aqua': 0x00FFFF, 'aquamarine': 0x7FFFD4, 'azure': 0xF0FFFF,
  9340. 'beige': 0xF5F5DC, 'bisque': 0xFFE4C4, 'black': 0x000000, 'blanchedalmond': 0xFFEBCD, 'blue': 0x0000FF, 'blueviolet': 0x8A2BE2,
  9341. 'brown': 0xA52A2A, 'burlywood': 0xDEB887, 'cadetblue': 0x5F9EA0, 'chartreuse': 0x7FFF00, 'chocolate': 0xD2691E, 'coral': 0xFF7F50,
  9342. 'cornflowerblue': 0x6495ED, 'cornsilk': 0xFFF8DC, 'crimson': 0xDC143C, 'cyan': 0x00FFFF, 'darkblue': 0x00008B, 'darkcyan': 0x008B8B,
  9343. 'darkgoldenrod': 0xB8860B, 'darkgray': 0xA9A9A9, 'darkgreen': 0x006400, 'darkgrey': 0xA9A9A9, 'darkkhaki': 0xBDB76B, 'darkmagenta': 0x8B008B,
  9344. 'darkolivegreen': 0x556B2F, 'darkorange': 0xFF8C00, 'darkorchid': 0x9932CC, 'darkred': 0x8B0000, 'darksalmon': 0xE9967A, 'darkseagreen': 0x8FBC8F,
  9345. 'darkslateblue': 0x483D8B, 'darkslategray': 0x2F4F4F, 'darkslategrey': 0x2F4F4F, 'darkturquoise': 0x00CED1, 'darkviolet': 0x9400D3,
  9346. 'deeppink': 0xFF1493, 'deepskyblue': 0x00BFFF, 'dimgray': 0x696969, 'dimgrey': 0x696969, 'dodgerblue': 0x1E90FF, 'firebrick': 0xB22222,
  9347. 'floralwhite': 0xFFFAF0, 'forestgreen': 0x228B22, 'fuchsia': 0xFF00FF, 'gainsboro': 0xDCDCDC, 'ghostwhite': 0xF8F8FF, 'gold': 0xFFD700,
  9348. 'goldenrod': 0xDAA520, 'gray': 0x808080, 'green': 0x008000, 'greenyellow': 0xADFF2F, 'grey': 0x808080, 'honeydew': 0xF0FFF0, 'hotpink': 0xFF69B4,
  9349. 'indianred': 0xCD5C5C, 'indigo': 0x4B0082, 'ivory': 0xFFFFF0, 'khaki': 0xF0E68C, 'lavender': 0xE6E6FA, 'lavenderblush': 0xFFF0F5, 'lawngreen': 0x7CFC00,
  9350. 'lemonchiffon': 0xFFFACD, 'lightblue': 0xADD8E6, 'lightcoral': 0xF08080, 'lightcyan': 0xE0FFFF, 'lightgoldenrodyellow': 0xFAFAD2, 'lightgray': 0xD3D3D3,
  9351. 'lightgreen': 0x90EE90, 'lightgrey': 0xD3D3D3, 'lightpink': 0xFFB6C1, 'lightsalmon': 0xFFA07A, 'lightseagreen': 0x20B2AA, 'lightskyblue': 0x87CEFA,
  9352. 'lightslategray': 0x778899, 'lightslategrey': 0x778899, 'lightsteelblue': 0xB0C4DE, 'lightyellow': 0xFFFFE0, 'lime': 0x00FF00, 'limegreen': 0x32CD32,
  9353. 'linen': 0xFAF0E6, 'magenta': 0xFF00FF, 'maroon': 0x800000, 'mediumaquamarine': 0x66CDAA, 'mediumblue': 0x0000CD, 'mediumorchid': 0xBA55D3,
  9354. 'mediumpurple': 0x9370DB, 'mediumseagreen': 0x3CB371, 'mediumslateblue': 0x7B68EE, 'mediumspringgreen': 0x00FA9A, 'mediumturquoise': 0x48D1CC,
  9355. 'mediumvioletred': 0xC71585, 'midnightblue': 0x191970, 'mintcream': 0xF5FFFA, 'mistyrose': 0xFFE4E1, 'moccasin': 0xFFE4B5, 'navajowhite': 0xFFDEAD,
  9356. 'navy': 0x000080, 'oldlace': 0xFDF5E6, 'olive': 0x808000, 'olivedrab': 0x6B8E23, 'orange': 0xFFA500, 'orangered': 0xFF4500, 'orchid': 0xDA70D6,
  9357. 'palegoldenrod': 0xEEE8AA, 'palegreen': 0x98FB98, 'paleturquoise': 0xAFEEEE, 'palevioletred': 0xDB7093, 'papayawhip': 0xFFEFD5, 'peachpuff': 0xFFDAB9,
  9358. 'peru': 0xCD853F, 'pink': 0xFFC0CB, 'plum': 0xDDA0DD, 'powderblue': 0xB0E0E6, 'purple': 0x800080, 'rebeccapurple': 0x663399, 'red': 0xFF0000, 'rosybrown': 0xBC8F8F,
  9359. 'royalblue': 0x4169E1, 'saddlebrown': 0x8B4513, 'salmon': 0xFA8072, 'sandybrown': 0xF4A460, 'seagreen': 0x2E8B57, 'seashell': 0xFFF5EE,
  9360. 'sienna': 0xA0522D, 'silver': 0xC0C0C0, 'skyblue': 0x87CEEB, 'slateblue': 0x6A5ACD, 'slategray': 0x708090, 'slategrey': 0x708090, 'snow': 0xFFFAFA,
  9361. 'springgreen': 0x00FF7F, 'steelblue': 0x4682B4, 'tan': 0xD2B48C, 'teal': 0x008080, 'thistle': 0xD8BFD8, 'tomato': 0xFF6347, 'turquoise': 0x40E0D0,
  9362. 'violet': 0xEE82EE, 'wheat': 0xF5DEB3, 'white': 0xFFFFFF, 'whitesmoke': 0xF5F5F5, 'yellow': 0xFFFF00, 'yellowgreen': 0x9ACD32 };
  9363. const _hslA = { h: 0, s: 0, l: 0 };
  9364. const _hslB = { h: 0, s: 0, l: 0 };
  9365. function hue2rgb( p, q, t ) {
  9366. if ( t < 0 ) t += 1;
  9367. if ( t > 1 ) t -= 1;
  9368. if ( t < 1 / 6 ) return p + ( q - p ) * 6 * t;
  9369. if ( t < 1 / 2 ) return q;
  9370. if ( t < 2 / 3 ) return p + ( q - p ) * 6 * ( 2 / 3 - t );
  9371. return p;
  9372. }
  9373. /**
  9374. * A Color instance is represented by RGB components in the linear <i>working
  9375. * color space</i>, which defaults to `LinearSRGBColorSpace`. Inputs
  9376. * conventionally using `SRGBColorSpace` (such as hexadecimals and CSS
  9377. * strings) are converted to the working color space automatically.
  9378. *
  9379. * ```js
  9380. * // converted automatically from SRGBColorSpace to LinearSRGBColorSpace
  9381. * const color = new THREE.Color().setHex( 0x112233 );
  9382. * ```
  9383. * Source color spaces may be specified explicitly, to ensure correct conversions.
  9384. * ```js
  9385. * // assumed already LinearSRGBColorSpace; no conversion
  9386. * const color = new THREE.Color().setRGB( 0.5, 0.5, 0.5 );
  9387. *
  9388. * // converted explicitly from SRGBColorSpace to LinearSRGBColorSpace
  9389. * const color = new THREE.Color().setRGB( 0.5, 0.5, 0.5, SRGBColorSpace );
  9390. * ```
  9391. * If THREE.ColorManagement is disabled, no conversions occur. For details,
  9392. * see <i>Color management</i>. Iterating through a Color instance will yield
  9393. * its components (r, g, b) in the corresponding order. A Color can be initialised
  9394. * in any of the following ways:
  9395. * ```js
  9396. * //empty constructor - will default white
  9397. * const color1 = new THREE.Color();
  9398. *
  9399. * //Hexadecimal color (recommended)
  9400. * const color2 = new THREE.Color( 0xff0000 );
  9401. *
  9402. * //RGB string
  9403. * const color3 = new THREE.Color("rgb(255, 0, 0)");
  9404. * const color4 = new THREE.Color("rgb(100%, 0%, 0%)");
  9405. *
  9406. * //X11 color name - all 140 color names are supported.
  9407. * //Note the lack of CamelCase in the name
  9408. * const color5 = new THREE.Color( 'skyblue' );
  9409. * //HSL string
  9410. * const color6 = new THREE.Color("hsl(0, 100%, 50%)");
  9411. *
  9412. * //Separate RGB values between 0 and 1
  9413. * const color7 = new THREE.Color( 1, 0, 0 );
  9414. * ```
  9415. */
  9416. class Color {
  9417. /**
  9418. * Constructs a new color.
  9419. *
  9420. * Note that standard method of specifying color in three.js is with a hexadecimal triplet,
  9421. * and that method is used throughout the rest of the documentation.
  9422. *
  9423. * @param {(number|string|Color)} [r] - The red component of the color. If `g` and `b` are
  9424. * not provided, it can be hexadecimal triplet, a CSS-style string or another `Color` instance.
  9425. * @param {number} [g] - The green component.
  9426. * @param {number} [b] - The blue component.
  9427. */
  9428. constructor( r, g, b ) {
  9429. /**
  9430. * This flag can be used for type testing.
  9431. *
  9432. * @type {boolean}
  9433. * @readonly
  9434. * @default true
  9435. */
  9436. this.isColor = true;
  9437. /**
  9438. * The red component.
  9439. *
  9440. * @type {number}
  9441. * @default 1
  9442. */
  9443. this.r = 1;
  9444. /**
  9445. * The green component.
  9446. *
  9447. * @type {number}
  9448. * @default 1
  9449. */
  9450. this.g = 1;
  9451. /**
  9452. * The blue component.
  9453. *
  9454. * @type {number}
  9455. * @default 1
  9456. */
  9457. this.b = 1;
  9458. return this.set( r, g, b );
  9459. }
  9460. /**
  9461. * Sets the colors's components from the given values.
  9462. *
  9463. * @param {(number|string|Color)} [r] - The red component of the color. If `g` and `b` are
  9464. * not provided, it can be hexadecimal triplet, a CSS-style string or another `Color` instance.
  9465. * @param {number} [g] - The green component.
  9466. * @param {number} [b] - The blue component.
  9467. * @return {Color} A reference to this color.
  9468. */
  9469. set( r, g, b ) {
  9470. if ( g === undefined && b === undefined ) {
  9471. // r is THREE.Color, hex or string
  9472. const value = r;
  9473. if ( value && value.isColor ) {
  9474. this.copy( value );
  9475. } else if ( typeof value === 'number' ) {
  9476. this.setHex( value );
  9477. } else if ( typeof value === 'string' ) {
  9478. this.setStyle( value );
  9479. }
  9480. } else {
  9481. this.setRGB( r, g, b );
  9482. }
  9483. return this;
  9484. }
  9485. /**
  9486. * Sets the colors's components to the given scalar value.
  9487. *
  9488. * @param {number} scalar - The scalar value.
  9489. * @return {Color} A reference to this color.
  9490. */
  9491. setScalar( scalar ) {
  9492. this.r = scalar;
  9493. this.g = scalar;
  9494. this.b = scalar;
  9495. return this;
  9496. }
  9497. /**
  9498. * Sets this color from a hexadecimal value.
  9499. *
  9500. * @param {number} hex - The hexadecimal value.
  9501. * @param {string} [colorSpace=SRGBColorSpace] - The color space.
  9502. * @return {Color} A reference to this color.
  9503. */
  9504. setHex( hex, colorSpace = SRGBColorSpace ) {
  9505. hex = Math.floor( hex );
  9506. this.r = ( hex >> 16 & 255 ) / 255;
  9507. this.g = ( hex >> 8 & 255 ) / 255;
  9508. this.b = ( hex & 255 ) / 255;
  9509. ColorManagement.toWorkingColorSpace( this, colorSpace );
  9510. return this;
  9511. }
  9512. /**
  9513. * Sets this color from RGB values.
  9514. *
  9515. * @param {number} r - Red channel value between `0.0` and `1.0`.
  9516. * @param {number} g - Green channel value between `0.0` and `1.0`.
  9517. * @param {number} b - Blue channel value between `0.0` and `1.0`.
  9518. * @param {string} [colorSpace=ColorManagement.workingColorSpace] - The color space.
  9519. * @return {Color} A reference to this color.
  9520. */
  9521. setRGB( r, g, b, colorSpace = ColorManagement.workingColorSpace ) {
  9522. this.r = r;
  9523. this.g = g;
  9524. this.b = b;
  9525. ColorManagement.toWorkingColorSpace( this, colorSpace );
  9526. return this;
  9527. }
  9528. /**
  9529. * Sets this color from RGB values.
  9530. *
  9531. * @param {number} h - Hue value between `0.0` and `1.0`.
  9532. * @param {number} s - Saturation value between `0.0` and `1.0`.
  9533. * @param {number} l - Lightness value between `0.0` and `1.0`.
  9534. * @param {string} [colorSpace=ColorManagement.workingColorSpace] - The color space.
  9535. * @return {Color} A reference to this color.
  9536. */
  9537. setHSL( h, s, l, colorSpace = ColorManagement.workingColorSpace ) {
  9538. // h,s,l ranges are in 0.0 - 1.0
  9539. h = euclideanModulo( h, 1 );
  9540. s = clamp( s, 0, 1 );
  9541. l = clamp( l, 0, 1 );
  9542. if ( s === 0 ) {
  9543. this.r = this.g = this.b = l;
  9544. } else {
  9545. const p = l <= 0.5 ? l * ( 1 + s ) : l + s - ( l * s );
  9546. const q = ( 2 * l ) - p;
  9547. this.r = hue2rgb( q, p, h + 1 / 3 );
  9548. this.g = hue2rgb( q, p, h );
  9549. this.b = hue2rgb( q, p, h - 1 / 3 );
  9550. }
  9551. ColorManagement.toWorkingColorSpace( this, colorSpace );
  9552. return this;
  9553. }
  9554. /**
  9555. * Sets this color from a CSS-style string. For example, `rgb(250, 0,0)`,
  9556. * `rgb(100%, 0%, 0%)`, `hsl(0, 100%, 50%)`, `#ff0000`, `#f00`, or `red` ( or
  9557. * any [X11 color name]{@link https://en.wikipedia.org/wiki/X11_color_names#Color_name_chart} -
  9558. * all 140 color names are supported).
  9559. *
  9560. * @param {string} style - Color as a CSS-style string.
  9561. * @param {string} [colorSpace=SRGBColorSpace] - The color space.
  9562. * @return {Color} A reference to this color.
  9563. */
  9564. setStyle( style, colorSpace = SRGBColorSpace ) {
  9565. function handleAlpha( string ) {
  9566. if ( string === undefined ) return;
  9567. if ( parseFloat( string ) < 1 ) {
  9568. console.warn( 'THREE.Color: Alpha component of ' + style + ' will be ignored.' );
  9569. }
  9570. }
  9571. let m;
  9572. if ( m = /^(\w+)\(([^\)]*)\)/.exec( style ) ) {
  9573. // rgb / hsl
  9574. let color;
  9575. const name = m[ 1 ];
  9576. const components = m[ 2 ];
  9577. switch ( name ) {
  9578. case 'rgb':
  9579. case 'rgba':
  9580. if ( color = /^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) {
  9581. // rgb(255,0,0) rgba(255,0,0,0.5)
  9582. handleAlpha( color[ 4 ] );
  9583. return this.setRGB(
  9584. Math.min( 255, parseInt( color[ 1 ], 10 ) ) / 255,
  9585. Math.min( 255, parseInt( color[ 2 ], 10 ) ) / 255,
  9586. Math.min( 255, parseInt( color[ 3 ], 10 ) ) / 255,
  9587. colorSpace
  9588. );
  9589. }
  9590. if ( color = /^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) {
  9591. // rgb(100%,0%,0%) rgba(100%,0%,0%,0.5)
  9592. handleAlpha( color[ 4 ] );
  9593. return this.setRGB(
  9594. Math.min( 100, parseInt( color[ 1 ], 10 ) ) / 100,
  9595. Math.min( 100, parseInt( color[ 2 ], 10 ) ) / 100,
  9596. Math.min( 100, parseInt( color[ 3 ], 10 ) ) / 100,
  9597. colorSpace
  9598. );
  9599. }
  9600. break;
  9601. case 'hsl':
  9602. case 'hsla':
  9603. if ( color = /^\s*(\d*\.?\d+)\s*,\s*(\d*\.?\d+)\%\s*,\s*(\d*\.?\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) {
  9604. // hsl(120,50%,50%) hsla(120,50%,50%,0.5)
  9605. handleAlpha( color[ 4 ] );
  9606. return this.setHSL(
  9607. parseFloat( color[ 1 ] ) / 360,
  9608. parseFloat( color[ 2 ] ) / 100,
  9609. parseFloat( color[ 3 ] ) / 100,
  9610. colorSpace
  9611. );
  9612. }
  9613. break;
  9614. default:
  9615. console.warn( 'THREE.Color: Unknown color model ' + style );
  9616. }
  9617. } else if ( m = /^\#([A-Fa-f\d]+)$/.exec( style ) ) {
  9618. // hex color
  9619. const hex = m[ 1 ];
  9620. const size = hex.length;
  9621. if ( size === 3 ) {
  9622. // #ff0
  9623. return this.setRGB(
  9624. parseInt( hex.charAt( 0 ), 16 ) / 15,
  9625. parseInt( hex.charAt( 1 ), 16 ) / 15,
  9626. parseInt( hex.charAt( 2 ), 16 ) / 15,
  9627. colorSpace
  9628. );
  9629. } else if ( size === 6 ) {
  9630. // #ff0000
  9631. return this.setHex( parseInt( hex, 16 ), colorSpace );
  9632. } else {
  9633. console.warn( 'THREE.Color: Invalid hex color ' + style );
  9634. }
  9635. } else if ( style && style.length > 0 ) {
  9636. return this.setColorName( style, colorSpace );
  9637. }
  9638. return this;
  9639. }
  9640. /**
  9641. * Sets this color from a color name. Faster than {@link Color#setStyle} if
  9642. * you don't need the other CSS-style formats.
  9643. *
  9644. * For convenience, the list of names is exposed in `Color.NAMES` as a hash.
  9645. * ```js
  9646. * Color.NAMES.aliceblue // returns 0xF0F8FF
  9647. * ```
  9648. *
  9649. * @param {string} style - The color name.
  9650. * @param {string} [colorSpace=SRGBColorSpace] - The color space.
  9651. * @return {Color} A reference to this color.
  9652. */
  9653. setColorName( style, colorSpace = SRGBColorSpace ) {
  9654. // color keywords
  9655. const hex = _colorKeywords[ style.toLowerCase() ];
  9656. if ( hex !== undefined ) {
  9657. // red
  9658. this.setHex( hex, colorSpace );
  9659. } else {
  9660. // unknown color
  9661. console.warn( 'THREE.Color: Unknown color ' + style );
  9662. }
  9663. return this;
  9664. }
  9665. /**
  9666. * Returns a new color with copied values from this instance.
  9667. *
  9668. * @return {Color} A clone of this instance.
  9669. */
  9670. clone() {
  9671. return new this.constructor( this.r, this.g, this.b );
  9672. }
  9673. /**
  9674. * Copies the values of the given color to this instance.
  9675. *
  9676. * @param {Color} color - The color to copy.
  9677. * @return {Color} A reference to this color.
  9678. */
  9679. copy( color ) {
  9680. this.r = color.r;
  9681. this.g = color.g;
  9682. this.b = color.b;
  9683. return this;
  9684. }
  9685. /**
  9686. * Copies the given color into this color, and then converts this color from
  9687. * `SRGBColorSpace` to `LinearSRGBColorSpace`.
  9688. *
  9689. * @param {Color} color - The color to copy/convert.
  9690. * @return {Color} A reference to this color.
  9691. */
  9692. copySRGBToLinear( color ) {
  9693. this.r = SRGBToLinear( color.r );
  9694. this.g = SRGBToLinear( color.g );
  9695. this.b = SRGBToLinear( color.b );
  9696. return this;
  9697. }
  9698. /**
  9699. * Copies the given color into this color, and then converts this color from
  9700. * `LinearSRGBColorSpace` to `SRGBColorSpace`.
  9701. *
  9702. * @param {Color} color - The color to copy/convert.
  9703. * @return {Color} A reference to this color.
  9704. */
  9705. copyLinearToSRGB( color ) {
  9706. this.r = LinearToSRGB( color.r );
  9707. this.g = LinearToSRGB( color.g );
  9708. this.b = LinearToSRGB( color.b );
  9709. return this;
  9710. }
  9711. /**
  9712. * Converts this color from `SRGBColorSpace` to `LinearSRGBColorSpace`.
  9713. *
  9714. * @return {Color} A reference to this color.
  9715. */
  9716. convertSRGBToLinear() {
  9717. this.copySRGBToLinear( this );
  9718. return this;
  9719. }
  9720. /**
  9721. * Converts this color from `LinearSRGBColorSpace` to `SRGBColorSpace`.
  9722. *
  9723. * @return {Color} A reference to this color.
  9724. */
  9725. convertLinearToSRGB() {
  9726. this.copyLinearToSRGB( this );
  9727. return this;
  9728. }
  9729. /**
  9730. * Returns the hexadecimal value of this color.
  9731. *
  9732. * @param {string} [colorSpace=SRGBColorSpace] - The color space.
  9733. * @return {number} The hexadecimal value.
  9734. */
  9735. getHex( colorSpace = SRGBColorSpace ) {
  9736. ColorManagement.fromWorkingColorSpace( _color.copy( this ), colorSpace );
  9737. 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 ) );
  9738. }
  9739. /**
  9740. * Returns the hexadecimal value of this color as a string (for example, 'FFFFFF').
  9741. *
  9742. * @param {string} [colorSpace=SRGBColorSpace] - The color space.
  9743. * @return {string} The hexadecimal value as a string.
  9744. */
  9745. getHexString( colorSpace = SRGBColorSpace ) {
  9746. return ( '000000' + this.getHex( colorSpace ).toString( 16 ) ).slice( -6 );
  9747. }
  9748. /**
  9749. * Converts the colors RGB values into the HSL format and stores them into the
  9750. * given target object.
  9751. *
  9752. * @param {{h:0,s:0,l:0}} target - The target object that is used to store the method's result.
  9753. * @param {string} [colorSpace=ColorManagement.workingColorSpace] - The color space.
  9754. * @return {{h:0,s:0,l:0}} The HSL representation of this color.
  9755. */
  9756. getHSL( target, colorSpace = ColorManagement.workingColorSpace ) {
  9757. // h,s,l ranges are in 0.0 - 1.0
  9758. ColorManagement.fromWorkingColorSpace( _color.copy( this ), colorSpace );
  9759. const r = _color.r, g = _color.g, b = _color.b;
  9760. const max = Math.max( r, g, b );
  9761. const min = Math.min( r, g, b );
  9762. let hue, saturation;
  9763. const lightness = ( min + max ) / 2.0;
  9764. if ( min === max ) {
  9765. hue = 0;
  9766. saturation = 0;
  9767. } else {
  9768. const delta = max - min;
  9769. saturation = lightness <= 0.5 ? delta / ( max + min ) : delta / ( 2 - max - min );
  9770. switch ( max ) {
  9771. case r: hue = ( g - b ) / delta + ( g < b ? 6 : 0 ); break;
  9772. case g: hue = ( b - r ) / delta + 2; break;
  9773. case b: hue = ( r - g ) / delta + 4; break;
  9774. }
  9775. hue /= 6;
  9776. }
  9777. target.h = hue;
  9778. target.s = saturation;
  9779. target.l = lightness;
  9780. return target;
  9781. }
  9782. /**
  9783. * Returns the RGB values of this color and stores them into the given target object.
  9784. *
  9785. * @param {Color} target - The target color that is used to store the method's result.
  9786. * @param {string} [colorSpace=ColorManagement.workingColorSpace] - The color space.
  9787. * @return {Color} The RGB representation of this color.
  9788. */
  9789. getRGB( target, colorSpace = ColorManagement.workingColorSpace ) {
  9790. ColorManagement.fromWorkingColorSpace( _color.copy( this ), colorSpace );
  9791. target.r = _color.r;
  9792. target.g = _color.g;
  9793. target.b = _color.b;
  9794. return target;
  9795. }
  9796. /**
  9797. * Returns the value of this color as a CSS style string. Example: `rgb(255,0,0)`.
  9798. *
  9799. * @param {string} [colorSpace=SRGBColorSpace] - The color space.
  9800. * @return {string} The CSS representation of this color.
  9801. */
  9802. getStyle( colorSpace = SRGBColorSpace ) {
  9803. ColorManagement.fromWorkingColorSpace( _color.copy( this ), colorSpace );
  9804. const r = _color.r, g = _color.g, b = _color.b;
  9805. if ( colorSpace !== SRGBColorSpace ) {
  9806. // Requires CSS Color Module Level 4 (https://www.w3.org/TR/css-color-4/).
  9807. return `color(${ colorSpace } ${ r.toFixed( 3 ) } ${ g.toFixed( 3 ) } ${ b.toFixed( 3 ) })`;
  9808. }
  9809. return `rgb(${ Math.round( r * 255 ) },${ Math.round( g * 255 ) },${ Math.round( b * 255 ) })`;
  9810. }
  9811. /**
  9812. * Adds the given HSL values to this color's values.
  9813. * Internally, this converts the color's RGB values to HSL, adds HSL
  9814. * and then converts the color back to RGB.
  9815. *
  9816. * @param {number} h - Hue value between `0.0` and `1.0`.
  9817. * @param {number} s - Saturation value between `0.0` and `1.0`.
  9818. * @param {number} l - Lightness value between `0.0` and `1.0`.
  9819. * @return {Color} A reference to this color.
  9820. */
  9821. offsetHSL( h, s, l ) {
  9822. this.getHSL( _hslA );
  9823. return this.setHSL( _hslA.h + h, _hslA.s + s, _hslA.l + l );
  9824. }
  9825. /**
  9826. * Adds the RGB values of the given color to the RGB values of this color.
  9827. *
  9828. * @param {Color} color - The color to add.
  9829. * @return {Color} A reference to this color.
  9830. */
  9831. add( color ) {
  9832. this.r += color.r;
  9833. this.g += color.g;
  9834. this.b += color.b;
  9835. return this;
  9836. }
  9837. /**
  9838. * Adds the RGB values of the given colors and stores the result in this instance.
  9839. *
  9840. * @param {Color} color1 - The first color.
  9841. * @param {Color} color2 - The second color.
  9842. * @return {Color} A reference to this color.
  9843. */
  9844. addColors( color1, color2 ) {
  9845. this.r = color1.r + color2.r;
  9846. this.g = color1.g + color2.g;
  9847. this.b = color1.b + color2.b;
  9848. return this;
  9849. }
  9850. /**
  9851. * Adds the given scalar value to the RGB values of this color.
  9852. *
  9853. * @param {number} s - The scalar to add.
  9854. * @return {Color} A reference to this color.
  9855. */
  9856. addScalar( s ) {
  9857. this.r += s;
  9858. this.g += s;
  9859. this.b += s;
  9860. return this;
  9861. }
  9862. /**
  9863. * Subtracts the RGB values of the given color from the RGB values of this color.
  9864. *
  9865. * @param {Color} color - The color to subtract.
  9866. * @return {Color} A reference to this color.
  9867. */
  9868. sub( color ) {
  9869. this.r = Math.max( 0, this.r - color.r );
  9870. this.g = Math.max( 0, this.g - color.g );
  9871. this.b = Math.max( 0, this.b - color.b );
  9872. return this;
  9873. }
  9874. /**
  9875. * Multiplies the RGB values of the given color with the RGB values of this color.
  9876. *
  9877. * @param {Color} color - The color to multiply.
  9878. * @return {Color} A reference to this color.
  9879. */
  9880. multiply( color ) {
  9881. this.r *= color.r;
  9882. this.g *= color.g;
  9883. this.b *= color.b;
  9884. return this;
  9885. }
  9886. /**
  9887. * Multiplies the given scalar value with the RGB values of this color.
  9888. *
  9889. * @param {number} s - The scalar to multiply.
  9890. * @return {Color} A reference to this color.
  9891. */
  9892. multiplyScalar( s ) {
  9893. this.r *= s;
  9894. this.g *= s;
  9895. this.b *= s;
  9896. return this;
  9897. }
  9898. /**
  9899. * Linearly interpolates this color's RGB values toward the RGB values of the
  9900. * given color. The alpha argument can be thought of as the ratio between
  9901. * the two colors, where `0.0` is this color and `1.0` is the first argument.
  9902. *
  9903. * @param {Color} color - The color to converge on.
  9904. * @param {number} alpha - The interpolation factor in the closed interval `[0,1]`.
  9905. * @return {Color} A reference to this color.
  9906. */
  9907. lerp( color, alpha ) {
  9908. this.r += ( color.r - this.r ) * alpha;
  9909. this.g += ( color.g - this.g ) * alpha;
  9910. this.b += ( color.b - this.b ) * alpha;
  9911. return this;
  9912. }
  9913. /**
  9914. * Linearly interpolates between the given colors and stores the result in this instance.
  9915. * The alpha argument can be thought of as the ratio between the two colors, where `0.0`
  9916. * is the first and `1.0` is the second color.
  9917. *
  9918. * @param {Color} color1 - The first color.
  9919. * @param {Color} color2 - The second color.
  9920. * @param {number} alpha - The interpolation factor in the closed interval `[0,1]`.
  9921. * @return {Color} A reference to this color.
  9922. */
  9923. lerpColors( color1, color2, alpha ) {
  9924. this.r = color1.r + ( color2.r - color1.r ) * alpha;
  9925. this.g = color1.g + ( color2.g - color1.g ) * alpha;
  9926. this.b = color1.b + ( color2.b - color1.b ) * alpha;
  9927. return this;
  9928. }
  9929. /**
  9930. * Linearly interpolates this color's HSL values toward the HSL values of the
  9931. * given color. It differs from {@link Color#lerp} by not interpolating straight
  9932. * from one color to the other, but instead going through all the hues in between
  9933. * those two colors. The alpha argument can be thought of as the ratio between
  9934. * the two colors, where 0.0 is this color and 1.0 is the first argument.
  9935. *
  9936. * @param {Color} color - The color to converge on.
  9937. * @param {number} alpha - The interpolation factor in the closed interval `[0,1]`.
  9938. * @return {Color} A reference to this color.
  9939. */
  9940. lerpHSL( color, alpha ) {
  9941. this.getHSL( _hslA );
  9942. color.getHSL( _hslB );
  9943. const h = lerp( _hslA.h, _hslB.h, alpha );
  9944. const s = lerp( _hslA.s, _hslB.s, alpha );
  9945. const l = lerp( _hslA.l, _hslB.l, alpha );
  9946. this.setHSL( h, s, l );
  9947. return this;
  9948. }
  9949. /**
  9950. * Sets the color's RGB components from the given 3D vector.
  9951. *
  9952. * @param {Vector3} v - The vector to set.
  9953. * @return {Color} A reference to this color.
  9954. */
  9955. setFromVector3( v ) {
  9956. this.r = v.x;
  9957. this.g = v.y;
  9958. this.b = v.z;
  9959. return this;
  9960. }
  9961. /**
  9962. * Transforms this color with the given 3x3 matrix.
  9963. *
  9964. * @param {Matrix3} m - The matrix.
  9965. * @return {Color} A reference to this color.
  9966. */
  9967. applyMatrix3( m ) {
  9968. const r = this.r, g = this.g, b = this.b;
  9969. const e = m.elements;
  9970. this.r = e[ 0 ] * r + e[ 3 ] * g + e[ 6 ] * b;
  9971. this.g = e[ 1 ] * r + e[ 4 ] * g + e[ 7 ] * b;
  9972. this.b = e[ 2 ] * r + e[ 5 ] * g + e[ 8 ] * b;
  9973. return this;
  9974. }
  9975. /**
  9976. * Returns `true` if this color is equal with the given one.
  9977. *
  9978. * @param {Color} c - The color to test for equality.
  9979. * @return {boolean} Whether this bounding color is equal with the given one.
  9980. */
  9981. equals( c ) {
  9982. return ( c.r === this.r ) && ( c.g === this.g ) && ( c.b === this.b );
  9983. }
  9984. /**
  9985. * Sets this color's RGB components from the given array.
  9986. *
  9987. * @param {Array<number>} array - An array holding the RGB values.
  9988. * @param {number} [offset=0] - The offset into the array.
  9989. * @return {Color} A reference to this color.
  9990. */
  9991. fromArray( array, offset = 0 ) {
  9992. this.r = array[ offset ];
  9993. this.g = array[ offset + 1 ];
  9994. this.b = array[ offset + 2 ];
  9995. return this;
  9996. }
  9997. /**
  9998. * Writes the RGB components of this color to the given array. If no array is provided,
  9999. * the method returns a new instance.
  10000. *
  10001. * @param {Array<number>} [array=[]] - The target array holding the color components.
  10002. * @param {number} [offset=0] - Index of the first element in the array.
  10003. * @return {Array<number>} The color components.
  10004. */
  10005. toArray( array = [], offset = 0 ) {
  10006. array[ offset ] = this.r;
  10007. array[ offset + 1 ] = this.g;
  10008. array[ offset + 2 ] = this.b;
  10009. return array;
  10010. }
  10011. /**
  10012. * Sets the components of this color from the given buffer attribute.
  10013. *
  10014. * @param {BufferAttribute} attribute - The buffer attribute holding color data.
  10015. * @param {number} index - The index into the attribute.
  10016. * @return {Color} A reference to this color.
  10017. */
  10018. fromBufferAttribute( attribute, index ) {
  10019. this.r = attribute.getX( index );
  10020. this.g = attribute.getY( index );
  10021. this.b = attribute.getZ( index );
  10022. return this;
  10023. }
  10024. /**
  10025. * This methods defines the serialization result of this class. Returns the color
  10026. * as a hexadecimal value.
  10027. *
  10028. * @return {number} The hexadecimal value.
  10029. */
  10030. toJSON() {
  10031. return this.getHex();
  10032. }
  10033. *[ Symbol.iterator ]() {
  10034. yield this.r;
  10035. yield this.g;
  10036. yield this.b;
  10037. }
  10038. }
  10039. const _color = /*@__PURE__*/ new Color();
  10040. /**
  10041. * A dictionary with X11 color names.
  10042. *
  10043. * Note that multiple words such as Dark Orange become the string 'darkorange'.
  10044. *
  10045. * @static
  10046. * @type {Object}
  10047. */
  10048. Color.NAMES = _colorKeywords;
  10049. let _materialId = 0;
  10050. /**
  10051. * Abstract base class for materials.
  10052. *
  10053. * Materials define the appearance of renderable 3D objects.
  10054. *
  10055. * @abstract
  10056. * @augments EventDispatcher
  10057. */
  10058. class Material extends EventDispatcher {
  10059. /**
  10060. * Constructs a new material.
  10061. */
  10062. constructor() {
  10063. super();
  10064. /**
  10065. * This flag can be used for type testing.
  10066. *
  10067. * @type {boolean}
  10068. * @readonly
  10069. * @default true
  10070. */
  10071. this.isMaterial = true;
  10072. /**
  10073. * The ID of the material.
  10074. *
  10075. * @name Material#id
  10076. * @type {number}
  10077. * @readonly
  10078. */
  10079. Object.defineProperty( this, 'id', { value: _materialId ++ } );
  10080. /**
  10081. * The UUID of the material.
  10082. *
  10083. * @type {string}
  10084. * @readonly
  10085. */
  10086. this.uuid = generateUUID();
  10087. /**
  10088. * The name of the material.
  10089. *
  10090. * @type {string}
  10091. */
  10092. this.name = '';
  10093. /**
  10094. * The type property is used for detecting the object type
  10095. * in context of serialization/deserialization.
  10096. *
  10097. * @type {string}
  10098. * @readonly
  10099. */
  10100. this.type = 'Material';
  10101. /**
  10102. * Defines the blending type of the material.
  10103. *
  10104. * It must be set to `CustomBlending` if custom blending properties like
  10105. * {@link Material#blendSrc}, {@link Material#blendDst} or {@link Material#blendEquation}
  10106. * should have any effect.
  10107. *
  10108. * @type {(NoBlending|NormalBlending|AdditiveBlending|SubtractiveBlending|MultiplyBlending|CustomBlending)}
  10109. * @default NormalBlending
  10110. */
  10111. this.blending = NormalBlending;
  10112. /**
  10113. * Defines which side of faces will be rendered - front, back or both.
  10114. *
  10115. * @type {(FrontSide|BackSide|DoubleSide)}
  10116. * @default FrontSide
  10117. */
  10118. this.side = FrontSide;
  10119. /**
  10120. * If set to `true`, vertex colors should be used.
  10121. *
  10122. * The engine supports RGB and RGBA vertex colors depending on whether a three (RGB) or
  10123. * four (RGBA) component color buffer attribute is used.
  10124. *
  10125. * @type {boolean}
  10126. * @default false
  10127. */
  10128. this.vertexColors = false;
  10129. /**
  10130. * Defines how transparent the material is.
  10131. * A value of `0.0` indicates fully transparent, `1.0` is fully opaque.
  10132. *
  10133. * If the {@link Material#transparent} is not set to `true`,
  10134. * the material will remain fully opaque and this value will only affect its color.
  10135. *
  10136. * @type {number}
  10137. * @default 1
  10138. */
  10139. this.opacity = 1;
  10140. /**
  10141. * Defines whether this material is transparent. This has an effect on
  10142. * rendering as transparent objects need special treatment and are rendered
  10143. * after non-transparent objects.
  10144. *
  10145. * When set to true, the extent to which the material is transparent is
  10146. * controlled by {@link Material#opacity}.
  10147. *
  10148. * @type {boolean}
  10149. * @default false
  10150. */
  10151. this.transparent = false;
  10152. /**
  10153. * Enables alpha hashed transparency, an alternative to {@link Material#transparent} or
  10154. * {@link Material#alphaTest}. The material will not be rendered if opacity is lower than
  10155. * a random threshold. Randomization introduces some grain or noise, but approximates alpha
  10156. * blending without the associated problems of sorting. Using TAA can reduce the resulting noise.
  10157. *
  10158. * @type {boolean}
  10159. * @default false
  10160. */
  10161. this.alphaHash = false;
  10162. /**
  10163. * Defines the blending source factor.
  10164. *
  10165. * @type {(ZeroFactor|OneFactor|SrcColorFactor|OneMinusSrcColorFactor|SrcAlphaFactor|OneMinusSrcAlphaFactor|DstAlphaFactor|OneMinusDstAlphaFactor|DstColorFactor|OneMinusDstColorFactor|SrcAlphaSaturateFactor|ConstantColorFactor|OneMinusConstantColorFactor|ConstantAlphaFactor|OneMinusConstantAlphaFactor)}
  10166. * @default SrcAlphaFactor
  10167. */
  10168. this.blendSrc = SrcAlphaFactor;
  10169. /**
  10170. * Defines the blending destination factor.
  10171. *
  10172. * @type {(ZeroFactor|OneFactor|SrcColorFactor|OneMinusSrcColorFactor|SrcAlphaFactor|OneMinusSrcAlphaFactor|DstAlphaFactor|OneMinusDstAlphaFactor|DstColorFactor|OneMinusDstColorFactor|SrcAlphaSaturateFactor|ConstantColorFactor|OneMinusConstantColorFactor|ConstantAlphaFactor|OneMinusConstantAlphaFactor)}
  10173. * @default OneMinusSrcAlphaFactor
  10174. */
  10175. this.blendDst = OneMinusSrcAlphaFactor;
  10176. /**
  10177. * Defines the blending equation.
  10178. *
  10179. * @type {(AddEquation|SubtractEquation|ReverseSubtractEquation|MinEquation|MaxEquation)}
  10180. * @default OneMinusSrcAlphaFactor
  10181. */
  10182. this.blendEquation = AddEquation;
  10183. /**
  10184. * Defines the blending source alpha factor.
  10185. *
  10186. * @type {?(ZeroFactor|OneFactor|SrcColorFactor|OneMinusSrcColorFactor|SrcAlphaFactor|OneMinusSrcAlphaFactor|DstAlphaFactor|OneMinusDstAlphaFactor|DstColorFactor|OneMinusDstColorFactor|SrcAlphaSaturateFactor|ConstantColorFactor|OneMinusConstantColorFactor|ConstantAlphaFactor|OneMinusConstantAlphaFactor)}
  10187. * @default null
  10188. */
  10189. this.blendSrcAlpha = null;
  10190. /**
  10191. * Defines the blending destination alpha factor.
  10192. *
  10193. * @type {?(ZeroFactor|OneFactor|SrcColorFactor|OneMinusSrcColorFactor|SrcAlphaFactor|OneMinusSrcAlphaFactor|DstAlphaFactor|OneMinusDstAlphaFactor|DstColorFactor|OneMinusDstColorFactor|SrcAlphaSaturateFactor|ConstantColorFactor|OneMinusConstantColorFactor|ConstantAlphaFactor|OneMinusConstantAlphaFactor)}
  10194. * @default null
  10195. */
  10196. this.blendDstAlpha = null;
  10197. /**
  10198. * Defines the blending equation of the alpha channel.
  10199. *
  10200. * @type {(AddEquation|SubtractEquation|ReverseSubtractEquation|MinEquation|MaxEquation)}
  10201. * @default OneMinusSrcAlphaFactor
  10202. */
  10203. this.blendEquationAlpha = null;
  10204. /**
  10205. * Represents the RGB values of the constant blend color.
  10206. *
  10207. * This property has only an effect when using custom blending with `ConstantColor` or `OneMinusConstantColor`.
  10208. *
  10209. * @type {Color}
  10210. * @default (0,0,0)
  10211. */
  10212. this.blendColor = new Color( 0, 0, 0 );
  10213. /**
  10214. * Represents the alpha value of the constant blend color.
  10215. *
  10216. * This property has only an effect when using custom blending with `ConstantAlpha` or `OneMinusConstantAlpha`.
  10217. *
  10218. * @type {number}
  10219. * @default 0
  10220. */
  10221. this.blendAlpha = 0;
  10222. /**
  10223. * Defines the depth function.
  10224. *
  10225. * @type {(NeverDepth|AlwaysDepth|LessDepth|LessEqualDepth|EqualDepth|GreaterEqualDepth|GreaterDepth|NotEqualDepth)}
  10226. * @default LessEqualDepth
  10227. */
  10228. this.depthFunc = LessEqualDepth;
  10229. /**
  10230. * Whether to have depth test enabled when rendering this material.
  10231. * When the depth test is disabled, the depth write will also be implicitly disabled.
  10232. *
  10233. * @type {boolean}
  10234. * @default true
  10235. */
  10236. this.depthTest = true;
  10237. /**
  10238. * Whether rendering this material has any effect on the depth buffer.
  10239. *
  10240. * When drawing 2D overlays it can be useful to disable the depth writing in
  10241. * order to layer several things together without creating z-index artifacts.
  10242. *
  10243. * @type {boolean}
  10244. * @default true
  10245. */
  10246. this.depthWrite = true;
  10247. /**
  10248. * The bit mask to use when writing to the stencil buffer.
  10249. *
  10250. * @type {number}
  10251. * @default 0xff
  10252. */
  10253. this.stencilWriteMask = 0xff;
  10254. /**
  10255. * The stencil comparison function to use.
  10256. *
  10257. * @type {NeverStencilFunc|LessStencilFunc|EqualStencilFunc|LessEqualStencilFunc|GreaterStencilFunc|NotEqualStencilFunc|GreaterEqualStencilFunc|AlwaysStencilFunc}
  10258. * @default AlwaysStencilFunc
  10259. */
  10260. this.stencilFunc = AlwaysStencilFunc;
  10261. /**
  10262. * The value to use when performing stencil comparisons or stencil operations.
  10263. *
  10264. * @type {number}
  10265. * @default 0
  10266. */
  10267. this.stencilRef = 0;
  10268. /**
  10269. * The bit mask to use when comparing against the stencil buffer.
  10270. *
  10271. * @type {number}
  10272. * @default 0xff
  10273. */
  10274. this.stencilFuncMask = 0xff;
  10275. /**
  10276. * Which stencil operation to perform when the comparison function returns `false`.
  10277. *
  10278. * @type {ZeroStencilOp|KeepStencilOp|ReplaceStencilOp|IncrementStencilOp|DecrementStencilOp|IncrementWrapStencilOp|DecrementWrapStencilOp|InvertStencilOp}
  10279. * @default KeepStencilOp
  10280. */
  10281. this.stencilFail = KeepStencilOp;
  10282. /**
  10283. * Which stencil operation to perform when the comparison function returns
  10284. * `true` but the depth test fails.
  10285. *
  10286. * @type {ZeroStencilOp|KeepStencilOp|ReplaceStencilOp|IncrementStencilOp|DecrementStencilOp|IncrementWrapStencilOp|DecrementWrapStencilOp|InvertStencilOp}
  10287. * @default KeepStencilOp
  10288. */
  10289. this.stencilZFail = KeepStencilOp;
  10290. /**
  10291. * Which stencil operation to perform when the comparison function returns
  10292. * `true` and the depth test passes.
  10293. *
  10294. * @type {ZeroStencilOp|KeepStencilOp|ReplaceStencilOp|IncrementStencilOp|DecrementStencilOp|IncrementWrapStencilOp|DecrementWrapStencilOp|InvertStencilOp}
  10295. * @default KeepStencilOp
  10296. */
  10297. this.stencilZPass = KeepStencilOp;
  10298. /**
  10299. * Whether stencil operations are performed against the stencil buffer. In
  10300. * order to perform writes or comparisons against the stencil buffer this
  10301. * value must be `true`.
  10302. *
  10303. * @type {boolean}
  10304. * @default false
  10305. */
  10306. this.stencilWrite = false;
  10307. /**
  10308. * User-defined clipping planes specified as THREE.Plane objects in world
  10309. * space. These planes apply to the objects this material is attached to.
  10310. * Points in space whose signed distance to the plane is negative are clipped
  10311. * (not rendered). This requires {@link WebGLRenderer#localClippingEnabled} to
  10312. * be `true`.
  10313. *
  10314. * @type {?Array<Plane>}
  10315. * @default null
  10316. */
  10317. this.clippingPlanes = null;
  10318. /**
  10319. * Changes the behavior of clipping planes so that only their intersection is
  10320. * clipped, rather than their union.
  10321. *
  10322. * @type {boolean}
  10323. * @default false
  10324. */
  10325. this.clipIntersection = false;
  10326. /**
  10327. * Defines whether to clip shadows according to the clipping planes specified
  10328. * on this material.
  10329. *
  10330. * @type {boolean}
  10331. * @default false
  10332. */
  10333. this.clipShadows = false;
  10334. /**
  10335. * Defines which side of faces cast shadows. If `null`, the side casting shadows
  10336. * is determined as follows:
  10337. *
  10338. * - When {@link Material#side} is set to `FrontSide`, the back side cast shadows.
  10339. * - When {@link Material#side} is set to `BackSide`, the front side cast shadows.
  10340. * - When {@link Material#side} is set to `DoubleSide`, both sides cast shadows.
  10341. *
  10342. * @type {?(FrontSide|BackSide|DoubleSide)}
  10343. * @default null
  10344. */
  10345. this.shadowSide = null;
  10346. /**
  10347. * Whether to render the material's color.
  10348. *
  10349. * This can be used in conjunction with {@link Object3D#renderOder} to create invisible
  10350. * objects that occlude other objects.
  10351. *
  10352. * @type {boolean}
  10353. * @default true
  10354. */
  10355. this.colorWrite = true;
  10356. /**
  10357. * Override the renderer's default precision for this material.
  10358. *
  10359. * @type {?('highp'|'mediump'|'lowp')}
  10360. * @default null
  10361. */
  10362. this.precision = null;
  10363. /**
  10364. * Whether to use polygon offset or not. When enabled, each fragment's depth value will
  10365. * be offset after it is interpolated from the depth values of the appropriate vertices.
  10366. * The offset is added before the depth test is performed and before the value is written
  10367. * into the depth buffer.
  10368. *
  10369. * Can be useful for rendering hidden-line images, for applying decals to surfaces, and for
  10370. * rendering solids with highlighted edges.
  10371. *
  10372. * @type {boolean}
  10373. * @default false
  10374. */
  10375. this.polygonOffset = false;
  10376. /**
  10377. * Specifies a scale factor that is used to create a variable depth offset for each polygon.
  10378. *
  10379. * @type {number}
  10380. * @default 0
  10381. */
  10382. this.polygonOffsetFactor = 0;
  10383. /**
  10384. * Is multiplied by an implementation-specific value to create a constant depth offset.
  10385. *
  10386. * @type {number}
  10387. * @default 0
  10388. */
  10389. this.polygonOffsetUnits = 0;
  10390. /**
  10391. * Whether to apply dithering to the color to remove the appearance of banding.
  10392. *
  10393. * @type {boolean}
  10394. * @default false
  10395. */
  10396. this.dithering = false;
  10397. /**
  10398. * Whether alpha to coverage should be enabled or not. Can only be used with MSAA-enabled contexts
  10399. * (meaning when the renderer was created with *antialias* parameter set to `true`). Enabling this
  10400. * will smooth aliasing on clip plane edges and alphaTest-clipped edges.
  10401. *
  10402. * @type {boolean}
  10403. * @default false
  10404. */
  10405. this.alphaToCoverage = false;
  10406. /**
  10407. * Whether to premultiply the alpha (transparency) value.
  10408. *
  10409. * @type {boolean}
  10410. * @default false
  10411. */
  10412. this.premultipliedAlpha = false;
  10413. /**
  10414. * Whether double-sided, transparent objects should be rendered with a single pass or not.
  10415. *
  10416. * The engine renders double-sided, transparent objects with two draw calls (back faces first,
  10417. * then front faces) to mitigate transparency artifacts. There are scenarios however where this
  10418. * approach produces no quality gains but still doubles draw calls e.g. when rendering flat
  10419. * vegetation like grass sprites. In these cases, set the `forceSinglePass` flag to `true` to
  10420. * disable the two pass rendering to avoid performance issues.
  10421. *
  10422. * @type {boolean}
  10423. * @default false
  10424. */
  10425. this.forceSinglePass = false;
  10426. /**
  10427. * Defines whether 3D objects using this material are visible.
  10428. *
  10429. * @type {boolean}
  10430. * @default true
  10431. */
  10432. this.visible = true;
  10433. /**
  10434. * Defines whether this material is tone mapped according to the renderer's tone mapping setting.
  10435. *
  10436. * It is ignored when rendering to a render target or using post processing or when using
  10437. * `WebGPURenderer`. In all these cases, all materials are honored by tone mapping.
  10438. *
  10439. * @type {boolean}
  10440. * @default true
  10441. */
  10442. this.toneMapped = true;
  10443. /**
  10444. * An object that can be used to store custom data about the Material. It
  10445. * should not hold references to functions as these will not be cloned.
  10446. *
  10447. * @type {Object}
  10448. */
  10449. this.userData = {};
  10450. /**
  10451. * This starts at `0` and counts how many times {@link Material#needsUpdate} is set to `true`.
  10452. *
  10453. * @type {number}
  10454. * @readonly
  10455. * @default 0
  10456. */
  10457. this.version = 0;
  10458. this._alphaTest = 0;
  10459. }
  10460. /**
  10461. * Sets the alpha value to be used when running an alpha test. The material
  10462. * will not be rendered if the opacity is lower than this value.
  10463. *
  10464. * @type {number}
  10465. * @readonly
  10466. * @default 0
  10467. */
  10468. get alphaTest() {
  10469. return this._alphaTest;
  10470. }
  10471. set alphaTest( value ) {
  10472. if ( this._alphaTest > 0 !== value > 0 ) {
  10473. this.version ++;
  10474. }
  10475. this._alphaTest = value;
  10476. }
  10477. /**
  10478. * An optional callback that is executed immediately before the material is used to render a 3D object.
  10479. *
  10480. * This method can only be used when rendering with {@link WebGLRenderer}.
  10481. *
  10482. * @param {WebGLRenderer} renderer - The renderer.
  10483. * @param {Scene} scene - The scene.
  10484. * @param {Camera} camera - The camera that is used to render the scene.
  10485. * @param {BufferGeometry} geometry - The 3D object's geometry.
  10486. * @param {Object3D} object - The 3D object.
  10487. * @param {Object} group - The geometry group data.
  10488. */
  10489. onBeforeRender( /* renderer, scene, camera, geometry, object, group */ ) {}
  10490. /**
  10491. * An optional callback that is executed immediately before the shader
  10492. * program is compiled. This function is called with the shader source code
  10493. * as a parameter. Useful for the modification of built-in materials.
  10494. *
  10495. * This method can only be used when rendering with {@link WebGLRenderer}. The
  10496. * recommended approach when customizing materials is to use `WebGPURenderer` with the new
  10497. * Node Material system and [TSL]{@link https://github.com/mrdoob/three.js/wiki/Three.js-Shading-Language}.
  10498. *
  10499. * @param {{vertexShader:string,fragmentShader:string,uniforms:Object}} shaderobject - The object holds the uniforms and the vertex and fragment shader source.
  10500. * @param {WebGLRenderer} renderer - A reference to the renderer.
  10501. */
  10502. onBeforeCompile( /* shaderobject, renderer */ ) {}
  10503. /**
  10504. * In case {@link Material#onBeforeCompile} is used, this callback can be used to identify
  10505. * values of settings used in `onBeforeCompile()`, so three.js can reuse a cached
  10506. * shader or recompile the shader for this material as needed.
  10507. *
  10508. * This method can only be used when rendering with {@link WebGLRenderer}.
  10509. *
  10510. * @return {string} The custom program cache key.
  10511. */
  10512. customProgramCacheKey() {
  10513. return this.onBeforeCompile.toString();
  10514. }
  10515. setValues( values ) {
  10516. if ( values === undefined ) return;
  10517. for ( const key in values ) {
  10518. const newValue = values[ key ];
  10519. if ( newValue === undefined ) {
  10520. console.warn( `THREE.Material: parameter '${ key }' has value of undefined.` );
  10521. continue;
  10522. }
  10523. const currentValue = this[ key ];
  10524. if ( currentValue === undefined ) {
  10525. console.warn( `THREE.Material: '${ key }' is not a property of THREE.${ this.type }.` );
  10526. continue;
  10527. }
  10528. if ( currentValue && currentValue.isColor ) {
  10529. currentValue.set( newValue );
  10530. } else if ( ( currentValue && currentValue.isVector3 ) && ( newValue && newValue.isVector3 ) ) {
  10531. currentValue.copy( newValue );
  10532. } else {
  10533. this[ key ] = newValue;
  10534. }
  10535. }
  10536. }
  10537. /**
  10538. * Serializes the material into JSON.
  10539. *
  10540. * @param {?(Object|string)} meta - An optional value holding meta information about the serialization.
  10541. * @return {Object} A JSON object representing the serialized material.
  10542. * @see {@link ObjectLoader#parse}
  10543. */
  10544. toJSON( meta ) {
  10545. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  10546. if ( isRootObject ) {
  10547. meta = {
  10548. textures: {},
  10549. images: {}
  10550. };
  10551. }
  10552. const data = {
  10553. metadata: {
  10554. version: 4.6,
  10555. type: 'Material',
  10556. generator: 'Material.toJSON'
  10557. }
  10558. };
  10559. // standard Material serialization
  10560. data.uuid = this.uuid;
  10561. data.type = this.type;
  10562. if ( this.name !== '' ) data.name = this.name;
  10563. if ( this.color && this.color.isColor ) data.color = this.color.getHex();
  10564. if ( this.roughness !== undefined ) data.roughness = this.roughness;
  10565. if ( this.metalness !== undefined ) data.metalness = this.metalness;
  10566. if ( this.sheen !== undefined ) data.sheen = this.sheen;
  10567. if ( this.sheenColor && this.sheenColor.isColor ) data.sheenColor = this.sheenColor.getHex();
  10568. if ( this.sheenRoughness !== undefined ) data.sheenRoughness = this.sheenRoughness;
  10569. if ( this.emissive && this.emissive.isColor ) data.emissive = this.emissive.getHex();
  10570. if ( this.emissiveIntensity !== undefined && this.emissiveIntensity !== 1 ) data.emissiveIntensity = this.emissiveIntensity;
  10571. if ( this.specular && this.specular.isColor ) data.specular = this.specular.getHex();
  10572. if ( this.specularIntensity !== undefined ) data.specularIntensity = this.specularIntensity;
  10573. if ( this.specularColor && this.specularColor.isColor ) data.specularColor = this.specularColor.getHex();
  10574. if ( this.shininess !== undefined ) data.shininess = this.shininess;
  10575. if ( this.clearcoat !== undefined ) data.clearcoat = this.clearcoat;
  10576. if ( this.clearcoatRoughness !== undefined ) data.clearcoatRoughness = this.clearcoatRoughness;
  10577. if ( this.clearcoatMap && this.clearcoatMap.isTexture ) {
  10578. data.clearcoatMap = this.clearcoatMap.toJSON( meta ).uuid;
  10579. }
  10580. if ( this.clearcoatRoughnessMap && this.clearcoatRoughnessMap.isTexture ) {
  10581. data.clearcoatRoughnessMap = this.clearcoatRoughnessMap.toJSON( meta ).uuid;
  10582. }
  10583. if ( this.clearcoatNormalMap && this.clearcoatNormalMap.isTexture ) {
  10584. data.clearcoatNormalMap = this.clearcoatNormalMap.toJSON( meta ).uuid;
  10585. data.clearcoatNormalScale = this.clearcoatNormalScale.toArray();
  10586. }
  10587. if ( this.dispersion !== undefined ) data.dispersion = this.dispersion;
  10588. if ( this.iridescence !== undefined ) data.iridescence = this.iridescence;
  10589. if ( this.iridescenceIOR !== undefined ) data.iridescenceIOR = this.iridescenceIOR;
  10590. if ( this.iridescenceThicknessRange !== undefined ) data.iridescenceThicknessRange = this.iridescenceThicknessRange;
  10591. if ( this.iridescenceMap && this.iridescenceMap.isTexture ) {
  10592. data.iridescenceMap = this.iridescenceMap.toJSON( meta ).uuid;
  10593. }
  10594. if ( this.iridescenceThicknessMap && this.iridescenceThicknessMap.isTexture ) {
  10595. data.iridescenceThicknessMap = this.iridescenceThicknessMap.toJSON( meta ).uuid;
  10596. }
  10597. if ( this.anisotropy !== undefined ) data.anisotropy = this.anisotropy;
  10598. if ( this.anisotropyRotation !== undefined ) data.anisotropyRotation = this.anisotropyRotation;
  10599. if ( this.anisotropyMap && this.anisotropyMap.isTexture ) {
  10600. data.anisotropyMap = this.anisotropyMap.toJSON( meta ).uuid;
  10601. }
  10602. if ( this.map && this.map.isTexture ) data.map = this.map.toJSON( meta ).uuid;
  10603. if ( this.matcap && this.matcap.isTexture ) data.matcap = this.matcap.toJSON( meta ).uuid;
  10604. if ( this.alphaMap && this.alphaMap.isTexture ) data.alphaMap = this.alphaMap.toJSON( meta ).uuid;
  10605. if ( this.lightMap && this.lightMap.isTexture ) {
  10606. data.lightMap = this.lightMap.toJSON( meta ).uuid;
  10607. data.lightMapIntensity = this.lightMapIntensity;
  10608. }
  10609. if ( this.aoMap && this.aoMap.isTexture ) {
  10610. data.aoMap = this.aoMap.toJSON( meta ).uuid;
  10611. data.aoMapIntensity = this.aoMapIntensity;
  10612. }
  10613. if ( this.bumpMap && this.bumpMap.isTexture ) {
  10614. data.bumpMap = this.bumpMap.toJSON( meta ).uuid;
  10615. data.bumpScale = this.bumpScale;
  10616. }
  10617. if ( this.normalMap && this.normalMap.isTexture ) {
  10618. data.normalMap = this.normalMap.toJSON( meta ).uuid;
  10619. data.normalMapType = this.normalMapType;
  10620. data.normalScale = this.normalScale.toArray();
  10621. }
  10622. if ( this.displacementMap && this.displacementMap.isTexture ) {
  10623. data.displacementMap = this.displacementMap.toJSON( meta ).uuid;
  10624. data.displacementScale = this.displacementScale;
  10625. data.displacementBias = this.displacementBias;
  10626. }
  10627. if ( this.roughnessMap && this.roughnessMap.isTexture ) data.roughnessMap = this.roughnessMap.toJSON( meta ).uuid;
  10628. if ( this.metalnessMap && this.metalnessMap.isTexture ) data.metalnessMap = this.metalnessMap.toJSON( meta ).uuid;
  10629. if ( this.emissiveMap && this.emissiveMap.isTexture ) data.emissiveMap = this.emissiveMap.toJSON( meta ).uuid;
  10630. if ( this.specularMap && this.specularMap.isTexture ) data.specularMap = this.specularMap.toJSON( meta ).uuid;
  10631. if ( this.specularIntensityMap && this.specularIntensityMap.isTexture ) data.specularIntensityMap = this.specularIntensityMap.toJSON( meta ).uuid;
  10632. if ( this.specularColorMap && this.specularColorMap.isTexture ) data.specularColorMap = this.specularColorMap.toJSON( meta ).uuid;
  10633. if ( this.envMap && this.envMap.isTexture ) {
  10634. data.envMap = this.envMap.toJSON( meta ).uuid;
  10635. if ( this.combine !== undefined ) data.combine = this.combine;
  10636. }
  10637. if ( this.envMapRotation !== undefined ) data.envMapRotation = this.envMapRotation.toArray();
  10638. if ( this.envMapIntensity !== undefined ) data.envMapIntensity = this.envMapIntensity;
  10639. if ( this.reflectivity !== undefined ) data.reflectivity = this.reflectivity;
  10640. if ( this.refractionRatio !== undefined ) data.refractionRatio = this.refractionRatio;
  10641. if ( this.gradientMap && this.gradientMap.isTexture ) {
  10642. data.gradientMap = this.gradientMap.toJSON( meta ).uuid;
  10643. }
  10644. if ( this.transmission !== undefined ) data.transmission = this.transmission;
  10645. if ( this.transmissionMap && this.transmissionMap.isTexture ) data.transmissionMap = this.transmissionMap.toJSON( meta ).uuid;
  10646. if ( this.thickness !== undefined ) data.thickness = this.thickness;
  10647. if ( this.thicknessMap && this.thicknessMap.isTexture ) data.thicknessMap = this.thicknessMap.toJSON( meta ).uuid;
  10648. if ( this.attenuationDistance !== undefined && this.attenuationDistance !== Infinity ) data.attenuationDistance = this.attenuationDistance;
  10649. if ( this.attenuationColor !== undefined ) data.attenuationColor = this.attenuationColor.getHex();
  10650. if ( this.size !== undefined ) data.size = this.size;
  10651. if ( this.shadowSide !== null ) data.shadowSide = this.shadowSide;
  10652. if ( this.sizeAttenuation !== undefined ) data.sizeAttenuation = this.sizeAttenuation;
  10653. if ( this.blending !== NormalBlending ) data.blending = this.blending;
  10654. if ( this.side !== FrontSide ) data.side = this.side;
  10655. if ( this.vertexColors === true ) data.vertexColors = true;
  10656. if ( this.opacity < 1 ) data.opacity = this.opacity;
  10657. if ( this.transparent === true ) data.transparent = true;
  10658. if ( this.blendSrc !== SrcAlphaFactor ) data.blendSrc = this.blendSrc;
  10659. if ( this.blendDst !== OneMinusSrcAlphaFactor ) data.blendDst = this.blendDst;
  10660. if ( this.blendEquation !== AddEquation ) data.blendEquation = this.blendEquation;
  10661. if ( this.blendSrcAlpha !== null ) data.blendSrcAlpha = this.blendSrcAlpha;
  10662. if ( this.blendDstAlpha !== null ) data.blendDstAlpha = this.blendDstAlpha;
  10663. if ( this.blendEquationAlpha !== null ) data.blendEquationAlpha = this.blendEquationAlpha;
  10664. if ( this.blendColor && this.blendColor.isColor ) data.blendColor = this.blendColor.getHex();
  10665. if ( this.blendAlpha !== 0 ) data.blendAlpha = this.blendAlpha;
  10666. if ( this.depthFunc !== LessEqualDepth ) data.depthFunc = this.depthFunc;
  10667. if ( this.depthTest === false ) data.depthTest = this.depthTest;
  10668. if ( this.depthWrite === false ) data.depthWrite = this.depthWrite;
  10669. if ( this.colorWrite === false ) data.colorWrite = this.colorWrite;
  10670. if ( this.stencilWriteMask !== 0xff ) data.stencilWriteMask = this.stencilWriteMask;
  10671. if ( this.stencilFunc !== AlwaysStencilFunc ) data.stencilFunc = this.stencilFunc;
  10672. if ( this.stencilRef !== 0 ) data.stencilRef = this.stencilRef;
  10673. if ( this.stencilFuncMask !== 0xff ) data.stencilFuncMask = this.stencilFuncMask;
  10674. if ( this.stencilFail !== KeepStencilOp ) data.stencilFail = this.stencilFail;
  10675. if ( this.stencilZFail !== KeepStencilOp ) data.stencilZFail = this.stencilZFail;
  10676. if ( this.stencilZPass !== KeepStencilOp ) data.stencilZPass = this.stencilZPass;
  10677. if ( this.stencilWrite === true ) data.stencilWrite = this.stencilWrite;
  10678. // rotation (SpriteMaterial)
  10679. if ( this.rotation !== undefined && this.rotation !== 0 ) data.rotation = this.rotation;
  10680. if ( this.polygonOffset === true ) data.polygonOffset = true;
  10681. if ( this.polygonOffsetFactor !== 0 ) data.polygonOffsetFactor = this.polygonOffsetFactor;
  10682. if ( this.polygonOffsetUnits !== 0 ) data.polygonOffsetUnits = this.polygonOffsetUnits;
  10683. if ( this.linewidth !== undefined && this.linewidth !== 1 ) data.linewidth = this.linewidth;
  10684. if ( this.dashSize !== undefined ) data.dashSize = this.dashSize;
  10685. if ( this.gapSize !== undefined ) data.gapSize = this.gapSize;
  10686. if ( this.scale !== undefined ) data.scale = this.scale;
  10687. if ( this.dithering === true ) data.dithering = true;
  10688. if ( this.alphaTest > 0 ) data.alphaTest = this.alphaTest;
  10689. if ( this.alphaHash === true ) data.alphaHash = true;
  10690. if ( this.alphaToCoverage === true ) data.alphaToCoverage = true;
  10691. if ( this.premultipliedAlpha === true ) data.premultipliedAlpha = true;
  10692. if ( this.forceSinglePass === true ) data.forceSinglePass = true;
  10693. if ( this.wireframe === true ) data.wireframe = true;
  10694. if ( this.wireframeLinewidth > 1 ) data.wireframeLinewidth = this.wireframeLinewidth;
  10695. if ( this.wireframeLinecap !== 'round' ) data.wireframeLinecap = this.wireframeLinecap;
  10696. if ( this.wireframeLinejoin !== 'round' ) data.wireframeLinejoin = this.wireframeLinejoin;
  10697. if ( this.flatShading === true ) data.flatShading = true;
  10698. if ( this.visible === false ) data.visible = false;
  10699. if ( this.toneMapped === false ) data.toneMapped = false;
  10700. if ( this.fog === false ) data.fog = false;
  10701. if ( Object.keys( this.userData ).length > 0 ) data.userData = this.userData;
  10702. // TODO: Copied from Object3D.toJSON
  10703. function extractFromCache( cache ) {
  10704. const values = [];
  10705. for ( const key in cache ) {
  10706. const data = cache[ key ];
  10707. delete data.metadata;
  10708. values.push( data );
  10709. }
  10710. return values;
  10711. }
  10712. if ( isRootObject ) {
  10713. const textures = extractFromCache( meta.textures );
  10714. const images = extractFromCache( meta.images );
  10715. if ( textures.length > 0 ) data.textures = textures;
  10716. if ( images.length > 0 ) data.images = images;
  10717. }
  10718. return data;
  10719. }
  10720. /**
  10721. * Returns a new material with copied values from this instance.
  10722. *
  10723. * @return {Material} A clone of this instance.
  10724. */
  10725. clone() {
  10726. return new this.constructor().copy( this );
  10727. }
  10728. /**
  10729. * Copies the values of the given material to this instance.
  10730. *
  10731. * @param {Material} source - The material to copy.
  10732. * @return {Material} A reference to this instance.
  10733. */
  10734. copy( source ) {
  10735. this.name = source.name;
  10736. this.blending = source.blending;
  10737. this.side = source.side;
  10738. this.vertexColors = source.vertexColors;
  10739. this.opacity = source.opacity;
  10740. this.transparent = source.transparent;
  10741. this.blendSrc = source.blendSrc;
  10742. this.blendDst = source.blendDst;
  10743. this.blendEquation = source.blendEquation;
  10744. this.blendSrcAlpha = source.blendSrcAlpha;
  10745. this.blendDstAlpha = source.blendDstAlpha;
  10746. this.blendEquationAlpha = source.blendEquationAlpha;
  10747. this.blendColor.copy( source.blendColor );
  10748. this.blendAlpha = source.blendAlpha;
  10749. this.depthFunc = source.depthFunc;
  10750. this.depthTest = source.depthTest;
  10751. this.depthWrite = source.depthWrite;
  10752. this.stencilWriteMask = source.stencilWriteMask;
  10753. this.stencilFunc = source.stencilFunc;
  10754. this.stencilRef = source.stencilRef;
  10755. this.stencilFuncMask = source.stencilFuncMask;
  10756. this.stencilFail = source.stencilFail;
  10757. this.stencilZFail = source.stencilZFail;
  10758. this.stencilZPass = source.stencilZPass;
  10759. this.stencilWrite = source.stencilWrite;
  10760. const srcPlanes = source.clippingPlanes;
  10761. let dstPlanes = null;
  10762. if ( srcPlanes !== null ) {
  10763. const n = srcPlanes.length;
  10764. dstPlanes = new Array( n );
  10765. for ( let i = 0; i !== n; ++ i ) {
  10766. dstPlanes[ i ] = srcPlanes[ i ].clone();
  10767. }
  10768. }
  10769. this.clippingPlanes = dstPlanes;
  10770. this.clipIntersection = source.clipIntersection;
  10771. this.clipShadows = source.clipShadows;
  10772. this.shadowSide = source.shadowSide;
  10773. this.colorWrite = source.colorWrite;
  10774. this.precision = source.precision;
  10775. this.polygonOffset = source.polygonOffset;
  10776. this.polygonOffsetFactor = source.polygonOffsetFactor;
  10777. this.polygonOffsetUnits = source.polygonOffsetUnits;
  10778. this.dithering = source.dithering;
  10779. this.alphaTest = source.alphaTest;
  10780. this.alphaHash = source.alphaHash;
  10781. this.alphaToCoverage = source.alphaToCoverage;
  10782. this.premultipliedAlpha = source.premultipliedAlpha;
  10783. this.forceSinglePass = source.forceSinglePass;
  10784. this.visible = source.visible;
  10785. this.toneMapped = source.toneMapped;
  10786. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  10787. return this;
  10788. }
  10789. /**
  10790. * Frees the GPU-related resources allocated by this instance. Call this
  10791. * method whenever this instance is no longer used in your app.
  10792. *
  10793. * @fires Material#dispose
  10794. */
  10795. dispose() {
  10796. /**
  10797. * Fires when the material has been disposed of.
  10798. *
  10799. * @event Material#dispose
  10800. * @type {Object}
  10801. */
  10802. this.dispatchEvent( { type: 'dispose' } );
  10803. }
  10804. /**
  10805. * Setting this property to `true` indicates the engine the material
  10806. * needs to be recompiled.
  10807. *
  10808. * @type {boolean}
  10809. * @default false
  10810. * @param {boolean} value
  10811. */
  10812. set needsUpdate( value ) {
  10813. if ( value === true ) this.version ++;
  10814. }
  10815. onBuild( /* shaderobject, renderer */ ) {
  10816. console.warn( 'Material: onBuild() has been removed.' ); // @deprecated, r166
  10817. }
  10818. }
  10819. class MeshBasicMaterial extends Material {
  10820. constructor( parameters ) {
  10821. super();
  10822. this.isMeshBasicMaterial = true;
  10823. this.type = 'MeshBasicMaterial';
  10824. this.color = new Color( 0xffffff ); // emissive
  10825. this.map = null;
  10826. this.lightMap = null;
  10827. this.lightMapIntensity = 1.0;
  10828. this.aoMap = null;
  10829. this.aoMapIntensity = 1.0;
  10830. this.specularMap = null;
  10831. this.alphaMap = null;
  10832. this.envMap = null;
  10833. this.envMapRotation = new Euler();
  10834. this.combine = MultiplyOperation;
  10835. this.reflectivity = 1;
  10836. this.refractionRatio = 0.98;
  10837. this.wireframe = false;
  10838. this.wireframeLinewidth = 1;
  10839. this.wireframeLinecap = 'round';
  10840. this.wireframeLinejoin = 'round';
  10841. this.fog = true;
  10842. this.setValues( parameters );
  10843. }
  10844. copy( source ) {
  10845. super.copy( source );
  10846. this.color.copy( source.color );
  10847. this.map = source.map;
  10848. this.lightMap = source.lightMap;
  10849. this.lightMapIntensity = source.lightMapIntensity;
  10850. this.aoMap = source.aoMap;
  10851. this.aoMapIntensity = source.aoMapIntensity;
  10852. this.specularMap = source.specularMap;
  10853. this.alphaMap = source.alphaMap;
  10854. this.envMap = source.envMap;
  10855. this.envMapRotation.copy( source.envMapRotation );
  10856. this.combine = source.combine;
  10857. this.reflectivity = source.reflectivity;
  10858. this.refractionRatio = source.refractionRatio;
  10859. this.wireframe = source.wireframe;
  10860. this.wireframeLinewidth = source.wireframeLinewidth;
  10861. this.wireframeLinecap = source.wireframeLinecap;
  10862. this.wireframeLinejoin = source.wireframeLinejoin;
  10863. this.fog = source.fog;
  10864. return this;
  10865. }
  10866. }
  10867. // Fast Half Float Conversions, http://www.fox-toolkit.org/ftp/fasthalffloatconversion.pdf
  10868. const _tables = /*@__PURE__*/ _generateTables();
  10869. function _generateTables() {
  10870. // float32 to float16 helpers
  10871. const buffer = new ArrayBuffer( 4 );
  10872. const floatView = new Float32Array( buffer );
  10873. const uint32View = new Uint32Array( buffer );
  10874. const baseTable = new Uint32Array( 512 );
  10875. const shiftTable = new Uint32Array( 512 );
  10876. for ( let i = 0; i < 256; ++ i ) {
  10877. const e = i - 127;
  10878. // very small number (0, -0)
  10879. if ( e < -27 ) {
  10880. baseTable[ i ] = 0x0000;
  10881. baseTable[ i | 0x100 ] = 0x8000;
  10882. shiftTable[ i ] = 24;
  10883. shiftTable[ i | 0x100 ] = 24;
  10884. // small number (denorm)
  10885. } else if ( e < -14 ) {
  10886. baseTable[ i ] = 0x0400 >> ( - e - 14 );
  10887. baseTable[ i | 0x100 ] = ( 0x0400 >> ( - e - 14 ) ) | 0x8000;
  10888. shiftTable[ i ] = - e - 1;
  10889. shiftTable[ i | 0x100 ] = - e - 1;
  10890. // normal number
  10891. } else if ( e <= 15 ) {
  10892. baseTable[ i ] = ( e + 15 ) << 10;
  10893. baseTable[ i | 0x100 ] = ( ( e + 15 ) << 10 ) | 0x8000;
  10894. shiftTable[ i ] = 13;
  10895. shiftTable[ i | 0x100 ] = 13;
  10896. // large number (Infinity, -Infinity)
  10897. } else if ( e < 128 ) {
  10898. baseTable[ i ] = 0x7c00;
  10899. baseTable[ i | 0x100 ] = 0xfc00;
  10900. shiftTable[ i ] = 24;
  10901. shiftTable[ i | 0x100 ] = 24;
  10902. // stay (NaN, Infinity, -Infinity)
  10903. } else {
  10904. baseTable[ i ] = 0x7c00;
  10905. baseTable[ i | 0x100 ] = 0xfc00;
  10906. shiftTable[ i ] = 13;
  10907. shiftTable[ i | 0x100 ] = 13;
  10908. }
  10909. }
  10910. // float16 to float32 helpers
  10911. const mantissaTable = new Uint32Array( 2048 );
  10912. const exponentTable = new Uint32Array( 64 );
  10913. const offsetTable = new Uint32Array( 64 );
  10914. for ( let i = 1; i < 1024; ++ i ) {
  10915. let m = i << 13; // zero pad mantissa bits
  10916. let e = 0; // zero exponent
  10917. // normalized
  10918. while ( ( m & 0x00800000 ) === 0 ) {
  10919. m <<= 1;
  10920. e -= 0x00800000; // decrement exponent
  10921. }
  10922. m &= -8388609; // clear leading 1 bit
  10923. e += 0x38800000; // adjust bias
  10924. mantissaTable[ i ] = m | e;
  10925. }
  10926. for ( let i = 1024; i < 2048; ++ i ) {
  10927. mantissaTable[ i ] = 0x38000000 + ( ( i - 1024 ) << 13 );
  10928. }
  10929. for ( let i = 1; i < 31; ++ i ) {
  10930. exponentTable[ i ] = i << 23;
  10931. }
  10932. exponentTable[ 31 ] = 0x47800000;
  10933. exponentTable[ 32 ] = 0x80000000;
  10934. for ( let i = 33; i < 63; ++ i ) {
  10935. exponentTable[ i ] = 0x80000000 + ( ( i - 32 ) << 23 );
  10936. }
  10937. exponentTable[ 63 ] = 0xc7800000;
  10938. for ( let i = 1; i < 64; ++ i ) {
  10939. if ( i !== 32 ) {
  10940. offsetTable[ i ] = 1024;
  10941. }
  10942. }
  10943. return {
  10944. floatView: floatView,
  10945. uint32View: uint32View,
  10946. baseTable: baseTable,
  10947. shiftTable: shiftTable,
  10948. mantissaTable: mantissaTable,
  10949. exponentTable: exponentTable,
  10950. offsetTable: offsetTable
  10951. };
  10952. }
  10953. /**
  10954. * Returns a half precision floating point value (FP16) from the given single
  10955. * precision floating point value (FP32).
  10956. *
  10957. * @param {number} val - A single precision floating point value.
  10958. * @return {number} The FP16 value.
  10959. */
  10960. function toHalfFloat( val ) {
  10961. if ( Math.abs( val ) > 65504 ) console.warn( 'THREE.DataUtils.toHalfFloat(): Value out of range.' );
  10962. val = clamp( val, -65504, 65504 );
  10963. _tables.floatView[ 0 ] = val;
  10964. const f = _tables.uint32View[ 0 ];
  10965. const e = ( f >> 23 ) & 0x1ff;
  10966. return _tables.baseTable[ e ] + ( ( f & 0x007fffff ) >> _tables.shiftTable[ e ] );
  10967. }
  10968. /**
  10969. * Returns a single precision floating point value (FP32) from the given half
  10970. * precision floating point value (FP16).
  10971. *
  10972. * @param {number} val - A half precision floating point value.
  10973. * @return {number} The FP32 value.
  10974. */
  10975. function fromHalfFloat( val ) {
  10976. const m = val >> 10;
  10977. _tables.uint32View[ 0 ] = _tables.mantissaTable[ _tables.offsetTable[ m ] + ( val & 0x3ff ) ] + _tables.exponentTable[ m ];
  10978. return _tables.floatView[ 0 ];
  10979. }
  10980. /**
  10981. * A class containing utility functions for data.
  10982. *
  10983. * @hideconstructor
  10984. */
  10985. class DataUtils {
  10986. /**
  10987. * Returns a half precision floating point value (FP16) from the given single
  10988. * precision floating point value (FP32).
  10989. *
  10990. * @param {number} val - A single precision floating point value.
  10991. * @return {number} The FP16 value.
  10992. */
  10993. static toHalfFloat( val ) {
  10994. return toHalfFloat( val );
  10995. }
  10996. /**
  10997. * Returns a single precision floating point value (FP32) from the given half
  10998. * precision floating point value (FP16).
  10999. *
  11000. * @param {number} val - A half precision floating point value.
  11001. * @return {number} The FP32 value.
  11002. */
  11003. static fromHalfFloat( val ) {
  11004. return fromHalfFloat( val );
  11005. }
  11006. }
  11007. const _vector$9 = /*@__PURE__*/ new Vector3();
  11008. const _vector2$1 = /*@__PURE__*/ new Vector2();
  11009. let _id$2 = 0;
  11010. class BufferAttribute {
  11011. constructor( array, itemSize, normalized = false ) {
  11012. if ( Array.isArray( array ) ) {
  11013. throw new TypeError( 'THREE.BufferAttribute: array should be a Typed Array.' );
  11014. }
  11015. this.isBufferAttribute = true;
  11016. Object.defineProperty( this, 'id', { value: _id$2 ++ } );
  11017. this.name = '';
  11018. this.array = array;
  11019. this.itemSize = itemSize;
  11020. this.count = array !== undefined ? array.length / itemSize : 0;
  11021. this.normalized = normalized;
  11022. this.usage = StaticDrawUsage;
  11023. this.updateRanges = [];
  11024. this.gpuType = FloatType;
  11025. this.version = 0;
  11026. }
  11027. onUploadCallback() {}
  11028. set needsUpdate( value ) {
  11029. if ( value === true ) this.version ++;
  11030. }
  11031. setUsage( value ) {
  11032. this.usage = value;
  11033. return this;
  11034. }
  11035. addUpdateRange( start, count ) {
  11036. this.updateRanges.push( { start, count } );
  11037. }
  11038. clearUpdateRanges() {
  11039. this.updateRanges.length = 0;
  11040. }
  11041. copy( source ) {
  11042. this.name = source.name;
  11043. this.array = new source.array.constructor( source.array );
  11044. this.itemSize = source.itemSize;
  11045. this.count = source.count;
  11046. this.normalized = source.normalized;
  11047. this.usage = source.usage;
  11048. this.gpuType = source.gpuType;
  11049. return this;
  11050. }
  11051. copyAt( index1, attribute, index2 ) {
  11052. index1 *= this.itemSize;
  11053. index2 *= attribute.itemSize;
  11054. for ( let i = 0, l = this.itemSize; i < l; i ++ ) {
  11055. this.array[ index1 + i ] = attribute.array[ index2 + i ];
  11056. }
  11057. return this;
  11058. }
  11059. copyArray( array ) {
  11060. this.array.set( array );
  11061. return this;
  11062. }
  11063. applyMatrix3( m ) {
  11064. if ( this.itemSize === 2 ) {
  11065. for ( let i = 0, l = this.count; i < l; i ++ ) {
  11066. _vector2$1.fromBufferAttribute( this, i );
  11067. _vector2$1.applyMatrix3( m );
  11068. this.setXY( i, _vector2$1.x, _vector2$1.y );
  11069. }
  11070. } else if ( this.itemSize === 3 ) {
  11071. for ( let i = 0, l = this.count; i < l; i ++ ) {
  11072. _vector$9.fromBufferAttribute( this, i );
  11073. _vector$9.applyMatrix3( m );
  11074. this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  11075. }
  11076. }
  11077. return this;
  11078. }
  11079. applyMatrix4( m ) {
  11080. for ( let i = 0, l = this.count; i < l; i ++ ) {
  11081. _vector$9.fromBufferAttribute( this, i );
  11082. _vector$9.applyMatrix4( m );
  11083. this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  11084. }
  11085. return this;
  11086. }
  11087. applyNormalMatrix( m ) {
  11088. for ( let i = 0, l = this.count; i < l; i ++ ) {
  11089. _vector$9.fromBufferAttribute( this, i );
  11090. _vector$9.applyNormalMatrix( m );
  11091. this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  11092. }
  11093. return this;
  11094. }
  11095. transformDirection( m ) {
  11096. for ( let i = 0, l = this.count; i < l; i ++ ) {
  11097. _vector$9.fromBufferAttribute( this, i );
  11098. _vector$9.transformDirection( m );
  11099. this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  11100. }
  11101. return this;
  11102. }
  11103. set( value, offset = 0 ) {
  11104. // Matching BufferAttribute constructor, do not normalize the array.
  11105. this.array.set( value, offset );
  11106. return this;
  11107. }
  11108. getComponent( index, component ) {
  11109. let value = this.array[ index * this.itemSize + component ];
  11110. if ( this.normalized ) value = denormalize( value, this.array );
  11111. return value;
  11112. }
  11113. setComponent( index, component, value ) {
  11114. if ( this.normalized ) value = normalize( value, this.array );
  11115. this.array[ index * this.itemSize + component ] = value;
  11116. return this;
  11117. }
  11118. getX( index ) {
  11119. let x = this.array[ index * this.itemSize ];
  11120. if ( this.normalized ) x = denormalize( x, this.array );
  11121. return x;
  11122. }
  11123. setX( index, x ) {
  11124. if ( this.normalized ) x = normalize( x, this.array );
  11125. this.array[ index * this.itemSize ] = x;
  11126. return this;
  11127. }
  11128. getY( index ) {
  11129. let y = this.array[ index * this.itemSize + 1 ];
  11130. if ( this.normalized ) y = denormalize( y, this.array );
  11131. return y;
  11132. }
  11133. setY( index, y ) {
  11134. if ( this.normalized ) y = normalize( y, this.array );
  11135. this.array[ index * this.itemSize + 1 ] = y;
  11136. return this;
  11137. }
  11138. getZ( index ) {
  11139. let z = this.array[ index * this.itemSize + 2 ];
  11140. if ( this.normalized ) z = denormalize( z, this.array );
  11141. return z;
  11142. }
  11143. setZ( index, z ) {
  11144. if ( this.normalized ) z = normalize( z, this.array );
  11145. this.array[ index * this.itemSize + 2 ] = z;
  11146. return this;
  11147. }
  11148. getW( index ) {
  11149. let w = this.array[ index * this.itemSize + 3 ];
  11150. if ( this.normalized ) w = denormalize( w, this.array );
  11151. return w;
  11152. }
  11153. setW( index, w ) {
  11154. if ( this.normalized ) w = normalize( w, this.array );
  11155. this.array[ index * this.itemSize + 3 ] = w;
  11156. return this;
  11157. }
  11158. setXY( index, x, y ) {
  11159. index *= this.itemSize;
  11160. if ( this.normalized ) {
  11161. x = normalize( x, this.array );
  11162. y = normalize( y, this.array );
  11163. }
  11164. this.array[ index + 0 ] = x;
  11165. this.array[ index + 1 ] = y;
  11166. return this;
  11167. }
  11168. setXYZ( index, x, y, z ) {
  11169. index *= this.itemSize;
  11170. if ( this.normalized ) {
  11171. x = normalize( x, this.array );
  11172. y = normalize( y, this.array );
  11173. z = normalize( z, this.array );
  11174. }
  11175. this.array[ index + 0 ] = x;
  11176. this.array[ index + 1 ] = y;
  11177. this.array[ index + 2 ] = z;
  11178. return this;
  11179. }
  11180. setXYZW( index, x, y, z, w ) {
  11181. index *= this.itemSize;
  11182. if ( this.normalized ) {
  11183. x = normalize( x, this.array );
  11184. y = normalize( y, this.array );
  11185. z = normalize( z, this.array );
  11186. w = normalize( w, this.array );
  11187. }
  11188. this.array[ index + 0 ] = x;
  11189. this.array[ index + 1 ] = y;
  11190. this.array[ index + 2 ] = z;
  11191. this.array[ index + 3 ] = w;
  11192. return this;
  11193. }
  11194. onUpload( callback ) {
  11195. this.onUploadCallback = callback;
  11196. return this;
  11197. }
  11198. clone() {
  11199. return new this.constructor( this.array, this.itemSize ).copy( this );
  11200. }
  11201. toJSON() {
  11202. const data = {
  11203. itemSize: this.itemSize,
  11204. type: this.array.constructor.name,
  11205. array: Array.from( this.array ),
  11206. normalized: this.normalized
  11207. };
  11208. if ( this.name !== '' ) data.name = this.name;
  11209. if ( this.usage !== StaticDrawUsage ) data.usage = this.usage;
  11210. return data;
  11211. }
  11212. }
  11213. //
  11214. class Int8BufferAttribute extends BufferAttribute {
  11215. constructor( array, itemSize, normalized ) {
  11216. super( new Int8Array( array ), itemSize, normalized );
  11217. }
  11218. }
  11219. class Uint8BufferAttribute extends BufferAttribute {
  11220. constructor( array, itemSize, normalized ) {
  11221. super( new Uint8Array( array ), itemSize, normalized );
  11222. }
  11223. }
  11224. class Uint8ClampedBufferAttribute extends BufferAttribute {
  11225. constructor( array, itemSize, normalized ) {
  11226. super( new Uint8ClampedArray( array ), itemSize, normalized );
  11227. }
  11228. }
  11229. class Int16BufferAttribute extends BufferAttribute {
  11230. constructor( array, itemSize, normalized ) {
  11231. super( new Int16Array( array ), itemSize, normalized );
  11232. }
  11233. }
  11234. class Uint16BufferAttribute extends BufferAttribute {
  11235. constructor( array, itemSize, normalized ) {
  11236. super( new Uint16Array( array ), itemSize, normalized );
  11237. }
  11238. }
  11239. class Int32BufferAttribute extends BufferAttribute {
  11240. constructor( array, itemSize, normalized ) {
  11241. super( new Int32Array( array ), itemSize, normalized );
  11242. }
  11243. }
  11244. class Uint32BufferAttribute extends BufferAttribute {
  11245. constructor( array, itemSize, normalized ) {
  11246. super( new Uint32Array( array ), itemSize, normalized );
  11247. }
  11248. }
  11249. class Float16BufferAttribute extends BufferAttribute {
  11250. constructor( array, itemSize, normalized ) {
  11251. super( new Uint16Array( array ), itemSize, normalized );
  11252. this.isFloat16BufferAttribute = true;
  11253. }
  11254. getX( index ) {
  11255. let x = fromHalfFloat( this.array[ index * this.itemSize ] );
  11256. if ( this.normalized ) x = denormalize( x, this.array );
  11257. return x;
  11258. }
  11259. setX( index, x ) {
  11260. if ( this.normalized ) x = normalize( x, this.array );
  11261. this.array[ index * this.itemSize ] = toHalfFloat( x );
  11262. return this;
  11263. }
  11264. getY( index ) {
  11265. let y = fromHalfFloat( this.array[ index * this.itemSize + 1 ] );
  11266. if ( this.normalized ) y = denormalize( y, this.array );
  11267. return y;
  11268. }
  11269. setY( index, y ) {
  11270. if ( this.normalized ) y = normalize( y, this.array );
  11271. this.array[ index * this.itemSize + 1 ] = toHalfFloat( y );
  11272. return this;
  11273. }
  11274. getZ( index ) {
  11275. let z = fromHalfFloat( this.array[ index * this.itemSize + 2 ] );
  11276. if ( this.normalized ) z = denormalize( z, this.array );
  11277. return z;
  11278. }
  11279. setZ( index, z ) {
  11280. if ( this.normalized ) z = normalize( z, this.array );
  11281. this.array[ index * this.itemSize + 2 ] = toHalfFloat( z );
  11282. return this;
  11283. }
  11284. getW( index ) {
  11285. let w = fromHalfFloat( this.array[ index * this.itemSize + 3 ] );
  11286. if ( this.normalized ) w = denormalize( w, this.array );
  11287. return w;
  11288. }
  11289. setW( index, w ) {
  11290. if ( this.normalized ) w = normalize( w, this.array );
  11291. this.array[ index * this.itemSize + 3 ] = toHalfFloat( w );
  11292. return this;
  11293. }
  11294. setXY( index, x, y ) {
  11295. index *= this.itemSize;
  11296. if ( this.normalized ) {
  11297. x = normalize( x, this.array );
  11298. y = normalize( y, this.array );
  11299. }
  11300. this.array[ index + 0 ] = toHalfFloat( x );
  11301. this.array[ index + 1 ] = toHalfFloat( y );
  11302. return this;
  11303. }
  11304. setXYZ( index, x, y, z ) {
  11305. index *= this.itemSize;
  11306. if ( this.normalized ) {
  11307. x = normalize( x, this.array );
  11308. y = normalize( y, this.array );
  11309. z = normalize( z, this.array );
  11310. }
  11311. this.array[ index + 0 ] = toHalfFloat( x );
  11312. this.array[ index + 1 ] = toHalfFloat( y );
  11313. this.array[ index + 2 ] = toHalfFloat( z );
  11314. return this;
  11315. }
  11316. setXYZW( index, x, y, z, w ) {
  11317. index *= this.itemSize;
  11318. if ( this.normalized ) {
  11319. x = normalize( x, this.array );
  11320. y = normalize( y, this.array );
  11321. z = normalize( z, this.array );
  11322. w = normalize( w, this.array );
  11323. }
  11324. this.array[ index + 0 ] = toHalfFloat( x );
  11325. this.array[ index + 1 ] = toHalfFloat( y );
  11326. this.array[ index + 2 ] = toHalfFloat( z );
  11327. this.array[ index + 3 ] = toHalfFloat( w );
  11328. return this;
  11329. }
  11330. }
  11331. class Float32BufferAttribute extends BufferAttribute {
  11332. constructor( array, itemSize, normalized ) {
  11333. super( new Float32Array( array ), itemSize, normalized );
  11334. }
  11335. }
  11336. let _id$1 = 0;
  11337. const _m1 = /*@__PURE__*/ new Matrix4();
  11338. const _obj = /*@__PURE__*/ new Object3D();
  11339. const _offset = /*@__PURE__*/ new Vector3();
  11340. const _box$2 = /*@__PURE__*/ new Box3();
  11341. const _boxMorphTargets = /*@__PURE__*/ new Box3();
  11342. const _vector$8 = /*@__PURE__*/ new Vector3();
  11343. class BufferGeometry extends EventDispatcher {
  11344. constructor() {
  11345. super();
  11346. this.isBufferGeometry = true;
  11347. Object.defineProperty( this, 'id', { value: _id$1 ++ } );
  11348. this.uuid = generateUUID();
  11349. this.name = '';
  11350. this.type = 'BufferGeometry';
  11351. this.index = null;
  11352. this.indirect = null;
  11353. this.attributes = {};
  11354. this.morphAttributes = {};
  11355. this.morphTargetsRelative = false;
  11356. this.groups = [];
  11357. this.boundingBox = null;
  11358. this.boundingSphere = null;
  11359. this.drawRange = { start: 0, count: Infinity };
  11360. this.userData = {};
  11361. }
  11362. getIndex() {
  11363. return this.index;
  11364. }
  11365. setIndex( index ) {
  11366. if ( Array.isArray( index ) ) {
  11367. this.index = new ( arrayNeedsUint32( index ) ? Uint32BufferAttribute : Uint16BufferAttribute )( index, 1 );
  11368. } else {
  11369. this.index = index;
  11370. }
  11371. return this;
  11372. }
  11373. setIndirect( indirect ) {
  11374. this.indirect = indirect;
  11375. return this;
  11376. }
  11377. getIndirect() {
  11378. return this.indirect;
  11379. }
  11380. getAttribute( name ) {
  11381. return this.attributes[ name ];
  11382. }
  11383. setAttribute( name, attribute ) {
  11384. this.attributes[ name ] = attribute;
  11385. return this;
  11386. }
  11387. deleteAttribute( name ) {
  11388. delete this.attributes[ name ];
  11389. return this;
  11390. }
  11391. hasAttribute( name ) {
  11392. return this.attributes[ name ] !== undefined;
  11393. }
  11394. addGroup( start, count, materialIndex = 0 ) {
  11395. this.groups.push( {
  11396. start: start,
  11397. count: count,
  11398. materialIndex: materialIndex
  11399. } );
  11400. }
  11401. clearGroups() {
  11402. this.groups = [];
  11403. }
  11404. setDrawRange( start, count ) {
  11405. this.drawRange.start = start;
  11406. this.drawRange.count = count;
  11407. }
  11408. applyMatrix4( matrix ) {
  11409. const position = this.attributes.position;
  11410. if ( position !== undefined ) {
  11411. position.applyMatrix4( matrix );
  11412. position.needsUpdate = true;
  11413. }
  11414. const normal = this.attributes.normal;
  11415. if ( normal !== undefined ) {
  11416. const normalMatrix = new Matrix3().getNormalMatrix( matrix );
  11417. normal.applyNormalMatrix( normalMatrix );
  11418. normal.needsUpdate = true;
  11419. }
  11420. const tangent = this.attributes.tangent;
  11421. if ( tangent !== undefined ) {
  11422. tangent.transformDirection( matrix );
  11423. tangent.needsUpdate = true;
  11424. }
  11425. if ( this.boundingBox !== null ) {
  11426. this.computeBoundingBox();
  11427. }
  11428. if ( this.boundingSphere !== null ) {
  11429. this.computeBoundingSphere();
  11430. }
  11431. return this;
  11432. }
  11433. applyQuaternion( q ) {
  11434. _m1.makeRotationFromQuaternion( q );
  11435. this.applyMatrix4( _m1 );
  11436. return this;
  11437. }
  11438. rotateX( angle ) {
  11439. // rotate geometry around world x-axis
  11440. _m1.makeRotationX( angle );
  11441. this.applyMatrix4( _m1 );
  11442. return this;
  11443. }
  11444. rotateY( angle ) {
  11445. // rotate geometry around world y-axis
  11446. _m1.makeRotationY( angle );
  11447. this.applyMatrix4( _m1 );
  11448. return this;
  11449. }
  11450. rotateZ( angle ) {
  11451. // rotate geometry around world z-axis
  11452. _m1.makeRotationZ( angle );
  11453. this.applyMatrix4( _m1 );
  11454. return this;
  11455. }
  11456. translate( x, y, z ) {
  11457. // translate geometry
  11458. _m1.makeTranslation( x, y, z );
  11459. this.applyMatrix4( _m1 );
  11460. return this;
  11461. }
  11462. scale( x, y, z ) {
  11463. // scale geometry
  11464. _m1.makeScale( x, y, z );
  11465. this.applyMatrix4( _m1 );
  11466. return this;
  11467. }
  11468. lookAt( vector ) {
  11469. _obj.lookAt( vector );
  11470. _obj.updateMatrix();
  11471. this.applyMatrix4( _obj.matrix );
  11472. return this;
  11473. }
  11474. center() {
  11475. this.computeBoundingBox();
  11476. this.boundingBox.getCenter( _offset ).negate();
  11477. this.translate( _offset.x, _offset.y, _offset.z );
  11478. return this;
  11479. }
  11480. setFromPoints( points ) {
  11481. const positionAttribute = this.getAttribute( 'position' );
  11482. if ( positionAttribute === undefined ) {
  11483. const position = [];
  11484. for ( let i = 0, l = points.length; i < l; i ++ ) {
  11485. const point = points[ i ];
  11486. position.push( point.x, point.y, point.z || 0 );
  11487. }
  11488. this.setAttribute( 'position', new Float32BufferAttribute( position, 3 ) );
  11489. } else {
  11490. const l = Math.min( points.length, positionAttribute.count ); // make sure data do not exceed buffer size
  11491. for ( let i = 0; i < l; i ++ ) {
  11492. const point = points[ i ];
  11493. positionAttribute.setXYZ( i, point.x, point.y, point.z || 0 );
  11494. }
  11495. if ( points.length > positionAttribute.count ) {
  11496. console.warn( 'THREE.BufferGeometry: Buffer size too small for points data. Use .dispose() and create a new geometry.' );
  11497. }
  11498. positionAttribute.needsUpdate = true;
  11499. }
  11500. return this;
  11501. }
  11502. computeBoundingBox() {
  11503. if ( this.boundingBox === null ) {
  11504. this.boundingBox = new Box3();
  11505. }
  11506. const position = this.attributes.position;
  11507. const morphAttributesPosition = this.morphAttributes.position;
  11508. if ( position && position.isGLBufferAttribute ) {
  11509. console.error( 'THREE.BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box.', this );
  11510. this.boundingBox.set(
  11511. new Vector3( - Infinity, - Infinity, - Infinity ),
  11512. new Vector3( + Infinity, + Infinity, + Infinity )
  11513. );
  11514. return;
  11515. }
  11516. if ( position !== undefined ) {
  11517. this.boundingBox.setFromBufferAttribute( position );
  11518. // process morph attributes if present
  11519. if ( morphAttributesPosition ) {
  11520. for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  11521. const morphAttribute = morphAttributesPosition[ i ];
  11522. _box$2.setFromBufferAttribute( morphAttribute );
  11523. if ( this.morphTargetsRelative ) {
  11524. _vector$8.addVectors( this.boundingBox.min, _box$2.min );
  11525. this.boundingBox.expandByPoint( _vector$8 );
  11526. _vector$8.addVectors( this.boundingBox.max, _box$2.max );
  11527. this.boundingBox.expandByPoint( _vector$8 );
  11528. } else {
  11529. this.boundingBox.expandByPoint( _box$2.min );
  11530. this.boundingBox.expandByPoint( _box$2.max );
  11531. }
  11532. }
  11533. }
  11534. } else {
  11535. this.boundingBox.makeEmpty();
  11536. }
  11537. if ( isNaN( this.boundingBox.min.x ) || isNaN( this.boundingBox.min.y ) || isNaN( this.boundingBox.min.z ) ) {
  11538. console.error( 'THREE.BufferGeometry.computeBoundingBox(): Computed min/max have NaN values. The "position" attribute is likely to have NaN values.', this );
  11539. }
  11540. }
  11541. computeBoundingSphere() {
  11542. if ( this.boundingSphere === null ) {
  11543. this.boundingSphere = new Sphere();
  11544. }
  11545. const position = this.attributes.position;
  11546. const morphAttributesPosition = this.morphAttributes.position;
  11547. if ( position && position.isGLBufferAttribute ) {
  11548. console.error( 'THREE.BufferGeometry.computeBoundingSphere(): GLBufferAttribute requires a manual bounding sphere.', this );
  11549. this.boundingSphere.set( new Vector3(), Infinity );
  11550. return;
  11551. }
  11552. if ( position ) {
  11553. // first, find the center of the bounding sphere
  11554. const center = this.boundingSphere.center;
  11555. _box$2.setFromBufferAttribute( position );
  11556. // process morph attributes if present
  11557. if ( morphAttributesPosition ) {
  11558. for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  11559. const morphAttribute = morphAttributesPosition[ i ];
  11560. _boxMorphTargets.setFromBufferAttribute( morphAttribute );
  11561. if ( this.morphTargetsRelative ) {
  11562. _vector$8.addVectors( _box$2.min, _boxMorphTargets.min );
  11563. _box$2.expandByPoint( _vector$8 );
  11564. _vector$8.addVectors( _box$2.max, _boxMorphTargets.max );
  11565. _box$2.expandByPoint( _vector$8 );
  11566. } else {
  11567. _box$2.expandByPoint( _boxMorphTargets.min );
  11568. _box$2.expandByPoint( _boxMorphTargets.max );
  11569. }
  11570. }
  11571. }
  11572. _box$2.getCenter( center );
  11573. // second, try to find a boundingSphere with a radius smaller than the
  11574. // boundingSphere of the boundingBox: sqrt(3) smaller in the best case
  11575. let maxRadiusSq = 0;
  11576. for ( let i = 0, il = position.count; i < il; i ++ ) {
  11577. _vector$8.fromBufferAttribute( position, i );
  11578. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( _vector$8 ) );
  11579. }
  11580. // process morph attributes if present
  11581. if ( morphAttributesPosition ) {
  11582. for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  11583. const morphAttribute = morphAttributesPosition[ i ];
  11584. const morphTargetsRelative = this.morphTargetsRelative;
  11585. for ( let j = 0, jl = morphAttribute.count; j < jl; j ++ ) {
  11586. _vector$8.fromBufferAttribute( morphAttribute, j );
  11587. if ( morphTargetsRelative ) {
  11588. _offset.fromBufferAttribute( position, j );
  11589. _vector$8.add( _offset );
  11590. }
  11591. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( _vector$8 ) );
  11592. }
  11593. }
  11594. }
  11595. this.boundingSphere.radius = Math.sqrt( maxRadiusSq );
  11596. if ( isNaN( this.boundingSphere.radius ) ) {
  11597. console.error( 'THREE.BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.', this );
  11598. }
  11599. }
  11600. }
  11601. computeTangents() {
  11602. const index = this.index;
  11603. const attributes = this.attributes;
  11604. // based on http://www.terathon.com/code/tangent.html
  11605. // (per vertex tangents)
  11606. if ( index === null ||
  11607. attributes.position === undefined ||
  11608. attributes.normal === undefined ||
  11609. attributes.uv === undefined ) {
  11610. console.error( 'THREE.BufferGeometry: .computeTangents() failed. Missing required attributes (index, position, normal or uv)' );
  11611. return;
  11612. }
  11613. const positionAttribute = attributes.position;
  11614. const normalAttribute = attributes.normal;
  11615. const uvAttribute = attributes.uv;
  11616. if ( this.hasAttribute( 'tangent' ) === false ) {
  11617. this.setAttribute( 'tangent', new BufferAttribute( new Float32Array( 4 * positionAttribute.count ), 4 ) );
  11618. }
  11619. const tangentAttribute = this.getAttribute( 'tangent' );
  11620. const tan1 = [], tan2 = [];
  11621. for ( let i = 0; i < positionAttribute.count; i ++ ) {
  11622. tan1[ i ] = new Vector3();
  11623. tan2[ i ] = new Vector3();
  11624. }
  11625. const vA = new Vector3(),
  11626. vB = new Vector3(),
  11627. vC = new Vector3(),
  11628. uvA = new Vector2(),
  11629. uvB = new Vector2(),
  11630. uvC = new Vector2(),
  11631. sdir = new Vector3(),
  11632. tdir = new Vector3();
  11633. function handleTriangle( a, b, c ) {
  11634. vA.fromBufferAttribute( positionAttribute, a );
  11635. vB.fromBufferAttribute( positionAttribute, b );
  11636. vC.fromBufferAttribute( positionAttribute, c );
  11637. uvA.fromBufferAttribute( uvAttribute, a );
  11638. uvB.fromBufferAttribute( uvAttribute, b );
  11639. uvC.fromBufferAttribute( uvAttribute, c );
  11640. vB.sub( vA );
  11641. vC.sub( vA );
  11642. uvB.sub( uvA );
  11643. uvC.sub( uvA );
  11644. const r = 1.0 / ( uvB.x * uvC.y - uvC.x * uvB.y );
  11645. // silently ignore degenerate uv triangles having coincident or colinear vertices
  11646. if ( ! isFinite( r ) ) return;
  11647. sdir.copy( vB ).multiplyScalar( uvC.y ).addScaledVector( vC, - uvB.y ).multiplyScalar( r );
  11648. tdir.copy( vC ).multiplyScalar( uvB.x ).addScaledVector( vB, - uvC.x ).multiplyScalar( r );
  11649. tan1[ a ].add( sdir );
  11650. tan1[ b ].add( sdir );
  11651. tan1[ c ].add( sdir );
  11652. tan2[ a ].add( tdir );
  11653. tan2[ b ].add( tdir );
  11654. tan2[ c ].add( tdir );
  11655. }
  11656. let groups = this.groups;
  11657. if ( groups.length === 0 ) {
  11658. groups = [ {
  11659. start: 0,
  11660. count: index.count
  11661. } ];
  11662. }
  11663. for ( let i = 0, il = groups.length; i < il; ++ i ) {
  11664. const group = groups[ i ];
  11665. const start = group.start;
  11666. const count = group.count;
  11667. for ( let j = start, jl = start + count; j < jl; j += 3 ) {
  11668. handleTriangle(
  11669. index.getX( j + 0 ),
  11670. index.getX( j + 1 ),
  11671. index.getX( j + 2 )
  11672. );
  11673. }
  11674. }
  11675. const tmp = new Vector3(), tmp2 = new Vector3();
  11676. const n = new Vector3(), n2 = new Vector3();
  11677. function handleVertex( v ) {
  11678. n.fromBufferAttribute( normalAttribute, v );
  11679. n2.copy( n );
  11680. const t = tan1[ v ];
  11681. // Gram-Schmidt orthogonalize
  11682. tmp.copy( t );
  11683. tmp.sub( n.multiplyScalar( n.dot( t ) ) ).normalize();
  11684. // Calculate handedness
  11685. tmp2.crossVectors( n2, t );
  11686. const test = tmp2.dot( tan2[ v ] );
  11687. const w = ( test < 0.0 ) ? -1 : 1.0;
  11688. tangentAttribute.setXYZW( v, tmp.x, tmp.y, tmp.z, w );
  11689. }
  11690. for ( let i = 0, il = groups.length; i < il; ++ i ) {
  11691. const group = groups[ i ];
  11692. const start = group.start;
  11693. const count = group.count;
  11694. for ( let j = start, jl = start + count; j < jl; j += 3 ) {
  11695. handleVertex( index.getX( j + 0 ) );
  11696. handleVertex( index.getX( j + 1 ) );
  11697. handleVertex( index.getX( j + 2 ) );
  11698. }
  11699. }
  11700. }
  11701. computeVertexNormals() {
  11702. const index = this.index;
  11703. const positionAttribute = this.getAttribute( 'position' );
  11704. if ( positionAttribute !== undefined ) {
  11705. let normalAttribute = this.getAttribute( 'normal' );
  11706. if ( normalAttribute === undefined ) {
  11707. normalAttribute = new BufferAttribute( new Float32Array( positionAttribute.count * 3 ), 3 );
  11708. this.setAttribute( 'normal', normalAttribute );
  11709. } else {
  11710. // reset existing normals to zero
  11711. for ( let i = 0, il = normalAttribute.count; i < il; i ++ ) {
  11712. normalAttribute.setXYZ( i, 0, 0, 0 );
  11713. }
  11714. }
  11715. const pA = new Vector3(), pB = new Vector3(), pC = new Vector3();
  11716. const nA = new Vector3(), nB = new Vector3(), nC = new Vector3();
  11717. const cb = new Vector3(), ab = new Vector3();
  11718. // indexed elements
  11719. if ( index ) {
  11720. for ( let i = 0, il = index.count; i < il; i += 3 ) {
  11721. const vA = index.getX( i + 0 );
  11722. const vB = index.getX( i + 1 );
  11723. const vC = index.getX( i + 2 );
  11724. pA.fromBufferAttribute( positionAttribute, vA );
  11725. pB.fromBufferAttribute( positionAttribute, vB );
  11726. pC.fromBufferAttribute( positionAttribute, vC );
  11727. cb.subVectors( pC, pB );
  11728. ab.subVectors( pA, pB );
  11729. cb.cross( ab );
  11730. nA.fromBufferAttribute( normalAttribute, vA );
  11731. nB.fromBufferAttribute( normalAttribute, vB );
  11732. nC.fromBufferAttribute( normalAttribute, vC );
  11733. nA.add( cb );
  11734. nB.add( cb );
  11735. nC.add( cb );
  11736. normalAttribute.setXYZ( vA, nA.x, nA.y, nA.z );
  11737. normalAttribute.setXYZ( vB, nB.x, nB.y, nB.z );
  11738. normalAttribute.setXYZ( vC, nC.x, nC.y, nC.z );
  11739. }
  11740. } else {
  11741. // non-indexed elements (unconnected triangle soup)
  11742. for ( let i = 0, il = positionAttribute.count; i < il; i += 3 ) {
  11743. pA.fromBufferAttribute( positionAttribute, i + 0 );
  11744. pB.fromBufferAttribute( positionAttribute, i + 1 );
  11745. pC.fromBufferAttribute( positionAttribute, i + 2 );
  11746. cb.subVectors( pC, pB );
  11747. ab.subVectors( pA, pB );
  11748. cb.cross( ab );
  11749. normalAttribute.setXYZ( i + 0, cb.x, cb.y, cb.z );
  11750. normalAttribute.setXYZ( i + 1, cb.x, cb.y, cb.z );
  11751. normalAttribute.setXYZ( i + 2, cb.x, cb.y, cb.z );
  11752. }
  11753. }
  11754. this.normalizeNormals();
  11755. normalAttribute.needsUpdate = true;
  11756. }
  11757. }
  11758. normalizeNormals() {
  11759. const normals = this.attributes.normal;
  11760. for ( let i = 0, il = normals.count; i < il; i ++ ) {
  11761. _vector$8.fromBufferAttribute( normals, i );
  11762. _vector$8.normalize();
  11763. normals.setXYZ( i, _vector$8.x, _vector$8.y, _vector$8.z );
  11764. }
  11765. }
  11766. toNonIndexed() {
  11767. function convertBufferAttribute( attribute, indices ) {
  11768. const array = attribute.array;
  11769. const itemSize = attribute.itemSize;
  11770. const normalized = attribute.normalized;
  11771. const array2 = new array.constructor( indices.length * itemSize );
  11772. let index = 0, index2 = 0;
  11773. for ( let i = 0, l = indices.length; i < l; i ++ ) {
  11774. if ( attribute.isInterleavedBufferAttribute ) {
  11775. index = indices[ i ] * attribute.data.stride + attribute.offset;
  11776. } else {
  11777. index = indices[ i ] * itemSize;
  11778. }
  11779. for ( let j = 0; j < itemSize; j ++ ) {
  11780. array2[ index2 ++ ] = array[ index ++ ];
  11781. }
  11782. }
  11783. return new BufferAttribute( array2, itemSize, normalized );
  11784. }
  11785. //
  11786. if ( this.index === null ) {
  11787. console.warn( 'THREE.BufferGeometry.toNonIndexed(): BufferGeometry is already non-indexed.' );
  11788. return this;
  11789. }
  11790. const geometry2 = new BufferGeometry();
  11791. const indices = this.index.array;
  11792. const attributes = this.attributes;
  11793. // attributes
  11794. for ( const name in attributes ) {
  11795. const attribute = attributes[ name ];
  11796. const newAttribute = convertBufferAttribute( attribute, indices );
  11797. geometry2.setAttribute( name, newAttribute );
  11798. }
  11799. // morph attributes
  11800. const morphAttributes = this.morphAttributes;
  11801. for ( const name in morphAttributes ) {
  11802. const morphArray = [];
  11803. const morphAttribute = morphAttributes[ name ]; // morphAttribute: array of Float32BufferAttributes
  11804. for ( let i = 0, il = morphAttribute.length; i < il; i ++ ) {
  11805. const attribute = morphAttribute[ i ];
  11806. const newAttribute = convertBufferAttribute( attribute, indices );
  11807. morphArray.push( newAttribute );
  11808. }
  11809. geometry2.morphAttributes[ name ] = morphArray;
  11810. }
  11811. geometry2.morphTargetsRelative = this.morphTargetsRelative;
  11812. // groups
  11813. const groups = this.groups;
  11814. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  11815. const group = groups[ i ];
  11816. geometry2.addGroup( group.start, group.count, group.materialIndex );
  11817. }
  11818. return geometry2;
  11819. }
  11820. toJSON() {
  11821. const data = {
  11822. metadata: {
  11823. version: 4.6,
  11824. type: 'BufferGeometry',
  11825. generator: 'BufferGeometry.toJSON'
  11826. }
  11827. };
  11828. // standard BufferGeometry serialization
  11829. data.uuid = this.uuid;
  11830. data.type = this.type;
  11831. if ( this.name !== '' ) data.name = this.name;
  11832. if ( Object.keys( this.userData ).length > 0 ) data.userData = this.userData;
  11833. if ( this.parameters !== undefined ) {
  11834. const parameters = this.parameters;
  11835. for ( const key in parameters ) {
  11836. if ( parameters[ key ] !== undefined ) data[ key ] = parameters[ key ];
  11837. }
  11838. return data;
  11839. }
  11840. // for simplicity the code assumes attributes are not shared across geometries, see #15811
  11841. data.data = { attributes: {} };
  11842. const index = this.index;
  11843. if ( index !== null ) {
  11844. data.data.index = {
  11845. type: index.array.constructor.name,
  11846. array: Array.prototype.slice.call( index.array )
  11847. };
  11848. }
  11849. const attributes = this.attributes;
  11850. for ( const key in attributes ) {
  11851. const attribute = attributes[ key ];
  11852. data.data.attributes[ key ] = attribute.toJSON( data.data );
  11853. }
  11854. const morphAttributes = {};
  11855. let hasMorphAttributes = false;
  11856. for ( const key in this.morphAttributes ) {
  11857. const attributeArray = this.morphAttributes[ key ];
  11858. const array = [];
  11859. for ( let i = 0, il = attributeArray.length; i < il; i ++ ) {
  11860. const attribute = attributeArray[ i ];
  11861. array.push( attribute.toJSON( data.data ) );
  11862. }
  11863. if ( array.length > 0 ) {
  11864. morphAttributes[ key ] = array;
  11865. hasMorphAttributes = true;
  11866. }
  11867. }
  11868. if ( hasMorphAttributes ) {
  11869. data.data.morphAttributes = morphAttributes;
  11870. data.data.morphTargetsRelative = this.morphTargetsRelative;
  11871. }
  11872. const groups = this.groups;
  11873. if ( groups.length > 0 ) {
  11874. data.data.groups = JSON.parse( JSON.stringify( groups ) );
  11875. }
  11876. const boundingSphere = this.boundingSphere;
  11877. if ( boundingSphere !== null ) {
  11878. data.data.boundingSphere = {
  11879. center: boundingSphere.center.toArray(),
  11880. radius: boundingSphere.radius
  11881. };
  11882. }
  11883. return data;
  11884. }
  11885. clone() {
  11886. return new this.constructor().copy( this );
  11887. }
  11888. copy( source ) {
  11889. // reset
  11890. this.index = null;
  11891. this.attributes = {};
  11892. this.morphAttributes = {};
  11893. this.groups = [];
  11894. this.boundingBox = null;
  11895. this.boundingSphere = null;
  11896. // used for storing cloned, shared data
  11897. const data = {};
  11898. // name
  11899. this.name = source.name;
  11900. // index
  11901. const index = source.index;
  11902. if ( index !== null ) {
  11903. this.setIndex( index.clone( data ) );
  11904. }
  11905. // attributes
  11906. const attributes = source.attributes;
  11907. for ( const name in attributes ) {
  11908. const attribute = attributes[ name ];
  11909. this.setAttribute( name, attribute.clone( data ) );
  11910. }
  11911. // morph attributes
  11912. const morphAttributes = source.morphAttributes;
  11913. for ( const name in morphAttributes ) {
  11914. const array = [];
  11915. const morphAttribute = morphAttributes[ name ]; // morphAttribute: array of Float32BufferAttributes
  11916. for ( let i = 0, l = morphAttribute.length; i < l; i ++ ) {
  11917. array.push( morphAttribute[ i ].clone( data ) );
  11918. }
  11919. this.morphAttributes[ name ] = array;
  11920. }
  11921. this.morphTargetsRelative = source.morphTargetsRelative;
  11922. // groups
  11923. const groups = source.groups;
  11924. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  11925. const group = groups[ i ];
  11926. this.addGroup( group.start, group.count, group.materialIndex );
  11927. }
  11928. // bounding box
  11929. const boundingBox = source.boundingBox;
  11930. if ( boundingBox !== null ) {
  11931. this.boundingBox = boundingBox.clone();
  11932. }
  11933. // bounding sphere
  11934. const boundingSphere = source.boundingSphere;
  11935. if ( boundingSphere !== null ) {
  11936. this.boundingSphere = boundingSphere.clone();
  11937. }
  11938. // draw range
  11939. this.drawRange.start = source.drawRange.start;
  11940. this.drawRange.count = source.drawRange.count;
  11941. // user data
  11942. this.userData = source.userData;
  11943. return this;
  11944. }
  11945. dispose() {
  11946. this.dispatchEvent( { type: 'dispose' } );
  11947. }
  11948. }
  11949. const _inverseMatrix$3 = /*@__PURE__*/ new Matrix4();
  11950. const _ray$3 = /*@__PURE__*/ new Ray();
  11951. const _sphere$6 = /*@__PURE__*/ new Sphere();
  11952. const _sphereHitAt = /*@__PURE__*/ new Vector3();
  11953. const _vA$1 = /*@__PURE__*/ new Vector3();
  11954. const _vB$1 = /*@__PURE__*/ new Vector3();
  11955. const _vC$1 = /*@__PURE__*/ new Vector3();
  11956. const _tempA = /*@__PURE__*/ new Vector3();
  11957. const _morphA = /*@__PURE__*/ new Vector3();
  11958. const _intersectionPoint = /*@__PURE__*/ new Vector3();
  11959. const _intersectionPointWorld = /*@__PURE__*/ new Vector3();
  11960. class Mesh extends Object3D {
  11961. constructor( geometry = new BufferGeometry(), material = new MeshBasicMaterial() ) {
  11962. super();
  11963. this.isMesh = true;
  11964. this.type = 'Mesh';
  11965. this.geometry = geometry;
  11966. this.material = material;
  11967. this.updateMorphTargets();
  11968. }
  11969. copy( source, recursive ) {
  11970. super.copy( source, recursive );
  11971. if ( source.morphTargetInfluences !== undefined ) {
  11972. this.morphTargetInfluences = source.morphTargetInfluences.slice();
  11973. }
  11974. if ( source.morphTargetDictionary !== undefined ) {
  11975. this.morphTargetDictionary = Object.assign( {}, source.morphTargetDictionary );
  11976. }
  11977. this.material = Array.isArray( source.material ) ? source.material.slice() : source.material;
  11978. this.geometry = source.geometry;
  11979. return this;
  11980. }
  11981. updateMorphTargets() {
  11982. const geometry = this.geometry;
  11983. const morphAttributes = geometry.morphAttributes;
  11984. const keys = Object.keys( morphAttributes );
  11985. if ( keys.length > 0 ) {
  11986. const morphAttribute = morphAttributes[ keys[ 0 ] ];
  11987. if ( morphAttribute !== undefined ) {
  11988. this.morphTargetInfluences = [];
  11989. this.morphTargetDictionary = {};
  11990. for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  11991. const name = morphAttribute[ m ].name || String( m );
  11992. this.morphTargetInfluences.push( 0 );
  11993. this.morphTargetDictionary[ name ] = m;
  11994. }
  11995. }
  11996. }
  11997. }
  11998. getVertexPosition( index, target ) {
  11999. const geometry = this.geometry;
  12000. const position = geometry.attributes.position;
  12001. const morphPosition = geometry.morphAttributes.position;
  12002. const morphTargetsRelative = geometry.morphTargetsRelative;
  12003. target.fromBufferAttribute( position, index );
  12004. const morphInfluences = this.morphTargetInfluences;
  12005. if ( morphPosition && morphInfluences ) {
  12006. _morphA.set( 0, 0, 0 );
  12007. for ( let i = 0, il = morphPosition.length; i < il; i ++ ) {
  12008. const influence = morphInfluences[ i ];
  12009. const morphAttribute = morphPosition[ i ];
  12010. if ( influence === 0 ) continue;
  12011. _tempA.fromBufferAttribute( morphAttribute, index );
  12012. if ( morphTargetsRelative ) {
  12013. _morphA.addScaledVector( _tempA, influence );
  12014. } else {
  12015. _morphA.addScaledVector( _tempA.sub( target ), influence );
  12016. }
  12017. }
  12018. target.add( _morphA );
  12019. }
  12020. return target;
  12021. }
  12022. raycast( raycaster, intersects ) {
  12023. const geometry = this.geometry;
  12024. const material = this.material;
  12025. const matrixWorld = this.matrixWorld;
  12026. if ( material === undefined ) return;
  12027. // test with bounding sphere in world space
  12028. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  12029. _sphere$6.copy( geometry.boundingSphere );
  12030. _sphere$6.applyMatrix4( matrixWorld );
  12031. // check distance from ray origin to bounding sphere
  12032. _ray$3.copy( raycaster.ray ).recast( raycaster.near );
  12033. if ( _sphere$6.containsPoint( _ray$3.origin ) === false ) {
  12034. if ( _ray$3.intersectSphere( _sphere$6, _sphereHitAt ) === null ) return;
  12035. if ( _ray$3.origin.distanceToSquared( _sphereHitAt ) > ( raycaster.far - raycaster.near ) ** 2 ) return;
  12036. }
  12037. // convert ray to local space of mesh
  12038. _inverseMatrix$3.copy( matrixWorld ).invert();
  12039. _ray$3.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$3 );
  12040. // test with bounding box in local space
  12041. if ( geometry.boundingBox !== null ) {
  12042. if ( _ray$3.intersectsBox( geometry.boundingBox ) === false ) return;
  12043. }
  12044. // test for intersections with geometry
  12045. this._computeIntersections( raycaster, intersects, _ray$3 );
  12046. }
  12047. _computeIntersections( raycaster, intersects, rayLocalSpace ) {
  12048. let intersection;
  12049. const geometry = this.geometry;
  12050. const material = this.material;
  12051. const index = geometry.index;
  12052. const position = geometry.attributes.position;
  12053. const uv = geometry.attributes.uv;
  12054. const uv1 = geometry.attributes.uv1;
  12055. const normal = geometry.attributes.normal;
  12056. const groups = geometry.groups;
  12057. const drawRange = geometry.drawRange;
  12058. if ( index !== null ) {
  12059. // indexed buffer geometry
  12060. if ( Array.isArray( material ) ) {
  12061. for ( let i = 0, il = groups.length; i < il; i ++ ) {
  12062. const group = groups[ i ];
  12063. const groupMaterial = material[ group.materialIndex ];
  12064. const start = Math.max( group.start, drawRange.start );
  12065. const end = Math.min( index.count, Math.min( ( group.start + group.count ), ( drawRange.start + drawRange.count ) ) );
  12066. for ( let j = start, jl = end; j < jl; j += 3 ) {
  12067. const a = index.getX( j );
  12068. const b = index.getX( j + 1 );
  12069. const c = index.getX( j + 2 );
  12070. intersection = checkGeometryIntersection( this, groupMaterial, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c );
  12071. if ( intersection ) {
  12072. intersection.faceIndex = Math.floor( j / 3 ); // triangle number in indexed buffer semantics
  12073. intersection.face.materialIndex = group.materialIndex;
  12074. intersects.push( intersection );
  12075. }
  12076. }
  12077. }
  12078. } else {
  12079. const start = Math.max( 0, drawRange.start );
  12080. const end = Math.min( index.count, ( drawRange.start + drawRange.count ) );
  12081. for ( let i = start, il = end; i < il; i += 3 ) {
  12082. const a = index.getX( i );
  12083. const b = index.getX( i + 1 );
  12084. const c = index.getX( i + 2 );
  12085. intersection = checkGeometryIntersection( this, material, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c );
  12086. if ( intersection ) {
  12087. intersection.faceIndex = Math.floor( i / 3 ); // triangle number in indexed buffer semantics
  12088. intersects.push( intersection );
  12089. }
  12090. }
  12091. }
  12092. } else if ( position !== undefined ) {
  12093. // non-indexed buffer geometry
  12094. if ( Array.isArray( material ) ) {
  12095. for ( let i = 0, il = groups.length; i < il; i ++ ) {
  12096. const group = groups[ i ];
  12097. const groupMaterial = material[ group.materialIndex ];
  12098. const start = Math.max( group.start, drawRange.start );
  12099. const end = Math.min( position.count, Math.min( ( group.start + group.count ), ( drawRange.start + drawRange.count ) ) );
  12100. for ( let j = start, jl = end; j < jl; j += 3 ) {
  12101. const a = j;
  12102. const b = j + 1;
  12103. const c = j + 2;
  12104. intersection = checkGeometryIntersection( this, groupMaterial, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c );
  12105. if ( intersection ) {
  12106. intersection.faceIndex = Math.floor( j / 3 ); // triangle number in non-indexed buffer semantics
  12107. intersection.face.materialIndex = group.materialIndex;
  12108. intersects.push( intersection );
  12109. }
  12110. }
  12111. }
  12112. } else {
  12113. const start = Math.max( 0, drawRange.start );
  12114. const end = Math.min( position.count, ( drawRange.start + drawRange.count ) );
  12115. for ( let i = start, il = end; i < il; i += 3 ) {
  12116. const a = i;
  12117. const b = i + 1;
  12118. const c = i + 2;
  12119. intersection = checkGeometryIntersection( this, material, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c );
  12120. if ( intersection ) {
  12121. intersection.faceIndex = Math.floor( i / 3 ); // triangle number in non-indexed buffer semantics
  12122. intersects.push( intersection );
  12123. }
  12124. }
  12125. }
  12126. }
  12127. }
  12128. }
  12129. function checkIntersection$1( object, material, raycaster, ray, pA, pB, pC, point ) {
  12130. let intersect;
  12131. if ( material.side === BackSide ) {
  12132. intersect = ray.intersectTriangle( pC, pB, pA, true, point );
  12133. } else {
  12134. intersect = ray.intersectTriangle( pA, pB, pC, ( material.side === FrontSide ), point );
  12135. }
  12136. if ( intersect === null ) return null;
  12137. _intersectionPointWorld.copy( point );
  12138. _intersectionPointWorld.applyMatrix4( object.matrixWorld );
  12139. const distance = raycaster.ray.origin.distanceTo( _intersectionPointWorld );
  12140. if ( distance < raycaster.near || distance > raycaster.far ) return null;
  12141. return {
  12142. distance: distance,
  12143. point: _intersectionPointWorld.clone(),
  12144. object: object
  12145. };
  12146. }
  12147. function checkGeometryIntersection( object, material, raycaster, ray, uv, uv1, normal, a, b, c ) {
  12148. object.getVertexPosition( a, _vA$1 );
  12149. object.getVertexPosition( b, _vB$1 );
  12150. object.getVertexPosition( c, _vC$1 );
  12151. const intersection = checkIntersection$1( object, material, raycaster, ray, _vA$1, _vB$1, _vC$1, _intersectionPoint );
  12152. if ( intersection ) {
  12153. const barycoord = new Vector3();
  12154. Triangle.getBarycoord( _intersectionPoint, _vA$1, _vB$1, _vC$1, barycoord );
  12155. if ( uv ) {
  12156. intersection.uv = Triangle.getInterpolatedAttribute( uv, a, b, c, barycoord, new Vector2() );
  12157. }
  12158. if ( uv1 ) {
  12159. intersection.uv1 = Triangle.getInterpolatedAttribute( uv1, a, b, c, barycoord, new Vector2() );
  12160. }
  12161. if ( normal ) {
  12162. intersection.normal = Triangle.getInterpolatedAttribute( normal, a, b, c, barycoord, new Vector3() );
  12163. if ( intersection.normal.dot( ray.direction ) > 0 ) {
  12164. intersection.normal.multiplyScalar( -1 );
  12165. }
  12166. }
  12167. const face = {
  12168. a: a,
  12169. b: b,
  12170. c: c,
  12171. normal: new Vector3(),
  12172. materialIndex: 0
  12173. };
  12174. Triangle.getNormal( _vA$1, _vB$1, _vC$1, face.normal );
  12175. intersection.face = face;
  12176. intersection.barycoord = barycoord;
  12177. }
  12178. return intersection;
  12179. }
  12180. class BoxGeometry extends BufferGeometry {
  12181. constructor( width = 1, height = 1, depth = 1, widthSegments = 1, heightSegments = 1, depthSegments = 1 ) {
  12182. super();
  12183. this.type = 'BoxGeometry';
  12184. this.parameters = {
  12185. width: width,
  12186. height: height,
  12187. depth: depth,
  12188. widthSegments: widthSegments,
  12189. heightSegments: heightSegments,
  12190. depthSegments: depthSegments
  12191. };
  12192. const scope = this;
  12193. // segments
  12194. widthSegments = Math.floor( widthSegments );
  12195. heightSegments = Math.floor( heightSegments );
  12196. depthSegments = Math.floor( depthSegments );
  12197. // buffers
  12198. const indices = [];
  12199. const vertices = [];
  12200. const normals = [];
  12201. const uvs = [];
  12202. // helper variables
  12203. let numberOfVertices = 0;
  12204. let groupStart = 0;
  12205. // build each side of the box geometry
  12206. buildPlane( 'z', 'y', 'x', -1, -1, depth, height, width, depthSegments, heightSegments, 0 ); // px
  12207. buildPlane( 'z', 'y', 'x', 1, -1, depth, height, - width, depthSegments, heightSegments, 1 ); // nx
  12208. buildPlane( 'x', 'z', 'y', 1, 1, width, depth, height, widthSegments, depthSegments, 2 ); // py
  12209. buildPlane( 'x', 'z', 'y', 1, -1, width, depth, - height, widthSegments, depthSegments, 3 ); // ny
  12210. buildPlane( 'x', 'y', 'z', 1, -1, width, height, depth, widthSegments, heightSegments, 4 ); // pz
  12211. buildPlane( 'x', 'y', 'z', -1, -1, width, height, - depth, widthSegments, heightSegments, 5 ); // nz
  12212. // build geometry
  12213. this.setIndex( indices );
  12214. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  12215. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  12216. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  12217. function buildPlane( u, v, w, udir, vdir, width, height, depth, gridX, gridY, materialIndex ) {
  12218. const segmentWidth = width / gridX;
  12219. const segmentHeight = height / gridY;
  12220. const widthHalf = width / 2;
  12221. const heightHalf = height / 2;
  12222. const depthHalf = depth / 2;
  12223. const gridX1 = gridX + 1;
  12224. const gridY1 = gridY + 1;
  12225. let vertexCounter = 0;
  12226. let groupCount = 0;
  12227. const vector = new Vector3();
  12228. // generate vertices, normals and uvs
  12229. for ( let iy = 0; iy < gridY1; iy ++ ) {
  12230. const y = iy * segmentHeight - heightHalf;
  12231. for ( let ix = 0; ix < gridX1; ix ++ ) {
  12232. const x = ix * segmentWidth - widthHalf;
  12233. // set values to correct vector component
  12234. vector[ u ] = x * udir;
  12235. vector[ v ] = y * vdir;
  12236. vector[ w ] = depthHalf;
  12237. // now apply vector to vertex buffer
  12238. vertices.push( vector.x, vector.y, vector.z );
  12239. // set values to correct vector component
  12240. vector[ u ] = 0;
  12241. vector[ v ] = 0;
  12242. vector[ w ] = depth > 0 ? 1 : -1;
  12243. // now apply vector to normal buffer
  12244. normals.push( vector.x, vector.y, vector.z );
  12245. // uvs
  12246. uvs.push( ix / gridX );
  12247. uvs.push( 1 - ( iy / gridY ) );
  12248. // counters
  12249. vertexCounter += 1;
  12250. }
  12251. }
  12252. // indices
  12253. // 1. you need three indices to draw a single face
  12254. // 2. a single segment consists of two faces
  12255. // 3. so we need to generate six (2*3) indices per segment
  12256. for ( let iy = 0; iy < gridY; iy ++ ) {
  12257. for ( let ix = 0; ix < gridX; ix ++ ) {
  12258. const a = numberOfVertices + ix + gridX1 * iy;
  12259. const b = numberOfVertices + ix + gridX1 * ( iy + 1 );
  12260. const c = numberOfVertices + ( ix + 1 ) + gridX1 * ( iy + 1 );
  12261. const d = numberOfVertices + ( ix + 1 ) + gridX1 * iy;
  12262. // faces
  12263. indices.push( a, b, d );
  12264. indices.push( b, c, d );
  12265. // increase counter
  12266. groupCount += 6;
  12267. }
  12268. }
  12269. // add a group to the geometry. this will ensure multi material support
  12270. scope.addGroup( groupStart, groupCount, materialIndex );
  12271. // calculate new start value for groups
  12272. groupStart += groupCount;
  12273. // update total number of vertices
  12274. numberOfVertices += vertexCounter;
  12275. }
  12276. }
  12277. copy( source ) {
  12278. super.copy( source );
  12279. this.parameters = Object.assign( {}, source.parameters );
  12280. return this;
  12281. }
  12282. static fromJSON( data ) {
  12283. return new BoxGeometry( data.width, data.height, data.depth, data.widthSegments, data.heightSegments, data.depthSegments );
  12284. }
  12285. }
  12286. /**
  12287. * Uniform Utilities
  12288. */
  12289. function cloneUniforms( src ) {
  12290. const dst = {};
  12291. for ( const u in src ) {
  12292. dst[ u ] = {};
  12293. for ( const p in src[ u ] ) {
  12294. const property = src[ u ][ p ];
  12295. if ( property && ( property.isColor ||
  12296. property.isMatrix3 || property.isMatrix4 ||
  12297. property.isVector2 || property.isVector3 || property.isVector4 ||
  12298. property.isTexture || property.isQuaternion ) ) {
  12299. if ( property.isRenderTargetTexture ) {
  12300. console.warn( 'UniformsUtils: Textures of render targets cannot be cloned via cloneUniforms() or mergeUniforms().' );
  12301. dst[ u ][ p ] = null;
  12302. } else {
  12303. dst[ u ][ p ] = property.clone();
  12304. }
  12305. } else if ( Array.isArray( property ) ) {
  12306. dst[ u ][ p ] = property.slice();
  12307. } else {
  12308. dst[ u ][ p ] = property;
  12309. }
  12310. }
  12311. }
  12312. return dst;
  12313. }
  12314. function mergeUniforms( uniforms ) {
  12315. const merged = {};
  12316. for ( let u = 0; u < uniforms.length; u ++ ) {
  12317. const tmp = cloneUniforms( uniforms[ u ] );
  12318. for ( const p in tmp ) {
  12319. merged[ p ] = tmp[ p ];
  12320. }
  12321. }
  12322. return merged;
  12323. }
  12324. function cloneUniformsGroups( src ) {
  12325. const dst = [];
  12326. for ( let u = 0; u < src.length; u ++ ) {
  12327. dst.push( src[ u ].clone() );
  12328. }
  12329. return dst;
  12330. }
  12331. function getUnlitUniformColorSpace( renderer ) {
  12332. const currentRenderTarget = renderer.getRenderTarget();
  12333. if ( currentRenderTarget === null ) {
  12334. // https://github.com/mrdoob/three.js/pull/23937#issuecomment-1111067398
  12335. return renderer.outputColorSpace;
  12336. }
  12337. // https://github.com/mrdoob/three.js/issues/27868
  12338. if ( currentRenderTarget.isXRRenderTarget === true ) {
  12339. return currentRenderTarget.texture.colorSpace;
  12340. }
  12341. return ColorManagement.workingColorSpace;
  12342. }
  12343. // Legacy
  12344. const UniformsUtils = { clone: cloneUniforms, merge: mergeUniforms };
  12345. var default_vertex = "void main() {\n\tgl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n}";
  12346. var default_fragment = "void main() {\n\tgl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );\n}";
  12347. class ShaderMaterial extends Material {
  12348. constructor( parameters ) {
  12349. super();
  12350. this.isShaderMaterial = true;
  12351. this.type = 'ShaderMaterial';
  12352. this.defines = {};
  12353. this.uniforms = {};
  12354. this.uniformsGroups = [];
  12355. this.vertexShader = default_vertex;
  12356. this.fragmentShader = default_fragment;
  12357. this.linewidth = 1;
  12358. this.wireframe = false;
  12359. this.wireframeLinewidth = 1;
  12360. this.fog = false; // set to use scene fog
  12361. this.lights = false; // set to use scene lights
  12362. this.clipping = false; // set to use user-defined clipping planes
  12363. this.forceSinglePass = true;
  12364. this.extensions = {
  12365. clipCullDistance: false, // set to use vertex shader clipping
  12366. multiDraw: false // set to use vertex shader multi_draw / enable gl_DrawID
  12367. };
  12368. // When rendered geometry doesn't include these attributes but the material does,
  12369. // use these default values in WebGL. This avoids errors when buffer data is missing.
  12370. this.defaultAttributeValues = {
  12371. 'color': [ 1, 1, 1 ],
  12372. 'uv': [ 0, 0 ],
  12373. 'uv1': [ 0, 0 ]
  12374. };
  12375. this.index0AttributeName = undefined;
  12376. this.uniformsNeedUpdate = false;
  12377. this.glslVersion = null;
  12378. if ( parameters !== undefined ) {
  12379. this.setValues( parameters );
  12380. }
  12381. }
  12382. copy( source ) {
  12383. super.copy( source );
  12384. this.fragmentShader = source.fragmentShader;
  12385. this.vertexShader = source.vertexShader;
  12386. this.uniforms = cloneUniforms( source.uniforms );
  12387. this.uniformsGroups = cloneUniformsGroups( source.uniformsGroups );
  12388. this.defines = Object.assign( {}, source.defines );
  12389. this.wireframe = source.wireframe;
  12390. this.wireframeLinewidth = source.wireframeLinewidth;
  12391. this.fog = source.fog;
  12392. this.lights = source.lights;
  12393. this.clipping = source.clipping;
  12394. this.extensions = Object.assign( {}, source.extensions );
  12395. this.glslVersion = source.glslVersion;
  12396. return this;
  12397. }
  12398. toJSON( meta ) {
  12399. const data = super.toJSON( meta );
  12400. data.glslVersion = this.glslVersion;
  12401. data.uniforms = {};
  12402. for ( const name in this.uniforms ) {
  12403. const uniform = this.uniforms[ name ];
  12404. const value = uniform.value;
  12405. if ( value && value.isTexture ) {
  12406. data.uniforms[ name ] = {
  12407. type: 't',
  12408. value: value.toJSON( meta ).uuid
  12409. };
  12410. } else if ( value && value.isColor ) {
  12411. data.uniforms[ name ] = {
  12412. type: 'c',
  12413. value: value.getHex()
  12414. };
  12415. } else if ( value && value.isVector2 ) {
  12416. data.uniforms[ name ] = {
  12417. type: 'v2',
  12418. value: value.toArray()
  12419. };
  12420. } else if ( value && value.isVector3 ) {
  12421. data.uniforms[ name ] = {
  12422. type: 'v3',
  12423. value: value.toArray()
  12424. };
  12425. } else if ( value && value.isVector4 ) {
  12426. data.uniforms[ name ] = {
  12427. type: 'v4',
  12428. value: value.toArray()
  12429. };
  12430. } else if ( value && value.isMatrix3 ) {
  12431. data.uniforms[ name ] = {
  12432. type: 'm3',
  12433. value: value.toArray()
  12434. };
  12435. } else if ( value && value.isMatrix4 ) {
  12436. data.uniforms[ name ] = {
  12437. type: 'm4',
  12438. value: value.toArray()
  12439. };
  12440. } else {
  12441. data.uniforms[ name ] = {
  12442. value: value
  12443. };
  12444. // note: the array variants v2v, v3v, v4v, m4v and tv are not supported so far
  12445. }
  12446. }
  12447. if ( Object.keys( this.defines ).length > 0 ) data.defines = this.defines;
  12448. data.vertexShader = this.vertexShader;
  12449. data.fragmentShader = this.fragmentShader;
  12450. data.lights = this.lights;
  12451. data.clipping = this.clipping;
  12452. const extensions = {};
  12453. for ( const key in this.extensions ) {
  12454. if ( this.extensions[ key ] === true ) extensions[ key ] = true;
  12455. }
  12456. if ( Object.keys( extensions ).length > 0 ) data.extensions = extensions;
  12457. return data;
  12458. }
  12459. }
  12460. /**
  12461. * Abstract base class for cameras. This class should always be inherited
  12462. * when you build a new camera.
  12463. *
  12464. * @abstract
  12465. * @augments Object3D
  12466. */
  12467. class Camera extends Object3D {
  12468. /**
  12469. * Constructs a new camera.
  12470. */
  12471. constructor() {
  12472. super();
  12473. /**
  12474. * This flag can be used for type testing.
  12475. *
  12476. * @type {boolean}
  12477. * @readonly
  12478. * @default true
  12479. */
  12480. this.isCamera = true;
  12481. this.type = 'Camera';
  12482. /**
  12483. * The inverse of the camera's world matrix.
  12484. *
  12485. * @type {Matrix4}
  12486. */
  12487. this.matrixWorldInverse = new Matrix4();
  12488. /**
  12489. * The camera's projection matrix.
  12490. *
  12491. * @type {Matrix4}
  12492. */
  12493. this.projectionMatrix = new Matrix4();
  12494. /**
  12495. * The inverse of the camera's prjection matrix.
  12496. *
  12497. * @type {Matrix4}
  12498. */
  12499. this.projectionMatrixInverse = new Matrix4();
  12500. /**
  12501. * The coordinate system in which the camrea is used.
  12502. *
  12503. * @type {(WebGLCoordinateSystem|WebGPUCoordinateSystem)}
  12504. */
  12505. this.coordinateSystem = WebGLCoordinateSystem;
  12506. }
  12507. copy( source, recursive ) {
  12508. super.copy( source, recursive );
  12509. this.matrixWorldInverse.copy( source.matrixWorldInverse );
  12510. this.projectionMatrix.copy( source.projectionMatrix );
  12511. this.projectionMatrixInverse.copy( source.projectionMatrixInverse );
  12512. this.coordinateSystem = source.coordinateSystem;
  12513. return this;
  12514. }
  12515. /**
  12516. * Returns a vector representing the ("look") direction of the 3D object in world space.
  12517. *
  12518. * This method is overwritten since cameras have a different forward vector compared to other
  12519. * 3D objects. A camera looks down its local, negative z-axis by default.
  12520. *
  12521. * @param {Vector3} target - The target vector the result is stored to.
  12522. * @return {Vector3} The 3D object's direction in world space.
  12523. */
  12524. getWorldDirection( target ) {
  12525. return super.getWorldDirection( target ).negate();
  12526. }
  12527. updateMatrixWorld( force ) {
  12528. super.updateMatrixWorld( force );
  12529. this.matrixWorldInverse.copy( this.matrixWorld ).invert();
  12530. }
  12531. updateWorldMatrix( updateParents, updateChildren ) {
  12532. super.updateWorldMatrix( updateParents, updateChildren );
  12533. this.matrixWorldInverse.copy( this.matrixWorld ).invert();
  12534. }
  12535. clone() {
  12536. return new this.constructor().copy( this );
  12537. }
  12538. }
  12539. const _v3$1 = /*@__PURE__*/ new Vector3();
  12540. const _minTarget = /*@__PURE__*/ new Vector2();
  12541. const _maxTarget = /*@__PURE__*/ new Vector2();
  12542. /**
  12543. * Camera that uses [perspective projection]{@link https://en.wikipedia.org/wiki/Perspective_(graphical)}.
  12544. *
  12545. * This projection mode is designed to mimic the way the human eye sees. It
  12546. * is the most common projection mode used for rendering a 3D scene.
  12547. *
  12548. * @augments Camera
  12549. */
  12550. class PerspectiveCamera extends Camera {
  12551. /**
  12552. * Constructs a new perspective camera.
  12553. *
  12554. * @param {number} [fov=50] - The vertical field of view.
  12555. * @param {number} [aspect=1] - The aspect ratio.
  12556. * @param {number} [near=0.1] - The camera's near plane.
  12557. * @param {number} [far=2000] - The camera's far plane.
  12558. */
  12559. constructor( fov = 50, aspect = 1, near = 0.1, far = 2000 ) {
  12560. super();
  12561. /**
  12562. * This flag can be used for type testing.
  12563. *
  12564. * @type {boolean}
  12565. * @readonly
  12566. * @default true
  12567. */
  12568. this.isPerspectiveCamera = true;
  12569. this.type = 'PerspectiveCamera';
  12570. /**
  12571. * The vertical field of view, from bottom to top of view,
  12572. * in degrees.
  12573. *
  12574. * @type {number}
  12575. * @default 50
  12576. */
  12577. this.fov = fov;
  12578. /**
  12579. * The zoom factor of the camera.
  12580. *
  12581. * @type {number}
  12582. * @default 1
  12583. */
  12584. this.zoom = 1;
  12585. /**
  12586. * The camera's near plane. The valid range is greater than `0`
  12587. * and less than the current value of {@link PerspectiveCamera#far}.
  12588. *
  12589. * Note that, unlike for the {@link OrthographicCamera}, `0` is <em>not</em> a
  12590. * valid value for a perspective camera's near plane.
  12591. *
  12592. * @type {number}
  12593. * @default 0.1
  12594. */
  12595. this.near = near;
  12596. /**
  12597. * The camera's far plane. Must be greater than the
  12598. * current value of {@link PerspectiveCamera#near}.
  12599. *
  12600. * @type {number}
  12601. * @default 2000
  12602. */
  12603. this.far = far;
  12604. /**
  12605. * Object distance used for stereoscopy and depth-of-field effects. This
  12606. * parameter does not influence the projection matrix unless a
  12607. * {@link StereoCamera} is being used.
  12608. *
  12609. * @type {number}
  12610. * @default 10
  12611. */
  12612. this.focus = 10;
  12613. /**
  12614. * The aspect ratio, usually the canvas width / canvas height.
  12615. *
  12616. * @type {number}
  12617. * @default 1
  12618. */
  12619. this.aspect = aspect;
  12620. /**
  12621. * Represents the frustum window specification. This property should not be edited
  12622. * directly but via {@link PerspectiveCamera#setViewOffset} and {@link PerspectiveCamera#clearViewOffset}.
  12623. *
  12624. * @type {?Object}
  12625. * @default null
  12626. */
  12627. this.view = null;
  12628. /**
  12629. * Film size used for the larger axis. Default is `35` (millimeters). This
  12630. * parameter does not influence the projection matrix unless {@link PerspectiveCamera#filmOffset}
  12631. * is set to a nonzero value.
  12632. *
  12633. * @type {number}
  12634. * @default 35
  12635. */
  12636. this.filmGauge = 35;
  12637. /**
  12638. * Horizontal off-center offset in the same unit as {@link PerspectiveCamera#filmGauge}.
  12639. *
  12640. * @type {number}
  12641. * @default 0
  12642. */
  12643. this.filmOffset = 0;
  12644. this.updateProjectionMatrix();
  12645. }
  12646. copy( source, recursive ) {
  12647. super.copy( source, recursive );
  12648. this.fov = source.fov;
  12649. this.zoom = source.zoom;
  12650. this.near = source.near;
  12651. this.far = source.far;
  12652. this.focus = source.focus;
  12653. this.aspect = source.aspect;
  12654. this.view = source.view === null ? null : Object.assign( {}, source.view );
  12655. this.filmGauge = source.filmGauge;
  12656. this.filmOffset = source.filmOffset;
  12657. return this;
  12658. }
  12659. /**
  12660. * Sets the FOV by focal length in respect to the current {@link PerspectiveCamera#filmGauge}.
  12661. *
  12662. * The default film gauge is 35, so that the focal length can be specified for
  12663. * a 35mm (full frame) camera.
  12664. *
  12665. * @param {number} focalLength - Values for focal length and film gauge must have the same unit.
  12666. */
  12667. setFocalLength( focalLength ) {
  12668. /** see {@link http://www.bobatkins.com/photography/technical/field_of_view.html} */
  12669. const vExtentSlope = 0.5 * this.getFilmHeight() / focalLength;
  12670. this.fov = RAD2DEG * 2 * Math.atan( vExtentSlope );
  12671. this.updateProjectionMatrix();
  12672. }
  12673. /**
  12674. * Returns the focal length from the current {@link PerspectiveCamera#fov} and
  12675. * {@link PerspectiveCamera#filmGauge}.
  12676. *
  12677. * @return {number} The computed focal length.
  12678. */
  12679. getFocalLength() {
  12680. const vExtentSlope = Math.tan( DEG2RAD * 0.5 * this.fov );
  12681. return 0.5 * this.getFilmHeight() / vExtentSlope;
  12682. }
  12683. /**
  12684. * Returns the current vertical field of view angle in degrees considering {@link PerspectiveCamera#zoom}.
  12685. *
  12686. * @return {number} The effective FOV.
  12687. */
  12688. getEffectiveFOV() {
  12689. return RAD2DEG * 2 * Math.atan(
  12690. Math.tan( DEG2RAD * 0.5 * this.fov ) / this.zoom );
  12691. }
  12692. /**
  12693. * Returns the width of the image on the film. If {@link PerspectiveCamera#aspect} is greater than or
  12694. * equal to one (landscape format), the result equals {@link PerspectiveCamera#filmGauge}.
  12695. *
  12696. * @return {number} The film width.
  12697. */
  12698. getFilmWidth() {
  12699. // film not completely covered in portrait format (aspect < 1)
  12700. return this.filmGauge * Math.min( this.aspect, 1 );
  12701. }
  12702. /**
  12703. * Returns the height of the image on the film. If {@link PerspectiveCamera#aspect} is greater than or
  12704. * equal to one (landscape format), the result equals {@link PerspectiveCamera#filmGauge}.
  12705. *
  12706. * @return {number} The film width.
  12707. */
  12708. getFilmHeight() {
  12709. // film not completely covered in landscape format (aspect > 1)
  12710. return this.filmGauge / Math.max( this.aspect, 1 );
  12711. }
  12712. /**
  12713. * Computes the 2D bounds of the camera's viewable rectangle at a given distance along the viewing direction.
  12714. * Sets `minTarget` and `maxTarget` to the coordinates of the lower-left and upper-right corners of the view rectangle.
  12715. *
  12716. * @param {number} distance - The viewing distance.
  12717. * @param {Vector2} minTarget - The lower-left corner of the view rectangle is written into this vector.
  12718. * @param {Vector2} maxTarget - The upper-right corner of the view rectangle is written into this vector.
  12719. */
  12720. getViewBounds( distance, minTarget, maxTarget ) {
  12721. _v3$1.set( -1, -1, 0.5 ).applyMatrix4( this.projectionMatrixInverse );
  12722. minTarget.set( _v3$1.x, _v3$1.y ).multiplyScalar( - distance / _v3$1.z );
  12723. _v3$1.set( 1, 1, 0.5 ).applyMatrix4( this.projectionMatrixInverse );
  12724. maxTarget.set( _v3$1.x, _v3$1.y ).multiplyScalar( - distance / _v3$1.z );
  12725. }
  12726. /**
  12727. * Computes the width and height of the camera's viewable rectangle at a given distance along the viewing direction.
  12728. *
  12729. * @param {number} distance - The viewing distance.
  12730. * @param {Vector2} target - The target vector that is used to store result where x is width and y is height.
  12731. * @returns {Vector2} The view size.
  12732. */
  12733. getViewSize( distance, target ) {
  12734. this.getViewBounds( distance, _minTarget, _maxTarget );
  12735. return target.subVectors( _maxTarget, _minTarget );
  12736. }
  12737. /**
  12738. * Sets an offset in a larger frustum. This is useful for multi-window or
  12739. * multi-monitor/multi-machine setups.
  12740. *
  12741. * For example, if you have 3x2 monitors and each monitor is 1920x1080 and
  12742. * the monitors are in grid like this
  12743. *```
  12744. * +---+---+---+
  12745. * | A | B | C |
  12746. * +---+---+---+
  12747. * | D | E | F |
  12748. * +---+---+---+
  12749. *```
  12750. * then for each monitor you would call it like this:
  12751. *```js
  12752. * const w = 1920;
  12753. * const h = 1080;
  12754. * const fullWidth = w * 3;
  12755. * const fullHeight = h * 2;
  12756. *
  12757. * // --A--
  12758. * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 0, w, h );
  12759. * // --B--
  12760. * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 0, w, h );
  12761. * // --C--
  12762. * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 0, w, h );
  12763. * // --D--
  12764. * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 1, w, h );
  12765. * // --E--
  12766. * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 1, w, h );
  12767. * // --F--
  12768. * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 1, w, h );
  12769. * ```
  12770. *
  12771. * Note there is no reason monitors have to be the same size or in a grid.
  12772. *
  12773. * @param {number} fullWidth - The full width of multiview setup.
  12774. * @param {number} fullHeight - The full height of multiview setup.
  12775. * @param {number} x - The horizontal offset of the subcamera.
  12776. * @param {number} y - The vertical offset of the subcamera.
  12777. * @param {number} width - The width of subcamera.
  12778. * @param {number} height - The height of subcamera.
  12779. */
  12780. setViewOffset( fullWidth, fullHeight, x, y, width, height ) {
  12781. this.aspect = fullWidth / fullHeight;
  12782. if ( this.view === null ) {
  12783. this.view = {
  12784. enabled: true,
  12785. fullWidth: 1,
  12786. fullHeight: 1,
  12787. offsetX: 0,
  12788. offsetY: 0,
  12789. width: 1,
  12790. height: 1
  12791. };
  12792. }
  12793. this.view.enabled = true;
  12794. this.view.fullWidth = fullWidth;
  12795. this.view.fullHeight = fullHeight;
  12796. this.view.offsetX = x;
  12797. this.view.offsetY = y;
  12798. this.view.width = width;
  12799. this.view.height = height;
  12800. this.updateProjectionMatrix();
  12801. }
  12802. /**
  12803. * Removes the view offset from the projection matrix.
  12804. */
  12805. clearViewOffset() {
  12806. if ( this.view !== null ) {
  12807. this.view.enabled = false;
  12808. }
  12809. this.updateProjectionMatrix();
  12810. }
  12811. /**
  12812. * Updates the camera's projection matrix. Must be called after any change of
  12813. * camera properties.
  12814. */
  12815. updateProjectionMatrix() {
  12816. const near = this.near;
  12817. let top = near * Math.tan( DEG2RAD * 0.5 * this.fov ) / this.zoom;
  12818. let height = 2 * top;
  12819. let width = this.aspect * height;
  12820. let left = -0.5 * width;
  12821. const view = this.view;
  12822. if ( this.view !== null && this.view.enabled ) {
  12823. const fullWidth = view.fullWidth,
  12824. fullHeight = view.fullHeight;
  12825. left += view.offsetX * width / fullWidth;
  12826. top -= view.offsetY * height / fullHeight;
  12827. width *= view.width / fullWidth;
  12828. height *= view.height / fullHeight;
  12829. }
  12830. const skew = this.filmOffset;
  12831. if ( skew !== 0 ) left += near * skew / this.getFilmWidth();
  12832. this.projectionMatrix.makePerspective( left, left + width, top, top - height, near, this.far, this.coordinateSystem );
  12833. this.projectionMatrixInverse.copy( this.projectionMatrix ).invert();
  12834. }
  12835. toJSON( meta ) {
  12836. const data = super.toJSON( meta );
  12837. data.object.fov = this.fov;
  12838. data.object.zoom = this.zoom;
  12839. data.object.near = this.near;
  12840. data.object.far = this.far;
  12841. data.object.focus = this.focus;
  12842. data.object.aspect = this.aspect;
  12843. if ( this.view !== null ) data.object.view = Object.assign( {}, this.view );
  12844. data.object.filmGauge = this.filmGauge;
  12845. data.object.filmOffset = this.filmOffset;
  12846. return data;
  12847. }
  12848. }
  12849. const fov = -90; // negative fov is not an error
  12850. const aspect = 1;
  12851. /**
  12852. * A special type of camera that is positioned in 3D space to render its surroundings into a
  12853. * cube render target. The render target can then be used as an environment map for rendering
  12854. * realtime reflections in your scene.
  12855. *
  12856. * ```js
  12857. * // Create cube render target
  12858. * const cubeRenderTarget = new THREE.WebGLCubeRenderTarget( 256, { generateMipmaps: true, minFilter: THREE.LinearMipmapLinearFilter } );
  12859. *
  12860. * // Create cube camera
  12861. * const cubeCamera = new THREE.CubeCamera( 1, 100000, cubeRenderTarget );
  12862. * scene.add( cubeCamera );
  12863. *
  12864. * // Create car
  12865. * const chromeMaterial = new THREE.MeshLambertMaterial( { color: 0xffffff, envMap: cubeRenderTarget.texture } );
  12866. * const car = new THREE.Mesh( carGeometry, chromeMaterial );
  12867. * scene.add( car );
  12868. *
  12869. * // Update the render target cube
  12870. * car.visible = false;
  12871. * cubeCamera.position.copy( car.position );
  12872. * cubeCamera.update( renderer, scene );
  12873. *
  12874. * // Render the scene
  12875. * car.visible = true;
  12876. * renderer.render( scene, camera );
  12877. * ```
  12878. *
  12879. * @augments Object3D
  12880. */
  12881. class CubeCamera extends Object3D {
  12882. /**
  12883. * Constructs a new cube camera.
  12884. *
  12885. * @param {number} near - The camera's near plane.
  12886. * @param {number} far - The camera's far plane.
  12887. * @param {WebGLCubeRenderTarget} renderTarget - The cube render target.
  12888. */
  12889. constructor( near, far, renderTarget ) {
  12890. super();
  12891. this.type = 'CubeCamera';
  12892. /**
  12893. * A reference to the cube render target.
  12894. *
  12895. * @type {WebGLCubeRenderTarget}
  12896. */
  12897. this.renderTarget = renderTarget;
  12898. /**
  12899. * The current active coordinate system.
  12900. *
  12901. * @type {?(WebGLCoordinateSystem|WebGPUCoordinateSystem)}
  12902. * @default null
  12903. */
  12904. this.coordinateSystem = null;
  12905. /**
  12906. * The current active mipmap level
  12907. *
  12908. * @type {number}
  12909. * @default 0
  12910. */
  12911. this.activeMipmapLevel = 0;
  12912. const cameraPX = new PerspectiveCamera( fov, aspect, near, far );
  12913. cameraPX.layers = this.layers;
  12914. this.add( cameraPX );
  12915. const cameraNX = new PerspectiveCamera( fov, aspect, near, far );
  12916. cameraNX.layers = this.layers;
  12917. this.add( cameraNX );
  12918. const cameraPY = new PerspectiveCamera( fov, aspect, near, far );
  12919. cameraPY.layers = this.layers;
  12920. this.add( cameraPY );
  12921. const cameraNY = new PerspectiveCamera( fov, aspect, near, far );
  12922. cameraNY.layers = this.layers;
  12923. this.add( cameraNY );
  12924. const cameraPZ = new PerspectiveCamera( fov, aspect, near, far );
  12925. cameraPZ.layers = this.layers;
  12926. this.add( cameraPZ );
  12927. const cameraNZ = new PerspectiveCamera( fov, aspect, near, far );
  12928. cameraNZ.layers = this.layers;
  12929. this.add( cameraNZ );
  12930. }
  12931. /**
  12932. * Must be called when the coordinate system of the cube camera is changed.
  12933. */
  12934. updateCoordinateSystem() {
  12935. const coordinateSystem = this.coordinateSystem;
  12936. const cameras = this.children.concat();
  12937. const [ cameraPX, cameraNX, cameraPY, cameraNY, cameraPZ, cameraNZ ] = cameras;
  12938. for ( const camera of cameras ) this.remove( camera );
  12939. if ( coordinateSystem === WebGLCoordinateSystem ) {
  12940. cameraPX.up.set( 0, 1, 0 );
  12941. cameraPX.lookAt( 1, 0, 0 );
  12942. cameraNX.up.set( 0, 1, 0 );
  12943. cameraNX.lookAt( -1, 0, 0 );
  12944. cameraPY.up.set( 0, 0, -1 );
  12945. cameraPY.lookAt( 0, 1, 0 );
  12946. cameraNY.up.set( 0, 0, 1 );
  12947. cameraNY.lookAt( 0, -1, 0 );
  12948. cameraPZ.up.set( 0, 1, 0 );
  12949. cameraPZ.lookAt( 0, 0, 1 );
  12950. cameraNZ.up.set( 0, 1, 0 );
  12951. cameraNZ.lookAt( 0, 0, -1 );
  12952. } else if ( coordinateSystem === WebGPUCoordinateSystem ) {
  12953. cameraPX.up.set( 0, -1, 0 );
  12954. cameraPX.lookAt( -1, 0, 0 );
  12955. cameraNX.up.set( 0, -1, 0 );
  12956. cameraNX.lookAt( 1, 0, 0 );
  12957. cameraPY.up.set( 0, 0, 1 );
  12958. cameraPY.lookAt( 0, 1, 0 );
  12959. cameraNY.up.set( 0, 0, -1 );
  12960. cameraNY.lookAt( 0, -1, 0 );
  12961. cameraPZ.up.set( 0, -1, 0 );
  12962. cameraPZ.lookAt( 0, 0, 1 );
  12963. cameraNZ.up.set( 0, -1, 0 );
  12964. cameraNZ.lookAt( 0, 0, -1 );
  12965. } else {
  12966. throw new Error( 'THREE.CubeCamera.updateCoordinateSystem(): Invalid coordinate system: ' + coordinateSystem );
  12967. }
  12968. for ( const camera of cameras ) {
  12969. this.add( camera );
  12970. camera.updateMatrixWorld();
  12971. }
  12972. }
  12973. /**
  12974. * Calling this method will render the given scene with the given renderer
  12975. * into the cube render target of the camera.
  12976. *
  12977. * @param {(Renderer|WebGLRenderer)} renderer - The renderer.
  12978. * @param {Scene} scene - The scene to render.
  12979. */
  12980. update( renderer, scene ) {
  12981. if ( this.parent === null ) this.updateMatrixWorld();
  12982. const { renderTarget, activeMipmapLevel } = this;
  12983. if ( this.coordinateSystem !== renderer.coordinateSystem ) {
  12984. this.coordinateSystem = renderer.coordinateSystem;
  12985. this.updateCoordinateSystem();
  12986. }
  12987. const [ cameraPX, cameraNX, cameraPY, cameraNY, cameraPZ, cameraNZ ] = this.children;
  12988. const currentRenderTarget = renderer.getRenderTarget();
  12989. const currentActiveCubeFace = renderer.getActiveCubeFace();
  12990. const currentActiveMipmapLevel = renderer.getActiveMipmapLevel();
  12991. const currentXrEnabled = renderer.xr.enabled;
  12992. renderer.xr.enabled = false;
  12993. const generateMipmaps = renderTarget.texture.generateMipmaps;
  12994. renderTarget.texture.generateMipmaps = false;
  12995. renderer.setRenderTarget( renderTarget, 0, activeMipmapLevel );
  12996. renderer.render( scene, cameraPX );
  12997. renderer.setRenderTarget( renderTarget, 1, activeMipmapLevel );
  12998. renderer.render( scene, cameraNX );
  12999. renderer.setRenderTarget( renderTarget, 2, activeMipmapLevel );
  13000. renderer.render( scene, cameraPY );
  13001. renderer.setRenderTarget( renderTarget, 3, activeMipmapLevel );
  13002. renderer.render( scene, cameraNY );
  13003. renderer.setRenderTarget( renderTarget, 4, activeMipmapLevel );
  13004. renderer.render( scene, cameraPZ );
  13005. // mipmaps are generated during the last call of render()
  13006. // at this point, all sides of the cube render target are defined
  13007. renderTarget.texture.generateMipmaps = generateMipmaps;
  13008. renderer.setRenderTarget( renderTarget, 5, activeMipmapLevel );
  13009. renderer.render( scene, cameraNZ );
  13010. renderer.setRenderTarget( currentRenderTarget, currentActiveCubeFace, currentActiveMipmapLevel );
  13011. renderer.xr.enabled = currentXrEnabled;
  13012. renderTarget.texture.needsPMREMUpdate = true;
  13013. }
  13014. }
  13015. class CubeTexture extends Texture {
  13016. constructor( images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace ) {
  13017. images = images !== undefined ? images : [];
  13018. mapping = mapping !== undefined ? mapping : CubeReflectionMapping;
  13019. super( images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace );
  13020. this.isCubeTexture = true;
  13021. this.flipY = false;
  13022. }
  13023. get images() {
  13024. return this.image;
  13025. }
  13026. set images( value ) {
  13027. this.image = value;
  13028. }
  13029. }
  13030. class WebGLCubeRenderTarget extends WebGLRenderTarget {
  13031. constructor( size = 1, options = {} ) {
  13032. super( size, size, options );
  13033. this.isWebGLCubeRenderTarget = true;
  13034. const image = { width: size, height: size, depth: 1 };
  13035. const images = [ image, image, image, image, image, image ];
  13036. this.texture = new CubeTexture( images, options.mapping, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.colorSpace );
  13037. // By convention -- likely based on the RenderMan spec from the 1990's -- cube maps are specified by WebGL (and three.js)
  13038. // in a coordinate system in which positive-x is to the right when looking up the positive-z axis -- in other words,
  13039. // in a left-handed coordinate system. By continuing this convention, preexisting cube maps continued to render correctly.
  13040. // three.js uses a right-handed coordinate system. So environment maps used in three.js appear to have px and nx swapped
  13041. // and the flag isRenderTargetTexture controls this conversion. The flip is not required when using WebGLCubeRenderTarget.texture
  13042. // as a cube texture (this is detected when isRenderTargetTexture is set to true for cube textures).
  13043. this.texture.isRenderTargetTexture = true;
  13044. this.texture.generateMipmaps = options.generateMipmaps !== undefined ? options.generateMipmaps : false;
  13045. this.texture.minFilter = options.minFilter !== undefined ? options.minFilter : LinearFilter;
  13046. }
  13047. fromEquirectangularTexture( renderer, texture ) {
  13048. this.texture.type = texture.type;
  13049. this.texture.colorSpace = texture.colorSpace;
  13050. this.texture.generateMipmaps = texture.generateMipmaps;
  13051. this.texture.minFilter = texture.minFilter;
  13052. this.texture.magFilter = texture.magFilter;
  13053. const shader = {
  13054. uniforms: {
  13055. tEquirect: { value: null },
  13056. },
  13057. vertexShader: /* glsl */`
  13058. varying vec3 vWorldDirection;
  13059. vec3 transformDirection( in vec3 dir, in mat4 matrix ) {
  13060. return normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );
  13061. }
  13062. void main() {
  13063. vWorldDirection = transformDirection( position, modelMatrix );
  13064. #include <begin_vertex>
  13065. #include <project_vertex>
  13066. }
  13067. `,
  13068. fragmentShader: /* glsl */`
  13069. uniform sampler2D tEquirect;
  13070. varying vec3 vWorldDirection;
  13071. #include <common>
  13072. void main() {
  13073. vec3 direction = normalize( vWorldDirection );
  13074. vec2 sampleUV = equirectUv( direction );
  13075. gl_FragColor = texture2D( tEquirect, sampleUV );
  13076. }
  13077. `
  13078. };
  13079. const geometry = new BoxGeometry( 5, 5, 5 );
  13080. const material = new ShaderMaterial( {
  13081. name: 'CubemapFromEquirect',
  13082. uniforms: cloneUniforms( shader.uniforms ),
  13083. vertexShader: shader.vertexShader,
  13084. fragmentShader: shader.fragmentShader,
  13085. side: BackSide,
  13086. blending: NoBlending
  13087. } );
  13088. material.uniforms.tEquirect.value = texture;
  13089. const mesh = new Mesh( geometry, material );
  13090. const currentMinFilter = texture.minFilter;
  13091. // Avoid blurred poles
  13092. if ( texture.minFilter === LinearMipmapLinearFilter ) texture.minFilter = LinearFilter;
  13093. const camera = new CubeCamera( 1, 10, this );
  13094. camera.update( renderer, mesh );
  13095. texture.minFilter = currentMinFilter;
  13096. mesh.geometry.dispose();
  13097. mesh.material.dispose();
  13098. return this;
  13099. }
  13100. clear( renderer, color, depth, stencil ) {
  13101. const currentRenderTarget = renderer.getRenderTarget();
  13102. for ( let i = 0; i < 6; i ++ ) {
  13103. renderer.setRenderTarget( this, i );
  13104. renderer.clear( color, depth, stencil );
  13105. }
  13106. renderer.setRenderTarget( currentRenderTarget );
  13107. }
  13108. }
  13109. class Group extends Object3D {
  13110. constructor() {
  13111. super();
  13112. this.isGroup = true;
  13113. this.type = 'Group';
  13114. }
  13115. }
  13116. const _moveEvent = { type: 'move' };
  13117. class WebXRController {
  13118. constructor() {
  13119. this._targetRay = null;
  13120. this._grip = null;
  13121. this._hand = null;
  13122. }
  13123. getHandSpace() {
  13124. if ( this._hand === null ) {
  13125. this._hand = new Group();
  13126. this._hand.matrixAutoUpdate = false;
  13127. this._hand.visible = false;
  13128. this._hand.joints = {};
  13129. this._hand.inputState = { pinching: false };
  13130. }
  13131. return this._hand;
  13132. }
  13133. getTargetRaySpace() {
  13134. if ( this._targetRay === null ) {
  13135. this._targetRay = new Group();
  13136. this._targetRay.matrixAutoUpdate = false;
  13137. this._targetRay.visible = false;
  13138. this._targetRay.hasLinearVelocity = false;
  13139. this._targetRay.linearVelocity = new Vector3();
  13140. this._targetRay.hasAngularVelocity = false;
  13141. this._targetRay.angularVelocity = new Vector3();
  13142. }
  13143. return this._targetRay;
  13144. }
  13145. getGripSpace() {
  13146. if ( this._grip === null ) {
  13147. this._grip = new Group();
  13148. this._grip.matrixAutoUpdate = false;
  13149. this._grip.visible = false;
  13150. this._grip.hasLinearVelocity = false;
  13151. this._grip.linearVelocity = new Vector3();
  13152. this._grip.hasAngularVelocity = false;
  13153. this._grip.angularVelocity = new Vector3();
  13154. }
  13155. return this._grip;
  13156. }
  13157. dispatchEvent( event ) {
  13158. if ( this._targetRay !== null ) {
  13159. this._targetRay.dispatchEvent( event );
  13160. }
  13161. if ( this._grip !== null ) {
  13162. this._grip.dispatchEvent( event );
  13163. }
  13164. if ( this._hand !== null ) {
  13165. this._hand.dispatchEvent( event );
  13166. }
  13167. return this;
  13168. }
  13169. connect( inputSource ) {
  13170. if ( inputSource && inputSource.hand ) {
  13171. const hand = this._hand;
  13172. if ( hand ) {
  13173. for ( const inputjoint of inputSource.hand.values() ) {
  13174. // Initialize hand with joints when connected
  13175. this._getHandJoint( hand, inputjoint );
  13176. }
  13177. }
  13178. }
  13179. this.dispatchEvent( { type: 'connected', data: inputSource } );
  13180. return this;
  13181. }
  13182. disconnect( inputSource ) {
  13183. this.dispatchEvent( { type: 'disconnected', data: inputSource } );
  13184. if ( this._targetRay !== null ) {
  13185. this._targetRay.visible = false;
  13186. }
  13187. if ( this._grip !== null ) {
  13188. this._grip.visible = false;
  13189. }
  13190. if ( this._hand !== null ) {
  13191. this._hand.visible = false;
  13192. }
  13193. return this;
  13194. }
  13195. update( inputSource, frame, referenceSpace ) {
  13196. let inputPose = null;
  13197. let gripPose = null;
  13198. let handPose = null;
  13199. const targetRay = this._targetRay;
  13200. const grip = this._grip;
  13201. const hand = this._hand;
  13202. if ( inputSource && frame.session.visibilityState !== 'visible-blurred' ) {
  13203. if ( hand && inputSource.hand ) {
  13204. handPose = true;
  13205. for ( const inputjoint of inputSource.hand.values() ) {
  13206. // Update the joints groups with the XRJoint poses
  13207. const jointPose = frame.getJointPose( inputjoint, referenceSpace );
  13208. // The transform of this joint will be updated with the joint pose on each frame
  13209. const joint = this._getHandJoint( hand, inputjoint );
  13210. if ( jointPose !== null ) {
  13211. joint.matrix.fromArray( jointPose.transform.matrix );
  13212. joint.matrix.decompose( joint.position, joint.rotation, joint.scale );
  13213. joint.matrixWorldNeedsUpdate = true;
  13214. joint.jointRadius = jointPose.radius;
  13215. }
  13216. joint.visible = jointPose !== null;
  13217. }
  13218. // Custom events
  13219. // Check pinchz
  13220. const indexTip = hand.joints[ 'index-finger-tip' ];
  13221. const thumbTip = hand.joints[ 'thumb-tip' ];
  13222. const distance = indexTip.position.distanceTo( thumbTip.position );
  13223. const distanceToPinch = 0.02;
  13224. const threshold = 0.005;
  13225. if ( hand.inputState.pinching && distance > distanceToPinch + threshold ) {
  13226. hand.inputState.pinching = false;
  13227. this.dispatchEvent( {
  13228. type: 'pinchend',
  13229. handedness: inputSource.handedness,
  13230. target: this
  13231. } );
  13232. } else if ( ! hand.inputState.pinching && distance <= distanceToPinch - threshold ) {
  13233. hand.inputState.pinching = true;
  13234. this.dispatchEvent( {
  13235. type: 'pinchstart',
  13236. handedness: inputSource.handedness,
  13237. target: this
  13238. } );
  13239. }
  13240. } else {
  13241. if ( grip !== null && inputSource.gripSpace ) {
  13242. gripPose = frame.getPose( inputSource.gripSpace, referenceSpace );
  13243. if ( gripPose !== null ) {
  13244. grip.matrix.fromArray( gripPose.transform.matrix );
  13245. grip.matrix.decompose( grip.position, grip.rotation, grip.scale );
  13246. grip.matrixWorldNeedsUpdate = true;
  13247. if ( gripPose.linearVelocity ) {
  13248. grip.hasLinearVelocity = true;
  13249. grip.linearVelocity.copy( gripPose.linearVelocity );
  13250. } else {
  13251. grip.hasLinearVelocity = false;
  13252. }
  13253. if ( gripPose.angularVelocity ) {
  13254. grip.hasAngularVelocity = true;
  13255. grip.angularVelocity.copy( gripPose.angularVelocity );
  13256. } else {
  13257. grip.hasAngularVelocity = false;
  13258. }
  13259. }
  13260. }
  13261. }
  13262. if ( targetRay !== null ) {
  13263. inputPose = frame.getPose( inputSource.targetRaySpace, referenceSpace );
  13264. // Some runtimes (namely Vive Cosmos with Vive OpenXR Runtime) have only grip space and ray space is equal to it
  13265. if ( inputPose === null && gripPose !== null ) {
  13266. inputPose = gripPose;
  13267. }
  13268. if ( inputPose !== null ) {
  13269. targetRay.matrix.fromArray( inputPose.transform.matrix );
  13270. targetRay.matrix.decompose( targetRay.position, targetRay.rotation, targetRay.scale );
  13271. targetRay.matrixWorldNeedsUpdate = true;
  13272. if ( inputPose.linearVelocity ) {
  13273. targetRay.hasLinearVelocity = true;
  13274. targetRay.linearVelocity.copy( inputPose.linearVelocity );
  13275. } else {
  13276. targetRay.hasLinearVelocity = false;
  13277. }
  13278. if ( inputPose.angularVelocity ) {
  13279. targetRay.hasAngularVelocity = true;
  13280. targetRay.angularVelocity.copy( inputPose.angularVelocity );
  13281. } else {
  13282. targetRay.hasAngularVelocity = false;
  13283. }
  13284. this.dispatchEvent( _moveEvent );
  13285. }
  13286. }
  13287. }
  13288. if ( targetRay !== null ) {
  13289. targetRay.visible = ( inputPose !== null );
  13290. }
  13291. if ( grip !== null ) {
  13292. grip.visible = ( gripPose !== null );
  13293. }
  13294. if ( hand !== null ) {
  13295. hand.visible = ( handPose !== null );
  13296. }
  13297. return this;
  13298. }
  13299. // private method
  13300. _getHandJoint( hand, inputjoint ) {
  13301. if ( hand.joints[ inputjoint.jointName ] === undefined ) {
  13302. const joint = new Group();
  13303. joint.matrixAutoUpdate = false;
  13304. joint.visible = false;
  13305. hand.joints[ inputjoint.jointName ] = joint;
  13306. hand.add( joint );
  13307. }
  13308. return hand.joints[ inputjoint.jointName ];
  13309. }
  13310. }
  13311. /**
  13312. * This class can be used to define an exponential squared fog,
  13313. * which gives a clear view near the camera and a faster than exponentially
  13314. * densening fog farther from the camera.
  13315. *
  13316. * ```js
  13317. * const scene = new THREE.Scene();
  13318. * scene.fog = new THREE.FogExp2( 0xcccccc, 0.002 );
  13319. * ```
  13320. */
  13321. class FogExp2 {
  13322. /**
  13323. * Constructs a new fog.
  13324. *
  13325. * @param {number|Color} color - The fog's color.
  13326. * @param {number} [density=0.00025] - Defines how fast the fog will grow dense.
  13327. */
  13328. constructor( color, density = 0.00025 ) {
  13329. /**
  13330. * This flag can be used for type testing.
  13331. *
  13332. * @type {boolean}
  13333. * @readonly
  13334. * @default true
  13335. */
  13336. this.isFogExp2 = true;
  13337. /**
  13338. * The name of the fog.
  13339. *
  13340. * @type {string}
  13341. */
  13342. this.name = '';
  13343. /**
  13344. * The fog's color.
  13345. *
  13346. * @type {Color}
  13347. */
  13348. this.color = new Color( color );
  13349. /**
  13350. * Defines how fast the fog will grow dense.
  13351. *
  13352. * @type {number}
  13353. * @default 0.00025
  13354. */
  13355. this.density = density;
  13356. }
  13357. /**
  13358. * Returns a new fog with copied values from this instance.
  13359. *
  13360. * @return {FogExp2} A clone of this instance.
  13361. */
  13362. clone() {
  13363. return new FogExp2( this.color, this.density );
  13364. }
  13365. /**
  13366. * Serializes the fog into JSON.
  13367. *
  13368. * @param {?(Object|string)} meta - An optional value holding meta information about the serialization.
  13369. * @return {Object} A JSON object representing the serialized fog
  13370. */
  13371. toJSON( /* meta */ ) {
  13372. return {
  13373. type: 'FogExp2',
  13374. name: this.name,
  13375. color: this.color.getHex(),
  13376. density: this.density
  13377. };
  13378. }
  13379. }
  13380. /**
  13381. * This class can be used to define a linear fog that grows linearly denser
  13382. * with the distance.
  13383. *
  13384. * ```js
  13385. * const scene = new THREE.Scene();
  13386. * scene.fog = new THREE.Fog( 0xcccccc, 10, 15 );
  13387. * ```
  13388. */
  13389. class Fog {
  13390. /**
  13391. * Constructs a new fog.
  13392. *
  13393. * @param {number|Color} color - The fog's color.
  13394. * @param {number} [near=1] - The minimum distance to start applying fog.
  13395. * @param {number} [far=1000] - The maximum distance at which fog stops being calculated and applied.
  13396. */
  13397. constructor( color, near = 1, far = 1000 ) {
  13398. /**
  13399. * This flag can be used for type testing.
  13400. *
  13401. * @type {boolean}
  13402. * @readonly
  13403. * @default true
  13404. */
  13405. this.isFog = true;
  13406. /**
  13407. * The name of the fog.
  13408. *
  13409. * @type {string}
  13410. */
  13411. this.name = '';
  13412. /**
  13413. * The fog's color.
  13414. *
  13415. * @type {Color}
  13416. */
  13417. this.color = new Color( color );
  13418. /**
  13419. * The minimum distance to start applying fog. Objects that are less than
  13420. * `near` units from the active camera won't be affected by fog.
  13421. *
  13422. * @type {number}
  13423. * @default 1
  13424. */
  13425. this.near = near;
  13426. /**
  13427. * The maximum distance at which fog stops being calculated and applied.
  13428. * Objects that are more than `far` units away from the active camera won't
  13429. * be affected by fog.
  13430. *
  13431. * @type {number}
  13432. * @default 1000
  13433. */
  13434. this.far = far;
  13435. }
  13436. /**
  13437. * Returns a new fog with copied values from this instance.
  13438. *
  13439. * @return {Fog} A clone of this instance.
  13440. */
  13441. clone() {
  13442. return new Fog( this.color, this.near, this.far );
  13443. }
  13444. /**
  13445. * Serializes the fog into JSON.
  13446. *
  13447. * @param {?(Object|string)} meta - An optional value holding meta information about the serialization.
  13448. * @return {Object} A JSON object representing the serialized fog
  13449. */
  13450. toJSON( /* meta */ ) {
  13451. return {
  13452. type: 'Fog',
  13453. name: this.name,
  13454. color: this.color.getHex(),
  13455. near: this.near,
  13456. far: this.far
  13457. };
  13458. }
  13459. }
  13460. /**
  13461. * Scenes allow you to set up what is to be rendered and where by three.js.
  13462. * This is where you place 3D objects like meshes, lines or lights.
  13463. *
  13464. * @augments Object3D
  13465. */
  13466. class Scene extends Object3D {
  13467. /**
  13468. * Constructs a new scene.
  13469. */
  13470. constructor() {
  13471. super();
  13472. /**
  13473. * This flag can be used for type testing.
  13474. *
  13475. * @type {boolean}
  13476. * @readonly
  13477. * @default true
  13478. */
  13479. this.isScene = true;
  13480. this.type = 'Scene';
  13481. /**
  13482. * Defines the background of the scene. Valid inputs are:
  13483. *
  13484. * - A color for defining a uniform colored background.
  13485. * - A texture for defining a (flat) textured background.
  13486. * - Cube textures or equirectangular textures for defining a skybox.
  13487. *
  13488. * @type {?(Color|Texture)}
  13489. * @default null
  13490. */
  13491. this.background = null;
  13492. /**
  13493. * Sets the environment map for all physical materials in the scene. However,
  13494. * it's not possible to overwrite an existing texture assigned to the `envMap`
  13495. * material property.
  13496. *
  13497. * @type {?Texture}
  13498. * @default null
  13499. */
  13500. this.environment = null;
  13501. /**
  13502. * A fog instance defining the type of fog that affects everything
  13503. * rendered in the scene.
  13504. *
  13505. * @type {?(Fog|FogExp2)}
  13506. * @default null
  13507. */
  13508. this.fog = null;
  13509. /**
  13510. * Sets the blurriness of the background. Only influences environment maps
  13511. * assigned to {@link Scene#background}. Valid input is a float between `0`
  13512. * and `1`.
  13513. *
  13514. * @type {number}
  13515. * @default 0
  13516. */
  13517. this.backgroundBlurriness = 0;
  13518. /**
  13519. * Attenuates the color of the background. Only applies to background textures.
  13520. *
  13521. * @type {number}
  13522. * @default 1
  13523. */
  13524. this.backgroundIntensity = 1;
  13525. /**
  13526. * The rotation of the background in radians. Only influences environment maps
  13527. * assigned to {@link Scene#background}.
  13528. *
  13529. * @type {Euler}
  13530. * @default (0,0,0)
  13531. */
  13532. this.backgroundRotation = new Euler();
  13533. /**
  13534. * Attenuates the color of the environment. Only influences environment maps
  13535. * assigned to {@link Scene#environment}.
  13536. *
  13537. * @type {number}
  13538. * @default 1
  13539. */
  13540. this.environmentIntensity = 1;
  13541. /**
  13542. * The rotation of the environment map in radians. Only influences physical materials
  13543. * in the scene when {@link Scene#environment} is used.
  13544. *
  13545. * @type {Euler}
  13546. * @default (0,0,0)
  13547. */
  13548. this.environmentRotation = new Euler();
  13549. /**
  13550. * Forces everything in the scene to be rendered with the defined material.
  13551. *
  13552. * @type {?Material}
  13553. * @default null
  13554. */
  13555. this.overrideMaterial = null;
  13556. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  13557. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'observe', { detail: this } ) );
  13558. }
  13559. }
  13560. copy( source, recursive ) {
  13561. super.copy( source, recursive );
  13562. if ( source.background !== null ) this.background = source.background.clone();
  13563. if ( source.environment !== null ) this.environment = source.environment.clone();
  13564. if ( source.fog !== null ) this.fog = source.fog.clone();
  13565. this.backgroundBlurriness = source.backgroundBlurriness;
  13566. this.backgroundIntensity = source.backgroundIntensity;
  13567. this.backgroundRotation.copy( source.backgroundRotation );
  13568. this.environmentIntensity = source.environmentIntensity;
  13569. this.environmentRotation.copy( source.environmentRotation );
  13570. if ( source.overrideMaterial !== null ) this.overrideMaterial = source.overrideMaterial.clone();
  13571. this.matrixAutoUpdate = source.matrixAutoUpdate;
  13572. return this;
  13573. }
  13574. toJSON( meta ) {
  13575. const data = super.toJSON( meta );
  13576. if ( this.fog !== null ) data.object.fog = this.fog.toJSON();
  13577. if ( this.backgroundBlurriness > 0 ) data.object.backgroundBlurriness = this.backgroundBlurriness;
  13578. if ( this.backgroundIntensity !== 1 ) data.object.backgroundIntensity = this.backgroundIntensity;
  13579. data.object.backgroundRotation = this.backgroundRotation.toArray();
  13580. if ( this.environmentIntensity !== 1 ) data.object.environmentIntensity = this.environmentIntensity;
  13581. data.object.environmentRotation = this.environmentRotation.toArray();
  13582. return data;
  13583. }
  13584. }
  13585. class InterleavedBuffer {
  13586. constructor( array, stride ) {
  13587. this.isInterleavedBuffer = true;
  13588. this.array = array;
  13589. this.stride = stride;
  13590. this.count = array !== undefined ? array.length / stride : 0;
  13591. this.usage = StaticDrawUsage;
  13592. this.updateRanges = [];
  13593. this.version = 0;
  13594. this.uuid = generateUUID();
  13595. }
  13596. onUploadCallback() {}
  13597. set needsUpdate( value ) {
  13598. if ( value === true ) this.version ++;
  13599. }
  13600. setUsage( value ) {
  13601. this.usage = value;
  13602. return this;
  13603. }
  13604. addUpdateRange( start, count ) {
  13605. this.updateRanges.push( { start, count } );
  13606. }
  13607. clearUpdateRanges() {
  13608. this.updateRanges.length = 0;
  13609. }
  13610. copy( source ) {
  13611. this.array = new source.array.constructor( source.array );
  13612. this.count = source.count;
  13613. this.stride = source.stride;
  13614. this.usage = source.usage;
  13615. return this;
  13616. }
  13617. copyAt( index1, attribute, index2 ) {
  13618. index1 *= this.stride;
  13619. index2 *= attribute.stride;
  13620. for ( let i = 0, l = this.stride; i < l; i ++ ) {
  13621. this.array[ index1 + i ] = attribute.array[ index2 + i ];
  13622. }
  13623. return this;
  13624. }
  13625. set( value, offset = 0 ) {
  13626. this.array.set( value, offset );
  13627. return this;
  13628. }
  13629. clone( data ) {
  13630. if ( data.arrayBuffers === undefined ) {
  13631. data.arrayBuffers = {};
  13632. }
  13633. if ( this.array.buffer._uuid === undefined ) {
  13634. this.array.buffer._uuid = generateUUID();
  13635. }
  13636. if ( data.arrayBuffers[ this.array.buffer._uuid ] === undefined ) {
  13637. data.arrayBuffers[ this.array.buffer._uuid ] = this.array.slice( 0 ).buffer;
  13638. }
  13639. const array = new this.array.constructor( data.arrayBuffers[ this.array.buffer._uuid ] );
  13640. const ib = new this.constructor( array, this.stride );
  13641. ib.setUsage( this.usage );
  13642. return ib;
  13643. }
  13644. onUpload( callback ) {
  13645. this.onUploadCallback = callback;
  13646. return this;
  13647. }
  13648. toJSON( data ) {
  13649. if ( data.arrayBuffers === undefined ) {
  13650. data.arrayBuffers = {};
  13651. }
  13652. // generate UUID for array buffer if necessary
  13653. if ( this.array.buffer._uuid === undefined ) {
  13654. this.array.buffer._uuid = generateUUID();
  13655. }
  13656. if ( data.arrayBuffers[ this.array.buffer._uuid ] === undefined ) {
  13657. data.arrayBuffers[ this.array.buffer._uuid ] = Array.from( new Uint32Array( this.array.buffer ) );
  13658. }
  13659. //
  13660. return {
  13661. uuid: this.uuid,
  13662. buffer: this.array.buffer._uuid,
  13663. type: this.array.constructor.name,
  13664. stride: this.stride
  13665. };
  13666. }
  13667. }
  13668. const _vector$7 = /*@__PURE__*/ new Vector3();
  13669. class InterleavedBufferAttribute {
  13670. constructor( interleavedBuffer, itemSize, offset, normalized = false ) {
  13671. this.isInterleavedBufferAttribute = true;
  13672. this.name = '';
  13673. this.data = interleavedBuffer;
  13674. this.itemSize = itemSize;
  13675. this.offset = offset;
  13676. this.normalized = normalized;
  13677. }
  13678. get count() {
  13679. return this.data.count;
  13680. }
  13681. get array() {
  13682. return this.data.array;
  13683. }
  13684. set needsUpdate( value ) {
  13685. this.data.needsUpdate = value;
  13686. }
  13687. applyMatrix4( m ) {
  13688. for ( let i = 0, l = this.data.count; i < l; i ++ ) {
  13689. _vector$7.fromBufferAttribute( this, i );
  13690. _vector$7.applyMatrix4( m );
  13691. this.setXYZ( i, _vector$7.x, _vector$7.y, _vector$7.z );
  13692. }
  13693. return this;
  13694. }
  13695. applyNormalMatrix( m ) {
  13696. for ( let i = 0, l = this.count; i < l; i ++ ) {
  13697. _vector$7.fromBufferAttribute( this, i );
  13698. _vector$7.applyNormalMatrix( m );
  13699. this.setXYZ( i, _vector$7.x, _vector$7.y, _vector$7.z );
  13700. }
  13701. return this;
  13702. }
  13703. transformDirection( m ) {
  13704. for ( let i = 0, l = this.count; i < l; i ++ ) {
  13705. _vector$7.fromBufferAttribute( this, i );
  13706. _vector$7.transformDirection( m );
  13707. this.setXYZ( i, _vector$7.x, _vector$7.y, _vector$7.z );
  13708. }
  13709. return this;
  13710. }
  13711. getComponent( index, component ) {
  13712. let value = this.array[ index * this.data.stride + this.offset + component ];
  13713. if ( this.normalized ) value = denormalize( value, this.array );
  13714. return value;
  13715. }
  13716. setComponent( index, component, value ) {
  13717. if ( this.normalized ) value = normalize( value, this.array );
  13718. this.data.array[ index * this.data.stride + this.offset + component ] = value;
  13719. return this;
  13720. }
  13721. setX( index, x ) {
  13722. if ( this.normalized ) x = normalize( x, this.array );
  13723. this.data.array[ index * this.data.stride + this.offset ] = x;
  13724. return this;
  13725. }
  13726. setY( index, y ) {
  13727. if ( this.normalized ) y = normalize( y, this.array );
  13728. this.data.array[ index * this.data.stride + this.offset + 1 ] = y;
  13729. return this;
  13730. }
  13731. setZ( index, z ) {
  13732. if ( this.normalized ) z = normalize( z, this.array );
  13733. this.data.array[ index * this.data.stride + this.offset + 2 ] = z;
  13734. return this;
  13735. }
  13736. setW( index, w ) {
  13737. if ( this.normalized ) w = normalize( w, this.array );
  13738. this.data.array[ index * this.data.stride + this.offset + 3 ] = w;
  13739. return this;
  13740. }
  13741. getX( index ) {
  13742. let x = this.data.array[ index * this.data.stride + this.offset ];
  13743. if ( this.normalized ) x = denormalize( x, this.array );
  13744. return x;
  13745. }
  13746. getY( index ) {
  13747. let y = this.data.array[ index * this.data.stride + this.offset + 1 ];
  13748. if ( this.normalized ) y = denormalize( y, this.array );
  13749. return y;
  13750. }
  13751. getZ( index ) {
  13752. let z = this.data.array[ index * this.data.stride + this.offset + 2 ];
  13753. if ( this.normalized ) z = denormalize( z, this.array );
  13754. return z;
  13755. }
  13756. getW( index ) {
  13757. let w = this.data.array[ index * this.data.stride + this.offset + 3 ];
  13758. if ( this.normalized ) w = denormalize( w, this.array );
  13759. return w;
  13760. }
  13761. setXY( index, x, y ) {
  13762. index = index * this.data.stride + this.offset;
  13763. if ( this.normalized ) {
  13764. x = normalize( x, this.array );
  13765. y = normalize( y, this.array );
  13766. }
  13767. this.data.array[ index + 0 ] = x;
  13768. this.data.array[ index + 1 ] = y;
  13769. return this;
  13770. }
  13771. setXYZ( index, x, y, z ) {
  13772. index = index * this.data.stride + this.offset;
  13773. if ( this.normalized ) {
  13774. x = normalize( x, this.array );
  13775. y = normalize( y, this.array );
  13776. z = normalize( z, this.array );
  13777. }
  13778. this.data.array[ index + 0 ] = x;
  13779. this.data.array[ index + 1 ] = y;
  13780. this.data.array[ index + 2 ] = z;
  13781. return this;
  13782. }
  13783. setXYZW( index, x, y, z, w ) {
  13784. index = index * this.data.stride + this.offset;
  13785. if ( this.normalized ) {
  13786. x = normalize( x, this.array );
  13787. y = normalize( y, this.array );
  13788. z = normalize( z, this.array );
  13789. w = normalize( w, this.array );
  13790. }
  13791. this.data.array[ index + 0 ] = x;
  13792. this.data.array[ index + 1 ] = y;
  13793. this.data.array[ index + 2 ] = z;
  13794. this.data.array[ index + 3 ] = w;
  13795. return this;
  13796. }
  13797. clone( data ) {
  13798. if ( data === undefined ) {
  13799. console.log( 'THREE.InterleavedBufferAttribute.clone(): Cloning an interleaved buffer attribute will de-interleave buffer data.' );
  13800. const array = [];
  13801. for ( let i = 0; i < this.count; i ++ ) {
  13802. const index = i * this.data.stride + this.offset;
  13803. for ( let j = 0; j < this.itemSize; j ++ ) {
  13804. array.push( this.data.array[ index + j ] );
  13805. }
  13806. }
  13807. return new BufferAttribute( new this.array.constructor( array ), this.itemSize, this.normalized );
  13808. } else {
  13809. if ( data.interleavedBuffers === undefined ) {
  13810. data.interleavedBuffers = {};
  13811. }
  13812. if ( data.interleavedBuffers[ this.data.uuid ] === undefined ) {
  13813. data.interleavedBuffers[ this.data.uuid ] = this.data.clone( data );
  13814. }
  13815. return new InterleavedBufferAttribute( data.interleavedBuffers[ this.data.uuid ], this.itemSize, this.offset, this.normalized );
  13816. }
  13817. }
  13818. toJSON( data ) {
  13819. if ( data === undefined ) {
  13820. console.log( 'THREE.InterleavedBufferAttribute.toJSON(): Serializing an interleaved buffer attribute will de-interleave buffer data.' );
  13821. const array = [];
  13822. for ( let i = 0; i < this.count; i ++ ) {
  13823. const index = i * this.data.stride + this.offset;
  13824. for ( let j = 0; j < this.itemSize; j ++ ) {
  13825. array.push( this.data.array[ index + j ] );
  13826. }
  13827. }
  13828. // de-interleave data and save it as an ordinary buffer attribute for now
  13829. return {
  13830. itemSize: this.itemSize,
  13831. type: this.array.constructor.name,
  13832. array: array,
  13833. normalized: this.normalized
  13834. };
  13835. } else {
  13836. // save as true interleaved attribute
  13837. if ( data.interleavedBuffers === undefined ) {
  13838. data.interleavedBuffers = {};
  13839. }
  13840. if ( data.interleavedBuffers[ this.data.uuid ] === undefined ) {
  13841. data.interleavedBuffers[ this.data.uuid ] = this.data.toJSON( data );
  13842. }
  13843. return {
  13844. isInterleavedBufferAttribute: true,
  13845. itemSize: this.itemSize,
  13846. data: this.data.uuid,
  13847. offset: this.offset,
  13848. normalized: this.normalized
  13849. };
  13850. }
  13851. }
  13852. }
  13853. class SpriteMaterial extends Material {
  13854. constructor( parameters ) {
  13855. super();
  13856. this.isSpriteMaterial = true;
  13857. this.type = 'SpriteMaterial';
  13858. this.color = new Color( 0xffffff );
  13859. this.map = null;
  13860. this.alphaMap = null;
  13861. this.rotation = 0;
  13862. this.sizeAttenuation = true;
  13863. this.transparent = true;
  13864. this.fog = true;
  13865. this.setValues( parameters );
  13866. }
  13867. copy( source ) {
  13868. super.copy( source );
  13869. this.color.copy( source.color );
  13870. this.map = source.map;
  13871. this.alphaMap = source.alphaMap;
  13872. this.rotation = source.rotation;
  13873. this.sizeAttenuation = source.sizeAttenuation;
  13874. this.fog = source.fog;
  13875. return this;
  13876. }
  13877. }
  13878. let _geometry;
  13879. const _intersectPoint = /*@__PURE__*/ new Vector3();
  13880. const _worldScale = /*@__PURE__*/ new Vector3();
  13881. const _mvPosition = /*@__PURE__*/ new Vector3();
  13882. const _alignedPosition = /*@__PURE__*/ new Vector2();
  13883. const _rotatedPosition = /*@__PURE__*/ new Vector2();
  13884. const _viewWorldMatrix = /*@__PURE__*/ new Matrix4();
  13885. const _vA = /*@__PURE__*/ new Vector3();
  13886. const _vB = /*@__PURE__*/ new Vector3();
  13887. const _vC = /*@__PURE__*/ new Vector3();
  13888. const _uvA = /*@__PURE__*/ new Vector2();
  13889. const _uvB = /*@__PURE__*/ new Vector2();
  13890. const _uvC = /*@__PURE__*/ new Vector2();
  13891. class Sprite extends Object3D {
  13892. constructor( material = new SpriteMaterial() ) {
  13893. super();
  13894. this.isSprite = true;
  13895. this.type = 'Sprite';
  13896. if ( _geometry === undefined ) {
  13897. _geometry = new BufferGeometry();
  13898. const float32Array = new Float32Array( [
  13899. -0.5, -0.5, 0, 0, 0,
  13900. 0.5, -0.5, 0, 1, 0,
  13901. 0.5, 0.5, 0, 1, 1,
  13902. -0.5, 0.5, 0, 0, 1
  13903. ] );
  13904. const interleavedBuffer = new InterleavedBuffer( float32Array, 5 );
  13905. _geometry.setIndex( [ 0, 1, 2, 0, 2, 3 ] );
  13906. _geometry.setAttribute( 'position', new InterleavedBufferAttribute( interleavedBuffer, 3, 0, false ) );
  13907. _geometry.setAttribute( 'uv', new InterleavedBufferAttribute( interleavedBuffer, 2, 3, false ) );
  13908. }
  13909. this.geometry = _geometry;
  13910. this.material = material;
  13911. this.center = new Vector2( 0.5, 0.5 );
  13912. }
  13913. raycast( raycaster, intersects ) {
  13914. if ( raycaster.camera === null ) {
  13915. console.error( 'THREE.Sprite: "Raycaster.camera" needs to be set in order to raycast against sprites.' );
  13916. }
  13917. _worldScale.setFromMatrixScale( this.matrixWorld );
  13918. _viewWorldMatrix.copy( raycaster.camera.matrixWorld );
  13919. this.modelViewMatrix.multiplyMatrices( raycaster.camera.matrixWorldInverse, this.matrixWorld );
  13920. _mvPosition.setFromMatrixPosition( this.modelViewMatrix );
  13921. if ( raycaster.camera.isPerspectiveCamera && this.material.sizeAttenuation === false ) {
  13922. _worldScale.multiplyScalar( - _mvPosition.z );
  13923. }
  13924. const rotation = this.material.rotation;
  13925. let sin, cos;
  13926. if ( rotation !== 0 ) {
  13927. cos = Math.cos( rotation );
  13928. sin = Math.sin( rotation );
  13929. }
  13930. const center = this.center;
  13931. transformVertex( _vA.set( -0.5, -0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  13932. transformVertex( _vB.set( 0.5, -0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  13933. transformVertex( _vC.set( 0.5, 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  13934. _uvA.set( 0, 0 );
  13935. _uvB.set( 1, 0 );
  13936. _uvC.set( 1, 1 );
  13937. // check first triangle
  13938. let intersect = raycaster.ray.intersectTriangle( _vA, _vB, _vC, false, _intersectPoint );
  13939. if ( intersect === null ) {
  13940. // check second triangle
  13941. transformVertex( _vB.set( -0.5, 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  13942. _uvB.set( 0, 1 );
  13943. intersect = raycaster.ray.intersectTriangle( _vA, _vC, _vB, false, _intersectPoint );
  13944. if ( intersect === null ) {
  13945. return;
  13946. }
  13947. }
  13948. const distance = raycaster.ray.origin.distanceTo( _intersectPoint );
  13949. if ( distance < raycaster.near || distance > raycaster.far ) return;
  13950. intersects.push( {
  13951. distance: distance,
  13952. point: _intersectPoint.clone(),
  13953. uv: Triangle.getInterpolation( _intersectPoint, _vA, _vB, _vC, _uvA, _uvB, _uvC, new Vector2() ),
  13954. face: null,
  13955. object: this
  13956. } );
  13957. }
  13958. copy( source, recursive ) {
  13959. super.copy( source, recursive );
  13960. if ( source.center !== undefined ) this.center.copy( source.center );
  13961. this.material = source.material;
  13962. return this;
  13963. }
  13964. }
  13965. function transformVertex( vertexPosition, mvPosition, center, scale, sin, cos ) {
  13966. // compute position in camera space
  13967. _alignedPosition.subVectors( vertexPosition, center ).addScalar( 0.5 ).multiply( scale );
  13968. // to check if rotation is not zero
  13969. if ( sin !== undefined ) {
  13970. _rotatedPosition.x = ( cos * _alignedPosition.x ) - ( sin * _alignedPosition.y );
  13971. _rotatedPosition.y = ( sin * _alignedPosition.x ) + ( cos * _alignedPosition.y );
  13972. } else {
  13973. _rotatedPosition.copy( _alignedPosition );
  13974. }
  13975. vertexPosition.copy( mvPosition );
  13976. vertexPosition.x += _rotatedPosition.x;
  13977. vertexPosition.y += _rotatedPosition.y;
  13978. // transform to world space
  13979. vertexPosition.applyMatrix4( _viewWorldMatrix );
  13980. }
  13981. const _v1$2 = /*@__PURE__*/ new Vector3();
  13982. const _v2$1 = /*@__PURE__*/ new Vector3();
  13983. class LOD extends Object3D {
  13984. constructor() {
  13985. super();
  13986. this._currentLevel = 0;
  13987. this.type = 'LOD';
  13988. Object.defineProperties( this, {
  13989. levels: {
  13990. enumerable: true,
  13991. value: []
  13992. },
  13993. isLOD: {
  13994. value: true,
  13995. }
  13996. } );
  13997. this.autoUpdate = true;
  13998. }
  13999. copy( source ) {
  14000. super.copy( source, false );
  14001. const levels = source.levels;
  14002. for ( let i = 0, l = levels.length; i < l; i ++ ) {
  14003. const level = levels[ i ];
  14004. this.addLevel( level.object.clone(), level.distance, level.hysteresis );
  14005. }
  14006. this.autoUpdate = source.autoUpdate;
  14007. return this;
  14008. }
  14009. addLevel( object, distance = 0, hysteresis = 0 ) {
  14010. distance = Math.abs( distance );
  14011. const levels = this.levels;
  14012. let l;
  14013. for ( l = 0; l < levels.length; l ++ ) {
  14014. if ( distance < levels[ l ].distance ) {
  14015. break;
  14016. }
  14017. }
  14018. levels.splice( l, 0, { distance: distance, hysteresis: hysteresis, object: object } );
  14019. this.add( object );
  14020. return this;
  14021. }
  14022. removeLevel( distance ) {
  14023. const levels = this.levels;
  14024. for ( let i = 0; i < levels.length; i ++ ) {
  14025. if ( levels[ i ].distance === distance ) {
  14026. const removedElements = levels.splice( i, 1 );
  14027. this.remove( removedElements[ 0 ].object );
  14028. return true;
  14029. }
  14030. }
  14031. return false;
  14032. }
  14033. getCurrentLevel() {
  14034. return this._currentLevel;
  14035. }
  14036. getObjectForDistance( distance ) {
  14037. const levels = this.levels;
  14038. if ( levels.length > 0 ) {
  14039. let i, l;
  14040. for ( i = 1, l = levels.length; i < l; i ++ ) {
  14041. let levelDistance = levels[ i ].distance;
  14042. if ( levels[ i ].object.visible ) {
  14043. levelDistance -= levelDistance * levels[ i ].hysteresis;
  14044. }
  14045. if ( distance < levelDistance ) {
  14046. break;
  14047. }
  14048. }
  14049. return levels[ i - 1 ].object;
  14050. }
  14051. return null;
  14052. }
  14053. raycast( raycaster, intersects ) {
  14054. const levels = this.levels;
  14055. if ( levels.length > 0 ) {
  14056. _v1$2.setFromMatrixPosition( this.matrixWorld );
  14057. const distance = raycaster.ray.origin.distanceTo( _v1$2 );
  14058. this.getObjectForDistance( distance ).raycast( raycaster, intersects );
  14059. }
  14060. }
  14061. update( camera ) {
  14062. const levels = this.levels;
  14063. if ( levels.length > 1 ) {
  14064. _v1$2.setFromMatrixPosition( camera.matrixWorld );
  14065. _v2$1.setFromMatrixPosition( this.matrixWorld );
  14066. const distance = _v1$2.distanceTo( _v2$1 ) / camera.zoom;
  14067. levels[ 0 ].object.visible = true;
  14068. let i, l;
  14069. for ( i = 1, l = levels.length; i < l; i ++ ) {
  14070. let levelDistance = levels[ i ].distance;
  14071. if ( levels[ i ].object.visible ) {
  14072. levelDistance -= levelDistance * levels[ i ].hysteresis;
  14073. }
  14074. if ( distance >= levelDistance ) {
  14075. levels[ i - 1 ].object.visible = false;
  14076. levels[ i ].object.visible = true;
  14077. } else {
  14078. break;
  14079. }
  14080. }
  14081. this._currentLevel = i - 1;
  14082. for ( ; i < l; i ++ ) {
  14083. levels[ i ].object.visible = false;
  14084. }
  14085. }
  14086. }
  14087. toJSON( meta ) {
  14088. const data = super.toJSON( meta );
  14089. if ( this.autoUpdate === false ) data.object.autoUpdate = false;
  14090. data.object.levels = [];
  14091. const levels = this.levels;
  14092. for ( let i = 0, l = levels.length; i < l; i ++ ) {
  14093. const level = levels[ i ];
  14094. data.object.levels.push( {
  14095. object: level.object.uuid,
  14096. distance: level.distance,
  14097. hysteresis: level.hysteresis
  14098. } );
  14099. }
  14100. return data;
  14101. }
  14102. }
  14103. const _basePosition = /*@__PURE__*/ new Vector3();
  14104. const _skinIndex = /*@__PURE__*/ new Vector4();
  14105. const _skinWeight = /*@__PURE__*/ new Vector4();
  14106. const _vector3 = /*@__PURE__*/ new Vector3();
  14107. const _matrix4 = /*@__PURE__*/ new Matrix4();
  14108. const _vertex = /*@__PURE__*/ new Vector3();
  14109. const _sphere$5 = /*@__PURE__*/ new Sphere();
  14110. const _inverseMatrix$2 = /*@__PURE__*/ new Matrix4();
  14111. const _ray$2 = /*@__PURE__*/ new Ray();
  14112. class SkinnedMesh extends Mesh {
  14113. constructor( geometry, material ) {
  14114. super( geometry, material );
  14115. this.isSkinnedMesh = true;
  14116. this.type = 'SkinnedMesh';
  14117. this.bindMode = AttachedBindMode;
  14118. this.bindMatrix = new Matrix4();
  14119. this.bindMatrixInverse = new Matrix4();
  14120. this.boundingBox = null;
  14121. this.boundingSphere = null;
  14122. }
  14123. computeBoundingBox() {
  14124. const geometry = this.geometry;
  14125. if ( this.boundingBox === null ) {
  14126. this.boundingBox = new Box3();
  14127. }
  14128. this.boundingBox.makeEmpty();
  14129. const positionAttribute = geometry.getAttribute( 'position' );
  14130. for ( let i = 0; i < positionAttribute.count; i ++ ) {
  14131. this.getVertexPosition( i, _vertex );
  14132. this.boundingBox.expandByPoint( _vertex );
  14133. }
  14134. }
  14135. computeBoundingSphere() {
  14136. const geometry = this.geometry;
  14137. if ( this.boundingSphere === null ) {
  14138. this.boundingSphere = new Sphere();
  14139. }
  14140. this.boundingSphere.makeEmpty();
  14141. const positionAttribute = geometry.getAttribute( 'position' );
  14142. for ( let i = 0; i < positionAttribute.count; i ++ ) {
  14143. this.getVertexPosition( i, _vertex );
  14144. this.boundingSphere.expandByPoint( _vertex );
  14145. }
  14146. }
  14147. copy( source, recursive ) {
  14148. super.copy( source, recursive );
  14149. this.bindMode = source.bindMode;
  14150. this.bindMatrix.copy( source.bindMatrix );
  14151. this.bindMatrixInverse.copy( source.bindMatrixInverse );
  14152. this.skeleton = source.skeleton;
  14153. if ( source.boundingBox !== null ) this.boundingBox = source.boundingBox.clone();
  14154. if ( source.boundingSphere !== null ) this.boundingSphere = source.boundingSphere.clone();
  14155. return this;
  14156. }
  14157. raycast( raycaster, intersects ) {
  14158. const material = this.material;
  14159. const matrixWorld = this.matrixWorld;
  14160. if ( material === undefined ) return;
  14161. // test with bounding sphere in world space
  14162. if ( this.boundingSphere === null ) this.computeBoundingSphere();
  14163. _sphere$5.copy( this.boundingSphere );
  14164. _sphere$5.applyMatrix4( matrixWorld );
  14165. if ( raycaster.ray.intersectsSphere( _sphere$5 ) === false ) return;
  14166. // convert ray to local space of skinned mesh
  14167. _inverseMatrix$2.copy( matrixWorld ).invert();
  14168. _ray$2.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$2 );
  14169. // test with bounding box in local space
  14170. if ( this.boundingBox !== null ) {
  14171. if ( _ray$2.intersectsBox( this.boundingBox ) === false ) return;
  14172. }
  14173. // test for intersections with geometry
  14174. this._computeIntersections( raycaster, intersects, _ray$2 );
  14175. }
  14176. getVertexPosition( index, target ) {
  14177. super.getVertexPosition( index, target );
  14178. this.applyBoneTransform( index, target );
  14179. return target;
  14180. }
  14181. bind( skeleton, bindMatrix ) {
  14182. this.skeleton = skeleton;
  14183. if ( bindMatrix === undefined ) {
  14184. this.updateMatrixWorld( true );
  14185. this.skeleton.calculateInverses();
  14186. bindMatrix = this.matrixWorld;
  14187. }
  14188. this.bindMatrix.copy( bindMatrix );
  14189. this.bindMatrixInverse.copy( bindMatrix ).invert();
  14190. }
  14191. pose() {
  14192. this.skeleton.pose();
  14193. }
  14194. normalizeSkinWeights() {
  14195. const vector = new Vector4();
  14196. const skinWeight = this.geometry.attributes.skinWeight;
  14197. for ( let i = 0, l = skinWeight.count; i < l; i ++ ) {
  14198. vector.fromBufferAttribute( skinWeight, i );
  14199. const scale = 1.0 / vector.manhattanLength();
  14200. if ( scale !== Infinity ) {
  14201. vector.multiplyScalar( scale );
  14202. } else {
  14203. vector.set( 1, 0, 0, 0 ); // do something reasonable
  14204. }
  14205. skinWeight.setXYZW( i, vector.x, vector.y, vector.z, vector.w );
  14206. }
  14207. }
  14208. updateMatrixWorld( force ) {
  14209. super.updateMatrixWorld( force );
  14210. if ( this.bindMode === AttachedBindMode ) {
  14211. this.bindMatrixInverse.copy( this.matrixWorld ).invert();
  14212. } else if ( this.bindMode === DetachedBindMode ) {
  14213. this.bindMatrixInverse.copy( this.bindMatrix ).invert();
  14214. } else {
  14215. console.warn( 'THREE.SkinnedMesh: Unrecognized bindMode: ' + this.bindMode );
  14216. }
  14217. }
  14218. applyBoneTransform( index, vector ) {
  14219. const skeleton = this.skeleton;
  14220. const geometry = this.geometry;
  14221. _skinIndex.fromBufferAttribute( geometry.attributes.skinIndex, index );
  14222. _skinWeight.fromBufferAttribute( geometry.attributes.skinWeight, index );
  14223. _basePosition.copy( vector ).applyMatrix4( this.bindMatrix );
  14224. vector.set( 0, 0, 0 );
  14225. for ( let i = 0; i < 4; i ++ ) {
  14226. const weight = _skinWeight.getComponent( i );
  14227. if ( weight !== 0 ) {
  14228. const boneIndex = _skinIndex.getComponent( i );
  14229. _matrix4.multiplyMatrices( skeleton.bones[ boneIndex ].matrixWorld, skeleton.boneInverses[ boneIndex ] );
  14230. vector.addScaledVector( _vector3.copy( _basePosition ).applyMatrix4( _matrix4 ), weight );
  14231. }
  14232. }
  14233. return vector.applyMatrix4( this.bindMatrixInverse );
  14234. }
  14235. }
  14236. class Bone extends Object3D {
  14237. constructor() {
  14238. super();
  14239. this.isBone = true;
  14240. this.type = 'Bone';
  14241. }
  14242. }
  14243. class DataTexture extends Texture {
  14244. constructor( data = null, width = 1, height = 1, format, type, mapping, wrapS, wrapT, magFilter = NearestFilter, minFilter = NearestFilter, anisotropy, colorSpace ) {
  14245. super( null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace );
  14246. this.isDataTexture = true;
  14247. this.image = { data: data, width: width, height: height };
  14248. this.generateMipmaps = false;
  14249. this.flipY = false;
  14250. this.unpackAlignment = 1;
  14251. }
  14252. }
  14253. const _offsetMatrix = /*@__PURE__*/ new Matrix4();
  14254. const _identityMatrix = /*@__PURE__*/ new Matrix4();
  14255. class Skeleton {
  14256. constructor( bones = [], boneInverses = [] ) {
  14257. this.uuid = generateUUID();
  14258. this.bones = bones.slice( 0 );
  14259. this.boneInverses = boneInverses;
  14260. this.boneMatrices = null;
  14261. this.boneTexture = null;
  14262. this.init();
  14263. }
  14264. init() {
  14265. const bones = this.bones;
  14266. const boneInverses = this.boneInverses;
  14267. this.boneMatrices = new Float32Array( bones.length * 16 );
  14268. // calculate inverse bone matrices if necessary
  14269. if ( boneInverses.length === 0 ) {
  14270. this.calculateInverses();
  14271. } else {
  14272. // handle special case
  14273. if ( bones.length !== boneInverses.length ) {
  14274. console.warn( 'THREE.Skeleton: Number of inverse bone matrices does not match amount of bones.' );
  14275. this.boneInverses = [];
  14276. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  14277. this.boneInverses.push( new Matrix4() );
  14278. }
  14279. }
  14280. }
  14281. }
  14282. calculateInverses() {
  14283. this.boneInverses.length = 0;
  14284. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  14285. const inverse = new Matrix4();
  14286. if ( this.bones[ i ] ) {
  14287. inverse.copy( this.bones[ i ].matrixWorld ).invert();
  14288. }
  14289. this.boneInverses.push( inverse );
  14290. }
  14291. }
  14292. pose() {
  14293. // recover the bind-time world matrices
  14294. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  14295. const bone = this.bones[ i ];
  14296. if ( bone ) {
  14297. bone.matrixWorld.copy( this.boneInverses[ i ] ).invert();
  14298. }
  14299. }
  14300. // compute the local matrices, positions, rotations and scales
  14301. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  14302. const bone = this.bones[ i ];
  14303. if ( bone ) {
  14304. if ( bone.parent && bone.parent.isBone ) {
  14305. bone.matrix.copy( bone.parent.matrixWorld ).invert();
  14306. bone.matrix.multiply( bone.matrixWorld );
  14307. } else {
  14308. bone.matrix.copy( bone.matrixWorld );
  14309. }
  14310. bone.matrix.decompose( bone.position, bone.quaternion, bone.scale );
  14311. }
  14312. }
  14313. }
  14314. update() {
  14315. const bones = this.bones;
  14316. const boneInverses = this.boneInverses;
  14317. const boneMatrices = this.boneMatrices;
  14318. const boneTexture = this.boneTexture;
  14319. // flatten bone matrices to array
  14320. for ( let i = 0, il = bones.length; i < il; i ++ ) {
  14321. // compute the offset between the current and the original transform
  14322. const matrix = bones[ i ] ? bones[ i ].matrixWorld : _identityMatrix;
  14323. _offsetMatrix.multiplyMatrices( matrix, boneInverses[ i ] );
  14324. _offsetMatrix.toArray( boneMatrices, i * 16 );
  14325. }
  14326. if ( boneTexture !== null ) {
  14327. boneTexture.needsUpdate = true;
  14328. }
  14329. }
  14330. clone() {
  14331. return new Skeleton( this.bones, this.boneInverses );
  14332. }
  14333. computeBoneTexture() {
  14334. // layout (1 matrix = 4 pixels)
  14335. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  14336. // with 8x8 pixel texture max 16 bones * 4 pixels = (8 * 8)
  14337. // 16x16 pixel texture max 64 bones * 4 pixels = (16 * 16)
  14338. // 32x32 pixel texture max 256 bones * 4 pixels = (32 * 32)
  14339. // 64x64 pixel texture max 1024 bones * 4 pixels = (64 * 64)
  14340. let size = Math.sqrt( this.bones.length * 4 ); // 4 pixels needed for 1 matrix
  14341. size = Math.ceil( size / 4 ) * 4;
  14342. size = Math.max( size, 4 );
  14343. const boneMatrices = new Float32Array( size * size * 4 ); // 4 floats per RGBA pixel
  14344. boneMatrices.set( this.boneMatrices ); // copy current values
  14345. const boneTexture = new DataTexture( boneMatrices, size, size, RGBAFormat, FloatType );
  14346. boneTexture.needsUpdate = true;
  14347. this.boneMatrices = boneMatrices;
  14348. this.boneTexture = boneTexture;
  14349. return this;
  14350. }
  14351. getBoneByName( name ) {
  14352. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  14353. const bone = this.bones[ i ];
  14354. if ( bone.name === name ) {
  14355. return bone;
  14356. }
  14357. }
  14358. return undefined;
  14359. }
  14360. dispose( ) {
  14361. if ( this.boneTexture !== null ) {
  14362. this.boneTexture.dispose();
  14363. this.boneTexture = null;
  14364. }
  14365. }
  14366. fromJSON( json, bones ) {
  14367. this.uuid = json.uuid;
  14368. for ( let i = 0, l = json.bones.length; i < l; i ++ ) {
  14369. const uuid = json.bones[ i ];
  14370. let bone = bones[ uuid ];
  14371. if ( bone === undefined ) {
  14372. console.warn( 'THREE.Skeleton: No bone found with UUID:', uuid );
  14373. bone = new Bone();
  14374. }
  14375. this.bones.push( bone );
  14376. this.boneInverses.push( new Matrix4().fromArray( json.boneInverses[ i ] ) );
  14377. }
  14378. this.init();
  14379. return this;
  14380. }
  14381. toJSON() {
  14382. const data = {
  14383. metadata: {
  14384. version: 4.6,
  14385. type: 'Skeleton',
  14386. generator: 'Skeleton.toJSON'
  14387. },
  14388. bones: [],
  14389. boneInverses: []
  14390. };
  14391. data.uuid = this.uuid;
  14392. const bones = this.bones;
  14393. const boneInverses = this.boneInverses;
  14394. for ( let i = 0, l = bones.length; i < l; i ++ ) {
  14395. const bone = bones[ i ];
  14396. data.bones.push( bone.uuid );
  14397. const boneInverse = boneInverses[ i ];
  14398. data.boneInverses.push( boneInverse.toArray() );
  14399. }
  14400. return data;
  14401. }
  14402. }
  14403. class InstancedBufferAttribute extends BufferAttribute {
  14404. constructor( array, itemSize, normalized, meshPerAttribute = 1 ) {
  14405. super( array, itemSize, normalized );
  14406. this.isInstancedBufferAttribute = true;
  14407. this.meshPerAttribute = meshPerAttribute;
  14408. }
  14409. copy( source ) {
  14410. super.copy( source );
  14411. this.meshPerAttribute = source.meshPerAttribute;
  14412. return this;
  14413. }
  14414. toJSON() {
  14415. const data = super.toJSON();
  14416. data.meshPerAttribute = this.meshPerAttribute;
  14417. data.isInstancedBufferAttribute = true;
  14418. return data;
  14419. }
  14420. }
  14421. const _instanceLocalMatrix = /*@__PURE__*/ new Matrix4();
  14422. const _instanceWorldMatrix = /*@__PURE__*/ new Matrix4();
  14423. const _instanceIntersects = [];
  14424. const _box3 = /*@__PURE__*/ new Box3();
  14425. const _identity = /*@__PURE__*/ new Matrix4();
  14426. const _mesh$1 = /*@__PURE__*/ new Mesh();
  14427. const _sphere$4 = /*@__PURE__*/ new Sphere();
  14428. class InstancedMesh extends Mesh {
  14429. constructor( geometry, material, count ) {
  14430. super( geometry, material );
  14431. this.isInstancedMesh = true;
  14432. this.instanceMatrix = new InstancedBufferAttribute( new Float32Array( count * 16 ), 16 );
  14433. this.instanceColor = null;
  14434. this.morphTexture = null;
  14435. this.count = count;
  14436. this.boundingBox = null;
  14437. this.boundingSphere = null;
  14438. for ( let i = 0; i < count; i ++ ) {
  14439. this.setMatrixAt( i, _identity );
  14440. }
  14441. }
  14442. computeBoundingBox() {
  14443. const geometry = this.geometry;
  14444. const count = this.count;
  14445. if ( this.boundingBox === null ) {
  14446. this.boundingBox = new Box3();
  14447. }
  14448. if ( geometry.boundingBox === null ) {
  14449. geometry.computeBoundingBox();
  14450. }
  14451. this.boundingBox.makeEmpty();
  14452. for ( let i = 0; i < count; i ++ ) {
  14453. this.getMatrixAt( i, _instanceLocalMatrix );
  14454. _box3.copy( geometry.boundingBox ).applyMatrix4( _instanceLocalMatrix );
  14455. this.boundingBox.union( _box3 );
  14456. }
  14457. }
  14458. computeBoundingSphere() {
  14459. const geometry = this.geometry;
  14460. const count = this.count;
  14461. if ( this.boundingSphere === null ) {
  14462. this.boundingSphere = new Sphere();
  14463. }
  14464. if ( geometry.boundingSphere === null ) {
  14465. geometry.computeBoundingSphere();
  14466. }
  14467. this.boundingSphere.makeEmpty();
  14468. for ( let i = 0; i < count; i ++ ) {
  14469. this.getMatrixAt( i, _instanceLocalMatrix );
  14470. _sphere$4.copy( geometry.boundingSphere ).applyMatrix4( _instanceLocalMatrix );
  14471. this.boundingSphere.union( _sphere$4 );
  14472. }
  14473. }
  14474. copy( source, recursive ) {
  14475. super.copy( source, recursive );
  14476. this.instanceMatrix.copy( source.instanceMatrix );
  14477. if ( source.morphTexture !== null ) this.morphTexture = source.morphTexture.clone();
  14478. if ( source.instanceColor !== null ) this.instanceColor = source.instanceColor.clone();
  14479. this.count = source.count;
  14480. if ( source.boundingBox !== null ) this.boundingBox = source.boundingBox.clone();
  14481. if ( source.boundingSphere !== null ) this.boundingSphere = source.boundingSphere.clone();
  14482. return this;
  14483. }
  14484. getColorAt( index, color ) {
  14485. color.fromArray( this.instanceColor.array, index * 3 );
  14486. }
  14487. getMatrixAt( index, matrix ) {
  14488. matrix.fromArray( this.instanceMatrix.array, index * 16 );
  14489. }
  14490. getMorphAt( index, object ) {
  14491. const objectInfluences = object.morphTargetInfluences;
  14492. const array = this.morphTexture.source.data.data;
  14493. const len = objectInfluences.length + 1; // All influences + the baseInfluenceSum
  14494. const dataIndex = index * len + 1; // Skip the baseInfluenceSum at the beginning
  14495. for ( let i = 0; i < objectInfluences.length; i ++ ) {
  14496. objectInfluences[ i ] = array[ dataIndex + i ];
  14497. }
  14498. }
  14499. raycast( raycaster, intersects ) {
  14500. const matrixWorld = this.matrixWorld;
  14501. const raycastTimes = this.count;
  14502. _mesh$1.geometry = this.geometry;
  14503. _mesh$1.material = this.material;
  14504. if ( _mesh$1.material === undefined ) return;
  14505. // test with bounding sphere first
  14506. if ( this.boundingSphere === null ) this.computeBoundingSphere();
  14507. _sphere$4.copy( this.boundingSphere );
  14508. _sphere$4.applyMatrix4( matrixWorld );
  14509. if ( raycaster.ray.intersectsSphere( _sphere$4 ) === false ) return;
  14510. // now test each instance
  14511. for ( let instanceId = 0; instanceId < raycastTimes; instanceId ++ ) {
  14512. // calculate the world matrix for each instance
  14513. this.getMatrixAt( instanceId, _instanceLocalMatrix );
  14514. _instanceWorldMatrix.multiplyMatrices( matrixWorld, _instanceLocalMatrix );
  14515. // the mesh represents this single instance
  14516. _mesh$1.matrixWorld = _instanceWorldMatrix;
  14517. _mesh$1.raycast( raycaster, _instanceIntersects );
  14518. // process the result of raycast
  14519. for ( let i = 0, l = _instanceIntersects.length; i < l; i ++ ) {
  14520. const intersect = _instanceIntersects[ i ];
  14521. intersect.instanceId = instanceId;
  14522. intersect.object = this;
  14523. intersects.push( intersect );
  14524. }
  14525. _instanceIntersects.length = 0;
  14526. }
  14527. }
  14528. setColorAt( index, color ) {
  14529. if ( this.instanceColor === null ) {
  14530. this.instanceColor = new InstancedBufferAttribute( new Float32Array( this.instanceMatrix.count * 3 ).fill( 1 ), 3 );
  14531. }
  14532. color.toArray( this.instanceColor.array, index * 3 );
  14533. }
  14534. setMatrixAt( index, matrix ) {
  14535. matrix.toArray( this.instanceMatrix.array, index * 16 );
  14536. }
  14537. setMorphAt( index, object ) {
  14538. const objectInfluences = object.morphTargetInfluences;
  14539. const len = objectInfluences.length + 1; // morphBaseInfluence + all influences
  14540. if ( this.morphTexture === null ) {
  14541. this.morphTexture = new DataTexture( new Float32Array( len * this.count ), len, this.count, RedFormat, FloatType );
  14542. }
  14543. const array = this.morphTexture.source.data.data;
  14544. let morphInfluencesSum = 0;
  14545. for ( let i = 0; i < objectInfluences.length; i ++ ) {
  14546. morphInfluencesSum += objectInfluences[ i ];
  14547. }
  14548. const morphBaseInfluence = this.geometry.morphTargetsRelative ? 1 : 1 - morphInfluencesSum;
  14549. const dataIndex = len * index;
  14550. array[ dataIndex ] = morphBaseInfluence;
  14551. array.set( objectInfluences, dataIndex + 1 );
  14552. }
  14553. updateMorphTargets() {
  14554. }
  14555. dispose() {
  14556. this.dispatchEvent( { type: 'dispose' } );
  14557. if ( this.morphTexture !== null ) {
  14558. this.morphTexture.dispose();
  14559. this.morphTexture = null;
  14560. }
  14561. return this;
  14562. }
  14563. }
  14564. const _vector1 = /*@__PURE__*/ new Vector3();
  14565. const _vector2 = /*@__PURE__*/ new Vector3();
  14566. const _normalMatrix = /*@__PURE__*/ new Matrix3();
  14567. /**
  14568. * A two dimensional surface that extends infinitely in 3D space, represented
  14569. * in [Hessian normal form]{@link http://mathworld.wolfram.com/HessianNormalForm.html}
  14570. * by a unit length normal vector and a constant.
  14571. */
  14572. class Plane {
  14573. /**
  14574. * Constructs a new plane.
  14575. *
  14576. * @param {Vector3} [normal=(1,0,0)] - A unit length vector defining the normal of the plane.
  14577. * @param {number} [constant=0] - The signed distance from the origin to the plane.
  14578. */
  14579. constructor( normal = new Vector3( 1, 0, 0 ), constant = 0 ) {
  14580. /**
  14581. * This flag can be used for type testing.
  14582. *
  14583. * @type {boolean}
  14584. * @readonly
  14585. * @default true
  14586. */
  14587. this.isPlane = true;
  14588. /**
  14589. * A unit length vector defining the normal of the plane.
  14590. *
  14591. * @type {Vector3}
  14592. */
  14593. this.normal = normal;
  14594. /**
  14595. * The signed distance from the origin to the plane.
  14596. *
  14597. * @type {number}
  14598. * @default 0
  14599. */
  14600. this.constant = constant;
  14601. }
  14602. /**
  14603. * Sets the plane components by copying the given values.
  14604. *
  14605. * @param {Vector3} normal - The normal.
  14606. * @param {number} constant - The constant.
  14607. * @return {Plane} A reference to this plane.
  14608. */
  14609. set( normal, constant ) {
  14610. this.normal.copy( normal );
  14611. this.constant = constant;
  14612. return this;
  14613. }
  14614. /**
  14615. * Sets the plane components by defining `x`, `y`, `z` as the
  14616. * plane normal and `w` as the constant.
  14617. *
  14618. * @param {number} x - The value for the normal's x component.
  14619. * @param {number} y - The value for the normal's y component.
  14620. * @param {number} z - The value for the normal's z component.
  14621. * @param {number} w - The constant value.
  14622. * @return {Plane} A reference to this plane.
  14623. */
  14624. setComponents( x, y, z, w ) {
  14625. this.normal.set( x, y, z );
  14626. this.constant = w;
  14627. return this;
  14628. }
  14629. /**
  14630. * Sets the plane from the given normal and coplanar point (that is a point
  14631. * that lies onto the plane).
  14632. *
  14633. * @param {Vector3} normal - The normal.
  14634. * @param {Vector3} point - A coplanar point.
  14635. * @return {Plane} A reference to this plane.
  14636. */
  14637. setFromNormalAndCoplanarPoint( normal, point ) {
  14638. this.normal.copy( normal );
  14639. this.constant = - point.dot( this.normal );
  14640. return this;
  14641. }
  14642. /**
  14643. * Sets the plane from three coplanar points. The winding order is
  14644. * assumed to be counter-clockwise, and determines the direction of
  14645. * the plane normal.
  14646. *
  14647. * @param {Vector3} a - The first coplanar point.
  14648. * @param {Vector3} b - The second coplanar point.
  14649. * @param {Vector3} c - The third coplanar point.
  14650. * @return {Plane} A reference to this plane.
  14651. */
  14652. setFromCoplanarPoints( a, b, c ) {
  14653. const normal = _vector1.subVectors( c, b ).cross( _vector2.subVectors( a, b ) ).normalize();
  14654. // Q: should an error be thrown if normal is zero (e.g. degenerate plane)?
  14655. this.setFromNormalAndCoplanarPoint( normal, a );
  14656. return this;
  14657. }
  14658. /**
  14659. * Copies the values of the given plane to this instance.
  14660. *
  14661. * @param {Plane} plane - The plane to copy.
  14662. * @return {Plane} A reference to this plane.
  14663. */
  14664. copy( plane ) {
  14665. this.normal.copy( plane.normal );
  14666. this.constant = plane.constant;
  14667. return this;
  14668. }
  14669. /**
  14670. * Normalizes the plane normal and adjusts the constant accordingly.
  14671. *
  14672. * @return {Plane} A reference to this plane.
  14673. */
  14674. normalize() {
  14675. // Note: will lead to a divide by zero if the plane is invalid.
  14676. const inverseNormalLength = 1.0 / this.normal.length();
  14677. this.normal.multiplyScalar( inverseNormalLength );
  14678. this.constant *= inverseNormalLength;
  14679. return this;
  14680. }
  14681. /**
  14682. * Negates both the plane normal and the constant.
  14683. *
  14684. * @return {Plane} A reference to this plane.
  14685. */
  14686. negate() {
  14687. this.constant *= -1;
  14688. this.normal.negate();
  14689. return this;
  14690. }
  14691. /**
  14692. * Returns the signed distance from the given point to this plane.
  14693. *
  14694. * @param {Vector3} point - The point to compute the distance for.
  14695. * @return {number} The signed distance.
  14696. */
  14697. distanceToPoint( point ) {
  14698. return this.normal.dot( point ) + this.constant;
  14699. }
  14700. /**
  14701. * Returns the signed distance from the given sphere to this plane.
  14702. *
  14703. * @param {Sphere} sphere - The sphere to compute the distance for.
  14704. * @return {number} The signed distance.
  14705. */
  14706. distanceToSphere( sphere ) {
  14707. return this.distanceToPoint( sphere.center ) - sphere.radius;
  14708. }
  14709. /**
  14710. * Projects a the given point onto the plane.
  14711. *
  14712. * @param {Vector3} point - The point to project.
  14713. * @param {Vector3} target - The target vector that is used to store the method's result.
  14714. * @return {Vector3} The projected point on the plane.
  14715. */
  14716. projectPoint( point, target ) {
  14717. return target.copy( point ).addScaledVector( this.normal, - this.distanceToPoint( point ) );
  14718. }
  14719. /**
  14720. * Returns the intersection point of the passed line and the plane. Returns
  14721. * `null` if the line does not intersect. Returns the line's starting point if
  14722. * the line is coplanar with the plane.
  14723. *
  14724. * @param {Line3} line - The line to compute the intersection for.
  14725. * @param {Vector3} target - The target vector that is used to store the method's result.
  14726. * @return {?Vector3} The intersection point.
  14727. */
  14728. intersectLine( line, target ) {
  14729. const direction = line.delta( _vector1 );
  14730. const denominator = this.normal.dot( direction );
  14731. if ( denominator === 0 ) {
  14732. // line is coplanar, return origin
  14733. if ( this.distanceToPoint( line.start ) === 0 ) {
  14734. return target.copy( line.start );
  14735. }
  14736. // Unsure if this is the correct method to handle this case.
  14737. return null;
  14738. }
  14739. const t = - ( line.start.dot( this.normal ) + this.constant ) / denominator;
  14740. if ( t < 0 || t > 1 ) {
  14741. return null;
  14742. }
  14743. return target.copy( line.start ).addScaledVector( direction, t );
  14744. }
  14745. /**
  14746. * Returns `true` if the given line segment intersects with (passes through) the plane.
  14747. *
  14748. * @param {Line3} line - The line to test.
  14749. * @return {boolean} Whether the given line segment intersects with the plane or not.
  14750. */
  14751. intersectsLine( line ) {
  14752. // Note: this tests if a line intersects the plane, not whether it (or its end-points) are coplanar with it.
  14753. const startSign = this.distanceToPoint( line.start );
  14754. const endSign = this.distanceToPoint( line.end );
  14755. return ( startSign < 0 && endSign > 0 ) || ( endSign < 0 && startSign > 0 );
  14756. }
  14757. /**
  14758. * Returns `true` if the given bounding box intersects with the plane.
  14759. *
  14760. * @param {Box3} box - The bounding box to test.
  14761. * @return {boolean} Whether the given bounding box intersects with the plane or not.
  14762. */
  14763. intersectsBox( box ) {
  14764. return box.intersectsPlane( this );
  14765. }
  14766. /**
  14767. * Returns `true` if the given bounding sphere intersects with the plane.
  14768. *
  14769. * @param {Sphere} sphere - The bounding sphere to test.
  14770. * @return {boolean} Whether the given bounding sphere intersects with the plane or not.
  14771. */
  14772. intersectsSphere( sphere ) {
  14773. return sphere.intersectsPlane( this );
  14774. }
  14775. /**
  14776. * Returns a coplanar vector to the plane, by calculating the
  14777. * projection of the normal at the origin onto the plane.
  14778. *
  14779. * @param {Vector3} target - The target vector that is used to store the method's result.
  14780. * @return {boolean} The coplanar point.
  14781. */
  14782. coplanarPoint( target ) {
  14783. return target.copy( this.normal ).multiplyScalar( - this.constant );
  14784. }
  14785. /**
  14786. * Apply a 4x4 matrix to the plane. The matrix must be an affine, homogeneous transform.
  14787. *
  14788. * The optional normal matrix can be pre-computed like so:
  14789. * ```js
  14790. * const optionalNormalMatrix = new THREE.Matrix3().getNormalMatrix( matrix );
  14791. * ```
  14792. *
  14793. * @param {Matrix4} matrix - The transformation matrix.
  14794. * @param {Matrix4} [optionalNormalMatrix] - A pre-computed normal matrix.
  14795. * @return {Plane} A reference to this plane.
  14796. */
  14797. applyMatrix4( matrix, optionalNormalMatrix ) {
  14798. const normalMatrix = optionalNormalMatrix || _normalMatrix.getNormalMatrix( matrix );
  14799. const referencePoint = this.coplanarPoint( _vector1 ).applyMatrix4( matrix );
  14800. const normal = this.normal.applyMatrix3( normalMatrix ).normalize();
  14801. this.constant = - referencePoint.dot( normal );
  14802. return this;
  14803. }
  14804. /**
  14805. * Translates the plane by the distance defined by the given offset vector.
  14806. * Note that this only affects the plane constant and will not affect the normal vector.
  14807. *
  14808. * @param {Vector3} offset - The offset vector.
  14809. * @return {Plane} A reference to this plane.
  14810. */
  14811. translate( offset ) {
  14812. this.constant -= offset.dot( this.normal );
  14813. return this;
  14814. }
  14815. /**
  14816. * Returns `true` if this plane is equal with the given one.
  14817. *
  14818. * @param {Plane} plane - The plane to test for equality.
  14819. * @return {boolean} Whether this plane is equal with the given one.
  14820. */
  14821. equals( plane ) {
  14822. return plane.normal.equals( this.normal ) && ( plane.constant === this.constant );
  14823. }
  14824. /**
  14825. * Returns a new plane with copied values from this instance.
  14826. *
  14827. * @return {Plane} A clone of this instance.
  14828. */
  14829. clone() {
  14830. return new this.constructor().copy( this );
  14831. }
  14832. }
  14833. const _sphere$3 = /*@__PURE__*/ new Sphere();
  14834. const _vector$6 = /*@__PURE__*/ new Vector3();
  14835. /**
  14836. * Frustums are used to determine what is inside the camera's field of view.
  14837. * They help speed up the rendering process - objects which lie outside a camera's
  14838. * frustum can safely be excluded from rendering.
  14839. *
  14840. * This class is mainly intended for use internally by a renderer.
  14841. */
  14842. class Frustum {
  14843. /**
  14844. * Constructs a new frustum.
  14845. *
  14846. * @param {Plane} [p0] - The first plane that encloses the frustum.
  14847. * @param {Plane} [p1] - The second plane that encloses the frustum.
  14848. * @param {Plane} [p2] - The third plane that encloses the frustum.
  14849. * @param {Plane} [p3] - The fourth plane that encloses the frustum.
  14850. * @param {Plane} [p4] - The fifth plane that encloses the frustum.
  14851. * @param {Plane} [p5] - The sixth plane that encloses the frustum.
  14852. */
  14853. constructor( p0 = new Plane(), p1 = new Plane(), p2 = new Plane(), p3 = new Plane(), p4 = new Plane(), p5 = new Plane() ) {
  14854. /**
  14855. * This array holds the planes that enclose the frustum.
  14856. *
  14857. * @type {Array<Plane>}
  14858. */
  14859. this.planes = [ p0, p1, p2, p3, p4, p5 ];
  14860. }
  14861. /**
  14862. * Sets the frustum planens by copying the given planes.
  14863. *
  14864. * @param {Plane} [p0] - The first plane that encloses the frustum.
  14865. * @param {Plane} [p1] - The second plane that encloses the frustum.
  14866. * @param {Plane} [p2] - The third plane that encloses the frustum.
  14867. * @param {Plane} [p3] - The fourth plane that encloses the frustum.
  14868. * @param {Plane} [p4] - The fifth plane that encloses the frustum.
  14869. * @param {Plane} [p5] - The sixth plane that encloses the frustum.
  14870. * @return {Frustum} A reference to this frustum.
  14871. */
  14872. set( p0, p1, p2, p3, p4, p5 ) {
  14873. const planes = this.planes;
  14874. planes[ 0 ].copy( p0 );
  14875. planes[ 1 ].copy( p1 );
  14876. planes[ 2 ].copy( p2 );
  14877. planes[ 3 ].copy( p3 );
  14878. planes[ 4 ].copy( p4 );
  14879. planes[ 5 ].copy( p5 );
  14880. return this;
  14881. }
  14882. /**
  14883. * Copies the values of the given frustum to this instance.
  14884. *
  14885. * @param {Frustum} frustum - The frustum to copy.
  14886. * @return {Frustum} A reference to this frustum.
  14887. */
  14888. copy( frustum ) {
  14889. const planes = this.planes;
  14890. for ( let i = 0; i < 6; i ++ ) {
  14891. planes[ i ].copy( frustum.planes[ i ] );
  14892. }
  14893. return this;
  14894. }
  14895. /**
  14896. * Sets the frustum planes from the given projection matrix.
  14897. *
  14898. * @param {Matrix4} m - The projection matrix.
  14899. * @param {(WebGLCoordinateSystem|WebGPUCoordinateSystem)} coordinateSystem - The coordinate system.
  14900. * @return {Frustum} A reference to this frustum.
  14901. */
  14902. setFromProjectionMatrix( m, coordinateSystem = WebGLCoordinateSystem ) {
  14903. const planes = this.planes;
  14904. const me = m.elements;
  14905. const me0 = me[ 0 ], me1 = me[ 1 ], me2 = me[ 2 ], me3 = me[ 3 ];
  14906. const me4 = me[ 4 ], me5 = me[ 5 ], me6 = me[ 6 ], me7 = me[ 7 ];
  14907. const me8 = me[ 8 ], me9 = me[ 9 ], me10 = me[ 10 ], me11 = me[ 11 ];
  14908. const me12 = me[ 12 ], me13 = me[ 13 ], me14 = me[ 14 ], me15 = me[ 15 ];
  14909. planes[ 0 ].setComponents( me3 - me0, me7 - me4, me11 - me8, me15 - me12 ).normalize();
  14910. planes[ 1 ].setComponents( me3 + me0, me7 + me4, me11 + me8, me15 + me12 ).normalize();
  14911. planes[ 2 ].setComponents( me3 + me1, me7 + me5, me11 + me9, me15 + me13 ).normalize();
  14912. planes[ 3 ].setComponents( me3 - me1, me7 - me5, me11 - me9, me15 - me13 ).normalize();
  14913. planes[ 4 ].setComponents( me3 - me2, me7 - me6, me11 - me10, me15 - me14 ).normalize();
  14914. if ( coordinateSystem === WebGLCoordinateSystem ) {
  14915. planes[ 5 ].setComponents( me3 + me2, me7 + me6, me11 + me10, me15 + me14 ).normalize();
  14916. } else if ( coordinateSystem === WebGPUCoordinateSystem ) {
  14917. planes[ 5 ].setComponents( me2, me6, me10, me14 ).normalize();
  14918. } else {
  14919. throw new Error( 'THREE.Frustum.setFromProjectionMatrix(): Invalid coordinate system: ' + coordinateSystem );
  14920. }
  14921. return this;
  14922. }
  14923. /**
  14924. * Returns `true` if the 3D object's bounding sphere is intersecting this frustum.
  14925. *
  14926. * Note that the 3D object must have a geometry so that the bounding sphere can be calculated.
  14927. *
  14928. * @param {Object3D} object - The 3D object to test.
  14929. * @return {boolean} Whether the 3D object's bounding sphere is intersecting this frustum or not.
  14930. */
  14931. intersectsObject( object ) {
  14932. if ( object.boundingSphere !== undefined ) {
  14933. if ( object.boundingSphere === null ) object.computeBoundingSphere();
  14934. _sphere$3.copy( object.boundingSphere ).applyMatrix4( object.matrixWorld );
  14935. } else {
  14936. const geometry = object.geometry;
  14937. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  14938. _sphere$3.copy( geometry.boundingSphere ).applyMatrix4( object.matrixWorld );
  14939. }
  14940. return this.intersectsSphere( _sphere$3 );
  14941. }
  14942. /**
  14943. * Returns `true` if the given sprite is intersecting this frustum.
  14944. *
  14945. * @param {Sprite} sprite - The sprite to test.
  14946. * @return {boolean} Whether the sprite is intersecting this frustum or not.
  14947. */
  14948. intersectsSprite( sprite ) {
  14949. _sphere$3.center.set( 0, 0, 0 );
  14950. _sphere$3.radius = 0.7071067811865476;
  14951. _sphere$3.applyMatrix4( sprite.matrixWorld );
  14952. return this.intersectsSphere( _sphere$3 );
  14953. }
  14954. /**
  14955. * Returns `true` if the given bounding sphere is intersecting this frustum.
  14956. *
  14957. * @param {Sphere} sphere - The bounding sphere to test.
  14958. * @return {boolean} Whether the bounding sphere is intersecting this frustum or not.
  14959. */
  14960. intersectsSphere( sphere ) {
  14961. const planes = this.planes;
  14962. const center = sphere.center;
  14963. const negRadius = - sphere.radius;
  14964. for ( let i = 0; i < 6; i ++ ) {
  14965. const distance = planes[ i ].distanceToPoint( center );
  14966. if ( distance < negRadius ) {
  14967. return false;
  14968. }
  14969. }
  14970. return true;
  14971. }
  14972. /**
  14973. * Returns `true` if the given bounding box is intersecting this frustum.
  14974. *
  14975. * @param {Box3} box - The bounding box to test.
  14976. * @return {boolean} Whether the bounding box is intersecting this frustum or not.
  14977. */
  14978. intersectsBox( box ) {
  14979. const planes = this.planes;
  14980. for ( let i = 0; i < 6; i ++ ) {
  14981. const plane = planes[ i ];
  14982. // corner at max distance
  14983. _vector$6.x = plane.normal.x > 0 ? box.max.x : box.min.x;
  14984. _vector$6.y = plane.normal.y > 0 ? box.max.y : box.min.y;
  14985. _vector$6.z = plane.normal.z > 0 ? box.max.z : box.min.z;
  14986. if ( plane.distanceToPoint( _vector$6 ) < 0 ) {
  14987. return false;
  14988. }
  14989. }
  14990. return true;
  14991. }
  14992. /**
  14993. * Returns `true` if the given point lies within the frustum.
  14994. *
  14995. * @param {Vector3} point - The point to test.
  14996. * @return {boolean} Whether the point liest within this frustum or not.
  14997. */
  14998. containsPoint( point ) {
  14999. const planes = this.planes;
  15000. for ( let i = 0; i < 6; i ++ ) {
  15001. if ( planes[ i ].distanceToPoint( point ) < 0 ) {
  15002. return false;
  15003. }
  15004. }
  15005. return true;
  15006. }
  15007. /**
  15008. * Returns a new frustum with copied values from this instance.
  15009. *
  15010. * @return {Frustum} A clone of this instance.
  15011. */
  15012. clone() {
  15013. return new this.constructor().copy( this );
  15014. }
  15015. }
  15016. function ascIdSort( a, b ) {
  15017. return a - b;
  15018. }
  15019. function sortOpaque( a, b ) {
  15020. return a.z - b.z;
  15021. }
  15022. function sortTransparent( a, b ) {
  15023. return b.z - a.z;
  15024. }
  15025. class MultiDrawRenderList {
  15026. constructor() {
  15027. this.index = 0;
  15028. this.pool = [];
  15029. this.list = [];
  15030. }
  15031. push( start, count, z, index ) {
  15032. const pool = this.pool;
  15033. const list = this.list;
  15034. if ( this.index >= pool.length ) {
  15035. pool.push( {
  15036. start: -1,
  15037. count: -1,
  15038. z: -1,
  15039. index: -1,
  15040. } );
  15041. }
  15042. const item = pool[ this.index ];
  15043. list.push( item );
  15044. this.index ++;
  15045. item.start = start;
  15046. item.count = count;
  15047. item.z = z;
  15048. item.index = index;
  15049. }
  15050. reset() {
  15051. this.list.length = 0;
  15052. this.index = 0;
  15053. }
  15054. }
  15055. const _matrix$1 = /*@__PURE__*/ new Matrix4();
  15056. const _whiteColor = /*@__PURE__*/ new Color( 1, 1, 1 );
  15057. const _frustum = /*@__PURE__*/ new Frustum();
  15058. const _box$1 = /*@__PURE__*/ new Box3();
  15059. const _sphere$2 = /*@__PURE__*/ new Sphere();
  15060. const _vector$5 = /*@__PURE__*/ new Vector3();
  15061. const _forward = /*@__PURE__*/ new Vector3();
  15062. const _temp = /*@__PURE__*/ new Vector3();
  15063. const _renderList = /*@__PURE__*/ new MultiDrawRenderList();
  15064. const _mesh = /*@__PURE__*/ new Mesh();
  15065. const _batchIntersects = [];
  15066. // copies data from attribute "src" into "target" starting at "targetOffset"
  15067. function copyAttributeData( src, target, targetOffset = 0 ) {
  15068. const itemSize = target.itemSize;
  15069. if ( src.isInterleavedBufferAttribute || src.array.constructor !== target.array.constructor ) {
  15070. // use the component getters and setters if the array data cannot
  15071. // be copied directly
  15072. const vertexCount = src.count;
  15073. for ( let i = 0; i < vertexCount; i ++ ) {
  15074. for ( let c = 0; c < itemSize; c ++ ) {
  15075. target.setComponent( i + targetOffset, c, src.getComponent( i, c ) );
  15076. }
  15077. }
  15078. } else {
  15079. // faster copy approach using typed array set function
  15080. target.array.set( src.array, targetOffset * itemSize );
  15081. }
  15082. target.needsUpdate = true;
  15083. }
  15084. // safely copies array contents to a potentially smaller array
  15085. function copyArrayContents( src, target ) {
  15086. if ( src.constructor !== target.constructor ) {
  15087. // if arrays are of a different type (eg due to index size increasing) then data must be per-element copied
  15088. const len = Math.min( src.length, target.length );
  15089. for ( let i = 0; i < len; i ++ ) {
  15090. target[ i ] = src[ i ];
  15091. }
  15092. } else {
  15093. // if the arrays use the same data layout we can use a fast block copy
  15094. const len = Math.min( src.length, target.length );
  15095. target.set( new src.constructor( src.buffer, 0, len ) );
  15096. }
  15097. }
  15098. class BatchedMesh extends Mesh {
  15099. get maxInstanceCount() {
  15100. return this._maxInstanceCount;
  15101. }
  15102. get instanceCount() {
  15103. return this._instanceInfo.length - this._availableInstanceIds.length;
  15104. }
  15105. get unusedVertexCount() {
  15106. return this._maxVertexCount - this._nextVertexStart;
  15107. }
  15108. get unusedIndexCount() {
  15109. return this._maxIndexCount - this._nextIndexStart;
  15110. }
  15111. constructor( maxInstanceCount, maxVertexCount, maxIndexCount = maxVertexCount * 2, material ) {
  15112. super( new BufferGeometry(), material );
  15113. this.isBatchedMesh = true;
  15114. this.perObjectFrustumCulled = true;
  15115. this.sortObjects = true;
  15116. this.boundingBox = null;
  15117. this.boundingSphere = null;
  15118. this.customSort = null;
  15119. // stores visible, active, and geometry id per instance and reserved buffer ranges for geometries
  15120. this._instanceInfo = [];
  15121. this._geometryInfo = [];
  15122. // instance, geometry ids that have been set as inactive, and are available to be overwritten
  15123. this._availableInstanceIds = [];
  15124. this._availableGeometryIds = [];
  15125. // used to track where the next point is that geometry should be inserted
  15126. this._nextIndexStart = 0;
  15127. this._nextVertexStart = 0;
  15128. this._geometryCount = 0;
  15129. // flags
  15130. this._visibilityChanged = true;
  15131. this._geometryInitialized = false;
  15132. // cached user options
  15133. this._maxInstanceCount = maxInstanceCount;
  15134. this._maxVertexCount = maxVertexCount;
  15135. this._maxIndexCount = maxIndexCount;
  15136. // buffers for multi draw
  15137. this._multiDrawCounts = new Int32Array( maxInstanceCount );
  15138. this._multiDrawStarts = new Int32Array( maxInstanceCount );
  15139. this._multiDrawCount = 0;
  15140. this._multiDrawInstances = null;
  15141. // Local matrix per geometry by using data texture
  15142. this._matricesTexture = null;
  15143. this._indirectTexture = null;
  15144. this._colorsTexture = null;
  15145. this._initMatricesTexture();
  15146. this._initIndirectTexture();
  15147. }
  15148. _initMatricesTexture() {
  15149. // layout (1 matrix = 4 pixels)
  15150. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  15151. // with 8x8 pixel texture max 16 matrices * 4 pixels = (8 * 8)
  15152. // 16x16 pixel texture max 64 matrices * 4 pixels = (16 * 16)
  15153. // 32x32 pixel texture max 256 matrices * 4 pixels = (32 * 32)
  15154. // 64x64 pixel texture max 1024 matrices * 4 pixels = (64 * 64)
  15155. let size = Math.sqrt( this._maxInstanceCount * 4 ); // 4 pixels needed for 1 matrix
  15156. size = Math.ceil( size / 4 ) * 4;
  15157. size = Math.max( size, 4 );
  15158. const matricesArray = new Float32Array( size * size * 4 ); // 4 floats per RGBA pixel
  15159. const matricesTexture = new DataTexture( matricesArray, size, size, RGBAFormat, FloatType );
  15160. this._matricesTexture = matricesTexture;
  15161. }
  15162. _initIndirectTexture() {
  15163. let size = Math.sqrt( this._maxInstanceCount );
  15164. size = Math.ceil( size );
  15165. const indirectArray = new Uint32Array( size * size );
  15166. const indirectTexture = new DataTexture( indirectArray, size, size, RedIntegerFormat, UnsignedIntType );
  15167. this._indirectTexture = indirectTexture;
  15168. }
  15169. _initColorsTexture() {
  15170. let size = Math.sqrt( this._maxInstanceCount );
  15171. size = Math.ceil( size );
  15172. // 4 floats per RGBA pixel initialized to white
  15173. const colorsArray = new Float32Array( size * size * 4 ).fill( 1 );
  15174. const colorsTexture = new DataTexture( colorsArray, size, size, RGBAFormat, FloatType );
  15175. colorsTexture.colorSpace = ColorManagement.workingColorSpace;
  15176. this._colorsTexture = colorsTexture;
  15177. }
  15178. _initializeGeometry( reference ) {
  15179. const geometry = this.geometry;
  15180. const maxVertexCount = this._maxVertexCount;
  15181. const maxIndexCount = this._maxIndexCount;
  15182. if ( this._geometryInitialized === false ) {
  15183. for ( const attributeName in reference.attributes ) {
  15184. const srcAttribute = reference.getAttribute( attributeName );
  15185. const { array, itemSize, normalized } = srcAttribute;
  15186. const dstArray = new array.constructor( maxVertexCount * itemSize );
  15187. const dstAttribute = new BufferAttribute( dstArray, itemSize, normalized );
  15188. geometry.setAttribute( attributeName, dstAttribute );
  15189. }
  15190. if ( reference.getIndex() !== null ) {
  15191. // Reserve last u16 index for primitive restart.
  15192. const indexArray = maxVertexCount > 65535
  15193. ? new Uint32Array( maxIndexCount )
  15194. : new Uint16Array( maxIndexCount );
  15195. geometry.setIndex( new BufferAttribute( indexArray, 1 ) );
  15196. }
  15197. this._geometryInitialized = true;
  15198. }
  15199. }
  15200. // Make sure the geometry is compatible with the existing combined geometry attributes
  15201. _validateGeometry( geometry ) {
  15202. // check to ensure the geometries are using consistent attributes and indices
  15203. const batchGeometry = this.geometry;
  15204. if ( Boolean( geometry.getIndex() ) !== Boolean( batchGeometry.getIndex() ) ) {
  15205. throw new Error( 'THREE.BatchedMesh: All geometries must consistently have "index".' );
  15206. }
  15207. for ( const attributeName in batchGeometry.attributes ) {
  15208. if ( ! geometry.hasAttribute( attributeName ) ) {
  15209. throw new Error( `THREE.BatchedMesh: Added geometry missing "${ attributeName }". All geometries must have consistent attributes.` );
  15210. }
  15211. const srcAttribute = geometry.getAttribute( attributeName );
  15212. const dstAttribute = batchGeometry.getAttribute( attributeName );
  15213. if ( srcAttribute.itemSize !== dstAttribute.itemSize || srcAttribute.normalized !== dstAttribute.normalized ) {
  15214. throw new Error( 'THREE.BatchedMesh: All attributes must have a consistent itemSize and normalized value.' );
  15215. }
  15216. }
  15217. }
  15218. validateInstanceId( instanceId ) {
  15219. const instanceInfo = this._instanceInfo;
  15220. if ( instanceId < 0 || instanceId >= instanceInfo.length || instanceInfo[ instanceId ].active === false ) {
  15221. throw new Error( `THREE.BatchedMesh: Invalid instanceId ${instanceId}. Instance is either out of range or has been deleted.` );
  15222. }
  15223. }
  15224. validateGeometryId( geometryId ) {
  15225. const geometryInfoList = this._geometryInfo;
  15226. if ( geometryId < 0 || geometryId >= geometryInfoList.length || geometryInfoList[ geometryId ].active === false ) {
  15227. throw new Error( `THREE.BatchedMesh: Invalid geometryId ${geometryId}. Geometry is either out of range or has been deleted.` );
  15228. }
  15229. }
  15230. setCustomSort( func ) {
  15231. this.customSort = func;
  15232. return this;
  15233. }
  15234. computeBoundingBox() {
  15235. if ( this.boundingBox === null ) {
  15236. this.boundingBox = new Box3();
  15237. }
  15238. const boundingBox = this.boundingBox;
  15239. const instanceInfo = this._instanceInfo;
  15240. boundingBox.makeEmpty();
  15241. for ( let i = 0, l = instanceInfo.length; i < l; i ++ ) {
  15242. if ( instanceInfo[ i ].active === false ) continue;
  15243. const geometryId = instanceInfo[ i ].geometryIndex;
  15244. this.getMatrixAt( i, _matrix$1 );
  15245. this.getBoundingBoxAt( geometryId, _box$1 ).applyMatrix4( _matrix$1 );
  15246. boundingBox.union( _box$1 );
  15247. }
  15248. }
  15249. computeBoundingSphere() {
  15250. if ( this.boundingSphere === null ) {
  15251. this.boundingSphere = new Sphere();
  15252. }
  15253. const boundingSphere = this.boundingSphere;
  15254. const instanceInfo = this._instanceInfo;
  15255. boundingSphere.makeEmpty();
  15256. for ( let i = 0, l = instanceInfo.length; i < l; i ++ ) {
  15257. if ( instanceInfo[ i ].active === false ) continue;
  15258. const geometryId = instanceInfo[ i ].geometryIndex;
  15259. this.getMatrixAt( i, _matrix$1 );
  15260. this.getBoundingSphereAt( geometryId, _sphere$2 ).applyMatrix4( _matrix$1 );
  15261. boundingSphere.union( _sphere$2 );
  15262. }
  15263. }
  15264. addInstance( geometryId ) {
  15265. const atCapacity = this._instanceInfo.length >= this.maxInstanceCount;
  15266. // ensure we're not over geometry
  15267. if ( atCapacity && this._availableInstanceIds.length === 0 ) {
  15268. throw new Error( 'THREE.BatchedMesh: Maximum item count reached.' );
  15269. }
  15270. const instanceInfo = {
  15271. visible: true,
  15272. active: true,
  15273. geometryIndex: geometryId,
  15274. };
  15275. let drawId = null;
  15276. // Prioritize using previously freed instance ids
  15277. if ( this._availableInstanceIds.length > 0 ) {
  15278. this._availableInstanceIds.sort( ascIdSort );
  15279. drawId = this._availableInstanceIds.shift();
  15280. this._instanceInfo[ drawId ] = instanceInfo;
  15281. } else {
  15282. drawId = this._instanceInfo.length;
  15283. this._instanceInfo.push( instanceInfo );
  15284. }
  15285. const matricesTexture = this._matricesTexture;
  15286. _matrix$1.identity().toArray( matricesTexture.image.data, drawId * 16 );
  15287. matricesTexture.needsUpdate = true;
  15288. const colorsTexture = this._colorsTexture;
  15289. if ( colorsTexture ) {
  15290. _whiteColor.toArray( colorsTexture.image.data, drawId * 4 );
  15291. colorsTexture.needsUpdate = true;
  15292. }
  15293. this._visibilityChanged = true;
  15294. return drawId;
  15295. }
  15296. addGeometry( geometry, reservedVertexCount = -1, reservedIndexCount = -1 ) {
  15297. this._initializeGeometry( geometry );
  15298. this._validateGeometry( geometry );
  15299. const geometryInfo = {
  15300. // geometry information
  15301. vertexStart: -1,
  15302. vertexCount: -1,
  15303. reservedVertexCount: -1,
  15304. indexStart: -1,
  15305. indexCount: -1,
  15306. reservedIndexCount: -1,
  15307. // draw range information
  15308. start: -1,
  15309. count: -1,
  15310. // state
  15311. boundingBox: null,
  15312. boundingSphere: null,
  15313. active: true,
  15314. };
  15315. const geometryInfoList = this._geometryInfo;
  15316. geometryInfo.vertexStart = this._nextVertexStart;
  15317. geometryInfo.reservedVertexCount = reservedVertexCount === -1 ? geometry.getAttribute( 'position' ).count : reservedVertexCount;
  15318. const index = geometry.getIndex();
  15319. const hasIndex = index !== null;
  15320. if ( hasIndex ) {
  15321. geometryInfo.indexStart = this._nextIndexStart;
  15322. geometryInfo.reservedIndexCount = reservedIndexCount === -1 ? index.count : reservedIndexCount;
  15323. }
  15324. if (
  15325. geometryInfo.indexStart !== -1 &&
  15326. geometryInfo.indexStart + geometryInfo.reservedIndexCount > this._maxIndexCount ||
  15327. geometryInfo.vertexStart + geometryInfo.reservedVertexCount > this._maxVertexCount
  15328. ) {
  15329. throw new Error( 'THREE.BatchedMesh: Reserved space request exceeds the maximum buffer size.' );
  15330. }
  15331. // update id
  15332. let geometryId;
  15333. if ( this._availableGeometryIds.length > 0 ) {
  15334. this._availableGeometryIds.sort( ascIdSort );
  15335. geometryId = this._availableGeometryIds.shift();
  15336. geometryInfoList[ geometryId ] = geometryInfo;
  15337. } else {
  15338. geometryId = this._geometryCount;
  15339. this._geometryCount ++;
  15340. geometryInfoList.push( geometryInfo );
  15341. }
  15342. // update the geometry
  15343. this.setGeometryAt( geometryId, geometry );
  15344. // increment the next geometry position
  15345. this._nextIndexStart = geometryInfo.indexStart + geometryInfo.reservedIndexCount;
  15346. this._nextVertexStart = geometryInfo.vertexStart + geometryInfo.reservedVertexCount;
  15347. return geometryId;
  15348. }
  15349. setGeometryAt( geometryId, geometry ) {
  15350. if ( geometryId >= this._geometryCount ) {
  15351. throw new Error( 'THREE.BatchedMesh: Maximum geometry count reached.' );
  15352. }
  15353. this._validateGeometry( geometry );
  15354. const batchGeometry = this.geometry;
  15355. const hasIndex = batchGeometry.getIndex() !== null;
  15356. const dstIndex = batchGeometry.getIndex();
  15357. const srcIndex = geometry.getIndex();
  15358. const geometryInfo = this._geometryInfo[ geometryId ];
  15359. if (
  15360. hasIndex &&
  15361. srcIndex.count > geometryInfo.reservedIndexCount ||
  15362. geometry.attributes.position.count > geometryInfo.reservedVertexCount
  15363. ) {
  15364. throw new Error( 'THREE.BatchedMesh: Reserved space not large enough for provided geometry.' );
  15365. }
  15366. // copy geometry buffer data over
  15367. const vertexStart = geometryInfo.vertexStart;
  15368. const reservedVertexCount = geometryInfo.reservedVertexCount;
  15369. geometryInfo.vertexCount = geometry.getAttribute( 'position' ).count;
  15370. for ( const attributeName in batchGeometry.attributes ) {
  15371. // copy attribute data
  15372. const srcAttribute = geometry.getAttribute( attributeName );
  15373. const dstAttribute = batchGeometry.getAttribute( attributeName );
  15374. copyAttributeData( srcAttribute, dstAttribute, vertexStart );
  15375. // fill the rest in with zeroes
  15376. const itemSize = srcAttribute.itemSize;
  15377. for ( let i = srcAttribute.count, l = reservedVertexCount; i < l; i ++ ) {
  15378. const index = vertexStart + i;
  15379. for ( let c = 0; c < itemSize; c ++ ) {
  15380. dstAttribute.setComponent( index, c, 0 );
  15381. }
  15382. }
  15383. dstAttribute.needsUpdate = true;
  15384. dstAttribute.addUpdateRange( vertexStart * itemSize, reservedVertexCount * itemSize );
  15385. }
  15386. // copy index
  15387. if ( hasIndex ) {
  15388. const indexStart = geometryInfo.indexStart;
  15389. const reservedIndexCount = geometryInfo.reservedIndexCount;
  15390. geometryInfo.indexCount = geometry.getIndex().count;
  15391. // copy index data over
  15392. for ( let i = 0; i < srcIndex.count; i ++ ) {
  15393. dstIndex.setX( indexStart + i, vertexStart + srcIndex.getX( i ) );
  15394. }
  15395. // fill the rest in with zeroes
  15396. for ( let i = srcIndex.count, l = reservedIndexCount; i < l; i ++ ) {
  15397. dstIndex.setX( indexStart + i, vertexStart );
  15398. }
  15399. dstIndex.needsUpdate = true;
  15400. dstIndex.addUpdateRange( indexStart, geometryInfo.reservedIndexCount );
  15401. }
  15402. // update the draw range
  15403. geometryInfo.start = hasIndex ? geometryInfo.indexStart : geometryInfo.vertexStart;
  15404. geometryInfo.count = hasIndex ? geometryInfo.indexCount : geometryInfo.vertexCount;
  15405. // store the bounding boxes
  15406. geometryInfo.boundingBox = null;
  15407. if ( geometry.boundingBox !== null ) {
  15408. geometryInfo.boundingBox = geometry.boundingBox.clone();
  15409. }
  15410. geometryInfo.boundingSphere = null;
  15411. if ( geometry.boundingSphere !== null ) {
  15412. geometryInfo.boundingSphere = geometry.boundingSphere.clone();
  15413. }
  15414. this._visibilityChanged = true;
  15415. return geometryId;
  15416. }
  15417. deleteGeometry( geometryId ) {
  15418. const geometryInfoList = this._geometryInfo;
  15419. if ( geometryId >= geometryInfoList.length || geometryInfoList[ geometryId ].active === false ) {
  15420. return this;
  15421. }
  15422. // delete any instances associated with this geometry
  15423. const instanceInfo = this._instanceInfo;
  15424. for ( let i = 0, l = instanceInfo.length; i < l; i ++ ) {
  15425. if ( instanceInfo[ i ].active && instanceInfo[ i ].geometryIndex === geometryId ) {
  15426. this.deleteInstance( i );
  15427. }
  15428. }
  15429. geometryInfoList[ geometryId ].active = false;
  15430. this._availableGeometryIds.push( geometryId );
  15431. this._visibilityChanged = true;
  15432. return this;
  15433. }
  15434. deleteInstance( instanceId ) {
  15435. this.validateInstanceId( instanceId );
  15436. this._instanceInfo[ instanceId ].active = false;
  15437. this._availableInstanceIds.push( instanceId );
  15438. this._visibilityChanged = true;
  15439. return this;
  15440. }
  15441. optimize() {
  15442. // track the next indices to copy data to
  15443. let nextVertexStart = 0;
  15444. let nextIndexStart = 0;
  15445. // Iterate over all geometry ranges in order sorted from earliest in the geometry buffer to latest
  15446. // in the geometry buffer. Because draw range objects can be reused there is no guarantee of their order.
  15447. const geometryInfoList = this._geometryInfo;
  15448. const indices = geometryInfoList
  15449. .map( ( e, i ) => i )
  15450. .sort( ( a, b ) => {
  15451. return geometryInfoList[ a ].vertexStart - geometryInfoList[ b ].vertexStart;
  15452. } );
  15453. const geometry = this.geometry;
  15454. for ( let i = 0, l = geometryInfoList.length; i < l; i ++ ) {
  15455. // if a geometry range is inactive then don't copy anything
  15456. const index = indices[ i ];
  15457. const geometryInfo = geometryInfoList[ index ];
  15458. if ( geometryInfo.active === false ) {
  15459. continue;
  15460. }
  15461. // if a geometry contains an index buffer then shift it, as well
  15462. if ( geometry.index !== null ) {
  15463. if ( geometryInfo.indexStart !== nextIndexStart ) {
  15464. const { indexStart, vertexStart, reservedIndexCount } = geometryInfo;
  15465. const index = geometry.index;
  15466. const array = index.array;
  15467. // shift the index pointers based on how the vertex data will shift
  15468. // adjusting the index must happen first so the original vertex start value is available
  15469. const elementDelta = nextVertexStart - vertexStart;
  15470. for ( let j = indexStart; j < indexStart + reservedIndexCount; j ++ ) {
  15471. array[ j ] = array[ j ] + elementDelta;
  15472. }
  15473. index.array.copyWithin( nextIndexStart, indexStart, indexStart + reservedIndexCount );
  15474. index.addUpdateRange( nextIndexStart, reservedIndexCount );
  15475. geometryInfo.indexStart = nextIndexStart;
  15476. }
  15477. nextIndexStart += geometryInfo.reservedIndexCount;
  15478. }
  15479. // if a geometry needs to be moved then copy attribute data to overwrite unused space
  15480. if ( geometryInfo.vertexStart !== nextVertexStart ) {
  15481. const { vertexStart, reservedVertexCount } = geometryInfo;
  15482. const attributes = geometry.attributes;
  15483. for ( const key in attributes ) {
  15484. const attribute = attributes[ key ];
  15485. const { array, itemSize } = attribute;
  15486. array.copyWithin( nextVertexStart * itemSize, vertexStart * itemSize, ( vertexStart + reservedVertexCount ) * itemSize );
  15487. attribute.addUpdateRange( nextVertexStart * itemSize, reservedVertexCount * itemSize );
  15488. }
  15489. geometryInfo.vertexStart = nextVertexStart;
  15490. }
  15491. nextVertexStart += geometryInfo.reservedVertexCount;
  15492. geometryInfo.start = geometry.index ? geometryInfo.indexStart : geometryInfo.vertexStart;
  15493. // step the next geometry points to the shifted position
  15494. this._nextIndexStart = geometry.index ? geometryInfo.indexStart + geometryInfo.reservedIndexCount : 0;
  15495. this._nextVertexStart = geometryInfo.vertexStart + geometryInfo.reservedVertexCount;
  15496. }
  15497. return this;
  15498. }
  15499. // get bounding box and compute it if it doesn't exist
  15500. getBoundingBoxAt( geometryId, target ) {
  15501. if ( geometryId >= this._geometryCount ) {
  15502. return null;
  15503. }
  15504. // compute bounding box
  15505. const geometry = this.geometry;
  15506. const geometryInfo = this._geometryInfo[ geometryId ];
  15507. if ( geometryInfo.boundingBox === null ) {
  15508. const box = new Box3();
  15509. const index = geometry.index;
  15510. const position = geometry.attributes.position;
  15511. for ( let i = geometryInfo.start, l = geometryInfo.start + geometryInfo.count; i < l; i ++ ) {
  15512. let iv = i;
  15513. if ( index ) {
  15514. iv = index.getX( iv );
  15515. }
  15516. box.expandByPoint( _vector$5.fromBufferAttribute( position, iv ) );
  15517. }
  15518. geometryInfo.boundingBox = box;
  15519. }
  15520. target.copy( geometryInfo.boundingBox );
  15521. return target;
  15522. }
  15523. // get bounding sphere and compute it if it doesn't exist
  15524. getBoundingSphereAt( geometryId, target ) {
  15525. if ( geometryId >= this._geometryCount ) {
  15526. return null;
  15527. }
  15528. // compute bounding sphere
  15529. const geometry = this.geometry;
  15530. const geometryInfo = this._geometryInfo[ geometryId ];
  15531. if ( geometryInfo.boundingSphere === null ) {
  15532. const sphere = new Sphere();
  15533. this.getBoundingBoxAt( geometryId, _box$1 );
  15534. _box$1.getCenter( sphere.center );
  15535. const index = geometry.index;
  15536. const position = geometry.attributes.position;
  15537. let maxRadiusSq = 0;
  15538. for ( let i = geometryInfo.start, l = geometryInfo.start + geometryInfo.count; i < l; i ++ ) {
  15539. let iv = i;
  15540. if ( index ) {
  15541. iv = index.getX( iv );
  15542. }
  15543. _vector$5.fromBufferAttribute( position, iv );
  15544. maxRadiusSq = Math.max( maxRadiusSq, sphere.center.distanceToSquared( _vector$5 ) );
  15545. }
  15546. sphere.radius = Math.sqrt( maxRadiusSq );
  15547. geometryInfo.boundingSphere = sphere;
  15548. }
  15549. target.copy( geometryInfo.boundingSphere );
  15550. return target;
  15551. }
  15552. setMatrixAt( instanceId, matrix ) {
  15553. this.validateInstanceId( instanceId );
  15554. const matricesTexture = this._matricesTexture;
  15555. const matricesArray = this._matricesTexture.image.data;
  15556. matrix.toArray( matricesArray, instanceId * 16 );
  15557. matricesTexture.needsUpdate = true;
  15558. return this;
  15559. }
  15560. getMatrixAt( instanceId, matrix ) {
  15561. this.validateInstanceId( instanceId );
  15562. return matrix.fromArray( this._matricesTexture.image.data, instanceId * 16 );
  15563. }
  15564. setColorAt( instanceId, color ) {
  15565. this.validateInstanceId( instanceId );
  15566. if ( this._colorsTexture === null ) {
  15567. this._initColorsTexture();
  15568. }
  15569. color.toArray( this._colorsTexture.image.data, instanceId * 4 );
  15570. this._colorsTexture.needsUpdate = true;
  15571. return this;
  15572. }
  15573. getColorAt( instanceId, color ) {
  15574. this.validateInstanceId( instanceId );
  15575. return color.fromArray( this._colorsTexture.image.data, instanceId * 4 );
  15576. }
  15577. setVisibleAt( instanceId, value ) {
  15578. this.validateInstanceId( instanceId );
  15579. if ( this._instanceInfo[ instanceId ].visible === value ) {
  15580. return this;
  15581. }
  15582. this._instanceInfo[ instanceId ].visible = value;
  15583. this._visibilityChanged = true;
  15584. return this;
  15585. }
  15586. getVisibleAt( instanceId ) {
  15587. this.validateInstanceId( instanceId );
  15588. return this._instanceInfo[ instanceId ].visible;
  15589. }
  15590. setGeometryIdAt( instanceId, geometryId ) {
  15591. this.validateInstanceId( instanceId );
  15592. this.validateGeometryId( geometryId );
  15593. this._instanceInfo[ instanceId ].geometryIndex = geometryId;
  15594. return this;
  15595. }
  15596. getGeometryIdAt( instanceId ) {
  15597. this.validateInstanceId( instanceId );
  15598. return this._instanceInfo[ instanceId ].geometryIndex;
  15599. }
  15600. getGeometryRangeAt( geometryId, target = {} ) {
  15601. this.validateGeometryId( geometryId );
  15602. const geometryInfo = this._geometryInfo[ geometryId ];
  15603. target.vertexStart = geometryInfo.vertexStart;
  15604. target.vertexCount = geometryInfo.vertexCount;
  15605. target.reservedVertexCount = geometryInfo.reservedVertexCount;
  15606. target.indexStart = geometryInfo.indexStart;
  15607. target.indexCount = geometryInfo.indexCount;
  15608. target.reservedIndexCount = geometryInfo.reservedIndexCount;
  15609. target.start = geometryInfo.start;
  15610. target.count = geometryInfo.count;
  15611. return target;
  15612. }
  15613. setInstanceCount( maxInstanceCount ) {
  15614. // shrink the available instances as much as possible
  15615. const availableInstanceIds = this._availableInstanceIds;
  15616. const instanceInfo = this._instanceInfo;
  15617. availableInstanceIds.sort( ascIdSort );
  15618. while ( availableInstanceIds[ availableInstanceIds.length - 1 ] === instanceInfo.length ) {
  15619. instanceInfo.pop();
  15620. availableInstanceIds.pop();
  15621. }
  15622. // throw an error if it can't be shrunk to the desired size
  15623. if ( maxInstanceCount < instanceInfo.length ) {
  15624. throw new Error( `BatchedMesh: Instance ids outside the range ${ maxInstanceCount } are being used. Cannot shrink instance count.` );
  15625. }
  15626. // copy the multi draw counts
  15627. const multiDrawCounts = new Int32Array( maxInstanceCount );
  15628. const multiDrawStarts = new Int32Array( maxInstanceCount );
  15629. copyArrayContents( this._multiDrawCounts, multiDrawCounts );
  15630. copyArrayContents( this._multiDrawStarts, multiDrawStarts );
  15631. this._multiDrawCounts = multiDrawCounts;
  15632. this._multiDrawStarts = multiDrawStarts;
  15633. this._maxInstanceCount = maxInstanceCount;
  15634. // update texture data for instance sampling
  15635. const indirectTexture = this._indirectTexture;
  15636. const matricesTexture = this._matricesTexture;
  15637. const colorsTexture = this._colorsTexture;
  15638. indirectTexture.dispose();
  15639. this._initIndirectTexture();
  15640. copyArrayContents( indirectTexture.image.data, this._indirectTexture.image.data );
  15641. matricesTexture.dispose();
  15642. this._initMatricesTexture();
  15643. copyArrayContents( matricesTexture.image.data, this._matricesTexture.image.data );
  15644. if ( colorsTexture ) {
  15645. colorsTexture.dispose();
  15646. this._initColorsTexture();
  15647. copyArrayContents( colorsTexture.image.data, this._colorsTexture.image.data );
  15648. }
  15649. }
  15650. setGeometrySize( maxVertexCount, maxIndexCount ) {
  15651. // Check if we can shrink to the requested vertex attribute size
  15652. const validRanges = [ ...this._geometryInfo ].filter( info => info.active );
  15653. const requiredVertexLength = Math.max( ...validRanges.map( range => range.vertexStart + range.reservedVertexCount ) );
  15654. if ( requiredVertexLength > maxVertexCount ) {
  15655. throw new Error( `BatchedMesh: Geometry vertex values are being used outside the range ${ maxIndexCount }. Cannot shrink further.` );
  15656. }
  15657. // Check if we can shrink to the requested index attribute size
  15658. if ( this.geometry.index ) {
  15659. const requiredIndexLength = Math.max( ...validRanges.map( range => range.indexStart + range.reservedIndexCount ) );
  15660. if ( requiredIndexLength > maxIndexCount ) {
  15661. throw new Error( `BatchedMesh: Geometry index values are being used outside the range ${ maxIndexCount }. Cannot shrink further.` );
  15662. }
  15663. }
  15664. //
  15665. // dispose of the previous geometry
  15666. const oldGeometry = this.geometry;
  15667. oldGeometry.dispose();
  15668. // recreate the geometry needed based on the previous variant
  15669. this._maxVertexCount = maxVertexCount;
  15670. this._maxIndexCount = maxIndexCount;
  15671. if ( this._geometryInitialized ) {
  15672. this._geometryInitialized = false;
  15673. this.geometry = new BufferGeometry();
  15674. this._initializeGeometry( oldGeometry );
  15675. }
  15676. // copy data from the previous geometry
  15677. const geometry = this.geometry;
  15678. if ( oldGeometry.index ) {
  15679. copyArrayContents( oldGeometry.index.array, geometry.index.array );
  15680. }
  15681. for ( const key in oldGeometry.attributes ) {
  15682. copyArrayContents( oldGeometry.attributes[ key ].array, geometry.attributes[ key ].array );
  15683. }
  15684. }
  15685. raycast( raycaster, intersects ) {
  15686. const instanceInfo = this._instanceInfo;
  15687. const geometryInfoList = this._geometryInfo;
  15688. const matrixWorld = this.matrixWorld;
  15689. const batchGeometry = this.geometry;
  15690. // iterate over each geometry
  15691. _mesh.material = this.material;
  15692. _mesh.geometry.index = batchGeometry.index;
  15693. _mesh.geometry.attributes = batchGeometry.attributes;
  15694. if ( _mesh.geometry.boundingBox === null ) {
  15695. _mesh.geometry.boundingBox = new Box3();
  15696. }
  15697. if ( _mesh.geometry.boundingSphere === null ) {
  15698. _mesh.geometry.boundingSphere = new Sphere();
  15699. }
  15700. for ( let i = 0, l = instanceInfo.length; i < l; i ++ ) {
  15701. if ( ! instanceInfo[ i ].visible || ! instanceInfo[ i ].active ) {
  15702. continue;
  15703. }
  15704. const geometryId = instanceInfo[ i ].geometryIndex;
  15705. const geometryInfo = geometryInfoList[ geometryId ];
  15706. _mesh.geometry.setDrawRange( geometryInfo.start, geometryInfo.count );
  15707. // get the intersects
  15708. this.getMatrixAt( i, _mesh.matrixWorld ).premultiply( matrixWorld );
  15709. this.getBoundingBoxAt( geometryId, _mesh.geometry.boundingBox );
  15710. this.getBoundingSphereAt( geometryId, _mesh.geometry.boundingSphere );
  15711. _mesh.raycast( raycaster, _batchIntersects );
  15712. // add batch id to the intersects
  15713. for ( let j = 0, l = _batchIntersects.length; j < l; j ++ ) {
  15714. const intersect = _batchIntersects[ j ];
  15715. intersect.object = this;
  15716. intersect.batchId = i;
  15717. intersects.push( intersect );
  15718. }
  15719. _batchIntersects.length = 0;
  15720. }
  15721. _mesh.material = null;
  15722. _mesh.geometry.index = null;
  15723. _mesh.geometry.attributes = {};
  15724. _mesh.geometry.setDrawRange( 0, Infinity );
  15725. }
  15726. copy( source ) {
  15727. super.copy( source );
  15728. this.geometry = source.geometry.clone();
  15729. this.perObjectFrustumCulled = source.perObjectFrustumCulled;
  15730. this.sortObjects = source.sortObjects;
  15731. this.boundingBox = source.boundingBox !== null ? source.boundingBox.clone() : null;
  15732. this.boundingSphere = source.boundingSphere !== null ? source.boundingSphere.clone() : null;
  15733. this._geometryInfo = source._geometryInfo.map( info => ( {
  15734. ...info,
  15735. boundingBox: info.boundingBox !== null ? info.boundingBox.clone() : null,
  15736. boundingSphere: info.boundingSphere !== null ? info.boundingSphere.clone() : null,
  15737. } ) );
  15738. this._instanceInfo = source._instanceInfo.map( info => ( { ...info } ) );
  15739. this._maxInstanceCount = source._maxInstanceCount;
  15740. this._maxVertexCount = source._maxVertexCount;
  15741. this._maxIndexCount = source._maxIndexCount;
  15742. this._geometryInitialized = source._geometryInitialized;
  15743. this._geometryCount = source._geometryCount;
  15744. this._multiDrawCounts = source._multiDrawCounts.slice();
  15745. this._multiDrawStarts = source._multiDrawStarts.slice();
  15746. this._matricesTexture = source._matricesTexture.clone();
  15747. this._matricesTexture.image.data = this._matricesTexture.image.data.slice();
  15748. if ( this._colorsTexture !== null ) {
  15749. this._colorsTexture = source._colorsTexture.clone();
  15750. this._colorsTexture.image.data = this._colorsTexture.image.data.slice();
  15751. }
  15752. return this;
  15753. }
  15754. dispose() {
  15755. // Assuming the geometry is not shared with other meshes
  15756. this.geometry.dispose();
  15757. this._matricesTexture.dispose();
  15758. this._matricesTexture = null;
  15759. this._indirectTexture.dispose();
  15760. this._indirectTexture = null;
  15761. if ( this._colorsTexture !== null ) {
  15762. this._colorsTexture.dispose();
  15763. this._colorsTexture = null;
  15764. }
  15765. return this;
  15766. }
  15767. onBeforeRender( renderer, scene, camera, geometry, material/*, _group*/ ) {
  15768. // if visibility has not changed and frustum culling and object sorting is not required
  15769. // then skip iterating over all items
  15770. if ( ! this._visibilityChanged && ! this.perObjectFrustumCulled && ! this.sortObjects ) {
  15771. return;
  15772. }
  15773. // the indexed version of the multi draw function requires specifying the start
  15774. // offset in bytes.
  15775. const index = geometry.getIndex();
  15776. const bytesPerElement = index === null ? 1 : index.array.BYTES_PER_ELEMENT;
  15777. const instanceInfo = this._instanceInfo;
  15778. const multiDrawStarts = this._multiDrawStarts;
  15779. const multiDrawCounts = this._multiDrawCounts;
  15780. const geometryInfoList = this._geometryInfo;
  15781. const perObjectFrustumCulled = this.perObjectFrustumCulled;
  15782. const indirectTexture = this._indirectTexture;
  15783. const indirectArray = indirectTexture.image.data;
  15784. // prepare the frustum in the local frame
  15785. if ( perObjectFrustumCulled ) {
  15786. _matrix$1
  15787. .multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse )
  15788. .multiply( this.matrixWorld );
  15789. _frustum.setFromProjectionMatrix(
  15790. _matrix$1,
  15791. renderer.coordinateSystem
  15792. );
  15793. }
  15794. let multiDrawCount = 0;
  15795. if ( this.sortObjects ) {
  15796. // get the camera position in the local frame
  15797. _matrix$1.copy( this.matrixWorld ).invert();
  15798. _vector$5.setFromMatrixPosition( camera.matrixWorld ).applyMatrix4( _matrix$1 );
  15799. _forward.set( 0, 0, -1 ).transformDirection( camera.matrixWorld ).transformDirection( _matrix$1 );
  15800. for ( let i = 0, l = instanceInfo.length; i < l; i ++ ) {
  15801. if ( instanceInfo[ i ].visible && instanceInfo[ i ].active ) {
  15802. const geometryId = instanceInfo[ i ].geometryIndex;
  15803. // get the bounds in world space
  15804. this.getMatrixAt( i, _matrix$1 );
  15805. this.getBoundingSphereAt( geometryId, _sphere$2 ).applyMatrix4( _matrix$1 );
  15806. // determine whether the batched geometry is within the frustum
  15807. let culled = false;
  15808. if ( perObjectFrustumCulled ) {
  15809. culled = ! _frustum.intersectsSphere( _sphere$2 );
  15810. }
  15811. if ( ! culled ) {
  15812. // get the distance from camera used for sorting
  15813. const geometryInfo = geometryInfoList[ geometryId ];
  15814. const z = _temp.subVectors( _sphere$2.center, _vector$5 ).dot( _forward );
  15815. _renderList.push( geometryInfo.start, geometryInfo.count, z, i );
  15816. }
  15817. }
  15818. }
  15819. // Sort the draw ranges and prep for rendering
  15820. const list = _renderList.list;
  15821. const customSort = this.customSort;
  15822. if ( customSort === null ) {
  15823. list.sort( material.transparent ? sortTransparent : sortOpaque );
  15824. } else {
  15825. customSort.call( this, list, camera );
  15826. }
  15827. for ( let i = 0, l = list.length; i < l; i ++ ) {
  15828. const item = list[ i ];
  15829. multiDrawStarts[ multiDrawCount ] = item.start * bytesPerElement;
  15830. multiDrawCounts[ multiDrawCount ] = item.count;
  15831. indirectArray[ multiDrawCount ] = item.index;
  15832. multiDrawCount ++;
  15833. }
  15834. _renderList.reset();
  15835. } else {
  15836. for ( let i = 0, l = instanceInfo.length; i < l; i ++ ) {
  15837. if ( instanceInfo[ i ].visible && instanceInfo[ i ].active ) {
  15838. const geometryId = instanceInfo[ i ].geometryIndex;
  15839. // determine whether the batched geometry is within the frustum
  15840. let culled = false;
  15841. if ( perObjectFrustumCulled ) {
  15842. // get the bounds in world space
  15843. this.getMatrixAt( i, _matrix$1 );
  15844. this.getBoundingSphereAt( geometryId, _sphere$2 ).applyMatrix4( _matrix$1 );
  15845. culled = ! _frustum.intersectsSphere( _sphere$2 );
  15846. }
  15847. if ( ! culled ) {
  15848. const geometryInfo = geometryInfoList[ geometryId ];
  15849. multiDrawStarts[ multiDrawCount ] = geometryInfo.start * bytesPerElement;
  15850. multiDrawCounts[ multiDrawCount ] = geometryInfo.count;
  15851. indirectArray[ multiDrawCount ] = i;
  15852. multiDrawCount ++;
  15853. }
  15854. }
  15855. }
  15856. }
  15857. indirectTexture.needsUpdate = true;
  15858. this._multiDrawCount = multiDrawCount;
  15859. this._visibilityChanged = false;
  15860. }
  15861. onBeforeShadow( renderer, object, camera, shadowCamera, geometry, depthMaterial/* , group */ ) {
  15862. this.onBeforeRender( renderer, null, shadowCamera, geometry, depthMaterial );
  15863. }
  15864. }
  15865. class LineBasicMaterial extends Material {
  15866. constructor( parameters ) {
  15867. super();
  15868. this.isLineBasicMaterial = true;
  15869. this.type = 'LineBasicMaterial';
  15870. this.color = new Color( 0xffffff );
  15871. this.map = null;
  15872. this.linewidth = 1;
  15873. this.linecap = 'round';
  15874. this.linejoin = 'round';
  15875. this.fog = true;
  15876. this.setValues( parameters );
  15877. }
  15878. copy( source ) {
  15879. super.copy( source );
  15880. this.color.copy( source.color );
  15881. this.map = source.map;
  15882. this.linewidth = source.linewidth;
  15883. this.linecap = source.linecap;
  15884. this.linejoin = source.linejoin;
  15885. this.fog = source.fog;
  15886. return this;
  15887. }
  15888. }
  15889. const _vStart = /*@__PURE__*/ new Vector3();
  15890. const _vEnd = /*@__PURE__*/ new Vector3();
  15891. const _inverseMatrix$1 = /*@__PURE__*/ new Matrix4();
  15892. const _ray$1 = /*@__PURE__*/ new Ray();
  15893. const _sphere$1 = /*@__PURE__*/ new Sphere();
  15894. const _intersectPointOnRay = /*@__PURE__*/ new Vector3();
  15895. const _intersectPointOnSegment = /*@__PURE__*/ new Vector3();
  15896. class Line extends Object3D {
  15897. constructor( geometry = new BufferGeometry(), material = new LineBasicMaterial() ) {
  15898. super();
  15899. this.isLine = true;
  15900. this.type = 'Line';
  15901. this.geometry = geometry;
  15902. this.material = material;
  15903. this.updateMorphTargets();
  15904. }
  15905. copy( source, recursive ) {
  15906. super.copy( source, recursive );
  15907. this.material = Array.isArray( source.material ) ? source.material.slice() : source.material;
  15908. this.geometry = source.geometry;
  15909. return this;
  15910. }
  15911. computeLineDistances() {
  15912. const geometry = this.geometry;
  15913. // we assume non-indexed geometry
  15914. if ( geometry.index === null ) {
  15915. const positionAttribute = geometry.attributes.position;
  15916. const lineDistances = [ 0 ];
  15917. for ( let i = 1, l = positionAttribute.count; i < l; i ++ ) {
  15918. _vStart.fromBufferAttribute( positionAttribute, i - 1 );
  15919. _vEnd.fromBufferAttribute( positionAttribute, i );
  15920. lineDistances[ i ] = lineDistances[ i - 1 ];
  15921. lineDistances[ i ] += _vStart.distanceTo( _vEnd );
  15922. }
  15923. geometry.setAttribute( 'lineDistance', new Float32BufferAttribute( lineDistances, 1 ) );
  15924. } else {
  15925. console.warn( 'THREE.Line.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.' );
  15926. }
  15927. return this;
  15928. }
  15929. raycast( raycaster, intersects ) {
  15930. const geometry = this.geometry;
  15931. const matrixWorld = this.matrixWorld;
  15932. const threshold = raycaster.params.Line.threshold;
  15933. const drawRange = geometry.drawRange;
  15934. // Checking boundingSphere distance to ray
  15935. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  15936. _sphere$1.copy( geometry.boundingSphere );
  15937. _sphere$1.applyMatrix4( matrixWorld );
  15938. _sphere$1.radius += threshold;
  15939. if ( raycaster.ray.intersectsSphere( _sphere$1 ) === false ) return;
  15940. //
  15941. _inverseMatrix$1.copy( matrixWorld ).invert();
  15942. _ray$1.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$1 );
  15943. const localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 );
  15944. const localThresholdSq = localThreshold * localThreshold;
  15945. const step = this.isLineSegments ? 2 : 1;
  15946. const index = geometry.index;
  15947. const attributes = geometry.attributes;
  15948. const positionAttribute = attributes.position;
  15949. if ( index !== null ) {
  15950. const start = Math.max( 0, drawRange.start );
  15951. const end = Math.min( index.count, ( drawRange.start + drawRange.count ) );
  15952. for ( let i = start, l = end - 1; i < l; i += step ) {
  15953. const a = index.getX( i );
  15954. const b = index.getX( i + 1 );
  15955. const intersect = checkIntersection( this, raycaster, _ray$1, localThresholdSq, a, b, i );
  15956. if ( intersect ) {
  15957. intersects.push( intersect );
  15958. }
  15959. }
  15960. if ( this.isLineLoop ) {
  15961. const a = index.getX( end - 1 );
  15962. const b = index.getX( start );
  15963. const intersect = checkIntersection( this, raycaster, _ray$1, localThresholdSq, a, b, end - 1 );
  15964. if ( intersect ) {
  15965. intersects.push( intersect );
  15966. }
  15967. }
  15968. } else {
  15969. const start = Math.max( 0, drawRange.start );
  15970. const end = Math.min( positionAttribute.count, ( drawRange.start + drawRange.count ) );
  15971. for ( let i = start, l = end - 1; i < l; i += step ) {
  15972. const intersect = checkIntersection( this, raycaster, _ray$1, localThresholdSq, i, i + 1, i );
  15973. if ( intersect ) {
  15974. intersects.push( intersect );
  15975. }
  15976. }
  15977. if ( this.isLineLoop ) {
  15978. const intersect = checkIntersection( this, raycaster, _ray$1, localThresholdSq, end - 1, start, end - 1 );
  15979. if ( intersect ) {
  15980. intersects.push( intersect );
  15981. }
  15982. }
  15983. }
  15984. }
  15985. updateMorphTargets() {
  15986. const geometry = this.geometry;
  15987. const morphAttributes = geometry.morphAttributes;
  15988. const keys = Object.keys( morphAttributes );
  15989. if ( keys.length > 0 ) {
  15990. const morphAttribute = morphAttributes[ keys[ 0 ] ];
  15991. if ( morphAttribute !== undefined ) {
  15992. this.morphTargetInfluences = [];
  15993. this.morphTargetDictionary = {};
  15994. for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  15995. const name = morphAttribute[ m ].name || String( m );
  15996. this.morphTargetInfluences.push( 0 );
  15997. this.morphTargetDictionary[ name ] = m;
  15998. }
  15999. }
  16000. }
  16001. }
  16002. }
  16003. function checkIntersection( object, raycaster, ray, thresholdSq, a, b, i ) {
  16004. const positionAttribute = object.geometry.attributes.position;
  16005. _vStart.fromBufferAttribute( positionAttribute, a );
  16006. _vEnd.fromBufferAttribute( positionAttribute, b );
  16007. const distSq = ray.distanceSqToSegment( _vStart, _vEnd, _intersectPointOnRay, _intersectPointOnSegment );
  16008. if ( distSq > thresholdSq ) return;
  16009. _intersectPointOnRay.applyMatrix4( object.matrixWorld ); // Move back to world space for distance calculation
  16010. const distance = raycaster.ray.origin.distanceTo( _intersectPointOnRay );
  16011. if ( distance < raycaster.near || distance > raycaster.far ) return;
  16012. return {
  16013. distance: distance,
  16014. // What do we want? intersection point on the ray or on the segment??
  16015. // point: raycaster.ray.at( distance ),
  16016. point: _intersectPointOnSegment.clone().applyMatrix4( object.matrixWorld ),
  16017. index: i,
  16018. face: null,
  16019. faceIndex: null,
  16020. barycoord: null,
  16021. object: object
  16022. };
  16023. }
  16024. const _start = /*@__PURE__*/ new Vector3();
  16025. const _end = /*@__PURE__*/ new Vector3();
  16026. class LineSegments extends Line {
  16027. constructor( geometry, material ) {
  16028. super( geometry, material );
  16029. this.isLineSegments = true;
  16030. this.type = 'LineSegments';
  16031. }
  16032. computeLineDistances() {
  16033. const geometry = this.geometry;
  16034. // we assume non-indexed geometry
  16035. if ( geometry.index === null ) {
  16036. const positionAttribute = geometry.attributes.position;
  16037. const lineDistances = [];
  16038. for ( let i = 0, l = positionAttribute.count; i < l; i += 2 ) {
  16039. _start.fromBufferAttribute( positionAttribute, i );
  16040. _end.fromBufferAttribute( positionAttribute, i + 1 );
  16041. lineDistances[ i ] = ( i === 0 ) ? 0 : lineDistances[ i - 1 ];
  16042. lineDistances[ i + 1 ] = lineDistances[ i ] + _start.distanceTo( _end );
  16043. }
  16044. geometry.setAttribute( 'lineDistance', new Float32BufferAttribute( lineDistances, 1 ) );
  16045. } else {
  16046. console.warn( 'THREE.LineSegments.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.' );
  16047. }
  16048. return this;
  16049. }
  16050. }
  16051. class LineLoop extends Line {
  16052. constructor( geometry, material ) {
  16053. super( geometry, material );
  16054. this.isLineLoop = true;
  16055. this.type = 'LineLoop';
  16056. }
  16057. }
  16058. class PointsMaterial extends Material {
  16059. constructor( parameters ) {
  16060. super();
  16061. this.isPointsMaterial = true;
  16062. this.type = 'PointsMaterial';
  16063. this.color = new Color( 0xffffff );
  16064. this.map = null;
  16065. this.alphaMap = null;
  16066. this.size = 1;
  16067. this.sizeAttenuation = true;
  16068. this.fog = true;
  16069. this.setValues( parameters );
  16070. }
  16071. copy( source ) {
  16072. super.copy( source );
  16073. this.color.copy( source.color );
  16074. this.map = source.map;
  16075. this.alphaMap = source.alphaMap;
  16076. this.size = source.size;
  16077. this.sizeAttenuation = source.sizeAttenuation;
  16078. this.fog = source.fog;
  16079. return this;
  16080. }
  16081. }
  16082. const _inverseMatrix = /*@__PURE__*/ new Matrix4();
  16083. const _ray = /*@__PURE__*/ new Ray();
  16084. const _sphere = /*@__PURE__*/ new Sphere();
  16085. const _position$2 = /*@__PURE__*/ new Vector3();
  16086. class Points extends Object3D {
  16087. constructor( geometry = new BufferGeometry(), material = new PointsMaterial() ) {
  16088. super();
  16089. this.isPoints = true;
  16090. this.type = 'Points';
  16091. this.geometry = geometry;
  16092. this.material = material;
  16093. this.updateMorphTargets();
  16094. }
  16095. copy( source, recursive ) {
  16096. super.copy( source, recursive );
  16097. this.material = Array.isArray( source.material ) ? source.material.slice() : source.material;
  16098. this.geometry = source.geometry;
  16099. return this;
  16100. }
  16101. raycast( raycaster, intersects ) {
  16102. const geometry = this.geometry;
  16103. const matrixWorld = this.matrixWorld;
  16104. const threshold = raycaster.params.Points.threshold;
  16105. const drawRange = geometry.drawRange;
  16106. // Checking boundingSphere distance to ray
  16107. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  16108. _sphere.copy( geometry.boundingSphere );
  16109. _sphere.applyMatrix4( matrixWorld );
  16110. _sphere.radius += threshold;
  16111. if ( raycaster.ray.intersectsSphere( _sphere ) === false ) return;
  16112. //
  16113. _inverseMatrix.copy( matrixWorld ).invert();
  16114. _ray.copy( raycaster.ray ).applyMatrix4( _inverseMatrix );
  16115. const localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 );
  16116. const localThresholdSq = localThreshold * localThreshold;
  16117. const index = geometry.index;
  16118. const attributes = geometry.attributes;
  16119. const positionAttribute = attributes.position;
  16120. if ( index !== null ) {
  16121. const start = Math.max( 0, drawRange.start );
  16122. const end = Math.min( index.count, ( drawRange.start + drawRange.count ) );
  16123. for ( let i = start, il = end; i < il; i ++ ) {
  16124. const a = index.getX( i );
  16125. _position$2.fromBufferAttribute( positionAttribute, a );
  16126. testPoint( _position$2, a, localThresholdSq, matrixWorld, raycaster, intersects, this );
  16127. }
  16128. } else {
  16129. const start = Math.max( 0, drawRange.start );
  16130. const end = Math.min( positionAttribute.count, ( drawRange.start + drawRange.count ) );
  16131. for ( let i = start, l = end; i < l; i ++ ) {
  16132. _position$2.fromBufferAttribute( positionAttribute, i );
  16133. testPoint( _position$2, i, localThresholdSq, matrixWorld, raycaster, intersects, this );
  16134. }
  16135. }
  16136. }
  16137. updateMorphTargets() {
  16138. const geometry = this.geometry;
  16139. const morphAttributes = geometry.morphAttributes;
  16140. const keys = Object.keys( morphAttributes );
  16141. if ( keys.length > 0 ) {
  16142. const morphAttribute = morphAttributes[ keys[ 0 ] ];
  16143. if ( morphAttribute !== undefined ) {
  16144. this.morphTargetInfluences = [];
  16145. this.morphTargetDictionary = {};
  16146. for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  16147. const name = morphAttribute[ m ].name || String( m );
  16148. this.morphTargetInfluences.push( 0 );
  16149. this.morphTargetDictionary[ name ] = m;
  16150. }
  16151. }
  16152. }
  16153. }
  16154. }
  16155. function testPoint( point, index, localThresholdSq, matrixWorld, raycaster, intersects, object ) {
  16156. const rayPointDistanceSq = _ray.distanceSqToPoint( point );
  16157. if ( rayPointDistanceSq < localThresholdSq ) {
  16158. const intersectPoint = new Vector3();
  16159. _ray.closestPointToPoint( point, intersectPoint );
  16160. intersectPoint.applyMatrix4( matrixWorld );
  16161. const distance = raycaster.ray.origin.distanceTo( intersectPoint );
  16162. if ( distance < raycaster.near || distance > raycaster.far ) return;
  16163. intersects.push( {
  16164. distance: distance,
  16165. distanceToRay: Math.sqrt( rayPointDistanceSq ),
  16166. point: intersectPoint,
  16167. index: index,
  16168. face: null,
  16169. faceIndex: null,
  16170. barycoord: null,
  16171. object: object
  16172. } );
  16173. }
  16174. }
  16175. class VideoTexture extends Texture {
  16176. constructor( video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  16177. super( video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  16178. this.isVideoTexture = true;
  16179. this.minFilter = minFilter !== undefined ? minFilter : LinearFilter;
  16180. this.magFilter = magFilter !== undefined ? magFilter : LinearFilter;
  16181. this.generateMipmaps = false;
  16182. const scope = this;
  16183. function updateVideo() {
  16184. scope.needsUpdate = true;
  16185. video.requestVideoFrameCallback( updateVideo );
  16186. }
  16187. if ( 'requestVideoFrameCallback' in video ) {
  16188. video.requestVideoFrameCallback( updateVideo );
  16189. }
  16190. }
  16191. clone() {
  16192. return new this.constructor( this.image ).copy( this );
  16193. }
  16194. update() {
  16195. const video = this.image;
  16196. const hasVideoFrameCallback = 'requestVideoFrameCallback' in video;
  16197. if ( hasVideoFrameCallback === false && video.readyState >= video.HAVE_CURRENT_DATA ) {
  16198. this.needsUpdate = true;
  16199. }
  16200. }
  16201. }
  16202. class VideoFrameTexture extends VideoTexture {
  16203. constructor( mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  16204. super( {}, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  16205. this.isVideoFrameTexture = true;
  16206. }
  16207. update() {
  16208. // overwrites `VideoTexture.update()` with an empty method since
  16209. // this type of texture is updated via `setFrame()`.
  16210. }
  16211. clone() {
  16212. return new this.constructor().copy( this ); // restoring Texture.clone()
  16213. }
  16214. setFrame( frame ) {
  16215. this.image = frame;
  16216. this.needsUpdate = true;
  16217. }
  16218. }
  16219. class FramebufferTexture extends Texture {
  16220. constructor( width, height ) {
  16221. super( { width, height } );
  16222. this.isFramebufferTexture = true;
  16223. this.magFilter = NearestFilter;
  16224. this.minFilter = NearestFilter;
  16225. this.generateMipmaps = false;
  16226. this.needsUpdate = true;
  16227. }
  16228. }
  16229. class CompressedTexture extends Texture {
  16230. constructor( mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, colorSpace ) {
  16231. super( null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace );
  16232. this.isCompressedTexture = true;
  16233. this.image = { width: width, height: height };
  16234. this.mipmaps = mipmaps;
  16235. // no flipping for cube textures
  16236. // (also flipping doesn't work for compressed textures )
  16237. this.flipY = false;
  16238. // can't generate mipmaps for compressed textures
  16239. // mips must be embedded in DDS files
  16240. this.generateMipmaps = false;
  16241. }
  16242. }
  16243. class CompressedArrayTexture extends CompressedTexture {
  16244. constructor( mipmaps, width, height, depth, format, type ) {
  16245. super( mipmaps, width, height, format, type );
  16246. this.isCompressedArrayTexture = true;
  16247. this.image.depth = depth;
  16248. this.wrapR = ClampToEdgeWrapping;
  16249. this.layerUpdates = new Set();
  16250. }
  16251. addLayerUpdate( layerIndex ) {
  16252. this.layerUpdates.add( layerIndex );
  16253. }
  16254. clearLayerUpdates() {
  16255. this.layerUpdates.clear();
  16256. }
  16257. }
  16258. class CompressedCubeTexture extends CompressedTexture {
  16259. constructor( images, format, type ) {
  16260. super( undefined, images[ 0 ].width, images[ 0 ].height, format, type, CubeReflectionMapping );
  16261. this.isCompressedCubeTexture = true;
  16262. this.isCubeTexture = true;
  16263. this.image = images;
  16264. }
  16265. }
  16266. class CanvasTexture extends Texture {
  16267. constructor( canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  16268. super( canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  16269. this.isCanvasTexture = true;
  16270. this.needsUpdate = true;
  16271. }
  16272. }
  16273. class DepthTexture extends Texture {
  16274. constructor( width, height, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, format = DepthFormat ) {
  16275. if ( format !== DepthFormat && format !== DepthStencilFormat ) {
  16276. throw new Error( 'DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat' );
  16277. }
  16278. if ( type === undefined && format === DepthFormat ) type = UnsignedIntType;
  16279. if ( type === undefined && format === DepthStencilFormat ) type = UnsignedInt248Type;
  16280. super( null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  16281. this.isDepthTexture = true;
  16282. this.image = { width: width, height: height };
  16283. this.magFilter = magFilter !== undefined ? magFilter : NearestFilter;
  16284. this.minFilter = minFilter !== undefined ? minFilter : NearestFilter;
  16285. this.flipY = false;
  16286. this.generateMipmaps = false;
  16287. this.compareFunction = null;
  16288. }
  16289. copy( source ) {
  16290. super.copy( source );
  16291. this.source = new Source( Object.assign( {}, source.image ) ); // see #30540
  16292. this.compareFunction = source.compareFunction;
  16293. return this;
  16294. }
  16295. toJSON( meta ) {
  16296. const data = super.toJSON( meta );
  16297. if ( this.compareFunction !== null ) data.compareFunction = this.compareFunction;
  16298. return data;
  16299. }
  16300. }
  16301. /**
  16302. * An abstract base class for creating an analytic curve object that contains methods
  16303. * for interpolation.
  16304. *
  16305. * @abstract
  16306. */
  16307. class Curve {
  16308. /**
  16309. * Constructs a new curve.
  16310. */
  16311. constructor() {
  16312. /**
  16313. * The type property is used for detecting the object type
  16314. * in context of serialization/deserialization.
  16315. *
  16316. * @type {string}
  16317. * @readonly
  16318. */
  16319. this.type = 'Curve';
  16320. /**
  16321. * This value determines the amount of divisions when calculating the
  16322. * cumulative segment lengths of a curve via {@link Curve#getLengths}. To ensure
  16323. * precision when using methods like {@link Curve#getSpacedPoints}, it is
  16324. * recommended to increase the value of this property if the curve is very large.
  16325. *
  16326. * @type {number}
  16327. * @default 200
  16328. */
  16329. this.arcLengthDivisions = 200;
  16330. /**
  16331. * Must be set to `true` if the curve parameters have changed.
  16332. *
  16333. * @type {boolean}
  16334. * @default false
  16335. */
  16336. this.needsUpdate = false;
  16337. /**
  16338. * An internal cache that holds precomputed curve length values.
  16339. *
  16340. * @private
  16341. * @type {?Array<number>}
  16342. * @default null
  16343. */
  16344. this.cacheArcLengths = null;
  16345. }
  16346. /**
  16347. * This method returns a vector in 2D or 3D space (depending on the curve definition)
  16348. * for the given interpolation factor.
  16349. *
  16350. * @abstract
  16351. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  16352. * @param {(Vector2|Vector3)} [optionalTarget] - The optional target vector the result is written to.
  16353. * @return {?(Vector2|Vector3)} The position on the curve. It can be a 2D or 3D vector depending on the curve definition.
  16354. */
  16355. getPoint( /* t, optionalTarget */ ) {
  16356. console.warn( 'THREE.Curve: .getPoint() not implemented.' );
  16357. }
  16358. /**
  16359. * This method returns a vector in 2D or 3D space (depending on the curve definition)
  16360. * for the given interpolation factor. Unlike {@link Curve#getPoint}, this method honors the length
  16361. * of the curve which equidistant samples.
  16362. *
  16363. * @param {number} u - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  16364. * @param {(Vector2|Vector3)} [optionalTarget] - The optional target vector the result is written to.
  16365. * @return {(Vector2|Vector3)} The position on the curve. It can be a 2D or 3D vector depending on the curve definition.
  16366. */
  16367. getPointAt( u, optionalTarget ) {
  16368. const t = this.getUtoTmapping( u );
  16369. return this.getPoint( t, optionalTarget );
  16370. }
  16371. /**
  16372. * This method samples the curve via {@link Curve#getPoint} and returns an array of points representing
  16373. * the curve shape.
  16374. *
  16375. * @param {number} [divisions=5] - The number of divisions.
  16376. * @return {Array<(Vector2|Vector3)>} An array holding the sampled curve values. The number of points is `divisions + 1`.
  16377. */
  16378. getPoints( divisions = 5 ) {
  16379. const points = [];
  16380. for ( let d = 0; d <= divisions; d ++ ) {
  16381. points.push( this.getPoint( d / divisions ) );
  16382. }
  16383. return points;
  16384. }
  16385. // Get sequence of points using getPointAt( u )
  16386. /**
  16387. * This method samples the curve via {@link Curve#getPointAt} and returns an array of points representing
  16388. * the curve shape. Unlike {@link Curve#getPoints}, this method returns equi-spaced points across the entire
  16389. * curve.
  16390. *
  16391. * @param {number} [divisions=5] - The number of divisions.
  16392. * @return {Array<(Vector2|Vector3)>} An array holding the sampled curve values. The number of points is `divisions + 1`.
  16393. */
  16394. getSpacedPoints( divisions = 5 ) {
  16395. const points = [];
  16396. for ( let d = 0; d <= divisions; d ++ ) {
  16397. points.push( this.getPointAt( d / divisions ) );
  16398. }
  16399. return points;
  16400. }
  16401. /**
  16402. * Returns the total arc length of the curve.
  16403. *
  16404. * @return {number} The length of the curve.
  16405. */
  16406. getLength() {
  16407. const lengths = this.getLengths();
  16408. return lengths[ lengths.length - 1 ];
  16409. }
  16410. /**
  16411. * Returns an array of cumulative segment lengths of the curve.
  16412. *
  16413. * @param {number} [divisions=this.arcLengthDivisions] - The number of divisions.
  16414. * @return {Array<number>} An array holding the cumulative segment lengths.
  16415. */
  16416. getLengths( divisions = this.arcLengthDivisions ) {
  16417. if ( this.cacheArcLengths &&
  16418. ( this.cacheArcLengths.length === divisions + 1 ) &&
  16419. ! this.needsUpdate ) {
  16420. return this.cacheArcLengths;
  16421. }
  16422. this.needsUpdate = false;
  16423. const cache = [];
  16424. let current, last = this.getPoint( 0 );
  16425. let sum = 0;
  16426. cache.push( 0 );
  16427. for ( let p = 1; p <= divisions; p ++ ) {
  16428. current = this.getPoint( p / divisions );
  16429. sum += current.distanceTo( last );
  16430. cache.push( sum );
  16431. last = current;
  16432. }
  16433. this.cacheArcLengths = cache;
  16434. return cache; // { sums: cache, sum: sum }; Sum is in the last element.
  16435. }
  16436. /**
  16437. * Update the cumulative segment distance cache. The method must be called
  16438. * every time curve parameters are changed. If an updated curve is part of a
  16439. * composed curve like {@link CurvePath}, this method must be called on the
  16440. * composed curve, too.
  16441. */
  16442. updateArcLengths() {
  16443. this.needsUpdate = true;
  16444. this.getLengths();
  16445. }
  16446. /**
  16447. * Given an interpolation factor in the range `[0,1]`, this method returns an updated
  16448. * interpolation factor in the same range that can be ued to sample equidistant points
  16449. * from a curve.
  16450. *
  16451. * @param {number} u - The interpolation factor.
  16452. * @param {?number} distance - An optional distance on the curve.
  16453. * @return {number} The updated interpolation factor.
  16454. */
  16455. getUtoTmapping( u, distance = null ) {
  16456. const arcLengths = this.getLengths();
  16457. let i = 0;
  16458. const il = arcLengths.length;
  16459. let targetArcLength; // The targeted u distance value to get
  16460. if ( distance ) {
  16461. targetArcLength = distance;
  16462. } else {
  16463. targetArcLength = u * arcLengths[ il - 1 ];
  16464. }
  16465. // binary search for the index with largest value smaller than target u distance
  16466. let low = 0, high = il - 1, comparison;
  16467. while ( low <= high ) {
  16468. 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
  16469. comparison = arcLengths[ i ] - targetArcLength;
  16470. if ( comparison < 0 ) {
  16471. low = i + 1;
  16472. } else if ( comparison > 0 ) {
  16473. high = i - 1;
  16474. } else {
  16475. high = i;
  16476. break;
  16477. // DONE
  16478. }
  16479. }
  16480. i = high;
  16481. if ( arcLengths[ i ] === targetArcLength ) {
  16482. return i / ( il - 1 );
  16483. }
  16484. // we could get finer grain at lengths, or use simple interpolation between two points
  16485. const lengthBefore = arcLengths[ i ];
  16486. const lengthAfter = arcLengths[ i + 1 ];
  16487. const segmentLength = lengthAfter - lengthBefore;
  16488. // determine where we are between the 'before' and 'after' points
  16489. const segmentFraction = ( targetArcLength - lengthBefore ) / segmentLength;
  16490. // add that fractional amount to t
  16491. const t = ( i + segmentFraction ) / ( il - 1 );
  16492. return t;
  16493. }
  16494. /**
  16495. * Returns a unit vector tangent for the given interpolation factor.
  16496. * If the derived curve does not implement its tangent derivation,
  16497. * two points a small delta apart will be used to find its gradient
  16498. * which seems to give a reasonable approximation.
  16499. *
  16500. * @param {number} t - The interpolation factor.
  16501. * @param {(Vector2|Vector3)} [optionalTarget] - The optional target vector the result is written to.
  16502. * @return {(Vector2|Vector3)} The tagent vector.
  16503. */
  16504. getTangent( t, optionalTarget ) {
  16505. const delta = 0.0001;
  16506. let t1 = t - delta;
  16507. let t2 = t + delta;
  16508. // Capping in case of danger
  16509. if ( t1 < 0 ) t1 = 0;
  16510. if ( t2 > 1 ) t2 = 1;
  16511. const pt1 = this.getPoint( t1 );
  16512. const pt2 = this.getPoint( t2 );
  16513. const tangent = optionalTarget || ( ( pt1.isVector2 ) ? new Vector2() : new Vector3() );
  16514. tangent.copy( pt2 ).sub( pt1 ).normalize();
  16515. return tangent;
  16516. }
  16517. /**
  16518. * Same as {@link Curve#getTangent} but with equidistant samples.
  16519. *
  16520. * @param {number} u - The interpolation factor.
  16521. * @param {(Vector2|Vector3)} [optionalTarget] - The optional target vector the result is written to.
  16522. * @return {(Vector2|Vector3)} The tagent vector.
  16523. * @see {@link Curve#getPointAt}
  16524. */
  16525. getTangentAt( u, optionalTarget ) {
  16526. const t = this.getUtoTmapping( u );
  16527. return this.getTangent( t, optionalTarget );
  16528. }
  16529. /**
  16530. * Generates the Frenet Frames. Requires a curve definition in 3D space. Used
  16531. * in geometries like {@link TubeGeometry} or {@link ExtrudeGeometry}.
  16532. *
  16533. * @param {number} segments - The number of segments.
  16534. * @param {boolean} [closed=false] - Whether the curve is closed or not.
  16535. * @return {{tangents: Array<Vector3>, normals: Array<Vector3>, binormals: Array<Vector3>}} The Frenet Frames.
  16536. */
  16537. computeFrenetFrames( segments, closed = false ) {
  16538. // see http://www.cs.indiana.edu/pub/techreports/TR425.pdf
  16539. const normal = new Vector3();
  16540. const tangents = [];
  16541. const normals = [];
  16542. const binormals = [];
  16543. const vec = new Vector3();
  16544. const mat = new Matrix4();
  16545. // compute the tangent vectors for each segment on the curve
  16546. for ( let i = 0; i <= segments; i ++ ) {
  16547. const u = i / segments;
  16548. tangents[ i ] = this.getTangentAt( u, new Vector3() );
  16549. }
  16550. // select an initial normal vector perpendicular to the first tangent vector,
  16551. // and in the direction of the minimum tangent xyz component
  16552. normals[ 0 ] = new Vector3();
  16553. binormals[ 0 ] = new Vector3();
  16554. let min = Number.MAX_VALUE;
  16555. const tx = Math.abs( tangents[ 0 ].x );
  16556. const ty = Math.abs( tangents[ 0 ].y );
  16557. const tz = Math.abs( tangents[ 0 ].z );
  16558. if ( tx <= min ) {
  16559. min = tx;
  16560. normal.set( 1, 0, 0 );
  16561. }
  16562. if ( ty <= min ) {
  16563. min = ty;
  16564. normal.set( 0, 1, 0 );
  16565. }
  16566. if ( tz <= min ) {
  16567. normal.set( 0, 0, 1 );
  16568. }
  16569. vec.crossVectors( tangents[ 0 ], normal ).normalize();
  16570. normals[ 0 ].crossVectors( tangents[ 0 ], vec );
  16571. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] );
  16572. // compute the slowly-varying normal and binormal vectors for each segment on the curve
  16573. for ( let i = 1; i <= segments; i ++ ) {
  16574. normals[ i ] = normals[ i - 1 ].clone();
  16575. binormals[ i ] = binormals[ i - 1 ].clone();
  16576. vec.crossVectors( tangents[ i - 1 ], tangents[ i ] );
  16577. if ( vec.length() > Number.EPSILON ) {
  16578. vec.normalize();
  16579. const theta = Math.acos( clamp( tangents[ i - 1 ].dot( tangents[ i ] ), -1, 1 ) ); // clamp for floating pt errors
  16580. normals[ i ].applyMatrix4( mat.makeRotationAxis( vec, theta ) );
  16581. }
  16582. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  16583. }
  16584. // if the curve is closed, postprocess the vectors so the first and last normal vectors are the same
  16585. if ( closed === true ) {
  16586. let theta = Math.acos( clamp( normals[ 0 ].dot( normals[ segments ] ), -1, 1 ) );
  16587. theta /= segments;
  16588. if ( tangents[ 0 ].dot( vec.crossVectors( normals[ 0 ], normals[ segments ] ) ) > 0 ) {
  16589. theta = - theta;
  16590. }
  16591. for ( let i = 1; i <= segments; i ++ ) {
  16592. // twist a little...
  16593. normals[ i ].applyMatrix4( mat.makeRotationAxis( tangents[ i ], theta * i ) );
  16594. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  16595. }
  16596. }
  16597. return {
  16598. tangents: tangents,
  16599. normals: normals,
  16600. binormals: binormals
  16601. };
  16602. }
  16603. /**
  16604. * Returns a new curve with copied values from this instance.
  16605. *
  16606. * @return {Curve} A clone of this instance.
  16607. */
  16608. clone() {
  16609. return new this.constructor().copy( this );
  16610. }
  16611. /**
  16612. * Copies the values of the given curve to this instance.
  16613. *
  16614. * @param {Curve} source - The curve to copy.
  16615. * @return {Curve} A reference to this curve.
  16616. */
  16617. copy( source ) {
  16618. this.arcLengthDivisions = source.arcLengthDivisions;
  16619. return this;
  16620. }
  16621. /**
  16622. * Serializes the curve into JSON.
  16623. *
  16624. * @return {Object} A JSON object representing the serialized curve.
  16625. * @see {@link ObjectLoader#parse}
  16626. */
  16627. toJSON() {
  16628. const data = {
  16629. metadata: {
  16630. version: 4.6,
  16631. type: 'Curve',
  16632. generator: 'Curve.toJSON'
  16633. }
  16634. };
  16635. data.arcLengthDivisions = this.arcLengthDivisions;
  16636. data.type = this.type;
  16637. return data;
  16638. }
  16639. /**
  16640. * Deserializes the curve from the given JSON.
  16641. *
  16642. * @param {Object} json - The JSON holding the serialized curve.
  16643. * @return {Curve} A reference to this curve.
  16644. */
  16645. fromJSON( json ) {
  16646. this.arcLengthDivisions = json.arcLengthDivisions;
  16647. return this;
  16648. }
  16649. }
  16650. /**
  16651. * A curve representing an ellipse.
  16652. *
  16653. * ```js
  16654. * const curve = new THREE.EllipseCurve(
  16655. * 0, 0,
  16656. * 10, 10,
  16657. * 0, 2 * Math.PI,
  16658. * false,
  16659. * 0
  16660. * );
  16661. *
  16662. * const points = curve.getPoints( 50 );
  16663. * const geometry = new THREE.BufferGeometry().setFromPoints( points );
  16664. *
  16665. * const material = new THREE.LineBasicMaterial( { color: 0xff0000 } );
  16666. *
  16667. * // Create the final object to add to the scene
  16668. * const ellipse = new THREE.Line( geometry, material );
  16669. * ```
  16670. *
  16671. * @augments Curve
  16672. */
  16673. class EllipseCurve extends Curve {
  16674. /**
  16675. * Constructs a new ellipse curve.
  16676. *
  16677. * @param {number} [aX=0] - The X center of the ellipse.
  16678. * @param {number} [aY=0] - The Y center of the ellipse.
  16679. * @param {number} [xRadius=1] - The radius of the ellipse in the x direction.
  16680. * @param {number} [yRadius=1] - The radius of the ellipse in the y direction.
  16681. * @param {number} [aStartAngle=0] - The start angle of the curve in radians starting from the positive X axis.
  16682. * @param {number} [aEndAngle=Math.PI*2] - The end angle of the curve in radians starting from the positive X axis.
  16683. * @param {boolean} [aClockwise=false] - Whether the ellipse is drawn clockwise or not.
  16684. * @param {number} [aRotation=0] - The rotation angle of the ellipse in radians, counterclockwise from the positive X axis.
  16685. */
  16686. constructor( aX = 0, aY = 0, xRadius = 1, yRadius = 1, aStartAngle = 0, aEndAngle = Math.PI * 2, aClockwise = false, aRotation = 0 ) {
  16687. super();
  16688. /**
  16689. * This flag can be used for type testing.
  16690. *
  16691. * @type {boolean}
  16692. * @readonly
  16693. * @default true
  16694. */
  16695. this.isEllipseCurve = true;
  16696. this.type = 'EllipseCurve';
  16697. /**
  16698. * The X center of the ellipse.
  16699. *
  16700. * @type {number}
  16701. * @default 0
  16702. */
  16703. this.aX = aX;
  16704. /**
  16705. * The Y center of the ellipse.
  16706. *
  16707. * @type {number}
  16708. * @default 0
  16709. */
  16710. this.aY = aY;
  16711. /**
  16712. * The radius of the ellipse in the x direction.
  16713. * Setting the this value equal to the {@link EllipseCurve#yRadius} will result in a circle.
  16714. *
  16715. * @type {number}
  16716. * @default 1
  16717. */
  16718. this.xRadius = xRadius;
  16719. /**
  16720. * The radius of the ellipse in the y direction.
  16721. * Setting the this value equal to the {@link EllipseCurve#xRadius} will result in a circle.
  16722. *
  16723. * @type {number}
  16724. * @default 1
  16725. */
  16726. this.yRadius = yRadius;
  16727. /**
  16728. * The start angle of the curve in radians starting from the positive X axis.
  16729. *
  16730. * @type {number}
  16731. * @default 0
  16732. */
  16733. this.aStartAngle = aStartAngle;
  16734. /**
  16735. * The end angle of the curve in radians starting from the positive X axis.
  16736. *
  16737. * @type {number}
  16738. * @default Math.PI*2
  16739. */
  16740. this.aEndAngle = aEndAngle;
  16741. /**
  16742. * Whether the ellipse is drawn clockwise or not.
  16743. *
  16744. * @type {boolean}
  16745. * @default false
  16746. */
  16747. this.aClockwise = aClockwise;
  16748. /**
  16749. * The rotation angle of the ellipse in radians, counterclockwise from the positive X axis.
  16750. *
  16751. * @type {number}
  16752. * @default 0
  16753. */
  16754. this.aRotation = aRotation;
  16755. }
  16756. /**
  16757. * Returns a point on the curve.
  16758. *
  16759. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  16760. * @param {Vector2} [optionalTarget] - The optional target vector the result is written to.
  16761. * @return {Vector2} The position on the curve.
  16762. */
  16763. getPoint( t, optionalTarget = new Vector2() ) {
  16764. const point = optionalTarget;
  16765. const twoPi = Math.PI * 2;
  16766. let deltaAngle = this.aEndAngle - this.aStartAngle;
  16767. const samePoints = Math.abs( deltaAngle ) < Number.EPSILON;
  16768. // ensures that deltaAngle is 0 .. 2 PI
  16769. while ( deltaAngle < 0 ) deltaAngle += twoPi;
  16770. while ( deltaAngle > twoPi ) deltaAngle -= twoPi;
  16771. if ( deltaAngle < Number.EPSILON ) {
  16772. if ( samePoints ) {
  16773. deltaAngle = 0;
  16774. } else {
  16775. deltaAngle = twoPi;
  16776. }
  16777. }
  16778. if ( this.aClockwise === true && ! samePoints ) {
  16779. if ( deltaAngle === twoPi ) {
  16780. deltaAngle = - twoPi;
  16781. } else {
  16782. deltaAngle = deltaAngle - twoPi;
  16783. }
  16784. }
  16785. const angle = this.aStartAngle + t * deltaAngle;
  16786. let x = this.aX + this.xRadius * Math.cos( angle );
  16787. let y = this.aY + this.yRadius * Math.sin( angle );
  16788. if ( this.aRotation !== 0 ) {
  16789. const cos = Math.cos( this.aRotation );
  16790. const sin = Math.sin( this.aRotation );
  16791. const tx = x - this.aX;
  16792. const ty = y - this.aY;
  16793. // Rotate the point about the center of the ellipse.
  16794. x = tx * cos - ty * sin + this.aX;
  16795. y = tx * sin + ty * cos + this.aY;
  16796. }
  16797. return point.set( x, y );
  16798. }
  16799. copy( source ) {
  16800. super.copy( source );
  16801. this.aX = source.aX;
  16802. this.aY = source.aY;
  16803. this.xRadius = source.xRadius;
  16804. this.yRadius = source.yRadius;
  16805. this.aStartAngle = source.aStartAngle;
  16806. this.aEndAngle = source.aEndAngle;
  16807. this.aClockwise = source.aClockwise;
  16808. this.aRotation = source.aRotation;
  16809. return this;
  16810. }
  16811. toJSON() {
  16812. const data = super.toJSON();
  16813. data.aX = this.aX;
  16814. data.aY = this.aY;
  16815. data.xRadius = this.xRadius;
  16816. data.yRadius = this.yRadius;
  16817. data.aStartAngle = this.aStartAngle;
  16818. data.aEndAngle = this.aEndAngle;
  16819. data.aClockwise = this.aClockwise;
  16820. data.aRotation = this.aRotation;
  16821. return data;
  16822. }
  16823. fromJSON( json ) {
  16824. super.fromJSON( json );
  16825. this.aX = json.aX;
  16826. this.aY = json.aY;
  16827. this.xRadius = json.xRadius;
  16828. this.yRadius = json.yRadius;
  16829. this.aStartAngle = json.aStartAngle;
  16830. this.aEndAngle = json.aEndAngle;
  16831. this.aClockwise = json.aClockwise;
  16832. this.aRotation = json.aRotation;
  16833. return this;
  16834. }
  16835. }
  16836. /**
  16837. * A curve representing an arc.
  16838. *
  16839. * @augments EllipseCurve
  16840. */
  16841. class ArcCurve extends EllipseCurve {
  16842. /**
  16843. * Constructs a new arc curve.
  16844. *
  16845. * @param {number} [aX=0] - The X center of the ellipse.
  16846. * @param {number} [aY=0] - The Y center of the ellipse.
  16847. * @param {number} [aRadius=1] - The radius of the ellipse in the x direction.
  16848. * @param {number} [aStartAngle=0] - The start angle of the curve in radians starting from the positive X axis.
  16849. * @param {number} [aEndAngle=Math.PI*2] - The end angle of the curve in radians starting from the positive X axis.
  16850. * @param {boolean} [aClockwise=false] - Whether the ellipse is drawn clockwise or not.
  16851. */
  16852. constructor( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  16853. super( aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  16854. /**
  16855. * This flag can be used for type testing.
  16856. *
  16857. * @type {boolean}
  16858. * @readonly
  16859. * @default true
  16860. */
  16861. this.isArcCurve = true;
  16862. this.type = 'ArcCurve';
  16863. }
  16864. }
  16865. function CubicPoly() {
  16866. /**
  16867. * Centripetal CatmullRom Curve - which is useful for avoiding
  16868. * cusps and self-intersections in non-uniform catmull rom curves.
  16869. * http://www.cemyuksel.com/research/catmullrom_param/catmullrom.pdf
  16870. *
  16871. * curve.type accepts centripetal(default), chordal and catmullrom
  16872. * curve.tension is used for catmullrom which defaults to 0.5
  16873. */
  16874. /*
  16875. Based on an optimized c++ solution in
  16876. - http://stackoverflow.com/questions/9489736/catmull-rom-curve-with-no-cusps-and-no-self-intersections/
  16877. - http://ideone.com/NoEbVM
  16878. This CubicPoly class could be used for reusing some variables and calculations,
  16879. but for three.js curve use, it could be possible inlined and flatten into a single function call
  16880. which can be placed in CurveUtils.
  16881. */
  16882. let c0 = 0, c1 = 0, c2 = 0, c3 = 0;
  16883. /*
  16884. * Compute coefficients for a cubic polynomial
  16885. * p(s) = c0 + c1*s + c2*s^2 + c3*s^3
  16886. * such that
  16887. * p(0) = x0, p(1) = x1
  16888. * and
  16889. * p'(0) = t0, p'(1) = t1.
  16890. */
  16891. function init( x0, x1, t0, t1 ) {
  16892. c0 = x0;
  16893. c1 = t0;
  16894. c2 = -3 * x0 + 3 * x1 - 2 * t0 - t1;
  16895. c3 = 2 * x0 - 2 * x1 + t0 + t1;
  16896. }
  16897. return {
  16898. initCatmullRom: function ( x0, x1, x2, x3, tension ) {
  16899. init( x1, x2, tension * ( x2 - x0 ), tension * ( x3 - x1 ) );
  16900. },
  16901. initNonuniformCatmullRom: function ( x0, x1, x2, x3, dt0, dt1, dt2 ) {
  16902. // compute tangents when parameterized in [t1,t2]
  16903. let t1 = ( x1 - x0 ) / dt0 - ( x2 - x0 ) / ( dt0 + dt1 ) + ( x2 - x1 ) / dt1;
  16904. let t2 = ( x2 - x1 ) / dt1 - ( x3 - x1 ) / ( dt1 + dt2 ) + ( x3 - x2 ) / dt2;
  16905. // rescale tangents for parametrization in [0,1]
  16906. t1 *= dt1;
  16907. t2 *= dt1;
  16908. init( x1, x2, t1, t2 );
  16909. },
  16910. calc: function ( t ) {
  16911. const t2 = t * t;
  16912. const t3 = t2 * t;
  16913. return c0 + c1 * t + c2 * t2 + c3 * t3;
  16914. }
  16915. };
  16916. }
  16917. //
  16918. const tmp = /*@__PURE__*/ new Vector3();
  16919. const px = /*@__PURE__*/ new CubicPoly();
  16920. const py = /*@__PURE__*/ new CubicPoly();
  16921. const pz = /*@__PURE__*/ new CubicPoly();
  16922. /**
  16923. * A curve representing a Catmull-Rom spline.
  16924. *
  16925. * ```js
  16926. * //Create a closed wavey loop
  16927. * const curve = new THREE.CatmullRomCurve3( [
  16928. * new THREE.Vector3( -10, 0, 10 ),
  16929. * new THREE.Vector3( -5, 5, 5 ),
  16930. * new THREE.Vector3( 0, 0, 0 ),
  16931. * new THREE.Vector3( 5, -5, 5 ),
  16932. * new THREE.Vector3( 10, 0, 10 )
  16933. * ] );
  16934. *
  16935. * const points = curve.getPoints( 50 );
  16936. * const geometry = new THREE.BufferGeometry().setFromPoints( points );
  16937. *
  16938. * const material = new THREE.LineBasicMaterial( { color: 0xff0000 } );
  16939. *
  16940. * // Create the final object to add to the scene
  16941. * const curveObject = new THREE.Line( geometry, material );
  16942. * ```
  16943. *
  16944. * @augments Curve
  16945. */
  16946. class CatmullRomCurve3 extends Curve {
  16947. /**
  16948. * Constructs a new Catmull-Rom curve.
  16949. *
  16950. * @param {Array<Vector3>} [points] - An array of 3D points defining the curve.
  16951. * @param {boolean} [closed=false] - Whether the curve is closed or not.
  16952. * @param {('centripetal'|'chordal'|'catmullrom')} [curveType='centripetal'] - The curve type.
  16953. * @param {number} [tension=0.5] - Tension of the curve.
  16954. */
  16955. constructor( points = [], closed = false, curveType = 'centripetal', tension = 0.5 ) {
  16956. super();
  16957. /**
  16958. * This flag can be used for type testing.
  16959. *
  16960. * @type {boolean}
  16961. * @readonly
  16962. * @default true
  16963. */
  16964. this.isCatmullRomCurve3 = true;
  16965. this.type = 'CatmullRomCurve3';
  16966. /**
  16967. * An array of 3D points defining the curve.
  16968. *
  16969. * @type {Array<Vector3>}
  16970. */
  16971. this.points = points;
  16972. /**
  16973. * Whether the curve is closed or not.
  16974. *
  16975. * @type {boolean}
  16976. * @default false
  16977. */
  16978. this.closed = closed;
  16979. /**
  16980. * The curve type.
  16981. *
  16982. * @type {('centripetal'|'chordal'|'catmullrom')}
  16983. * @default 'centripetal'
  16984. */
  16985. this.curveType = curveType;
  16986. /**
  16987. * Tension of the curve.
  16988. *
  16989. * @type {number}
  16990. * @default 0.5
  16991. */
  16992. this.tension = tension;
  16993. }
  16994. /**
  16995. * Returns a point on the curve.
  16996. *
  16997. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  16998. * @param {Vector3} [optionalTarget] - The optional target vector the result is written to.
  16999. * @return {Vector3} The position on the curve.
  17000. */
  17001. getPoint( t, optionalTarget = new Vector3() ) {
  17002. const point = optionalTarget;
  17003. const points = this.points;
  17004. const l = points.length;
  17005. const p = ( l - ( this.closed ? 0 : 1 ) ) * t;
  17006. let intPoint = Math.floor( p );
  17007. let weight = p - intPoint;
  17008. if ( this.closed ) {
  17009. intPoint += intPoint > 0 ? 0 : ( Math.floor( Math.abs( intPoint ) / l ) + 1 ) * l;
  17010. } else if ( weight === 0 && intPoint === l - 1 ) {
  17011. intPoint = l - 2;
  17012. weight = 1;
  17013. }
  17014. let p0, p3; // 4 points (p1 & p2 defined below)
  17015. if ( this.closed || intPoint > 0 ) {
  17016. p0 = points[ ( intPoint - 1 ) % l ];
  17017. } else {
  17018. // extrapolate first point
  17019. tmp.subVectors( points[ 0 ], points[ 1 ] ).add( points[ 0 ] );
  17020. p0 = tmp;
  17021. }
  17022. const p1 = points[ intPoint % l ];
  17023. const p2 = points[ ( intPoint + 1 ) % l ];
  17024. if ( this.closed || intPoint + 2 < l ) {
  17025. p3 = points[ ( intPoint + 2 ) % l ];
  17026. } else {
  17027. // extrapolate last point
  17028. tmp.subVectors( points[ l - 1 ], points[ l - 2 ] ).add( points[ l - 1 ] );
  17029. p3 = tmp;
  17030. }
  17031. if ( this.curveType === 'centripetal' || this.curveType === 'chordal' ) {
  17032. // init Centripetal / Chordal Catmull-Rom
  17033. const pow = this.curveType === 'chordal' ? 0.5 : 0.25;
  17034. let dt0 = Math.pow( p0.distanceToSquared( p1 ), pow );
  17035. let dt1 = Math.pow( p1.distanceToSquared( p2 ), pow );
  17036. let dt2 = Math.pow( p2.distanceToSquared( p3 ), pow );
  17037. // safety check for repeated points
  17038. if ( dt1 < 1e-4 ) dt1 = 1.0;
  17039. if ( dt0 < 1e-4 ) dt0 = dt1;
  17040. if ( dt2 < 1e-4 ) dt2 = dt1;
  17041. px.initNonuniformCatmullRom( p0.x, p1.x, p2.x, p3.x, dt0, dt1, dt2 );
  17042. py.initNonuniformCatmullRom( p0.y, p1.y, p2.y, p3.y, dt0, dt1, dt2 );
  17043. pz.initNonuniformCatmullRom( p0.z, p1.z, p2.z, p3.z, dt0, dt1, dt2 );
  17044. } else if ( this.curveType === 'catmullrom' ) {
  17045. px.initCatmullRom( p0.x, p1.x, p2.x, p3.x, this.tension );
  17046. py.initCatmullRom( p0.y, p1.y, p2.y, p3.y, this.tension );
  17047. pz.initCatmullRom( p0.z, p1.z, p2.z, p3.z, this.tension );
  17048. }
  17049. point.set(
  17050. px.calc( weight ),
  17051. py.calc( weight ),
  17052. pz.calc( weight )
  17053. );
  17054. return point;
  17055. }
  17056. copy( source ) {
  17057. super.copy( source );
  17058. this.points = [];
  17059. for ( let i = 0, l = source.points.length; i < l; i ++ ) {
  17060. const point = source.points[ i ];
  17061. this.points.push( point.clone() );
  17062. }
  17063. this.closed = source.closed;
  17064. this.curveType = source.curveType;
  17065. this.tension = source.tension;
  17066. return this;
  17067. }
  17068. toJSON() {
  17069. const data = super.toJSON();
  17070. data.points = [];
  17071. for ( let i = 0, l = this.points.length; i < l; i ++ ) {
  17072. const point = this.points[ i ];
  17073. data.points.push( point.toArray() );
  17074. }
  17075. data.closed = this.closed;
  17076. data.curveType = this.curveType;
  17077. data.tension = this.tension;
  17078. return data;
  17079. }
  17080. fromJSON( json ) {
  17081. super.fromJSON( json );
  17082. this.points = [];
  17083. for ( let i = 0, l = json.points.length; i < l; i ++ ) {
  17084. const point = json.points[ i ];
  17085. this.points.push( new Vector3().fromArray( point ) );
  17086. }
  17087. this.closed = json.closed;
  17088. this.curveType = json.curveType;
  17089. this.tension = json.tension;
  17090. return this;
  17091. }
  17092. }
  17093. // Bezier Curves formulas obtained from: https://en.wikipedia.org/wiki/B%C3%A9zier_curve
  17094. /**
  17095. * Computes a point on a Camtull-Rom spline.
  17096. *
  17097. * @param {number} t - The interpolation factor.
  17098. * @param {number} p0 - The first control point.
  17099. * @param {number} p1 - The second control point.
  17100. * @param {number} p2 - The third control point.
  17101. * @param {number} p3 - The fourth control point.
  17102. * @return {number} The calculated point on a Camtull-Rom spline.
  17103. */
  17104. function CatmullRom( t, p0, p1, p2, p3 ) {
  17105. const v0 = ( p2 - p0 ) * 0.5;
  17106. const v1 = ( p3 - p1 ) * 0.5;
  17107. const t2 = t * t;
  17108. const t3 = t * t2;
  17109. return ( 2 * p1 - 2 * p2 + v0 + v1 ) * t3 + ( -3 * p1 + 3 * p2 - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  17110. }
  17111. //
  17112. function QuadraticBezierP0( t, p ) {
  17113. const k = 1 - t;
  17114. return k * k * p;
  17115. }
  17116. function QuadraticBezierP1( t, p ) {
  17117. return 2 * ( 1 - t ) * t * p;
  17118. }
  17119. function QuadraticBezierP2( t, p ) {
  17120. return t * t * p;
  17121. }
  17122. /**
  17123. * Computes a point on a Quadratic Bezier curve.
  17124. *
  17125. * @param {number} t - The interpolation factor.
  17126. * @param {number} p0 - The first control point.
  17127. * @param {number} p1 - The second control point.
  17128. * @param {number} p2 - The third control point.
  17129. * @return {number} The calculated point on a Quadratic Bezier curve.
  17130. */
  17131. function QuadraticBezier( t, p0, p1, p2 ) {
  17132. return QuadraticBezierP0( t, p0 ) + QuadraticBezierP1( t, p1 ) +
  17133. QuadraticBezierP2( t, p2 );
  17134. }
  17135. //
  17136. function CubicBezierP0( t, p ) {
  17137. const k = 1 - t;
  17138. return k * k * k * p;
  17139. }
  17140. function CubicBezierP1( t, p ) {
  17141. const k = 1 - t;
  17142. return 3 * k * k * t * p;
  17143. }
  17144. function CubicBezierP2( t, p ) {
  17145. return 3 * ( 1 - t ) * t * t * p;
  17146. }
  17147. function CubicBezierP3( t, p ) {
  17148. return t * t * t * p;
  17149. }
  17150. /**
  17151. * Computes a point on a Cubic Bezier curve.
  17152. *
  17153. * @param {number} t - The interpolation factor.
  17154. * @param {number} p0 - The first control point.
  17155. * @param {number} p1 - The second control point.
  17156. * @param {number} p2 - The third control point.
  17157. * @param {number} p3 - The fourth control point.
  17158. * @return {number} The calculated point on a Cubic Bezier curve.
  17159. */
  17160. function CubicBezier( t, p0, p1, p2, p3 ) {
  17161. return CubicBezierP0( t, p0 ) + CubicBezierP1( t, p1 ) + CubicBezierP2( t, p2 ) +
  17162. CubicBezierP3( t, p3 );
  17163. }
  17164. /**
  17165. * A curve representing a 2D Cubic Bezier curve.
  17166. *
  17167. * ```js
  17168. * const curve = new THREE.CubicBezierCurve(
  17169. * new THREE.Vector2( - 0, 0 ),
  17170. * new THREE.Vector2( - 5, 15 ),
  17171. * new THREE.Vector2( 20, 15 ),
  17172. * new THREE.Vector2( 10, 0 )
  17173. * );
  17174. *
  17175. * const points = curve.getPoints( 50 );
  17176. * const geometry = new THREE.BufferGeometry().setFromPoints( points );
  17177. *
  17178. * const material = new THREE.LineBasicMaterial( { color: 0xff0000 } );
  17179. *
  17180. * // Create the final object to add to the scene
  17181. * const curveObject = new THREE.Line( geometry, material );
  17182. * ```
  17183. *
  17184. * @augments Curve
  17185. */
  17186. class CubicBezierCurve extends Curve {
  17187. /**
  17188. * Constructs a new Cubic Bezier curve.
  17189. *
  17190. * @param {Vector2} [v0] - The start point.
  17191. * @param {Vector2} [v1] - The first control point.
  17192. * @param {Vector2} [v2] - The second control point.
  17193. * @param {Vector2} [v3] - The end point.
  17194. */
  17195. constructor( v0 = new Vector2(), v1 = new Vector2(), v2 = new Vector2(), v3 = new Vector2() ) {
  17196. super();
  17197. /**
  17198. * This flag can be used for type testing.
  17199. *
  17200. * @type {boolean}
  17201. * @readonly
  17202. * @default true
  17203. */
  17204. this.isCubicBezierCurve = true;
  17205. this.type = 'CubicBezierCurve';
  17206. /**
  17207. * The start point.
  17208. *
  17209. * @type {Vector2}
  17210. */
  17211. this.v0 = v0;
  17212. /**
  17213. * The first control point.
  17214. *
  17215. * @type {Vector2}
  17216. */
  17217. this.v1 = v1;
  17218. /**
  17219. * The second control point.
  17220. *
  17221. * @type {Vector2}
  17222. */
  17223. this.v2 = v2;
  17224. /**
  17225. * The end point.
  17226. *
  17227. * @type {Vector2}
  17228. */
  17229. this.v3 = v3;
  17230. }
  17231. /**
  17232. * Returns a point on the curve.
  17233. *
  17234. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  17235. * @param {Vector2} [optionalTarget] - The optional target vector the result is written to.
  17236. * @return {Vector2} The position on the curve.
  17237. */
  17238. getPoint( t, optionalTarget = new Vector2() ) {
  17239. const point = optionalTarget;
  17240. const v0 = this.v0, v1 = this.v1, v2 = this.v2, v3 = this.v3;
  17241. point.set(
  17242. CubicBezier( t, v0.x, v1.x, v2.x, v3.x ),
  17243. CubicBezier( t, v0.y, v1.y, v2.y, v3.y )
  17244. );
  17245. return point;
  17246. }
  17247. copy( source ) {
  17248. super.copy( source );
  17249. this.v0.copy( source.v0 );
  17250. this.v1.copy( source.v1 );
  17251. this.v2.copy( source.v2 );
  17252. this.v3.copy( source.v3 );
  17253. return this;
  17254. }
  17255. toJSON() {
  17256. const data = super.toJSON();
  17257. data.v0 = this.v0.toArray();
  17258. data.v1 = this.v1.toArray();
  17259. data.v2 = this.v2.toArray();
  17260. data.v3 = this.v3.toArray();
  17261. return data;
  17262. }
  17263. fromJSON( json ) {
  17264. super.fromJSON( json );
  17265. this.v0.fromArray( json.v0 );
  17266. this.v1.fromArray( json.v1 );
  17267. this.v2.fromArray( json.v2 );
  17268. this.v3.fromArray( json.v3 );
  17269. return this;
  17270. }
  17271. }
  17272. /**
  17273. * A curve representing a 3D Cubic Bezier curve.
  17274. *
  17275. * @augments Curve
  17276. */
  17277. class CubicBezierCurve3 extends Curve {
  17278. /**
  17279. * Constructs a new Cubic Bezier curve.
  17280. *
  17281. * @param {Vector3} [v0] - The start point.
  17282. * @param {Vector3} [v1] - The first control point.
  17283. * @param {Vector3} [v2] - The second control point.
  17284. * @param {Vector3} [v3] - The end point.
  17285. */
  17286. constructor( v0 = new Vector3(), v1 = new Vector3(), v2 = new Vector3(), v3 = new Vector3() ) {
  17287. super();
  17288. /**
  17289. * This flag can be used for type testing.
  17290. *
  17291. * @type {boolean}
  17292. * @readonly
  17293. * @default true
  17294. */
  17295. this.isCubicBezierCurve3 = true;
  17296. this.type = 'CubicBezierCurve3';
  17297. /**
  17298. * The start point.
  17299. *
  17300. * @type {Vector3}
  17301. */
  17302. this.v0 = v0;
  17303. /**
  17304. * The first control point.
  17305. *
  17306. * @type {Vector3}
  17307. */
  17308. this.v1 = v1;
  17309. /**
  17310. * The second control point.
  17311. *
  17312. * @type {Vector3}
  17313. */
  17314. this.v2 = v2;
  17315. /**
  17316. * The end point.
  17317. *
  17318. * @type {Vector3}
  17319. */
  17320. this.v3 = v3;
  17321. }
  17322. /**
  17323. * Returns a point on the curve.
  17324. *
  17325. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  17326. * @param {Vector3} [optionalTarget] - The optional target vector the result is written to.
  17327. * @return {Vector3} The position on the curve.
  17328. */
  17329. getPoint( t, optionalTarget = new Vector3() ) {
  17330. const point = optionalTarget;
  17331. const v0 = this.v0, v1 = this.v1, v2 = this.v2, v3 = this.v3;
  17332. point.set(
  17333. CubicBezier( t, v0.x, v1.x, v2.x, v3.x ),
  17334. CubicBezier( t, v0.y, v1.y, v2.y, v3.y ),
  17335. CubicBezier( t, v0.z, v1.z, v2.z, v3.z )
  17336. );
  17337. return point;
  17338. }
  17339. copy( source ) {
  17340. super.copy( source );
  17341. this.v0.copy( source.v0 );
  17342. this.v1.copy( source.v1 );
  17343. this.v2.copy( source.v2 );
  17344. this.v3.copy( source.v3 );
  17345. return this;
  17346. }
  17347. toJSON() {
  17348. const data = super.toJSON();
  17349. data.v0 = this.v0.toArray();
  17350. data.v1 = this.v1.toArray();
  17351. data.v2 = this.v2.toArray();
  17352. data.v3 = this.v3.toArray();
  17353. return data;
  17354. }
  17355. fromJSON( json ) {
  17356. super.fromJSON( json );
  17357. this.v0.fromArray( json.v0 );
  17358. this.v1.fromArray( json.v1 );
  17359. this.v2.fromArray( json.v2 );
  17360. this.v3.fromArray( json.v3 );
  17361. return this;
  17362. }
  17363. }
  17364. /**
  17365. * A curve representing a 2D line segment.
  17366. *
  17367. * @augments Curve
  17368. */
  17369. class LineCurve extends Curve {
  17370. /**
  17371. * Constructs a new line curve.
  17372. *
  17373. * @param {Vector2} [v1] - The start point.
  17374. * @param {Vector2} [v2] - The end point.
  17375. */
  17376. constructor( v1 = new Vector2(), v2 = new Vector2() ) {
  17377. super();
  17378. /**
  17379. * This flag can be used for type testing.
  17380. *
  17381. * @type {boolean}
  17382. * @readonly
  17383. * @default true
  17384. */
  17385. this.isLineCurve = true;
  17386. this.type = 'LineCurve';
  17387. /**
  17388. * The start point.
  17389. *
  17390. * @type {Vector2}
  17391. */
  17392. this.v1 = v1;
  17393. /**
  17394. * The end point.
  17395. *
  17396. * @type {Vector2}
  17397. */
  17398. this.v2 = v2;
  17399. }
  17400. /**
  17401. * Returns a point on the line.
  17402. *
  17403. * @param {number} t - A interpolation factor representing a position on the line. Must be in the range `[0,1]`.
  17404. * @param {Vector2} [optionalTarget] - The optional target vector the result is written to.
  17405. * @return {Vector2} The position on the line.
  17406. */
  17407. getPoint( t, optionalTarget = new Vector2() ) {
  17408. const point = optionalTarget;
  17409. if ( t === 1 ) {
  17410. point.copy( this.v2 );
  17411. } else {
  17412. point.copy( this.v2 ).sub( this.v1 );
  17413. point.multiplyScalar( t ).add( this.v1 );
  17414. }
  17415. return point;
  17416. }
  17417. // Line curve is linear, so we can overwrite default getPointAt
  17418. getPointAt( u, optionalTarget ) {
  17419. return this.getPoint( u, optionalTarget );
  17420. }
  17421. getTangent( t, optionalTarget = new Vector2() ) {
  17422. return optionalTarget.subVectors( this.v2, this.v1 ).normalize();
  17423. }
  17424. getTangentAt( u, optionalTarget ) {
  17425. return this.getTangent( u, optionalTarget );
  17426. }
  17427. copy( source ) {
  17428. super.copy( source );
  17429. this.v1.copy( source.v1 );
  17430. this.v2.copy( source.v2 );
  17431. return this;
  17432. }
  17433. toJSON() {
  17434. const data = super.toJSON();
  17435. data.v1 = this.v1.toArray();
  17436. data.v2 = this.v2.toArray();
  17437. return data;
  17438. }
  17439. fromJSON( json ) {
  17440. super.fromJSON( json );
  17441. this.v1.fromArray( json.v1 );
  17442. this.v2.fromArray( json.v2 );
  17443. return this;
  17444. }
  17445. }
  17446. /**
  17447. * A curve representing a 3D line segment.
  17448. *
  17449. * @augments Curve
  17450. */
  17451. class LineCurve3 extends Curve {
  17452. /**
  17453. * Constructs a new line curve.
  17454. *
  17455. * @param {Vector3} [v1] - The start point.
  17456. * @param {Vector3} [v2] - The end point.
  17457. */
  17458. constructor( v1 = new Vector3(), v2 = new Vector3() ) {
  17459. super();
  17460. /**
  17461. * This flag can be used for type testing.
  17462. *
  17463. * @type {boolean}
  17464. * @readonly
  17465. * @default true
  17466. */
  17467. this.isLineCurve3 = true;
  17468. this.type = 'LineCurve3';
  17469. /**
  17470. * The start point.
  17471. *
  17472. * @type {Vector3}
  17473. */
  17474. this.v1 = v1;
  17475. /**
  17476. * The end point.
  17477. *
  17478. * @type {Vector2}
  17479. */
  17480. this.v2 = v2;
  17481. }
  17482. /**
  17483. * Returns a point on the line.
  17484. *
  17485. * @param {number} t - A interpolation factor representing a position on the line. Must be in the range `[0,1]`.
  17486. * @param {Vector3} [optionalTarget] - The optional target vector the result is written to.
  17487. * @return {Vector3} The position on the line.
  17488. */
  17489. getPoint( t, optionalTarget = new Vector3() ) {
  17490. const point = optionalTarget;
  17491. if ( t === 1 ) {
  17492. point.copy( this.v2 );
  17493. } else {
  17494. point.copy( this.v2 ).sub( this.v1 );
  17495. point.multiplyScalar( t ).add( this.v1 );
  17496. }
  17497. return point;
  17498. }
  17499. // Line curve is linear, so we can overwrite default getPointAt
  17500. getPointAt( u, optionalTarget ) {
  17501. return this.getPoint( u, optionalTarget );
  17502. }
  17503. getTangent( t, optionalTarget = new Vector3() ) {
  17504. return optionalTarget.subVectors( this.v2, this.v1 ).normalize();
  17505. }
  17506. getTangentAt( u, optionalTarget ) {
  17507. return this.getTangent( u, optionalTarget );
  17508. }
  17509. copy( source ) {
  17510. super.copy( source );
  17511. this.v1.copy( source.v1 );
  17512. this.v2.copy( source.v2 );
  17513. return this;
  17514. }
  17515. toJSON() {
  17516. const data = super.toJSON();
  17517. data.v1 = this.v1.toArray();
  17518. data.v2 = this.v2.toArray();
  17519. return data;
  17520. }
  17521. fromJSON( json ) {
  17522. super.fromJSON( json );
  17523. this.v1.fromArray( json.v1 );
  17524. this.v2.fromArray( json.v2 );
  17525. return this;
  17526. }
  17527. }
  17528. /**
  17529. * A curve representing a 2D Quadratic Bezier curve.
  17530. *
  17531. * ```js
  17532. * const curve = new THREE.QuadraticBezierCurve(
  17533. * new THREE.Vector2( - 10, 0 ),
  17534. * new THREE.Vector2( 20, 15 ),
  17535. * new THREE.Vector2( 10, 0 )
  17536. * )
  17537. *
  17538. * const points = curve.getPoints( 50 );
  17539. * const geometry = new THREE.BufferGeometry().setFromPoints( points );
  17540. *
  17541. * const material = new THREE.LineBasicMaterial( { color: 0xff0000 } );
  17542. *
  17543. * // Create the final object to add to the scene
  17544. * const curveObject = new THREE.Line( geometry, material );
  17545. * ```
  17546. *
  17547. * @augments Curve
  17548. */
  17549. class QuadraticBezierCurve extends Curve {
  17550. /**
  17551. * Constructs a new Quadratic Bezier curve.
  17552. *
  17553. * @param {Vector2} [v0] - The start point.
  17554. * @param {Vector2} [v1] - The control point.
  17555. * @param {Vector2} [v2] - The end point.
  17556. */
  17557. constructor( v0 = new Vector2(), v1 = new Vector2(), v2 = new Vector2() ) {
  17558. super();
  17559. /**
  17560. * This flag can be used for type testing.
  17561. *
  17562. * @type {boolean}
  17563. * @readonly
  17564. * @default true
  17565. */
  17566. this.isQuadraticBezierCurve = true;
  17567. this.type = 'QuadraticBezierCurve';
  17568. /**
  17569. * The start point.
  17570. *
  17571. * @type {Vector2}
  17572. */
  17573. this.v0 = v0;
  17574. /**
  17575. * The control point.
  17576. *
  17577. * @type {Vector2}
  17578. */
  17579. this.v1 = v1;
  17580. /**
  17581. * The end point.
  17582. *
  17583. * @type {Vector2}
  17584. */
  17585. this.v2 = v2;
  17586. }
  17587. /**
  17588. * Returns a point on the curve.
  17589. *
  17590. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  17591. * @param {Vector2} [optionalTarget] - The optional target vector the result is written to.
  17592. * @return {Vector2} The position on the curve.
  17593. */
  17594. getPoint( t, optionalTarget = new Vector2() ) {
  17595. const point = optionalTarget;
  17596. const v0 = this.v0, v1 = this.v1, v2 = this.v2;
  17597. point.set(
  17598. QuadraticBezier( t, v0.x, v1.x, v2.x ),
  17599. QuadraticBezier( t, v0.y, v1.y, v2.y )
  17600. );
  17601. return point;
  17602. }
  17603. copy( source ) {
  17604. super.copy( source );
  17605. this.v0.copy( source.v0 );
  17606. this.v1.copy( source.v1 );
  17607. this.v2.copy( source.v2 );
  17608. return this;
  17609. }
  17610. toJSON() {
  17611. const data = super.toJSON();
  17612. data.v0 = this.v0.toArray();
  17613. data.v1 = this.v1.toArray();
  17614. data.v2 = this.v2.toArray();
  17615. return data;
  17616. }
  17617. fromJSON( json ) {
  17618. super.fromJSON( json );
  17619. this.v0.fromArray( json.v0 );
  17620. this.v1.fromArray( json.v1 );
  17621. this.v2.fromArray( json.v2 );
  17622. return this;
  17623. }
  17624. }
  17625. /**
  17626. * A curve representing a 3D Quadratic Bezier curve.
  17627. *
  17628. * @augments Curve
  17629. */
  17630. class QuadraticBezierCurve3 extends Curve {
  17631. /**
  17632. * Constructs a new Quadratic Bezier curve.
  17633. *
  17634. * @param {Vector3} [v0] - The start point.
  17635. * @param {Vector3} [v1] - The control point.
  17636. * @param {Vector3} [v2] - The end point.
  17637. */
  17638. constructor( v0 = new Vector3(), v1 = new Vector3(), v2 = new Vector3() ) {
  17639. super();
  17640. /**
  17641. * This flag can be used for type testing.
  17642. *
  17643. * @type {boolean}
  17644. * @readonly
  17645. * @default true
  17646. */
  17647. this.isQuadraticBezierCurve3 = true;
  17648. this.type = 'QuadraticBezierCurve3';
  17649. /**
  17650. * The start point.
  17651. *
  17652. * @type {Vector3}
  17653. */
  17654. this.v0 = v0;
  17655. /**
  17656. * The control point.
  17657. *
  17658. * @type {Vector3}
  17659. */
  17660. this.v1 = v1;
  17661. /**
  17662. * The end point.
  17663. *
  17664. * @type {Vector3}
  17665. */
  17666. this.v2 = v2;
  17667. }
  17668. /**
  17669. * Returns a point on the curve.
  17670. *
  17671. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  17672. * @param {Vector3} [optionalTarget] - The optional target vector the result is written to.
  17673. * @return {Vector3} The position on the curve.
  17674. */
  17675. getPoint( t, optionalTarget = new Vector3() ) {
  17676. const point = optionalTarget;
  17677. const v0 = this.v0, v1 = this.v1, v2 = this.v2;
  17678. point.set(
  17679. QuadraticBezier( t, v0.x, v1.x, v2.x ),
  17680. QuadraticBezier( t, v0.y, v1.y, v2.y ),
  17681. QuadraticBezier( t, v0.z, v1.z, v2.z )
  17682. );
  17683. return point;
  17684. }
  17685. copy( source ) {
  17686. super.copy( source );
  17687. this.v0.copy( source.v0 );
  17688. this.v1.copy( source.v1 );
  17689. this.v2.copy( source.v2 );
  17690. return this;
  17691. }
  17692. toJSON() {
  17693. const data = super.toJSON();
  17694. data.v0 = this.v0.toArray();
  17695. data.v1 = this.v1.toArray();
  17696. data.v2 = this.v2.toArray();
  17697. return data;
  17698. }
  17699. fromJSON( json ) {
  17700. super.fromJSON( json );
  17701. this.v0.fromArray( json.v0 );
  17702. this.v1.fromArray( json.v1 );
  17703. this.v2.fromArray( json.v2 );
  17704. return this;
  17705. }
  17706. }
  17707. /**
  17708. * A curve representing a 2D spline curve.
  17709. *
  17710. * ```js
  17711. * // Create a sine-like wave
  17712. * const curve = new THREE.SplineCurve( [
  17713. * new THREE.Vector2( -10, 0 ),
  17714. * new THREE.Vector2( -5, 5 ),
  17715. * new THREE.Vector2( 0, 0 ),
  17716. * new THREE.Vector2( 5, -5 ),
  17717. * new THREE.Vector2( 10, 0 )
  17718. * ] );
  17719. *
  17720. * const points = curve.getPoints( 50 );
  17721. * const geometry = new THREE.BufferGeometry().setFromPoints( points );
  17722. *
  17723. * const material = new THREE.LineBasicMaterial( { color: 0xff0000 } );
  17724. *
  17725. * // Create the final object to add to the scene
  17726. * const splineObject = new THREE.Line( geometry, material );
  17727. * ```
  17728. *
  17729. * @augments Curve
  17730. */
  17731. class SplineCurve extends Curve {
  17732. /**
  17733. * Constructs a new 2D spline curve.
  17734. *
  17735. * @param {Array<Vector2>} [points] - An array of 2D points defining the curve.
  17736. */
  17737. constructor( points = [] ) {
  17738. super();
  17739. /**
  17740. * This flag can be used for type testing.
  17741. *
  17742. * @type {boolean}
  17743. * @readonly
  17744. * @default true
  17745. */
  17746. this.isSplineCurve = true;
  17747. this.type = 'SplineCurve';
  17748. /**
  17749. * An array of 2D points defining the curve.
  17750. *
  17751. * @type {Array<Vector2>}
  17752. */
  17753. this.points = points;
  17754. }
  17755. /**
  17756. * Returns a point on the curve.
  17757. *
  17758. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  17759. * @param {Vector2} [optionalTarget] - The optional target vector the result is written to.
  17760. * @return {Vector2} The position on the curve.
  17761. */
  17762. getPoint( t, optionalTarget = new Vector2() ) {
  17763. const point = optionalTarget;
  17764. const points = this.points;
  17765. const p = ( points.length - 1 ) * t;
  17766. const intPoint = Math.floor( p );
  17767. const weight = p - intPoint;
  17768. const p0 = points[ intPoint === 0 ? intPoint : intPoint - 1 ];
  17769. const p1 = points[ intPoint ];
  17770. const p2 = points[ intPoint > points.length - 2 ? points.length - 1 : intPoint + 1 ];
  17771. const p3 = points[ intPoint > points.length - 3 ? points.length - 1 : intPoint + 2 ];
  17772. point.set(
  17773. CatmullRom( weight, p0.x, p1.x, p2.x, p3.x ),
  17774. CatmullRom( weight, p0.y, p1.y, p2.y, p3.y )
  17775. );
  17776. return point;
  17777. }
  17778. copy( source ) {
  17779. super.copy( source );
  17780. this.points = [];
  17781. for ( let i = 0, l = source.points.length; i < l; i ++ ) {
  17782. const point = source.points[ i ];
  17783. this.points.push( point.clone() );
  17784. }
  17785. return this;
  17786. }
  17787. toJSON() {
  17788. const data = super.toJSON();
  17789. data.points = [];
  17790. for ( let i = 0, l = this.points.length; i < l; i ++ ) {
  17791. const point = this.points[ i ];
  17792. data.points.push( point.toArray() );
  17793. }
  17794. return data;
  17795. }
  17796. fromJSON( json ) {
  17797. super.fromJSON( json );
  17798. this.points = [];
  17799. for ( let i = 0, l = json.points.length; i < l; i ++ ) {
  17800. const point = json.points[ i ];
  17801. this.points.push( new Vector2().fromArray( point ) );
  17802. }
  17803. return this;
  17804. }
  17805. }
  17806. var Curves = /*#__PURE__*/Object.freeze({
  17807. __proto__: null,
  17808. ArcCurve: ArcCurve,
  17809. CatmullRomCurve3: CatmullRomCurve3,
  17810. CubicBezierCurve: CubicBezierCurve,
  17811. CubicBezierCurve3: CubicBezierCurve3,
  17812. EllipseCurve: EllipseCurve,
  17813. LineCurve: LineCurve,
  17814. LineCurve3: LineCurve3,
  17815. QuadraticBezierCurve: QuadraticBezierCurve,
  17816. QuadraticBezierCurve3: QuadraticBezierCurve3,
  17817. SplineCurve: SplineCurve
  17818. });
  17819. /**
  17820. * A base class extending {@link Curve}. `CurvePath` is simply an
  17821. * array of connected curves, but retains the API of a curve.
  17822. *
  17823. * @augments Curve
  17824. */
  17825. class CurvePath extends Curve {
  17826. /**
  17827. * Constructs a new curve path.
  17828. */
  17829. constructor() {
  17830. super();
  17831. this.type = 'CurvePath';
  17832. /**
  17833. * An array of curves defining the
  17834. * path.
  17835. *
  17836. * @type {Array<Curve>}
  17837. */
  17838. this.curves = [];
  17839. /**
  17840. * Whether the path should automatically be closed
  17841. * by a line curve.
  17842. *
  17843. * @type {boolean}
  17844. * @default false
  17845. */
  17846. this.autoClose = false;
  17847. }
  17848. /**
  17849. * Adds a curve to this curve path.
  17850. *
  17851. * @param {Curve} curve - The curve to add.
  17852. */
  17853. add( curve ) {
  17854. this.curves.push( curve );
  17855. }
  17856. /**
  17857. * Adds a line curve to close the path.
  17858. *
  17859. * @return {CurvePath} A reference to this curve path.
  17860. */
  17861. closePath() {
  17862. // Add a line curve if start and end of lines are not connected
  17863. const startPoint = this.curves[ 0 ].getPoint( 0 );
  17864. const endPoint = this.curves[ this.curves.length - 1 ].getPoint( 1 );
  17865. if ( ! startPoint.equals( endPoint ) ) {
  17866. const lineType = ( startPoint.isVector2 === true ) ? 'LineCurve' : 'LineCurve3';
  17867. this.curves.push( new Curves[ lineType ]( endPoint, startPoint ) );
  17868. }
  17869. return this;
  17870. }
  17871. /**
  17872. * This method returns a vector in 2D or 3D space (depending on the curve definitions)
  17873. * for the given interpolation factor.
  17874. *
  17875. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  17876. * @param {(Vector2|Vector3)} [optionalTarget] - The optional target vector the result is written to.
  17877. * @return {?(Vector2|Vector3)} The position on the curve. It can be a 2D or 3D vector depending on the curve definition.
  17878. */
  17879. getPoint( t, optionalTarget ) {
  17880. // To get accurate point with reference to
  17881. // entire path distance at time t,
  17882. // following has to be done:
  17883. // 1. Length of each sub path have to be known
  17884. // 2. Locate and identify type of curve
  17885. // 3. Get t for the curve
  17886. // 4. Return curve.getPointAt(t')
  17887. const d = t * this.getLength();
  17888. const curveLengths = this.getCurveLengths();
  17889. let i = 0;
  17890. // To think about boundaries points.
  17891. while ( i < curveLengths.length ) {
  17892. if ( curveLengths[ i ] >= d ) {
  17893. const diff = curveLengths[ i ] - d;
  17894. const curve = this.curves[ i ];
  17895. const segmentLength = curve.getLength();
  17896. const u = segmentLength === 0 ? 0 : 1 - diff / segmentLength;
  17897. return curve.getPointAt( u, optionalTarget );
  17898. }
  17899. i ++;
  17900. }
  17901. return null;
  17902. // loop where sum != 0, sum > d , sum+1 <d
  17903. }
  17904. getLength() {
  17905. // We cannot use the default THREE.Curve getPoint() with getLength() because in
  17906. // THREE.Curve, getLength() depends on getPoint() but in THREE.CurvePath
  17907. // getPoint() depends on getLength
  17908. const lens = this.getCurveLengths();
  17909. return lens[ lens.length - 1 ];
  17910. }
  17911. updateArcLengths() {
  17912. // cacheLengths must be recalculated.
  17913. this.needsUpdate = true;
  17914. this.cacheLengths = null;
  17915. this.getCurveLengths();
  17916. }
  17917. /**
  17918. * Returns list of cumulative curve lengths of the defined curves.
  17919. *
  17920. * @return {Array<number>} The curve lengths.
  17921. */
  17922. getCurveLengths() {
  17923. // Compute lengths and cache them
  17924. // We cannot overwrite getLengths() because UtoT mapping uses it.
  17925. // We use cache values if curves and cache array are same length
  17926. if ( this.cacheLengths && this.cacheLengths.length === this.curves.length ) {
  17927. return this.cacheLengths;
  17928. }
  17929. // Get length of sub-curve
  17930. // Push sums into cached array
  17931. const lengths = [];
  17932. let sums = 0;
  17933. for ( let i = 0, l = this.curves.length; i < l; i ++ ) {
  17934. sums += this.curves[ i ].getLength();
  17935. lengths.push( sums );
  17936. }
  17937. this.cacheLengths = lengths;
  17938. return lengths;
  17939. }
  17940. getSpacedPoints( divisions = 40 ) {
  17941. const points = [];
  17942. for ( let i = 0; i <= divisions; i ++ ) {
  17943. points.push( this.getPoint( i / divisions ) );
  17944. }
  17945. if ( this.autoClose ) {
  17946. points.push( points[ 0 ] );
  17947. }
  17948. return points;
  17949. }
  17950. getPoints( divisions = 12 ) {
  17951. const points = [];
  17952. let last;
  17953. for ( let i = 0, curves = this.curves; i < curves.length; i ++ ) {
  17954. const curve = curves[ i ];
  17955. const resolution = curve.isEllipseCurve ? divisions * 2
  17956. : ( curve.isLineCurve || curve.isLineCurve3 ) ? 1
  17957. : curve.isSplineCurve ? divisions * curve.points.length
  17958. : divisions;
  17959. const pts = curve.getPoints( resolution );
  17960. for ( let j = 0; j < pts.length; j ++ ) {
  17961. const point = pts[ j ];
  17962. if ( last && last.equals( point ) ) continue; // ensures no consecutive points are duplicates
  17963. points.push( point );
  17964. last = point;
  17965. }
  17966. }
  17967. if ( this.autoClose && points.length > 1 && ! points[ points.length - 1 ].equals( points[ 0 ] ) ) {
  17968. points.push( points[ 0 ] );
  17969. }
  17970. return points;
  17971. }
  17972. copy( source ) {
  17973. super.copy( source );
  17974. this.curves = [];
  17975. for ( let i = 0, l = source.curves.length; i < l; i ++ ) {
  17976. const curve = source.curves[ i ];
  17977. this.curves.push( curve.clone() );
  17978. }
  17979. this.autoClose = source.autoClose;
  17980. return this;
  17981. }
  17982. toJSON() {
  17983. const data = super.toJSON();
  17984. data.autoClose = this.autoClose;
  17985. data.curves = [];
  17986. for ( let i = 0, l = this.curves.length; i < l; i ++ ) {
  17987. const curve = this.curves[ i ];
  17988. data.curves.push( curve.toJSON() );
  17989. }
  17990. return data;
  17991. }
  17992. fromJSON( json ) {
  17993. super.fromJSON( json );
  17994. this.autoClose = json.autoClose;
  17995. this.curves = [];
  17996. for ( let i = 0, l = json.curves.length; i < l; i ++ ) {
  17997. const curve = json.curves[ i ];
  17998. this.curves.push( new Curves[ curve.type ]().fromJSON( curve ) );
  17999. }
  18000. return this;
  18001. }
  18002. }
  18003. /**
  18004. * A 2D path representation. The class provides methods for creating paths
  18005. * and contours of 2D shapes similar to the 2D Canvas API.
  18006. *
  18007. * ```js
  18008. * const path = new THREE.Path();
  18009. *
  18010. * path.lineTo( 0, 0.8 );
  18011. * path.quadraticCurveTo( 0, 1, 0.2, 1 );
  18012. * path.lineTo( 1, 1 );
  18013. *
  18014. * const points = path.getPoints();
  18015. *
  18016. * const geometry = new THREE.BufferGeometry().setFromPoints( points );
  18017. * const material = new THREE.LineBasicMaterial( { color: 0xffffff } );
  18018. *
  18019. * const line = new THREE.Line( geometry, material );
  18020. * scene.add( line );
  18021. * ```
  18022. *
  18023. * @augments CurvePath
  18024. */
  18025. class Path extends CurvePath {
  18026. /**
  18027. * Constructs a new path.
  18028. *
  18029. * @param {Array<Vector2>} [points] - An array of 2D points defining the path.
  18030. */
  18031. constructor( points ) {
  18032. super();
  18033. this.type = 'Path';
  18034. /**
  18035. * The current offset of the path. Any new curve added will start here.
  18036. *
  18037. * @type {Vector2}
  18038. */
  18039. this.currentPoint = new Vector2();
  18040. if ( points ) {
  18041. this.setFromPoints( points );
  18042. }
  18043. }
  18044. /**
  18045. * Creates a path from the given list of points. The points are added
  18046. * to the path as instances of {@link LineCurve}.
  18047. *
  18048. * @param {Array<Vector2>} points - An array of 2D points.
  18049. * @return {Path} A reference to this path.
  18050. */
  18051. setFromPoints( points ) {
  18052. this.moveTo( points[ 0 ].x, points[ 0 ].y );
  18053. for ( let i = 1, l = points.length; i < l; i ++ ) {
  18054. this.lineTo( points[ i ].x, points[ i ].y );
  18055. }
  18056. return this;
  18057. }
  18058. /**
  18059. * Moves {@link Path#currentPoint} to the given point.
  18060. *
  18061. * @param {number} x - The x coordinate.
  18062. * @param {number} y - The y coordinate.
  18063. * @return {Path} A reference to this path.
  18064. */
  18065. moveTo( x, y ) {
  18066. this.currentPoint.set( x, y ); // TODO consider referencing vectors instead of copying?
  18067. return this;
  18068. }
  18069. /**
  18070. * Adds an instance of {@link LineCurve} to the path by connecting
  18071. * the current point with the given one.
  18072. *
  18073. * @param {number} x - The x coordinate of the end point.
  18074. * @param {number} y - The y coordinate of the end point.
  18075. * @return {Path} A reference to this path.
  18076. */
  18077. lineTo( x, y ) {
  18078. const curve = new LineCurve( this.currentPoint.clone(), new Vector2( x, y ) );
  18079. this.curves.push( curve );
  18080. this.currentPoint.set( x, y );
  18081. return this;
  18082. }
  18083. /**
  18084. * Adds an instance of {@link QuadraticBezierCurve} to the path by connecting
  18085. * the current point with the given one.
  18086. *
  18087. * @param {number} aCPx - The x coordinate of the control point.
  18088. * @param {number} aCPy - The y coordinate of the control point.
  18089. * @param {number} aX - The x coordinate of the end point.
  18090. * @param {number} aY - The y coordinate of the end point.
  18091. * @return {Path} A reference to this path.
  18092. */
  18093. quadraticCurveTo( aCPx, aCPy, aX, aY ) {
  18094. const curve = new QuadraticBezierCurve(
  18095. this.currentPoint.clone(),
  18096. new Vector2( aCPx, aCPy ),
  18097. new Vector2( aX, aY )
  18098. );
  18099. this.curves.push( curve );
  18100. this.currentPoint.set( aX, aY );
  18101. return this;
  18102. }
  18103. /**
  18104. * Adds an instance of {@link CubicBezierCurve} to the path by connecting
  18105. * the current point with the given one.
  18106. *
  18107. * @param {number} aCP1x - The x coordinate of the first control point.
  18108. * @param {number} aCP1y - The y coordinate of the first control point.
  18109. * @param {number} aCP2x - The x coordinate of the second control point.
  18110. * @param {number} aCP2y - The y coordinate of the second control point.
  18111. * @param {number} aX - The x coordinate of the end point.
  18112. * @param {number} aY - The y coordinate of the end point.
  18113. * @return {Path} A reference to this path.
  18114. */
  18115. bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) {
  18116. const curve = new CubicBezierCurve(
  18117. this.currentPoint.clone(),
  18118. new Vector2( aCP1x, aCP1y ),
  18119. new Vector2( aCP2x, aCP2y ),
  18120. new Vector2( aX, aY )
  18121. );
  18122. this.curves.push( curve );
  18123. this.currentPoint.set( aX, aY );
  18124. return this;
  18125. }
  18126. /**
  18127. * Adds an instance of {@link SplineCurve} to the path by connecting
  18128. * the current point with the given list of points.
  18129. *
  18130. * @param {Array<Vector2>} pts - An array of points in 2D space.
  18131. * @return {Path} A reference to this path.
  18132. */
  18133. splineThru( pts ) {
  18134. const npts = [ this.currentPoint.clone() ].concat( pts );
  18135. const curve = new SplineCurve( npts );
  18136. this.curves.push( curve );
  18137. this.currentPoint.copy( pts[ pts.length - 1 ] );
  18138. return this;
  18139. }
  18140. /**
  18141. * Adds an arc as an instance of {@link EllipseCurve} to the path, positioned relative
  18142. * to the current point.
  18143. *
  18144. * @param {number} aX - The x coordinate of the center of the arc offsetted from the previous curve.
  18145. * @param {number} aY - The y coordinate of the center of the arc offsetted from the previous curve.
  18146. * @param {number} aRadius - The radius of the arc.
  18147. * @param {number} aStartAngle - The start angle in radians.
  18148. * @param {number} aEndAngle - The end angle in radians.
  18149. * @param {boolean} [aClockwise=false] - Whether to sweep the arc clockwise or not.
  18150. * @return {Path} A reference to this path.
  18151. */
  18152. arc( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  18153. const x0 = this.currentPoint.x;
  18154. const y0 = this.currentPoint.y;
  18155. this.absarc( aX + x0, aY + y0, aRadius,
  18156. aStartAngle, aEndAngle, aClockwise );
  18157. return this;
  18158. }
  18159. /**
  18160. * Adds an absolutely positioned arc as an instance of {@link EllipseCurve} to the path.
  18161. *
  18162. * @param {number} aX - The x coordinate of the center of the arc.
  18163. * @param {number} aY - The y coordinate of the center of the arc.
  18164. * @param {number} aRadius - The radius of the arc.
  18165. * @param {number} aStartAngle - The start angle in radians.
  18166. * @param {number} aEndAngle - The end angle in radians.
  18167. * @param {boolean} [aClockwise=false] - Whether to sweep the arc clockwise or not.
  18168. * @return {Path} A reference to this path.
  18169. */
  18170. absarc( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  18171. this.absellipse( aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  18172. return this;
  18173. }
  18174. /**
  18175. * Adds an ellipse as an instance of {@link EllipseCurve} to the path, positioned relative
  18176. * to the current point
  18177. *
  18178. * @param {number} aX - The x coordinate of the center of the ellipse offsetted from the previous curve.
  18179. * @param {number} aY - The y coordinate of the center of the ellipse offsetted from the previous curve.
  18180. * @param {number} xRadius - The radius of the ellipse in the x axis.
  18181. * @param {number} yRadius - The radius of the ellipse in the y axis.
  18182. * @param {number} aStartAngle - The start angle in radians.
  18183. * @param {number} aEndAngle - The end angle in radians.
  18184. * @param {boolean} [aClockwise=false] - Whether to sweep the ellipse clockwise or not.
  18185. * @param {boolean} [aRotation=0] - The rotation angle of the ellipse in radians, counterclockwise from the positive X axis.
  18186. * @return {Path} A reference to this path.
  18187. */
  18188. ellipse( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  18189. const x0 = this.currentPoint.x;
  18190. const y0 = this.currentPoint.y;
  18191. this.absellipse( aX + x0, aY + y0, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation );
  18192. return this;
  18193. }
  18194. /**
  18195. * Adds an absolutely positioned ellipse as an instance of {@link EllipseCurve} to the path.
  18196. *
  18197. * @param {number} aX - The x coordinate of the absolute center of the ellipse.
  18198. * @param {number} aY - The y coordinate of the absolute center of the ellipse.
  18199. * @param {number} xRadius - The radius of the ellipse in the x axis.
  18200. * @param {number} yRadius - The radius of the ellipse in the y axis.
  18201. * @param {number} aStartAngle - The start angle in radians.
  18202. * @param {number} aEndAngle - The end angle in radians.
  18203. * @param {boolean} [aClockwise=false] - Whether to sweep the ellipse clockwise or not.
  18204. * @param {boolean} [aRotation=0] - The rotation angle of the ellipse in radians, counterclockwise from the positive X axis.
  18205. * @return {Path} A reference to this path.
  18206. */
  18207. absellipse( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  18208. const curve = new EllipseCurve( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation );
  18209. if ( this.curves.length > 0 ) {
  18210. // if a previous curve is present, attempt to join
  18211. const firstPoint = curve.getPoint( 0 );
  18212. if ( ! firstPoint.equals( this.currentPoint ) ) {
  18213. this.lineTo( firstPoint.x, firstPoint.y );
  18214. }
  18215. }
  18216. this.curves.push( curve );
  18217. const lastPoint = curve.getPoint( 1 );
  18218. this.currentPoint.copy( lastPoint );
  18219. return this;
  18220. }
  18221. copy( source ) {
  18222. super.copy( source );
  18223. this.currentPoint.copy( source.currentPoint );
  18224. return this;
  18225. }
  18226. toJSON() {
  18227. const data = super.toJSON();
  18228. data.currentPoint = this.currentPoint.toArray();
  18229. return data;
  18230. }
  18231. fromJSON( json ) {
  18232. super.fromJSON( json );
  18233. this.currentPoint.fromArray( json.currentPoint );
  18234. return this;
  18235. }
  18236. }
  18237. class LatheGeometry extends BufferGeometry {
  18238. 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 ) {
  18239. super();
  18240. this.type = 'LatheGeometry';
  18241. this.parameters = {
  18242. points: points,
  18243. segments: segments,
  18244. phiStart: phiStart,
  18245. phiLength: phiLength
  18246. };
  18247. segments = Math.floor( segments );
  18248. // clamp phiLength so it's in range of [ 0, 2PI ]
  18249. phiLength = clamp( phiLength, 0, Math.PI * 2 );
  18250. // buffers
  18251. const indices = [];
  18252. const vertices = [];
  18253. const uvs = [];
  18254. const initNormals = [];
  18255. const normals = [];
  18256. // helper variables
  18257. const inverseSegments = 1.0 / segments;
  18258. const vertex = new Vector3();
  18259. const uv = new Vector2();
  18260. const normal = new Vector3();
  18261. const curNormal = new Vector3();
  18262. const prevNormal = new Vector3();
  18263. let dx = 0;
  18264. let dy = 0;
  18265. // pre-compute normals for initial "meridian"
  18266. for ( let j = 0; j <= ( points.length - 1 ); j ++ ) {
  18267. switch ( j ) {
  18268. case 0: // special handling for 1st vertex on path
  18269. dx = points[ j + 1 ].x - points[ j ].x;
  18270. dy = points[ j + 1 ].y - points[ j ].y;
  18271. normal.x = dy * 1.0;
  18272. normal.y = - dx;
  18273. normal.z = dy * 0.0;
  18274. prevNormal.copy( normal );
  18275. normal.normalize();
  18276. initNormals.push( normal.x, normal.y, normal.z );
  18277. break;
  18278. case ( points.length - 1 ): // special handling for last Vertex on path
  18279. initNormals.push( prevNormal.x, prevNormal.y, prevNormal.z );
  18280. break;
  18281. default: // default handling for all vertices in between
  18282. dx = points[ j + 1 ].x - points[ j ].x;
  18283. dy = points[ j + 1 ].y - points[ j ].y;
  18284. normal.x = dy * 1.0;
  18285. normal.y = - dx;
  18286. normal.z = dy * 0.0;
  18287. curNormal.copy( normal );
  18288. normal.x += prevNormal.x;
  18289. normal.y += prevNormal.y;
  18290. normal.z += prevNormal.z;
  18291. normal.normalize();
  18292. initNormals.push( normal.x, normal.y, normal.z );
  18293. prevNormal.copy( curNormal );
  18294. }
  18295. }
  18296. // generate vertices, uvs and normals
  18297. for ( let i = 0; i <= segments; i ++ ) {
  18298. const phi = phiStart + i * inverseSegments * phiLength;
  18299. const sin = Math.sin( phi );
  18300. const cos = Math.cos( phi );
  18301. for ( let j = 0; j <= ( points.length - 1 ); j ++ ) {
  18302. // vertex
  18303. vertex.x = points[ j ].x * sin;
  18304. vertex.y = points[ j ].y;
  18305. vertex.z = points[ j ].x * cos;
  18306. vertices.push( vertex.x, vertex.y, vertex.z );
  18307. // uv
  18308. uv.x = i / segments;
  18309. uv.y = j / ( points.length - 1 );
  18310. uvs.push( uv.x, uv.y );
  18311. // normal
  18312. const x = initNormals[ 3 * j + 0 ] * sin;
  18313. const y = initNormals[ 3 * j + 1 ];
  18314. const z = initNormals[ 3 * j + 0 ] * cos;
  18315. normals.push( x, y, z );
  18316. }
  18317. }
  18318. // indices
  18319. for ( let i = 0; i < segments; i ++ ) {
  18320. for ( let j = 0; j < ( points.length - 1 ); j ++ ) {
  18321. const base = j + i * points.length;
  18322. const a = base;
  18323. const b = base + points.length;
  18324. const c = base + points.length + 1;
  18325. const d = base + 1;
  18326. // faces
  18327. indices.push( a, b, d );
  18328. indices.push( c, d, b );
  18329. }
  18330. }
  18331. // build geometry
  18332. this.setIndex( indices );
  18333. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  18334. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  18335. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  18336. }
  18337. copy( source ) {
  18338. super.copy( source );
  18339. this.parameters = Object.assign( {}, source.parameters );
  18340. return this;
  18341. }
  18342. static fromJSON( data ) {
  18343. return new LatheGeometry( data.points, data.segments, data.phiStart, data.phiLength );
  18344. }
  18345. }
  18346. class CapsuleGeometry extends LatheGeometry {
  18347. constructor( radius = 1, length = 1, capSegments = 4, radialSegments = 8 ) {
  18348. const path = new Path();
  18349. path.absarc( 0, - length / 2, radius, Math.PI * 1.5, 0 );
  18350. path.absarc( 0, length / 2, radius, 0, Math.PI * 0.5 );
  18351. super( path.getPoints( capSegments ), radialSegments );
  18352. this.type = 'CapsuleGeometry';
  18353. this.parameters = {
  18354. radius: radius,
  18355. length: length,
  18356. capSegments: capSegments,
  18357. radialSegments: radialSegments,
  18358. };
  18359. }
  18360. static fromJSON( data ) {
  18361. return new CapsuleGeometry( data.radius, data.length, data.capSegments, data.radialSegments );
  18362. }
  18363. }
  18364. class CircleGeometry extends BufferGeometry {
  18365. constructor( radius = 1, segments = 32, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  18366. super();
  18367. this.type = 'CircleGeometry';
  18368. this.parameters = {
  18369. radius: radius,
  18370. segments: segments,
  18371. thetaStart: thetaStart,
  18372. thetaLength: thetaLength
  18373. };
  18374. segments = Math.max( 3, segments );
  18375. // buffers
  18376. const indices = [];
  18377. const vertices = [];
  18378. const normals = [];
  18379. const uvs = [];
  18380. // helper variables
  18381. const vertex = new Vector3();
  18382. const uv = new Vector2();
  18383. // center point
  18384. vertices.push( 0, 0, 0 );
  18385. normals.push( 0, 0, 1 );
  18386. uvs.push( 0.5, 0.5 );
  18387. for ( let s = 0, i = 3; s <= segments; s ++, i += 3 ) {
  18388. const segment = thetaStart + s / segments * thetaLength;
  18389. // vertex
  18390. vertex.x = radius * Math.cos( segment );
  18391. vertex.y = radius * Math.sin( segment );
  18392. vertices.push( vertex.x, vertex.y, vertex.z );
  18393. // normal
  18394. normals.push( 0, 0, 1 );
  18395. // uvs
  18396. uv.x = ( vertices[ i ] / radius + 1 ) / 2;
  18397. uv.y = ( vertices[ i + 1 ] / radius + 1 ) / 2;
  18398. uvs.push( uv.x, uv.y );
  18399. }
  18400. // indices
  18401. for ( let i = 1; i <= segments; i ++ ) {
  18402. indices.push( i, i + 1, 0 );
  18403. }
  18404. // build geometry
  18405. this.setIndex( indices );
  18406. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  18407. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  18408. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  18409. }
  18410. copy( source ) {
  18411. super.copy( source );
  18412. this.parameters = Object.assign( {}, source.parameters );
  18413. return this;
  18414. }
  18415. static fromJSON( data ) {
  18416. return new CircleGeometry( data.radius, data.segments, data.thetaStart, data.thetaLength );
  18417. }
  18418. }
  18419. class CylinderGeometry extends BufferGeometry {
  18420. constructor( radiusTop = 1, radiusBottom = 1, height = 1, radialSegments = 32, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  18421. super();
  18422. this.type = 'CylinderGeometry';
  18423. this.parameters = {
  18424. radiusTop: radiusTop,
  18425. radiusBottom: radiusBottom,
  18426. height: height,
  18427. radialSegments: radialSegments,
  18428. heightSegments: heightSegments,
  18429. openEnded: openEnded,
  18430. thetaStart: thetaStart,
  18431. thetaLength: thetaLength
  18432. };
  18433. const scope = this;
  18434. radialSegments = Math.floor( radialSegments );
  18435. heightSegments = Math.floor( heightSegments );
  18436. // buffers
  18437. const indices = [];
  18438. const vertices = [];
  18439. const normals = [];
  18440. const uvs = [];
  18441. // helper variables
  18442. let index = 0;
  18443. const indexArray = [];
  18444. const halfHeight = height / 2;
  18445. let groupStart = 0;
  18446. // generate geometry
  18447. generateTorso();
  18448. if ( openEnded === false ) {
  18449. if ( radiusTop > 0 ) generateCap( true );
  18450. if ( radiusBottom > 0 ) generateCap( false );
  18451. }
  18452. // build geometry
  18453. this.setIndex( indices );
  18454. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  18455. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  18456. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  18457. function generateTorso() {
  18458. const normal = new Vector3();
  18459. const vertex = new Vector3();
  18460. let groupCount = 0;
  18461. // this will be used to calculate the normal
  18462. const slope = ( radiusBottom - radiusTop ) / height;
  18463. // generate vertices, normals and uvs
  18464. for ( let y = 0; y <= heightSegments; y ++ ) {
  18465. const indexRow = [];
  18466. const v = y / heightSegments;
  18467. // calculate the radius of the current row
  18468. const radius = v * ( radiusBottom - radiusTop ) + radiusTop;
  18469. for ( let x = 0; x <= radialSegments; x ++ ) {
  18470. const u = x / radialSegments;
  18471. const theta = u * thetaLength + thetaStart;
  18472. const sinTheta = Math.sin( theta );
  18473. const cosTheta = Math.cos( theta );
  18474. // vertex
  18475. vertex.x = radius * sinTheta;
  18476. vertex.y = - v * height + halfHeight;
  18477. vertex.z = radius * cosTheta;
  18478. vertices.push( vertex.x, vertex.y, vertex.z );
  18479. // normal
  18480. normal.set( sinTheta, slope, cosTheta ).normalize();
  18481. normals.push( normal.x, normal.y, normal.z );
  18482. // uv
  18483. uvs.push( u, 1 - v );
  18484. // save index of vertex in respective row
  18485. indexRow.push( index ++ );
  18486. }
  18487. // now save vertices of the row in our index array
  18488. indexArray.push( indexRow );
  18489. }
  18490. // generate indices
  18491. for ( let x = 0; x < radialSegments; x ++ ) {
  18492. for ( let y = 0; y < heightSegments; y ++ ) {
  18493. // we use the index array to access the correct indices
  18494. const a = indexArray[ y ][ x ];
  18495. const b = indexArray[ y + 1 ][ x ];
  18496. const c = indexArray[ y + 1 ][ x + 1 ];
  18497. const d = indexArray[ y ][ x + 1 ];
  18498. // faces
  18499. if ( radiusTop > 0 || y !== 0 ) {
  18500. indices.push( a, b, d );
  18501. groupCount += 3;
  18502. }
  18503. if ( radiusBottom > 0 || y !== heightSegments - 1 ) {
  18504. indices.push( b, c, d );
  18505. groupCount += 3;
  18506. }
  18507. }
  18508. }
  18509. // add a group to the geometry. this will ensure multi material support
  18510. scope.addGroup( groupStart, groupCount, 0 );
  18511. // calculate new start value for groups
  18512. groupStart += groupCount;
  18513. }
  18514. function generateCap( top ) {
  18515. // save the index of the first center vertex
  18516. const centerIndexStart = index;
  18517. const uv = new Vector2();
  18518. const vertex = new Vector3();
  18519. let groupCount = 0;
  18520. const radius = ( top === true ) ? radiusTop : radiusBottom;
  18521. const sign = ( top === true ) ? 1 : -1;
  18522. // first we generate the center vertex data of the cap.
  18523. // because the geometry needs one set of uvs per face,
  18524. // we must generate a center vertex per face/segment
  18525. for ( let x = 1; x <= radialSegments; x ++ ) {
  18526. // vertex
  18527. vertices.push( 0, halfHeight * sign, 0 );
  18528. // normal
  18529. normals.push( 0, sign, 0 );
  18530. // uv
  18531. uvs.push( 0.5, 0.5 );
  18532. // increase index
  18533. index ++;
  18534. }
  18535. // save the index of the last center vertex
  18536. const centerIndexEnd = index;
  18537. // now we generate the surrounding vertices, normals and uvs
  18538. for ( let x = 0; x <= radialSegments; x ++ ) {
  18539. const u = x / radialSegments;
  18540. const theta = u * thetaLength + thetaStart;
  18541. const cosTheta = Math.cos( theta );
  18542. const sinTheta = Math.sin( theta );
  18543. // vertex
  18544. vertex.x = radius * sinTheta;
  18545. vertex.y = halfHeight * sign;
  18546. vertex.z = radius * cosTheta;
  18547. vertices.push( vertex.x, vertex.y, vertex.z );
  18548. // normal
  18549. normals.push( 0, sign, 0 );
  18550. // uv
  18551. uv.x = ( cosTheta * 0.5 ) + 0.5;
  18552. uv.y = ( sinTheta * 0.5 * sign ) + 0.5;
  18553. uvs.push( uv.x, uv.y );
  18554. // increase index
  18555. index ++;
  18556. }
  18557. // generate indices
  18558. for ( let x = 0; x < radialSegments; x ++ ) {
  18559. const c = centerIndexStart + x;
  18560. const i = centerIndexEnd + x;
  18561. if ( top === true ) {
  18562. // face top
  18563. indices.push( i, i + 1, c );
  18564. } else {
  18565. // face bottom
  18566. indices.push( i + 1, i, c );
  18567. }
  18568. groupCount += 3;
  18569. }
  18570. // add a group to the geometry. this will ensure multi material support
  18571. scope.addGroup( groupStart, groupCount, top === true ? 1 : 2 );
  18572. // calculate new start value for groups
  18573. groupStart += groupCount;
  18574. }
  18575. }
  18576. copy( source ) {
  18577. super.copy( source );
  18578. this.parameters = Object.assign( {}, source.parameters );
  18579. return this;
  18580. }
  18581. static fromJSON( data ) {
  18582. return new CylinderGeometry( data.radiusTop, data.radiusBottom, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength );
  18583. }
  18584. }
  18585. class ConeGeometry extends CylinderGeometry {
  18586. constructor( radius = 1, height = 1, radialSegments = 32, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  18587. super( 0, radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength );
  18588. this.type = 'ConeGeometry';
  18589. this.parameters = {
  18590. radius: radius,
  18591. height: height,
  18592. radialSegments: radialSegments,
  18593. heightSegments: heightSegments,
  18594. openEnded: openEnded,
  18595. thetaStart: thetaStart,
  18596. thetaLength: thetaLength
  18597. };
  18598. }
  18599. static fromJSON( data ) {
  18600. return new ConeGeometry( data.radius, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength );
  18601. }
  18602. }
  18603. class PolyhedronGeometry extends BufferGeometry {
  18604. constructor( vertices = [], indices = [], radius = 1, detail = 0 ) {
  18605. super();
  18606. this.type = 'PolyhedronGeometry';
  18607. this.parameters = {
  18608. vertices: vertices,
  18609. indices: indices,
  18610. radius: radius,
  18611. detail: detail
  18612. };
  18613. // default buffer data
  18614. const vertexBuffer = [];
  18615. const uvBuffer = [];
  18616. // the subdivision creates the vertex buffer data
  18617. subdivide( detail );
  18618. // all vertices should lie on a conceptual sphere with a given radius
  18619. applyRadius( radius );
  18620. // finally, create the uv data
  18621. generateUVs();
  18622. // build non-indexed geometry
  18623. this.setAttribute( 'position', new Float32BufferAttribute( vertexBuffer, 3 ) );
  18624. this.setAttribute( 'normal', new Float32BufferAttribute( vertexBuffer.slice(), 3 ) );
  18625. this.setAttribute( 'uv', new Float32BufferAttribute( uvBuffer, 2 ) );
  18626. if ( detail === 0 ) {
  18627. this.computeVertexNormals(); // flat normals
  18628. } else {
  18629. this.normalizeNormals(); // smooth normals
  18630. }
  18631. // helper functions
  18632. function subdivide( detail ) {
  18633. const a = new Vector3();
  18634. const b = new Vector3();
  18635. const c = new Vector3();
  18636. // iterate over all faces and apply a subdivision with the given detail value
  18637. for ( let i = 0; i < indices.length; i += 3 ) {
  18638. // get the vertices of the face
  18639. getVertexByIndex( indices[ i + 0 ], a );
  18640. getVertexByIndex( indices[ i + 1 ], b );
  18641. getVertexByIndex( indices[ i + 2 ], c );
  18642. // perform subdivision
  18643. subdivideFace( a, b, c, detail );
  18644. }
  18645. }
  18646. function subdivideFace( a, b, c, detail ) {
  18647. const cols = detail + 1;
  18648. // we use this multidimensional array as a data structure for creating the subdivision
  18649. const v = [];
  18650. // construct all of the vertices for this subdivision
  18651. for ( let i = 0; i <= cols; i ++ ) {
  18652. v[ i ] = [];
  18653. const aj = a.clone().lerp( c, i / cols );
  18654. const bj = b.clone().lerp( c, i / cols );
  18655. const rows = cols - i;
  18656. for ( let j = 0; j <= rows; j ++ ) {
  18657. if ( j === 0 && i === cols ) {
  18658. v[ i ][ j ] = aj;
  18659. } else {
  18660. v[ i ][ j ] = aj.clone().lerp( bj, j / rows );
  18661. }
  18662. }
  18663. }
  18664. // construct all of the faces
  18665. for ( let i = 0; i < cols; i ++ ) {
  18666. for ( let j = 0; j < 2 * ( cols - i ) - 1; j ++ ) {
  18667. const k = Math.floor( j / 2 );
  18668. if ( j % 2 === 0 ) {
  18669. pushVertex( v[ i ][ k + 1 ] );
  18670. pushVertex( v[ i + 1 ][ k ] );
  18671. pushVertex( v[ i ][ k ] );
  18672. } else {
  18673. pushVertex( v[ i ][ k + 1 ] );
  18674. pushVertex( v[ i + 1 ][ k + 1 ] );
  18675. pushVertex( v[ i + 1 ][ k ] );
  18676. }
  18677. }
  18678. }
  18679. }
  18680. function applyRadius( radius ) {
  18681. const vertex = new Vector3();
  18682. // iterate over the entire buffer and apply the radius to each vertex
  18683. for ( let i = 0; i < vertexBuffer.length; i += 3 ) {
  18684. vertex.x = vertexBuffer[ i + 0 ];
  18685. vertex.y = vertexBuffer[ i + 1 ];
  18686. vertex.z = vertexBuffer[ i + 2 ];
  18687. vertex.normalize().multiplyScalar( radius );
  18688. vertexBuffer[ i + 0 ] = vertex.x;
  18689. vertexBuffer[ i + 1 ] = vertex.y;
  18690. vertexBuffer[ i + 2 ] = vertex.z;
  18691. }
  18692. }
  18693. function generateUVs() {
  18694. const vertex = new Vector3();
  18695. for ( let i = 0; i < vertexBuffer.length; i += 3 ) {
  18696. vertex.x = vertexBuffer[ i + 0 ];
  18697. vertex.y = vertexBuffer[ i + 1 ];
  18698. vertex.z = vertexBuffer[ i + 2 ];
  18699. const u = azimuth( vertex ) / 2 / Math.PI + 0.5;
  18700. const v = inclination( vertex ) / Math.PI + 0.5;
  18701. uvBuffer.push( u, 1 - v );
  18702. }
  18703. correctUVs();
  18704. correctSeam();
  18705. }
  18706. function correctSeam() {
  18707. // handle case when face straddles the seam, see #3269
  18708. for ( let i = 0; i < uvBuffer.length; i += 6 ) {
  18709. // uv data of a single face
  18710. const x0 = uvBuffer[ i + 0 ];
  18711. const x1 = uvBuffer[ i + 2 ];
  18712. const x2 = uvBuffer[ i + 4 ];
  18713. const max = Math.max( x0, x1, x2 );
  18714. const min = Math.min( x0, x1, x2 );
  18715. // 0.9 is somewhat arbitrary
  18716. if ( max > 0.9 && min < 0.1 ) {
  18717. if ( x0 < 0.2 ) uvBuffer[ i + 0 ] += 1;
  18718. if ( x1 < 0.2 ) uvBuffer[ i + 2 ] += 1;
  18719. if ( x2 < 0.2 ) uvBuffer[ i + 4 ] += 1;
  18720. }
  18721. }
  18722. }
  18723. function pushVertex( vertex ) {
  18724. vertexBuffer.push( vertex.x, vertex.y, vertex.z );
  18725. }
  18726. function getVertexByIndex( index, vertex ) {
  18727. const stride = index * 3;
  18728. vertex.x = vertices[ stride + 0 ];
  18729. vertex.y = vertices[ stride + 1 ];
  18730. vertex.z = vertices[ stride + 2 ];
  18731. }
  18732. function correctUVs() {
  18733. const a = new Vector3();
  18734. const b = new Vector3();
  18735. const c = new Vector3();
  18736. const centroid = new Vector3();
  18737. const uvA = new Vector2();
  18738. const uvB = new Vector2();
  18739. const uvC = new Vector2();
  18740. for ( let i = 0, j = 0; i < vertexBuffer.length; i += 9, j += 6 ) {
  18741. a.set( vertexBuffer[ i + 0 ], vertexBuffer[ i + 1 ], vertexBuffer[ i + 2 ] );
  18742. b.set( vertexBuffer[ i + 3 ], vertexBuffer[ i + 4 ], vertexBuffer[ i + 5 ] );
  18743. c.set( vertexBuffer[ i + 6 ], vertexBuffer[ i + 7 ], vertexBuffer[ i + 8 ] );
  18744. uvA.set( uvBuffer[ j + 0 ], uvBuffer[ j + 1 ] );
  18745. uvB.set( uvBuffer[ j + 2 ], uvBuffer[ j + 3 ] );
  18746. uvC.set( uvBuffer[ j + 4 ], uvBuffer[ j + 5 ] );
  18747. centroid.copy( a ).add( b ).add( c ).divideScalar( 3 );
  18748. const azi = azimuth( centroid );
  18749. correctUV( uvA, j + 0, a, azi );
  18750. correctUV( uvB, j + 2, b, azi );
  18751. correctUV( uvC, j + 4, c, azi );
  18752. }
  18753. }
  18754. function correctUV( uv, stride, vector, azimuth ) {
  18755. if ( ( azimuth < 0 ) && ( uv.x === 1 ) ) {
  18756. uvBuffer[ stride ] = uv.x - 1;
  18757. }
  18758. if ( ( vector.x === 0 ) && ( vector.z === 0 ) ) {
  18759. uvBuffer[ stride ] = azimuth / 2 / Math.PI + 0.5;
  18760. }
  18761. }
  18762. // Angle around the Y axis, counter-clockwise when looking from above.
  18763. function azimuth( vector ) {
  18764. return Math.atan2( vector.z, - vector.x );
  18765. }
  18766. // Angle above the XZ plane.
  18767. function inclination( vector ) {
  18768. return Math.atan2( - vector.y, Math.sqrt( ( vector.x * vector.x ) + ( vector.z * vector.z ) ) );
  18769. }
  18770. }
  18771. copy( source ) {
  18772. super.copy( source );
  18773. this.parameters = Object.assign( {}, source.parameters );
  18774. return this;
  18775. }
  18776. static fromJSON( data ) {
  18777. return new PolyhedronGeometry( data.vertices, data.indices, data.radius, data.details );
  18778. }
  18779. }
  18780. class DodecahedronGeometry extends PolyhedronGeometry {
  18781. constructor( radius = 1, detail = 0 ) {
  18782. const t = ( 1 + Math.sqrt( 5 ) ) / 2;
  18783. const r = 1 / t;
  18784. const vertices = [
  18785. // (±1, ±1, ±1)
  18786. -1, -1, -1, -1, -1, 1,
  18787. -1, 1, -1, -1, 1, 1,
  18788. 1, -1, -1, 1, -1, 1,
  18789. 1, 1, -1, 1, 1, 1,
  18790. // (0, ±1/φ, ±φ)
  18791. 0, - r, - t, 0, - r, t,
  18792. 0, r, - t, 0, r, t,
  18793. // (±1/φ, ±φ, 0)
  18794. - r, - t, 0, - r, t, 0,
  18795. r, - t, 0, r, t, 0,
  18796. // (±φ, 0, ±1/φ)
  18797. - t, 0, - r, t, 0, - r,
  18798. - t, 0, r, t, 0, r
  18799. ];
  18800. const indices = [
  18801. 3, 11, 7, 3, 7, 15, 3, 15, 13,
  18802. 7, 19, 17, 7, 17, 6, 7, 6, 15,
  18803. 17, 4, 8, 17, 8, 10, 17, 10, 6,
  18804. 8, 0, 16, 8, 16, 2, 8, 2, 10,
  18805. 0, 12, 1, 0, 1, 18, 0, 18, 16,
  18806. 6, 10, 2, 6, 2, 13, 6, 13, 15,
  18807. 2, 16, 18, 2, 18, 3, 2, 3, 13,
  18808. 18, 1, 9, 18, 9, 11, 18, 11, 3,
  18809. 4, 14, 12, 4, 12, 0, 4, 0, 8,
  18810. 11, 9, 5, 11, 5, 19, 11, 19, 7,
  18811. 19, 5, 14, 19, 14, 4, 19, 4, 17,
  18812. 1, 12, 14, 1, 14, 5, 1, 5, 9
  18813. ];
  18814. super( vertices, indices, radius, detail );
  18815. this.type = 'DodecahedronGeometry';
  18816. this.parameters = {
  18817. radius: radius,
  18818. detail: detail
  18819. };
  18820. }
  18821. static fromJSON( data ) {
  18822. return new DodecahedronGeometry( data.radius, data.detail );
  18823. }
  18824. }
  18825. const _v0 = /*@__PURE__*/ new Vector3();
  18826. const _v1$1 = /*@__PURE__*/ new Vector3();
  18827. const _normal = /*@__PURE__*/ new Vector3();
  18828. const _triangle = /*@__PURE__*/ new Triangle();
  18829. class EdgesGeometry extends BufferGeometry {
  18830. constructor( geometry = null, thresholdAngle = 1 ) {
  18831. super();
  18832. this.type = 'EdgesGeometry';
  18833. this.parameters = {
  18834. geometry: geometry,
  18835. thresholdAngle: thresholdAngle
  18836. };
  18837. if ( geometry !== null ) {
  18838. const precisionPoints = 4;
  18839. const precision = Math.pow( 10, precisionPoints );
  18840. const thresholdDot = Math.cos( DEG2RAD * thresholdAngle );
  18841. const indexAttr = geometry.getIndex();
  18842. const positionAttr = geometry.getAttribute( 'position' );
  18843. const indexCount = indexAttr ? indexAttr.count : positionAttr.count;
  18844. const indexArr = [ 0, 0, 0 ];
  18845. const vertKeys = [ 'a', 'b', 'c' ];
  18846. const hashes = new Array( 3 );
  18847. const edgeData = {};
  18848. const vertices = [];
  18849. for ( let i = 0; i < indexCount; i += 3 ) {
  18850. if ( indexAttr ) {
  18851. indexArr[ 0 ] = indexAttr.getX( i );
  18852. indexArr[ 1 ] = indexAttr.getX( i + 1 );
  18853. indexArr[ 2 ] = indexAttr.getX( i + 2 );
  18854. } else {
  18855. indexArr[ 0 ] = i;
  18856. indexArr[ 1 ] = i + 1;
  18857. indexArr[ 2 ] = i + 2;
  18858. }
  18859. const { a, b, c } = _triangle;
  18860. a.fromBufferAttribute( positionAttr, indexArr[ 0 ] );
  18861. b.fromBufferAttribute( positionAttr, indexArr[ 1 ] );
  18862. c.fromBufferAttribute( positionAttr, indexArr[ 2 ] );
  18863. _triangle.getNormal( _normal );
  18864. // create hashes for the edge from the vertices
  18865. hashes[ 0 ] = `${ Math.round( a.x * precision ) },${ Math.round( a.y * precision ) },${ Math.round( a.z * precision ) }`;
  18866. hashes[ 1 ] = `${ Math.round( b.x * precision ) },${ Math.round( b.y * precision ) },${ Math.round( b.z * precision ) }`;
  18867. hashes[ 2 ] = `${ Math.round( c.x * precision ) },${ Math.round( c.y * precision ) },${ Math.round( c.z * precision ) }`;
  18868. // skip degenerate triangles
  18869. if ( hashes[ 0 ] === hashes[ 1 ] || hashes[ 1 ] === hashes[ 2 ] || hashes[ 2 ] === hashes[ 0 ] ) {
  18870. continue;
  18871. }
  18872. // iterate over every edge
  18873. for ( let j = 0; j < 3; j ++ ) {
  18874. // get the first and next vertex making up the edge
  18875. const jNext = ( j + 1 ) % 3;
  18876. const vecHash0 = hashes[ j ];
  18877. const vecHash1 = hashes[ jNext ];
  18878. const v0 = _triangle[ vertKeys[ j ] ];
  18879. const v1 = _triangle[ vertKeys[ jNext ] ];
  18880. const hash = `${ vecHash0 }_${ vecHash1 }`;
  18881. const reverseHash = `${ vecHash1 }_${ vecHash0 }`;
  18882. if ( reverseHash in edgeData && edgeData[ reverseHash ] ) {
  18883. // if we found a sibling edge add it into the vertex array if
  18884. // it meets the angle threshold and delete the edge from the map.
  18885. if ( _normal.dot( edgeData[ reverseHash ].normal ) <= thresholdDot ) {
  18886. vertices.push( v0.x, v0.y, v0.z );
  18887. vertices.push( v1.x, v1.y, v1.z );
  18888. }
  18889. edgeData[ reverseHash ] = null;
  18890. } else if ( ! ( hash in edgeData ) ) {
  18891. // if we've already got an edge here then skip adding a new one
  18892. edgeData[ hash ] = {
  18893. index0: indexArr[ j ],
  18894. index1: indexArr[ jNext ],
  18895. normal: _normal.clone(),
  18896. };
  18897. }
  18898. }
  18899. }
  18900. // iterate over all remaining, unmatched edges and add them to the vertex array
  18901. for ( const key in edgeData ) {
  18902. if ( edgeData[ key ] ) {
  18903. const { index0, index1 } = edgeData[ key ];
  18904. _v0.fromBufferAttribute( positionAttr, index0 );
  18905. _v1$1.fromBufferAttribute( positionAttr, index1 );
  18906. vertices.push( _v0.x, _v0.y, _v0.z );
  18907. vertices.push( _v1$1.x, _v1$1.y, _v1$1.z );
  18908. }
  18909. }
  18910. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  18911. }
  18912. }
  18913. copy( source ) {
  18914. super.copy( source );
  18915. this.parameters = Object.assign( {}, source.parameters );
  18916. return this;
  18917. }
  18918. }
  18919. /**
  18920. * Defines an arbitrary 2d shape plane using paths with optional holes. It
  18921. * can be used with {@link ExtrudeGeometry}, {@link ShapeGeometry}, to get
  18922. * points, or to get triangulated faces.
  18923. *
  18924. * ```js
  18925. * const heartShape = new THREE.Shape();
  18926. *
  18927. * heartShape.moveTo( 25, 25 );
  18928. * heartShape.bezierCurveTo( 25, 25, 20, 0, 0, 0 );
  18929. * heartShape.bezierCurveTo( - 30, 0, - 30, 35, - 30, 35 );
  18930. * heartShape.bezierCurveTo( - 30, 55, - 10, 77, 25, 95 );
  18931. * heartShape.bezierCurveTo( 60, 77, 80, 55, 80, 35 );
  18932. * heartShape.bezierCurveTo( 80, 35, 80, 0, 50, 0 );
  18933. * heartShape.bezierCurveTo( 35, 0, 25, 25, 25, 25 );
  18934. *
  18935. * const extrudeSettings = {
  18936. * depth: 8,
  18937. * bevelEnabled: true,
  18938. * bevelSegments: 2,
  18939. * steps: 2,
  18940. * bevelSize: 1,
  18941. * bevelThickness: 1
  18942. * };
  18943. *
  18944. * const geometry = new THREE.ExtrudeGeometry( heartShape, extrudeSettings );
  18945. * const mesh = new THREE.Mesh( geometry, new THREE.MeshBasicMaterial() );
  18946. * ```
  18947. *
  18948. * @augments Path
  18949. */
  18950. class Shape extends Path {
  18951. /**
  18952. * Constructs a new shape.
  18953. *
  18954. * @param {Array<Vector2>} [points] - An array of 2D points defining the shape.
  18955. */
  18956. constructor( points ) {
  18957. super( points );
  18958. /**
  18959. * The UUID of the shape.
  18960. *
  18961. * @type {string}
  18962. * @readonly
  18963. */
  18964. this.uuid = generateUUID();
  18965. this.type = 'Shape';
  18966. /**
  18967. * Defines the holes in the shape. Hole defnitions must use the
  18968. * opposite winding order (CW/CCW) than the outer shape.
  18969. *
  18970. * @type {Array<Path>}
  18971. * @readonly
  18972. */
  18973. this.holes = [];
  18974. }
  18975. /**
  18976. * Returns an array representing each contour of the holes
  18977. * as a list of 2D points.
  18978. *
  18979. * @param {number} divisions - The fineness of the result.
  18980. * @return {Array<Array<Vector2>>} The holes as a series of 2D points.
  18981. */
  18982. getPointsHoles( divisions ) {
  18983. const holesPts = [];
  18984. for ( let i = 0, l = this.holes.length; i < l; i ++ ) {
  18985. holesPts[ i ] = this.holes[ i ].getPoints( divisions );
  18986. }
  18987. return holesPts;
  18988. }
  18989. // get points of shape and holes (keypoints based on segments parameter)
  18990. /**
  18991. * Returns an object that holds contour data for the shape and its holes as
  18992. * arrays of 2D points.
  18993. *
  18994. * @param {number} divisions - The fineness of the result.
  18995. * @return {{shape:Array<Vector2>,holes:Array<Array<Vector2>>}} An object with contour data.
  18996. */
  18997. extractPoints( divisions ) {
  18998. return {
  18999. shape: this.getPoints( divisions ),
  19000. holes: this.getPointsHoles( divisions )
  19001. };
  19002. }
  19003. copy( source ) {
  19004. super.copy( source );
  19005. this.holes = [];
  19006. for ( let i = 0, l = source.holes.length; i < l; i ++ ) {
  19007. const hole = source.holes[ i ];
  19008. this.holes.push( hole.clone() );
  19009. }
  19010. return this;
  19011. }
  19012. toJSON() {
  19013. const data = super.toJSON();
  19014. data.uuid = this.uuid;
  19015. data.holes = [];
  19016. for ( let i = 0, l = this.holes.length; i < l; i ++ ) {
  19017. const hole = this.holes[ i ];
  19018. data.holes.push( hole.toJSON() );
  19019. }
  19020. return data;
  19021. }
  19022. fromJSON( json ) {
  19023. super.fromJSON( json );
  19024. this.uuid = json.uuid;
  19025. this.holes = [];
  19026. for ( let i = 0, l = json.holes.length; i < l; i ++ ) {
  19027. const hole = json.holes[ i ];
  19028. this.holes.push( new Path().fromJSON( hole ) );
  19029. }
  19030. return this;
  19031. }
  19032. }
  19033. /**
  19034. * An implementation of the earcut polygon triangulation algorithm. The code
  19035. * is a port of [mapbox/earcut]{@link https://github.com/mapbox/earcut mapbox/earcut} (v2.2.4).
  19036. *
  19037. * @hideconstructor
  19038. */
  19039. class Earcut {
  19040. /**
  19041. * Triangulates the given shape definition by returning an array of triangles.
  19042. *
  19043. * @param {Array<number>} data - An array with 2D points.
  19044. * @param {Array<number>} holeIndices - An array with indices defining holes.
  19045. * @param {number} [dim=2] - The number of coordinates per vertex in the input array.
  19046. * @return {Array<number>} An array representing the triangulated faces. Each face is defined by three consecutive numbers
  19047. * representing vertex indices.
  19048. */
  19049. static triangulate( data, holeIndices, dim = 2 ) {
  19050. const hasHoles = holeIndices && holeIndices.length;
  19051. const outerLen = hasHoles ? holeIndices[ 0 ] * dim : data.length;
  19052. let outerNode = linkedList( data, 0, outerLen, dim, true );
  19053. const triangles = [];
  19054. if ( ! outerNode || outerNode.next === outerNode.prev ) return triangles;
  19055. let minX, minY, maxX, maxY, x, y, invSize;
  19056. if ( hasHoles ) outerNode = eliminateHoles( data, holeIndices, outerNode, dim );
  19057. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  19058. if ( data.length > 80 * dim ) {
  19059. minX = maxX = data[ 0 ];
  19060. minY = maxY = data[ 1 ];
  19061. for ( let i = dim; i < outerLen; i += dim ) {
  19062. x = data[ i ];
  19063. y = data[ i + 1 ];
  19064. if ( x < minX ) minX = x;
  19065. if ( y < minY ) minY = y;
  19066. if ( x > maxX ) maxX = x;
  19067. if ( y > maxY ) maxY = y;
  19068. }
  19069. // minX, minY and invSize are later used to transform coords into integers for z-order calculation
  19070. invSize = Math.max( maxX - minX, maxY - minY );
  19071. invSize = invSize !== 0 ? 32767 / invSize : 0;
  19072. }
  19073. earcutLinked( outerNode, triangles, dim, minX, minY, invSize, 0 );
  19074. return triangles;
  19075. }
  19076. }
  19077. // create a circular doubly linked list from polygon points in the specified winding order
  19078. function linkedList( data, start, end, dim, clockwise ) {
  19079. let i, last;
  19080. if ( clockwise === ( signedArea( data, start, end, dim ) > 0 ) ) {
  19081. for ( i = start; i < end; i += dim ) last = insertNode( i, data[ i ], data[ i + 1 ], last );
  19082. } else {
  19083. for ( i = end - dim; i >= start; i -= dim ) last = insertNode( i, data[ i ], data[ i + 1 ], last );
  19084. }
  19085. if ( last && equals( last, last.next ) ) {
  19086. removeNode( last );
  19087. last = last.next;
  19088. }
  19089. return last;
  19090. }
  19091. // eliminate colinear or duplicate points
  19092. function filterPoints( start, end ) {
  19093. if ( ! start ) return start;
  19094. if ( ! end ) end = start;
  19095. let p = start,
  19096. again;
  19097. do {
  19098. again = false;
  19099. if ( ! p.steiner && ( equals( p, p.next ) || area( p.prev, p, p.next ) === 0 ) ) {
  19100. removeNode( p );
  19101. p = end = p.prev;
  19102. if ( p === p.next ) break;
  19103. again = true;
  19104. } else {
  19105. p = p.next;
  19106. }
  19107. } while ( again || p !== end );
  19108. return end;
  19109. }
  19110. // main ear slicing loop which triangulates a polygon (given as a linked list)
  19111. function earcutLinked( ear, triangles, dim, minX, minY, invSize, pass ) {
  19112. if ( ! ear ) return;
  19113. // interlink polygon nodes in z-order
  19114. if ( ! pass && invSize ) indexCurve( ear, minX, minY, invSize );
  19115. let stop = ear,
  19116. prev, next;
  19117. // iterate through ears, slicing them one by one
  19118. while ( ear.prev !== ear.next ) {
  19119. prev = ear.prev;
  19120. next = ear.next;
  19121. if ( invSize ? isEarHashed( ear, minX, minY, invSize ) : isEar( ear ) ) {
  19122. // cut off the triangle
  19123. triangles.push( prev.i / dim | 0 );
  19124. triangles.push( ear.i / dim | 0 );
  19125. triangles.push( next.i / dim | 0 );
  19126. removeNode( ear );
  19127. // skipping the next vertex leads to less sliver triangles
  19128. ear = next.next;
  19129. stop = next.next;
  19130. continue;
  19131. }
  19132. ear = next;
  19133. // if we looped through the whole remaining polygon and can't find any more ears
  19134. if ( ear === stop ) {
  19135. // try filtering points and slicing again
  19136. if ( ! pass ) {
  19137. earcutLinked( filterPoints( ear ), triangles, dim, minX, minY, invSize, 1 );
  19138. // if this didn't work, try curing all small self-intersections locally
  19139. } else if ( pass === 1 ) {
  19140. ear = cureLocalIntersections( filterPoints( ear ), triangles, dim );
  19141. earcutLinked( ear, triangles, dim, minX, minY, invSize, 2 );
  19142. // as a last resort, try splitting the remaining polygon into two
  19143. } else if ( pass === 2 ) {
  19144. splitEarcut( ear, triangles, dim, minX, minY, invSize );
  19145. }
  19146. break;
  19147. }
  19148. }
  19149. }
  19150. // check whether a polygon node forms a valid ear with adjacent nodes
  19151. function isEar( ear ) {
  19152. const a = ear.prev,
  19153. b = ear,
  19154. c = ear.next;
  19155. if ( area( a, b, c ) >= 0 ) return false; // reflex, can't be an ear
  19156. // now make sure we don't have other points inside the potential ear
  19157. const ax = a.x, bx = b.x, cx = c.x, ay = a.y, by = b.y, cy = c.y;
  19158. // triangle bbox; min & max are calculated like this for speed
  19159. const x0 = ax < bx ? ( ax < cx ? ax : cx ) : ( bx < cx ? bx : cx ),
  19160. y0 = ay < by ? ( ay < cy ? ay : cy ) : ( by < cy ? by : cy ),
  19161. x1 = ax > bx ? ( ax > cx ? ax : cx ) : ( bx > cx ? bx : cx ),
  19162. y1 = ay > by ? ( ay > cy ? ay : cy ) : ( by > cy ? by : cy );
  19163. let p = c.next;
  19164. while ( p !== a ) {
  19165. if ( p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 &&
  19166. pointInTriangle( ax, ay, bx, by, cx, cy, p.x, p.y ) &&
  19167. area( p.prev, p, p.next ) >= 0 ) return false;
  19168. p = p.next;
  19169. }
  19170. return true;
  19171. }
  19172. function isEarHashed( ear, minX, minY, invSize ) {
  19173. const a = ear.prev,
  19174. b = ear,
  19175. c = ear.next;
  19176. if ( area( a, b, c ) >= 0 ) return false; // reflex, can't be an ear
  19177. const ax = a.x, bx = b.x, cx = c.x, ay = a.y, by = b.y, cy = c.y;
  19178. // triangle bbox; min & max are calculated like this for speed
  19179. const x0 = ax < bx ? ( ax < cx ? ax : cx ) : ( bx < cx ? bx : cx ),
  19180. y0 = ay < by ? ( ay < cy ? ay : cy ) : ( by < cy ? by : cy ),
  19181. x1 = ax > bx ? ( ax > cx ? ax : cx ) : ( bx > cx ? bx : cx ),
  19182. y1 = ay > by ? ( ay > cy ? ay : cy ) : ( by > cy ? by : cy );
  19183. // z-order range for the current triangle bbox;
  19184. const minZ = zOrder( x0, y0, minX, minY, invSize ),
  19185. maxZ = zOrder( x1, y1, minX, minY, invSize );
  19186. let p = ear.prevZ,
  19187. n = ear.nextZ;
  19188. // look for points inside the triangle in both directions
  19189. while ( p && p.z >= minZ && n && n.z <= maxZ ) {
  19190. if ( p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 && p !== a && p !== c &&
  19191. pointInTriangle( ax, ay, bx, by, cx, cy, p.x, p.y ) && area( p.prev, p, p.next ) >= 0 ) return false;
  19192. p = p.prevZ;
  19193. if ( n.x >= x0 && n.x <= x1 && n.y >= y0 && n.y <= y1 && n !== a && n !== c &&
  19194. pointInTriangle( ax, ay, bx, by, cx, cy, n.x, n.y ) && area( n.prev, n, n.next ) >= 0 ) return false;
  19195. n = n.nextZ;
  19196. }
  19197. // look for remaining points in decreasing z-order
  19198. while ( p && p.z >= minZ ) {
  19199. if ( p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 && p !== a && p !== c &&
  19200. pointInTriangle( ax, ay, bx, by, cx, cy, p.x, p.y ) && area( p.prev, p, p.next ) >= 0 ) return false;
  19201. p = p.prevZ;
  19202. }
  19203. // look for remaining points in increasing z-order
  19204. while ( n && n.z <= maxZ ) {
  19205. if ( n.x >= x0 && n.x <= x1 && n.y >= y0 && n.y <= y1 && n !== a && n !== c &&
  19206. pointInTriangle( ax, ay, bx, by, cx, cy, n.x, n.y ) && area( n.prev, n, n.next ) >= 0 ) return false;
  19207. n = n.nextZ;
  19208. }
  19209. return true;
  19210. }
  19211. // go through all polygon nodes and cure small local self-intersections
  19212. function cureLocalIntersections( start, triangles, dim ) {
  19213. let p = start;
  19214. do {
  19215. const a = p.prev,
  19216. b = p.next.next;
  19217. if ( ! equals( a, b ) && intersects( a, p, p.next, b ) && locallyInside( a, b ) && locallyInside( b, a ) ) {
  19218. triangles.push( a.i / dim | 0 );
  19219. triangles.push( p.i / dim | 0 );
  19220. triangles.push( b.i / dim | 0 );
  19221. // remove two nodes involved
  19222. removeNode( p );
  19223. removeNode( p.next );
  19224. p = start = b;
  19225. }
  19226. p = p.next;
  19227. } while ( p !== start );
  19228. return filterPoints( p );
  19229. }
  19230. // try splitting polygon into two and triangulate them independently
  19231. function splitEarcut( start, triangles, dim, minX, minY, invSize ) {
  19232. // look for a valid diagonal that divides the polygon into two
  19233. let a = start;
  19234. do {
  19235. let b = a.next.next;
  19236. while ( b !== a.prev ) {
  19237. if ( a.i !== b.i && isValidDiagonal( a, b ) ) {
  19238. // split the polygon in two by the diagonal
  19239. let c = splitPolygon( a, b );
  19240. // filter colinear points around the cuts
  19241. a = filterPoints( a, a.next );
  19242. c = filterPoints( c, c.next );
  19243. // run earcut on each half
  19244. earcutLinked( a, triangles, dim, minX, minY, invSize, 0 );
  19245. earcutLinked( c, triangles, dim, minX, minY, invSize, 0 );
  19246. return;
  19247. }
  19248. b = b.next;
  19249. }
  19250. a = a.next;
  19251. } while ( a !== start );
  19252. }
  19253. // link every hole into the outer loop, producing a single-ring polygon without holes
  19254. function eliminateHoles( data, holeIndices, outerNode, dim ) {
  19255. const queue = [];
  19256. let i, len, start, end, list;
  19257. for ( i = 0, len = holeIndices.length; i < len; i ++ ) {
  19258. start = holeIndices[ i ] * dim;
  19259. end = i < len - 1 ? holeIndices[ i + 1 ] * dim : data.length;
  19260. list = linkedList( data, start, end, dim, false );
  19261. if ( list === list.next ) list.steiner = true;
  19262. queue.push( getLeftmost( list ) );
  19263. }
  19264. queue.sort( compareX );
  19265. // process holes from left to right
  19266. for ( i = 0; i < queue.length; i ++ ) {
  19267. outerNode = eliminateHole( queue[ i ], outerNode );
  19268. }
  19269. return outerNode;
  19270. }
  19271. function compareX( a, b ) {
  19272. return a.x - b.x;
  19273. }
  19274. // find a bridge between vertices that connects hole with an outer ring and link it
  19275. function eliminateHole( hole, outerNode ) {
  19276. const bridge = findHoleBridge( hole, outerNode );
  19277. if ( ! bridge ) {
  19278. return outerNode;
  19279. }
  19280. const bridgeReverse = splitPolygon( bridge, hole );
  19281. // filter collinear points around the cuts
  19282. filterPoints( bridgeReverse, bridgeReverse.next );
  19283. return filterPoints( bridge, bridge.next );
  19284. }
  19285. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  19286. function findHoleBridge( hole, outerNode ) {
  19287. let p = outerNode,
  19288. qx = - Infinity,
  19289. m;
  19290. const hx = hole.x, hy = hole.y;
  19291. // find a segment intersected by a ray from the hole's leftmost point to the left;
  19292. // segment's endpoint with lesser x will be potential connection point
  19293. do {
  19294. if ( hy <= p.y && hy >= p.next.y && p.next.y !== p.y ) {
  19295. const x = p.x + ( hy - p.y ) * ( p.next.x - p.x ) / ( p.next.y - p.y );
  19296. if ( x <= hx && x > qx ) {
  19297. qx = x;
  19298. m = p.x < p.next.x ? p : p.next;
  19299. if ( x === hx ) return m; // hole touches outer segment; pick leftmost endpoint
  19300. }
  19301. }
  19302. p = p.next;
  19303. } while ( p !== outerNode );
  19304. if ( ! m ) return null;
  19305. // look for points inside the triangle of hole point, segment intersection and endpoint;
  19306. // if there are no points found, we have a valid connection;
  19307. // otherwise choose the point of the minimum angle with the ray as connection point
  19308. const stop = m,
  19309. mx = m.x,
  19310. my = m.y;
  19311. let tanMin = Infinity, tan;
  19312. p = m;
  19313. do {
  19314. if ( hx >= p.x && p.x >= mx && hx !== p.x &&
  19315. pointInTriangle( hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y ) ) {
  19316. tan = Math.abs( hy - p.y ) / ( hx - p.x ); // tangential
  19317. if ( locallyInside( p, hole ) && ( tan < tanMin || ( tan === tanMin && ( p.x > m.x || ( p.x === m.x && sectorContainsSector( m, p ) ) ) ) ) ) {
  19318. m = p;
  19319. tanMin = tan;
  19320. }
  19321. }
  19322. p = p.next;
  19323. } while ( p !== stop );
  19324. return m;
  19325. }
  19326. // whether sector in vertex m contains sector in vertex p in the same coordinates
  19327. function sectorContainsSector( m, p ) {
  19328. return area( m.prev, m, p.prev ) < 0 && area( p.next, m, m.next ) < 0;
  19329. }
  19330. // interlink polygon nodes in z-order
  19331. function indexCurve( start, minX, minY, invSize ) {
  19332. let p = start;
  19333. do {
  19334. if ( p.z === 0 ) p.z = zOrder( p.x, p.y, minX, minY, invSize );
  19335. p.prevZ = p.prev;
  19336. p.nextZ = p.next;
  19337. p = p.next;
  19338. } while ( p !== start );
  19339. p.prevZ.nextZ = null;
  19340. p.prevZ = null;
  19341. sortLinked( p );
  19342. }
  19343. // Simon Tatham's linked list merge sort algorithm
  19344. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  19345. function sortLinked( list ) {
  19346. let i, p, q, e, tail, numMerges, pSize, qSize,
  19347. inSize = 1;
  19348. do {
  19349. p = list;
  19350. list = null;
  19351. tail = null;
  19352. numMerges = 0;
  19353. while ( p ) {
  19354. numMerges ++;
  19355. q = p;
  19356. pSize = 0;
  19357. for ( i = 0; i < inSize; i ++ ) {
  19358. pSize ++;
  19359. q = q.nextZ;
  19360. if ( ! q ) break;
  19361. }
  19362. qSize = inSize;
  19363. while ( pSize > 0 || ( qSize > 0 && q ) ) {
  19364. if ( pSize !== 0 && ( qSize === 0 || ! q || p.z <= q.z ) ) {
  19365. e = p;
  19366. p = p.nextZ;
  19367. pSize --;
  19368. } else {
  19369. e = q;
  19370. q = q.nextZ;
  19371. qSize --;
  19372. }
  19373. if ( tail ) tail.nextZ = e;
  19374. else list = e;
  19375. e.prevZ = tail;
  19376. tail = e;
  19377. }
  19378. p = q;
  19379. }
  19380. tail.nextZ = null;
  19381. inSize *= 2;
  19382. } while ( numMerges > 1 );
  19383. return list;
  19384. }
  19385. // z-order of a point given coords and inverse of the longer side of data bbox
  19386. function zOrder( x, y, minX, minY, invSize ) {
  19387. // coords are transformed into non-negative 15-bit integer range
  19388. x = ( x - minX ) * invSize | 0;
  19389. y = ( y - minY ) * invSize | 0;
  19390. x = ( x | ( x << 8 ) ) & 0x00FF00FF;
  19391. x = ( x | ( x << 4 ) ) & 0x0F0F0F0F;
  19392. x = ( x | ( x << 2 ) ) & 0x33333333;
  19393. x = ( x | ( x << 1 ) ) & 0x55555555;
  19394. y = ( y | ( y << 8 ) ) & 0x00FF00FF;
  19395. y = ( y | ( y << 4 ) ) & 0x0F0F0F0F;
  19396. y = ( y | ( y << 2 ) ) & 0x33333333;
  19397. y = ( y | ( y << 1 ) ) & 0x55555555;
  19398. return x | ( y << 1 );
  19399. }
  19400. // find the leftmost node of a polygon ring
  19401. function getLeftmost( start ) {
  19402. let p = start,
  19403. leftmost = start;
  19404. do {
  19405. if ( p.x < leftmost.x || ( p.x === leftmost.x && p.y < leftmost.y ) ) leftmost = p;
  19406. p = p.next;
  19407. } while ( p !== start );
  19408. return leftmost;
  19409. }
  19410. // check if a point lies within a convex triangle
  19411. function pointInTriangle( ax, ay, bx, by, cx, cy, px, py ) {
  19412. return ( cx - px ) * ( ay - py ) >= ( ax - px ) * ( cy - py ) &&
  19413. ( ax - px ) * ( by - py ) >= ( bx - px ) * ( ay - py ) &&
  19414. ( bx - px ) * ( cy - py ) >= ( cx - px ) * ( by - py );
  19415. }
  19416. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  19417. function isValidDiagonal( a, b ) {
  19418. return a.next.i !== b.i && a.prev.i !== b.i && ! intersectsPolygon( a, b ) && // doesn't intersect other edges
  19419. ( locallyInside( a, b ) && locallyInside( b, a ) && middleInside( a, b ) && // locally visible
  19420. ( area( a.prev, a, b.prev ) || area( a, b.prev, b ) ) || // does not create opposite-facing sectors
  19421. equals( a, b ) && area( a.prev, a, a.next ) > 0 && area( b.prev, b, b.next ) > 0 ); // special zero-length case
  19422. }
  19423. // signed area of a triangle
  19424. function area( p, q, r ) {
  19425. return ( q.y - p.y ) * ( r.x - q.x ) - ( q.x - p.x ) * ( r.y - q.y );
  19426. }
  19427. // check if two points are equal
  19428. function equals( p1, p2 ) {
  19429. return p1.x === p2.x && p1.y === p2.y;
  19430. }
  19431. // check if two segments intersect
  19432. function intersects( p1, q1, p2, q2 ) {
  19433. const o1 = sign( area( p1, q1, p2 ) );
  19434. const o2 = sign( area( p1, q1, q2 ) );
  19435. const o3 = sign( area( p2, q2, p1 ) );
  19436. const o4 = sign( area( p2, q2, q1 ) );
  19437. if ( o1 !== o2 && o3 !== o4 ) return true; // general case
  19438. if ( o1 === 0 && onSegment( p1, p2, q1 ) ) return true; // p1, q1 and p2 are collinear and p2 lies on p1q1
  19439. if ( o2 === 0 && onSegment( p1, q2, q1 ) ) return true; // p1, q1 and q2 are collinear and q2 lies on p1q1
  19440. if ( o3 === 0 && onSegment( p2, p1, q2 ) ) return true; // p2, q2 and p1 are collinear and p1 lies on p2q2
  19441. if ( o4 === 0 && onSegment( p2, q1, q2 ) ) return true; // p2, q2 and q1 are collinear and q1 lies on p2q2
  19442. return false;
  19443. }
  19444. // for collinear points p, q, r, check if point q lies on segment pr
  19445. function onSegment( p, q, r ) {
  19446. 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 );
  19447. }
  19448. function sign( num ) {
  19449. return num > 0 ? 1 : num < 0 ? -1 : 0;
  19450. }
  19451. // check if a polygon diagonal intersects any polygon segments
  19452. function intersectsPolygon( a, b ) {
  19453. let p = a;
  19454. do {
  19455. if ( p.i !== a.i && p.next.i !== a.i && p.i !== b.i && p.next.i !== b.i &&
  19456. intersects( p, p.next, a, b ) ) return true;
  19457. p = p.next;
  19458. } while ( p !== a );
  19459. return false;
  19460. }
  19461. // check if a polygon diagonal is locally inside the polygon
  19462. function locallyInside( a, b ) {
  19463. return area( a.prev, a, a.next ) < 0 ?
  19464. area( a, b, a.next ) >= 0 && area( a, a.prev, b ) >= 0 :
  19465. area( a, b, a.prev ) < 0 || area( a, a.next, b ) < 0;
  19466. }
  19467. // check if the middle point of a polygon diagonal is inside the polygon
  19468. function middleInside( a, b ) {
  19469. let p = a,
  19470. inside = false;
  19471. const px = ( a.x + b.x ) / 2,
  19472. py = ( a.y + b.y ) / 2;
  19473. do {
  19474. if ( ( ( p.y > py ) !== ( p.next.y > py ) ) && p.next.y !== p.y &&
  19475. ( px < ( p.next.x - p.x ) * ( py - p.y ) / ( p.next.y - p.y ) + p.x ) )
  19476. inside = ! inside;
  19477. p = p.next;
  19478. } while ( p !== a );
  19479. return inside;
  19480. }
  19481. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  19482. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  19483. function splitPolygon( a, b ) {
  19484. const a2 = new Node( a.i, a.x, a.y ),
  19485. b2 = new Node( b.i, b.x, b.y ),
  19486. an = a.next,
  19487. bp = b.prev;
  19488. a.next = b;
  19489. b.prev = a;
  19490. a2.next = an;
  19491. an.prev = a2;
  19492. b2.next = a2;
  19493. a2.prev = b2;
  19494. bp.next = b2;
  19495. b2.prev = bp;
  19496. return b2;
  19497. }
  19498. // create a node and optionally link it with previous one (in a circular doubly linked list)
  19499. function insertNode( i, x, y, last ) {
  19500. const p = new Node( i, x, y );
  19501. if ( ! last ) {
  19502. p.prev = p;
  19503. p.next = p;
  19504. } else {
  19505. p.next = last.next;
  19506. p.prev = last;
  19507. last.next.prev = p;
  19508. last.next = p;
  19509. }
  19510. return p;
  19511. }
  19512. function removeNode( p ) {
  19513. p.next.prev = p.prev;
  19514. p.prev.next = p.next;
  19515. if ( p.prevZ ) p.prevZ.nextZ = p.nextZ;
  19516. if ( p.nextZ ) p.nextZ.prevZ = p.prevZ;
  19517. }
  19518. function Node( i, x, y ) {
  19519. // vertex index in coordinates array
  19520. this.i = i;
  19521. // vertex coordinates
  19522. this.x = x;
  19523. this.y = y;
  19524. // previous and next vertex nodes in a polygon ring
  19525. this.prev = null;
  19526. this.next = null;
  19527. // z-order curve value
  19528. this.z = 0;
  19529. // previous and next nodes in z-order
  19530. this.prevZ = null;
  19531. this.nextZ = null;
  19532. // indicates whether this is a steiner point
  19533. this.steiner = false;
  19534. }
  19535. function signedArea( data, start, end, dim ) {
  19536. let sum = 0;
  19537. for ( let i = start, j = end - dim; i < end; i += dim ) {
  19538. sum += ( data[ j ] - data[ i ] ) * ( data[ i + 1 ] + data[ j + 1 ] );
  19539. j = i;
  19540. }
  19541. return sum;
  19542. }
  19543. /**
  19544. * A class containing utility functions for shapes.
  19545. *
  19546. * @hideconstructor
  19547. */
  19548. class ShapeUtils {
  19549. /**
  19550. * Calculate area of a ( 2D ) contour polygon.
  19551. *
  19552. * @param {Array<Vector2>} contour - An array of 2D points.
  19553. * @return {number} The area.
  19554. */
  19555. static area( contour ) {
  19556. const n = contour.length;
  19557. let a = 0.0;
  19558. for ( let p = n - 1, q = 0; q < n; p = q ++ ) {
  19559. a += contour[ p ].x * contour[ q ].y - contour[ q ].x * contour[ p ].y;
  19560. }
  19561. return a * 0.5;
  19562. }
  19563. /**
  19564. * Returns `true` if the given contour uses a clockwise winding order.
  19565. *
  19566. * @param {Array<Vector2>} pts - An array of 2D points defining a polyong.
  19567. * @return {boolean} Whether the given contour uses a clockwise winding order or not.
  19568. */
  19569. static isClockWise( pts ) {
  19570. return ShapeUtils.area( pts ) < 0;
  19571. }
  19572. /**
  19573. * Triangluates the given shape definition.
  19574. *
  19575. * @param {Array<Vector2>} contour - An array of 2D points defining the contour.
  19576. * @param {Array<Array<Vector2>>} holes - An array that holds arrays of 2D points defining the holes.
  19577. * @return {Array<Array<number>>} An array that holds for each face definition an array with three indices.
  19578. */
  19579. static triangulateShape( contour, holes ) {
  19580. const vertices = []; // flat array of vertices like [ x0,y0, x1,y1, x2,y2, ... ]
  19581. const holeIndices = []; // array of hole indices
  19582. const faces = []; // final array of vertex indices like [ [ a,b,d ], [ b,c,d ] ]
  19583. removeDupEndPts( contour );
  19584. addContour( vertices, contour );
  19585. //
  19586. let holeIndex = contour.length;
  19587. holes.forEach( removeDupEndPts );
  19588. for ( let i = 0; i < holes.length; i ++ ) {
  19589. holeIndices.push( holeIndex );
  19590. holeIndex += holes[ i ].length;
  19591. addContour( vertices, holes[ i ] );
  19592. }
  19593. //
  19594. const triangles = Earcut.triangulate( vertices, holeIndices );
  19595. //
  19596. for ( let i = 0; i < triangles.length; i += 3 ) {
  19597. faces.push( triangles.slice( i, i + 3 ) );
  19598. }
  19599. return faces;
  19600. }
  19601. }
  19602. function removeDupEndPts( points ) {
  19603. const l = points.length;
  19604. if ( l > 2 && points[ l - 1 ].equals( points[ 0 ] ) ) {
  19605. points.pop();
  19606. }
  19607. }
  19608. function addContour( vertices, contour ) {
  19609. for ( let i = 0; i < contour.length; i ++ ) {
  19610. vertices.push( contour[ i ].x );
  19611. vertices.push( contour[ i ].y );
  19612. }
  19613. }
  19614. /**
  19615. * Creates extruded geometry from a path shape.
  19616. *
  19617. * parameters = {
  19618. *
  19619. * curveSegments: <int>, // number of points on the curves
  19620. * steps: <int>, // number of points for z-side extrusions / used for subdividing segments of extrude spline too
  19621. * depth: <float>, // Depth to extrude the shape
  19622. *
  19623. * bevelEnabled: <bool>, // turn on bevel
  19624. * bevelThickness: <float>, // how deep into the original shape bevel goes
  19625. * bevelSize: <float>, // how far from shape outline (including bevelOffset) is bevel
  19626. * bevelOffset: <float>, // how far from shape outline does bevel start
  19627. * bevelSegments: <int>, // number of bevel layers
  19628. *
  19629. * extrudePath: <THREE.Curve> // curve to extrude shape along
  19630. *
  19631. * UVGenerator: <Object> // object that provides UV generator functions
  19632. *
  19633. * }
  19634. */
  19635. class ExtrudeGeometry extends BufferGeometry {
  19636. 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 = {} ) {
  19637. super();
  19638. this.type = 'ExtrudeGeometry';
  19639. this.parameters = {
  19640. shapes: shapes,
  19641. options: options
  19642. };
  19643. shapes = Array.isArray( shapes ) ? shapes : [ shapes ];
  19644. const scope = this;
  19645. const verticesArray = [];
  19646. const uvArray = [];
  19647. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  19648. const shape = shapes[ i ];
  19649. addShape( shape );
  19650. }
  19651. // build geometry
  19652. this.setAttribute( 'position', new Float32BufferAttribute( verticesArray, 3 ) );
  19653. this.setAttribute( 'uv', new Float32BufferAttribute( uvArray, 2 ) );
  19654. this.computeVertexNormals();
  19655. // functions
  19656. function addShape( shape ) {
  19657. const placeholder = [];
  19658. // options
  19659. const curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  19660. const steps = options.steps !== undefined ? options.steps : 1;
  19661. const depth = options.depth !== undefined ? options.depth : 1;
  19662. let bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true;
  19663. let bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 0.2;
  19664. let bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 0.1;
  19665. let bevelOffset = options.bevelOffset !== undefined ? options.bevelOffset : 0;
  19666. let bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3;
  19667. const extrudePath = options.extrudePath;
  19668. const uvgen = options.UVGenerator !== undefined ? options.UVGenerator : WorldUVGenerator;
  19669. //
  19670. let extrudePts, extrudeByPath = false;
  19671. let splineTube, binormal, normal, position2;
  19672. if ( extrudePath ) {
  19673. extrudePts = extrudePath.getSpacedPoints( steps );
  19674. extrudeByPath = true;
  19675. bevelEnabled = false; // bevels not supported for path extrusion
  19676. // SETUP TNB variables
  19677. // TODO1 - have a .isClosed in spline?
  19678. splineTube = extrudePath.computeFrenetFrames( steps, false );
  19679. // console.log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length);
  19680. binormal = new Vector3();
  19681. normal = new Vector3();
  19682. position2 = new Vector3();
  19683. }
  19684. // Safeguards if bevels are not enabled
  19685. if ( ! bevelEnabled ) {
  19686. bevelSegments = 0;
  19687. bevelThickness = 0;
  19688. bevelSize = 0;
  19689. bevelOffset = 0;
  19690. }
  19691. // Variables initialization
  19692. const shapePoints = shape.extractPoints( curveSegments );
  19693. let vertices = shapePoints.shape;
  19694. const holes = shapePoints.holes;
  19695. const reverse = ! ShapeUtils.isClockWise( vertices );
  19696. if ( reverse ) {
  19697. vertices = vertices.reverse();
  19698. // Maybe we should also check if holes are in the opposite direction, just to be safe ...
  19699. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  19700. const ahole = holes[ h ];
  19701. if ( ShapeUtils.isClockWise( ahole ) ) {
  19702. holes[ h ] = ahole.reverse();
  19703. }
  19704. }
  19705. }
  19706. const faces = ShapeUtils.triangulateShape( vertices, holes );
  19707. /* Vertices */
  19708. const contour = vertices; // vertices has all points but contour has only points of circumference
  19709. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  19710. const ahole = holes[ h ];
  19711. vertices = vertices.concat( ahole );
  19712. }
  19713. function scalePt2( pt, vec, size ) {
  19714. if ( ! vec ) console.error( 'THREE.ExtrudeGeometry: vec does not exist' );
  19715. return pt.clone().addScaledVector( vec, size );
  19716. }
  19717. const vlen = vertices.length, flen = faces.length;
  19718. // Find directions for point movement
  19719. function getBevelVec( inPt, inPrev, inNext ) {
  19720. // computes for inPt the corresponding point inPt' on a new contour
  19721. // shifted by 1 unit (length of normalized vector) to the left
  19722. // if we walk along contour clockwise, this new contour is outside the old one
  19723. //
  19724. // inPt' is the intersection of the two lines parallel to the two
  19725. // adjacent edges of inPt at a distance of 1 unit on the left side.
  19726. let v_trans_x, v_trans_y, shrink_by; // resulting translation vector for inPt
  19727. // good reading for geometry algorithms (here: line-line intersection)
  19728. // http://geomalgorithms.com/a05-_intersect-1.html
  19729. const v_prev_x = inPt.x - inPrev.x,
  19730. v_prev_y = inPt.y - inPrev.y;
  19731. const v_next_x = inNext.x - inPt.x,
  19732. v_next_y = inNext.y - inPt.y;
  19733. const v_prev_lensq = ( v_prev_x * v_prev_x + v_prev_y * v_prev_y );
  19734. // check for collinear edges
  19735. const collinear0 = ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  19736. if ( Math.abs( collinear0 ) > Number.EPSILON ) {
  19737. // not collinear
  19738. // length of vectors for normalizing
  19739. const v_prev_len = Math.sqrt( v_prev_lensq );
  19740. const v_next_len = Math.sqrt( v_next_x * v_next_x + v_next_y * v_next_y );
  19741. // shift adjacent points by unit vectors to the left
  19742. const ptPrevShift_x = ( inPrev.x - v_prev_y / v_prev_len );
  19743. const ptPrevShift_y = ( inPrev.y + v_prev_x / v_prev_len );
  19744. const ptNextShift_x = ( inNext.x - v_next_y / v_next_len );
  19745. const ptNextShift_y = ( inNext.y + v_next_x / v_next_len );
  19746. // scaling factor for v_prev to intersection point
  19747. const sf = ( ( ptNextShift_x - ptPrevShift_x ) * v_next_y -
  19748. ( ptNextShift_y - ptPrevShift_y ) * v_next_x ) /
  19749. ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  19750. // vector from inPt to intersection point
  19751. v_trans_x = ( ptPrevShift_x + v_prev_x * sf - inPt.x );
  19752. v_trans_y = ( ptPrevShift_y + v_prev_y * sf - inPt.y );
  19753. // Don't normalize!, otherwise sharp corners become ugly
  19754. // but prevent crazy spikes
  19755. const v_trans_lensq = ( v_trans_x * v_trans_x + v_trans_y * v_trans_y );
  19756. if ( v_trans_lensq <= 2 ) {
  19757. return new Vector2( v_trans_x, v_trans_y );
  19758. } else {
  19759. shrink_by = Math.sqrt( v_trans_lensq / 2 );
  19760. }
  19761. } else {
  19762. // handle special case of collinear edges
  19763. let direction_eq = false; // assumes: opposite
  19764. if ( v_prev_x > Number.EPSILON ) {
  19765. if ( v_next_x > Number.EPSILON ) {
  19766. direction_eq = true;
  19767. }
  19768. } else {
  19769. if ( v_prev_x < - Number.EPSILON ) {
  19770. if ( v_next_x < - Number.EPSILON ) {
  19771. direction_eq = true;
  19772. }
  19773. } else {
  19774. if ( Math.sign( v_prev_y ) === Math.sign( v_next_y ) ) {
  19775. direction_eq = true;
  19776. }
  19777. }
  19778. }
  19779. if ( direction_eq ) {
  19780. // console.log("Warning: lines are a straight sequence");
  19781. v_trans_x = - v_prev_y;
  19782. v_trans_y = v_prev_x;
  19783. shrink_by = Math.sqrt( v_prev_lensq );
  19784. } else {
  19785. // console.log("Warning: lines are a straight spike");
  19786. v_trans_x = v_prev_x;
  19787. v_trans_y = v_prev_y;
  19788. shrink_by = Math.sqrt( v_prev_lensq / 2 );
  19789. }
  19790. }
  19791. return new Vector2( v_trans_x / shrink_by, v_trans_y / shrink_by );
  19792. }
  19793. const contourMovements = [];
  19794. for ( let i = 0, il = contour.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  19795. if ( j === il ) j = 0;
  19796. if ( k === il ) k = 0;
  19797. // (j)---(i)---(k)
  19798. // console.log('i,j,k', i, j , k)
  19799. contourMovements[ i ] = getBevelVec( contour[ i ], contour[ j ], contour[ k ] );
  19800. }
  19801. const holesMovements = [];
  19802. let oneHoleMovements, verticesMovements = contourMovements.concat();
  19803. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  19804. const ahole = holes[ h ];
  19805. oneHoleMovements = [];
  19806. for ( let i = 0, il = ahole.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  19807. if ( j === il ) j = 0;
  19808. if ( k === il ) k = 0;
  19809. // (j)---(i)---(k)
  19810. oneHoleMovements[ i ] = getBevelVec( ahole[ i ], ahole[ j ], ahole[ k ] );
  19811. }
  19812. holesMovements.push( oneHoleMovements );
  19813. verticesMovements = verticesMovements.concat( oneHoleMovements );
  19814. }
  19815. // Loop bevelSegments, 1 for the front, 1 for the back
  19816. for ( let b = 0; b < bevelSegments; b ++ ) {
  19817. //for ( b = bevelSegments; b > 0; b -- ) {
  19818. const t = b / bevelSegments;
  19819. const z = bevelThickness * Math.cos( t * Math.PI / 2 );
  19820. const bs = bevelSize * Math.sin( t * Math.PI / 2 ) + bevelOffset;
  19821. // contract shape
  19822. for ( let i = 0, il = contour.length; i < il; i ++ ) {
  19823. const vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  19824. v( vert.x, vert.y, - z );
  19825. }
  19826. // expand holes
  19827. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  19828. const ahole = holes[ h ];
  19829. oneHoleMovements = holesMovements[ h ];
  19830. for ( let i = 0, il = ahole.length; i < il; i ++ ) {
  19831. const vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  19832. v( vert.x, vert.y, - z );
  19833. }
  19834. }
  19835. }
  19836. const bs = bevelSize + bevelOffset;
  19837. // Back facing vertices
  19838. for ( let i = 0; i < vlen; i ++ ) {
  19839. const vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  19840. if ( ! extrudeByPath ) {
  19841. v( vert.x, vert.y, 0 );
  19842. } else {
  19843. // v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x );
  19844. normal.copy( splineTube.normals[ 0 ] ).multiplyScalar( vert.x );
  19845. binormal.copy( splineTube.binormals[ 0 ] ).multiplyScalar( vert.y );
  19846. position2.copy( extrudePts[ 0 ] ).add( normal ).add( binormal );
  19847. v( position2.x, position2.y, position2.z );
  19848. }
  19849. }
  19850. // Add stepped vertices...
  19851. // Including front facing vertices
  19852. for ( let s = 1; s <= steps; s ++ ) {
  19853. for ( let i = 0; i < vlen; i ++ ) {
  19854. const vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  19855. if ( ! extrudeByPath ) {
  19856. v( vert.x, vert.y, depth / steps * s );
  19857. } else {
  19858. // v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x );
  19859. normal.copy( splineTube.normals[ s ] ).multiplyScalar( vert.x );
  19860. binormal.copy( splineTube.binormals[ s ] ).multiplyScalar( vert.y );
  19861. position2.copy( extrudePts[ s ] ).add( normal ).add( binormal );
  19862. v( position2.x, position2.y, position2.z );
  19863. }
  19864. }
  19865. }
  19866. // Add bevel segments planes
  19867. //for ( b = 1; b <= bevelSegments; b ++ ) {
  19868. for ( let b = bevelSegments - 1; b >= 0; b -- ) {
  19869. const t = b / bevelSegments;
  19870. const z = bevelThickness * Math.cos( t * Math.PI / 2 );
  19871. const bs = bevelSize * Math.sin( t * Math.PI / 2 ) + bevelOffset;
  19872. // contract shape
  19873. for ( let i = 0, il = contour.length; i < il; i ++ ) {
  19874. const vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  19875. v( vert.x, vert.y, depth + z );
  19876. }
  19877. // expand holes
  19878. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  19879. const ahole = holes[ h ];
  19880. oneHoleMovements = holesMovements[ h ];
  19881. for ( let i = 0, il = ahole.length; i < il; i ++ ) {
  19882. const vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  19883. if ( ! extrudeByPath ) {
  19884. v( vert.x, vert.y, depth + z );
  19885. } else {
  19886. v( vert.x, vert.y + extrudePts[ steps - 1 ].y, extrudePts[ steps - 1 ].x + z );
  19887. }
  19888. }
  19889. }
  19890. }
  19891. /* Faces */
  19892. // Top and bottom faces
  19893. buildLidFaces();
  19894. // Sides faces
  19895. buildSideFaces();
  19896. ///// Internal functions
  19897. function buildLidFaces() {
  19898. const start = verticesArray.length / 3;
  19899. if ( bevelEnabled ) {
  19900. let layer = 0; // steps + 1
  19901. let offset = vlen * layer;
  19902. // Bottom faces
  19903. for ( let i = 0; i < flen; i ++ ) {
  19904. const face = faces[ i ];
  19905. f3( face[ 2 ] + offset, face[ 1 ] + offset, face[ 0 ] + offset );
  19906. }
  19907. layer = steps + bevelSegments * 2;
  19908. offset = vlen * layer;
  19909. // Top faces
  19910. for ( let i = 0; i < flen; i ++ ) {
  19911. const face = faces[ i ];
  19912. f3( face[ 0 ] + offset, face[ 1 ] + offset, face[ 2 ] + offset );
  19913. }
  19914. } else {
  19915. // Bottom faces
  19916. for ( let i = 0; i < flen; i ++ ) {
  19917. const face = faces[ i ];
  19918. f3( face[ 2 ], face[ 1 ], face[ 0 ] );
  19919. }
  19920. // Top faces
  19921. for ( let i = 0; i < flen; i ++ ) {
  19922. const face = faces[ i ];
  19923. f3( face[ 0 ] + vlen * steps, face[ 1 ] + vlen * steps, face[ 2 ] + vlen * steps );
  19924. }
  19925. }
  19926. scope.addGroup( start, verticesArray.length / 3 - start, 0 );
  19927. }
  19928. // Create faces for the z-sides of the shape
  19929. function buildSideFaces() {
  19930. const start = verticesArray.length / 3;
  19931. let layeroffset = 0;
  19932. sidewalls( contour, layeroffset );
  19933. layeroffset += contour.length;
  19934. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  19935. const ahole = holes[ h ];
  19936. sidewalls( ahole, layeroffset );
  19937. //, true
  19938. layeroffset += ahole.length;
  19939. }
  19940. scope.addGroup( start, verticesArray.length / 3 - start, 1 );
  19941. }
  19942. function sidewalls( contour, layeroffset ) {
  19943. let i = contour.length;
  19944. while ( -- i >= 0 ) {
  19945. const j = i;
  19946. let k = i - 1;
  19947. if ( k < 0 ) k = contour.length - 1;
  19948. //console.log('b', i,j, i-1, k,vertices.length);
  19949. for ( let s = 0, sl = ( steps + bevelSegments * 2 ); s < sl; s ++ ) {
  19950. const slen1 = vlen * s;
  19951. const slen2 = vlen * ( s + 1 );
  19952. const a = layeroffset + j + slen1,
  19953. b = layeroffset + k + slen1,
  19954. c = layeroffset + k + slen2,
  19955. d = layeroffset + j + slen2;
  19956. f4( a, b, c, d );
  19957. }
  19958. }
  19959. }
  19960. function v( x, y, z ) {
  19961. placeholder.push( x );
  19962. placeholder.push( y );
  19963. placeholder.push( z );
  19964. }
  19965. function f3( a, b, c ) {
  19966. addVertex( a );
  19967. addVertex( b );
  19968. addVertex( c );
  19969. const nextIndex = verticesArray.length / 3;
  19970. const uvs = uvgen.generateTopUV( scope, verticesArray, nextIndex - 3, nextIndex - 2, nextIndex - 1 );
  19971. addUV( uvs[ 0 ] );
  19972. addUV( uvs[ 1 ] );
  19973. addUV( uvs[ 2 ] );
  19974. }
  19975. function f4( a, b, c, d ) {
  19976. addVertex( a );
  19977. addVertex( b );
  19978. addVertex( d );
  19979. addVertex( b );
  19980. addVertex( c );
  19981. addVertex( d );
  19982. const nextIndex = verticesArray.length / 3;
  19983. const uvs = uvgen.generateSideWallUV( scope, verticesArray, nextIndex - 6, nextIndex - 3, nextIndex - 2, nextIndex - 1 );
  19984. addUV( uvs[ 0 ] );
  19985. addUV( uvs[ 1 ] );
  19986. addUV( uvs[ 3 ] );
  19987. addUV( uvs[ 1 ] );
  19988. addUV( uvs[ 2 ] );
  19989. addUV( uvs[ 3 ] );
  19990. }
  19991. function addVertex( index ) {
  19992. verticesArray.push( placeholder[ index * 3 + 0 ] );
  19993. verticesArray.push( placeholder[ index * 3 + 1 ] );
  19994. verticesArray.push( placeholder[ index * 3 + 2 ] );
  19995. }
  19996. function addUV( vector2 ) {
  19997. uvArray.push( vector2.x );
  19998. uvArray.push( vector2.y );
  19999. }
  20000. }
  20001. }
  20002. copy( source ) {
  20003. super.copy( source );
  20004. this.parameters = Object.assign( {}, source.parameters );
  20005. return this;
  20006. }
  20007. toJSON() {
  20008. const data = super.toJSON();
  20009. const shapes = this.parameters.shapes;
  20010. const options = this.parameters.options;
  20011. return toJSON$1( shapes, options, data );
  20012. }
  20013. static fromJSON( data, shapes ) {
  20014. const geometryShapes = [];
  20015. for ( let j = 0, jl = data.shapes.length; j < jl; j ++ ) {
  20016. const shape = shapes[ data.shapes[ j ] ];
  20017. geometryShapes.push( shape );
  20018. }
  20019. const extrudePath = data.options.extrudePath;
  20020. if ( extrudePath !== undefined ) {
  20021. data.options.extrudePath = new Curves[ extrudePath.type ]().fromJSON( extrudePath );
  20022. }
  20023. return new ExtrudeGeometry( geometryShapes, data.options );
  20024. }
  20025. }
  20026. const WorldUVGenerator = {
  20027. generateTopUV: function ( geometry, vertices, indexA, indexB, indexC ) {
  20028. const a_x = vertices[ indexA * 3 ];
  20029. const a_y = vertices[ indexA * 3 + 1 ];
  20030. const b_x = vertices[ indexB * 3 ];
  20031. const b_y = vertices[ indexB * 3 + 1 ];
  20032. const c_x = vertices[ indexC * 3 ];
  20033. const c_y = vertices[ indexC * 3 + 1 ];
  20034. return [
  20035. new Vector2( a_x, a_y ),
  20036. new Vector2( b_x, b_y ),
  20037. new Vector2( c_x, c_y )
  20038. ];
  20039. },
  20040. generateSideWallUV: function ( geometry, vertices, indexA, indexB, indexC, indexD ) {
  20041. const a_x = vertices[ indexA * 3 ];
  20042. const a_y = vertices[ indexA * 3 + 1 ];
  20043. const a_z = vertices[ indexA * 3 + 2 ];
  20044. const b_x = vertices[ indexB * 3 ];
  20045. const b_y = vertices[ indexB * 3 + 1 ];
  20046. const b_z = vertices[ indexB * 3 + 2 ];
  20047. const c_x = vertices[ indexC * 3 ];
  20048. const c_y = vertices[ indexC * 3 + 1 ];
  20049. const c_z = vertices[ indexC * 3 + 2 ];
  20050. const d_x = vertices[ indexD * 3 ];
  20051. const d_y = vertices[ indexD * 3 + 1 ];
  20052. const d_z = vertices[ indexD * 3 + 2 ];
  20053. if ( Math.abs( a_y - b_y ) < Math.abs( a_x - b_x ) ) {
  20054. return [
  20055. new Vector2( a_x, 1 - a_z ),
  20056. new Vector2( b_x, 1 - b_z ),
  20057. new Vector2( c_x, 1 - c_z ),
  20058. new Vector2( d_x, 1 - d_z )
  20059. ];
  20060. } else {
  20061. return [
  20062. new Vector2( a_y, 1 - a_z ),
  20063. new Vector2( b_y, 1 - b_z ),
  20064. new Vector2( c_y, 1 - c_z ),
  20065. new Vector2( d_y, 1 - d_z )
  20066. ];
  20067. }
  20068. }
  20069. };
  20070. function toJSON$1( shapes, options, data ) {
  20071. data.shapes = [];
  20072. if ( Array.isArray( shapes ) ) {
  20073. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  20074. const shape = shapes[ i ];
  20075. data.shapes.push( shape.uuid );
  20076. }
  20077. } else {
  20078. data.shapes.push( shapes.uuid );
  20079. }
  20080. data.options = Object.assign( {}, options );
  20081. if ( options.extrudePath !== undefined ) data.options.extrudePath = options.extrudePath.toJSON();
  20082. return data;
  20083. }
  20084. class IcosahedronGeometry extends PolyhedronGeometry {
  20085. constructor( radius = 1, detail = 0 ) {
  20086. const t = ( 1 + Math.sqrt( 5 ) ) / 2;
  20087. const vertices = [
  20088. -1, t, 0, 1, t, 0, -1, - t, 0, 1, - t, 0,
  20089. 0, -1, t, 0, 1, t, 0, -1, - t, 0, 1, - t,
  20090. t, 0, -1, t, 0, 1, - t, 0, -1, - t, 0, 1
  20091. ];
  20092. const indices = [
  20093. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 0, 10, 11,
  20094. 1, 5, 9, 5, 11, 4, 11, 10, 2, 10, 7, 6, 7, 1, 8,
  20095. 3, 9, 4, 3, 4, 2, 3, 2, 6, 3, 6, 8, 3, 8, 9,
  20096. 4, 9, 5, 2, 4, 11, 6, 2, 10, 8, 6, 7, 9, 8, 1
  20097. ];
  20098. super( vertices, indices, radius, detail );
  20099. this.type = 'IcosahedronGeometry';
  20100. this.parameters = {
  20101. radius: radius,
  20102. detail: detail
  20103. };
  20104. }
  20105. static fromJSON( data ) {
  20106. return new IcosahedronGeometry( data.radius, data.detail );
  20107. }
  20108. }
  20109. class OctahedronGeometry extends PolyhedronGeometry {
  20110. constructor( radius = 1, detail = 0 ) {
  20111. const vertices = [
  20112. 1, 0, 0, -1, 0, 0, 0, 1, 0,
  20113. 0, -1, 0, 0, 0, 1, 0, 0, -1
  20114. ];
  20115. const indices = [
  20116. 0, 2, 4, 0, 4, 3, 0, 3, 5,
  20117. 0, 5, 2, 1, 2, 5, 1, 5, 3,
  20118. 1, 3, 4, 1, 4, 2
  20119. ];
  20120. super( vertices, indices, radius, detail );
  20121. this.type = 'OctahedronGeometry';
  20122. this.parameters = {
  20123. radius: radius,
  20124. detail: detail
  20125. };
  20126. }
  20127. static fromJSON( data ) {
  20128. return new OctahedronGeometry( data.radius, data.detail );
  20129. }
  20130. }
  20131. class PlaneGeometry extends BufferGeometry {
  20132. constructor( width = 1, height = 1, widthSegments = 1, heightSegments = 1 ) {
  20133. super();
  20134. this.type = 'PlaneGeometry';
  20135. this.parameters = {
  20136. width: width,
  20137. height: height,
  20138. widthSegments: widthSegments,
  20139. heightSegments: heightSegments
  20140. };
  20141. const width_half = width / 2;
  20142. const height_half = height / 2;
  20143. const gridX = Math.floor( widthSegments );
  20144. const gridY = Math.floor( heightSegments );
  20145. const gridX1 = gridX + 1;
  20146. const gridY1 = gridY + 1;
  20147. const segment_width = width / gridX;
  20148. const segment_height = height / gridY;
  20149. //
  20150. const indices = [];
  20151. const vertices = [];
  20152. const normals = [];
  20153. const uvs = [];
  20154. for ( let iy = 0; iy < gridY1; iy ++ ) {
  20155. const y = iy * segment_height - height_half;
  20156. for ( let ix = 0; ix < gridX1; ix ++ ) {
  20157. const x = ix * segment_width - width_half;
  20158. vertices.push( x, - y, 0 );
  20159. normals.push( 0, 0, 1 );
  20160. uvs.push( ix / gridX );
  20161. uvs.push( 1 - ( iy / gridY ) );
  20162. }
  20163. }
  20164. for ( let iy = 0; iy < gridY; iy ++ ) {
  20165. for ( let ix = 0; ix < gridX; ix ++ ) {
  20166. const a = ix + gridX1 * iy;
  20167. const b = ix + gridX1 * ( iy + 1 );
  20168. const c = ( ix + 1 ) + gridX1 * ( iy + 1 );
  20169. const d = ( ix + 1 ) + gridX1 * iy;
  20170. indices.push( a, b, d );
  20171. indices.push( b, c, d );
  20172. }
  20173. }
  20174. this.setIndex( indices );
  20175. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  20176. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  20177. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  20178. }
  20179. copy( source ) {
  20180. super.copy( source );
  20181. this.parameters = Object.assign( {}, source.parameters );
  20182. return this;
  20183. }
  20184. static fromJSON( data ) {
  20185. return new PlaneGeometry( data.width, data.height, data.widthSegments, data.heightSegments );
  20186. }
  20187. }
  20188. class RingGeometry extends BufferGeometry {
  20189. constructor( innerRadius = 0.5, outerRadius = 1, thetaSegments = 32, phiSegments = 1, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  20190. super();
  20191. this.type = 'RingGeometry';
  20192. this.parameters = {
  20193. innerRadius: innerRadius,
  20194. outerRadius: outerRadius,
  20195. thetaSegments: thetaSegments,
  20196. phiSegments: phiSegments,
  20197. thetaStart: thetaStart,
  20198. thetaLength: thetaLength
  20199. };
  20200. thetaSegments = Math.max( 3, thetaSegments );
  20201. phiSegments = Math.max( 1, phiSegments );
  20202. // buffers
  20203. const indices = [];
  20204. const vertices = [];
  20205. const normals = [];
  20206. const uvs = [];
  20207. // some helper variables
  20208. let radius = innerRadius;
  20209. const radiusStep = ( ( outerRadius - innerRadius ) / phiSegments );
  20210. const vertex = new Vector3();
  20211. const uv = new Vector2();
  20212. // generate vertices, normals and uvs
  20213. for ( let j = 0; j <= phiSegments; j ++ ) {
  20214. for ( let i = 0; i <= thetaSegments; i ++ ) {
  20215. // values are generate from the inside of the ring to the outside
  20216. const segment = thetaStart + i / thetaSegments * thetaLength;
  20217. // vertex
  20218. vertex.x = radius * Math.cos( segment );
  20219. vertex.y = radius * Math.sin( segment );
  20220. vertices.push( vertex.x, vertex.y, vertex.z );
  20221. // normal
  20222. normals.push( 0, 0, 1 );
  20223. // uv
  20224. uv.x = ( vertex.x / outerRadius + 1 ) / 2;
  20225. uv.y = ( vertex.y / outerRadius + 1 ) / 2;
  20226. uvs.push( uv.x, uv.y );
  20227. }
  20228. // increase the radius for next row of vertices
  20229. radius += radiusStep;
  20230. }
  20231. // indices
  20232. for ( let j = 0; j < phiSegments; j ++ ) {
  20233. const thetaSegmentLevel = j * ( thetaSegments + 1 );
  20234. for ( let i = 0; i < thetaSegments; i ++ ) {
  20235. const segment = i + thetaSegmentLevel;
  20236. const a = segment;
  20237. const b = segment + thetaSegments + 1;
  20238. const c = segment + thetaSegments + 2;
  20239. const d = segment + 1;
  20240. // faces
  20241. indices.push( a, b, d );
  20242. indices.push( b, c, d );
  20243. }
  20244. }
  20245. // build geometry
  20246. this.setIndex( indices );
  20247. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  20248. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  20249. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  20250. }
  20251. copy( source ) {
  20252. super.copy( source );
  20253. this.parameters = Object.assign( {}, source.parameters );
  20254. return this;
  20255. }
  20256. static fromJSON( data ) {
  20257. return new RingGeometry( data.innerRadius, data.outerRadius, data.thetaSegments, data.phiSegments, data.thetaStart, data.thetaLength );
  20258. }
  20259. }
  20260. class ShapeGeometry extends BufferGeometry {
  20261. constructor( shapes = new Shape( [ new Vector2( 0, 0.5 ), new Vector2( -0.5, -0.5 ), new Vector2( 0.5, -0.5 ) ] ), curveSegments = 12 ) {
  20262. super();
  20263. this.type = 'ShapeGeometry';
  20264. this.parameters = {
  20265. shapes: shapes,
  20266. curveSegments: curveSegments
  20267. };
  20268. // buffers
  20269. const indices = [];
  20270. const vertices = [];
  20271. const normals = [];
  20272. const uvs = [];
  20273. // helper variables
  20274. let groupStart = 0;
  20275. let groupCount = 0;
  20276. // allow single and array values for "shapes" parameter
  20277. if ( Array.isArray( shapes ) === false ) {
  20278. addShape( shapes );
  20279. } else {
  20280. for ( let i = 0; i < shapes.length; i ++ ) {
  20281. addShape( shapes[ i ] );
  20282. this.addGroup( groupStart, groupCount, i ); // enables MultiMaterial support
  20283. groupStart += groupCount;
  20284. groupCount = 0;
  20285. }
  20286. }
  20287. // build geometry
  20288. this.setIndex( indices );
  20289. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  20290. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  20291. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  20292. // helper functions
  20293. function addShape( shape ) {
  20294. const indexOffset = vertices.length / 3;
  20295. const points = shape.extractPoints( curveSegments );
  20296. let shapeVertices = points.shape;
  20297. const shapeHoles = points.holes;
  20298. // check direction of vertices
  20299. if ( ShapeUtils.isClockWise( shapeVertices ) === false ) {
  20300. shapeVertices = shapeVertices.reverse();
  20301. }
  20302. for ( let i = 0, l = shapeHoles.length; i < l; i ++ ) {
  20303. const shapeHole = shapeHoles[ i ];
  20304. if ( ShapeUtils.isClockWise( shapeHole ) === true ) {
  20305. shapeHoles[ i ] = shapeHole.reverse();
  20306. }
  20307. }
  20308. const faces = ShapeUtils.triangulateShape( shapeVertices, shapeHoles );
  20309. // join vertices of inner and outer paths to a single array
  20310. for ( let i = 0, l = shapeHoles.length; i < l; i ++ ) {
  20311. const shapeHole = shapeHoles[ i ];
  20312. shapeVertices = shapeVertices.concat( shapeHole );
  20313. }
  20314. // vertices, normals, uvs
  20315. for ( let i = 0, l = shapeVertices.length; i < l; i ++ ) {
  20316. const vertex = shapeVertices[ i ];
  20317. vertices.push( vertex.x, vertex.y, 0 );
  20318. normals.push( 0, 0, 1 );
  20319. uvs.push( vertex.x, vertex.y ); // world uvs
  20320. }
  20321. // indices
  20322. for ( let i = 0, l = faces.length; i < l; i ++ ) {
  20323. const face = faces[ i ];
  20324. const a = face[ 0 ] + indexOffset;
  20325. const b = face[ 1 ] + indexOffset;
  20326. const c = face[ 2 ] + indexOffset;
  20327. indices.push( a, b, c );
  20328. groupCount += 3;
  20329. }
  20330. }
  20331. }
  20332. copy( source ) {
  20333. super.copy( source );
  20334. this.parameters = Object.assign( {}, source.parameters );
  20335. return this;
  20336. }
  20337. toJSON() {
  20338. const data = super.toJSON();
  20339. const shapes = this.parameters.shapes;
  20340. return toJSON( shapes, data );
  20341. }
  20342. static fromJSON( data, shapes ) {
  20343. const geometryShapes = [];
  20344. for ( let j = 0, jl = data.shapes.length; j < jl; j ++ ) {
  20345. const shape = shapes[ data.shapes[ j ] ];
  20346. geometryShapes.push( shape );
  20347. }
  20348. return new ShapeGeometry( geometryShapes, data.curveSegments );
  20349. }
  20350. }
  20351. function toJSON( shapes, data ) {
  20352. data.shapes = [];
  20353. if ( Array.isArray( shapes ) ) {
  20354. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  20355. const shape = shapes[ i ];
  20356. data.shapes.push( shape.uuid );
  20357. }
  20358. } else {
  20359. data.shapes.push( shapes.uuid );
  20360. }
  20361. return data;
  20362. }
  20363. class SphereGeometry extends BufferGeometry {
  20364. constructor( radius = 1, widthSegments = 32, heightSegments = 16, phiStart = 0, phiLength = Math.PI * 2, thetaStart = 0, thetaLength = Math.PI ) {
  20365. super();
  20366. this.type = 'SphereGeometry';
  20367. this.parameters = {
  20368. radius: radius,
  20369. widthSegments: widthSegments,
  20370. heightSegments: heightSegments,
  20371. phiStart: phiStart,
  20372. phiLength: phiLength,
  20373. thetaStart: thetaStart,
  20374. thetaLength: thetaLength
  20375. };
  20376. widthSegments = Math.max( 3, Math.floor( widthSegments ) );
  20377. heightSegments = Math.max( 2, Math.floor( heightSegments ) );
  20378. const thetaEnd = Math.min( thetaStart + thetaLength, Math.PI );
  20379. let index = 0;
  20380. const grid = [];
  20381. const vertex = new Vector3();
  20382. const normal = new Vector3();
  20383. // buffers
  20384. const indices = [];
  20385. const vertices = [];
  20386. const normals = [];
  20387. const uvs = [];
  20388. // generate vertices, normals and uvs
  20389. for ( let iy = 0; iy <= heightSegments; iy ++ ) {
  20390. const verticesRow = [];
  20391. const v = iy / heightSegments;
  20392. // special case for the poles
  20393. let uOffset = 0;
  20394. if ( iy === 0 && thetaStart === 0 ) {
  20395. uOffset = 0.5 / widthSegments;
  20396. } else if ( iy === heightSegments && thetaEnd === Math.PI ) {
  20397. uOffset = -0.5 / widthSegments;
  20398. }
  20399. for ( let ix = 0; ix <= widthSegments; ix ++ ) {
  20400. const u = ix / widthSegments;
  20401. // vertex
  20402. vertex.x = - radius * Math.cos( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  20403. vertex.y = radius * Math.cos( thetaStart + v * thetaLength );
  20404. vertex.z = radius * Math.sin( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  20405. vertices.push( vertex.x, vertex.y, vertex.z );
  20406. // normal
  20407. normal.copy( vertex ).normalize();
  20408. normals.push( normal.x, normal.y, normal.z );
  20409. // uv
  20410. uvs.push( u + uOffset, 1 - v );
  20411. verticesRow.push( index ++ );
  20412. }
  20413. grid.push( verticesRow );
  20414. }
  20415. // indices
  20416. for ( let iy = 0; iy < heightSegments; iy ++ ) {
  20417. for ( let ix = 0; ix < widthSegments; ix ++ ) {
  20418. const a = grid[ iy ][ ix + 1 ];
  20419. const b = grid[ iy ][ ix ];
  20420. const c = grid[ iy + 1 ][ ix ];
  20421. const d = grid[ iy + 1 ][ ix + 1 ];
  20422. if ( iy !== 0 || thetaStart > 0 ) indices.push( a, b, d );
  20423. if ( iy !== heightSegments - 1 || thetaEnd < Math.PI ) indices.push( b, c, d );
  20424. }
  20425. }
  20426. // build geometry
  20427. this.setIndex( indices );
  20428. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  20429. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  20430. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  20431. }
  20432. copy( source ) {
  20433. super.copy( source );
  20434. this.parameters = Object.assign( {}, source.parameters );
  20435. return this;
  20436. }
  20437. static fromJSON( data ) {
  20438. return new SphereGeometry( data.radius, data.widthSegments, data.heightSegments, data.phiStart, data.phiLength, data.thetaStart, data.thetaLength );
  20439. }
  20440. }
  20441. class TetrahedronGeometry extends PolyhedronGeometry {
  20442. constructor( radius = 1, detail = 0 ) {
  20443. const vertices = [
  20444. 1, 1, 1, -1, -1, 1, -1, 1, -1, 1, -1, -1
  20445. ];
  20446. const indices = [
  20447. 2, 1, 0, 0, 3, 2, 1, 3, 0, 2, 3, 1
  20448. ];
  20449. super( vertices, indices, radius, detail );
  20450. this.type = 'TetrahedronGeometry';
  20451. this.parameters = {
  20452. radius: radius,
  20453. detail: detail
  20454. };
  20455. }
  20456. static fromJSON( data ) {
  20457. return new TetrahedronGeometry( data.radius, data.detail );
  20458. }
  20459. }
  20460. class TorusGeometry extends BufferGeometry {
  20461. constructor( radius = 1, tube = 0.4, radialSegments = 12, tubularSegments = 48, arc = Math.PI * 2 ) {
  20462. super();
  20463. this.type = 'TorusGeometry';
  20464. this.parameters = {
  20465. radius: radius,
  20466. tube: tube,
  20467. radialSegments: radialSegments,
  20468. tubularSegments: tubularSegments,
  20469. arc: arc
  20470. };
  20471. radialSegments = Math.floor( radialSegments );
  20472. tubularSegments = Math.floor( tubularSegments );
  20473. // buffers
  20474. const indices = [];
  20475. const vertices = [];
  20476. const normals = [];
  20477. const uvs = [];
  20478. // helper variables
  20479. const center = new Vector3();
  20480. const vertex = new Vector3();
  20481. const normal = new Vector3();
  20482. // generate vertices, normals and uvs
  20483. for ( let j = 0; j <= radialSegments; j ++ ) {
  20484. for ( let i = 0; i <= tubularSegments; i ++ ) {
  20485. const u = i / tubularSegments * arc;
  20486. const v = j / radialSegments * Math.PI * 2;
  20487. // vertex
  20488. vertex.x = ( radius + tube * Math.cos( v ) ) * Math.cos( u );
  20489. vertex.y = ( radius + tube * Math.cos( v ) ) * Math.sin( u );
  20490. vertex.z = tube * Math.sin( v );
  20491. vertices.push( vertex.x, vertex.y, vertex.z );
  20492. // normal
  20493. center.x = radius * Math.cos( u );
  20494. center.y = radius * Math.sin( u );
  20495. normal.subVectors( vertex, center ).normalize();
  20496. normals.push( normal.x, normal.y, normal.z );
  20497. // uv
  20498. uvs.push( i / tubularSegments );
  20499. uvs.push( j / radialSegments );
  20500. }
  20501. }
  20502. // generate indices
  20503. for ( let j = 1; j <= radialSegments; j ++ ) {
  20504. for ( let i = 1; i <= tubularSegments; i ++ ) {
  20505. // indices
  20506. const a = ( tubularSegments + 1 ) * j + i - 1;
  20507. const b = ( tubularSegments + 1 ) * ( j - 1 ) + i - 1;
  20508. const c = ( tubularSegments + 1 ) * ( j - 1 ) + i;
  20509. const d = ( tubularSegments + 1 ) * j + i;
  20510. // faces
  20511. indices.push( a, b, d );
  20512. indices.push( b, c, d );
  20513. }
  20514. }
  20515. // build geometry
  20516. this.setIndex( indices );
  20517. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  20518. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  20519. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  20520. }
  20521. copy( source ) {
  20522. super.copy( source );
  20523. this.parameters = Object.assign( {}, source.parameters );
  20524. return this;
  20525. }
  20526. static fromJSON( data ) {
  20527. return new TorusGeometry( data.radius, data.tube, data.radialSegments, data.tubularSegments, data.arc );
  20528. }
  20529. }
  20530. class TorusKnotGeometry extends BufferGeometry {
  20531. constructor( radius = 1, tube = 0.4, tubularSegments = 64, radialSegments = 8, p = 2, q = 3 ) {
  20532. super();
  20533. this.type = 'TorusKnotGeometry';
  20534. this.parameters = {
  20535. radius: radius,
  20536. tube: tube,
  20537. tubularSegments: tubularSegments,
  20538. radialSegments: radialSegments,
  20539. p: p,
  20540. q: q
  20541. };
  20542. tubularSegments = Math.floor( tubularSegments );
  20543. radialSegments = Math.floor( radialSegments );
  20544. // buffers
  20545. const indices = [];
  20546. const vertices = [];
  20547. const normals = [];
  20548. const uvs = [];
  20549. // helper variables
  20550. const vertex = new Vector3();
  20551. const normal = new Vector3();
  20552. const P1 = new Vector3();
  20553. const P2 = new Vector3();
  20554. const B = new Vector3();
  20555. const T = new Vector3();
  20556. const N = new Vector3();
  20557. // generate vertices, normals and uvs
  20558. for ( let i = 0; i <= tubularSegments; ++ i ) {
  20559. // the radian "u" is used to calculate the position on the torus curve of the current tubular segment
  20560. const u = i / tubularSegments * p * Math.PI * 2;
  20561. // now we calculate two points. P1 is our current position on the curve, P2 is a little farther ahead.
  20562. // these points are used to create a special "coordinate space", which is necessary to calculate the correct vertex positions
  20563. calculatePositionOnCurve( u, p, q, radius, P1 );
  20564. calculatePositionOnCurve( u + 0.01, p, q, radius, P2 );
  20565. // calculate orthonormal basis
  20566. T.subVectors( P2, P1 );
  20567. N.addVectors( P2, P1 );
  20568. B.crossVectors( T, N );
  20569. N.crossVectors( B, T );
  20570. // normalize B, N. T can be ignored, we don't use it
  20571. B.normalize();
  20572. N.normalize();
  20573. for ( let j = 0; j <= radialSegments; ++ j ) {
  20574. // now calculate the vertices. they are nothing more than an extrusion of the torus curve.
  20575. // because we extrude a shape in the xy-plane, there is no need to calculate a z-value.
  20576. const v = j / radialSegments * Math.PI * 2;
  20577. const cx = - tube * Math.cos( v );
  20578. const cy = tube * Math.sin( v );
  20579. // now calculate the final vertex position.
  20580. // first we orient the extrusion with our basis vectors, then we add it to the current position on the curve
  20581. vertex.x = P1.x + ( cx * N.x + cy * B.x );
  20582. vertex.y = P1.y + ( cx * N.y + cy * B.y );
  20583. vertex.z = P1.z + ( cx * N.z + cy * B.z );
  20584. vertices.push( vertex.x, vertex.y, vertex.z );
  20585. // normal (P1 is always the center/origin of the extrusion, thus we can use it to calculate the normal)
  20586. normal.subVectors( vertex, P1 ).normalize();
  20587. normals.push( normal.x, normal.y, normal.z );
  20588. // uv
  20589. uvs.push( i / tubularSegments );
  20590. uvs.push( j / radialSegments );
  20591. }
  20592. }
  20593. // generate indices
  20594. for ( let j = 1; j <= tubularSegments; j ++ ) {
  20595. for ( let i = 1; i <= radialSegments; i ++ ) {
  20596. // indices
  20597. const a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 );
  20598. const b = ( radialSegments + 1 ) * j + ( i - 1 );
  20599. const c = ( radialSegments + 1 ) * j + i;
  20600. const d = ( radialSegments + 1 ) * ( j - 1 ) + i;
  20601. // faces
  20602. indices.push( a, b, d );
  20603. indices.push( b, c, d );
  20604. }
  20605. }
  20606. // build geometry
  20607. this.setIndex( indices );
  20608. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  20609. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  20610. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  20611. // this function calculates the current position on the torus curve
  20612. function calculatePositionOnCurve( u, p, q, radius, position ) {
  20613. const cu = Math.cos( u );
  20614. const su = Math.sin( u );
  20615. const quOverP = q / p * u;
  20616. const cs = Math.cos( quOverP );
  20617. position.x = radius * ( 2 + cs ) * 0.5 * cu;
  20618. position.y = radius * ( 2 + cs ) * su * 0.5;
  20619. position.z = radius * Math.sin( quOverP ) * 0.5;
  20620. }
  20621. }
  20622. copy( source ) {
  20623. super.copy( source );
  20624. this.parameters = Object.assign( {}, source.parameters );
  20625. return this;
  20626. }
  20627. static fromJSON( data ) {
  20628. return new TorusKnotGeometry( data.radius, data.tube, data.tubularSegments, data.radialSegments, data.p, data.q );
  20629. }
  20630. }
  20631. class TubeGeometry extends BufferGeometry {
  20632. 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 ) {
  20633. super();
  20634. this.type = 'TubeGeometry';
  20635. this.parameters = {
  20636. path: path,
  20637. tubularSegments: tubularSegments,
  20638. radius: radius,
  20639. radialSegments: radialSegments,
  20640. closed: closed
  20641. };
  20642. const frames = path.computeFrenetFrames( tubularSegments, closed );
  20643. // expose internals
  20644. this.tangents = frames.tangents;
  20645. this.normals = frames.normals;
  20646. this.binormals = frames.binormals;
  20647. // helper variables
  20648. const vertex = new Vector3();
  20649. const normal = new Vector3();
  20650. const uv = new Vector2();
  20651. let P = new Vector3();
  20652. // buffer
  20653. const vertices = [];
  20654. const normals = [];
  20655. const uvs = [];
  20656. const indices = [];
  20657. // create buffer data
  20658. generateBufferData();
  20659. // build geometry
  20660. this.setIndex( indices );
  20661. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  20662. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  20663. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  20664. // functions
  20665. function generateBufferData() {
  20666. for ( let i = 0; i < tubularSegments; i ++ ) {
  20667. generateSegment( i );
  20668. }
  20669. // if the geometry is not closed, generate the last row of vertices and normals
  20670. // at the regular position on the given path
  20671. //
  20672. // if the geometry is closed, duplicate the first row of vertices and normals (uvs will differ)
  20673. generateSegment( ( closed === false ) ? tubularSegments : 0 );
  20674. // uvs are generated in a separate function.
  20675. // this makes it easy compute correct values for closed geometries
  20676. generateUVs();
  20677. // finally create faces
  20678. generateIndices();
  20679. }
  20680. function generateSegment( i ) {
  20681. // we use getPointAt to sample evenly distributed points from the given path
  20682. P = path.getPointAt( i / tubularSegments, P );
  20683. // retrieve corresponding normal and binormal
  20684. const N = frames.normals[ i ];
  20685. const B = frames.binormals[ i ];
  20686. // generate normals and vertices for the current segment
  20687. for ( let j = 0; j <= radialSegments; j ++ ) {
  20688. const v = j / radialSegments * Math.PI * 2;
  20689. const sin = Math.sin( v );
  20690. const cos = - Math.cos( v );
  20691. // normal
  20692. normal.x = ( cos * N.x + sin * B.x );
  20693. normal.y = ( cos * N.y + sin * B.y );
  20694. normal.z = ( cos * N.z + sin * B.z );
  20695. normal.normalize();
  20696. normals.push( normal.x, normal.y, normal.z );
  20697. // vertex
  20698. vertex.x = P.x + radius * normal.x;
  20699. vertex.y = P.y + radius * normal.y;
  20700. vertex.z = P.z + radius * normal.z;
  20701. vertices.push( vertex.x, vertex.y, vertex.z );
  20702. }
  20703. }
  20704. function generateIndices() {
  20705. for ( let j = 1; j <= tubularSegments; j ++ ) {
  20706. for ( let i = 1; i <= radialSegments; i ++ ) {
  20707. const a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 );
  20708. const b = ( radialSegments + 1 ) * j + ( i - 1 );
  20709. const c = ( radialSegments + 1 ) * j + i;
  20710. const d = ( radialSegments + 1 ) * ( j - 1 ) + i;
  20711. // faces
  20712. indices.push( a, b, d );
  20713. indices.push( b, c, d );
  20714. }
  20715. }
  20716. }
  20717. function generateUVs() {
  20718. for ( let i = 0; i <= tubularSegments; i ++ ) {
  20719. for ( let j = 0; j <= radialSegments; j ++ ) {
  20720. uv.x = i / tubularSegments;
  20721. uv.y = j / radialSegments;
  20722. uvs.push( uv.x, uv.y );
  20723. }
  20724. }
  20725. }
  20726. }
  20727. copy( source ) {
  20728. super.copy( source );
  20729. this.parameters = Object.assign( {}, source.parameters );
  20730. return this;
  20731. }
  20732. toJSON() {
  20733. const data = super.toJSON();
  20734. data.path = this.parameters.path.toJSON();
  20735. return data;
  20736. }
  20737. static fromJSON( data ) {
  20738. // This only works for built-in curves (e.g. CatmullRomCurve3).
  20739. // User defined curves or instances of CurvePath will not be deserialized.
  20740. return new TubeGeometry(
  20741. new Curves[ data.path.type ]().fromJSON( data.path ),
  20742. data.tubularSegments,
  20743. data.radius,
  20744. data.radialSegments,
  20745. data.closed
  20746. );
  20747. }
  20748. }
  20749. class WireframeGeometry extends BufferGeometry {
  20750. constructor( geometry = null ) {
  20751. super();
  20752. this.type = 'WireframeGeometry';
  20753. this.parameters = {
  20754. geometry: geometry
  20755. };
  20756. if ( geometry !== null ) {
  20757. // buffer
  20758. const vertices = [];
  20759. const edges = new Set();
  20760. // helper variables
  20761. const start = new Vector3();
  20762. const end = new Vector3();
  20763. if ( geometry.index !== null ) {
  20764. // indexed BufferGeometry
  20765. const position = geometry.attributes.position;
  20766. const indices = geometry.index;
  20767. let groups = geometry.groups;
  20768. if ( groups.length === 0 ) {
  20769. groups = [ { start: 0, count: indices.count, materialIndex: 0 } ];
  20770. }
  20771. // create a data structure that contains all edges without duplicates
  20772. for ( let o = 0, ol = groups.length; o < ol; ++ o ) {
  20773. const group = groups[ o ];
  20774. const groupStart = group.start;
  20775. const groupCount = group.count;
  20776. for ( let i = groupStart, l = ( groupStart + groupCount ); i < l; i += 3 ) {
  20777. for ( let j = 0; j < 3; j ++ ) {
  20778. const index1 = indices.getX( i + j );
  20779. const index2 = indices.getX( i + ( j + 1 ) % 3 );
  20780. start.fromBufferAttribute( position, index1 );
  20781. end.fromBufferAttribute( position, index2 );
  20782. if ( isUniqueEdge( start, end, edges ) === true ) {
  20783. vertices.push( start.x, start.y, start.z );
  20784. vertices.push( end.x, end.y, end.z );
  20785. }
  20786. }
  20787. }
  20788. }
  20789. } else {
  20790. // non-indexed BufferGeometry
  20791. const position = geometry.attributes.position;
  20792. for ( let i = 0, l = ( position.count / 3 ); i < l; i ++ ) {
  20793. for ( let j = 0; j < 3; j ++ ) {
  20794. // three edges per triangle, an edge is represented as (index1, index2)
  20795. // e.g. the first triangle has the following edges: (0,1),(1,2),(2,0)
  20796. const index1 = 3 * i + j;
  20797. const index2 = 3 * i + ( ( j + 1 ) % 3 );
  20798. start.fromBufferAttribute( position, index1 );
  20799. end.fromBufferAttribute( position, index2 );
  20800. if ( isUniqueEdge( start, end, edges ) === true ) {
  20801. vertices.push( start.x, start.y, start.z );
  20802. vertices.push( end.x, end.y, end.z );
  20803. }
  20804. }
  20805. }
  20806. }
  20807. // build geometry
  20808. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  20809. }
  20810. }
  20811. copy( source ) {
  20812. super.copy( source );
  20813. this.parameters = Object.assign( {}, source.parameters );
  20814. return this;
  20815. }
  20816. }
  20817. function isUniqueEdge( start, end, edges ) {
  20818. const hash1 = `${start.x},${start.y},${start.z}-${end.x},${end.y},${end.z}`;
  20819. const hash2 = `${end.x},${end.y},${end.z}-${start.x},${start.y},${start.z}`; // coincident edge
  20820. if ( edges.has( hash1 ) === true || edges.has( hash2 ) === true ) {
  20821. return false;
  20822. } else {
  20823. edges.add( hash1 );
  20824. edges.add( hash2 );
  20825. return true;
  20826. }
  20827. }
  20828. var Geometries = /*#__PURE__*/Object.freeze({
  20829. __proto__: null,
  20830. BoxGeometry: BoxGeometry,
  20831. CapsuleGeometry: CapsuleGeometry,
  20832. CircleGeometry: CircleGeometry,
  20833. ConeGeometry: ConeGeometry,
  20834. CylinderGeometry: CylinderGeometry,
  20835. DodecahedronGeometry: DodecahedronGeometry,
  20836. EdgesGeometry: EdgesGeometry,
  20837. ExtrudeGeometry: ExtrudeGeometry,
  20838. IcosahedronGeometry: IcosahedronGeometry,
  20839. LatheGeometry: LatheGeometry,
  20840. OctahedronGeometry: OctahedronGeometry,
  20841. PlaneGeometry: PlaneGeometry,
  20842. PolyhedronGeometry: PolyhedronGeometry,
  20843. RingGeometry: RingGeometry,
  20844. ShapeGeometry: ShapeGeometry,
  20845. SphereGeometry: SphereGeometry,
  20846. TetrahedronGeometry: TetrahedronGeometry,
  20847. TorusGeometry: TorusGeometry,
  20848. TorusKnotGeometry: TorusKnotGeometry,
  20849. TubeGeometry: TubeGeometry,
  20850. WireframeGeometry: WireframeGeometry
  20851. });
  20852. class ShadowMaterial extends Material {
  20853. constructor( parameters ) {
  20854. super();
  20855. this.isShadowMaterial = true;
  20856. this.type = 'ShadowMaterial';
  20857. this.color = new Color( 0x000000 );
  20858. this.transparent = true;
  20859. this.fog = true;
  20860. this.setValues( parameters );
  20861. }
  20862. copy( source ) {
  20863. super.copy( source );
  20864. this.color.copy( source.color );
  20865. this.fog = source.fog;
  20866. return this;
  20867. }
  20868. }
  20869. class RawShaderMaterial extends ShaderMaterial {
  20870. constructor( parameters ) {
  20871. super( parameters );
  20872. this.isRawShaderMaterial = true;
  20873. this.type = 'RawShaderMaterial';
  20874. }
  20875. }
  20876. class MeshStandardMaterial extends Material {
  20877. constructor( parameters ) {
  20878. super();
  20879. this.isMeshStandardMaterial = true;
  20880. this.type = 'MeshStandardMaterial';
  20881. this.defines = { 'STANDARD': '' };
  20882. this.color = new Color( 0xffffff ); // diffuse
  20883. this.roughness = 1.0;
  20884. this.metalness = 0.0;
  20885. this.map = null;
  20886. this.lightMap = null;
  20887. this.lightMapIntensity = 1.0;
  20888. this.aoMap = null;
  20889. this.aoMapIntensity = 1.0;
  20890. this.emissive = new Color( 0x000000 );
  20891. this.emissiveIntensity = 1.0;
  20892. this.emissiveMap = null;
  20893. this.bumpMap = null;
  20894. this.bumpScale = 1;
  20895. this.normalMap = null;
  20896. this.normalMapType = TangentSpaceNormalMap;
  20897. this.normalScale = new Vector2( 1, 1 );
  20898. this.displacementMap = null;
  20899. this.displacementScale = 1;
  20900. this.displacementBias = 0;
  20901. this.roughnessMap = null;
  20902. this.metalnessMap = null;
  20903. this.alphaMap = null;
  20904. this.envMap = null;
  20905. this.envMapRotation = new Euler();
  20906. this.envMapIntensity = 1.0;
  20907. this.wireframe = false;
  20908. this.wireframeLinewidth = 1;
  20909. this.wireframeLinecap = 'round';
  20910. this.wireframeLinejoin = 'round';
  20911. this.flatShading = false;
  20912. this.fog = true;
  20913. this.setValues( parameters );
  20914. }
  20915. copy( source ) {
  20916. super.copy( source );
  20917. this.defines = { 'STANDARD': '' };
  20918. this.color.copy( source.color );
  20919. this.roughness = source.roughness;
  20920. this.metalness = source.metalness;
  20921. this.map = source.map;
  20922. this.lightMap = source.lightMap;
  20923. this.lightMapIntensity = source.lightMapIntensity;
  20924. this.aoMap = source.aoMap;
  20925. this.aoMapIntensity = source.aoMapIntensity;
  20926. this.emissive.copy( source.emissive );
  20927. this.emissiveMap = source.emissiveMap;
  20928. this.emissiveIntensity = source.emissiveIntensity;
  20929. this.bumpMap = source.bumpMap;
  20930. this.bumpScale = source.bumpScale;
  20931. this.normalMap = source.normalMap;
  20932. this.normalMapType = source.normalMapType;
  20933. this.normalScale.copy( source.normalScale );
  20934. this.displacementMap = source.displacementMap;
  20935. this.displacementScale = source.displacementScale;
  20936. this.displacementBias = source.displacementBias;
  20937. this.roughnessMap = source.roughnessMap;
  20938. this.metalnessMap = source.metalnessMap;
  20939. this.alphaMap = source.alphaMap;
  20940. this.envMap = source.envMap;
  20941. this.envMapRotation.copy( source.envMapRotation );
  20942. this.envMapIntensity = source.envMapIntensity;
  20943. this.wireframe = source.wireframe;
  20944. this.wireframeLinewidth = source.wireframeLinewidth;
  20945. this.wireframeLinecap = source.wireframeLinecap;
  20946. this.wireframeLinejoin = source.wireframeLinejoin;
  20947. this.flatShading = source.flatShading;
  20948. this.fog = source.fog;
  20949. return this;
  20950. }
  20951. }
  20952. class MeshPhysicalMaterial extends MeshStandardMaterial {
  20953. constructor( parameters ) {
  20954. super();
  20955. this.isMeshPhysicalMaterial = true;
  20956. this.defines = {
  20957. 'STANDARD': '',
  20958. 'PHYSICAL': ''
  20959. };
  20960. this.type = 'MeshPhysicalMaterial';
  20961. this.anisotropyRotation = 0;
  20962. this.anisotropyMap = null;
  20963. this.clearcoatMap = null;
  20964. this.clearcoatRoughness = 0.0;
  20965. this.clearcoatRoughnessMap = null;
  20966. this.clearcoatNormalScale = new Vector2( 1, 1 );
  20967. this.clearcoatNormalMap = null;
  20968. this.ior = 1.5;
  20969. Object.defineProperty( this, 'reflectivity', {
  20970. get: function () {
  20971. return ( clamp( 2.5 * ( this.ior - 1 ) / ( this.ior + 1 ), 0, 1 ) );
  20972. },
  20973. set: function ( reflectivity ) {
  20974. this.ior = ( 1 + 0.4 * reflectivity ) / ( 1 - 0.4 * reflectivity );
  20975. }
  20976. } );
  20977. this.iridescenceMap = null;
  20978. this.iridescenceIOR = 1.3;
  20979. this.iridescenceThicknessRange = [ 100, 400 ];
  20980. this.iridescenceThicknessMap = null;
  20981. this.sheenColor = new Color( 0x000000 );
  20982. this.sheenColorMap = null;
  20983. this.sheenRoughness = 1.0;
  20984. this.sheenRoughnessMap = null;
  20985. this.transmissionMap = null;
  20986. this.thickness = 0;
  20987. this.thicknessMap = null;
  20988. this.attenuationDistance = Infinity;
  20989. this.attenuationColor = new Color( 1, 1, 1 );
  20990. this.specularIntensity = 1.0;
  20991. this.specularIntensityMap = null;
  20992. this.specularColor = new Color( 1, 1, 1 );
  20993. this.specularColorMap = null;
  20994. this._anisotropy = 0;
  20995. this._clearcoat = 0;
  20996. this._dispersion = 0;
  20997. this._iridescence = 0;
  20998. this._sheen = 0.0;
  20999. this._transmission = 0;
  21000. this.setValues( parameters );
  21001. }
  21002. get anisotropy() {
  21003. return this._anisotropy;
  21004. }
  21005. set anisotropy( value ) {
  21006. if ( this._anisotropy > 0 !== value > 0 ) {
  21007. this.version ++;
  21008. }
  21009. this._anisotropy = value;
  21010. }
  21011. get clearcoat() {
  21012. return this._clearcoat;
  21013. }
  21014. set clearcoat( value ) {
  21015. if ( this._clearcoat > 0 !== value > 0 ) {
  21016. this.version ++;
  21017. }
  21018. this._clearcoat = value;
  21019. }
  21020. get iridescence() {
  21021. return this._iridescence;
  21022. }
  21023. set iridescence( value ) {
  21024. if ( this._iridescence > 0 !== value > 0 ) {
  21025. this.version ++;
  21026. }
  21027. this._iridescence = value;
  21028. }
  21029. get dispersion() {
  21030. return this._dispersion;
  21031. }
  21032. set dispersion( value ) {
  21033. if ( this._dispersion > 0 !== value > 0 ) {
  21034. this.version ++;
  21035. }
  21036. this._dispersion = value;
  21037. }
  21038. get sheen() {
  21039. return this._sheen;
  21040. }
  21041. set sheen( value ) {
  21042. if ( this._sheen > 0 !== value > 0 ) {
  21043. this.version ++;
  21044. }
  21045. this._sheen = value;
  21046. }
  21047. get transmission() {
  21048. return this._transmission;
  21049. }
  21050. set transmission( value ) {
  21051. if ( this._transmission > 0 !== value > 0 ) {
  21052. this.version ++;
  21053. }
  21054. this._transmission = value;
  21055. }
  21056. copy( source ) {
  21057. super.copy( source );
  21058. this.defines = {
  21059. 'STANDARD': '',
  21060. 'PHYSICAL': ''
  21061. };
  21062. this.anisotropy = source.anisotropy;
  21063. this.anisotropyRotation = source.anisotropyRotation;
  21064. this.anisotropyMap = source.anisotropyMap;
  21065. this.clearcoat = source.clearcoat;
  21066. this.clearcoatMap = source.clearcoatMap;
  21067. this.clearcoatRoughness = source.clearcoatRoughness;
  21068. this.clearcoatRoughnessMap = source.clearcoatRoughnessMap;
  21069. this.clearcoatNormalMap = source.clearcoatNormalMap;
  21070. this.clearcoatNormalScale.copy( source.clearcoatNormalScale );
  21071. this.dispersion = source.dispersion;
  21072. this.ior = source.ior;
  21073. this.iridescence = source.iridescence;
  21074. this.iridescenceMap = source.iridescenceMap;
  21075. this.iridescenceIOR = source.iridescenceIOR;
  21076. this.iridescenceThicknessRange = [ ...source.iridescenceThicknessRange ];
  21077. this.iridescenceThicknessMap = source.iridescenceThicknessMap;
  21078. this.sheen = source.sheen;
  21079. this.sheenColor.copy( source.sheenColor );
  21080. this.sheenColorMap = source.sheenColorMap;
  21081. this.sheenRoughness = source.sheenRoughness;
  21082. this.sheenRoughnessMap = source.sheenRoughnessMap;
  21083. this.transmission = source.transmission;
  21084. this.transmissionMap = source.transmissionMap;
  21085. this.thickness = source.thickness;
  21086. this.thicknessMap = source.thicknessMap;
  21087. this.attenuationDistance = source.attenuationDistance;
  21088. this.attenuationColor.copy( source.attenuationColor );
  21089. this.specularIntensity = source.specularIntensity;
  21090. this.specularIntensityMap = source.specularIntensityMap;
  21091. this.specularColor.copy( source.specularColor );
  21092. this.specularColorMap = source.specularColorMap;
  21093. return this;
  21094. }
  21095. }
  21096. class MeshPhongMaterial extends Material {
  21097. constructor( parameters ) {
  21098. super();
  21099. this.isMeshPhongMaterial = true;
  21100. this.type = 'MeshPhongMaterial';
  21101. this.color = new Color( 0xffffff ); // diffuse
  21102. this.specular = new Color( 0x111111 );
  21103. this.shininess = 30;
  21104. this.map = null;
  21105. this.lightMap = null;
  21106. this.lightMapIntensity = 1.0;
  21107. this.aoMap = null;
  21108. this.aoMapIntensity = 1.0;
  21109. this.emissive = new Color( 0x000000 );
  21110. this.emissiveIntensity = 1.0;
  21111. this.emissiveMap = null;
  21112. this.bumpMap = null;
  21113. this.bumpScale = 1;
  21114. this.normalMap = null;
  21115. this.normalMapType = TangentSpaceNormalMap;
  21116. this.normalScale = new Vector2( 1, 1 );
  21117. this.displacementMap = null;
  21118. this.displacementScale = 1;
  21119. this.displacementBias = 0;
  21120. this.specularMap = null;
  21121. this.alphaMap = null;
  21122. this.envMap = null;
  21123. this.envMapRotation = new Euler();
  21124. this.combine = MultiplyOperation;
  21125. this.reflectivity = 1;
  21126. this.refractionRatio = 0.98;
  21127. this.wireframe = false;
  21128. this.wireframeLinewidth = 1;
  21129. this.wireframeLinecap = 'round';
  21130. this.wireframeLinejoin = 'round';
  21131. this.flatShading = false;
  21132. this.fog = true;
  21133. this.setValues( parameters );
  21134. }
  21135. copy( source ) {
  21136. super.copy( source );
  21137. this.color.copy( source.color );
  21138. this.specular.copy( source.specular );
  21139. this.shininess = source.shininess;
  21140. this.map = source.map;
  21141. this.lightMap = source.lightMap;
  21142. this.lightMapIntensity = source.lightMapIntensity;
  21143. this.aoMap = source.aoMap;
  21144. this.aoMapIntensity = source.aoMapIntensity;
  21145. this.emissive.copy( source.emissive );
  21146. this.emissiveMap = source.emissiveMap;
  21147. this.emissiveIntensity = source.emissiveIntensity;
  21148. this.bumpMap = source.bumpMap;
  21149. this.bumpScale = source.bumpScale;
  21150. this.normalMap = source.normalMap;
  21151. this.normalMapType = source.normalMapType;
  21152. this.normalScale.copy( source.normalScale );
  21153. this.displacementMap = source.displacementMap;
  21154. this.displacementScale = source.displacementScale;
  21155. this.displacementBias = source.displacementBias;
  21156. this.specularMap = source.specularMap;
  21157. this.alphaMap = source.alphaMap;
  21158. this.envMap = source.envMap;
  21159. this.envMapRotation.copy( source.envMapRotation );
  21160. this.combine = source.combine;
  21161. this.reflectivity = source.reflectivity;
  21162. this.refractionRatio = source.refractionRatio;
  21163. this.wireframe = source.wireframe;
  21164. this.wireframeLinewidth = source.wireframeLinewidth;
  21165. this.wireframeLinecap = source.wireframeLinecap;
  21166. this.wireframeLinejoin = source.wireframeLinejoin;
  21167. this.flatShading = source.flatShading;
  21168. this.fog = source.fog;
  21169. return this;
  21170. }
  21171. }
  21172. class MeshToonMaterial extends Material {
  21173. constructor( parameters ) {
  21174. super();
  21175. this.isMeshToonMaterial = true;
  21176. this.defines = { 'TOON': '' };
  21177. this.type = 'MeshToonMaterial';
  21178. this.color = new Color( 0xffffff );
  21179. this.map = null;
  21180. this.gradientMap = null;
  21181. this.lightMap = null;
  21182. this.lightMapIntensity = 1.0;
  21183. this.aoMap = null;
  21184. this.aoMapIntensity = 1.0;
  21185. this.emissive = new Color( 0x000000 );
  21186. this.emissiveIntensity = 1.0;
  21187. this.emissiveMap = null;
  21188. this.bumpMap = null;
  21189. this.bumpScale = 1;
  21190. this.normalMap = null;
  21191. this.normalMapType = TangentSpaceNormalMap;
  21192. this.normalScale = new Vector2( 1, 1 );
  21193. this.displacementMap = null;
  21194. this.displacementScale = 1;
  21195. this.displacementBias = 0;
  21196. this.alphaMap = null;
  21197. this.wireframe = false;
  21198. this.wireframeLinewidth = 1;
  21199. this.wireframeLinecap = 'round';
  21200. this.wireframeLinejoin = 'round';
  21201. this.fog = true;
  21202. this.setValues( parameters );
  21203. }
  21204. copy( source ) {
  21205. super.copy( source );
  21206. this.color.copy( source.color );
  21207. this.map = source.map;
  21208. this.gradientMap = source.gradientMap;
  21209. this.lightMap = source.lightMap;
  21210. this.lightMapIntensity = source.lightMapIntensity;
  21211. this.aoMap = source.aoMap;
  21212. this.aoMapIntensity = source.aoMapIntensity;
  21213. this.emissive.copy( source.emissive );
  21214. this.emissiveMap = source.emissiveMap;
  21215. this.emissiveIntensity = source.emissiveIntensity;
  21216. this.bumpMap = source.bumpMap;
  21217. this.bumpScale = source.bumpScale;
  21218. this.normalMap = source.normalMap;
  21219. this.normalMapType = source.normalMapType;
  21220. this.normalScale.copy( source.normalScale );
  21221. this.displacementMap = source.displacementMap;
  21222. this.displacementScale = source.displacementScale;
  21223. this.displacementBias = source.displacementBias;
  21224. this.alphaMap = source.alphaMap;
  21225. this.wireframe = source.wireframe;
  21226. this.wireframeLinewidth = source.wireframeLinewidth;
  21227. this.wireframeLinecap = source.wireframeLinecap;
  21228. this.wireframeLinejoin = source.wireframeLinejoin;
  21229. this.fog = source.fog;
  21230. return this;
  21231. }
  21232. }
  21233. class MeshNormalMaterial extends Material {
  21234. constructor( parameters ) {
  21235. super();
  21236. this.isMeshNormalMaterial = true;
  21237. this.type = 'MeshNormalMaterial';
  21238. this.bumpMap = null;
  21239. this.bumpScale = 1;
  21240. this.normalMap = null;
  21241. this.normalMapType = TangentSpaceNormalMap;
  21242. this.normalScale = new Vector2( 1, 1 );
  21243. this.displacementMap = null;
  21244. this.displacementScale = 1;
  21245. this.displacementBias = 0;
  21246. this.wireframe = false;
  21247. this.wireframeLinewidth = 1;
  21248. this.flatShading = false;
  21249. this.setValues( parameters );
  21250. }
  21251. copy( source ) {
  21252. super.copy( source );
  21253. this.bumpMap = source.bumpMap;
  21254. this.bumpScale = source.bumpScale;
  21255. this.normalMap = source.normalMap;
  21256. this.normalMapType = source.normalMapType;
  21257. this.normalScale.copy( source.normalScale );
  21258. this.displacementMap = source.displacementMap;
  21259. this.displacementScale = source.displacementScale;
  21260. this.displacementBias = source.displacementBias;
  21261. this.wireframe = source.wireframe;
  21262. this.wireframeLinewidth = source.wireframeLinewidth;
  21263. this.flatShading = source.flatShading;
  21264. return this;
  21265. }
  21266. }
  21267. class MeshLambertMaterial extends Material {
  21268. constructor( parameters ) {
  21269. super();
  21270. this.isMeshLambertMaterial = true;
  21271. this.type = 'MeshLambertMaterial';
  21272. this.color = new Color( 0xffffff ); // diffuse
  21273. this.map = null;
  21274. this.lightMap = null;
  21275. this.lightMapIntensity = 1.0;
  21276. this.aoMap = null;
  21277. this.aoMapIntensity = 1.0;
  21278. this.emissive = new Color( 0x000000 );
  21279. this.emissiveIntensity = 1.0;
  21280. this.emissiveMap = null;
  21281. this.bumpMap = null;
  21282. this.bumpScale = 1;
  21283. this.normalMap = null;
  21284. this.normalMapType = TangentSpaceNormalMap;
  21285. this.normalScale = new Vector2( 1, 1 );
  21286. this.displacementMap = null;
  21287. this.displacementScale = 1;
  21288. this.displacementBias = 0;
  21289. this.specularMap = null;
  21290. this.alphaMap = null;
  21291. this.envMap = null;
  21292. this.envMapRotation = new Euler();
  21293. this.combine = MultiplyOperation;
  21294. this.reflectivity = 1;
  21295. this.refractionRatio = 0.98;
  21296. this.wireframe = false;
  21297. this.wireframeLinewidth = 1;
  21298. this.wireframeLinecap = 'round';
  21299. this.wireframeLinejoin = 'round';
  21300. this.flatShading = false;
  21301. this.fog = true;
  21302. this.setValues( parameters );
  21303. }
  21304. copy( source ) {
  21305. super.copy( source );
  21306. this.color.copy( source.color );
  21307. this.map = source.map;
  21308. this.lightMap = source.lightMap;
  21309. this.lightMapIntensity = source.lightMapIntensity;
  21310. this.aoMap = source.aoMap;
  21311. this.aoMapIntensity = source.aoMapIntensity;
  21312. this.emissive.copy( source.emissive );
  21313. this.emissiveMap = source.emissiveMap;
  21314. this.emissiveIntensity = source.emissiveIntensity;
  21315. this.bumpMap = source.bumpMap;
  21316. this.bumpScale = source.bumpScale;
  21317. this.normalMap = source.normalMap;
  21318. this.normalMapType = source.normalMapType;
  21319. this.normalScale.copy( source.normalScale );
  21320. this.displacementMap = source.displacementMap;
  21321. this.displacementScale = source.displacementScale;
  21322. this.displacementBias = source.displacementBias;
  21323. this.specularMap = source.specularMap;
  21324. this.alphaMap = source.alphaMap;
  21325. this.envMap = source.envMap;
  21326. this.envMapRotation.copy( source.envMapRotation );
  21327. this.combine = source.combine;
  21328. this.reflectivity = source.reflectivity;
  21329. this.refractionRatio = source.refractionRatio;
  21330. this.wireframe = source.wireframe;
  21331. this.wireframeLinewidth = source.wireframeLinewidth;
  21332. this.wireframeLinecap = source.wireframeLinecap;
  21333. this.wireframeLinejoin = source.wireframeLinejoin;
  21334. this.flatShading = source.flatShading;
  21335. this.fog = source.fog;
  21336. return this;
  21337. }
  21338. }
  21339. class MeshDepthMaterial extends Material {
  21340. constructor( parameters ) {
  21341. super();
  21342. this.isMeshDepthMaterial = true;
  21343. this.type = 'MeshDepthMaterial';
  21344. this.depthPacking = BasicDepthPacking;
  21345. this.map = null;
  21346. this.alphaMap = null;
  21347. this.displacementMap = null;
  21348. this.displacementScale = 1;
  21349. this.displacementBias = 0;
  21350. this.wireframe = false;
  21351. this.wireframeLinewidth = 1;
  21352. this.setValues( parameters );
  21353. }
  21354. copy( source ) {
  21355. super.copy( source );
  21356. this.depthPacking = source.depthPacking;
  21357. this.map = source.map;
  21358. this.alphaMap = source.alphaMap;
  21359. this.displacementMap = source.displacementMap;
  21360. this.displacementScale = source.displacementScale;
  21361. this.displacementBias = source.displacementBias;
  21362. this.wireframe = source.wireframe;
  21363. this.wireframeLinewidth = source.wireframeLinewidth;
  21364. return this;
  21365. }
  21366. }
  21367. class MeshDistanceMaterial extends Material {
  21368. constructor( parameters ) {
  21369. super();
  21370. this.isMeshDistanceMaterial = true;
  21371. this.type = 'MeshDistanceMaterial';
  21372. this.map = null;
  21373. this.alphaMap = null;
  21374. this.displacementMap = null;
  21375. this.displacementScale = 1;
  21376. this.displacementBias = 0;
  21377. this.setValues( parameters );
  21378. }
  21379. copy( source ) {
  21380. super.copy( source );
  21381. this.map = source.map;
  21382. this.alphaMap = source.alphaMap;
  21383. this.displacementMap = source.displacementMap;
  21384. this.displacementScale = source.displacementScale;
  21385. this.displacementBias = source.displacementBias;
  21386. return this;
  21387. }
  21388. }
  21389. class MeshMatcapMaterial extends Material {
  21390. constructor( parameters ) {
  21391. super();
  21392. this.isMeshMatcapMaterial = true;
  21393. this.defines = { 'MATCAP': '' };
  21394. this.type = 'MeshMatcapMaterial';
  21395. this.color = new Color( 0xffffff ); // diffuse
  21396. this.matcap = null;
  21397. this.map = null;
  21398. this.bumpMap = null;
  21399. this.bumpScale = 1;
  21400. this.normalMap = null;
  21401. this.normalMapType = TangentSpaceNormalMap;
  21402. this.normalScale = new Vector2( 1, 1 );
  21403. this.displacementMap = null;
  21404. this.displacementScale = 1;
  21405. this.displacementBias = 0;
  21406. this.alphaMap = null;
  21407. this.flatShading = false;
  21408. this.fog = true;
  21409. this.setValues( parameters );
  21410. }
  21411. copy( source ) {
  21412. super.copy( source );
  21413. this.defines = { 'MATCAP': '' };
  21414. this.color.copy( source.color );
  21415. this.matcap = source.matcap;
  21416. this.map = source.map;
  21417. this.bumpMap = source.bumpMap;
  21418. this.bumpScale = source.bumpScale;
  21419. this.normalMap = source.normalMap;
  21420. this.normalMapType = source.normalMapType;
  21421. this.normalScale.copy( source.normalScale );
  21422. this.displacementMap = source.displacementMap;
  21423. this.displacementScale = source.displacementScale;
  21424. this.displacementBias = source.displacementBias;
  21425. this.alphaMap = source.alphaMap;
  21426. this.flatShading = source.flatShading;
  21427. this.fog = source.fog;
  21428. return this;
  21429. }
  21430. }
  21431. class LineDashedMaterial extends LineBasicMaterial {
  21432. constructor( parameters ) {
  21433. super();
  21434. this.isLineDashedMaterial = true;
  21435. this.type = 'LineDashedMaterial';
  21436. this.scale = 1;
  21437. this.dashSize = 3;
  21438. this.gapSize = 1;
  21439. this.setValues( parameters );
  21440. }
  21441. copy( source ) {
  21442. super.copy( source );
  21443. this.scale = source.scale;
  21444. this.dashSize = source.dashSize;
  21445. this.gapSize = source.gapSize;
  21446. return this;
  21447. }
  21448. }
  21449. // converts an array to a specific type
  21450. function convertArray( array, type, forceClone ) {
  21451. if ( ! array || // let 'undefined' and 'null' pass
  21452. ! forceClone && array.constructor === type ) return array;
  21453. if ( typeof type.BYTES_PER_ELEMENT === 'number' ) {
  21454. return new type( array ); // create typed array
  21455. }
  21456. return Array.prototype.slice.call( array ); // create Array
  21457. }
  21458. function isTypedArray( object ) {
  21459. return ArrayBuffer.isView( object ) &&
  21460. ! ( object instanceof DataView );
  21461. }
  21462. // returns an array by which times and values can be sorted
  21463. function getKeyframeOrder( times ) {
  21464. function compareTime( i, j ) {
  21465. return times[ i ] - times[ j ];
  21466. }
  21467. const n = times.length;
  21468. const result = new Array( n );
  21469. for ( let i = 0; i !== n; ++ i ) result[ i ] = i;
  21470. result.sort( compareTime );
  21471. return result;
  21472. }
  21473. // uses the array previously returned by 'getKeyframeOrder' to sort data
  21474. function sortedArray( values, stride, order ) {
  21475. const nValues = values.length;
  21476. const result = new values.constructor( nValues );
  21477. for ( let i = 0, dstOffset = 0; dstOffset !== nValues; ++ i ) {
  21478. const srcOffset = order[ i ] * stride;
  21479. for ( let j = 0; j !== stride; ++ j ) {
  21480. result[ dstOffset ++ ] = values[ srcOffset + j ];
  21481. }
  21482. }
  21483. return result;
  21484. }
  21485. // function for parsing AOS keyframe formats
  21486. function flattenJSON( jsonKeys, times, values, valuePropertyName ) {
  21487. let i = 1, key = jsonKeys[ 0 ];
  21488. while ( key !== undefined && key[ valuePropertyName ] === undefined ) {
  21489. key = jsonKeys[ i ++ ];
  21490. }
  21491. if ( key === undefined ) return; // no data
  21492. let value = key[ valuePropertyName ];
  21493. if ( value === undefined ) return; // no data
  21494. if ( Array.isArray( value ) ) {
  21495. do {
  21496. value = key[ valuePropertyName ];
  21497. if ( value !== undefined ) {
  21498. times.push( key.time );
  21499. values.push( ...value ); // push all elements
  21500. }
  21501. key = jsonKeys[ i ++ ];
  21502. } while ( key !== undefined );
  21503. } else if ( value.toArray !== undefined ) {
  21504. // ...assume THREE.Math-ish
  21505. do {
  21506. value = key[ valuePropertyName ];
  21507. if ( value !== undefined ) {
  21508. times.push( key.time );
  21509. value.toArray( values, values.length );
  21510. }
  21511. key = jsonKeys[ i ++ ];
  21512. } while ( key !== undefined );
  21513. } else {
  21514. // otherwise push as-is
  21515. do {
  21516. value = key[ valuePropertyName ];
  21517. if ( value !== undefined ) {
  21518. times.push( key.time );
  21519. values.push( value );
  21520. }
  21521. key = jsonKeys[ i ++ ];
  21522. } while ( key !== undefined );
  21523. }
  21524. }
  21525. function subclip( sourceClip, name, startFrame, endFrame, fps = 30 ) {
  21526. const clip = sourceClip.clone();
  21527. clip.name = name;
  21528. const tracks = [];
  21529. for ( let i = 0; i < clip.tracks.length; ++ i ) {
  21530. const track = clip.tracks[ i ];
  21531. const valueSize = track.getValueSize();
  21532. const times = [];
  21533. const values = [];
  21534. for ( let j = 0; j < track.times.length; ++ j ) {
  21535. const frame = track.times[ j ] * fps;
  21536. if ( frame < startFrame || frame >= endFrame ) continue;
  21537. times.push( track.times[ j ] );
  21538. for ( let k = 0; k < valueSize; ++ k ) {
  21539. values.push( track.values[ j * valueSize + k ] );
  21540. }
  21541. }
  21542. if ( times.length === 0 ) continue;
  21543. track.times = convertArray( times, track.times.constructor );
  21544. track.values = convertArray( values, track.values.constructor );
  21545. tracks.push( track );
  21546. }
  21547. clip.tracks = tracks;
  21548. // find minimum .times value across all tracks in the trimmed clip
  21549. let minStartTime = Infinity;
  21550. for ( let i = 0; i < clip.tracks.length; ++ i ) {
  21551. if ( minStartTime > clip.tracks[ i ].times[ 0 ] ) {
  21552. minStartTime = clip.tracks[ i ].times[ 0 ];
  21553. }
  21554. }
  21555. // shift all tracks such that clip begins at t=0
  21556. for ( let i = 0; i < clip.tracks.length; ++ i ) {
  21557. clip.tracks[ i ].shift( -1 * minStartTime );
  21558. }
  21559. clip.resetDuration();
  21560. return clip;
  21561. }
  21562. function makeClipAdditive( targetClip, referenceFrame = 0, referenceClip = targetClip, fps = 30 ) {
  21563. if ( fps <= 0 ) fps = 30;
  21564. const numTracks = referenceClip.tracks.length;
  21565. const referenceTime = referenceFrame / fps;
  21566. // Make each track's values relative to the values at the reference frame
  21567. for ( let i = 0; i < numTracks; ++ i ) {
  21568. const referenceTrack = referenceClip.tracks[ i ];
  21569. const referenceTrackType = referenceTrack.ValueTypeName;
  21570. // Skip this track if it's non-numeric
  21571. if ( referenceTrackType === 'bool' || referenceTrackType === 'string' ) continue;
  21572. // Find the track in the target clip whose name and type matches the reference track
  21573. const targetTrack = targetClip.tracks.find( function ( track ) {
  21574. return track.name === referenceTrack.name
  21575. && track.ValueTypeName === referenceTrackType;
  21576. } );
  21577. if ( targetTrack === undefined ) continue;
  21578. let referenceOffset = 0;
  21579. const referenceValueSize = referenceTrack.getValueSize();
  21580. if ( referenceTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline ) {
  21581. referenceOffset = referenceValueSize / 3;
  21582. }
  21583. let targetOffset = 0;
  21584. const targetValueSize = targetTrack.getValueSize();
  21585. if ( targetTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline ) {
  21586. targetOffset = targetValueSize / 3;
  21587. }
  21588. const lastIndex = referenceTrack.times.length - 1;
  21589. let referenceValue;
  21590. // Find the value to subtract out of the track
  21591. if ( referenceTime <= referenceTrack.times[ 0 ] ) {
  21592. // Reference frame is earlier than the first keyframe, so just use the first keyframe
  21593. const startIndex = referenceOffset;
  21594. const endIndex = referenceValueSize - referenceOffset;
  21595. referenceValue = referenceTrack.values.slice( startIndex, endIndex );
  21596. } else if ( referenceTime >= referenceTrack.times[ lastIndex ] ) {
  21597. // Reference frame is after the last keyframe, so just use the last keyframe
  21598. const startIndex = lastIndex * referenceValueSize + referenceOffset;
  21599. const endIndex = startIndex + referenceValueSize - referenceOffset;
  21600. referenceValue = referenceTrack.values.slice( startIndex, endIndex );
  21601. } else {
  21602. // Interpolate to the reference value
  21603. const interpolant = referenceTrack.createInterpolant();
  21604. const startIndex = referenceOffset;
  21605. const endIndex = referenceValueSize - referenceOffset;
  21606. interpolant.evaluate( referenceTime );
  21607. referenceValue = interpolant.resultBuffer.slice( startIndex, endIndex );
  21608. }
  21609. // Conjugate the quaternion
  21610. if ( referenceTrackType === 'quaternion' ) {
  21611. const referenceQuat = new Quaternion().fromArray( referenceValue ).normalize().conjugate();
  21612. referenceQuat.toArray( referenceValue );
  21613. }
  21614. // Subtract the reference value from all of the track values
  21615. const numTimes = targetTrack.times.length;
  21616. for ( let j = 0; j < numTimes; ++ j ) {
  21617. const valueStart = j * targetValueSize + targetOffset;
  21618. if ( referenceTrackType === 'quaternion' ) {
  21619. // Multiply the conjugate for quaternion track types
  21620. Quaternion.multiplyQuaternionsFlat(
  21621. targetTrack.values,
  21622. valueStart,
  21623. referenceValue,
  21624. 0,
  21625. targetTrack.values,
  21626. valueStart
  21627. );
  21628. } else {
  21629. const valueEnd = targetValueSize - targetOffset * 2;
  21630. // Subtract each value for all other numeric track types
  21631. for ( let k = 0; k < valueEnd; ++ k ) {
  21632. targetTrack.values[ valueStart + k ] -= referenceValue[ k ];
  21633. }
  21634. }
  21635. }
  21636. }
  21637. targetClip.blendMode = AdditiveAnimationBlendMode;
  21638. return targetClip;
  21639. }
  21640. const AnimationUtils = {
  21641. convertArray: convertArray,
  21642. isTypedArray: isTypedArray,
  21643. getKeyframeOrder: getKeyframeOrder,
  21644. sortedArray: sortedArray,
  21645. flattenJSON: flattenJSON,
  21646. subclip: subclip,
  21647. makeClipAdditive: makeClipAdditive
  21648. };
  21649. /**
  21650. * Abstract base class of interpolants over parametric samples.
  21651. *
  21652. * The parameter domain is one dimensional, typically the time or a path
  21653. * along a curve defined by the data.
  21654. *
  21655. * The sample values can have any dimensionality and derived classes may
  21656. * apply special interpretations to the data.
  21657. *
  21658. * This class provides the interval seek in a Template Method, deferring
  21659. * the actual interpolation to derived classes.
  21660. *
  21661. * Time complexity is O(1) for linear access crossing at most two points
  21662. * and O(log N) for random access, where N is the number of positions.
  21663. *
  21664. * References: {@link http://www.oodesign.com/template-method-pattern.html}
  21665. *
  21666. * @abstract
  21667. */
  21668. class Interpolant {
  21669. /**
  21670. * Constructs a new interpolant.
  21671. *
  21672. * @param {TypedArray} parameterPositions - The parameter positions hold the interpolation factors.
  21673. * @param {TypedArray} sampleValues - The sample values.
  21674. * @param {number} sampleSize - The sample size
  21675. * @param {TypedArray} [resultBuffer] - The result buffer.
  21676. */
  21677. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  21678. /**
  21679. * The parameter positions.
  21680. *
  21681. * @type {TypedArray}
  21682. */
  21683. this.parameterPositions = parameterPositions;
  21684. /**
  21685. * A cache index.
  21686. *
  21687. * @private
  21688. * @type {number}
  21689. * @default 0
  21690. */
  21691. this._cachedIndex = 0;
  21692. /**
  21693. * The result buffer.
  21694. *
  21695. * @type {TypedArray}
  21696. */
  21697. this.resultBuffer = resultBuffer !== undefined ? resultBuffer : new sampleValues.constructor( sampleSize );
  21698. /**
  21699. * The sample values.
  21700. *
  21701. * @type {TypedArray}
  21702. */
  21703. this.sampleValues = sampleValues;
  21704. /**
  21705. * The value size.
  21706. *
  21707. * @type {TypedArray}
  21708. */
  21709. this.valueSize = sampleSize;
  21710. /**
  21711. * The interpolation settings.
  21712. *
  21713. * @type {?Object}
  21714. * @default null
  21715. */
  21716. this.settings = null;
  21717. /**
  21718. * The default settings object.
  21719. *
  21720. * @type {Object}
  21721. */
  21722. this.DefaultSettings_ = {};
  21723. }
  21724. /**
  21725. * Evaluate the interpolant at position `t`.
  21726. *
  21727. * @param {number} t - The interpolation factor.
  21728. * @return {TypedArray} The result buffer.
  21729. */
  21730. evaluate( t ) {
  21731. const pp = this.parameterPositions;
  21732. let i1 = this._cachedIndex,
  21733. t1 = pp[ i1 ],
  21734. t0 = pp[ i1 - 1 ];
  21735. validate_interval: {
  21736. seek: {
  21737. let right;
  21738. linear_scan: {
  21739. //- See http://jsperf.com/comparison-to-undefined/3
  21740. //- slower code:
  21741. //-
  21742. //- if ( t >= t1 || t1 === undefined ) {
  21743. forward_scan: if ( ! ( t < t1 ) ) {
  21744. for ( let giveUpAt = i1 + 2; ; ) {
  21745. if ( t1 === undefined ) {
  21746. if ( t < t0 ) break forward_scan;
  21747. // after end
  21748. i1 = pp.length;
  21749. this._cachedIndex = i1;
  21750. return this.copySampleValue_( i1 - 1 );
  21751. }
  21752. if ( i1 === giveUpAt ) break; // this loop
  21753. t0 = t1;
  21754. t1 = pp[ ++ i1 ];
  21755. if ( t < t1 ) {
  21756. // we have arrived at the sought interval
  21757. break seek;
  21758. }
  21759. }
  21760. // prepare binary search on the right side of the index
  21761. right = pp.length;
  21762. break linear_scan;
  21763. }
  21764. //- slower code:
  21765. //- if ( t < t0 || t0 === undefined ) {
  21766. if ( ! ( t >= t0 ) ) {
  21767. // looping?
  21768. const t1global = pp[ 1 ];
  21769. if ( t < t1global ) {
  21770. i1 = 2; // + 1, using the scan for the details
  21771. t0 = t1global;
  21772. }
  21773. // linear reverse scan
  21774. for ( let giveUpAt = i1 - 2; ; ) {
  21775. if ( t0 === undefined ) {
  21776. // before start
  21777. this._cachedIndex = 0;
  21778. return this.copySampleValue_( 0 );
  21779. }
  21780. if ( i1 === giveUpAt ) break; // this loop
  21781. t1 = t0;
  21782. t0 = pp[ -- i1 - 1 ];
  21783. if ( t >= t0 ) {
  21784. // we have arrived at the sought interval
  21785. break seek;
  21786. }
  21787. }
  21788. // prepare binary search on the left side of the index
  21789. right = i1;
  21790. i1 = 0;
  21791. break linear_scan;
  21792. }
  21793. // the interval is valid
  21794. break validate_interval;
  21795. } // linear scan
  21796. // binary search
  21797. while ( i1 < right ) {
  21798. const mid = ( i1 + right ) >>> 1;
  21799. if ( t < pp[ mid ] ) {
  21800. right = mid;
  21801. } else {
  21802. i1 = mid + 1;
  21803. }
  21804. }
  21805. t1 = pp[ i1 ];
  21806. t0 = pp[ i1 - 1 ];
  21807. // check boundary cases, again
  21808. if ( t0 === undefined ) {
  21809. this._cachedIndex = 0;
  21810. return this.copySampleValue_( 0 );
  21811. }
  21812. if ( t1 === undefined ) {
  21813. i1 = pp.length;
  21814. this._cachedIndex = i1;
  21815. return this.copySampleValue_( i1 - 1 );
  21816. }
  21817. } // seek
  21818. this._cachedIndex = i1;
  21819. this.intervalChanged_( i1, t0, t1 );
  21820. } // validate_interval
  21821. return this.interpolate_( i1, t0, t, t1 );
  21822. }
  21823. /**
  21824. * Returns the interpolation settings.
  21825. *
  21826. * @return {Object} The interpolation settings.
  21827. */
  21828. getSettings_() {
  21829. return this.settings || this.DefaultSettings_;
  21830. }
  21831. /**
  21832. * Copies a sample value to the result buffer.
  21833. *
  21834. * @param {number} index - An index into the sample value buffer.
  21835. * @return {TypedArray} The result buffer.
  21836. */
  21837. copySampleValue_( index ) {
  21838. // copies a sample value to the result buffer
  21839. const result = this.resultBuffer,
  21840. values = this.sampleValues,
  21841. stride = this.valueSize,
  21842. offset = index * stride;
  21843. for ( let i = 0; i !== stride; ++ i ) {
  21844. result[ i ] = values[ offset + i ];
  21845. }
  21846. return result;
  21847. }
  21848. /**
  21849. * Copies a sample value to the result buffer.
  21850. *
  21851. * @abstract
  21852. * @param {number} i1 - An index into the sample value buffer.
  21853. * @param {number} t0 - The previous interpolation factor.
  21854. * @param {number} t - The current interpolation factor.
  21855. * @param {number} t1 - The next interpolation factor.
  21856. * @return {TypedArray} The result buffer.
  21857. */
  21858. interpolate_( /* i1, t0, t, t1 */ ) {
  21859. throw new Error( 'call to abstract method' );
  21860. // implementations shall return this.resultBuffer
  21861. }
  21862. /**
  21863. * Optional method that is executed when the interval has changed.
  21864. *
  21865. * @param {number} i1 - An index into the sample value buffer.
  21866. * @param {number} t0 - The previous interpolation factor.
  21867. * @param {number} t - The current interpolation factor.
  21868. */
  21869. intervalChanged_( /* i1, t0, t1 */ ) {
  21870. // empty
  21871. }
  21872. }
  21873. /**
  21874. * Fast and simple cubic spline interpolant.
  21875. *
  21876. * It was derived from a Hermitian construction setting the first derivative
  21877. * at each sample position to the linear slope between neighboring positions
  21878. * over their parameter interval.
  21879. *
  21880. * @augments Interpolant
  21881. */
  21882. class CubicInterpolant extends Interpolant {
  21883. /**
  21884. * Constructs a new cubic interpolant.
  21885. *
  21886. * @param {TypedArray} parameterPositions - The parameter positions hold the interpolation factors.
  21887. * @param {TypedArray} sampleValues - The sample values.
  21888. * @param {number} sampleSize - The sample size
  21889. * @param {TypedArray} [resultBuffer] - The result buffer.
  21890. */
  21891. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  21892. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  21893. this._weightPrev = -0;
  21894. this._offsetPrev = -0;
  21895. this._weightNext = -0;
  21896. this._offsetNext = -0;
  21897. this.DefaultSettings_ = {
  21898. endingStart: ZeroCurvatureEnding,
  21899. endingEnd: ZeroCurvatureEnding
  21900. };
  21901. }
  21902. intervalChanged_( i1, t0, t1 ) {
  21903. const pp = this.parameterPositions;
  21904. let iPrev = i1 - 2,
  21905. iNext = i1 + 1,
  21906. tPrev = pp[ iPrev ],
  21907. tNext = pp[ iNext ];
  21908. if ( tPrev === undefined ) {
  21909. switch ( this.getSettings_().endingStart ) {
  21910. case ZeroSlopeEnding:
  21911. // f'(t0) = 0
  21912. iPrev = i1;
  21913. tPrev = 2 * t0 - t1;
  21914. break;
  21915. case WrapAroundEnding:
  21916. // use the other end of the curve
  21917. iPrev = pp.length - 2;
  21918. tPrev = t0 + pp[ iPrev ] - pp[ iPrev + 1 ];
  21919. break;
  21920. default: // ZeroCurvatureEnding
  21921. // f''(t0) = 0 a.k.a. Natural Spline
  21922. iPrev = i1;
  21923. tPrev = t1;
  21924. }
  21925. }
  21926. if ( tNext === undefined ) {
  21927. switch ( this.getSettings_().endingEnd ) {
  21928. case ZeroSlopeEnding:
  21929. // f'(tN) = 0
  21930. iNext = i1;
  21931. tNext = 2 * t1 - t0;
  21932. break;
  21933. case WrapAroundEnding:
  21934. // use the other end of the curve
  21935. iNext = 1;
  21936. tNext = t1 + pp[ 1 ] - pp[ 0 ];
  21937. break;
  21938. default: // ZeroCurvatureEnding
  21939. // f''(tN) = 0, a.k.a. Natural Spline
  21940. iNext = i1 - 1;
  21941. tNext = t0;
  21942. }
  21943. }
  21944. const halfDt = ( t1 - t0 ) * 0.5,
  21945. stride = this.valueSize;
  21946. this._weightPrev = halfDt / ( t0 - tPrev );
  21947. this._weightNext = halfDt / ( tNext - t1 );
  21948. this._offsetPrev = iPrev * stride;
  21949. this._offsetNext = iNext * stride;
  21950. }
  21951. interpolate_( i1, t0, t, t1 ) {
  21952. const result = this.resultBuffer,
  21953. values = this.sampleValues,
  21954. stride = this.valueSize,
  21955. o1 = i1 * stride, o0 = o1 - stride,
  21956. oP = this._offsetPrev, oN = this._offsetNext,
  21957. wP = this._weightPrev, wN = this._weightNext,
  21958. p = ( t - t0 ) / ( t1 - t0 ),
  21959. pp = p * p,
  21960. ppp = pp * p;
  21961. // evaluate polynomials
  21962. const sP = - wP * ppp + 2 * wP * pp - wP * p;
  21963. const s0 = ( 1 + wP ) * ppp + ( -1.5 - 2 * wP ) * pp + ( -0.5 + wP ) * p + 1;
  21964. const s1 = ( -1 - wN ) * ppp + ( 1.5 + wN ) * pp + 0.5 * p;
  21965. const sN = wN * ppp - wN * pp;
  21966. // combine data linearly
  21967. for ( let i = 0; i !== stride; ++ i ) {
  21968. result[ i ] =
  21969. sP * values[ oP + i ] +
  21970. s0 * values[ o0 + i ] +
  21971. s1 * values[ o1 + i ] +
  21972. sN * values[ oN + i ];
  21973. }
  21974. return result;
  21975. }
  21976. }
  21977. /**
  21978. * A basic linear interpolant.
  21979. *
  21980. * @augments Interpolant
  21981. */
  21982. class LinearInterpolant extends Interpolant {
  21983. /**
  21984. * Constructs a new linear interpolant.
  21985. *
  21986. * @param {TypedArray} parameterPositions - The parameter positions hold the interpolation factors.
  21987. * @param {TypedArray} sampleValues - The sample values.
  21988. * @param {number} sampleSize - The sample size
  21989. * @param {TypedArray} [resultBuffer] - The result buffer.
  21990. */
  21991. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  21992. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  21993. }
  21994. interpolate_( i1, t0, t, t1 ) {
  21995. const result = this.resultBuffer,
  21996. values = this.sampleValues,
  21997. stride = this.valueSize,
  21998. offset1 = i1 * stride,
  21999. offset0 = offset1 - stride,
  22000. weight1 = ( t - t0 ) / ( t1 - t0 ),
  22001. weight0 = 1 - weight1;
  22002. for ( let i = 0; i !== stride; ++ i ) {
  22003. result[ i ] =
  22004. values[ offset0 + i ] * weight0 +
  22005. values[ offset1 + i ] * weight1;
  22006. }
  22007. return result;
  22008. }
  22009. }
  22010. /**
  22011. * Interpolant that evaluates to the sample value at the position preceding
  22012. * the parameter.
  22013. *
  22014. * @augments Interpolant
  22015. */
  22016. class DiscreteInterpolant extends Interpolant {
  22017. /**
  22018. * Constructs a new discrete interpolant.
  22019. *
  22020. * @param {TypedArray} parameterPositions - The parameter positions hold the interpolation factors.
  22021. * @param {TypedArray} sampleValues - The sample values.
  22022. * @param {number} sampleSize - The sample size
  22023. * @param {TypedArray} [resultBuffer] - The result buffer.
  22024. */
  22025. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  22026. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  22027. }
  22028. interpolate_( i1 /*, t0, t, t1 */ ) {
  22029. return this.copySampleValue_( i1 - 1 );
  22030. }
  22031. }
  22032. class KeyframeTrack {
  22033. constructor( name, times, values, interpolation ) {
  22034. if ( name === undefined ) throw new Error( 'THREE.KeyframeTrack: track name is undefined' );
  22035. if ( times === undefined || times.length === 0 ) throw new Error( 'THREE.KeyframeTrack: no keyframes in track named ' + name );
  22036. this.name = name;
  22037. this.times = convertArray( times, this.TimeBufferType );
  22038. this.values = convertArray( values, this.ValueBufferType );
  22039. this.setInterpolation( interpolation || this.DefaultInterpolation );
  22040. }
  22041. // Serialization (in static context, because of constructor invocation
  22042. // and automatic invocation of .toJSON):
  22043. static toJSON( track ) {
  22044. const trackType = track.constructor;
  22045. let json;
  22046. // derived classes can define a static toJSON method
  22047. if ( trackType.toJSON !== this.toJSON ) {
  22048. json = trackType.toJSON( track );
  22049. } else {
  22050. // by default, we assume the data can be serialized as-is
  22051. json = {
  22052. 'name': track.name,
  22053. 'times': convertArray( track.times, Array ),
  22054. 'values': convertArray( track.values, Array )
  22055. };
  22056. const interpolation = track.getInterpolation();
  22057. if ( interpolation !== track.DefaultInterpolation ) {
  22058. json.interpolation = interpolation;
  22059. }
  22060. }
  22061. json.type = track.ValueTypeName; // mandatory
  22062. return json;
  22063. }
  22064. InterpolantFactoryMethodDiscrete( result ) {
  22065. return new DiscreteInterpolant( this.times, this.values, this.getValueSize(), result );
  22066. }
  22067. InterpolantFactoryMethodLinear( result ) {
  22068. return new LinearInterpolant( this.times, this.values, this.getValueSize(), result );
  22069. }
  22070. InterpolantFactoryMethodSmooth( result ) {
  22071. return new CubicInterpolant( this.times, this.values, this.getValueSize(), result );
  22072. }
  22073. setInterpolation( interpolation ) {
  22074. let factoryMethod;
  22075. switch ( interpolation ) {
  22076. case InterpolateDiscrete:
  22077. factoryMethod = this.InterpolantFactoryMethodDiscrete;
  22078. break;
  22079. case InterpolateLinear:
  22080. factoryMethod = this.InterpolantFactoryMethodLinear;
  22081. break;
  22082. case InterpolateSmooth:
  22083. factoryMethod = this.InterpolantFactoryMethodSmooth;
  22084. break;
  22085. }
  22086. if ( factoryMethod === undefined ) {
  22087. const message = 'unsupported interpolation for ' +
  22088. this.ValueTypeName + ' keyframe track named ' + this.name;
  22089. if ( this.createInterpolant === undefined ) {
  22090. // fall back to default, unless the default itself is messed up
  22091. if ( interpolation !== this.DefaultInterpolation ) {
  22092. this.setInterpolation( this.DefaultInterpolation );
  22093. } else {
  22094. throw new Error( message ); // fatal, in this case
  22095. }
  22096. }
  22097. console.warn( 'THREE.KeyframeTrack:', message );
  22098. return this;
  22099. }
  22100. this.createInterpolant = factoryMethod;
  22101. return this;
  22102. }
  22103. getInterpolation() {
  22104. switch ( this.createInterpolant ) {
  22105. case this.InterpolantFactoryMethodDiscrete:
  22106. return InterpolateDiscrete;
  22107. case this.InterpolantFactoryMethodLinear:
  22108. return InterpolateLinear;
  22109. case this.InterpolantFactoryMethodSmooth:
  22110. return InterpolateSmooth;
  22111. }
  22112. }
  22113. getValueSize() {
  22114. return this.values.length / this.times.length;
  22115. }
  22116. // move all keyframes either forwards or backwards in time
  22117. shift( timeOffset ) {
  22118. if ( timeOffset !== 0.0 ) {
  22119. const times = this.times;
  22120. for ( let i = 0, n = times.length; i !== n; ++ i ) {
  22121. times[ i ] += timeOffset;
  22122. }
  22123. }
  22124. return this;
  22125. }
  22126. // scale all keyframe times by a factor (useful for frame <-> seconds conversions)
  22127. scale( timeScale ) {
  22128. if ( timeScale !== 1.0 ) {
  22129. const times = this.times;
  22130. for ( let i = 0, n = times.length; i !== n; ++ i ) {
  22131. times[ i ] *= timeScale;
  22132. }
  22133. }
  22134. return this;
  22135. }
  22136. // removes keyframes before and after animation without changing any values within the range [startTime, endTime].
  22137. // IMPORTANT: We do not shift around keys to the start of the track time, because for interpolated keys this will change their values
  22138. trim( startTime, endTime ) {
  22139. const times = this.times,
  22140. nKeys = times.length;
  22141. let from = 0,
  22142. to = nKeys - 1;
  22143. while ( from !== nKeys && times[ from ] < startTime ) {
  22144. ++ from;
  22145. }
  22146. while ( to !== -1 && times[ to ] > endTime ) {
  22147. -- to;
  22148. }
  22149. ++ to; // inclusive -> exclusive bound
  22150. if ( from !== 0 || to !== nKeys ) {
  22151. // empty tracks are forbidden, so keep at least one keyframe
  22152. if ( from >= to ) {
  22153. to = Math.max( to, 1 );
  22154. from = to - 1;
  22155. }
  22156. const stride = this.getValueSize();
  22157. this.times = times.slice( from, to );
  22158. this.values = this.values.slice( from * stride, to * stride );
  22159. }
  22160. return this;
  22161. }
  22162. // ensure we do not get a GarbageInGarbageOut situation, make sure tracks are at least minimally viable
  22163. validate() {
  22164. let valid = true;
  22165. const valueSize = this.getValueSize();
  22166. if ( valueSize - Math.floor( valueSize ) !== 0 ) {
  22167. console.error( 'THREE.KeyframeTrack: Invalid value size in track.', this );
  22168. valid = false;
  22169. }
  22170. const times = this.times,
  22171. values = this.values,
  22172. nKeys = times.length;
  22173. if ( nKeys === 0 ) {
  22174. console.error( 'THREE.KeyframeTrack: Track is empty.', this );
  22175. valid = false;
  22176. }
  22177. let prevTime = null;
  22178. for ( let i = 0; i !== nKeys; i ++ ) {
  22179. const currTime = times[ i ];
  22180. if ( typeof currTime === 'number' && isNaN( currTime ) ) {
  22181. console.error( 'THREE.KeyframeTrack: Time is not a valid number.', this, i, currTime );
  22182. valid = false;
  22183. break;
  22184. }
  22185. if ( prevTime !== null && prevTime > currTime ) {
  22186. console.error( 'THREE.KeyframeTrack: Out of order keys.', this, i, currTime, prevTime );
  22187. valid = false;
  22188. break;
  22189. }
  22190. prevTime = currTime;
  22191. }
  22192. if ( values !== undefined ) {
  22193. if ( isTypedArray( values ) ) {
  22194. for ( let i = 0, n = values.length; i !== n; ++ i ) {
  22195. const value = values[ i ];
  22196. if ( isNaN( value ) ) {
  22197. console.error( 'THREE.KeyframeTrack: Value is not a valid number.', this, i, value );
  22198. valid = false;
  22199. break;
  22200. }
  22201. }
  22202. }
  22203. }
  22204. return valid;
  22205. }
  22206. // removes equivalent sequential keys as common in morph target sequences
  22207. // (0,0,0,0,1,1,1,0,0,0,0,0,0,0) --> (0,0,1,1,0,0)
  22208. optimize() {
  22209. // times or values may be shared with other tracks, so overwriting is unsafe
  22210. const times = this.times.slice(),
  22211. values = this.values.slice(),
  22212. stride = this.getValueSize(),
  22213. smoothInterpolation = this.getInterpolation() === InterpolateSmooth,
  22214. lastIndex = times.length - 1;
  22215. let writeIndex = 1;
  22216. for ( let i = 1; i < lastIndex; ++ i ) {
  22217. let keep = false;
  22218. const time = times[ i ];
  22219. const timeNext = times[ i + 1 ];
  22220. // remove adjacent keyframes scheduled at the same time
  22221. if ( time !== timeNext && ( i !== 1 || time !== times[ 0 ] ) ) {
  22222. if ( ! smoothInterpolation ) {
  22223. // remove unnecessary keyframes same as their neighbors
  22224. const offset = i * stride,
  22225. offsetP = offset - stride,
  22226. offsetN = offset + stride;
  22227. for ( let j = 0; j !== stride; ++ j ) {
  22228. const value = values[ offset + j ];
  22229. if ( value !== values[ offsetP + j ] ||
  22230. value !== values[ offsetN + j ] ) {
  22231. keep = true;
  22232. break;
  22233. }
  22234. }
  22235. } else {
  22236. keep = true;
  22237. }
  22238. }
  22239. // in-place compaction
  22240. if ( keep ) {
  22241. if ( i !== writeIndex ) {
  22242. times[ writeIndex ] = times[ i ];
  22243. const readOffset = i * stride,
  22244. writeOffset = writeIndex * stride;
  22245. for ( let j = 0; j !== stride; ++ j ) {
  22246. values[ writeOffset + j ] = values[ readOffset + j ];
  22247. }
  22248. }
  22249. ++ writeIndex;
  22250. }
  22251. }
  22252. // flush last keyframe (compaction looks ahead)
  22253. if ( lastIndex > 0 ) {
  22254. times[ writeIndex ] = times[ lastIndex ];
  22255. for ( let readOffset = lastIndex * stride, writeOffset = writeIndex * stride, j = 0; j !== stride; ++ j ) {
  22256. values[ writeOffset + j ] = values[ readOffset + j ];
  22257. }
  22258. ++ writeIndex;
  22259. }
  22260. if ( writeIndex !== times.length ) {
  22261. this.times = times.slice( 0, writeIndex );
  22262. this.values = values.slice( 0, writeIndex * stride );
  22263. } else {
  22264. this.times = times;
  22265. this.values = values;
  22266. }
  22267. return this;
  22268. }
  22269. clone() {
  22270. const times = this.times.slice();
  22271. const values = this.values.slice();
  22272. const TypedKeyframeTrack = this.constructor;
  22273. const track = new TypedKeyframeTrack( this.name, times, values );
  22274. // Interpolant argument to constructor is not saved, so copy the factory method directly.
  22275. track.createInterpolant = this.createInterpolant;
  22276. return track;
  22277. }
  22278. }
  22279. KeyframeTrack.prototype.TimeBufferType = Float32Array;
  22280. KeyframeTrack.prototype.ValueBufferType = Float32Array;
  22281. KeyframeTrack.prototype.DefaultInterpolation = InterpolateLinear;
  22282. /**
  22283. * A Track of Boolean keyframe values.
  22284. */
  22285. class BooleanKeyframeTrack extends KeyframeTrack {
  22286. // No interpolation parameter because only InterpolateDiscrete is valid.
  22287. constructor( name, times, values ) {
  22288. super( name, times, values );
  22289. }
  22290. }
  22291. BooleanKeyframeTrack.prototype.ValueTypeName = 'bool';
  22292. BooleanKeyframeTrack.prototype.ValueBufferType = Array;
  22293. BooleanKeyframeTrack.prototype.DefaultInterpolation = InterpolateDiscrete;
  22294. BooleanKeyframeTrack.prototype.InterpolantFactoryMethodLinear = undefined;
  22295. BooleanKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  22296. /**
  22297. * A Track of keyframe values that represent color.
  22298. */
  22299. class ColorKeyframeTrack extends KeyframeTrack {}
  22300. ColorKeyframeTrack.prototype.ValueTypeName = 'color';
  22301. /**
  22302. * A Track of numeric keyframe values.
  22303. */
  22304. class NumberKeyframeTrack extends KeyframeTrack {}
  22305. NumberKeyframeTrack.prototype.ValueTypeName = 'number';
  22306. /**
  22307. * Spherical linear unit quaternion interpolant.
  22308. *
  22309. * @augments Interpolant
  22310. */
  22311. class QuaternionLinearInterpolant extends Interpolant {
  22312. /**
  22313. * Constructs a new SLERP interpolant.
  22314. *
  22315. * @param {TypedArray} parameterPositions - The parameter positions hold the interpolation factors.
  22316. * @param {TypedArray} sampleValues - The sample values.
  22317. * @param {number} sampleSize - The sample size
  22318. * @param {TypedArray} [resultBuffer] - The result buffer.
  22319. */
  22320. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  22321. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  22322. }
  22323. interpolate_( i1, t0, t, t1 ) {
  22324. const result = this.resultBuffer,
  22325. values = this.sampleValues,
  22326. stride = this.valueSize,
  22327. alpha = ( t - t0 ) / ( t1 - t0 );
  22328. let offset = i1 * stride;
  22329. for ( let end = offset + stride; offset !== end; offset += 4 ) {
  22330. Quaternion.slerpFlat( result, 0, values, offset - stride, values, offset, alpha );
  22331. }
  22332. return result;
  22333. }
  22334. }
  22335. /**
  22336. * A Track of quaternion keyframe values.
  22337. */
  22338. class QuaternionKeyframeTrack extends KeyframeTrack {
  22339. InterpolantFactoryMethodLinear( result ) {
  22340. return new QuaternionLinearInterpolant( this.times, this.values, this.getValueSize(), result );
  22341. }
  22342. }
  22343. QuaternionKeyframeTrack.prototype.ValueTypeName = 'quaternion';
  22344. // ValueBufferType is inherited
  22345. // DefaultInterpolation is inherited;
  22346. QuaternionKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  22347. /**
  22348. * A Track that interpolates Strings
  22349. */
  22350. class StringKeyframeTrack extends KeyframeTrack {
  22351. // No interpolation parameter because only InterpolateDiscrete is valid.
  22352. constructor( name, times, values ) {
  22353. super( name, times, values );
  22354. }
  22355. }
  22356. StringKeyframeTrack.prototype.ValueTypeName = 'string';
  22357. StringKeyframeTrack.prototype.ValueBufferType = Array;
  22358. StringKeyframeTrack.prototype.DefaultInterpolation = InterpolateDiscrete;
  22359. StringKeyframeTrack.prototype.InterpolantFactoryMethodLinear = undefined;
  22360. StringKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  22361. /**
  22362. * A Track of vectored keyframe values.
  22363. */
  22364. class VectorKeyframeTrack extends KeyframeTrack {}
  22365. VectorKeyframeTrack.prototype.ValueTypeName = 'vector';
  22366. class AnimationClip {
  22367. constructor( name = '', duration = -1, tracks = [], blendMode = NormalAnimationBlendMode ) {
  22368. this.name = name;
  22369. this.tracks = tracks;
  22370. this.duration = duration;
  22371. this.blendMode = blendMode;
  22372. this.uuid = generateUUID();
  22373. // this means it should figure out its duration by scanning the tracks
  22374. if ( this.duration < 0 ) {
  22375. this.resetDuration();
  22376. }
  22377. }
  22378. static parse( json ) {
  22379. const tracks = [],
  22380. jsonTracks = json.tracks,
  22381. frameTime = 1.0 / ( json.fps || 1.0 );
  22382. for ( let i = 0, n = jsonTracks.length; i !== n; ++ i ) {
  22383. tracks.push( parseKeyframeTrack( jsonTracks[ i ] ).scale( frameTime ) );
  22384. }
  22385. const clip = new this( json.name, json.duration, tracks, json.blendMode );
  22386. clip.uuid = json.uuid;
  22387. return clip;
  22388. }
  22389. static toJSON( clip ) {
  22390. const tracks = [],
  22391. clipTracks = clip.tracks;
  22392. const json = {
  22393. 'name': clip.name,
  22394. 'duration': clip.duration,
  22395. 'tracks': tracks,
  22396. 'uuid': clip.uuid,
  22397. 'blendMode': clip.blendMode
  22398. };
  22399. for ( let i = 0, n = clipTracks.length; i !== n; ++ i ) {
  22400. tracks.push( KeyframeTrack.toJSON( clipTracks[ i ] ) );
  22401. }
  22402. return json;
  22403. }
  22404. static CreateFromMorphTargetSequence( name, morphTargetSequence, fps, noLoop ) {
  22405. const numMorphTargets = morphTargetSequence.length;
  22406. const tracks = [];
  22407. for ( let i = 0; i < numMorphTargets; i ++ ) {
  22408. let times = [];
  22409. let values = [];
  22410. times.push(
  22411. ( i + numMorphTargets - 1 ) % numMorphTargets,
  22412. i,
  22413. ( i + 1 ) % numMorphTargets );
  22414. values.push( 0, 1, 0 );
  22415. const order = getKeyframeOrder( times );
  22416. times = sortedArray( times, 1, order );
  22417. values = sortedArray( values, 1, order );
  22418. // if there is a key at the first frame, duplicate it as the
  22419. // last frame as well for perfect loop.
  22420. if ( ! noLoop && times[ 0 ] === 0 ) {
  22421. times.push( numMorphTargets );
  22422. values.push( values[ 0 ] );
  22423. }
  22424. tracks.push(
  22425. new NumberKeyframeTrack(
  22426. '.morphTargetInfluences[' + morphTargetSequence[ i ].name + ']',
  22427. times, values
  22428. ).scale( 1.0 / fps ) );
  22429. }
  22430. return new this( name, -1, tracks );
  22431. }
  22432. static findByName( objectOrClipArray, name ) {
  22433. let clipArray = objectOrClipArray;
  22434. if ( ! Array.isArray( objectOrClipArray ) ) {
  22435. const o = objectOrClipArray;
  22436. clipArray = o.geometry && o.geometry.animations || o.animations;
  22437. }
  22438. for ( let i = 0; i < clipArray.length; i ++ ) {
  22439. if ( clipArray[ i ].name === name ) {
  22440. return clipArray[ i ];
  22441. }
  22442. }
  22443. return null;
  22444. }
  22445. static CreateClipsFromMorphTargetSequences( morphTargets, fps, noLoop ) {
  22446. const animationToMorphTargets = {};
  22447. // tested with https://regex101.com/ on trick sequences
  22448. // such flamingo_flyA_003, flamingo_run1_003, crdeath0059
  22449. const pattern = /^([\w-]*?)([\d]+)$/;
  22450. // sort morph target names into animation groups based
  22451. // patterns like Walk_001, Walk_002, Run_001, Run_002
  22452. for ( let i = 0, il = morphTargets.length; i < il; i ++ ) {
  22453. const morphTarget = morphTargets[ i ];
  22454. const parts = morphTarget.name.match( pattern );
  22455. if ( parts && parts.length > 1 ) {
  22456. const name = parts[ 1 ];
  22457. let animationMorphTargets = animationToMorphTargets[ name ];
  22458. if ( ! animationMorphTargets ) {
  22459. animationToMorphTargets[ name ] = animationMorphTargets = [];
  22460. }
  22461. animationMorphTargets.push( morphTarget );
  22462. }
  22463. }
  22464. const clips = [];
  22465. for ( const name in animationToMorphTargets ) {
  22466. clips.push( this.CreateFromMorphTargetSequence( name, animationToMorphTargets[ name ], fps, noLoop ) );
  22467. }
  22468. return clips;
  22469. }
  22470. // parse the animation.hierarchy format
  22471. static parseAnimation( animation, bones ) {
  22472. if ( ! animation ) {
  22473. console.error( 'THREE.AnimationClip: No animation in JSONLoader data.' );
  22474. return null;
  22475. }
  22476. const addNonemptyTrack = function ( trackType, trackName, animationKeys, propertyName, destTracks ) {
  22477. // only return track if there are actually keys.
  22478. if ( animationKeys.length !== 0 ) {
  22479. const times = [];
  22480. const values = [];
  22481. flattenJSON( animationKeys, times, values, propertyName );
  22482. // empty keys are filtered out, so check again
  22483. if ( times.length !== 0 ) {
  22484. destTracks.push( new trackType( trackName, times, values ) );
  22485. }
  22486. }
  22487. };
  22488. const tracks = [];
  22489. const clipName = animation.name || 'default';
  22490. const fps = animation.fps || 30;
  22491. const blendMode = animation.blendMode;
  22492. // automatic length determination in AnimationClip.
  22493. let duration = animation.length || -1;
  22494. const hierarchyTracks = animation.hierarchy || [];
  22495. for ( let h = 0; h < hierarchyTracks.length; h ++ ) {
  22496. const animationKeys = hierarchyTracks[ h ].keys;
  22497. // skip empty tracks
  22498. if ( ! animationKeys || animationKeys.length === 0 ) continue;
  22499. // process morph targets
  22500. if ( animationKeys[ 0 ].morphTargets ) {
  22501. // figure out all morph targets used in this track
  22502. const morphTargetNames = {};
  22503. let k;
  22504. for ( k = 0; k < animationKeys.length; k ++ ) {
  22505. if ( animationKeys[ k ].morphTargets ) {
  22506. for ( let m = 0; m < animationKeys[ k ].morphTargets.length; m ++ ) {
  22507. morphTargetNames[ animationKeys[ k ].morphTargets[ m ] ] = -1;
  22508. }
  22509. }
  22510. }
  22511. // create a track for each morph target with all zero
  22512. // morphTargetInfluences except for the keys in which
  22513. // the morphTarget is named.
  22514. for ( const morphTargetName in morphTargetNames ) {
  22515. const times = [];
  22516. const values = [];
  22517. for ( let m = 0; m !== animationKeys[ k ].morphTargets.length; ++ m ) {
  22518. const animationKey = animationKeys[ k ];
  22519. times.push( animationKey.time );
  22520. values.push( ( animationKey.morphTarget === morphTargetName ) ? 1 : 0 );
  22521. }
  22522. tracks.push( new NumberKeyframeTrack( '.morphTargetInfluence[' + morphTargetName + ']', times, values ) );
  22523. }
  22524. duration = morphTargetNames.length * fps;
  22525. } else {
  22526. // ...assume skeletal animation
  22527. const boneName = '.bones[' + bones[ h ].name + ']';
  22528. addNonemptyTrack(
  22529. VectorKeyframeTrack, boneName + '.position',
  22530. animationKeys, 'pos', tracks );
  22531. addNonemptyTrack(
  22532. QuaternionKeyframeTrack, boneName + '.quaternion',
  22533. animationKeys, 'rot', tracks );
  22534. addNonemptyTrack(
  22535. VectorKeyframeTrack, boneName + '.scale',
  22536. animationKeys, 'scl', tracks );
  22537. }
  22538. }
  22539. if ( tracks.length === 0 ) {
  22540. return null;
  22541. }
  22542. const clip = new this( clipName, duration, tracks, blendMode );
  22543. return clip;
  22544. }
  22545. resetDuration() {
  22546. const tracks = this.tracks;
  22547. let duration = 0;
  22548. for ( let i = 0, n = tracks.length; i !== n; ++ i ) {
  22549. const track = this.tracks[ i ];
  22550. duration = Math.max( duration, track.times[ track.times.length - 1 ] );
  22551. }
  22552. this.duration = duration;
  22553. return this;
  22554. }
  22555. trim() {
  22556. for ( let i = 0; i < this.tracks.length; i ++ ) {
  22557. this.tracks[ i ].trim( 0, this.duration );
  22558. }
  22559. return this;
  22560. }
  22561. validate() {
  22562. let valid = true;
  22563. for ( let i = 0; i < this.tracks.length; i ++ ) {
  22564. valid = valid && this.tracks[ i ].validate();
  22565. }
  22566. return valid;
  22567. }
  22568. optimize() {
  22569. for ( let i = 0; i < this.tracks.length; i ++ ) {
  22570. this.tracks[ i ].optimize();
  22571. }
  22572. return this;
  22573. }
  22574. clone() {
  22575. const tracks = [];
  22576. for ( let i = 0; i < this.tracks.length; i ++ ) {
  22577. tracks.push( this.tracks[ i ].clone() );
  22578. }
  22579. return new this.constructor( this.name, this.duration, tracks, this.blendMode );
  22580. }
  22581. toJSON() {
  22582. return this.constructor.toJSON( this );
  22583. }
  22584. }
  22585. function getTrackTypeForValueTypeName( typeName ) {
  22586. switch ( typeName.toLowerCase() ) {
  22587. case 'scalar':
  22588. case 'double':
  22589. case 'float':
  22590. case 'number':
  22591. case 'integer':
  22592. return NumberKeyframeTrack;
  22593. case 'vector':
  22594. case 'vector2':
  22595. case 'vector3':
  22596. case 'vector4':
  22597. return VectorKeyframeTrack;
  22598. case 'color':
  22599. return ColorKeyframeTrack;
  22600. case 'quaternion':
  22601. return QuaternionKeyframeTrack;
  22602. case 'bool':
  22603. case 'boolean':
  22604. return BooleanKeyframeTrack;
  22605. case 'string':
  22606. return StringKeyframeTrack;
  22607. }
  22608. throw new Error( 'THREE.KeyframeTrack: Unsupported typeName: ' + typeName );
  22609. }
  22610. function parseKeyframeTrack( json ) {
  22611. if ( json.type === undefined ) {
  22612. throw new Error( 'THREE.KeyframeTrack: track type undefined, can not parse' );
  22613. }
  22614. const trackType = getTrackTypeForValueTypeName( json.type );
  22615. if ( json.times === undefined ) {
  22616. const times = [], values = [];
  22617. flattenJSON( json.keys, times, values, 'value' );
  22618. json.times = times;
  22619. json.values = values;
  22620. }
  22621. // derived classes can define a static parse method
  22622. if ( trackType.parse !== undefined ) {
  22623. return trackType.parse( json );
  22624. } else {
  22625. // by default, we assume a constructor compatible with the base
  22626. return new trackType( json.name, json.times, json.values, json.interpolation );
  22627. }
  22628. }
  22629. const Cache = {
  22630. enabled: false,
  22631. files: {},
  22632. add: function ( key, file ) {
  22633. if ( this.enabled === false ) return;
  22634. // console.log( 'THREE.Cache', 'Adding key:', key );
  22635. this.files[ key ] = file;
  22636. },
  22637. get: function ( key ) {
  22638. if ( this.enabled === false ) return;
  22639. // console.log( 'THREE.Cache', 'Checking key:', key );
  22640. return this.files[ key ];
  22641. },
  22642. remove: function ( key ) {
  22643. delete this.files[ key ];
  22644. },
  22645. clear: function () {
  22646. this.files = {};
  22647. }
  22648. };
  22649. class LoadingManager {
  22650. constructor( onLoad, onProgress, onError ) {
  22651. const scope = this;
  22652. let isLoading = false;
  22653. let itemsLoaded = 0;
  22654. let itemsTotal = 0;
  22655. let urlModifier = undefined;
  22656. const handlers = [];
  22657. // Refer to #5689 for the reason why we don't set .onStart
  22658. // in the constructor
  22659. this.onStart = undefined;
  22660. this.onLoad = onLoad;
  22661. this.onProgress = onProgress;
  22662. this.onError = onError;
  22663. this.itemStart = function ( url ) {
  22664. itemsTotal ++;
  22665. if ( isLoading === false ) {
  22666. if ( scope.onStart !== undefined ) {
  22667. scope.onStart( url, itemsLoaded, itemsTotal );
  22668. }
  22669. }
  22670. isLoading = true;
  22671. };
  22672. this.itemEnd = function ( url ) {
  22673. itemsLoaded ++;
  22674. if ( scope.onProgress !== undefined ) {
  22675. scope.onProgress( url, itemsLoaded, itemsTotal );
  22676. }
  22677. if ( itemsLoaded === itemsTotal ) {
  22678. isLoading = false;
  22679. if ( scope.onLoad !== undefined ) {
  22680. scope.onLoad();
  22681. }
  22682. }
  22683. };
  22684. this.itemError = function ( url ) {
  22685. if ( scope.onError !== undefined ) {
  22686. scope.onError( url );
  22687. }
  22688. };
  22689. this.resolveURL = function ( url ) {
  22690. if ( urlModifier ) {
  22691. return urlModifier( url );
  22692. }
  22693. return url;
  22694. };
  22695. this.setURLModifier = function ( transform ) {
  22696. urlModifier = transform;
  22697. return this;
  22698. };
  22699. this.addHandler = function ( regex, loader ) {
  22700. handlers.push( regex, loader );
  22701. return this;
  22702. };
  22703. this.removeHandler = function ( regex ) {
  22704. const index = handlers.indexOf( regex );
  22705. if ( index !== -1 ) {
  22706. handlers.splice( index, 2 );
  22707. }
  22708. return this;
  22709. };
  22710. this.getHandler = function ( file ) {
  22711. for ( let i = 0, l = handlers.length; i < l; i += 2 ) {
  22712. const regex = handlers[ i ];
  22713. const loader = handlers[ i + 1 ];
  22714. if ( regex.global ) regex.lastIndex = 0; // see #17920
  22715. if ( regex.test( file ) ) {
  22716. return loader;
  22717. }
  22718. }
  22719. return null;
  22720. };
  22721. }
  22722. }
  22723. const DefaultLoadingManager = /*@__PURE__*/ new LoadingManager();
  22724. /**
  22725. * Abstract base class for loaders.
  22726. *
  22727. * @abstract
  22728. */
  22729. class Loader {
  22730. /**
  22731. * Constructs a new loader.
  22732. *
  22733. * @param {LoadingManager} [manager] - The loading manager.
  22734. */
  22735. constructor( manager ) {
  22736. /**
  22737. * The loading manager.
  22738. *
  22739. * @type {LoadingManager}
  22740. * @default DefaultLoadingManager
  22741. */
  22742. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  22743. /**
  22744. * The crossOrigin string to implement CORS for loading the url from a
  22745. * different domain that allows CORS.
  22746. *
  22747. * @type {string}
  22748. * @default 'anonymous'
  22749. */
  22750. this.crossOrigin = 'anonymous';
  22751. /**
  22752. * Whether the XMLHttpRequest uses credentials.
  22753. *
  22754. * @type {boolean}
  22755. * @default false
  22756. */
  22757. this.withCredentials = false;
  22758. /**
  22759. * The base path from which the asset will be loaded.
  22760. *
  22761. * @type {string}
  22762. */
  22763. this.path = '';
  22764. /**
  22765. * The base path from which additional resources like textures will be loaded.
  22766. *
  22767. * @type {string}
  22768. */
  22769. this.resourcePath = '';
  22770. /**
  22771. * The [request header]{@link https://developer.mozilla.org/en-US/docs/Glossary/Request_header}
  22772. * used in HTTP request.
  22773. *
  22774. * @type {Object}
  22775. */
  22776. this.requestHeader = {};
  22777. }
  22778. /**
  22779. * This method needs to be implemented by all concrete loaders. It holds the
  22780. * logic for loading assets from the backend.
  22781. *
  22782. * @param {string} url - The path/URL of the file to be loaded.
  22783. * @param {Function} onLoad - Executed when the loading process has been finished.
  22784. * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
  22785. * @param {onErrorCallback} onError - Executed when errors occur.
  22786. */
  22787. load( /* url, onLoad, onProgress, onError */ ) {}
  22788. /**
  22789. * A async version of {@link Loader#load}.
  22790. *
  22791. * @param {string} url - The path/URL of the file to be loaded.
  22792. * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
  22793. * @return {Promise} A Promise that resolves when the asset has been loaded.
  22794. */
  22795. loadAsync( url, onProgress ) {
  22796. const scope = this;
  22797. return new Promise( function ( resolve, reject ) {
  22798. scope.load( url, resolve, onProgress, reject );
  22799. } );
  22800. }
  22801. /**
  22802. * This method needs to be implemented by all concrete loaders. It holds the
  22803. * logic for parsing the asset into three.js entities.
  22804. *
  22805. * @param {any} data - The data to parse.
  22806. */
  22807. parse( /* data */ ) {}
  22808. /**
  22809. * Sets the `crossOrigin` String to implement CORS for loading the URL
  22810. * from a different domain that allows CORS.
  22811. *
  22812. * @param {string} crossOrigin - The `crossOrigin` value.
  22813. * @return {Loader} A reference to this instance.
  22814. */
  22815. setCrossOrigin( crossOrigin ) {
  22816. this.crossOrigin = crossOrigin;
  22817. return this;
  22818. }
  22819. /**
  22820. * Whether the XMLHttpRequest uses credentials such as cookies, authorization
  22821. * headers or TLS client certificates, see [XMLHttpRequest.withCredentials]{@link https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/withCredentials}.
  22822. *
  22823. * Note: This setting has no effect if you are loading files locally or from the same domain.
  22824. *
  22825. * @param {boolean} value - The `withCredentials` value.
  22826. * @return {Loader} A reference to this instance.
  22827. */
  22828. setWithCredentials( value ) {
  22829. this.withCredentials = value;
  22830. return this;
  22831. }
  22832. /**
  22833. * Sets the base path for the asset.
  22834. *
  22835. * @param {string} path - The base path.
  22836. * @return {Loader} A reference to this instance.
  22837. */
  22838. setPath( path ) {
  22839. this.path = path;
  22840. return this;
  22841. }
  22842. /**
  22843. * Sets the base path for dependent resources like textures.
  22844. *
  22845. * @param {string} resourcePath - The resource path.
  22846. * @return {Loader} A reference to this instance.
  22847. */
  22848. setResourcePath( resourcePath ) {
  22849. this.resourcePath = resourcePath;
  22850. return this;
  22851. }
  22852. /**
  22853. * Sets the given request header.
  22854. *
  22855. * @param {Object} requestHeader - A [request header]{@link https://developer.mozilla.org/en-US/docs/Glossary/Request_header}
  22856. * for configuring the HTTP request.
  22857. * @return {Loader} A reference to this instance.
  22858. */
  22859. setRequestHeader( requestHeader ) {
  22860. this.requestHeader = requestHeader;
  22861. return this;
  22862. }
  22863. }
  22864. /**
  22865. * Callback for onProgress in loaders.
  22866. *
  22867. *
  22868. * @callback onProgressCallback
  22869. * @param {ProgressEvent} event - An instance of `ProgressEvent` that represents the current loading status.
  22870. */
  22871. /**
  22872. * Callback for onError in loaders.
  22873. *
  22874. *
  22875. * @callback onErrorCallback
  22876. * @param {Error} error - The error which occured during the loading process.
  22877. */
  22878. /**
  22879. * The default material name that is used by loaders
  22880. * when creating materials for loaded 3D objects.
  22881. *
  22882. * Note: Not all loaders might honor this setting.
  22883. *
  22884. * @static
  22885. * @type {string}
  22886. * @default '__DEFAULT'
  22887. */
  22888. Loader.DEFAULT_MATERIAL_NAME = '__DEFAULT';
  22889. const loading = {};
  22890. class HttpError extends Error {
  22891. constructor( message, response ) {
  22892. super( message );
  22893. this.response = response;
  22894. }
  22895. }
  22896. class FileLoader extends Loader {
  22897. constructor( manager ) {
  22898. super( manager );
  22899. }
  22900. load( url, onLoad, onProgress, onError ) {
  22901. if ( url === undefined ) url = '';
  22902. if ( this.path !== undefined ) url = this.path + url;
  22903. url = this.manager.resolveURL( url );
  22904. const cached = Cache.get( url );
  22905. if ( cached !== undefined ) {
  22906. this.manager.itemStart( url );
  22907. setTimeout( () => {
  22908. if ( onLoad ) onLoad( cached );
  22909. this.manager.itemEnd( url );
  22910. }, 0 );
  22911. return cached;
  22912. }
  22913. // Check if request is duplicate
  22914. if ( loading[ url ] !== undefined ) {
  22915. loading[ url ].push( {
  22916. onLoad: onLoad,
  22917. onProgress: onProgress,
  22918. onError: onError
  22919. } );
  22920. return;
  22921. }
  22922. // Initialise array for duplicate requests
  22923. loading[ url ] = [];
  22924. loading[ url ].push( {
  22925. onLoad: onLoad,
  22926. onProgress: onProgress,
  22927. onError: onError,
  22928. } );
  22929. // create request
  22930. const req = new Request( url, {
  22931. headers: new Headers( this.requestHeader ),
  22932. credentials: this.withCredentials ? 'include' : 'same-origin',
  22933. // An abort controller could be added within a future PR
  22934. } );
  22935. // record states ( avoid data race )
  22936. const mimeType = this.mimeType;
  22937. const responseType = this.responseType;
  22938. // start the fetch
  22939. fetch( req )
  22940. .then( response => {
  22941. if ( response.status === 200 || response.status === 0 ) {
  22942. // Some browsers return HTTP Status 0 when using non-http protocol
  22943. // e.g. 'file://' or 'data://'. Handle as success.
  22944. if ( response.status === 0 ) {
  22945. console.warn( 'THREE.FileLoader: HTTP Status 0 received.' );
  22946. }
  22947. // Workaround: Checking if response.body === undefined for Alipay browser #23548
  22948. if ( typeof ReadableStream === 'undefined' || response.body === undefined || response.body.getReader === undefined ) {
  22949. return response;
  22950. }
  22951. const callbacks = loading[ url ];
  22952. const reader = response.body.getReader();
  22953. // Nginx needs X-File-Size check
  22954. // https://serverfault.com/questions/482875/why-does-nginx-remove-content-length-header-for-chunked-content
  22955. const contentLength = response.headers.get( 'X-File-Size' ) || response.headers.get( 'Content-Length' );
  22956. const total = contentLength ? parseInt( contentLength ) : 0;
  22957. const lengthComputable = total !== 0;
  22958. let loaded = 0;
  22959. // periodically read data into the new stream tracking while download progress
  22960. const stream = new ReadableStream( {
  22961. start( controller ) {
  22962. readData();
  22963. function readData() {
  22964. reader.read().then( ( { done, value } ) => {
  22965. if ( done ) {
  22966. controller.close();
  22967. } else {
  22968. loaded += value.byteLength;
  22969. const event = new ProgressEvent( 'progress', { lengthComputable, loaded, total } );
  22970. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  22971. const callback = callbacks[ i ];
  22972. if ( callback.onProgress ) callback.onProgress( event );
  22973. }
  22974. controller.enqueue( value );
  22975. readData();
  22976. }
  22977. }, ( e ) => {
  22978. controller.error( e );
  22979. } );
  22980. }
  22981. }
  22982. } );
  22983. return new Response( stream );
  22984. } else {
  22985. throw new HttpError( `fetch for "${response.url}" responded with ${response.status}: ${response.statusText}`, response );
  22986. }
  22987. } )
  22988. .then( response => {
  22989. switch ( responseType ) {
  22990. case 'arraybuffer':
  22991. return response.arrayBuffer();
  22992. case 'blob':
  22993. return response.blob();
  22994. case 'document':
  22995. return response.text()
  22996. .then( text => {
  22997. const parser = new DOMParser();
  22998. return parser.parseFromString( text, mimeType );
  22999. } );
  23000. case 'json':
  23001. return response.json();
  23002. default:
  23003. if ( mimeType === undefined ) {
  23004. return response.text();
  23005. } else {
  23006. // sniff encoding
  23007. const re = /charset="?([^;"\s]*)"?/i;
  23008. const exec = re.exec( mimeType );
  23009. const label = exec && exec[ 1 ] ? exec[ 1 ].toLowerCase() : undefined;
  23010. const decoder = new TextDecoder( label );
  23011. return response.arrayBuffer().then( ab => decoder.decode( ab ) );
  23012. }
  23013. }
  23014. } )
  23015. .then( data => {
  23016. // Add to cache only on HTTP success, so that we do not cache
  23017. // error response bodies as proper responses to requests.
  23018. Cache.add( url, data );
  23019. const callbacks = loading[ url ];
  23020. delete loading[ url ];
  23021. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  23022. const callback = callbacks[ i ];
  23023. if ( callback.onLoad ) callback.onLoad( data );
  23024. }
  23025. } )
  23026. .catch( err => {
  23027. // Abort errors and other errors are handled the same
  23028. const callbacks = loading[ url ];
  23029. if ( callbacks === undefined ) {
  23030. // When onLoad was called and url was deleted in `loading`
  23031. this.manager.itemError( url );
  23032. throw err;
  23033. }
  23034. delete loading[ url ];
  23035. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  23036. const callback = callbacks[ i ];
  23037. if ( callback.onError ) callback.onError( err );
  23038. }
  23039. this.manager.itemError( url );
  23040. } )
  23041. .finally( () => {
  23042. this.manager.itemEnd( url );
  23043. } );
  23044. this.manager.itemStart( url );
  23045. }
  23046. setResponseType( value ) {
  23047. this.responseType = value;
  23048. return this;
  23049. }
  23050. setMimeType( value ) {
  23051. this.mimeType = value;
  23052. return this;
  23053. }
  23054. }
  23055. class AnimationLoader extends Loader {
  23056. constructor( manager ) {
  23057. super( manager );
  23058. }
  23059. load( url, onLoad, onProgress, onError ) {
  23060. const scope = this;
  23061. const loader = new FileLoader( this.manager );
  23062. loader.setPath( this.path );
  23063. loader.setRequestHeader( this.requestHeader );
  23064. loader.setWithCredentials( this.withCredentials );
  23065. loader.load( url, function ( text ) {
  23066. try {
  23067. onLoad( scope.parse( JSON.parse( text ) ) );
  23068. } catch ( e ) {
  23069. if ( onError ) {
  23070. onError( e );
  23071. } else {
  23072. console.error( e );
  23073. }
  23074. scope.manager.itemError( url );
  23075. }
  23076. }, onProgress, onError );
  23077. }
  23078. parse( json ) {
  23079. const animations = [];
  23080. for ( let i = 0; i < json.length; i ++ ) {
  23081. const clip = AnimationClip.parse( json[ i ] );
  23082. animations.push( clip );
  23083. }
  23084. return animations;
  23085. }
  23086. }
  23087. /**
  23088. * Abstract Base class to block based textures loader (dds, pvr, ...)
  23089. *
  23090. * Sub classes have to implement the parse() method which will be used in load().
  23091. */
  23092. class CompressedTextureLoader extends Loader {
  23093. constructor( manager ) {
  23094. super( manager );
  23095. }
  23096. load( url, onLoad, onProgress, onError ) {
  23097. const scope = this;
  23098. const images = [];
  23099. const texture = new CompressedTexture();
  23100. const loader = new FileLoader( this.manager );
  23101. loader.setPath( this.path );
  23102. loader.setResponseType( 'arraybuffer' );
  23103. loader.setRequestHeader( this.requestHeader );
  23104. loader.setWithCredentials( scope.withCredentials );
  23105. let loaded = 0;
  23106. function loadTexture( i ) {
  23107. loader.load( url[ i ], function ( buffer ) {
  23108. const texDatas = scope.parse( buffer, true );
  23109. images[ i ] = {
  23110. width: texDatas.width,
  23111. height: texDatas.height,
  23112. format: texDatas.format,
  23113. mipmaps: texDatas.mipmaps
  23114. };
  23115. loaded += 1;
  23116. if ( loaded === 6 ) {
  23117. if ( texDatas.mipmapCount === 1 ) texture.minFilter = LinearFilter;
  23118. texture.image = images;
  23119. texture.format = texDatas.format;
  23120. texture.needsUpdate = true;
  23121. if ( onLoad ) onLoad( texture );
  23122. }
  23123. }, onProgress, onError );
  23124. }
  23125. if ( Array.isArray( url ) ) {
  23126. for ( let i = 0, il = url.length; i < il; ++ i ) {
  23127. loadTexture( i );
  23128. }
  23129. } else {
  23130. // compressed cubemap texture stored in a single DDS file
  23131. loader.load( url, function ( buffer ) {
  23132. const texDatas = scope.parse( buffer, true );
  23133. if ( texDatas.isCubemap ) {
  23134. const faces = texDatas.mipmaps.length / texDatas.mipmapCount;
  23135. for ( let f = 0; f < faces; f ++ ) {
  23136. images[ f ] = { mipmaps: [] };
  23137. for ( let i = 0; i < texDatas.mipmapCount; i ++ ) {
  23138. images[ f ].mipmaps.push( texDatas.mipmaps[ f * texDatas.mipmapCount + i ] );
  23139. images[ f ].format = texDatas.format;
  23140. images[ f ].width = texDatas.width;
  23141. images[ f ].height = texDatas.height;
  23142. }
  23143. }
  23144. texture.image = images;
  23145. } else {
  23146. texture.image.width = texDatas.width;
  23147. texture.image.height = texDatas.height;
  23148. texture.mipmaps = texDatas.mipmaps;
  23149. }
  23150. if ( texDatas.mipmapCount === 1 ) {
  23151. texture.minFilter = LinearFilter;
  23152. }
  23153. texture.format = texDatas.format;
  23154. texture.needsUpdate = true;
  23155. if ( onLoad ) onLoad( texture );
  23156. }, onProgress, onError );
  23157. }
  23158. return texture;
  23159. }
  23160. }
  23161. class ImageLoader extends Loader {
  23162. constructor( manager ) {
  23163. super( manager );
  23164. }
  23165. load( url, onLoad, onProgress, onError ) {
  23166. if ( this.path !== undefined ) url = this.path + url;
  23167. url = this.manager.resolveURL( url );
  23168. const scope = this;
  23169. const cached = Cache.get( url );
  23170. if ( cached !== undefined ) {
  23171. scope.manager.itemStart( url );
  23172. setTimeout( function () {
  23173. if ( onLoad ) onLoad( cached );
  23174. scope.manager.itemEnd( url );
  23175. }, 0 );
  23176. return cached;
  23177. }
  23178. const image = createElementNS( 'img' );
  23179. function onImageLoad() {
  23180. removeEventListeners();
  23181. Cache.add( url, this );
  23182. if ( onLoad ) onLoad( this );
  23183. scope.manager.itemEnd( url );
  23184. }
  23185. function onImageError( event ) {
  23186. removeEventListeners();
  23187. if ( onError ) onError( event );
  23188. scope.manager.itemError( url );
  23189. scope.manager.itemEnd( url );
  23190. }
  23191. function removeEventListeners() {
  23192. image.removeEventListener( 'load', onImageLoad, false );
  23193. image.removeEventListener( 'error', onImageError, false );
  23194. }
  23195. image.addEventListener( 'load', onImageLoad, false );
  23196. image.addEventListener( 'error', onImageError, false );
  23197. if ( url.slice( 0, 5 ) !== 'data:' ) {
  23198. if ( this.crossOrigin !== undefined ) image.crossOrigin = this.crossOrigin;
  23199. }
  23200. scope.manager.itemStart( url );
  23201. image.src = url;
  23202. return image;
  23203. }
  23204. }
  23205. class CubeTextureLoader extends Loader {
  23206. constructor( manager ) {
  23207. super( manager );
  23208. }
  23209. load( urls, onLoad, onProgress, onError ) {
  23210. const texture = new CubeTexture();
  23211. texture.colorSpace = SRGBColorSpace;
  23212. const loader = new ImageLoader( this.manager );
  23213. loader.setCrossOrigin( this.crossOrigin );
  23214. loader.setPath( this.path );
  23215. let loaded = 0;
  23216. function loadTexture( i ) {
  23217. loader.load( urls[ i ], function ( image ) {
  23218. texture.images[ i ] = image;
  23219. loaded ++;
  23220. if ( loaded === 6 ) {
  23221. texture.needsUpdate = true;
  23222. if ( onLoad ) onLoad( texture );
  23223. }
  23224. }, undefined, onError );
  23225. }
  23226. for ( let i = 0; i < urls.length; ++ i ) {
  23227. loadTexture( i );
  23228. }
  23229. return texture;
  23230. }
  23231. }
  23232. /**
  23233. * Abstract Base class to load generic binary textures formats (rgbe, hdr, ...)
  23234. *
  23235. * Sub classes have to implement the parse() method which will be used in load().
  23236. */
  23237. class DataTextureLoader extends Loader {
  23238. constructor( manager ) {
  23239. super( manager );
  23240. }
  23241. load( url, onLoad, onProgress, onError ) {
  23242. const scope = this;
  23243. const texture = new DataTexture();
  23244. const loader = new FileLoader( this.manager );
  23245. loader.setResponseType( 'arraybuffer' );
  23246. loader.setRequestHeader( this.requestHeader );
  23247. loader.setPath( this.path );
  23248. loader.setWithCredentials( scope.withCredentials );
  23249. loader.load( url, function ( buffer ) {
  23250. let texData;
  23251. try {
  23252. texData = scope.parse( buffer );
  23253. } catch ( error ) {
  23254. if ( onError !== undefined ) {
  23255. onError( error );
  23256. } else {
  23257. console.error( error );
  23258. return;
  23259. }
  23260. }
  23261. if ( texData.image !== undefined ) {
  23262. texture.image = texData.image;
  23263. } else if ( texData.data !== undefined ) {
  23264. texture.image.width = texData.width;
  23265. texture.image.height = texData.height;
  23266. texture.image.data = texData.data;
  23267. }
  23268. texture.wrapS = texData.wrapS !== undefined ? texData.wrapS : ClampToEdgeWrapping;
  23269. texture.wrapT = texData.wrapT !== undefined ? texData.wrapT : ClampToEdgeWrapping;
  23270. texture.magFilter = texData.magFilter !== undefined ? texData.magFilter : LinearFilter;
  23271. texture.minFilter = texData.minFilter !== undefined ? texData.minFilter : LinearFilter;
  23272. texture.anisotropy = texData.anisotropy !== undefined ? texData.anisotropy : 1;
  23273. if ( texData.colorSpace !== undefined ) {
  23274. texture.colorSpace = texData.colorSpace;
  23275. }
  23276. if ( texData.flipY !== undefined ) {
  23277. texture.flipY = texData.flipY;
  23278. }
  23279. if ( texData.format !== undefined ) {
  23280. texture.format = texData.format;
  23281. }
  23282. if ( texData.type !== undefined ) {
  23283. texture.type = texData.type;
  23284. }
  23285. if ( texData.mipmaps !== undefined ) {
  23286. texture.mipmaps = texData.mipmaps;
  23287. texture.minFilter = LinearMipmapLinearFilter; // presumably...
  23288. }
  23289. if ( texData.mipmapCount === 1 ) {
  23290. texture.minFilter = LinearFilter;
  23291. }
  23292. if ( texData.generateMipmaps !== undefined ) {
  23293. texture.generateMipmaps = texData.generateMipmaps;
  23294. }
  23295. texture.needsUpdate = true;
  23296. if ( onLoad ) onLoad( texture, texData );
  23297. }, onProgress, onError );
  23298. return texture;
  23299. }
  23300. }
  23301. class TextureLoader extends Loader {
  23302. constructor( manager ) {
  23303. super( manager );
  23304. }
  23305. load( url, onLoad, onProgress, onError ) {
  23306. const texture = new Texture();
  23307. const loader = new ImageLoader( this.manager );
  23308. loader.setCrossOrigin( this.crossOrigin );
  23309. loader.setPath( this.path );
  23310. loader.load( url, function ( image ) {
  23311. texture.image = image;
  23312. texture.needsUpdate = true;
  23313. if ( onLoad !== undefined ) {
  23314. onLoad( texture );
  23315. }
  23316. }, onProgress, onError );
  23317. return texture;
  23318. }
  23319. }
  23320. class Light extends Object3D {
  23321. constructor( color, intensity = 1 ) {
  23322. super();
  23323. this.isLight = true;
  23324. this.type = 'Light';
  23325. this.color = new Color( color );
  23326. this.intensity = intensity;
  23327. }
  23328. dispose() {
  23329. // Empty here in base class; some subclasses override.
  23330. }
  23331. copy( source, recursive ) {
  23332. super.copy( source, recursive );
  23333. this.color.copy( source.color );
  23334. this.intensity = source.intensity;
  23335. return this;
  23336. }
  23337. toJSON( meta ) {
  23338. const data = super.toJSON( meta );
  23339. data.object.color = this.color.getHex();
  23340. data.object.intensity = this.intensity;
  23341. if ( this.groundColor !== undefined ) data.object.groundColor = this.groundColor.getHex();
  23342. if ( this.distance !== undefined ) data.object.distance = this.distance;
  23343. if ( this.angle !== undefined ) data.object.angle = this.angle;
  23344. if ( this.decay !== undefined ) data.object.decay = this.decay;
  23345. if ( this.penumbra !== undefined ) data.object.penumbra = this.penumbra;
  23346. if ( this.shadow !== undefined ) data.object.shadow = this.shadow.toJSON();
  23347. if ( this.target !== undefined ) data.object.target = this.target.uuid;
  23348. return data;
  23349. }
  23350. }
  23351. class HemisphereLight extends Light {
  23352. constructor( skyColor, groundColor, intensity ) {
  23353. super( skyColor, intensity );
  23354. this.isHemisphereLight = true;
  23355. this.type = 'HemisphereLight';
  23356. this.position.copy( Object3D.DEFAULT_UP );
  23357. this.updateMatrix();
  23358. this.groundColor = new Color( groundColor );
  23359. }
  23360. copy( source, recursive ) {
  23361. super.copy( source, recursive );
  23362. this.groundColor.copy( source.groundColor );
  23363. return this;
  23364. }
  23365. }
  23366. const _projScreenMatrix$1 = /*@__PURE__*/ new Matrix4();
  23367. const _lightPositionWorld$1 = /*@__PURE__*/ new Vector3();
  23368. const _lookTarget$1 = /*@__PURE__*/ new Vector3();
  23369. class LightShadow {
  23370. constructor( camera ) {
  23371. this.camera = camera;
  23372. this.intensity = 1;
  23373. this.bias = 0;
  23374. this.normalBias = 0;
  23375. this.radius = 1;
  23376. this.blurSamples = 8;
  23377. this.mapSize = new Vector2( 512, 512 );
  23378. this.map = null;
  23379. this.mapPass = null;
  23380. this.matrix = new Matrix4();
  23381. this.autoUpdate = true;
  23382. this.needsUpdate = false;
  23383. this._frustum = new Frustum();
  23384. this._frameExtents = new Vector2( 1, 1 );
  23385. this._viewportCount = 1;
  23386. this._viewports = [
  23387. new Vector4( 0, 0, 1, 1 )
  23388. ];
  23389. }
  23390. getViewportCount() {
  23391. return this._viewportCount;
  23392. }
  23393. getFrustum() {
  23394. return this._frustum;
  23395. }
  23396. updateMatrices( light ) {
  23397. const shadowCamera = this.camera;
  23398. const shadowMatrix = this.matrix;
  23399. _lightPositionWorld$1.setFromMatrixPosition( light.matrixWorld );
  23400. shadowCamera.position.copy( _lightPositionWorld$1 );
  23401. _lookTarget$1.setFromMatrixPosition( light.target.matrixWorld );
  23402. shadowCamera.lookAt( _lookTarget$1 );
  23403. shadowCamera.updateMatrixWorld();
  23404. _projScreenMatrix$1.multiplyMatrices( shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse );
  23405. this._frustum.setFromProjectionMatrix( _projScreenMatrix$1 );
  23406. shadowMatrix.set(
  23407. 0.5, 0.0, 0.0, 0.5,
  23408. 0.0, 0.5, 0.0, 0.5,
  23409. 0.0, 0.0, 0.5, 0.5,
  23410. 0.0, 0.0, 0.0, 1.0
  23411. );
  23412. shadowMatrix.multiply( _projScreenMatrix$1 );
  23413. }
  23414. getViewport( viewportIndex ) {
  23415. return this._viewports[ viewportIndex ];
  23416. }
  23417. getFrameExtents() {
  23418. return this._frameExtents;
  23419. }
  23420. dispose() {
  23421. if ( this.map ) {
  23422. this.map.dispose();
  23423. }
  23424. if ( this.mapPass ) {
  23425. this.mapPass.dispose();
  23426. }
  23427. }
  23428. copy( source ) {
  23429. this.camera = source.camera.clone();
  23430. this.intensity = source.intensity;
  23431. this.bias = source.bias;
  23432. this.radius = source.radius;
  23433. this.mapSize.copy( source.mapSize );
  23434. return this;
  23435. }
  23436. clone() {
  23437. return new this.constructor().copy( this );
  23438. }
  23439. toJSON() {
  23440. const object = {};
  23441. if ( this.intensity !== 1 ) object.intensity = this.intensity;
  23442. if ( this.bias !== 0 ) object.bias = this.bias;
  23443. if ( this.normalBias !== 0 ) object.normalBias = this.normalBias;
  23444. if ( this.radius !== 1 ) object.radius = this.radius;
  23445. if ( this.mapSize.x !== 512 || this.mapSize.y !== 512 ) object.mapSize = this.mapSize.toArray();
  23446. object.camera = this.camera.toJSON( false ).object;
  23447. delete object.camera.matrix;
  23448. return object;
  23449. }
  23450. }
  23451. class SpotLightShadow extends LightShadow {
  23452. constructor() {
  23453. super( new PerspectiveCamera( 50, 1, 0.5, 500 ) );
  23454. this.isSpotLightShadow = true;
  23455. this.focus = 1;
  23456. }
  23457. updateMatrices( light ) {
  23458. const camera = this.camera;
  23459. const fov = RAD2DEG * 2 * light.angle * this.focus;
  23460. const aspect = this.mapSize.width / this.mapSize.height;
  23461. const far = light.distance || camera.far;
  23462. if ( fov !== camera.fov || aspect !== camera.aspect || far !== camera.far ) {
  23463. camera.fov = fov;
  23464. camera.aspect = aspect;
  23465. camera.far = far;
  23466. camera.updateProjectionMatrix();
  23467. }
  23468. super.updateMatrices( light );
  23469. }
  23470. copy( source ) {
  23471. super.copy( source );
  23472. this.focus = source.focus;
  23473. return this;
  23474. }
  23475. }
  23476. class SpotLight extends Light {
  23477. constructor( color, intensity, distance = 0, angle = Math.PI / 3, penumbra = 0, decay = 2 ) {
  23478. super( color, intensity );
  23479. this.isSpotLight = true;
  23480. this.type = 'SpotLight';
  23481. this.position.copy( Object3D.DEFAULT_UP );
  23482. this.updateMatrix();
  23483. this.target = new Object3D();
  23484. this.distance = distance;
  23485. this.angle = angle;
  23486. this.penumbra = penumbra;
  23487. this.decay = decay;
  23488. this.map = null;
  23489. this.shadow = new SpotLightShadow();
  23490. }
  23491. get power() {
  23492. // compute the light's luminous power (in lumens) from its intensity (in candela)
  23493. // by convention for a spotlight, luminous power (lm) = π * luminous intensity (cd)
  23494. return this.intensity * Math.PI;
  23495. }
  23496. set power( power ) {
  23497. // set the light's intensity (in candela) from the desired luminous power (in lumens)
  23498. this.intensity = power / Math.PI;
  23499. }
  23500. dispose() {
  23501. this.shadow.dispose();
  23502. }
  23503. copy( source, recursive ) {
  23504. super.copy( source, recursive );
  23505. this.distance = source.distance;
  23506. this.angle = source.angle;
  23507. this.penumbra = source.penumbra;
  23508. this.decay = source.decay;
  23509. this.target = source.target.clone();
  23510. this.shadow = source.shadow.clone();
  23511. return this;
  23512. }
  23513. }
  23514. const _projScreenMatrix = /*@__PURE__*/ new Matrix4();
  23515. const _lightPositionWorld = /*@__PURE__*/ new Vector3();
  23516. const _lookTarget = /*@__PURE__*/ new Vector3();
  23517. class PointLightShadow extends LightShadow {
  23518. constructor() {
  23519. super( new PerspectiveCamera( 90, 1, 0.5, 500 ) );
  23520. this.isPointLightShadow = true;
  23521. this._frameExtents = new Vector2( 4, 2 );
  23522. this._viewportCount = 6;
  23523. this._viewports = [
  23524. // These viewports map a cube-map onto a 2D texture with the
  23525. // following orientation:
  23526. //
  23527. // xzXZ
  23528. // y Y
  23529. //
  23530. // X - Positive x direction
  23531. // x - Negative x direction
  23532. // Y - Positive y direction
  23533. // y - Negative y direction
  23534. // Z - Positive z direction
  23535. // z - Negative z direction
  23536. // positive X
  23537. new Vector4( 2, 1, 1, 1 ),
  23538. // negative X
  23539. new Vector4( 0, 1, 1, 1 ),
  23540. // positive Z
  23541. new Vector4( 3, 1, 1, 1 ),
  23542. // negative Z
  23543. new Vector4( 1, 1, 1, 1 ),
  23544. // positive Y
  23545. new Vector4( 3, 0, 1, 1 ),
  23546. // negative Y
  23547. new Vector4( 1, 0, 1, 1 )
  23548. ];
  23549. this._cubeDirections = [
  23550. new Vector3( 1, 0, 0 ), new Vector3( -1, 0, 0 ), new Vector3( 0, 0, 1 ),
  23551. new Vector3( 0, 0, -1 ), new Vector3( 0, 1, 0 ), new Vector3( 0, -1, 0 )
  23552. ];
  23553. this._cubeUps = [
  23554. new Vector3( 0, 1, 0 ), new Vector3( 0, 1, 0 ), new Vector3( 0, 1, 0 ),
  23555. new Vector3( 0, 1, 0 ), new Vector3( 0, 0, 1 ), new Vector3( 0, 0, -1 )
  23556. ];
  23557. }
  23558. updateMatrices( light, viewportIndex = 0 ) {
  23559. const camera = this.camera;
  23560. const shadowMatrix = this.matrix;
  23561. const far = light.distance || camera.far;
  23562. if ( far !== camera.far ) {
  23563. camera.far = far;
  23564. camera.updateProjectionMatrix();
  23565. }
  23566. _lightPositionWorld.setFromMatrixPosition( light.matrixWorld );
  23567. camera.position.copy( _lightPositionWorld );
  23568. _lookTarget.copy( camera.position );
  23569. _lookTarget.add( this._cubeDirections[ viewportIndex ] );
  23570. camera.up.copy( this._cubeUps[ viewportIndex ] );
  23571. camera.lookAt( _lookTarget );
  23572. camera.updateMatrixWorld();
  23573. shadowMatrix.makeTranslation( - _lightPositionWorld.x, - _lightPositionWorld.y, - _lightPositionWorld.z );
  23574. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  23575. this._frustum.setFromProjectionMatrix( _projScreenMatrix );
  23576. }
  23577. }
  23578. class PointLight extends Light {
  23579. constructor( color, intensity, distance = 0, decay = 2 ) {
  23580. super( color, intensity );
  23581. this.isPointLight = true;
  23582. this.type = 'PointLight';
  23583. this.distance = distance;
  23584. this.decay = decay;
  23585. this.shadow = new PointLightShadow();
  23586. }
  23587. get power() {
  23588. // compute the light's luminous power (in lumens) from its intensity (in candela)
  23589. // for an isotropic light source, luminous power (lm) = 4 π luminous intensity (cd)
  23590. return this.intensity * 4 * Math.PI;
  23591. }
  23592. set power( power ) {
  23593. // set the light's intensity (in candela) from the desired luminous power (in lumens)
  23594. this.intensity = power / ( 4 * Math.PI );
  23595. }
  23596. dispose() {
  23597. this.shadow.dispose();
  23598. }
  23599. copy( source, recursive ) {
  23600. super.copy( source, recursive );
  23601. this.distance = source.distance;
  23602. this.decay = source.decay;
  23603. this.shadow = source.shadow.clone();
  23604. return this;
  23605. }
  23606. }
  23607. /**
  23608. * Camera that uses [orthographic projection]{@link https://en.wikipedia.org/wiki/Orthographic_projection}.
  23609. *
  23610. * In this projection mode, an object's size in the rendered image stays
  23611. * constant regardless of its distance from the camera. This can be useful
  23612. * for rendering 2D scenes and UI elements, amongst other things.
  23613. *
  23614. * @augments Camera
  23615. */
  23616. class OrthographicCamera extends Camera {
  23617. /**
  23618. * Constructs a new orthographic camera.
  23619. *
  23620. * @param {number} [left=-1] - The left plane of the camera's frustum.
  23621. * @param {number} [right=1] - The right plane of the camera's frustum.
  23622. * @param {number} [top=1] - The top plane of the camera's frustum.
  23623. * @param {number} [bottom=-1] - The bottom plane of the camera's frustum.
  23624. * @param {number} [near=0.1] - The camera's near plane.
  23625. * @param {number} [far=2000] - The camera's far plane.
  23626. */
  23627. constructor( left = -1, right = 1, top = 1, bottom = -1, near = 0.1, far = 2000 ) {
  23628. super();
  23629. /**
  23630. * This flag can be used for type testing.
  23631. *
  23632. * @type {boolean}
  23633. * @readonly
  23634. * @default true
  23635. */
  23636. this.isOrthographicCamera = true;
  23637. this.type = 'OrthographicCamera';
  23638. /**
  23639. * The zoom factor of the camera.
  23640. *
  23641. * @type {number}
  23642. * @default 1
  23643. */
  23644. this.zoom = 1;
  23645. /**
  23646. * Represents the frustum window specification. This property should not be edited
  23647. * directly but via {@link PerspectiveCamera#setViewOffset} and {@link PerspectiveCamera#clearViewOffset}.
  23648. *
  23649. * @type {?Object}
  23650. * @default null
  23651. */
  23652. this.view = null;
  23653. /**
  23654. * The left plane of the camera's frustum.
  23655. *
  23656. * @type {number}
  23657. * @default -1
  23658. */
  23659. this.left = left;
  23660. /**
  23661. * The right plane of the camera's frustum.
  23662. *
  23663. * @type {number}
  23664. * @default 1
  23665. */
  23666. this.right = right;
  23667. /**
  23668. * The top plane of the camera's frustum.
  23669. *
  23670. * @type {number}
  23671. * @default 1
  23672. */
  23673. this.top = top;
  23674. /**
  23675. * The bottom plane of the camera's frustum.
  23676. *
  23677. * @type {number}
  23678. * @default -1
  23679. */
  23680. this.bottom = bottom;
  23681. /**
  23682. * The camera's near plane. The valid range is greater than `0`
  23683. * and less than the current value of {@link OrthographicCamera#far}.
  23684. *
  23685. * Note that, unlike for the {@link PerspectiveCamera}, `0` is a
  23686. * valid value for an orthographic camera's near plane.
  23687. *
  23688. * @type {number}
  23689. * @default 0.1
  23690. */
  23691. this.near = near;
  23692. /**
  23693. * The camera's far plane. Must be greater than the
  23694. * current value of {@link OrthographicCamera#near}.
  23695. *
  23696. * @type {number}
  23697. * @default 2000
  23698. */
  23699. this.far = far;
  23700. this.updateProjectionMatrix();
  23701. }
  23702. copy( source, recursive ) {
  23703. super.copy( source, recursive );
  23704. this.left = source.left;
  23705. this.right = source.right;
  23706. this.top = source.top;
  23707. this.bottom = source.bottom;
  23708. this.near = source.near;
  23709. this.far = source.far;
  23710. this.zoom = source.zoom;
  23711. this.view = source.view === null ? null : Object.assign( {}, source.view );
  23712. return this;
  23713. }
  23714. /**
  23715. * Sets an offset in a larger frustum. This is useful for multi-window or
  23716. * multi-monitor/multi-machine setups.
  23717. *
  23718. * @param {number} fullWidth - The full width of multiview setup.
  23719. * @param {number} fullHeight - The full height of multiview setup.
  23720. * @param {number} x - The horizontal offset of the subcamera.
  23721. * @param {number} y - The vertical offset of the subcamera.
  23722. * @param {number} width - The width of subcamera.
  23723. * @param {number} height - The height of subcamera.
  23724. * @see {@link PerspectiveCamera#setViewOffset}
  23725. */
  23726. setViewOffset( fullWidth, fullHeight, x, y, width, height ) {
  23727. if ( this.view === null ) {
  23728. this.view = {
  23729. enabled: true,
  23730. fullWidth: 1,
  23731. fullHeight: 1,
  23732. offsetX: 0,
  23733. offsetY: 0,
  23734. width: 1,
  23735. height: 1
  23736. };
  23737. }
  23738. this.view.enabled = true;
  23739. this.view.fullWidth = fullWidth;
  23740. this.view.fullHeight = fullHeight;
  23741. this.view.offsetX = x;
  23742. this.view.offsetY = y;
  23743. this.view.width = width;
  23744. this.view.height = height;
  23745. this.updateProjectionMatrix();
  23746. }
  23747. /**
  23748. * Removes the view offset from the projection matrix.
  23749. */
  23750. clearViewOffset() {
  23751. if ( this.view !== null ) {
  23752. this.view.enabled = false;
  23753. }
  23754. this.updateProjectionMatrix();
  23755. }
  23756. /**
  23757. * Updates the camera's projection matrix. Must be called after any change of
  23758. * camera properties.
  23759. */
  23760. updateProjectionMatrix() {
  23761. const dx = ( this.right - this.left ) / ( 2 * this.zoom );
  23762. const dy = ( this.top - this.bottom ) / ( 2 * this.zoom );
  23763. const cx = ( this.right + this.left ) / 2;
  23764. const cy = ( this.top + this.bottom ) / 2;
  23765. let left = cx - dx;
  23766. let right = cx + dx;
  23767. let top = cy + dy;
  23768. let bottom = cy - dy;
  23769. if ( this.view !== null && this.view.enabled ) {
  23770. const scaleW = ( this.right - this.left ) / this.view.fullWidth / this.zoom;
  23771. const scaleH = ( this.top - this.bottom ) / this.view.fullHeight / this.zoom;
  23772. left += scaleW * this.view.offsetX;
  23773. right = left + scaleW * this.view.width;
  23774. top -= scaleH * this.view.offsetY;
  23775. bottom = top - scaleH * this.view.height;
  23776. }
  23777. this.projectionMatrix.makeOrthographic( left, right, top, bottom, this.near, this.far, this.coordinateSystem );
  23778. this.projectionMatrixInverse.copy( this.projectionMatrix ).invert();
  23779. }
  23780. toJSON( meta ) {
  23781. const data = super.toJSON( meta );
  23782. data.object.zoom = this.zoom;
  23783. data.object.left = this.left;
  23784. data.object.right = this.right;
  23785. data.object.top = this.top;
  23786. data.object.bottom = this.bottom;
  23787. data.object.near = this.near;
  23788. data.object.far = this.far;
  23789. if ( this.view !== null ) data.object.view = Object.assign( {}, this.view );
  23790. return data;
  23791. }
  23792. }
  23793. class DirectionalLightShadow extends LightShadow {
  23794. constructor() {
  23795. super( new OrthographicCamera( -5, 5, 5, -5, 0.5, 500 ) );
  23796. this.isDirectionalLightShadow = true;
  23797. }
  23798. }
  23799. class DirectionalLight extends Light {
  23800. constructor( color, intensity ) {
  23801. super( color, intensity );
  23802. this.isDirectionalLight = true;
  23803. this.type = 'DirectionalLight';
  23804. this.position.copy( Object3D.DEFAULT_UP );
  23805. this.updateMatrix();
  23806. this.target = new Object3D();
  23807. this.shadow = new DirectionalLightShadow();
  23808. }
  23809. dispose() {
  23810. this.shadow.dispose();
  23811. }
  23812. copy( source ) {
  23813. super.copy( source );
  23814. this.target = source.target.clone();
  23815. this.shadow = source.shadow.clone();
  23816. return this;
  23817. }
  23818. }
  23819. class AmbientLight extends Light {
  23820. constructor( color, intensity ) {
  23821. super( color, intensity );
  23822. this.isAmbientLight = true;
  23823. this.type = 'AmbientLight';
  23824. }
  23825. }
  23826. class RectAreaLight extends Light {
  23827. constructor( color, intensity, width = 10, height = 10 ) {
  23828. super( color, intensity );
  23829. this.isRectAreaLight = true;
  23830. this.type = 'RectAreaLight';
  23831. this.width = width;
  23832. this.height = height;
  23833. }
  23834. get power() {
  23835. // compute the light's luminous power (in lumens) from its intensity (in nits)
  23836. return this.intensity * this.width * this.height * Math.PI;
  23837. }
  23838. set power( power ) {
  23839. // set the light's intensity (in nits) from the desired luminous power (in lumens)
  23840. this.intensity = power / ( this.width * this.height * Math.PI );
  23841. }
  23842. copy( source ) {
  23843. super.copy( source );
  23844. this.width = source.width;
  23845. this.height = source.height;
  23846. return this;
  23847. }
  23848. toJSON( meta ) {
  23849. const data = super.toJSON( meta );
  23850. data.object.width = this.width;
  23851. data.object.height = this.height;
  23852. return data;
  23853. }
  23854. }
  23855. /**
  23856. * Represents a third-order spherical harmonics (SH). Light probes use this class
  23857. * to encode lighting information.
  23858. *
  23859. * - Primary reference: {@link https://graphics.stanford.edu/papers/envmap/envmap.pdf}
  23860. * - Secondary reference: {@link https://www.ppsloan.org/publications/StupidSH36.pdf}
  23861. */
  23862. class SphericalHarmonics3 {
  23863. /**
  23864. * Constructs a new spherical harmonics.
  23865. */
  23866. constructor() {
  23867. /**
  23868. * This flag can be used for type testing.
  23869. *
  23870. * @type {boolean}
  23871. * @readonly
  23872. * @default true
  23873. */
  23874. this.isSphericalHarmonics3 = true;
  23875. /**
  23876. * An array holding the (9) SH coefficients.
  23877. *
  23878. * @type {Array<Vector3>}
  23879. */
  23880. this.coefficients = [];
  23881. for ( let i = 0; i < 9; i ++ ) {
  23882. this.coefficients.push( new Vector3() );
  23883. }
  23884. }
  23885. /**
  23886. * Sets the given SH coefficients to this instance by copying
  23887. * the values.
  23888. *
  23889. * @param {Array<Vector3>} coefficients - The SH coefficients.
  23890. * @return {SphericalHarmonics3} A reference to this spherical harmonics.
  23891. */
  23892. set( coefficients ) {
  23893. for ( let i = 0; i < 9; i ++ ) {
  23894. this.coefficients[ i ].copy( coefficients[ i ] );
  23895. }
  23896. return this;
  23897. }
  23898. /**
  23899. * Sets all SH coefficients to `0`.
  23900. *
  23901. * @return {SphericalHarmonics3} A reference to this spherical harmonics.
  23902. */
  23903. zero() {
  23904. for ( let i = 0; i < 9; i ++ ) {
  23905. this.coefficients[ i ].set( 0, 0, 0 );
  23906. }
  23907. return this;
  23908. }
  23909. /**
  23910. * Returns the radiance in the direction of the given normal.
  23911. *
  23912. * @param {Vector3} normal - The normal vector (assumed to be unit length)
  23913. * @param {Vector3} target - The target vector that is used to store the method's result.
  23914. * @return {Vector3} The radiance.
  23915. */
  23916. getAt( normal, target ) {
  23917. // normal is assumed to be unit length
  23918. const x = normal.x, y = normal.y, z = normal.z;
  23919. const coeff = this.coefficients;
  23920. // band 0
  23921. target.copy( coeff[ 0 ] ).multiplyScalar( 0.282095 );
  23922. // band 1
  23923. target.addScaledVector( coeff[ 1 ], 0.488603 * y );
  23924. target.addScaledVector( coeff[ 2 ], 0.488603 * z );
  23925. target.addScaledVector( coeff[ 3 ], 0.488603 * x );
  23926. // band 2
  23927. target.addScaledVector( coeff[ 4 ], 1.092548 * ( x * y ) );
  23928. target.addScaledVector( coeff[ 5 ], 1.092548 * ( y * z ) );
  23929. target.addScaledVector( coeff[ 6 ], 0.315392 * ( 3.0 * z * z - 1.0 ) );
  23930. target.addScaledVector( coeff[ 7 ], 1.092548 * ( x * z ) );
  23931. target.addScaledVector( coeff[ 8 ], 0.546274 * ( x * x - y * y ) );
  23932. return target;
  23933. }
  23934. /**
  23935. * Returns the irradiance (radiance convolved with cosine lobe) in the
  23936. * direction of the given normal.
  23937. *
  23938. * @param {Vector3} normal - The normal vector (assumed to be unit length)
  23939. * @param {Vector3} target - The target vector that is used to store the method's result.
  23940. * @return {Vector3} The irradiance.
  23941. */
  23942. getIrradianceAt( normal, target ) {
  23943. // normal is assumed to be unit length
  23944. const x = normal.x, y = normal.y, z = normal.z;
  23945. const coeff = this.coefficients;
  23946. // band 0
  23947. target.copy( coeff[ 0 ] ).multiplyScalar( 0.886227 ); // π * 0.282095
  23948. // band 1
  23949. target.addScaledVector( coeff[ 1 ], 2.0 * 0.511664 * y ); // ( 2 * π / 3 ) * 0.488603
  23950. target.addScaledVector( coeff[ 2 ], 2.0 * 0.511664 * z );
  23951. target.addScaledVector( coeff[ 3 ], 2.0 * 0.511664 * x );
  23952. // band 2
  23953. target.addScaledVector( coeff[ 4 ], 2.0 * 0.429043 * x * y ); // ( π / 4 ) * 1.092548
  23954. target.addScaledVector( coeff[ 5 ], 2.0 * 0.429043 * y * z );
  23955. target.addScaledVector( coeff[ 6 ], 0.743125 * z * z - 0.247708 ); // ( π / 4 ) * 0.315392 * 3
  23956. target.addScaledVector( coeff[ 7 ], 2.0 * 0.429043 * x * z );
  23957. target.addScaledVector( coeff[ 8 ], 0.429043 * ( x * x - y * y ) ); // ( π / 4 ) * 0.546274
  23958. return target;
  23959. }
  23960. /**
  23961. * Adds the given SH to this instance.
  23962. *
  23963. * @param {SphericalHarmonics3} sh - The SH to add.
  23964. * @return {SphericalHarmonics3} A reference to this spherical harmonics.
  23965. */
  23966. add( sh ) {
  23967. for ( let i = 0; i < 9; i ++ ) {
  23968. this.coefficients[ i ].add( sh.coefficients[ i ] );
  23969. }
  23970. return this;
  23971. }
  23972. /**
  23973. * A convenience method for performing {@link SphericalHarmonics3#add} and
  23974. * {@link SphericalHarmonics3#scale} at once.
  23975. *
  23976. * @param {SphericalHarmonics3} sh - The SH to add.
  23977. * @param {number} s - The scale factor.
  23978. * @return {SphericalHarmonics3} A reference to this spherical harmonics.
  23979. */
  23980. addScaledSH( sh, s ) {
  23981. for ( let i = 0; i < 9; i ++ ) {
  23982. this.coefficients[ i ].addScaledVector( sh.coefficients[ i ], s );
  23983. }
  23984. return this;
  23985. }
  23986. /**
  23987. * Scales this SH by the given scale factor.
  23988. *
  23989. * @param {number} s - The scale factor.
  23990. * @return {SphericalHarmonics3} A reference to this spherical harmonics.
  23991. */
  23992. scale( s ) {
  23993. for ( let i = 0; i < 9; i ++ ) {
  23994. this.coefficients[ i ].multiplyScalar( s );
  23995. }
  23996. return this;
  23997. }
  23998. /**
  23999. * Linear interpolates between the given SH and this instance by the given
  24000. * alpha factor.
  24001. *
  24002. * @param {SphericalHarmonics3} sh - The SH to interpolate with.
  24003. * @param {number} alpha - The alpha factor.
  24004. * @return {SphericalHarmonics3} A reference to this spherical harmonics.
  24005. */
  24006. lerp( sh, alpha ) {
  24007. for ( let i = 0; i < 9; i ++ ) {
  24008. this.coefficients[ i ].lerp( sh.coefficients[ i ], alpha );
  24009. }
  24010. return this;
  24011. }
  24012. /**
  24013. * Returns `true` if this spherical harmonics is equal with the given one.
  24014. *
  24015. * @param {SphericalHarmonics3} sh - The spherical harmonics to test for equality.
  24016. * @return {boolean} Whether this spherical harmonics is equal with the given one.
  24017. */
  24018. equals( sh ) {
  24019. for ( let i = 0; i < 9; i ++ ) {
  24020. if ( ! this.coefficients[ i ].equals( sh.coefficients[ i ] ) ) {
  24021. return false;
  24022. }
  24023. }
  24024. return true;
  24025. }
  24026. /**
  24027. * Copies the values of the given spherical harmonics to this instance.
  24028. *
  24029. * @param {SphericalHarmonics3} sh - The spherical harmonics to copy.
  24030. * @return {SphericalHarmonics3} A reference to this spherical harmonics.
  24031. */
  24032. copy( sh ) {
  24033. return this.set( sh.coefficients );
  24034. }
  24035. /**
  24036. * Returns a new spherical harmonics with copied values from this instance.
  24037. *
  24038. * @return {SphericalHarmonics3} A clone of this instance.
  24039. */
  24040. clone() {
  24041. return new this.constructor().copy( this );
  24042. }
  24043. /**
  24044. * Sets the SH coefficients of this instance from the given array.
  24045. *
  24046. * @param {Array<number>} array - An array holding the SH coefficients.
  24047. * @param {number} [offset=0] - The array offset where to start copying.
  24048. * @return {SphericalHarmonics3} A clone of this instance.
  24049. */
  24050. fromArray( array, offset = 0 ) {
  24051. const coefficients = this.coefficients;
  24052. for ( let i = 0; i < 9; i ++ ) {
  24053. coefficients[ i ].fromArray( array, offset + ( i * 3 ) );
  24054. }
  24055. return this;
  24056. }
  24057. /**
  24058. * Returns an array with the SH coefficients, or copies them into the provided
  24059. * array. The coefficients are represented as numbers.
  24060. *
  24061. * @param {Array<number>} [array=[]] - The target array.
  24062. * @param {number} [offset=0] - The array offset where to start copying.
  24063. * @return {Array<number>} An array with flat SH coefficients.
  24064. */
  24065. toArray( array = [], offset = 0 ) {
  24066. const coefficients = this.coefficients;
  24067. for ( let i = 0; i < 9; i ++ ) {
  24068. coefficients[ i ].toArray( array, offset + ( i * 3 ) );
  24069. }
  24070. return array;
  24071. }
  24072. /**
  24073. * Computes the SH basis for the given normal vector.
  24074. *
  24075. * @param {Vector3} normal - The normal.
  24076. * @param {Array<number>} shBasis - The target array holding the SH basis.
  24077. */
  24078. static getBasisAt( normal, shBasis ) {
  24079. // normal is assumed to be unit length
  24080. const x = normal.x, y = normal.y, z = normal.z;
  24081. // band 0
  24082. shBasis[ 0 ] = 0.282095;
  24083. // band 1
  24084. shBasis[ 1 ] = 0.488603 * y;
  24085. shBasis[ 2 ] = 0.488603 * z;
  24086. shBasis[ 3 ] = 0.488603 * x;
  24087. // band 2
  24088. shBasis[ 4 ] = 1.092548 * x * y;
  24089. shBasis[ 5 ] = 1.092548 * y * z;
  24090. shBasis[ 6 ] = 0.315392 * ( 3 * z * z - 1 );
  24091. shBasis[ 7 ] = 1.092548 * x * z;
  24092. shBasis[ 8 ] = 0.546274 * ( x * x - y * y );
  24093. }
  24094. }
  24095. class LightProbe extends Light {
  24096. constructor( sh = new SphericalHarmonics3(), intensity = 1 ) {
  24097. super( undefined, intensity );
  24098. this.isLightProbe = true;
  24099. this.sh = sh;
  24100. }
  24101. copy( source ) {
  24102. super.copy( source );
  24103. this.sh.copy( source.sh );
  24104. return this;
  24105. }
  24106. fromJSON( json ) {
  24107. this.intensity = json.intensity; // TODO: Move this bit to Light.fromJSON();
  24108. this.sh.fromArray( json.sh );
  24109. return this;
  24110. }
  24111. toJSON( meta ) {
  24112. const data = super.toJSON( meta );
  24113. data.object.sh = this.sh.toArray();
  24114. return data;
  24115. }
  24116. }
  24117. class MaterialLoader extends Loader {
  24118. constructor( manager ) {
  24119. super( manager );
  24120. this.textures = {};
  24121. }
  24122. load( url, onLoad, onProgress, onError ) {
  24123. const scope = this;
  24124. const loader = new FileLoader( scope.manager );
  24125. loader.setPath( scope.path );
  24126. loader.setRequestHeader( scope.requestHeader );
  24127. loader.setWithCredentials( scope.withCredentials );
  24128. loader.load( url, function ( text ) {
  24129. try {
  24130. onLoad( scope.parse( JSON.parse( text ) ) );
  24131. } catch ( e ) {
  24132. if ( onError ) {
  24133. onError( e );
  24134. } else {
  24135. console.error( e );
  24136. }
  24137. scope.manager.itemError( url );
  24138. }
  24139. }, onProgress, onError );
  24140. }
  24141. parse( json ) {
  24142. const textures = this.textures;
  24143. function getTexture( name ) {
  24144. if ( textures[ name ] === undefined ) {
  24145. console.warn( 'THREE.MaterialLoader: Undefined texture', name );
  24146. }
  24147. return textures[ name ];
  24148. }
  24149. const material = this.createMaterialFromType( json.type );
  24150. if ( json.uuid !== undefined ) material.uuid = json.uuid;
  24151. if ( json.name !== undefined ) material.name = json.name;
  24152. if ( json.color !== undefined && material.color !== undefined ) material.color.setHex( json.color );
  24153. if ( json.roughness !== undefined ) material.roughness = json.roughness;
  24154. if ( json.metalness !== undefined ) material.metalness = json.metalness;
  24155. if ( json.sheen !== undefined ) material.sheen = json.sheen;
  24156. if ( json.sheenColor !== undefined ) material.sheenColor = new Color().setHex( json.sheenColor );
  24157. if ( json.sheenRoughness !== undefined ) material.sheenRoughness = json.sheenRoughness;
  24158. if ( json.emissive !== undefined && material.emissive !== undefined ) material.emissive.setHex( json.emissive );
  24159. if ( json.specular !== undefined && material.specular !== undefined ) material.specular.setHex( json.specular );
  24160. if ( json.specularIntensity !== undefined ) material.specularIntensity = json.specularIntensity;
  24161. if ( json.specularColor !== undefined && material.specularColor !== undefined ) material.specularColor.setHex( json.specularColor );
  24162. if ( json.shininess !== undefined ) material.shininess = json.shininess;
  24163. if ( json.clearcoat !== undefined ) material.clearcoat = json.clearcoat;
  24164. if ( json.clearcoatRoughness !== undefined ) material.clearcoatRoughness = json.clearcoatRoughness;
  24165. if ( json.dispersion !== undefined ) material.dispersion = json.dispersion;
  24166. if ( json.iridescence !== undefined ) material.iridescence = json.iridescence;
  24167. if ( json.iridescenceIOR !== undefined ) material.iridescenceIOR = json.iridescenceIOR;
  24168. if ( json.iridescenceThicknessRange !== undefined ) material.iridescenceThicknessRange = json.iridescenceThicknessRange;
  24169. if ( json.transmission !== undefined ) material.transmission = json.transmission;
  24170. if ( json.thickness !== undefined ) material.thickness = json.thickness;
  24171. if ( json.attenuationDistance !== undefined ) material.attenuationDistance = json.attenuationDistance;
  24172. if ( json.attenuationColor !== undefined && material.attenuationColor !== undefined ) material.attenuationColor.setHex( json.attenuationColor );
  24173. if ( json.anisotropy !== undefined ) material.anisotropy = json.anisotropy;
  24174. if ( json.anisotropyRotation !== undefined ) material.anisotropyRotation = json.anisotropyRotation;
  24175. if ( json.fog !== undefined ) material.fog = json.fog;
  24176. if ( json.flatShading !== undefined ) material.flatShading = json.flatShading;
  24177. if ( json.blending !== undefined ) material.blending = json.blending;
  24178. if ( json.combine !== undefined ) material.combine = json.combine;
  24179. if ( json.side !== undefined ) material.side = json.side;
  24180. if ( json.shadowSide !== undefined ) material.shadowSide = json.shadowSide;
  24181. if ( json.opacity !== undefined ) material.opacity = json.opacity;
  24182. if ( json.transparent !== undefined ) material.transparent = json.transparent;
  24183. if ( json.alphaTest !== undefined ) material.alphaTest = json.alphaTest;
  24184. if ( json.alphaHash !== undefined ) material.alphaHash = json.alphaHash;
  24185. if ( json.depthFunc !== undefined ) material.depthFunc = json.depthFunc;
  24186. if ( json.depthTest !== undefined ) material.depthTest = json.depthTest;
  24187. if ( json.depthWrite !== undefined ) material.depthWrite = json.depthWrite;
  24188. if ( json.colorWrite !== undefined ) material.colorWrite = json.colorWrite;
  24189. if ( json.blendSrc !== undefined ) material.blendSrc = json.blendSrc;
  24190. if ( json.blendDst !== undefined ) material.blendDst = json.blendDst;
  24191. if ( json.blendEquation !== undefined ) material.blendEquation = json.blendEquation;
  24192. if ( json.blendSrcAlpha !== undefined ) material.blendSrcAlpha = json.blendSrcAlpha;
  24193. if ( json.blendDstAlpha !== undefined ) material.blendDstAlpha = json.blendDstAlpha;
  24194. if ( json.blendEquationAlpha !== undefined ) material.blendEquationAlpha = json.blendEquationAlpha;
  24195. if ( json.blendColor !== undefined && material.blendColor !== undefined ) material.blendColor.setHex( json.blendColor );
  24196. if ( json.blendAlpha !== undefined ) material.blendAlpha = json.blendAlpha;
  24197. if ( json.stencilWriteMask !== undefined ) material.stencilWriteMask = json.stencilWriteMask;
  24198. if ( json.stencilFunc !== undefined ) material.stencilFunc = json.stencilFunc;
  24199. if ( json.stencilRef !== undefined ) material.stencilRef = json.stencilRef;
  24200. if ( json.stencilFuncMask !== undefined ) material.stencilFuncMask = json.stencilFuncMask;
  24201. if ( json.stencilFail !== undefined ) material.stencilFail = json.stencilFail;
  24202. if ( json.stencilZFail !== undefined ) material.stencilZFail = json.stencilZFail;
  24203. if ( json.stencilZPass !== undefined ) material.stencilZPass = json.stencilZPass;
  24204. if ( json.stencilWrite !== undefined ) material.stencilWrite = json.stencilWrite;
  24205. if ( json.wireframe !== undefined ) material.wireframe = json.wireframe;
  24206. if ( json.wireframeLinewidth !== undefined ) material.wireframeLinewidth = json.wireframeLinewidth;
  24207. if ( json.wireframeLinecap !== undefined ) material.wireframeLinecap = json.wireframeLinecap;
  24208. if ( json.wireframeLinejoin !== undefined ) material.wireframeLinejoin = json.wireframeLinejoin;
  24209. if ( json.rotation !== undefined ) material.rotation = json.rotation;
  24210. if ( json.linewidth !== undefined ) material.linewidth = json.linewidth;
  24211. if ( json.dashSize !== undefined ) material.dashSize = json.dashSize;
  24212. if ( json.gapSize !== undefined ) material.gapSize = json.gapSize;
  24213. if ( json.scale !== undefined ) material.scale = json.scale;
  24214. if ( json.polygonOffset !== undefined ) material.polygonOffset = json.polygonOffset;
  24215. if ( json.polygonOffsetFactor !== undefined ) material.polygonOffsetFactor = json.polygonOffsetFactor;
  24216. if ( json.polygonOffsetUnits !== undefined ) material.polygonOffsetUnits = json.polygonOffsetUnits;
  24217. if ( json.dithering !== undefined ) material.dithering = json.dithering;
  24218. if ( json.alphaToCoverage !== undefined ) material.alphaToCoverage = json.alphaToCoverage;
  24219. if ( json.premultipliedAlpha !== undefined ) material.premultipliedAlpha = json.premultipliedAlpha;
  24220. if ( json.forceSinglePass !== undefined ) material.forceSinglePass = json.forceSinglePass;
  24221. if ( json.visible !== undefined ) material.visible = json.visible;
  24222. if ( json.toneMapped !== undefined ) material.toneMapped = json.toneMapped;
  24223. if ( json.userData !== undefined ) material.userData = json.userData;
  24224. if ( json.vertexColors !== undefined ) {
  24225. if ( typeof json.vertexColors === 'number' ) {
  24226. material.vertexColors = ( json.vertexColors > 0 ) ? true : false;
  24227. } else {
  24228. material.vertexColors = json.vertexColors;
  24229. }
  24230. }
  24231. // Shader Material
  24232. if ( json.uniforms !== undefined ) {
  24233. for ( const name in json.uniforms ) {
  24234. const uniform = json.uniforms[ name ];
  24235. material.uniforms[ name ] = {};
  24236. switch ( uniform.type ) {
  24237. case 't':
  24238. material.uniforms[ name ].value = getTexture( uniform.value );
  24239. break;
  24240. case 'c':
  24241. material.uniforms[ name ].value = new Color().setHex( uniform.value );
  24242. break;
  24243. case 'v2':
  24244. material.uniforms[ name ].value = new Vector2().fromArray( uniform.value );
  24245. break;
  24246. case 'v3':
  24247. material.uniforms[ name ].value = new Vector3().fromArray( uniform.value );
  24248. break;
  24249. case 'v4':
  24250. material.uniforms[ name ].value = new Vector4().fromArray( uniform.value );
  24251. break;
  24252. case 'm3':
  24253. material.uniforms[ name ].value = new Matrix3().fromArray( uniform.value );
  24254. break;
  24255. case 'm4':
  24256. material.uniforms[ name ].value = new Matrix4().fromArray( uniform.value );
  24257. break;
  24258. default:
  24259. material.uniforms[ name ].value = uniform.value;
  24260. }
  24261. }
  24262. }
  24263. if ( json.defines !== undefined ) material.defines = json.defines;
  24264. if ( json.vertexShader !== undefined ) material.vertexShader = json.vertexShader;
  24265. if ( json.fragmentShader !== undefined ) material.fragmentShader = json.fragmentShader;
  24266. if ( json.glslVersion !== undefined ) material.glslVersion = json.glslVersion;
  24267. if ( json.extensions !== undefined ) {
  24268. for ( const key in json.extensions ) {
  24269. material.extensions[ key ] = json.extensions[ key ];
  24270. }
  24271. }
  24272. if ( json.lights !== undefined ) material.lights = json.lights;
  24273. if ( json.clipping !== undefined ) material.clipping = json.clipping;
  24274. // for PointsMaterial
  24275. if ( json.size !== undefined ) material.size = json.size;
  24276. if ( json.sizeAttenuation !== undefined ) material.sizeAttenuation = json.sizeAttenuation;
  24277. // maps
  24278. if ( json.map !== undefined ) material.map = getTexture( json.map );
  24279. if ( json.matcap !== undefined ) material.matcap = getTexture( json.matcap );
  24280. if ( json.alphaMap !== undefined ) material.alphaMap = getTexture( json.alphaMap );
  24281. if ( json.bumpMap !== undefined ) material.bumpMap = getTexture( json.bumpMap );
  24282. if ( json.bumpScale !== undefined ) material.bumpScale = json.bumpScale;
  24283. if ( json.normalMap !== undefined ) material.normalMap = getTexture( json.normalMap );
  24284. if ( json.normalMapType !== undefined ) material.normalMapType = json.normalMapType;
  24285. if ( json.normalScale !== undefined ) {
  24286. let normalScale = json.normalScale;
  24287. if ( Array.isArray( normalScale ) === false ) {
  24288. // Blender exporter used to export a scalar. See #7459
  24289. normalScale = [ normalScale, normalScale ];
  24290. }
  24291. material.normalScale = new Vector2().fromArray( normalScale );
  24292. }
  24293. if ( json.displacementMap !== undefined ) material.displacementMap = getTexture( json.displacementMap );
  24294. if ( json.displacementScale !== undefined ) material.displacementScale = json.displacementScale;
  24295. if ( json.displacementBias !== undefined ) material.displacementBias = json.displacementBias;
  24296. if ( json.roughnessMap !== undefined ) material.roughnessMap = getTexture( json.roughnessMap );
  24297. if ( json.metalnessMap !== undefined ) material.metalnessMap = getTexture( json.metalnessMap );
  24298. if ( json.emissiveMap !== undefined ) material.emissiveMap = getTexture( json.emissiveMap );
  24299. if ( json.emissiveIntensity !== undefined ) material.emissiveIntensity = json.emissiveIntensity;
  24300. if ( json.specularMap !== undefined ) material.specularMap = getTexture( json.specularMap );
  24301. if ( json.specularIntensityMap !== undefined ) material.specularIntensityMap = getTexture( json.specularIntensityMap );
  24302. if ( json.specularColorMap !== undefined ) material.specularColorMap = getTexture( json.specularColorMap );
  24303. if ( json.envMap !== undefined ) material.envMap = getTexture( json.envMap );
  24304. if ( json.envMapRotation !== undefined ) material.envMapRotation.fromArray( json.envMapRotation );
  24305. if ( json.envMapIntensity !== undefined ) material.envMapIntensity = json.envMapIntensity;
  24306. if ( json.reflectivity !== undefined ) material.reflectivity = json.reflectivity;
  24307. if ( json.refractionRatio !== undefined ) material.refractionRatio = json.refractionRatio;
  24308. if ( json.lightMap !== undefined ) material.lightMap = getTexture( json.lightMap );
  24309. if ( json.lightMapIntensity !== undefined ) material.lightMapIntensity = json.lightMapIntensity;
  24310. if ( json.aoMap !== undefined ) material.aoMap = getTexture( json.aoMap );
  24311. if ( json.aoMapIntensity !== undefined ) material.aoMapIntensity = json.aoMapIntensity;
  24312. if ( json.gradientMap !== undefined ) material.gradientMap = getTexture( json.gradientMap );
  24313. if ( json.clearcoatMap !== undefined ) material.clearcoatMap = getTexture( json.clearcoatMap );
  24314. if ( json.clearcoatRoughnessMap !== undefined ) material.clearcoatRoughnessMap = getTexture( json.clearcoatRoughnessMap );
  24315. if ( json.clearcoatNormalMap !== undefined ) material.clearcoatNormalMap = getTexture( json.clearcoatNormalMap );
  24316. if ( json.clearcoatNormalScale !== undefined ) material.clearcoatNormalScale = new Vector2().fromArray( json.clearcoatNormalScale );
  24317. if ( json.iridescenceMap !== undefined ) material.iridescenceMap = getTexture( json.iridescenceMap );
  24318. if ( json.iridescenceThicknessMap !== undefined ) material.iridescenceThicknessMap = getTexture( json.iridescenceThicknessMap );
  24319. if ( json.transmissionMap !== undefined ) material.transmissionMap = getTexture( json.transmissionMap );
  24320. if ( json.thicknessMap !== undefined ) material.thicknessMap = getTexture( json.thicknessMap );
  24321. if ( json.anisotropyMap !== undefined ) material.anisotropyMap = getTexture( json.anisotropyMap );
  24322. if ( json.sheenColorMap !== undefined ) material.sheenColorMap = getTexture( json.sheenColorMap );
  24323. if ( json.sheenRoughnessMap !== undefined ) material.sheenRoughnessMap = getTexture( json.sheenRoughnessMap );
  24324. return material;
  24325. }
  24326. setTextures( value ) {
  24327. this.textures = value;
  24328. return this;
  24329. }
  24330. createMaterialFromType( type ) {
  24331. return MaterialLoader.createMaterialFromType( type );
  24332. }
  24333. static createMaterialFromType( type ) {
  24334. const materialLib = {
  24335. ShadowMaterial,
  24336. SpriteMaterial,
  24337. RawShaderMaterial,
  24338. ShaderMaterial,
  24339. PointsMaterial,
  24340. MeshPhysicalMaterial,
  24341. MeshStandardMaterial,
  24342. MeshPhongMaterial,
  24343. MeshToonMaterial,
  24344. MeshNormalMaterial,
  24345. MeshLambertMaterial,
  24346. MeshDepthMaterial,
  24347. MeshDistanceMaterial,
  24348. MeshBasicMaterial,
  24349. MeshMatcapMaterial,
  24350. LineDashedMaterial,
  24351. LineBasicMaterial,
  24352. Material
  24353. };
  24354. return new materialLib[ type ]();
  24355. }
  24356. }
  24357. class LoaderUtils {
  24358. static decodeText( array ) { // @deprecated, r165
  24359. console.warn( 'THREE.LoaderUtils: decodeText() has been deprecated with r165 and will be removed with r175. Use TextDecoder instead.' );
  24360. if ( typeof TextDecoder !== 'undefined' ) {
  24361. return new TextDecoder().decode( array );
  24362. }
  24363. // Avoid the String.fromCharCode.apply(null, array) shortcut, which
  24364. // throws a "maximum call stack size exceeded" error for large arrays.
  24365. let s = '';
  24366. for ( let i = 0, il = array.length; i < il; i ++ ) {
  24367. // Implicitly assumes little-endian.
  24368. s += String.fromCharCode( array[ i ] );
  24369. }
  24370. try {
  24371. // merges multi-byte utf-8 characters.
  24372. return decodeURIComponent( escape( s ) );
  24373. } catch ( e ) { // see #16358
  24374. return s;
  24375. }
  24376. }
  24377. static extractUrlBase( url ) {
  24378. const index = url.lastIndexOf( '/' );
  24379. if ( index === -1 ) return './';
  24380. return url.slice( 0, index + 1 );
  24381. }
  24382. static resolveURL( url, path ) {
  24383. // Invalid URL
  24384. if ( typeof url !== 'string' || url === '' ) return '';
  24385. // Host Relative URL
  24386. if ( /^https?:\/\//i.test( path ) && /^\//.test( url ) ) {
  24387. path = path.replace( /(^https?:\/\/[^\/]+).*/i, '$1' );
  24388. }
  24389. // Absolute URL http://,https://,//
  24390. if ( /^(https?:)?\/\//i.test( url ) ) return url;
  24391. // Data URI
  24392. if ( /^data:.*,.*$/i.test( url ) ) return url;
  24393. // Blob URL
  24394. if ( /^blob:.*$/i.test( url ) ) return url;
  24395. // Relative URL
  24396. return path + url;
  24397. }
  24398. }
  24399. class InstancedBufferGeometry extends BufferGeometry {
  24400. constructor() {
  24401. super();
  24402. this.isInstancedBufferGeometry = true;
  24403. this.type = 'InstancedBufferGeometry';
  24404. this.instanceCount = Infinity;
  24405. }
  24406. copy( source ) {
  24407. super.copy( source );
  24408. this.instanceCount = source.instanceCount;
  24409. return this;
  24410. }
  24411. toJSON() {
  24412. const data = super.toJSON();
  24413. data.instanceCount = this.instanceCount;
  24414. data.isInstancedBufferGeometry = true;
  24415. return data;
  24416. }
  24417. }
  24418. class BufferGeometryLoader extends Loader {
  24419. constructor( manager ) {
  24420. super( manager );
  24421. }
  24422. load( url, onLoad, onProgress, onError ) {
  24423. const scope = this;
  24424. const loader = new FileLoader( scope.manager );
  24425. loader.setPath( scope.path );
  24426. loader.setRequestHeader( scope.requestHeader );
  24427. loader.setWithCredentials( scope.withCredentials );
  24428. loader.load( url, function ( text ) {
  24429. try {
  24430. onLoad( scope.parse( JSON.parse( text ) ) );
  24431. } catch ( e ) {
  24432. if ( onError ) {
  24433. onError( e );
  24434. } else {
  24435. console.error( e );
  24436. }
  24437. scope.manager.itemError( url );
  24438. }
  24439. }, onProgress, onError );
  24440. }
  24441. parse( json ) {
  24442. const interleavedBufferMap = {};
  24443. const arrayBufferMap = {};
  24444. function getInterleavedBuffer( json, uuid ) {
  24445. if ( interleavedBufferMap[ uuid ] !== undefined ) return interleavedBufferMap[ uuid ];
  24446. const interleavedBuffers = json.interleavedBuffers;
  24447. const interleavedBuffer = interleavedBuffers[ uuid ];
  24448. const buffer = getArrayBuffer( json, interleavedBuffer.buffer );
  24449. const array = getTypedArray( interleavedBuffer.type, buffer );
  24450. const ib = new InterleavedBuffer( array, interleavedBuffer.stride );
  24451. ib.uuid = interleavedBuffer.uuid;
  24452. interleavedBufferMap[ uuid ] = ib;
  24453. return ib;
  24454. }
  24455. function getArrayBuffer( json, uuid ) {
  24456. if ( arrayBufferMap[ uuid ] !== undefined ) return arrayBufferMap[ uuid ];
  24457. const arrayBuffers = json.arrayBuffers;
  24458. const arrayBuffer = arrayBuffers[ uuid ];
  24459. const ab = new Uint32Array( arrayBuffer ).buffer;
  24460. arrayBufferMap[ uuid ] = ab;
  24461. return ab;
  24462. }
  24463. const geometry = json.isInstancedBufferGeometry ? new InstancedBufferGeometry() : new BufferGeometry();
  24464. const index = json.data.index;
  24465. if ( index !== undefined ) {
  24466. const typedArray = getTypedArray( index.type, index.array );
  24467. geometry.setIndex( new BufferAttribute( typedArray, 1 ) );
  24468. }
  24469. const attributes = json.data.attributes;
  24470. for ( const key in attributes ) {
  24471. const attribute = attributes[ key ];
  24472. let bufferAttribute;
  24473. if ( attribute.isInterleavedBufferAttribute ) {
  24474. const interleavedBuffer = getInterleavedBuffer( json.data, attribute.data );
  24475. bufferAttribute = new InterleavedBufferAttribute( interleavedBuffer, attribute.itemSize, attribute.offset, attribute.normalized );
  24476. } else {
  24477. const typedArray = getTypedArray( attribute.type, attribute.array );
  24478. const bufferAttributeConstr = attribute.isInstancedBufferAttribute ? InstancedBufferAttribute : BufferAttribute;
  24479. bufferAttribute = new bufferAttributeConstr( typedArray, attribute.itemSize, attribute.normalized );
  24480. }
  24481. if ( attribute.name !== undefined ) bufferAttribute.name = attribute.name;
  24482. if ( attribute.usage !== undefined ) bufferAttribute.setUsage( attribute.usage );
  24483. geometry.setAttribute( key, bufferAttribute );
  24484. }
  24485. const morphAttributes = json.data.morphAttributes;
  24486. if ( morphAttributes ) {
  24487. for ( const key in morphAttributes ) {
  24488. const attributeArray = morphAttributes[ key ];
  24489. const array = [];
  24490. for ( let i = 0, il = attributeArray.length; i < il; i ++ ) {
  24491. const attribute = attributeArray[ i ];
  24492. let bufferAttribute;
  24493. if ( attribute.isInterleavedBufferAttribute ) {
  24494. const interleavedBuffer = getInterleavedBuffer( json.data, attribute.data );
  24495. bufferAttribute = new InterleavedBufferAttribute( interleavedBuffer, attribute.itemSize, attribute.offset, attribute.normalized );
  24496. } else {
  24497. const typedArray = getTypedArray( attribute.type, attribute.array );
  24498. bufferAttribute = new BufferAttribute( typedArray, attribute.itemSize, attribute.normalized );
  24499. }
  24500. if ( attribute.name !== undefined ) bufferAttribute.name = attribute.name;
  24501. array.push( bufferAttribute );
  24502. }
  24503. geometry.morphAttributes[ key ] = array;
  24504. }
  24505. }
  24506. const morphTargetsRelative = json.data.morphTargetsRelative;
  24507. if ( morphTargetsRelative ) {
  24508. geometry.morphTargetsRelative = true;
  24509. }
  24510. const groups = json.data.groups || json.data.drawcalls || json.data.offsets;
  24511. if ( groups !== undefined ) {
  24512. for ( let i = 0, n = groups.length; i !== n; ++ i ) {
  24513. const group = groups[ i ];
  24514. geometry.addGroup( group.start, group.count, group.materialIndex );
  24515. }
  24516. }
  24517. const boundingSphere = json.data.boundingSphere;
  24518. if ( boundingSphere !== undefined ) {
  24519. const center = new Vector3();
  24520. if ( boundingSphere.center !== undefined ) {
  24521. center.fromArray( boundingSphere.center );
  24522. }
  24523. geometry.boundingSphere = new Sphere( center, boundingSphere.radius );
  24524. }
  24525. if ( json.name ) geometry.name = json.name;
  24526. if ( json.userData ) geometry.userData = json.userData;
  24527. return geometry;
  24528. }
  24529. }
  24530. class ObjectLoader extends Loader {
  24531. constructor( manager ) {
  24532. super( manager );
  24533. }
  24534. load( url, onLoad, onProgress, onError ) {
  24535. const scope = this;
  24536. const path = ( this.path === '' ) ? LoaderUtils.extractUrlBase( url ) : this.path;
  24537. this.resourcePath = this.resourcePath || path;
  24538. const loader = new FileLoader( this.manager );
  24539. loader.setPath( this.path );
  24540. loader.setRequestHeader( this.requestHeader );
  24541. loader.setWithCredentials( this.withCredentials );
  24542. loader.load( url, function ( text ) {
  24543. let json = null;
  24544. try {
  24545. json = JSON.parse( text );
  24546. } catch ( error ) {
  24547. if ( onError !== undefined ) onError( error );
  24548. console.error( 'THREE:ObjectLoader: Can\'t parse ' + url + '.', error.message );
  24549. return;
  24550. }
  24551. const metadata = json.metadata;
  24552. if ( metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry' ) {
  24553. if ( onError !== undefined ) onError( new Error( 'THREE.ObjectLoader: Can\'t load ' + url ) );
  24554. console.error( 'THREE.ObjectLoader: Can\'t load ' + url );
  24555. return;
  24556. }
  24557. scope.parse( json, onLoad );
  24558. }, onProgress, onError );
  24559. }
  24560. async loadAsync( url, onProgress ) {
  24561. const scope = this;
  24562. const path = ( this.path === '' ) ? LoaderUtils.extractUrlBase( url ) : this.path;
  24563. this.resourcePath = this.resourcePath || path;
  24564. const loader = new FileLoader( this.manager );
  24565. loader.setPath( this.path );
  24566. loader.setRequestHeader( this.requestHeader );
  24567. loader.setWithCredentials( this.withCredentials );
  24568. const text = await loader.loadAsync( url, onProgress );
  24569. const json = JSON.parse( text );
  24570. const metadata = json.metadata;
  24571. if ( metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry' ) {
  24572. throw new Error( 'THREE.ObjectLoader: Can\'t load ' + url );
  24573. }
  24574. return await scope.parseAsync( json );
  24575. }
  24576. parse( json, onLoad ) {
  24577. const animations = this.parseAnimations( json.animations );
  24578. const shapes = this.parseShapes( json.shapes );
  24579. const geometries = this.parseGeometries( json.geometries, shapes );
  24580. const images = this.parseImages( json.images, function () {
  24581. if ( onLoad !== undefined ) onLoad( object );
  24582. } );
  24583. const textures = this.parseTextures( json.textures, images );
  24584. const materials = this.parseMaterials( json.materials, textures );
  24585. const object = this.parseObject( json.object, geometries, materials, textures, animations );
  24586. const skeletons = this.parseSkeletons( json.skeletons, object );
  24587. this.bindSkeletons( object, skeletons );
  24588. this.bindLightTargets( object );
  24589. //
  24590. if ( onLoad !== undefined ) {
  24591. let hasImages = false;
  24592. for ( const uuid in images ) {
  24593. if ( images[ uuid ].data instanceof HTMLImageElement ) {
  24594. hasImages = true;
  24595. break;
  24596. }
  24597. }
  24598. if ( hasImages === false ) onLoad( object );
  24599. }
  24600. return object;
  24601. }
  24602. async parseAsync( json ) {
  24603. const animations = this.parseAnimations( json.animations );
  24604. const shapes = this.parseShapes( json.shapes );
  24605. const geometries = this.parseGeometries( json.geometries, shapes );
  24606. const images = await this.parseImagesAsync( json.images );
  24607. const textures = this.parseTextures( json.textures, images );
  24608. const materials = this.parseMaterials( json.materials, textures );
  24609. const object = this.parseObject( json.object, geometries, materials, textures, animations );
  24610. const skeletons = this.parseSkeletons( json.skeletons, object );
  24611. this.bindSkeletons( object, skeletons );
  24612. this.bindLightTargets( object );
  24613. return object;
  24614. }
  24615. parseShapes( json ) {
  24616. const shapes = {};
  24617. if ( json !== undefined ) {
  24618. for ( let i = 0, l = json.length; i < l; i ++ ) {
  24619. const shape = new Shape().fromJSON( json[ i ] );
  24620. shapes[ shape.uuid ] = shape;
  24621. }
  24622. }
  24623. return shapes;
  24624. }
  24625. parseSkeletons( json, object ) {
  24626. const skeletons = {};
  24627. const bones = {};
  24628. // generate bone lookup table
  24629. object.traverse( function ( child ) {
  24630. if ( child.isBone ) bones[ child.uuid ] = child;
  24631. } );
  24632. // create skeletons
  24633. if ( json !== undefined ) {
  24634. for ( let i = 0, l = json.length; i < l; i ++ ) {
  24635. const skeleton = new Skeleton().fromJSON( json[ i ], bones );
  24636. skeletons[ skeleton.uuid ] = skeleton;
  24637. }
  24638. }
  24639. return skeletons;
  24640. }
  24641. parseGeometries( json, shapes ) {
  24642. const geometries = {};
  24643. if ( json !== undefined ) {
  24644. const bufferGeometryLoader = new BufferGeometryLoader();
  24645. for ( let i = 0, l = json.length; i < l; i ++ ) {
  24646. let geometry;
  24647. const data = json[ i ];
  24648. switch ( data.type ) {
  24649. case 'BufferGeometry':
  24650. case 'InstancedBufferGeometry':
  24651. geometry = bufferGeometryLoader.parse( data );
  24652. break;
  24653. default:
  24654. if ( data.type in Geometries ) {
  24655. geometry = Geometries[ data.type ].fromJSON( data, shapes );
  24656. } else {
  24657. console.warn( `THREE.ObjectLoader: Unsupported geometry type "${ data.type }"` );
  24658. }
  24659. }
  24660. geometry.uuid = data.uuid;
  24661. if ( data.name !== undefined ) geometry.name = data.name;
  24662. if ( data.userData !== undefined ) geometry.userData = data.userData;
  24663. geometries[ data.uuid ] = geometry;
  24664. }
  24665. }
  24666. return geometries;
  24667. }
  24668. parseMaterials( json, textures ) {
  24669. const cache = {}; // MultiMaterial
  24670. const materials = {};
  24671. if ( json !== undefined ) {
  24672. const loader = new MaterialLoader();
  24673. loader.setTextures( textures );
  24674. for ( let i = 0, l = json.length; i < l; i ++ ) {
  24675. const data = json[ i ];
  24676. if ( cache[ data.uuid ] === undefined ) {
  24677. cache[ data.uuid ] = loader.parse( data );
  24678. }
  24679. materials[ data.uuid ] = cache[ data.uuid ];
  24680. }
  24681. }
  24682. return materials;
  24683. }
  24684. parseAnimations( json ) {
  24685. const animations = {};
  24686. if ( json !== undefined ) {
  24687. for ( let i = 0; i < json.length; i ++ ) {
  24688. const data = json[ i ];
  24689. const clip = AnimationClip.parse( data );
  24690. animations[ clip.uuid ] = clip;
  24691. }
  24692. }
  24693. return animations;
  24694. }
  24695. parseImages( json, onLoad ) {
  24696. const scope = this;
  24697. const images = {};
  24698. let loader;
  24699. function loadImage( url ) {
  24700. scope.manager.itemStart( url );
  24701. return loader.load( url, function () {
  24702. scope.manager.itemEnd( url );
  24703. }, undefined, function () {
  24704. scope.manager.itemError( url );
  24705. scope.manager.itemEnd( url );
  24706. } );
  24707. }
  24708. function deserializeImage( image ) {
  24709. if ( typeof image === 'string' ) {
  24710. const url = image;
  24711. const path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test( url ) ? url : scope.resourcePath + url;
  24712. return loadImage( path );
  24713. } else {
  24714. if ( image.data ) {
  24715. return {
  24716. data: getTypedArray( image.type, image.data ),
  24717. width: image.width,
  24718. height: image.height
  24719. };
  24720. } else {
  24721. return null;
  24722. }
  24723. }
  24724. }
  24725. if ( json !== undefined && json.length > 0 ) {
  24726. const manager = new LoadingManager( onLoad );
  24727. loader = new ImageLoader( manager );
  24728. loader.setCrossOrigin( this.crossOrigin );
  24729. for ( let i = 0, il = json.length; i < il; i ++ ) {
  24730. const image = json[ i ];
  24731. const url = image.url;
  24732. if ( Array.isArray( url ) ) {
  24733. // load array of images e.g CubeTexture
  24734. const imageArray = [];
  24735. for ( let j = 0, jl = url.length; j < jl; j ++ ) {
  24736. const currentUrl = url[ j ];
  24737. const deserializedImage = deserializeImage( currentUrl );
  24738. if ( deserializedImage !== null ) {
  24739. if ( deserializedImage instanceof HTMLImageElement ) {
  24740. imageArray.push( deserializedImage );
  24741. } else {
  24742. // special case: handle array of data textures for cube textures
  24743. imageArray.push( new DataTexture( deserializedImage.data, deserializedImage.width, deserializedImage.height ) );
  24744. }
  24745. }
  24746. }
  24747. images[ image.uuid ] = new Source( imageArray );
  24748. } else {
  24749. // load single image
  24750. const deserializedImage = deserializeImage( image.url );
  24751. images[ image.uuid ] = new Source( deserializedImage );
  24752. }
  24753. }
  24754. }
  24755. return images;
  24756. }
  24757. async parseImagesAsync( json ) {
  24758. const scope = this;
  24759. const images = {};
  24760. let loader;
  24761. async function deserializeImage( image ) {
  24762. if ( typeof image === 'string' ) {
  24763. const url = image;
  24764. const path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test( url ) ? url : scope.resourcePath + url;
  24765. return await loader.loadAsync( path );
  24766. } else {
  24767. if ( image.data ) {
  24768. return {
  24769. data: getTypedArray( image.type, image.data ),
  24770. width: image.width,
  24771. height: image.height
  24772. };
  24773. } else {
  24774. return null;
  24775. }
  24776. }
  24777. }
  24778. if ( json !== undefined && json.length > 0 ) {
  24779. loader = new ImageLoader( this.manager );
  24780. loader.setCrossOrigin( this.crossOrigin );
  24781. for ( let i = 0, il = json.length; i < il; i ++ ) {
  24782. const image = json[ i ];
  24783. const url = image.url;
  24784. if ( Array.isArray( url ) ) {
  24785. // load array of images e.g CubeTexture
  24786. const imageArray = [];
  24787. for ( let j = 0, jl = url.length; j < jl; j ++ ) {
  24788. const currentUrl = url[ j ];
  24789. const deserializedImage = await deserializeImage( currentUrl );
  24790. if ( deserializedImage !== null ) {
  24791. if ( deserializedImage instanceof HTMLImageElement ) {
  24792. imageArray.push( deserializedImage );
  24793. } else {
  24794. // special case: handle array of data textures for cube textures
  24795. imageArray.push( new DataTexture( deserializedImage.data, deserializedImage.width, deserializedImage.height ) );
  24796. }
  24797. }
  24798. }
  24799. images[ image.uuid ] = new Source( imageArray );
  24800. } else {
  24801. // load single image
  24802. const deserializedImage = await deserializeImage( image.url );
  24803. images[ image.uuid ] = new Source( deserializedImage );
  24804. }
  24805. }
  24806. }
  24807. return images;
  24808. }
  24809. parseTextures( json, images ) {
  24810. function parseConstant( value, type ) {
  24811. if ( typeof value === 'number' ) return value;
  24812. console.warn( 'THREE.ObjectLoader.parseTexture: Constant should be in numeric form.', value );
  24813. return type[ value ];
  24814. }
  24815. const textures = {};
  24816. if ( json !== undefined ) {
  24817. for ( let i = 0, l = json.length; i < l; i ++ ) {
  24818. const data = json[ i ];
  24819. if ( data.image === undefined ) {
  24820. console.warn( 'THREE.ObjectLoader: No "image" specified for', data.uuid );
  24821. }
  24822. if ( images[ data.image ] === undefined ) {
  24823. console.warn( 'THREE.ObjectLoader: Undefined image', data.image );
  24824. }
  24825. const source = images[ data.image ];
  24826. const image = source.data;
  24827. let texture;
  24828. if ( Array.isArray( image ) ) {
  24829. texture = new CubeTexture();
  24830. if ( image.length === 6 ) texture.needsUpdate = true;
  24831. } else {
  24832. if ( image && image.data ) {
  24833. texture = new DataTexture();
  24834. } else {
  24835. texture = new Texture();
  24836. }
  24837. if ( image ) texture.needsUpdate = true; // textures can have undefined image data
  24838. }
  24839. texture.source = source;
  24840. texture.uuid = data.uuid;
  24841. if ( data.name !== undefined ) texture.name = data.name;
  24842. if ( data.mapping !== undefined ) texture.mapping = parseConstant( data.mapping, TEXTURE_MAPPING );
  24843. if ( data.channel !== undefined ) texture.channel = data.channel;
  24844. if ( data.offset !== undefined ) texture.offset.fromArray( data.offset );
  24845. if ( data.repeat !== undefined ) texture.repeat.fromArray( data.repeat );
  24846. if ( data.center !== undefined ) texture.center.fromArray( data.center );
  24847. if ( data.rotation !== undefined ) texture.rotation = data.rotation;
  24848. if ( data.wrap !== undefined ) {
  24849. texture.wrapS = parseConstant( data.wrap[ 0 ], TEXTURE_WRAPPING );
  24850. texture.wrapT = parseConstant( data.wrap[ 1 ], TEXTURE_WRAPPING );
  24851. }
  24852. if ( data.format !== undefined ) texture.format = data.format;
  24853. if ( data.internalFormat !== undefined ) texture.internalFormat = data.internalFormat;
  24854. if ( data.type !== undefined ) texture.type = data.type;
  24855. if ( data.colorSpace !== undefined ) texture.colorSpace = data.colorSpace;
  24856. if ( data.minFilter !== undefined ) texture.minFilter = parseConstant( data.minFilter, TEXTURE_FILTER );
  24857. if ( data.magFilter !== undefined ) texture.magFilter = parseConstant( data.magFilter, TEXTURE_FILTER );
  24858. if ( data.anisotropy !== undefined ) texture.anisotropy = data.anisotropy;
  24859. if ( data.flipY !== undefined ) texture.flipY = data.flipY;
  24860. if ( data.generateMipmaps !== undefined ) texture.generateMipmaps = data.generateMipmaps;
  24861. if ( data.premultiplyAlpha !== undefined ) texture.premultiplyAlpha = data.premultiplyAlpha;
  24862. if ( data.unpackAlignment !== undefined ) texture.unpackAlignment = data.unpackAlignment;
  24863. if ( data.compareFunction !== undefined ) texture.compareFunction = data.compareFunction;
  24864. if ( data.userData !== undefined ) texture.userData = data.userData;
  24865. textures[ data.uuid ] = texture;
  24866. }
  24867. }
  24868. return textures;
  24869. }
  24870. parseObject( data, geometries, materials, textures, animations ) {
  24871. let object;
  24872. function getGeometry( name ) {
  24873. if ( geometries[ name ] === undefined ) {
  24874. console.warn( 'THREE.ObjectLoader: Undefined geometry', name );
  24875. }
  24876. return geometries[ name ];
  24877. }
  24878. function getMaterial( name ) {
  24879. if ( name === undefined ) return undefined;
  24880. if ( Array.isArray( name ) ) {
  24881. const array = [];
  24882. for ( let i = 0, l = name.length; i < l; i ++ ) {
  24883. const uuid = name[ i ];
  24884. if ( materials[ uuid ] === undefined ) {
  24885. console.warn( 'THREE.ObjectLoader: Undefined material', uuid );
  24886. }
  24887. array.push( materials[ uuid ] );
  24888. }
  24889. return array;
  24890. }
  24891. if ( materials[ name ] === undefined ) {
  24892. console.warn( 'THREE.ObjectLoader: Undefined material', name );
  24893. }
  24894. return materials[ name ];
  24895. }
  24896. function getTexture( uuid ) {
  24897. if ( textures[ uuid ] === undefined ) {
  24898. console.warn( 'THREE.ObjectLoader: Undefined texture', uuid );
  24899. }
  24900. return textures[ uuid ];
  24901. }
  24902. let geometry, material;
  24903. switch ( data.type ) {
  24904. case 'Scene':
  24905. object = new Scene();
  24906. if ( data.background !== undefined ) {
  24907. if ( Number.isInteger( data.background ) ) {
  24908. object.background = new Color( data.background );
  24909. } else {
  24910. object.background = getTexture( data.background );
  24911. }
  24912. }
  24913. if ( data.environment !== undefined ) {
  24914. object.environment = getTexture( data.environment );
  24915. }
  24916. if ( data.fog !== undefined ) {
  24917. if ( data.fog.type === 'Fog' ) {
  24918. object.fog = new Fog( data.fog.color, data.fog.near, data.fog.far );
  24919. } else if ( data.fog.type === 'FogExp2' ) {
  24920. object.fog = new FogExp2( data.fog.color, data.fog.density );
  24921. }
  24922. if ( data.fog.name !== '' ) {
  24923. object.fog.name = data.fog.name;
  24924. }
  24925. }
  24926. if ( data.backgroundBlurriness !== undefined ) object.backgroundBlurriness = data.backgroundBlurriness;
  24927. if ( data.backgroundIntensity !== undefined ) object.backgroundIntensity = data.backgroundIntensity;
  24928. if ( data.backgroundRotation !== undefined ) object.backgroundRotation.fromArray( data.backgroundRotation );
  24929. if ( data.environmentIntensity !== undefined ) object.environmentIntensity = data.environmentIntensity;
  24930. if ( data.environmentRotation !== undefined ) object.environmentRotation.fromArray( data.environmentRotation );
  24931. break;
  24932. case 'PerspectiveCamera':
  24933. object = new PerspectiveCamera( data.fov, data.aspect, data.near, data.far );
  24934. if ( data.focus !== undefined ) object.focus = data.focus;
  24935. if ( data.zoom !== undefined ) object.zoom = data.zoom;
  24936. if ( data.filmGauge !== undefined ) object.filmGauge = data.filmGauge;
  24937. if ( data.filmOffset !== undefined ) object.filmOffset = data.filmOffset;
  24938. if ( data.view !== undefined ) object.view = Object.assign( {}, data.view );
  24939. break;
  24940. case 'OrthographicCamera':
  24941. object = new OrthographicCamera( data.left, data.right, data.top, data.bottom, data.near, data.far );
  24942. if ( data.zoom !== undefined ) object.zoom = data.zoom;
  24943. if ( data.view !== undefined ) object.view = Object.assign( {}, data.view );
  24944. break;
  24945. case 'AmbientLight':
  24946. object = new AmbientLight( data.color, data.intensity );
  24947. break;
  24948. case 'DirectionalLight':
  24949. object = new DirectionalLight( data.color, data.intensity );
  24950. object.target = data.target || '';
  24951. break;
  24952. case 'PointLight':
  24953. object = new PointLight( data.color, data.intensity, data.distance, data.decay );
  24954. break;
  24955. case 'RectAreaLight':
  24956. object = new RectAreaLight( data.color, data.intensity, data.width, data.height );
  24957. break;
  24958. case 'SpotLight':
  24959. object = new SpotLight( data.color, data.intensity, data.distance, data.angle, data.penumbra, data.decay );
  24960. object.target = data.target || '';
  24961. break;
  24962. case 'HemisphereLight':
  24963. object = new HemisphereLight( data.color, data.groundColor, data.intensity );
  24964. break;
  24965. case 'LightProbe':
  24966. object = new LightProbe().fromJSON( data );
  24967. break;
  24968. case 'SkinnedMesh':
  24969. geometry = getGeometry( data.geometry );
  24970. material = getMaterial( data.material );
  24971. object = new SkinnedMesh( geometry, material );
  24972. if ( data.bindMode !== undefined ) object.bindMode = data.bindMode;
  24973. if ( data.bindMatrix !== undefined ) object.bindMatrix.fromArray( data.bindMatrix );
  24974. if ( data.skeleton !== undefined ) object.skeleton = data.skeleton;
  24975. break;
  24976. case 'Mesh':
  24977. geometry = getGeometry( data.geometry );
  24978. material = getMaterial( data.material );
  24979. object = new Mesh( geometry, material );
  24980. break;
  24981. case 'InstancedMesh':
  24982. geometry = getGeometry( data.geometry );
  24983. material = getMaterial( data.material );
  24984. const count = data.count;
  24985. const instanceMatrix = data.instanceMatrix;
  24986. const instanceColor = data.instanceColor;
  24987. object = new InstancedMesh( geometry, material, count );
  24988. object.instanceMatrix = new InstancedBufferAttribute( new Float32Array( instanceMatrix.array ), 16 );
  24989. if ( instanceColor !== undefined ) object.instanceColor = new InstancedBufferAttribute( new Float32Array( instanceColor.array ), instanceColor.itemSize );
  24990. break;
  24991. case 'BatchedMesh':
  24992. geometry = getGeometry( data.geometry );
  24993. material = getMaterial( data.material );
  24994. object = new BatchedMesh( data.maxInstanceCount, data.maxVertexCount, data.maxIndexCount, material );
  24995. object.geometry = geometry;
  24996. object.perObjectFrustumCulled = data.perObjectFrustumCulled;
  24997. object.sortObjects = data.sortObjects;
  24998. object._drawRanges = data.drawRanges;
  24999. object._reservedRanges = data.reservedRanges;
  25000. object._visibility = data.visibility;
  25001. object._active = data.active;
  25002. object._bounds = data.bounds.map( bound => {
  25003. const box = new Box3();
  25004. box.min.fromArray( bound.boxMin );
  25005. box.max.fromArray( bound.boxMax );
  25006. const sphere = new Sphere();
  25007. sphere.radius = bound.sphereRadius;
  25008. sphere.center.fromArray( bound.sphereCenter );
  25009. return {
  25010. boxInitialized: bound.boxInitialized,
  25011. box: box,
  25012. sphereInitialized: bound.sphereInitialized,
  25013. sphere: sphere
  25014. };
  25015. } );
  25016. object._maxInstanceCount = data.maxInstanceCount;
  25017. object._maxVertexCount = data.maxVertexCount;
  25018. object._maxIndexCount = data.maxIndexCount;
  25019. object._geometryInitialized = data.geometryInitialized;
  25020. object._geometryCount = data.geometryCount;
  25021. object._matricesTexture = getTexture( data.matricesTexture.uuid );
  25022. if ( data.colorsTexture !== undefined ) object._colorsTexture = getTexture( data.colorsTexture.uuid );
  25023. break;
  25024. case 'LOD':
  25025. object = new LOD();
  25026. break;
  25027. case 'Line':
  25028. object = new Line( getGeometry( data.geometry ), getMaterial( data.material ) );
  25029. break;
  25030. case 'LineLoop':
  25031. object = new LineLoop( getGeometry( data.geometry ), getMaterial( data.material ) );
  25032. break;
  25033. case 'LineSegments':
  25034. object = new LineSegments( getGeometry( data.geometry ), getMaterial( data.material ) );
  25035. break;
  25036. case 'PointCloud':
  25037. case 'Points':
  25038. object = new Points( getGeometry( data.geometry ), getMaterial( data.material ) );
  25039. break;
  25040. case 'Sprite':
  25041. object = new Sprite( getMaterial( data.material ) );
  25042. break;
  25043. case 'Group':
  25044. object = new Group();
  25045. break;
  25046. case 'Bone':
  25047. object = new Bone();
  25048. break;
  25049. default:
  25050. object = new Object3D();
  25051. }
  25052. object.uuid = data.uuid;
  25053. if ( data.name !== undefined ) object.name = data.name;
  25054. if ( data.matrix !== undefined ) {
  25055. object.matrix.fromArray( data.matrix );
  25056. if ( data.matrixAutoUpdate !== undefined ) object.matrixAutoUpdate = data.matrixAutoUpdate;
  25057. if ( object.matrixAutoUpdate ) object.matrix.decompose( object.position, object.quaternion, object.scale );
  25058. } else {
  25059. if ( data.position !== undefined ) object.position.fromArray( data.position );
  25060. if ( data.rotation !== undefined ) object.rotation.fromArray( data.rotation );
  25061. if ( data.quaternion !== undefined ) object.quaternion.fromArray( data.quaternion );
  25062. if ( data.scale !== undefined ) object.scale.fromArray( data.scale );
  25063. }
  25064. if ( data.up !== undefined ) object.up.fromArray( data.up );
  25065. if ( data.castShadow !== undefined ) object.castShadow = data.castShadow;
  25066. if ( data.receiveShadow !== undefined ) object.receiveShadow = data.receiveShadow;
  25067. if ( data.shadow ) {
  25068. if ( data.shadow.intensity !== undefined ) object.shadow.intensity = data.shadow.intensity;
  25069. if ( data.shadow.bias !== undefined ) object.shadow.bias = data.shadow.bias;
  25070. if ( data.shadow.normalBias !== undefined ) object.shadow.normalBias = data.shadow.normalBias;
  25071. if ( data.shadow.radius !== undefined ) object.shadow.radius = data.shadow.radius;
  25072. if ( data.shadow.mapSize !== undefined ) object.shadow.mapSize.fromArray( data.shadow.mapSize );
  25073. if ( data.shadow.camera !== undefined ) object.shadow.camera = this.parseObject( data.shadow.camera );
  25074. }
  25075. if ( data.visible !== undefined ) object.visible = data.visible;
  25076. if ( data.frustumCulled !== undefined ) object.frustumCulled = data.frustumCulled;
  25077. if ( data.renderOrder !== undefined ) object.renderOrder = data.renderOrder;
  25078. if ( data.userData !== undefined ) object.userData = data.userData;
  25079. if ( data.layers !== undefined ) object.layers.mask = data.layers;
  25080. if ( data.children !== undefined ) {
  25081. const children = data.children;
  25082. for ( let i = 0; i < children.length; i ++ ) {
  25083. object.add( this.parseObject( children[ i ], geometries, materials, textures, animations ) );
  25084. }
  25085. }
  25086. if ( data.animations !== undefined ) {
  25087. const objectAnimations = data.animations;
  25088. for ( let i = 0; i < objectAnimations.length; i ++ ) {
  25089. const uuid = objectAnimations[ i ];
  25090. object.animations.push( animations[ uuid ] );
  25091. }
  25092. }
  25093. if ( data.type === 'LOD' ) {
  25094. if ( data.autoUpdate !== undefined ) object.autoUpdate = data.autoUpdate;
  25095. const levels = data.levels;
  25096. for ( let l = 0; l < levels.length; l ++ ) {
  25097. const level = levels[ l ];
  25098. const child = object.getObjectByProperty( 'uuid', level.object );
  25099. if ( child !== undefined ) {
  25100. object.addLevel( child, level.distance, level.hysteresis );
  25101. }
  25102. }
  25103. }
  25104. return object;
  25105. }
  25106. bindSkeletons( object, skeletons ) {
  25107. if ( Object.keys( skeletons ).length === 0 ) return;
  25108. object.traverse( function ( child ) {
  25109. if ( child.isSkinnedMesh === true && child.skeleton !== undefined ) {
  25110. const skeleton = skeletons[ child.skeleton ];
  25111. if ( skeleton === undefined ) {
  25112. console.warn( 'THREE.ObjectLoader: No skeleton found with UUID:', child.skeleton );
  25113. } else {
  25114. child.bind( skeleton, child.bindMatrix );
  25115. }
  25116. }
  25117. } );
  25118. }
  25119. bindLightTargets( object ) {
  25120. object.traverse( function ( child ) {
  25121. if ( child.isDirectionalLight || child.isSpotLight ) {
  25122. const uuid = child.target;
  25123. const target = object.getObjectByProperty( 'uuid', uuid );
  25124. if ( target !== undefined ) {
  25125. child.target = target;
  25126. } else {
  25127. child.target = new Object3D();
  25128. }
  25129. }
  25130. } );
  25131. }
  25132. }
  25133. const TEXTURE_MAPPING = {
  25134. UVMapping: UVMapping,
  25135. CubeReflectionMapping: CubeReflectionMapping,
  25136. CubeRefractionMapping: CubeRefractionMapping,
  25137. EquirectangularReflectionMapping: EquirectangularReflectionMapping,
  25138. EquirectangularRefractionMapping: EquirectangularRefractionMapping,
  25139. CubeUVReflectionMapping: CubeUVReflectionMapping
  25140. };
  25141. const TEXTURE_WRAPPING = {
  25142. RepeatWrapping: RepeatWrapping,
  25143. ClampToEdgeWrapping: ClampToEdgeWrapping,
  25144. MirroredRepeatWrapping: MirroredRepeatWrapping
  25145. };
  25146. const TEXTURE_FILTER = {
  25147. NearestFilter: NearestFilter,
  25148. NearestMipmapNearestFilter: NearestMipmapNearestFilter,
  25149. NearestMipmapLinearFilter: NearestMipmapLinearFilter,
  25150. LinearFilter: LinearFilter,
  25151. LinearMipmapNearestFilter: LinearMipmapNearestFilter,
  25152. LinearMipmapLinearFilter: LinearMipmapLinearFilter
  25153. };
  25154. class ImageBitmapLoader extends Loader {
  25155. constructor( manager ) {
  25156. super( manager );
  25157. this.isImageBitmapLoader = true;
  25158. if ( typeof createImageBitmap === 'undefined' ) {
  25159. console.warn( 'THREE.ImageBitmapLoader: createImageBitmap() not supported.' );
  25160. }
  25161. if ( typeof fetch === 'undefined' ) {
  25162. console.warn( 'THREE.ImageBitmapLoader: fetch() not supported.' );
  25163. }
  25164. this.options = { premultiplyAlpha: 'none' };
  25165. }
  25166. setOptions( options ) {
  25167. this.options = options;
  25168. return this;
  25169. }
  25170. load( url, onLoad, onProgress, onError ) {
  25171. if ( url === undefined ) url = '';
  25172. if ( this.path !== undefined ) url = this.path + url;
  25173. url = this.manager.resolveURL( url );
  25174. const scope = this;
  25175. const cached = Cache.get( url );
  25176. if ( cached !== undefined ) {
  25177. scope.manager.itemStart( url );
  25178. // If cached is a promise, wait for it to resolve
  25179. if ( cached.then ) {
  25180. cached.then( imageBitmap => {
  25181. if ( onLoad ) onLoad( imageBitmap );
  25182. scope.manager.itemEnd( url );
  25183. } ).catch( e => {
  25184. if ( onError ) onError( e );
  25185. } );
  25186. return;
  25187. }
  25188. // If cached is not a promise (i.e., it's already an imageBitmap)
  25189. setTimeout( function () {
  25190. if ( onLoad ) onLoad( cached );
  25191. scope.manager.itemEnd( url );
  25192. }, 0 );
  25193. return cached;
  25194. }
  25195. const fetchOptions = {};
  25196. fetchOptions.credentials = ( this.crossOrigin === 'anonymous' ) ? 'same-origin' : 'include';
  25197. fetchOptions.headers = this.requestHeader;
  25198. const promise = fetch( url, fetchOptions ).then( function ( res ) {
  25199. return res.blob();
  25200. } ).then( function ( blob ) {
  25201. return createImageBitmap( blob, Object.assign( scope.options, { colorSpaceConversion: 'none' } ) );
  25202. } ).then( function ( imageBitmap ) {
  25203. Cache.add( url, imageBitmap );
  25204. if ( onLoad ) onLoad( imageBitmap );
  25205. scope.manager.itemEnd( url );
  25206. return imageBitmap;
  25207. } ).catch( function ( e ) {
  25208. if ( onError ) onError( e );
  25209. Cache.remove( url );
  25210. scope.manager.itemError( url );
  25211. scope.manager.itemEnd( url );
  25212. } );
  25213. Cache.add( url, promise );
  25214. scope.manager.itemStart( url );
  25215. }
  25216. }
  25217. let _context;
  25218. class AudioContext {
  25219. static getContext() {
  25220. if ( _context === undefined ) {
  25221. _context = new ( window.AudioContext || window.webkitAudioContext )();
  25222. }
  25223. return _context;
  25224. }
  25225. static setContext( value ) {
  25226. _context = value;
  25227. }
  25228. }
  25229. class AudioLoader extends Loader {
  25230. constructor( manager ) {
  25231. super( manager );
  25232. }
  25233. load( url, onLoad, onProgress, onError ) {
  25234. const scope = this;
  25235. const loader = new FileLoader( this.manager );
  25236. loader.setResponseType( 'arraybuffer' );
  25237. loader.setPath( this.path );
  25238. loader.setRequestHeader( this.requestHeader );
  25239. loader.setWithCredentials( this.withCredentials );
  25240. loader.load( url, function ( buffer ) {
  25241. try {
  25242. // Create a copy of the buffer. The `decodeAudioData` method
  25243. // detaches the buffer when complete, preventing reuse.
  25244. const bufferCopy = buffer.slice( 0 );
  25245. const context = AudioContext.getContext();
  25246. context.decodeAudioData( bufferCopy, function ( audioBuffer ) {
  25247. onLoad( audioBuffer );
  25248. } ).catch( handleError );
  25249. } catch ( e ) {
  25250. handleError( e );
  25251. }
  25252. }, onProgress, onError );
  25253. function handleError( e ) {
  25254. if ( onError ) {
  25255. onError( e );
  25256. } else {
  25257. console.error( e );
  25258. }
  25259. scope.manager.itemError( url );
  25260. }
  25261. }
  25262. }
  25263. const _eyeRight = /*@__PURE__*/ new Matrix4();
  25264. const _eyeLeft = /*@__PURE__*/ new Matrix4();
  25265. const _projectionMatrix = /*@__PURE__*/ new Matrix4();
  25266. /**
  25267. * A special type of camera that uses two perspective cameras with
  25268. * stereoscopic projection. Can be used for rendering stereo effects
  25269. * like [3D Anaglyph]{@link https://en.wikipedia.org/wiki/Anaglyph_3D} or
  25270. * [Parallax Barrier]{@link https://en.wikipedia.org/wiki/parallax_barrier}.
  25271. */
  25272. class StereoCamera {
  25273. /**
  25274. * Constructs a new stereo camera.
  25275. */
  25276. constructor() {
  25277. /**
  25278. * The type property is used for detecting the object type
  25279. * in context of serialization/deserialization.
  25280. *
  25281. * @type {string}
  25282. * @readonly
  25283. */
  25284. this.type = 'StereoCamera';
  25285. /**
  25286. * The aspect.
  25287. *
  25288. * @type {number}
  25289. * @default 1
  25290. */
  25291. this.aspect = 1;
  25292. /**
  25293. * The eye separation which represents the distance
  25294. * between the left and right camera.
  25295. *
  25296. * @type {number}
  25297. * @default 0.064
  25298. */
  25299. this.eyeSep = 0.064;
  25300. /**
  25301. * The camera representing the left eye. This is added to layer `1` so objects to be
  25302. * rendered by the left camera must also be added to this layer.
  25303. *
  25304. * @type {PerspectiveCamera}
  25305. */
  25306. this.cameraL = new PerspectiveCamera();
  25307. this.cameraL.layers.enable( 1 );
  25308. this.cameraL.matrixAutoUpdate = false;
  25309. /**
  25310. * The camera representing the right eye. This is added to layer `2` so objects to be
  25311. * rendered by the right camera must also be added to this layer.
  25312. *
  25313. * @type {PerspectiveCamera}
  25314. */
  25315. this.cameraR = new PerspectiveCamera();
  25316. this.cameraR.layers.enable( 2 );
  25317. this.cameraR.matrixAutoUpdate = false;
  25318. this._cache = {
  25319. focus: null,
  25320. fov: null,
  25321. aspect: null,
  25322. near: null,
  25323. far: null,
  25324. zoom: null,
  25325. eyeSep: null
  25326. };
  25327. }
  25328. /**
  25329. * Updates the stereo camera based on the given perspective camera.
  25330. *
  25331. * @param {PerspectiveCamera} camera - The perspective camera.
  25332. */
  25333. update( camera ) {
  25334. const cache = this._cache;
  25335. const needsUpdate = cache.focus !== camera.focus || cache.fov !== camera.fov ||
  25336. cache.aspect !== camera.aspect * this.aspect || cache.near !== camera.near ||
  25337. cache.far !== camera.far || cache.zoom !== camera.zoom || cache.eyeSep !== this.eyeSep;
  25338. if ( needsUpdate ) {
  25339. cache.focus = camera.focus;
  25340. cache.fov = camera.fov;
  25341. cache.aspect = camera.aspect * this.aspect;
  25342. cache.near = camera.near;
  25343. cache.far = camera.far;
  25344. cache.zoom = camera.zoom;
  25345. cache.eyeSep = this.eyeSep;
  25346. // Off-axis stereoscopic effect based on
  25347. // http://paulbourke.net/stereographics/stereorender/
  25348. _projectionMatrix.copy( camera.projectionMatrix );
  25349. const eyeSepHalf = cache.eyeSep / 2;
  25350. const eyeSepOnProjection = eyeSepHalf * cache.near / cache.focus;
  25351. const ymax = ( cache.near * Math.tan( DEG2RAD * cache.fov * 0.5 ) ) / cache.zoom;
  25352. let xmin, xmax;
  25353. // translate xOffset
  25354. _eyeLeft.elements[ 12 ] = - eyeSepHalf;
  25355. _eyeRight.elements[ 12 ] = eyeSepHalf;
  25356. // for left eye
  25357. xmin = - ymax * cache.aspect + eyeSepOnProjection;
  25358. xmax = ymax * cache.aspect + eyeSepOnProjection;
  25359. _projectionMatrix.elements[ 0 ] = 2 * cache.near / ( xmax - xmin );
  25360. _projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin );
  25361. this.cameraL.projectionMatrix.copy( _projectionMatrix );
  25362. // for right eye
  25363. xmin = - ymax * cache.aspect - eyeSepOnProjection;
  25364. xmax = ymax * cache.aspect - eyeSepOnProjection;
  25365. _projectionMatrix.elements[ 0 ] = 2 * cache.near / ( xmax - xmin );
  25366. _projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin );
  25367. this.cameraR.projectionMatrix.copy( _projectionMatrix );
  25368. }
  25369. this.cameraL.matrixWorld.copy( camera.matrixWorld ).multiply( _eyeLeft );
  25370. this.cameraR.matrixWorld.copy( camera.matrixWorld ).multiply( _eyeRight );
  25371. }
  25372. }
  25373. /**
  25374. * This type of camera can be used in order to efficiently render a scene with a
  25375. * predefined set of cameras. This is an important performance aspect for
  25376. * rendering VR scenes.
  25377. *
  25378. * An instance of `ArrayCamera` always has an array of sub cameras. It's mandatory
  25379. * to define for each sub camera the `viewport` property which determines the
  25380. * part of the viewport that is rendered with this camera.
  25381. *
  25382. * @augments PerspectiveCamera
  25383. */
  25384. class ArrayCamera extends PerspectiveCamera {
  25385. /**
  25386. * Constructs a new array camera.
  25387. *
  25388. * @param {Array<PerspectiveCamera>} [array=[]] - An array of perspective sub cameras.
  25389. */
  25390. constructor( array = [] ) {
  25391. super();
  25392. /**
  25393. * This flag can be used for type testing.
  25394. *
  25395. * @type {boolean}
  25396. * @readonly
  25397. * @default true
  25398. */
  25399. this.isArrayCamera = true;
  25400. /**
  25401. * An array of perspective sub cameras.
  25402. *
  25403. * @type {Array<PerspectiveCamera>}
  25404. */
  25405. this.cameras = array;
  25406. this.index = 0;
  25407. }
  25408. }
  25409. class Clock {
  25410. constructor( autoStart = true ) {
  25411. this.autoStart = autoStart;
  25412. this.startTime = 0;
  25413. this.oldTime = 0;
  25414. this.elapsedTime = 0;
  25415. this.running = false;
  25416. }
  25417. start() {
  25418. this.startTime = now();
  25419. this.oldTime = this.startTime;
  25420. this.elapsedTime = 0;
  25421. this.running = true;
  25422. }
  25423. stop() {
  25424. this.getElapsedTime();
  25425. this.running = false;
  25426. this.autoStart = false;
  25427. }
  25428. getElapsedTime() {
  25429. this.getDelta();
  25430. return this.elapsedTime;
  25431. }
  25432. getDelta() {
  25433. let diff = 0;
  25434. if ( this.autoStart && ! this.running ) {
  25435. this.start();
  25436. return 0;
  25437. }
  25438. if ( this.running ) {
  25439. const newTime = now();
  25440. diff = ( newTime - this.oldTime ) / 1000;
  25441. this.oldTime = newTime;
  25442. this.elapsedTime += diff;
  25443. }
  25444. return diff;
  25445. }
  25446. }
  25447. function now() {
  25448. return performance.now();
  25449. }
  25450. const _position$1 = /*@__PURE__*/ new Vector3();
  25451. const _quaternion$1 = /*@__PURE__*/ new Quaternion();
  25452. const _scale$1 = /*@__PURE__*/ new Vector3();
  25453. const _orientation$1 = /*@__PURE__*/ new Vector3();
  25454. class AudioListener extends Object3D {
  25455. constructor() {
  25456. super();
  25457. this.type = 'AudioListener';
  25458. this.context = AudioContext.getContext();
  25459. this.gain = this.context.createGain();
  25460. this.gain.connect( this.context.destination );
  25461. this.filter = null;
  25462. this.timeDelta = 0;
  25463. // private
  25464. this._clock = new Clock();
  25465. }
  25466. getInput() {
  25467. return this.gain;
  25468. }
  25469. removeFilter() {
  25470. if ( this.filter !== null ) {
  25471. this.gain.disconnect( this.filter );
  25472. this.filter.disconnect( this.context.destination );
  25473. this.gain.connect( this.context.destination );
  25474. this.filter = null;
  25475. }
  25476. return this;
  25477. }
  25478. getFilter() {
  25479. return this.filter;
  25480. }
  25481. setFilter( value ) {
  25482. if ( this.filter !== null ) {
  25483. this.gain.disconnect( this.filter );
  25484. this.filter.disconnect( this.context.destination );
  25485. } else {
  25486. this.gain.disconnect( this.context.destination );
  25487. }
  25488. this.filter = value;
  25489. this.gain.connect( this.filter );
  25490. this.filter.connect( this.context.destination );
  25491. return this;
  25492. }
  25493. getMasterVolume() {
  25494. return this.gain.gain.value;
  25495. }
  25496. setMasterVolume( value ) {
  25497. this.gain.gain.setTargetAtTime( value, this.context.currentTime, 0.01 );
  25498. return this;
  25499. }
  25500. updateMatrixWorld( force ) {
  25501. super.updateMatrixWorld( force );
  25502. const listener = this.context.listener;
  25503. const up = this.up;
  25504. this.timeDelta = this._clock.getDelta();
  25505. this.matrixWorld.decompose( _position$1, _quaternion$1, _scale$1 );
  25506. _orientation$1.set( 0, 0, -1 ).applyQuaternion( _quaternion$1 );
  25507. if ( listener.positionX ) {
  25508. // code path for Chrome (see #14393)
  25509. const endTime = this.context.currentTime + this.timeDelta;
  25510. listener.positionX.linearRampToValueAtTime( _position$1.x, endTime );
  25511. listener.positionY.linearRampToValueAtTime( _position$1.y, endTime );
  25512. listener.positionZ.linearRampToValueAtTime( _position$1.z, endTime );
  25513. listener.forwardX.linearRampToValueAtTime( _orientation$1.x, endTime );
  25514. listener.forwardY.linearRampToValueAtTime( _orientation$1.y, endTime );
  25515. listener.forwardZ.linearRampToValueAtTime( _orientation$1.z, endTime );
  25516. listener.upX.linearRampToValueAtTime( up.x, endTime );
  25517. listener.upY.linearRampToValueAtTime( up.y, endTime );
  25518. listener.upZ.linearRampToValueAtTime( up.z, endTime );
  25519. } else {
  25520. listener.setPosition( _position$1.x, _position$1.y, _position$1.z );
  25521. listener.setOrientation( _orientation$1.x, _orientation$1.y, _orientation$1.z, up.x, up.y, up.z );
  25522. }
  25523. }
  25524. }
  25525. class Audio extends Object3D {
  25526. constructor( listener ) {
  25527. super();
  25528. this.type = 'Audio';
  25529. this.listener = listener;
  25530. this.context = listener.context;
  25531. this.gain = this.context.createGain();
  25532. this.gain.connect( listener.getInput() );
  25533. this.autoplay = false;
  25534. this.buffer = null;
  25535. this.detune = 0;
  25536. this.loop = false;
  25537. this.loopStart = 0;
  25538. this.loopEnd = 0;
  25539. this.offset = 0;
  25540. this.duration = undefined;
  25541. this.playbackRate = 1;
  25542. this.isPlaying = false;
  25543. this.hasPlaybackControl = true;
  25544. this.source = null;
  25545. this.sourceType = 'empty';
  25546. this._startedAt = 0;
  25547. this._progress = 0;
  25548. this._connected = false;
  25549. this.filters = [];
  25550. }
  25551. getOutput() {
  25552. return this.gain;
  25553. }
  25554. setNodeSource( audioNode ) {
  25555. this.hasPlaybackControl = false;
  25556. this.sourceType = 'audioNode';
  25557. this.source = audioNode;
  25558. this.connect();
  25559. return this;
  25560. }
  25561. setMediaElementSource( mediaElement ) {
  25562. this.hasPlaybackControl = false;
  25563. this.sourceType = 'mediaNode';
  25564. this.source = this.context.createMediaElementSource( mediaElement );
  25565. this.connect();
  25566. return this;
  25567. }
  25568. setMediaStreamSource( mediaStream ) {
  25569. this.hasPlaybackControl = false;
  25570. this.sourceType = 'mediaStreamNode';
  25571. this.source = this.context.createMediaStreamSource( mediaStream );
  25572. this.connect();
  25573. return this;
  25574. }
  25575. setBuffer( audioBuffer ) {
  25576. this.buffer = audioBuffer;
  25577. this.sourceType = 'buffer';
  25578. if ( this.autoplay ) this.play();
  25579. return this;
  25580. }
  25581. play( delay = 0 ) {
  25582. if ( this.isPlaying === true ) {
  25583. console.warn( 'THREE.Audio: Audio is already playing.' );
  25584. return;
  25585. }
  25586. if ( this.hasPlaybackControl === false ) {
  25587. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  25588. return;
  25589. }
  25590. this._startedAt = this.context.currentTime + delay;
  25591. const source = this.context.createBufferSource();
  25592. source.buffer = this.buffer;
  25593. source.loop = this.loop;
  25594. source.loopStart = this.loopStart;
  25595. source.loopEnd = this.loopEnd;
  25596. source.onended = this.onEnded.bind( this );
  25597. source.start( this._startedAt, this._progress + this.offset, this.duration );
  25598. this.isPlaying = true;
  25599. this.source = source;
  25600. this.setDetune( this.detune );
  25601. this.setPlaybackRate( this.playbackRate );
  25602. return this.connect();
  25603. }
  25604. pause() {
  25605. if ( this.hasPlaybackControl === false ) {
  25606. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  25607. return;
  25608. }
  25609. if ( this.isPlaying === true ) {
  25610. // update current progress
  25611. this._progress += Math.max( this.context.currentTime - this._startedAt, 0 ) * this.playbackRate;
  25612. if ( this.loop === true ) {
  25613. // ensure _progress does not exceed duration with looped audios
  25614. this._progress = this._progress % ( this.duration || this.buffer.duration );
  25615. }
  25616. this.source.stop();
  25617. this.source.onended = null;
  25618. this.isPlaying = false;
  25619. }
  25620. return this;
  25621. }
  25622. stop( delay = 0 ) {
  25623. if ( this.hasPlaybackControl === false ) {
  25624. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  25625. return;
  25626. }
  25627. this._progress = 0;
  25628. if ( this.source !== null ) {
  25629. this.source.stop( this.context.currentTime + delay );
  25630. this.source.onended = null;
  25631. }
  25632. this.isPlaying = false;
  25633. return this;
  25634. }
  25635. connect() {
  25636. if ( this.filters.length > 0 ) {
  25637. this.source.connect( this.filters[ 0 ] );
  25638. for ( let i = 1, l = this.filters.length; i < l; i ++ ) {
  25639. this.filters[ i - 1 ].connect( this.filters[ i ] );
  25640. }
  25641. this.filters[ this.filters.length - 1 ].connect( this.getOutput() );
  25642. } else {
  25643. this.source.connect( this.getOutput() );
  25644. }
  25645. this._connected = true;
  25646. return this;
  25647. }
  25648. disconnect() {
  25649. if ( this._connected === false ) {
  25650. return;
  25651. }
  25652. if ( this.filters.length > 0 ) {
  25653. this.source.disconnect( this.filters[ 0 ] );
  25654. for ( let i = 1, l = this.filters.length; i < l; i ++ ) {
  25655. this.filters[ i - 1 ].disconnect( this.filters[ i ] );
  25656. }
  25657. this.filters[ this.filters.length - 1 ].disconnect( this.getOutput() );
  25658. } else {
  25659. this.source.disconnect( this.getOutput() );
  25660. }
  25661. this._connected = false;
  25662. return this;
  25663. }
  25664. getFilters() {
  25665. return this.filters;
  25666. }
  25667. setFilters( value ) {
  25668. if ( ! value ) value = [];
  25669. if ( this._connected === true ) {
  25670. this.disconnect();
  25671. this.filters = value.slice();
  25672. this.connect();
  25673. } else {
  25674. this.filters = value.slice();
  25675. }
  25676. return this;
  25677. }
  25678. setDetune( value ) {
  25679. this.detune = value;
  25680. if ( this.isPlaying === true && this.source.detune !== undefined ) {
  25681. this.source.detune.setTargetAtTime( this.detune, this.context.currentTime, 0.01 );
  25682. }
  25683. return this;
  25684. }
  25685. getDetune() {
  25686. return this.detune;
  25687. }
  25688. getFilter() {
  25689. return this.getFilters()[ 0 ];
  25690. }
  25691. setFilter( filter ) {
  25692. return this.setFilters( filter ? [ filter ] : [] );
  25693. }
  25694. setPlaybackRate( value ) {
  25695. if ( this.hasPlaybackControl === false ) {
  25696. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  25697. return;
  25698. }
  25699. this.playbackRate = value;
  25700. if ( this.isPlaying === true ) {
  25701. this.source.playbackRate.setTargetAtTime( this.playbackRate, this.context.currentTime, 0.01 );
  25702. }
  25703. return this;
  25704. }
  25705. getPlaybackRate() {
  25706. return this.playbackRate;
  25707. }
  25708. onEnded() {
  25709. this.isPlaying = false;
  25710. this._progress = 0;
  25711. }
  25712. getLoop() {
  25713. if ( this.hasPlaybackControl === false ) {
  25714. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  25715. return false;
  25716. }
  25717. return this.loop;
  25718. }
  25719. setLoop( value ) {
  25720. if ( this.hasPlaybackControl === false ) {
  25721. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  25722. return;
  25723. }
  25724. this.loop = value;
  25725. if ( this.isPlaying === true ) {
  25726. this.source.loop = this.loop;
  25727. }
  25728. return this;
  25729. }
  25730. setLoopStart( value ) {
  25731. this.loopStart = value;
  25732. return this;
  25733. }
  25734. setLoopEnd( value ) {
  25735. this.loopEnd = value;
  25736. return this;
  25737. }
  25738. getVolume() {
  25739. return this.gain.gain.value;
  25740. }
  25741. setVolume( value ) {
  25742. this.gain.gain.setTargetAtTime( value, this.context.currentTime, 0.01 );
  25743. return this;
  25744. }
  25745. copy( source, recursive ) {
  25746. super.copy( source, recursive );
  25747. if ( source.sourceType !== 'buffer' ) {
  25748. console.warn( 'THREE.Audio: Audio source type cannot be copied.' );
  25749. return this;
  25750. }
  25751. this.autoplay = source.autoplay;
  25752. this.buffer = source.buffer;
  25753. this.detune = source.detune;
  25754. this.loop = source.loop;
  25755. this.loopStart = source.loopStart;
  25756. this.loopEnd = source.loopEnd;
  25757. this.offset = source.offset;
  25758. this.duration = source.duration;
  25759. this.playbackRate = source.playbackRate;
  25760. this.hasPlaybackControl = source.hasPlaybackControl;
  25761. this.sourceType = source.sourceType;
  25762. this.filters = source.filters.slice();
  25763. return this;
  25764. }
  25765. clone( recursive ) {
  25766. return new this.constructor( this.listener ).copy( this, recursive );
  25767. }
  25768. }
  25769. const _position = /*@__PURE__*/ new Vector3();
  25770. const _quaternion = /*@__PURE__*/ new Quaternion();
  25771. const _scale = /*@__PURE__*/ new Vector3();
  25772. const _orientation = /*@__PURE__*/ new Vector3();
  25773. class PositionalAudio extends Audio {
  25774. constructor( listener ) {
  25775. super( listener );
  25776. this.panner = this.context.createPanner();
  25777. this.panner.panningModel = 'HRTF';
  25778. this.panner.connect( this.gain );
  25779. }
  25780. connect() {
  25781. super.connect();
  25782. this.panner.connect( this.gain );
  25783. }
  25784. disconnect() {
  25785. super.disconnect();
  25786. this.panner.disconnect( this.gain );
  25787. }
  25788. getOutput() {
  25789. return this.panner;
  25790. }
  25791. getRefDistance() {
  25792. return this.panner.refDistance;
  25793. }
  25794. setRefDistance( value ) {
  25795. this.panner.refDistance = value;
  25796. return this;
  25797. }
  25798. getRolloffFactor() {
  25799. return this.panner.rolloffFactor;
  25800. }
  25801. setRolloffFactor( value ) {
  25802. this.panner.rolloffFactor = value;
  25803. return this;
  25804. }
  25805. getDistanceModel() {
  25806. return this.panner.distanceModel;
  25807. }
  25808. setDistanceModel( value ) {
  25809. this.panner.distanceModel = value;
  25810. return this;
  25811. }
  25812. getMaxDistance() {
  25813. return this.panner.maxDistance;
  25814. }
  25815. setMaxDistance( value ) {
  25816. this.panner.maxDistance = value;
  25817. return this;
  25818. }
  25819. setDirectionalCone( coneInnerAngle, coneOuterAngle, coneOuterGain ) {
  25820. this.panner.coneInnerAngle = coneInnerAngle;
  25821. this.panner.coneOuterAngle = coneOuterAngle;
  25822. this.panner.coneOuterGain = coneOuterGain;
  25823. return this;
  25824. }
  25825. updateMatrixWorld( force ) {
  25826. super.updateMatrixWorld( force );
  25827. if ( this.hasPlaybackControl === true && this.isPlaying === false ) return;
  25828. this.matrixWorld.decompose( _position, _quaternion, _scale );
  25829. _orientation.set( 0, 0, 1 ).applyQuaternion( _quaternion );
  25830. const panner = this.panner;
  25831. if ( panner.positionX ) {
  25832. // code path for Chrome and Firefox (see #14393)
  25833. const endTime = this.context.currentTime + this.listener.timeDelta;
  25834. panner.positionX.linearRampToValueAtTime( _position.x, endTime );
  25835. panner.positionY.linearRampToValueAtTime( _position.y, endTime );
  25836. panner.positionZ.linearRampToValueAtTime( _position.z, endTime );
  25837. panner.orientationX.linearRampToValueAtTime( _orientation.x, endTime );
  25838. panner.orientationY.linearRampToValueAtTime( _orientation.y, endTime );
  25839. panner.orientationZ.linearRampToValueAtTime( _orientation.z, endTime );
  25840. } else {
  25841. panner.setPosition( _position.x, _position.y, _position.z );
  25842. panner.setOrientation( _orientation.x, _orientation.y, _orientation.z );
  25843. }
  25844. }
  25845. }
  25846. class AudioAnalyser {
  25847. constructor( audio, fftSize = 2048 ) {
  25848. this.analyser = audio.context.createAnalyser();
  25849. this.analyser.fftSize = fftSize;
  25850. this.data = new Uint8Array( this.analyser.frequencyBinCount );
  25851. audio.getOutput().connect( this.analyser );
  25852. }
  25853. getFrequencyData() {
  25854. this.analyser.getByteFrequencyData( this.data );
  25855. return this.data;
  25856. }
  25857. getAverageFrequency() {
  25858. let value = 0;
  25859. const data = this.getFrequencyData();
  25860. for ( let i = 0; i < data.length; i ++ ) {
  25861. value += data[ i ];
  25862. }
  25863. return value / data.length;
  25864. }
  25865. }
  25866. class PropertyMixer {
  25867. constructor( binding, typeName, valueSize ) {
  25868. this.binding = binding;
  25869. this.valueSize = valueSize;
  25870. let mixFunction,
  25871. mixFunctionAdditive,
  25872. setIdentity;
  25873. // buffer layout: [ incoming | accu0 | accu1 | orig | addAccu | (optional work) ]
  25874. //
  25875. // interpolators can use .buffer as their .result
  25876. // the data then goes to 'incoming'
  25877. //
  25878. // 'accu0' and 'accu1' are used frame-interleaved for
  25879. // the cumulative result and are compared to detect
  25880. // changes
  25881. //
  25882. // 'orig' stores the original state of the property
  25883. //
  25884. // 'add' is used for additive cumulative results
  25885. //
  25886. // 'work' is optional and is only present for quaternion types. It is used
  25887. // to store intermediate quaternion multiplication results
  25888. switch ( typeName ) {
  25889. case 'quaternion':
  25890. mixFunction = this._slerp;
  25891. mixFunctionAdditive = this._slerpAdditive;
  25892. setIdentity = this._setAdditiveIdentityQuaternion;
  25893. this.buffer = new Float64Array( valueSize * 6 );
  25894. this._workIndex = 5;
  25895. break;
  25896. case 'string':
  25897. case 'bool':
  25898. mixFunction = this._select;
  25899. // Use the regular mix function and for additive on these types,
  25900. // additive is not relevant for non-numeric types
  25901. mixFunctionAdditive = this._select;
  25902. setIdentity = this._setAdditiveIdentityOther;
  25903. this.buffer = new Array( valueSize * 5 );
  25904. break;
  25905. default:
  25906. mixFunction = this._lerp;
  25907. mixFunctionAdditive = this._lerpAdditive;
  25908. setIdentity = this._setAdditiveIdentityNumeric;
  25909. this.buffer = new Float64Array( valueSize * 5 );
  25910. }
  25911. this._mixBufferRegion = mixFunction;
  25912. this._mixBufferRegionAdditive = mixFunctionAdditive;
  25913. this._setIdentity = setIdentity;
  25914. this._origIndex = 3;
  25915. this._addIndex = 4;
  25916. this.cumulativeWeight = 0;
  25917. this.cumulativeWeightAdditive = 0;
  25918. this.useCount = 0;
  25919. this.referenceCount = 0;
  25920. }
  25921. // accumulate data in the 'incoming' region into 'accu<i>'
  25922. accumulate( accuIndex, weight ) {
  25923. // note: happily accumulating nothing when weight = 0, the caller knows
  25924. // the weight and shouldn't have made the call in the first place
  25925. const buffer = this.buffer,
  25926. stride = this.valueSize,
  25927. offset = accuIndex * stride + stride;
  25928. let currentWeight = this.cumulativeWeight;
  25929. if ( currentWeight === 0 ) {
  25930. // accuN := incoming * weight
  25931. for ( let i = 0; i !== stride; ++ i ) {
  25932. buffer[ offset + i ] = buffer[ i ];
  25933. }
  25934. currentWeight = weight;
  25935. } else {
  25936. // accuN := accuN + incoming * weight
  25937. currentWeight += weight;
  25938. const mix = weight / currentWeight;
  25939. this._mixBufferRegion( buffer, offset, 0, mix, stride );
  25940. }
  25941. this.cumulativeWeight = currentWeight;
  25942. }
  25943. // accumulate data in the 'incoming' region into 'add'
  25944. accumulateAdditive( weight ) {
  25945. const buffer = this.buffer,
  25946. stride = this.valueSize,
  25947. offset = stride * this._addIndex;
  25948. if ( this.cumulativeWeightAdditive === 0 ) {
  25949. // add = identity
  25950. this._setIdentity();
  25951. }
  25952. // add := add + incoming * weight
  25953. this._mixBufferRegionAdditive( buffer, offset, 0, weight, stride );
  25954. this.cumulativeWeightAdditive += weight;
  25955. }
  25956. // apply the state of 'accu<i>' to the binding when accus differ
  25957. apply( accuIndex ) {
  25958. const stride = this.valueSize,
  25959. buffer = this.buffer,
  25960. offset = accuIndex * stride + stride,
  25961. weight = this.cumulativeWeight,
  25962. weightAdditive = this.cumulativeWeightAdditive,
  25963. binding = this.binding;
  25964. this.cumulativeWeight = 0;
  25965. this.cumulativeWeightAdditive = 0;
  25966. if ( weight < 1 ) {
  25967. // accuN := accuN + original * ( 1 - cumulativeWeight )
  25968. const originalValueOffset = stride * this._origIndex;
  25969. this._mixBufferRegion(
  25970. buffer, offset, originalValueOffset, 1 - weight, stride );
  25971. }
  25972. if ( weightAdditive > 0 ) {
  25973. // accuN := accuN + additive accuN
  25974. this._mixBufferRegionAdditive( buffer, offset, this._addIndex * stride, 1, stride );
  25975. }
  25976. for ( let i = stride, e = stride + stride; i !== e; ++ i ) {
  25977. if ( buffer[ i ] !== buffer[ i + stride ] ) {
  25978. // value has changed -> update scene graph
  25979. binding.setValue( buffer, offset );
  25980. break;
  25981. }
  25982. }
  25983. }
  25984. // remember the state of the bound property and copy it to both accus
  25985. saveOriginalState() {
  25986. const binding = this.binding;
  25987. const buffer = this.buffer,
  25988. stride = this.valueSize,
  25989. originalValueOffset = stride * this._origIndex;
  25990. binding.getValue( buffer, originalValueOffset );
  25991. // accu[0..1] := orig -- initially detect changes against the original
  25992. for ( let i = stride, e = originalValueOffset; i !== e; ++ i ) {
  25993. buffer[ i ] = buffer[ originalValueOffset + ( i % stride ) ];
  25994. }
  25995. // Add to identity for additive
  25996. this._setIdentity();
  25997. this.cumulativeWeight = 0;
  25998. this.cumulativeWeightAdditive = 0;
  25999. }
  26000. // apply the state previously taken via 'saveOriginalState' to the binding
  26001. restoreOriginalState() {
  26002. const originalValueOffset = this.valueSize * 3;
  26003. this.binding.setValue( this.buffer, originalValueOffset );
  26004. }
  26005. _setAdditiveIdentityNumeric() {
  26006. const startIndex = this._addIndex * this.valueSize;
  26007. const endIndex = startIndex + this.valueSize;
  26008. for ( let i = startIndex; i < endIndex; i ++ ) {
  26009. this.buffer[ i ] = 0;
  26010. }
  26011. }
  26012. _setAdditiveIdentityQuaternion() {
  26013. this._setAdditiveIdentityNumeric();
  26014. this.buffer[ this._addIndex * this.valueSize + 3 ] = 1;
  26015. }
  26016. _setAdditiveIdentityOther() {
  26017. const startIndex = this._origIndex * this.valueSize;
  26018. const targetIndex = this._addIndex * this.valueSize;
  26019. for ( let i = 0; i < this.valueSize; i ++ ) {
  26020. this.buffer[ targetIndex + i ] = this.buffer[ startIndex + i ];
  26021. }
  26022. }
  26023. // mix functions
  26024. _select( buffer, dstOffset, srcOffset, t, stride ) {
  26025. if ( t >= 0.5 ) {
  26026. for ( let i = 0; i !== stride; ++ i ) {
  26027. buffer[ dstOffset + i ] = buffer[ srcOffset + i ];
  26028. }
  26029. }
  26030. }
  26031. _slerp( buffer, dstOffset, srcOffset, t ) {
  26032. Quaternion.slerpFlat( buffer, dstOffset, buffer, dstOffset, buffer, srcOffset, t );
  26033. }
  26034. _slerpAdditive( buffer, dstOffset, srcOffset, t, stride ) {
  26035. const workOffset = this._workIndex * stride;
  26036. // Store result in intermediate buffer offset
  26037. Quaternion.multiplyQuaternionsFlat( buffer, workOffset, buffer, dstOffset, buffer, srcOffset );
  26038. // Slerp to the intermediate result
  26039. Quaternion.slerpFlat( buffer, dstOffset, buffer, dstOffset, buffer, workOffset, t );
  26040. }
  26041. _lerp( buffer, dstOffset, srcOffset, t, stride ) {
  26042. const s = 1 - t;
  26043. for ( let i = 0; i !== stride; ++ i ) {
  26044. const j = dstOffset + i;
  26045. buffer[ j ] = buffer[ j ] * s + buffer[ srcOffset + i ] * t;
  26046. }
  26047. }
  26048. _lerpAdditive( buffer, dstOffset, srcOffset, t, stride ) {
  26049. for ( let i = 0; i !== stride; ++ i ) {
  26050. const j = dstOffset + i;
  26051. buffer[ j ] = buffer[ j ] + buffer[ srcOffset + i ] * t;
  26052. }
  26053. }
  26054. }
  26055. // Characters [].:/ are reserved for track binding syntax.
  26056. const _RESERVED_CHARS_RE = '\\[\\]\\.:\\/';
  26057. const _reservedRe = new RegExp( '[' + _RESERVED_CHARS_RE + ']', 'g' );
  26058. // Attempts to allow node names from any language. ES5's `\w` regexp matches
  26059. // only latin characters, and the unicode \p{L} is not yet supported. So
  26060. // instead, we exclude reserved characters and match everything else.
  26061. const _wordChar = '[^' + _RESERVED_CHARS_RE + ']';
  26062. const _wordCharOrDot = '[^' + _RESERVED_CHARS_RE.replace( '\\.', '' ) + ']';
  26063. // Parent directories, delimited by '/' or ':'. Currently unused, but must
  26064. // be matched to parse the rest of the track name.
  26065. const _directoryRe = /*@__PURE__*/ /((?:WC+[\/:])*)/.source.replace( 'WC', _wordChar );
  26066. // Target node. May contain word characters (a-zA-Z0-9_) and '.' or '-'.
  26067. const _nodeRe = /*@__PURE__*/ /(WCOD+)?/.source.replace( 'WCOD', _wordCharOrDot );
  26068. // Object on target node, and accessor. May not contain reserved
  26069. // characters. Accessor may contain any character except closing bracket.
  26070. const _objectRe = /*@__PURE__*/ /(?:\.(WC+)(?:\[(.+)\])?)?/.source.replace( 'WC', _wordChar );
  26071. // Property and accessor. May not contain reserved characters. Accessor may
  26072. // contain any non-bracket characters.
  26073. const _propertyRe = /*@__PURE__*/ /\.(WC+)(?:\[(.+)\])?/.source.replace( 'WC', _wordChar );
  26074. const _trackRe = new RegExp( ''
  26075. + '^'
  26076. + _directoryRe
  26077. + _nodeRe
  26078. + _objectRe
  26079. + _propertyRe
  26080. + '$'
  26081. );
  26082. const _supportedObjectNames = [ 'material', 'materials', 'bones', 'map' ];
  26083. class Composite {
  26084. constructor( targetGroup, path, optionalParsedPath ) {
  26085. const parsedPath = optionalParsedPath || PropertyBinding.parseTrackName( path );
  26086. this._targetGroup = targetGroup;
  26087. this._bindings = targetGroup.subscribe_( path, parsedPath );
  26088. }
  26089. getValue( array, offset ) {
  26090. this.bind(); // bind all binding
  26091. const firstValidIndex = this._targetGroup.nCachedObjects_,
  26092. binding = this._bindings[ firstValidIndex ];
  26093. // and only call .getValue on the first
  26094. if ( binding !== undefined ) binding.getValue( array, offset );
  26095. }
  26096. setValue( array, offset ) {
  26097. const bindings = this._bindings;
  26098. for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  26099. bindings[ i ].setValue( array, offset );
  26100. }
  26101. }
  26102. bind() {
  26103. const bindings = this._bindings;
  26104. for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  26105. bindings[ i ].bind();
  26106. }
  26107. }
  26108. unbind() {
  26109. const bindings = this._bindings;
  26110. for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  26111. bindings[ i ].unbind();
  26112. }
  26113. }
  26114. }
  26115. // Note: This class uses a State pattern on a per-method basis:
  26116. // 'bind' sets 'this.getValue' / 'setValue' and shadows the
  26117. // prototype version of these methods with one that represents
  26118. // the bound state. When the property is not found, the methods
  26119. // become no-ops.
  26120. class PropertyBinding {
  26121. constructor( rootNode, path, parsedPath ) {
  26122. this.path = path;
  26123. this.parsedPath = parsedPath || PropertyBinding.parseTrackName( path );
  26124. this.node = PropertyBinding.findNode( rootNode, this.parsedPath.nodeName );
  26125. this.rootNode = rootNode;
  26126. // initial state of these methods that calls 'bind'
  26127. this.getValue = this._getValue_unbound;
  26128. this.setValue = this._setValue_unbound;
  26129. }
  26130. static create( root, path, parsedPath ) {
  26131. if ( ! ( root && root.isAnimationObjectGroup ) ) {
  26132. return new PropertyBinding( root, path, parsedPath );
  26133. } else {
  26134. return new PropertyBinding.Composite( root, path, parsedPath );
  26135. }
  26136. }
  26137. /**
  26138. * Replaces spaces with underscores and removes unsupported characters from
  26139. * node names, to ensure compatibility with parseTrackName().
  26140. *
  26141. * @param {string} name Node name to be sanitized.
  26142. * @return {string}
  26143. */
  26144. static sanitizeNodeName( name ) {
  26145. return name.replace( /\s/g, '_' ).replace( _reservedRe, '' );
  26146. }
  26147. static parseTrackName( trackName ) {
  26148. const matches = _trackRe.exec( trackName );
  26149. if ( matches === null ) {
  26150. throw new Error( 'PropertyBinding: Cannot parse trackName: ' + trackName );
  26151. }
  26152. const results = {
  26153. // directoryName: matches[ 1 ], // (tschw) currently unused
  26154. nodeName: matches[ 2 ],
  26155. objectName: matches[ 3 ],
  26156. objectIndex: matches[ 4 ],
  26157. propertyName: matches[ 5 ], // required
  26158. propertyIndex: matches[ 6 ]
  26159. };
  26160. const lastDot = results.nodeName && results.nodeName.lastIndexOf( '.' );
  26161. if ( lastDot !== undefined && lastDot !== -1 ) {
  26162. const objectName = results.nodeName.substring( lastDot + 1 );
  26163. // Object names must be checked against an allowlist. Otherwise, there
  26164. // is no way to parse 'foo.bar.baz': 'baz' must be a property, but
  26165. // 'bar' could be the objectName, or part of a nodeName (which can
  26166. // include '.' characters).
  26167. if ( _supportedObjectNames.indexOf( objectName ) !== -1 ) {
  26168. results.nodeName = results.nodeName.substring( 0, lastDot );
  26169. results.objectName = objectName;
  26170. }
  26171. }
  26172. if ( results.propertyName === null || results.propertyName.length === 0 ) {
  26173. throw new Error( 'PropertyBinding: can not parse propertyName from trackName: ' + trackName );
  26174. }
  26175. return results;
  26176. }
  26177. static findNode( root, nodeName ) {
  26178. if ( nodeName === undefined || nodeName === '' || nodeName === '.' || nodeName === -1 || nodeName === root.name || nodeName === root.uuid ) {
  26179. return root;
  26180. }
  26181. // search into skeleton bones.
  26182. if ( root.skeleton ) {
  26183. const bone = root.skeleton.getBoneByName( nodeName );
  26184. if ( bone !== undefined ) {
  26185. return bone;
  26186. }
  26187. }
  26188. // search into node subtree.
  26189. if ( root.children ) {
  26190. const searchNodeSubtree = function ( children ) {
  26191. for ( let i = 0; i < children.length; i ++ ) {
  26192. const childNode = children[ i ];
  26193. if ( childNode.name === nodeName || childNode.uuid === nodeName ) {
  26194. return childNode;
  26195. }
  26196. const result = searchNodeSubtree( childNode.children );
  26197. if ( result ) return result;
  26198. }
  26199. return null;
  26200. };
  26201. const subTreeNode = searchNodeSubtree( root.children );
  26202. if ( subTreeNode ) {
  26203. return subTreeNode;
  26204. }
  26205. }
  26206. return null;
  26207. }
  26208. // these are used to "bind" a nonexistent property
  26209. _getValue_unavailable() {}
  26210. _setValue_unavailable() {}
  26211. // Getters
  26212. _getValue_direct( buffer, offset ) {
  26213. buffer[ offset ] = this.targetObject[ this.propertyName ];
  26214. }
  26215. _getValue_array( buffer, offset ) {
  26216. const source = this.resolvedProperty;
  26217. for ( let i = 0, n = source.length; i !== n; ++ i ) {
  26218. buffer[ offset ++ ] = source[ i ];
  26219. }
  26220. }
  26221. _getValue_arrayElement( buffer, offset ) {
  26222. buffer[ offset ] = this.resolvedProperty[ this.propertyIndex ];
  26223. }
  26224. _getValue_toArray( buffer, offset ) {
  26225. this.resolvedProperty.toArray( buffer, offset );
  26226. }
  26227. // Direct
  26228. _setValue_direct( buffer, offset ) {
  26229. this.targetObject[ this.propertyName ] = buffer[ offset ];
  26230. }
  26231. _setValue_direct_setNeedsUpdate( buffer, offset ) {
  26232. this.targetObject[ this.propertyName ] = buffer[ offset ];
  26233. this.targetObject.needsUpdate = true;
  26234. }
  26235. _setValue_direct_setMatrixWorldNeedsUpdate( buffer, offset ) {
  26236. this.targetObject[ this.propertyName ] = buffer[ offset ];
  26237. this.targetObject.matrixWorldNeedsUpdate = true;
  26238. }
  26239. // EntireArray
  26240. _setValue_array( buffer, offset ) {
  26241. const dest = this.resolvedProperty;
  26242. for ( let i = 0, n = dest.length; i !== n; ++ i ) {
  26243. dest[ i ] = buffer[ offset ++ ];
  26244. }
  26245. }
  26246. _setValue_array_setNeedsUpdate( buffer, offset ) {
  26247. const dest = this.resolvedProperty;
  26248. for ( let i = 0, n = dest.length; i !== n; ++ i ) {
  26249. dest[ i ] = buffer[ offset ++ ];
  26250. }
  26251. this.targetObject.needsUpdate = true;
  26252. }
  26253. _setValue_array_setMatrixWorldNeedsUpdate( buffer, offset ) {
  26254. const dest = this.resolvedProperty;
  26255. for ( let i = 0, n = dest.length; i !== n; ++ i ) {
  26256. dest[ i ] = buffer[ offset ++ ];
  26257. }
  26258. this.targetObject.matrixWorldNeedsUpdate = true;
  26259. }
  26260. // ArrayElement
  26261. _setValue_arrayElement( buffer, offset ) {
  26262. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  26263. }
  26264. _setValue_arrayElement_setNeedsUpdate( buffer, offset ) {
  26265. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  26266. this.targetObject.needsUpdate = true;
  26267. }
  26268. _setValue_arrayElement_setMatrixWorldNeedsUpdate( buffer, offset ) {
  26269. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  26270. this.targetObject.matrixWorldNeedsUpdate = true;
  26271. }
  26272. // HasToFromArray
  26273. _setValue_fromArray( buffer, offset ) {
  26274. this.resolvedProperty.fromArray( buffer, offset );
  26275. }
  26276. _setValue_fromArray_setNeedsUpdate( buffer, offset ) {
  26277. this.resolvedProperty.fromArray( buffer, offset );
  26278. this.targetObject.needsUpdate = true;
  26279. }
  26280. _setValue_fromArray_setMatrixWorldNeedsUpdate( buffer, offset ) {
  26281. this.resolvedProperty.fromArray( buffer, offset );
  26282. this.targetObject.matrixWorldNeedsUpdate = true;
  26283. }
  26284. _getValue_unbound( targetArray, offset ) {
  26285. this.bind();
  26286. this.getValue( targetArray, offset );
  26287. }
  26288. _setValue_unbound( sourceArray, offset ) {
  26289. this.bind();
  26290. this.setValue( sourceArray, offset );
  26291. }
  26292. // create getter / setter pair for a property in the scene graph
  26293. bind() {
  26294. let targetObject = this.node;
  26295. const parsedPath = this.parsedPath;
  26296. const objectName = parsedPath.objectName;
  26297. const propertyName = parsedPath.propertyName;
  26298. let propertyIndex = parsedPath.propertyIndex;
  26299. if ( ! targetObject ) {
  26300. targetObject = PropertyBinding.findNode( this.rootNode, parsedPath.nodeName );
  26301. this.node = targetObject;
  26302. }
  26303. // set fail state so we can just 'return' on error
  26304. this.getValue = this._getValue_unavailable;
  26305. this.setValue = this._setValue_unavailable;
  26306. // ensure there is a value node
  26307. if ( ! targetObject ) {
  26308. console.warn( 'THREE.PropertyBinding: No target node found for track: ' + this.path + '.' );
  26309. return;
  26310. }
  26311. if ( objectName ) {
  26312. let objectIndex = parsedPath.objectIndex;
  26313. // special cases were we need to reach deeper into the hierarchy to get the face materials....
  26314. switch ( objectName ) {
  26315. case 'materials':
  26316. if ( ! targetObject.material ) {
  26317. console.error( 'THREE.PropertyBinding: Can not bind to material as node does not have a material.', this );
  26318. return;
  26319. }
  26320. if ( ! targetObject.material.materials ) {
  26321. console.error( 'THREE.PropertyBinding: Can not bind to material.materials as node.material does not have a materials array.', this );
  26322. return;
  26323. }
  26324. targetObject = targetObject.material.materials;
  26325. break;
  26326. case 'bones':
  26327. if ( ! targetObject.skeleton ) {
  26328. console.error( 'THREE.PropertyBinding: Can not bind to bones as node does not have a skeleton.', this );
  26329. return;
  26330. }
  26331. // potential future optimization: skip this if propertyIndex is already an integer
  26332. // and convert the integer string to a true integer.
  26333. targetObject = targetObject.skeleton.bones;
  26334. // support resolving morphTarget names into indices.
  26335. for ( let i = 0; i < targetObject.length; i ++ ) {
  26336. if ( targetObject[ i ].name === objectIndex ) {
  26337. objectIndex = i;
  26338. break;
  26339. }
  26340. }
  26341. break;
  26342. case 'map':
  26343. if ( 'map' in targetObject ) {
  26344. targetObject = targetObject.map;
  26345. break;
  26346. }
  26347. if ( ! targetObject.material ) {
  26348. console.error( 'THREE.PropertyBinding: Can not bind to material as node does not have a material.', this );
  26349. return;
  26350. }
  26351. if ( ! targetObject.material.map ) {
  26352. console.error( 'THREE.PropertyBinding: Can not bind to material.map as node.material does not have a map.', this );
  26353. return;
  26354. }
  26355. targetObject = targetObject.material.map;
  26356. break;
  26357. default:
  26358. if ( targetObject[ objectName ] === undefined ) {
  26359. console.error( 'THREE.PropertyBinding: Can not bind to objectName of node undefined.', this );
  26360. return;
  26361. }
  26362. targetObject = targetObject[ objectName ];
  26363. }
  26364. if ( objectIndex !== undefined ) {
  26365. if ( targetObject[ objectIndex ] === undefined ) {
  26366. console.error( 'THREE.PropertyBinding: Trying to bind to objectIndex of objectName, but is undefined.', this, targetObject );
  26367. return;
  26368. }
  26369. targetObject = targetObject[ objectIndex ];
  26370. }
  26371. }
  26372. // resolve property
  26373. const nodeProperty = targetObject[ propertyName ];
  26374. if ( nodeProperty === undefined ) {
  26375. const nodeName = parsedPath.nodeName;
  26376. console.error( 'THREE.PropertyBinding: Trying to update property for track: ' + nodeName +
  26377. '.' + propertyName + ' but it wasn\'t found.', targetObject );
  26378. return;
  26379. }
  26380. // determine versioning scheme
  26381. let versioning = this.Versioning.None;
  26382. this.targetObject = targetObject;
  26383. if ( targetObject.isMaterial === true ) {
  26384. versioning = this.Versioning.NeedsUpdate;
  26385. } else if ( targetObject.isObject3D === true ) {
  26386. versioning = this.Versioning.MatrixWorldNeedsUpdate;
  26387. }
  26388. // determine how the property gets bound
  26389. let bindingType = this.BindingType.Direct;
  26390. if ( propertyIndex !== undefined ) {
  26391. // access a sub element of the property array (only primitives are supported right now)
  26392. if ( propertyName === 'morphTargetInfluences' ) {
  26393. // potential optimization, skip this if propertyIndex is already an integer, and convert the integer string to a true integer.
  26394. // support resolving morphTarget names into indices.
  26395. if ( ! targetObject.geometry ) {
  26396. console.error( 'THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.', this );
  26397. return;
  26398. }
  26399. if ( ! targetObject.geometry.morphAttributes ) {
  26400. console.error( 'THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.morphAttributes.', this );
  26401. return;
  26402. }
  26403. if ( targetObject.morphTargetDictionary[ propertyIndex ] !== undefined ) {
  26404. propertyIndex = targetObject.morphTargetDictionary[ propertyIndex ];
  26405. }
  26406. }
  26407. bindingType = this.BindingType.ArrayElement;
  26408. this.resolvedProperty = nodeProperty;
  26409. this.propertyIndex = propertyIndex;
  26410. } else if ( nodeProperty.fromArray !== undefined && nodeProperty.toArray !== undefined ) {
  26411. // must use copy for Object3D.Euler/Quaternion
  26412. bindingType = this.BindingType.HasFromToArray;
  26413. this.resolvedProperty = nodeProperty;
  26414. } else if ( Array.isArray( nodeProperty ) ) {
  26415. bindingType = this.BindingType.EntireArray;
  26416. this.resolvedProperty = nodeProperty;
  26417. } else {
  26418. this.propertyName = propertyName;
  26419. }
  26420. // select getter / setter
  26421. this.getValue = this.GetterByBindingType[ bindingType ];
  26422. this.setValue = this.SetterByBindingTypeAndVersioning[ bindingType ][ versioning ];
  26423. }
  26424. unbind() {
  26425. this.node = null;
  26426. // back to the prototype version of getValue / setValue
  26427. // note: avoiding to mutate the shape of 'this' via 'delete'
  26428. this.getValue = this._getValue_unbound;
  26429. this.setValue = this._setValue_unbound;
  26430. }
  26431. }
  26432. PropertyBinding.Composite = Composite;
  26433. PropertyBinding.prototype.BindingType = {
  26434. Direct: 0,
  26435. EntireArray: 1,
  26436. ArrayElement: 2,
  26437. HasFromToArray: 3
  26438. };
  26439. PropertyBinding.prototype.Versioning = {
  26440. None: 0,
  26441. NeedsUpdate: 1,
  26442. MatrixWorldNeedsUpdate: 2
  26443. };
  26444. PropertyBinding.prototype.GetterByBindingType = [
  26445. PropertyBinding.prototype._getValue_direct,
  26446. PropertyBinding.prototype._getValue_array,
  26447. PropertyBinding.prototype._getValue_arrayElement,
  26448. PropertyBinding.prototype._getValue_toArray,
  26449. ];
  26450. PropertyBinding.prototype.SetterByBindingTypeAndVersioning = [
  26451. [
  26452. // Direct
  26453. PropertyBinding.prototype._setValue_direct,
  26454. PropertyBinding.prototype._setValue_direct_setNeedsUpdate,
  26455. PropertyBinding.prototype._setValue_direct_setMatrixWorldNeedsUpdate,
  26456. ], [
  26457. // EntireArray
  26458. PropertyBinding.prototype._setValue_array,
  26459. PropertyBinding.prototype._setValue_array_setNeedsUpdate,
  26460. PropertyBinding.prototype._setValue_array_setMatrixWorldNeedsUpdate,
  26461. ], [
  26462. // ArrayElement
  26463. PropertyBinding.prototype._setValue_arrayElement,
  26464. PropertyBinding.prototype._setValue_arrayElement_setNeedsUpdate,
  26465. PropertyBinding.prototype._setValue_arrayElement_setMatrixWorldNeedsUpdate,
  26466. ], [
  26467. // HasToFromArray
  26468. PropertyBinding.prototype._setValue_fromArray,
  26469. PropertyBinding.prototype._setValue_fromArray_setNeedsUpdate,
  26470. PropertyBinding.prototype._setValue_fromArray_setMatrixWorldNeedsUpdate,
  26471. ]
  26472. ];
  26473. /**
  26474. *
  26475. * A group of objects that receives a shared animation state.
  26476. *
  26477. * Usage:
  26478. *
  26479. * - Add objects you would otherwise pass as 'root' to the
  26480. * constructor or the .clipAction method of AnimationMixer.
  26481. *
  26482. * - Instead pass this object as 'root'.
  26483. *
  26484. * - You can also add and remove objects later when the mixer
  26485. * is running.
  26486. *
  26487. * Note:
  26488. *
  26489. * Objects of this class appear as one object to the mixer,
  26490. * so cache control of the individual objects must be done
  26491. * on the group.
  26492. *
  26493. * Limitation:
  26494. *
  26495. * - The animated properties must be compatible among the
  26496. * all objects in the group.
  26497. *
  26498. * - A single property can either be controlled through a
  26499. * target group or directly, but not both.
  26500. */
  26501. class AnimationObjectGroup {
  26502. constructor() {
  26503. this.isAnimationObjectGroup = true;
  26504. this.uuid = generateUUID();
  26505. // cached objects followed by the active ones
  26506. this._objects = Array.prototype.slice.call( arguments );
  26507. this.nCachedObjects_ = 0; // threshold
  26508. // note: read by PropertyBinding.Composite
  26509. const indices = {};
  26510. this._indicesByUUID = indices; // for bookkeeping
  26511. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  26512. indices[ arguments[ i ].uuid ] = i;
  26513. }
  26514. this._paths = []; // inside: string
  26515. this._parsedPaths = []; // inside: { we don't care, here }
  26516. this._bindings = []; // inside: Array< PropertyBinding >
  26517. this._bindingsIndicesByPath = {}; // inside: indices in these arrays
  26518. const scope = this;
  26519. this.stats = {
  26520. objects: {
  26521. get total() {
  26522. return scope._objects.length;
  26523. },
  26524. get inUse() {
  26525. return this.total - scope.nCachedObjects_;
  26526. }
  26527. },
  26528. get bindingsPerObject() {
  26529. return scope._bindings.length;
  26530. }
  26531. };
  26532. }
  26533. add() {
  26534. const objects = this._objects,
  26535. indicesByUUID = this._indicesByUUID,
  26536. paths = this._paths,
  26537. parsedPaths = this._parsedPaths,
  26538. bindings = this._bindings,
  26539. nBindings = bindings.length;
  26540. let knownObject = undefined,
  26541. nObjects = objects.length,
  26542. nCachedObjects = this.nCachedObjects_;
  26543. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  26544. const object = arguments[ i ],
  26545. uuid = object.uuid;
  26546. let index = indicesByUUID[ uuid ];
  26547. if ( index === undefined ) {
  26548. // unknown object -> add it to the ACTIVE region
  26549. index = nObjects ++;
  26550. indicesByUUID[ uuid ] = index;
  26551. objects.push( object );
  26552. // accounting is done, now do the same for all bindings
  26553. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  26554. bindings[ j ].push( new PropertyBinding( object, paths[ j ], parsedPaths[ j ] ) );
  26555. }
  26556. } else if ( index < nCachedObjects ) {
  26557. knownObject = objects[ index ];
  26558. // move existing object to the ACTIVE region
  26559. const firstActiveIndex = -- nCachedObjects,
  26560. lastCachedObject = objects[ firstActiveIndex ];
  26561. indicesByUUID[ lastCachedObject.uuid ] = index;
  26562. objects[ index ] = lastCachedObject;
  26563. indicesByUUID[ uuid ] = firstActiveIndex;
  26564. objects[ firstActiveIndex ] = object;
  26565. // accounting is done, now do the same for all bindings
  26566. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  26567. const bindingsForPath = bindings[ j ],
  26568. lastCached = bindingsForPath[ firstActiveIndex ];
  26569. let binding = bindingsForPath[ index ];
  26570. bindingsForPath[ index ] = lastCached;
  26571. if ( binding === undefined ) {
  26572. // since we do not bother to create new bindings
  26573. // for objects that are cached, the binding may
  26574. // or may not exist
  26575. binding = new PropertyBinding( object, paths[ j ], parsedPaths[ j ] );
  26576. }
  26577. bindingsForPath[ firstActiveIndex ] = binding;
  26578. }
  26579. } else if ( objects[ index ] !== knownObject ) {
  26580. console.error( 'THREE.AnimationObjectGroup: Different objects with the same UUID ' +
  26581. 'detected. Clean the caches or recreate your infrastructure when reloading scenes.' );
  26582. } // else the object is already where we want it to be
  26583. } // for arguments
  26584. this.nCachedObjects_ = nCachedObjects;
  26585. }
  26586. remove() {
  26587. const objects = this._objects,
  26588. indicesByUUID = this._indicesByUUID,
  26589. bindings = this._bindings,
  26590. nBindings = bindings.length;
  26591. let nCachedObjects = this.nCachedObjects_;
  26592. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  26593. const object = arguments[ i ],
  26594. uuid = object.uuid,
  26595. index = indicesByUUID[ uuid ];
  26596. if ( index !== undefined && index >= nCachedObjects ) {
  26597. // move existing object into the CACHED region
  26598. const lastCachedIndex = nCachedObjects ++,
  26599. firstActiveObject = objects[ lastCachedIndex ];
  26600. indicesByUUID[ firstActiveObject.uuid ] = index;
  26601. objects[ index ] = firstActiveObject;
  26602. indicesByUUID[ uuid ] = lastCachedIndex;
  26603. objects[ lastCachedIndex ] = object;
  26604. // accounting is done, now do the same for all bindings
  26605. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  26606. const bindingsForPath = bindings[ j ],
  26607. firstActive = bindingsForPath[ lastCachedIndex ],
  26608. binding = bindingsForPath[ index ];
  26609. bindingsForPath[ index ] = firstActive;
  26610. bindingsForPath[ lastCachedIndex ] = binding;
  26611. }
  26612. }
  26613. } // for arguments
  26614. this.nCachedObjects_ = nCachedObjects;
  26615. }
  26616. // remove & forget
  26617. uncache() {
  26618. const objects = this._objects,
  26619. indicesByUUID = this._indicesByUUID,
  26620. bindings = this._bindings,
  26621. nBindings = bindings.length;
  26622. let nCachedObjects = this.nCachedObjects_,
  26623. nObjects = objects.length;
  26624. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  26625. const object = arguments[ i ],
  26626. uuid = object.uuid,
  26627. index = indicesByUUID[ uuid ];
  26628. if ( index !== undefined ) {
  26629. delete indicesByUUID[ uuid ];
  26630. if ( index < nCachedObjects ) {
  26631. // object is cached, shrink the CACHED region
  26632. const firstActiveIndex = -- nCachedObjects,
  26633. lastCachedObject = objects[ firstActiveIndex ],
  26634. lastIndex = -- nObjects,
  26635. lastObject = objects[ lastIndex ];
  26636. // last cached object takes this object's place
  26637. indicesByUUID[ lastCachedObject.uuid ] = index;
  26638. objects[ index ] = lastCachedObject;
  26639. // last object goes to the activated slot and pop
  26640. indicesByUUID[ lastObject.uuid ] = firstActiveIndex;
  26641. objects[ firstActiveIndex ] = lastObject;
  26642. objects.pop();
  26643. // accounting is done, now do the same for all bindings
  26644. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  26645. const bindingsForPath = bindings[ j ],
  26646. lastCached = bindingsForPath[ firstActiveIndex ],
  26647. last = bindingsForPath[ lastIndex ];
  26648. bindingsForPath[ index ] = lastCached;
  26649. bindingsForPath[ firstActiveIndex ] = last;
  26650. bindingsForPath.pop();
  26651. }
  26652. } else {
  26653. // object is active, just swap with the last and pop
  26654. const lastIndex = -- nObjects,
  26655. lastObject = objects[ lastIndex ];
  26656. if ( lastIndex > 0 ) {
  26657. indicesByUUID[ lastObject.uuid ] = index;
  26658. }
  26659. objects[ index ] = lastObject;
  26660. objects.pop();
  26661. // accounting is done, now do the same for all bindings
  26662. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  26663. const bindingsForPath = bindings[ j ];
  26664. bindingsForPath[ index ] = bindingsForPath[ lastIndex ];
  26665. bindingsForPath.pop();
  26666. }
  26667. } // cached or active
  26668. } // if object is known
  26669. } // for arguments
  26670. this.nCachedObjects_ = nCachedObjects;
  26671. }
  26672. // Internal interface used by befriended PropertyBinding.Composite:
  26673. subscribe_( path, parsedPath ) {
  26674. // returns an array of bindings for the given path that is changed
  26675. // according to the contained objects in the group
  26676. const indicesByPath = this._bindingsIndicesByPath;
  26677. let index = indicesByPath[ path ];
  26678. const bindings = this._bindings;
  26679. if ( index !== undefined ) return bindings[ index ];
  26680. const paths = this._paths,
  26681. parsedPaths = this._parsedPaths,
  26682. objects = this._objects,
  26683. nObjects = objects.length,
  26684. nCachedObjects = this.nCachedObjects_,
  26685. bindingsForPath = new Array( nObjects );
  26686. index = bindings.length;
  26687. indicesByPath[ path ] = index;
  26688. paths.push( path );
  26689. parsedPaths.push( parsedPath );
  26690. bindings.push( bindingsForPath );
  26691. for ( let i = nCachedObjects, n = objects.length; i !== n; ++ i ) {
  26692. const object = objects[ i ];
  26693. bindingsForPath[ i ] = new PropertyBinding( object, path, parsedPath );
  26694. }
  26695. return bindingsForPath;
  26696. }
  26697. unsubscribe_( path ) {
  26698. // tells the group to forget about a property path and no longer
  26699. // update the array previously obtained with 'subscribe_'
  26700. const indicesByPath = this._bindingsIndicesByPath,
  26701. index = indicesByPath[ path ];
  26702. if ( index !== undefined ) {
  26703. const paths = this._paths,
  26704. parsedPaths = this._parsedPaths,
  26705. bindings = this._bindings,
  26706. lastBindingsIndex = bindings.length - 1,
  26707. lastBindings = bindings[ lastBindingsIndex ],
  26708. lastBindingsPath = path[ lastBindingsIndex ];
  26709. indicesByPath[ lastBindingsPath ] = index;
  26710. bindings[ index ] = lastBindings;
  26711. bindings.pop();
  26712. parsedPaths[ index ] = parsedPaths[ lastBindingsIndex ];
  26713. parsedPaths.pop();
  26714. paths[ index ] = paths[ lastBindingsIndex ];
  26715. paths.pop();
  26716. }
  26717. }
  26718. }
  26719. class AnimationAction {
  26720. constructor( mixer, clip, localRoot = null, blendMode = clip.blendMode ) {
  26721. this._mixer = mixer;
  26722. this._clip = clip;
  26723. this._localRoot = localRoot;
  26724. this.blendMode = blendMode;
  26725. const tracks = clip.tracks,
  26726. nTracks = tracks.length,
  26727. interpolants = new Array( nTracks );
  26728. const interpolantSettings = {
  26729. endingStart: ZeroCurvatureEnding,
  26730. endingEnd: ZeroCurvatureEnding
  26731. };
  26732. for ( let i = 0; i !== nTracks; ++ i ) {
  26733. const interpolant = tracks[ i ].createInterpolant( null );
  26734. interpolants[ i ] = interpolant;
  26735. interpolant.settings = interpolantSettings;
  26736. }
  26737. this._interpolantSettings = interpolantSettings;
  26738. this._interpolants = interpolants; // bound by the mixer
  26739. // inside: PropertyMixer (managed by the mixer)
  26740. this._propertyBindings = new Array( nTracks );
  26741. this._cacheIndex = null; // for the memory manager
  26742. this._byClipCacheIndex = null; // for the memory manager
  26743. this._timeScaleInterpolant = null;
  26744. this._weightInterpolant = null;
  26745. this.loop = LoopRepeat;
  26746. this._loopCount = -1;
  26747. // global mixer time when the action is to be started
  26748. // it's set back to 'null' upon start of the action
  26749. this._startTime = null;
  26750. // scaled local time of the action
  26751. // gets clamped or wrapped to 0..clip.duration according to loop
  26752. this.time = 0;
  26753. this.timeScale = 1;
  26754. this._effectiveTimeScale = 1;
  26755. this.weight = 1;
  26756. this._effectiveWeight = 1;
  26757. this.repetitions = Infinity; // no. of repetitions when looping
  26758. this.paused = false; // true -> zero effective time scale
  26759. this.enabled = true; // false -> zero effective weight
  26760. this.clampWhenFinished = false;// keep feeding the last frame?
  26761. this.zeroSlopeAtStart = true;// for smooth interpolation w/o separate
  26762. this.zeroSlopeAtEnd = true;// clips for start, loop and end
  26763. }
  26764. // State & Scheduling
  26765. play() {
  26766. this._mixer._activateAction( this );
  26767. return this;
  26768. }
  26769. stop() {
  26770. this._mixer._deactivateAction( this );
  26771. return this.reset();
  26772. }
  26773. reset() {
  26774. this.paused = false;
  26775. this.enabled = true;
  26776. this.time = 0; // restart clip
  26777. this._loopCount = -1;// forget previous loops
  26778. this._startTime = null;// forget scheduling
  26779. return this.stopFading().stopWarping();
  26780. }
  26781. isRunning() {
  26782. return this.enabled && ! this.paused && this.timeScale !== 0 &&
  26783. this._startTime === null && this._mixer._isActiveAction( this );
  26784. }
  26785. // return true when play has been called
  26786. isScheduled() {
  26787. return this._mixer._isActiveAction( this );
  26788. }
  26789. startAt( time ) {
  26790. this._startTime = time;
  26791. return this;
  26792. }
  26793. setLoop( mode, repetitions ) {
  26794. this.loop = mode;
  26795. this.repetitions = repetitions;
  26796. return this;
  26797. }
  26798. // Weight
  26799. // set the weight stopping any scheduled fading
  26800. // although .enabled = false yields an effective weight of zero, this
  26801. // method does *not* change .enabled, because it would be confusing
  26802. setEffectiveWeight( weight ) {
  26803. this.weight = weight;
  26804. // note: same logic as when updated at runtime
  26805. this._effectiveWeight = this.enabled ? weight : 0;
  26806. return this.stopFading();
  26807. }
  26808. // return the weight considering fading and .enabled
  26809. getEffectiveWeight() {
  26810. return this._effectiveWeight;
  26811. }
  26812. fadeIn( duration ) {
  26813. return this._scheduleFading( duration, 0, 1 );
  26814. }
  26815. fadeOut( duration ) {
  26816. return this._scheduleFading( duration, 1, 0 );
  26817. }
  26818. crossFadeFrom( fadeOutAction, duration, warp ) {
  26819. fadeOutAction.fadeOut( duration );
  26820. this.fadeIn( duration );
  26821. if ( warp ) {
  26822. const fadeInDuration = this._clip.duration,
  26823. fadeOutDuration = fadeOutAction._clip.duration,
  26824. startEndRatio = fadeOutDuration / fadeInDuration,
  26825. endStartRatio = fadeInDuration / fadeOutDuration;
  26826. fadeOutAction.warp( 1.0, startEndRatio, duration );
  26827. this.warp( endStartRatio, 1.0, duration );
  26828. }
  26829. return this;
  26830. }
  26831. crossFadeTo( fadeInAction, duration, warp ) {
  26832. return fadeInAction.crossFadeFrom( this, duration, warp );
  26833. }
  26834. stopFading() {
  26835. const weightInterpolant = this._weightInterpolant;
  26836. if ( weightInterpolant !== null ) {
  26837. this._weightInterpolant = null;
  26838. this._mixer._takeBackControlInterpolant( weightInterpolant );
  26839. }
  26840. return this;
  26841. }
  26842. // Time Scale Control
  26843. // set the time scale stopping any scheduled warping
  26844. // although .paused = true yields an effective time scale of zero, this
  26845. // method does *not* change .paused, because it would be confusing
  26846. setEffectiveTimeScale( timeScale ) {
  26847. this.timeScale = timeScale;
  26848. this._effectiveTimeScale = this.paused ? 0 : timeScale;
  26849. return this.stopWarping();
  26850. }
  26851. // return the time scale considering warping and .paused
  26852. getEffectiveTimeScale() {
  26853. return this._effectiveTimeScale;
  26854. }
  26855. setDuration( duration ) {
  26856. this.timeScale = this._clip.duration / duration;
  26857. return this.stopWarping();
  26858. }
  26859. syncWith( action ) {
  26860. this.time = action.time;
  26861. this.timeScale = action.timeScale;
  26862. return this.stopWarping();
  26863. }
  26864. halt( duration ) {
  26865. return this.warp( this._effectiveTimeScale, 0, duration );
  26866. }
  26867. warp( startTimeScale, endTimeScale, duration ) {
  26868. const mixer = this._mixer,
  26869. now = mixer.time,
  26870. timeScale = this.timeScale;
  26871. let interpolant = this._timeScaleInterpolant;
  26872. if ( interpolant === null ) {
  26873. interpolant = mixer._lendControlInterpolant();
  26874. this._timeScaleInterpolant = interpolant;
  26875. }
  26876. const times = interpolant.parameterPositions,
  26877. values = interpolant.sampleValues;
  26878. times[ 0 ] = now;
  26879. times[ 1 ] = now + duration;
  26880. values[ 0 ] = startTimeScale / timeScale;
  26881. values[ 1 ] = endTimeScale / timeScale;
  26882. return this;
  26883. }
  26884. stopWarping() {
  26885. const timeScaleInterpolant = this._timeScaleInterpolant;
  26886. if ( timeScaleInterpolant !== null ) {
  26887. this._timeScaleInterpolant = null;
  26888. this._mixer._takeBackControlInterpolant( timeScaleInterpolant );
  26889. }
  26890. return this;
  26891. }
  26892. // Object Accessors
  26893. getMixer() {
  26894. return this._mixer;
  26895. }
  26896. getClip() {
  26897. return this._clip;
  26898. }
  26899. getRoot() {
  26900. return this._localRoot || this._mixer._root;
  26901. }
  26902. // Interna
  26903. _update( time, deltaTime, timeDirection, accuIndex ) {
  26904. // called by the mixer
  26905. if ( ! this.enabled ) {
  26906. // call ._updateWeight() to update ._effectiveWeight
  26907. this._updateWeight( time );
  26908. return;
  26909. }
  26910. const startTime = this._startTime;
  26911. if ( startTime !== null ) {
  26912. // check for scheduled start of action
  26913. const timeRunning = ( time - startTime ) * timeDirection;
  26914. if ( timeRunning < 0 || timeDirection === 0 ) {
  26915. deltaTime = 0;
  26916. } else {
  26917. this._startTime = null; // unschedule
  26918. deltaTime = timeDirection * timeRunning;
  26919. }
  26920. }
  26921. // apply time scale and advance time
  26922. deltaTime *= this._updateTimeScale( time );
  26923. const clipTime = this._updateTime( deltaTime );
  26924. // note: _updateTime may disable the action resulting in
  26925. // an effective weight of 0
  26926. const weight = this._updateWeight( time );
  26927. if ( weight > 0 ) {
  26928. const interpolants = this._interpolants;
  26929. const propertyMixers = this._propertyBindings;
  26930. switch ( this.blendMode ) {
  26931. case AdditiveAnimationBlendMode:
  26932. for ( let j = 0, m = interpolants.length; j !== m; ++ j ) {
  26933. interpolants[ j ].evaluate( clipTime );
  26934. propertyMixers[ j ].accumulateAdditive( weight );
  26935. }
  26936. break;
  26937. case NormalAnimationBlendMode:
  26938. default:
  26939. for ( let j = 0, m = interpolants.length; j !== m; ++ j ) {
  26940. interpolants[ j ].evaluate( clipTime );
  26941. propertyMixers[ j ].accumulate( accuIndex, weight );
  26942. }
  26943. }
  26944. }
  26945. }
  26946. _updateWeight( time ) {
  26947. let weight = 0;
  26948. if ( this.enabled ) {
  26949. weight = this.weight;
  26950. const interpolant = this._weightInterpolant;
  26951. if ( interpolant !== null ) {
  26952. const interpolantValue = interpolant.evaluate( time )[ 0 ];
  26953. weight *= interpolantValue;
  26954. if ( time > interpolant.parameterPositions[ 1 ] ) {
  26955. this.stopFading();
  26956. if ( interpolantValue === 0 ) {
  26957. // faded out, disable
  26958. this.enabled = false;
  26959. }
  26960. }
  26961. }
  26962. }
  26963. this._effectiveWeight = weight;
  26964. return weight;
  26965. }
  26966. _updateTimeScale( time ) {
  26967. let timeScale = 0;
  26968. if ( ! this.paused ) {
  26969. timeScale = this.timeScale;
  26970. const interpolant = this._timeScaleInterpolant;
  26971. if ( interpolant !== null ) {
  26972. const interpolantValue = interpolant.evaluate( time )[ 0 ];
  26973. timeScale *= interpolantValue;
  26974. if ( time > interpolant.parameterPositions[ 1 ] ) {
  26975. this.stopWarping();
  26976. if ( timeScale === 0 ) {
  26977. // motion has halted, pause
  26978. this.paused = true;
  26979. } else {
  26980. // warp done - apply final time scale
  26981. this.timeScale = timeScale;
  26982. }
  26983. }
  26984. }
  26985. }
  26986. this._effectiveTimeScale = timeScale;
  26987. return timeScale;
  26988. }
  26989. _updateTime( deltaTime ) {
  26990. const duration = this._clip.duration;
  26991. const loop = this.loop;
  26992. let time = this.time + deltaTime;
  26993. let loopCount = this._loopCount;
  26994. const pingPong = ( loop === LoopPingPong );
  26995. if ( deltaTime === 0 ) {
  26996. if ( loopCount === -1 ) return time;
  26997. return ( pingPong && ( loopCount & 1 ) === 1 ) ? duration - time : time;
  26998. }
  26999. if ( loop === LoopOnce ) {
  27000. if ( loopCount === -1 ) {
  27001. // just started
  27002. this._loopCount = 0;
  27003. this._setEndings( true, true, false );
  27004. }
  27005. handle_stop: {
  27006. if ( time >= duration ) {
  27007. time = duration;
  27008. } else if ( time < 0 ) {
  27009. time = 0;
  27010. } else {
  27011. this.time = time;
  27012. break handle_stop;
  27013. }
  27014. if ( this.clampWhenFinished ) this.paused = true;
  27015. else this.enabled = false;
  27016. this.time = time;
  27017. this._mixer.dispatchEvent( {
  27018. type: 'finished', action: this,
  27019. direction: deltaTime < 0 ? -1 : 1
  27020. } );
  27021. }
  27022. } else { // repetitive Repeat or PingPong
  27023. if ( loopCount === -1 ) {
  27024. // just started
  27025. if ( deltaTime >= 0 ) {
  27026. loopCount = 0;
  27027. this._setEndings( true, this.repetitions === 0, pingPong );
  27028. } else {
  27029. // when looping in reverse direction, the initial
  27030. // transition through zero counts as a repetition,
  27031. // so leave loopCount at -1
  27032. this._setEndings( this.repetitions === 0, true, pingPong );
  27033. }
  27034. }
  27035. if ( time >= duration || time < 0 ) {
  27036. // wrap around
  27037. const loopDelta = Math.floor( time / duration ); // signed
  27038. time -= duration * loopDelta;
  27039. loopCount += Math.abs( loopDelta );
  27040. const pending = this.repetitions - loopCount;
  27041. if ( pending <= 0 ) {
  27042. // have to stop (switch state, clamp time, fire event)
  27043. if ( this.clampWhenFinished ) this.paused = true;
  27044. else this.enabled = false;
  27045. time = deltaTime > 0 ? duration : 0;
  27046. this.time = time;
  27047. this._mixer.dispatchEvent( {
  27048. type: 'finished', action: this,
  27049. direction: deltaTime > 0 ? 1 : -1
  27050. } );
  27051. } else {
  27052. // keep running
  27053. if ( pending === 1 ) {
  27054. // entering the last round
  27055. const atStart = deltaTime < 0;
  27056. this._setEndings( atStart, ! atStart, pingPong );
  27057. } else {
  27058. this._setEndings( false, false, pingPong );
  27059. }
  27060. this._loopCount = loopCount;
  27061. this.time = time;
  27062. this._mixer.dispatchEvent( {
  27063. type: 'loop', action: this, loopDelta: loopDelta
  27064. } );
  27065. }
  27066. } else {
  27067. this.time = time;
  27068. }
  27069. if ( pingPong && ( loopCount & 1 ) === 1 ) {
  27070. // invert time for the "pong round"
  27071. return duration - time;
  27072. }
  27073. }
  27074. return time;
  27075. }
  27076. _setEndings( atStart, atEnd, pingPong ) {
  27077. const settings = this._interpolantSettings;
  27078. if ( pingPong ) {
  27079. settings.endingStart = ZeroSlopeEnding;
  27080. settings.endingEnd = ZeroSlopeEnding;
  27081. } else {
  27082. // assuming for LoopOnce atStart == atEnd == true
  27083. if ( atStart ) {
  27084. settings.endingStart = this.zeroSlopeAtStart ? ZeroSlopeEnding : ZeroCurvatureEnding;
  27085. } else {
  27086. settings.endingStart = WrapAroundEnding;
  27087. }
  27088. if ( atEnd ) {
  27089. settings.endingEnd = this.zeroSlopeAtEnd ? ZeroSlopeEnding : ZeroCurvatureEnding;
  27090. } else {
  27091. settings.endingEnd = WrapAroundEnding;
  27092. }
  27093. }
  27094. }
  27095. _scheduleFading( duration, weightNow, weightThen ) {
  27096. const mixer = this._mixer, now = mixer.time;
  27097. let interpolant = this._weightInterpolant;
  27098. if ( interpolant === null ) {
  27099. interpolant = mixer._lendControlInterpolant();
  27100. this._weightInterpolant = interpolant;
  27101. }
  27102. const times = interpolant.parameterPositions,
  27103. values = interpolant.sampleValues;
  27104. times[ 0 ] = now;
  27105. values[ 0 ] = weightNow;
  27106. times[ 1 ] = now + duration;
  27107. values[ 1 ] = weightThen;
  27108. return this;
  27109. }
  27110. }
  27111. const _controlInterpolantsResultBuffer = new Float32Array( 1 );
  27112. class AnimationMixer extends EventDispatcher {
  27113. constructor( root ) {
  27114. super();
  27115. this._root = root;
  27116. this._initMemoryManager();
  27117. this._accuIndex = 0;
  27118. this.time = 0;
  27119. this.timeScale = 1.0;
  27120. }
  27121. _bindAction( action, prototypeAction ) {
  27122. const root = action._localRoot || this._root,
  27123. tracks = action._clip.tracks,
  27124. nTracks = tracks.length,
  27125. bindings = action._propertyBindings,
  27126. interpolants = action._interpolants,
  27127. rootUuid = root.uuid,
  27128. bindingsByRoot = this._bindingsByRootAndName;
  27129. let bindingsByName = bindingsByRoot[ rootUuid ];
  27130. if ( bindingsByName === undefined ) {
  27131. bindingsByName = {};
  27132. bindingsByRoot[ rootUuid ] = bindingsByName;
  27133. }
  27134. for ( let i = 0; i !== nTracks; ++ i ) {
  27135. const track = tracks[ i ],
  27136. trackName = track.name;
  27137. let binding = bindingsByName[ trackName ];
  27138. if ( binding !== undefined ) {
  27139. ++ binding.referenceCount;
  27140. bindings[ i ] = binding;
  27141. } else {
  27142. binding = bindings[ i ];
  27143. if ( binding !== undefined ) {
  27144. // existing binding, make sure the cache knows
  27145. if ( binding._cacheIndex === null ) {
  27146. ++ binding.referenceCount;
  27147. this._addInactiveBinding( binding, rootUuid, trackName );
  27148. }
  27149. continue;
  27150. }
  27151. const path = prototypeAction && prototypeAction.
  27152. _propertyBindings[ i ].binding.parsedPath;
  27153. binding = new PropertyMixer(
  27154. PropertyBinding.create( root, trackName, path ),
  27155. track.ValueTypeName, track.getValueSize() );
  27156. ++ binding.referenceCount;
  27157. this._addInactiveBinding( binding, rootUuid, trackName );
  27158. bindings[ i ] = binding;
  27159. }
  27160. interpolants[ i ].resultBuffer = binding.buffer;
  27161. }
  27162. }
  27163. _activateAction( action ) {
  27164. if ( ! this._isActiveAction( action ) ) {
  27165. if ( action._cacheIndex === null ) {
  27166. // this action has been forgotten by the cache, but the user
  27167. // appears to be still using it -> rebind
  27168. const rootUuid = ( action._localRoot || this._root ).uuid,
  27169. clipUuid = action._clip.uuid,
  27170. actionsForClip = this._actionsByClip[ clipUuid ];
  27171. this._bindAction( action,
  27172. actionsForClip && actionsForClip.knownActions[ 0 ] );
  27173. this._addInactiveAction( action, clipUuid, rootUuid );
  27174. }
  27175. const bindings = action._propertyBindings;
  27176. // increment reference counts / sort out state
  27177. for ( let i = 0, n = bindings.length; i !== n; ++ i ) {
  27178. const binding = bindings[ i ];
  27179. if ( binding.useCount ++ === 0 ) {
  27180. this._lendBinding( binding );
  27181. binding.saveOriginalState();
  27182. }
  27183. }
  27184. this._lendAction( action );
  27185. }
  27186. }
  27187. _deactivateAction( action ) {
  27188. if ( this._isActiveAction( action ) ) {
  27189. const bindings = action._propertyBindings;
  27190. // decrement reference counts / sort out state
  27191. for ( let i = 0, n = bindings.length; i !== n; ++ i ) {
  27192. const binding = bindings[ i ];
  27193. if ( -- binding.useCount === 0 ) {
  27194. binding.restoreOriginalState();
  27195. this._takeBackBinding( binding );
  27196. }
  27197. }
  27198. this._takeBackAction( action );
  27199. }
  27200. }
  27201. // Memory manager
  27202. _initMemoryManager() {
  27203. this._actions = []; // 'nActiveActions' followed by inactive ones
  27204. this._nActiveActions = 0;
  27205. this._actionsByClip = {};
  27206. // inside:
  27207. // {
  27208. // knownActions: Array< AnimationAction > - used as prototypes
  27209. // actionByRoot: AnimationAction - lookup
  27210. // }
  27211. this._bindings = []; // 'nActiveBindings' followed by inactive ones
  27212. this._nActiveBindings = 0;
  27213. this._bindingsByRootAndName = {}; // inside: Map< name, PropertyMixer >
  27214. this._controlInterpolants = []; // same game as above
  27215. this._nActiveControlInterpolants = 0;
  27216. const scope = this;
  27217. this.stats = {
  27218. actions: {
  27219. get total() {
  27220. return scope._actions.length;
  27221. },
  27222. get inUse() {
  27223. return scope._nActiveActions;
  27224. }
  27225. },
  27226. bindings: {
  27227. get total() {
  27228. return scope._bindings.length;
  27229. },
  27230. get inUse() {
  27231. return scope._nActiveBindings;
  27232. }
  27233. },
  27234. controlInterpolants: {
  27235. get total() {
  27236. return scope._controlInterpolants.length;
  27237. },
  27238. get inUse() {
  27239. return scope._nActiveControlInterpolants;
  27240. }
  27241. }
  27242. };
  27243. }
  27244. // Memory management for AnimationAction objects
  27245. _isActiveAction( action ) {
  27246. const index = action._cacheIndex;
  27247. return index !== null && index < this._nActiveActions;
  27248. }
  27249. _addInactiveAction( action, clipUuid, rootUuid ) {
  27250. const actions = this._actions,
  27251. actionsByClip = this._actionsByClip;
  27252. let actionsForClip = actionsByClip[ clipUuid ];
  27253. if ( actionsForClip === undefined ) {
  27254. actionsForClip = {
  27255. knownActions: [ action ],
  27256. actionByRoot: {}
  27257. };
  27258. action._byClipCacheIndex = 0;
  27259. actionsByClip[ clipUuid ] = actionsForClip;
  27260. } else {
  27261. const knownActions = actionsForClip.knownActions;
  27262. action._byClipCacheIndex = knownActions.length;
  27263. knownActions.push( action );
  27264. }
  27265. action._cacheIndex = actions.length;
  27266. actions.push( action );
  27267. actionsForClip.actionByRoot[ rootUuid ] = action;
  27268. }
  27269. _removeInactiveAction( action ) {
  27270. const actions = this._actions,
  27271. lastInactiveAction = actions[ actions.length - 1 ],
  27272. cacheIndex = action._cacheIndex;
  27273. lastInactiveAction._cacheIndex = cacheIndex;
  27274. actions[ cacheIndex ] = lastInactiveAction;
  27275. actions.pop();
  27276. action._cacheIndex = null;
  27277. const clipUuid = action._clip.uuid,
  27278. actionsByClip = this._actionsByClip,
  27279. actionsForClip = actionsByClip[ clipUuid ],
  27280. knownActionsForClip = actionsForClip.knownActions,
  27281. lastKnownAction =
  27282. knownActionsForClip[ knownActionsForClip.length - 1 ],
  27283. byClipCacheIndex = action._byClipCacheIndex;
  27284. lastKnownAction._byClipCacheIndex = byClipCacheIndex;
  27285. knownActionsForClip[ byClipCacheIndex ] = lastKnownAction;
  27286. knownActionsForClip.pop();
  27287. action._byClipCacheIndex = null;
  27288. const actionByRoot = actionsForClip.actionByRoot,
  27289. rootUuid = ( action._localRoot || this._root ).uuid;
  27290. delete actionByRoot[ rootUuid ];
  27291. if ( knownActionsForClip.length === 0 ) {
  27292. delete actionsByClip[ clipUuid ];
  27293. }
  27294. this._removeInactiveBindingsForAction( action );
  27295. }
  27296. _removeInactiveBindingsForAction( action ) {
  27297. const bindings = action._propertyBindings;
  27298. for ( let i = 0, n = bindings.length; i !== n; ++ i ) {
  27299. const binding = bindings[ i ];
  27300. if ( -- binding.referenceCount === 0 ) {
  27301. this._removeInactiveBinding( binding );
  27302. }
  27303. }
  27304. }
  27305. _lendAction( action ) {
  27306. // [ active actions | inactive actions ]
  27307. // [ active actions >| inactive actions ]
  27308. // s a
  27309. // <-swap->
  27310. // a s
  27311. const actions = this._actions,
  27312. prevIndex = action._cacheIndex,
  27313. lastActiveIndex = this._nActiveActions ++,
  27314. firstInactiveAction = actions[ lastActiveIndex ];
  27315. action._cacheIndex = lastActiveIndex;
  27316. actions[ lastActiveIndex ] = action;
  27317. firstInactiveAction._cacheIndex = prevIndex;
  27318. actions[ prevIndex ] = firstInactiveAction;
  27319. }
  27320. _takeBackAction( action ) {
  27321. // [ active actions | inactive actions ]
  27322. // [ active actions |< inactive actions ]
  27323. // a s
  27324. // <-swap->
  27325. // s a
  27326. const actions = this._actions,
  27327. prevIndex = action._cacheIndex,
  27328. firstInactiveIndex = -- this._nActiveActions,
  27329. lastActiveAction = actions[ firstInactiveIndex ];
  27330. action._cacheIndex = firstInactiveIndex;
  27331. actions[ firstInactiveIndex ] = action;
  27332. lastActiveAction._cacheIndex = prevIndex;
  27333. actions[ prevIndex ] = lastActiveAction;
  27334. }
  27335. // Memory management for PropertyMixer objects
  27336. _addInactiveBinding( binding, rootUuid, trackName ) {
  27337. const bindingsByRoot = this._bindingsByRootAndName,
  27338. bindings = this._bindings;
  27339. let bindingByName = bindingsByRoot[ rootUuid ];
  27340. if ( bindingByName === undefined ) {
  27341. bindingByName = {};
  27342. bindingsByRoot[ rootUuid ] = bindingByName;
  27343. }
  27344. bindingByName[ trackName ] = binding;
  27345. binding._cacheIndex = bindings.length;
  27346. bindings.push( binding );
  27347. }
  27348. _removeInactiveBinding( binding ) {
  27349. const bindings = this._bindings,
  27350. propBinding = binding.binding,
  27351. rootUuid = propBinding.rootNode.uuid,
  27352. trackName = propBinding.path,
  27353. bindingsByRoot = this._bindingsByRootAndName,
  27354. bindingByName = bindingsByRoot[ rootUuid ],
  27355. lastInactiveBinding = bindings[ bindings.length - 1 ],
  27356. cacheIndex = binding._cacheIndex;
  27357. lastInactiveBinding._cacheIndex = cacheIndex;
  27358. bindings[ cacheIndex ] = lastInactiveBinding;
  27359. bindings.pop();
  27360. delete bindingByName[ trackName ];
  27361. if ( Object.keys( bindingByName ).length === 0 ) {
  27362. delete bindingsByRoot[ rootUuid ];
  27363. }
  27364. }
  27365. _lendBinding( binding ) {
  27366. const bindings = this._bindings,
  27367. prevIndex = binding._cacheIndex,
  27368. lastActiveIndex = this._nActiveBindings ++,
  27369. firstInactiveBinding = bindings[ lastActiveIndex ];
  27370. binding._cacheIndex = lastActiveIndex;
  27371. bindings[ lastActiveIndex ] = binding;
  27372. firstInactiveBinding._cacheIndex = prevIndex;
  27373. bindings[ prevIndex ] = firstInactiveBinding;
  27374. }
  27375. _takeBackBinding( binding ) {
  27376. const bindings = this._bindings,
  27377. prevIndex = binding._cacheIndex,
  27378. firstInactiveIndex = -- this._nActiveBindings,
  27379. lastActiveBinding = bindings[ firstInactiveIndex ];
  27380. binding._cacheIndex = firstInactiveIndex;
  27381. bindings[ firstInactiveIndex ] = binding;
  27382. lastActiveBinding._cacheIndex = prevIndex;
  27383. bindings[ prevIndex ] = lastActiveBinding;
  27384. }
  27385. // Memory management of Interpolants for weight and time scale
  27386. _lendControlInterpolant() {
  27387. const interpolants = this._controlInterpolants,
  27388. lastActiveIndex = this._nActiveControlInterpolants ++;
  27389. let interpolant = interpolants[ lastActiveIndex ];
  27390. if ( interpolant === undefined ) {
  27391. interpolant = new LinearInterpolant(
  27392. new Float32Array( 2 ), new Float32Array( 2 ),
  27393. 1, _controlInterpolantsResultBuffer );
  27394. interpolant.__cacheIndex = lastActiveIndex;
  27395. interpolants[ lastActiveIndex ] = interpolant;
  27396. }
  27397. return interpolant;
  27398. }
  27399. _takeBackControlInterpolant( interpolant ) {
  27400. const interpolants = this._controlInterpolants,
  27401. prevIndex = interpolant.__cacheIndex,
  27402. firstInactiveIndex = -- this._nActiveControlInterpolants,
  27403. lastActiveInterpolant = interpolants[ firstInactiveIndex ];
  27404. interpolant.__cacheIndex = firstInactiveIndex;
  27405. interpolants[ firstInactiveIndex ] = interpolant;
  27406. lastActiveInterpolant.__cacheIndex = prevIndex;
  27407. interpolants[ prevIndex ] = lastActiveInterpolant;
  27408. }
  27409. // return an action for a clip optionally using a custom root target
  27410. // object (this method allocates a lot of dynamic memory in case a
  27411. // previously unknown clip/root combination is specified)
  27412. clipAction( clip, optionalRoot, blendMode ) {
  27413. const root = optionalRoot || this._root,
  27414. rootUuid = root.uuid;
  27415. let clipObject = typeof clip === 'string' ? AnimationClip.findByName( root, clip ) : clip;
  27416. const clipUuid = clipObject !== null ? clipObject.uuid : clip;
  27417. const actionsForClip = this._actionsByClip[ clipUuid ];
  27418. let prototypeAction = null;
  27419. if ( blendMode === undefined ) {
  27420. if ( clipObject !== null ) {
  27421. blendMode = clipObject.blendMode;
  27422. } else {
  27423. blendMode = NormalAnimationBlendMode;
  27424. }
  27425. }
  27426. if ( actionsForClip !== undefined ) {
  27427. const existingAction = actionsForClip.actionByRoot[ rootUuid ];
  27428. if ( existingAction !== undefined && existingAction.blendMode === blendMode ) {
  27429. return existingAction;
  27430. }
  27431. // we know the clip, so we don't have to parse all
  27432. // the bindings again but can just copy
  27433. prototypeAction = actionsForClip.knownActions[ 0 ];
  27434. // also, take the clip from the prototype action
  27435. if ( clipObject === null )
  27436. clipObject = prototypeAction._clip;
  27437. }
  27438. // clip must be known when specified via string
  27439. if ( clipObject === null ) return null;
  27440. // allocate all resources required to run it
  27441. const newAction = new AnimationAction( this, clipObject, optionalRoot, blendMode );
  27442. this._bindAction( newAction, prototypeAction );
  27443. // and make the action known to the memory manager
  27444. this._addInactiveAction( newAction, clipUuid, rootUuid );
  27445. return newAction;
  27446. }
  27447. // get an existing action
  27448. existingAction( clip, optionalRoot ) {
  27449. const root = optionalRoot || this._root,
  27450. rootUuid = root.uuid,
  27451. clipObject = typeof clip === 'string' ?
  27452. AnimationClip.findByName( root, clip ) : clip,
  27453. clipUuid = clipObject ? clipObject.uuid : clip,
  27454. actionsForClip = this._actionsByClip[ clipUuid ];
  27455. if ( actionsForClip !== undefined ) {
  27456. return actionsForClip.actionByRoot[ rootUuid ] || null;
  27457. }
  27458. return null;
  27459. }
  27460. // deactivates all previously scheduled actions
  27461. stopAllAction() {
  27462. const actions = this._actions,
  27463. nActions = this._nActiveActions;
  27464. for ( let i = nActions - 1; i >= 0; -- i ) {
  27465. actions[ i ].stop();
  27466. }
  27467. return this;
  27468. }
  27469. // advance the time and update apply the animation
  27470. update( deltaTime ) {
  27471. deltaTime *= this.timeScale;
  27472. const actions = this._actions,
  27473. nActions = this._nActiveActions,
  27474. time = this.time += deltaTime,
  27475. timeDirection = Math.sign( deltaTime ),
  27476. accuIndex = this._accuIndex ^= 1;
  27477. // run active actions
  27478. for ( let i = 0; i !== nActions; ++ i ) {
  27479. const action = actions[ i ];
  27480. action._update( time, deltaTime, timeDirection, accuIndex );
  27481. }
  27482. // update scene graph
  27483. const bindings = this._bindings,
  27484. nBindings = this._nActiveBindings;
  27485. for ( let i = 0; i !== nBindings; ++ i ) {
  27486. bindings[ i ].apply( accuIndex );
  27487. }
  27488. return this;
  27489. }
  27490. // Allows you to seek to a specific time in an animation.
  27491. setTime( timeInSeconds ) {
  27492. this.time = 0; // Zero out time attribute for AnimationMixer object;
  27493. for ( let i = 0; i < this._actions.length; i ++ ) {
  27494. this._actions[ i ].time = 0; // Zero out time attribute for all associated AnimationAction objects.
  27495. }
  27496. return this.update( timeInSeconds ); // Update used to set exact time. Returns "this" AnimationMixer object.
  27497. }
  27498. // return this mixer's root target object
  27499. getRoot() {
  27500. return this._root;
  27501. }
  27502. // free all resources specific to a particular clip
  27503. uncacheClip( clip ) {
  27504. const actions = this._actions,
  27505. clipUuid = clip.uuid,
  27506. actionsByClip = this._actionsByClip,
  27507. actionsForClip = actionsByClip[ clipUuid ];
  27508. if ( actionsForClip !== undefined ) {
  27509. // note: just calling _removeInactiveAction would mess up the
  27510. // iteration state and also require updating the state we can
  27511. // just throw away
  27512. const actionsToRemove = actionsForClip.knownActions;
  27513. for ( let i = 0, n = actionsToRemove.length; i !== n; ++ i ) {
  27514. const action = actionsToRemove[ i ];
  27515. this._deactivateAction( action );
  27516. const cacheIndex = action._cacheIndex,
  27517. lastInactiveAction = actions[ actions.length - 1 ];
  27518. action._cacheIndex = null;
  27519. action._byClipCacheIndex = null;
  27520. lastInactiveAction._cacheIndex = cacheIndex;
  27521. actions[ cacheIndex ] = lastInactiveAction;
  27522. actions.pop();
  27523. this._removeInactiveBindingsForAction( action );
  27524. }
  27525. delete actionsByClip[ clipUuid ];
  27526. }
  27527. }
  27528. // free all resources specific to a particular root target object
  27529. uncacheRoot( root ) {
  27530. const rootUuid = root.uuid,
  27531. actionsByClip = this._actionsByClip;
  27532. for ( const clipUuid in actionsByClip ) {
  27533. const actionByRoot = actionsByClip[ clipUuid ].actionByRoot,
  27534. action = actionByRoot[ rootUuid ];
  27535. if ( action !== undefined ) {
  27536. this._deactivateAction( action );
  27537. this._removeInactiveAction( action );
  27538. }
  27539. }
  27540. const bindingsByRoot = this._bindingsByRootAndName,
  27541. bindingByName = bindingsByRoot[ rootUuid ];
  27542. if ( bindingByName !== undefined ) {
  27543. for ( const trackName in bindingByName ) {
  27544. const binding = bindingByName[ trackName ];
  27545. binding.restoreOriginalState();
  27546. this._removeInactiveBinding( binding );
  27547. }
  27548. }
  27549. }
  27550. // remove a targeted clip from the cache
  27551. uncacheAction( clip, optionalRoot ) {
  27552. const action = this.existingAction( clip, optionalRoot );
  27553. if ( action !== null ) {
  27554. this._deactivateAction( action );
  27555. this._removeInactiveAction( action );
  27556. }
  27557. }
  27558. }
  27559. class RenderTarget3D extends RenderTarget {
  27560. constructor( width = 1, height = 1, depth = 1, options = {} ) {
  27561. super( width, height, options );
  27562. this.isRenderTarget3D = true;
  27563. this.depth = depth;
  27564. this.texture = new Data3DTexture( null, width, height, depth );
  27565. this.texture.isRenderTargetTexture = true;
  27566. }
  27567. }
  27568. class RenderTargetArray extends RenderTarget {
  27569. constructor( width = 1, height = 1, depth = 1, options = {} ) {
  27570. super( width, height, options );
  27571. this.isRenderTargetArray = true;
  27572. this.depth = depth;
  27573. this.texture = new DataArrayTexture( null, width, height, depth );
  27574. this.texture.isRenderTargetTexture = true;
  27575. }
  27576. }
  27577. class Uniform {
  27578. constructor( value ) {
  27579. this.value = value;
  27580. }
  27581. clone() {
  27582. return new Uniform( this.value.clone === undefined ? this.value : this.value.clone() );
  27583. }
  27584. }
  27585. let _id = 0;
  27586. class UniformsGroup extends EventDispatcher {
  27587. constructor() {
  27588. super();
  27589. this.isUniformsGroup = true;
  27590. Object.defineProperty( this, 'id', { value: _id ++ } );
  27591. this.name = '';
  27592. this.usage = StaticDrawUsage;
  27593. this.uniforms = [];
  27594. }
  27595. add( uniform ) {
  27596. this.uniforms.push( uniform );
  27597. return this;
  27598. }
  27599. remove( uniform ) {
  27600. const index = this.uniforms.indexOf( uniform );
  27601. if ( index !== -1 ) this.uniforms.splice( index, 1 );
  27602. return this;
  27603. }
  27604. setName( name ) {
  27605. this.name = name;
  27606. return this;
  27607. }
  27608. setUsage( value ) {
  27609. this.usage = value;
  27610. return this;
  27611. }
  27612. dispose() {
  27613. this.dispatchEvent( { type: 'dispose' } );
  27614. return this;
  27615. }
  27616. copy( source ) {
  27617. this.name = source.name;
  27618. this.usage = source.usage;
  27619. const uniformsSource = source.uniforms;
  27620. this.uniforms.length = 0;
  27621. for ( let i = 0, l = uniformsSource.length; i < l; i ++ ) {
  27622. const uniforms = Array.isArray( uniformsSource[ i ] ) ? uniformsSource[ i ] : [ uniformsSource[ i ] ];
  27623. for ( let j = 0; j < uniforms.length; j ++ ) {
  27624. this.uniforms.push( uniforms[ j ].clone() );
  27625. }
  27626. }
  27627. return this;
  27628. }
  27629. clone() {
  27630. return new this.constructor().copy( this );
  27631. }
  27632. }
  27633. class InstancedInterleavedBuffer extends InterleavedBuffer {
  27634. constructor( array, stride, meshPerAttribute = 1 ) {
  27635. super( array, stride );
  27636. this.isInstancedInterleavedBuffer = true;
  27637. this.meshPerAttribute = meshPerAttribute;
  27638. }
  27639. copy( source ) {
  27640. super.copy( source );
  27641. this.meshPerAttribute = source.meshPerAttribute;
  27642. return this;
  27643. }
  27644. clone( data ) {
  27645. const ib = super.clone( data );
  27646. ib.meshPerAttribute = this.meshPerAttribute;
  27647. return ib;
  27648. }
  27649. toJSON( data ) {
  27650. const json = super.toJSON( data );
  27651. json.isInstancedInterleavedBuffer = true;
  27652. json.meshPerAttribute = this.meshPerAttribute;
  27653. return json;
  27654. }
  27655. }
  27656. class GLBufferAttribute {
  27657. constructor( buffer, type, itemSize, elementSize, count ) {
  27658. this.isGLBufferAttribute = true;
  27659. this.name = '';
  27660. this.buffer = buffer;
  27661. this.type = type;
  27662. this.itemSize = itemSize;
  27663. this.elementSize = elementSize;
  27664. this.count = count;
  27665. this.version = 0;
  27666. }
  27667. set needsUpdate( value ) {
  27668. if ( value === true ) this.version ++;
  27669. }
  27670. setBuffer( buffer ) {
  27671. this.buffer = buffer;
  27672. return this;
  27673. }
  27674. setType( type, elementSize ) {
  27675. this.type = type;
  27676. this.elementSize = elementSize;
  27677. return this;
  27678. }
  27679. setItemSize( itemSize ) {
  27680. this.itemSize = itemSize;
  27681. return this;
  27682. }
  27683. setCount( count ) {
  27684. this.count = count;
  27685. return this;
  27686. }
  27687. }
  27688. const _matrix = /*@__PURE__*/ new Matrix4();
  27689. class Raycaster {
  27690. constructor( origin, direction, near = 0, far = Infinity ) {
  27691. this.ray = new Ray( origin, direction );
  27692. // direction is assumed to be normalized (for accurate distance calculations)
  27693. this.near = near;
  27694. this.far = far;
  27695. this.camera = null;
  27696. this.layers = new Layers();
  27697. this.params = {
  27698. Mesh: {},
  27699. Line: { threshold: 1 },
  27700. LOD: {},
  27701. Points: { threshold: 1 },
  27702. Sprite: {}
  27703. };
  27704. }
  27705. set( origin, direction ) {
  27706. // direction is assumed to be normalized (for accurate distance calculations)
  27707. this.ray.set( origin, direction );
  27708. }
  27709. setFromCamera( coords, camera ) {
  27710. if ( camera.isPerspectiveCamera ) {
  27711. this.ray.origin.setFromMatrixPosition( camera.matrixWorld );
  27712. this.ray.direction.set( coords.x, coords.y, 0.5 ).unproject( camera ).sub( this.ray.origin ).normalize();
  27713. this.camera = camera;
  27714. } else if ( camera.isOrthographicCamera ) {
  27715. this.ray.origin.set( coords.x, coords.y, ( camera.near + camera.far ) / ( camera.near - camera.far ) ).unproject( camera ); // set origin in plane of camera
  27716. this.ray.direction.set( 0, 0, -1 ).transformDirection( camera.matrixWorld );
  27717. this.camera = camera;
  27718. } else {
  27719. console.error( 'THREE.Raycaster: Unsupported camera type: ' + camera.type );
  27720. }
  27721. }
  27722. setFromXRController( controller ) {
  27723. _matrix.identity().extractRotation( controller.matrixWorld );
  27724. this.ray.origin.setFromMatrixPosition( controller.matrixWorld );
  27725. this.ray.direction.set( 0, 0, -1 ).applyMatrix4( _matrix );
  27726. return this;
  27727. }
  27728. intersectObject( object, recursive = true, intersects = [] ) {
  27729. intersect( object, this, intersects, recursive );
  27730. intersects.sort( ascSort );
  27731. return intersects;
  27732. }
  27733. intersectObjects( objects, recursive = true, intersects = [] ) {
  27734. for ( let i = 0, l = objects.length; i < l; i ++ ) {
  27735. intersect( objects[ i ], this, intersects, recursive );
  27736. }
  27737. intersects.sort( ascSort );
  27738. return intersects;
  27739. }
  27740. }
  27741. function ascSort( a, b ) {
  27742. return a.distance - b.distance;
  27743. }
  27744. function intersect( object, raycaster, intersects, recursive ) {
  27745. let propagate = true;
  27746. if ( object.layers.test( raycaster.layers ) ) {
  27747. const result = object.raycast( raycaster, intersects );
  27748. if ( result === false ) propagate = false;
  27749. }
  27750. if ( propagate === true && recursive === true ) {
  27751. const children = object.children;
  27752. for ( let i = 0, l = children.length; i < l; i ++ ) {
  27753. intersect( children[ i ], raycaster, intersects, true );
  27754. }
  27755. }
  27756. }
  27757. /**
  27758. * This class can be used to represent points in 3D space as
  27759. * [Spherical coordinates]{@link https://en.wikipedia.org/wiki/Spherical_coordinate_system}.
  27760. */
  27761. class Spherical {
  27762. /**
  27763. * Constructs a new spherical.
  27764. *
  27765. * @param {number} [radius=1] - The radius, or the Euclidean distance (straight-line distance) from the point to the origin.
  27766. * @param {number} [phi=0] - The polar angle in radians from the y (up) axis.
  27767. * @param {number} [theta=0] - The equator/azimuthal angle in radians around the y (up) axis.
  27768. */
  27769. constructor( radius = 1, phi = 0, theta = 0 ) {
  27770. /**
  27771. * The radius, or the Euclidean distance (straight-line distance) from the point to the origin.
  27772. *
  27773. * @type {number}
  27774. * @default 1
  27775. */
  27776. this.radius = radius;
  27777. /**
  27778. * The polar angle in radians from the y (up) axis.
  27779. *
  27780. * @type {number}
  27781. * @default 0
  27782. */
  27783. this.phi = phi;
  27784. /**
  27785. * The equator/azimuthal angle in radians around the y (up) axis.
  27786. *
  27787. * @type {number}
  27788. * @default 0
  27789. */
  27790. this.theta = theta;
  27791. }
  27792. /**
  27793. * Sets the spherical components by copying the given values.
  27794. *
  27795. * @param {number} radius - The radius.
  27796. * @param {number} phi - The polar angle.
  27797. * @param {number} theta - The azimuthal angle.
  27798. * @return {Spherical} A reference to this spherical.
  27799. */
  27800. set( radius, phi, theta ) {
  27801. this.radius = radius;
  27802. this.phi = phi;
  27803. this.theta = theta;
  27804. return this;
  27805. }
  27806. /**
  27807. * Copies the values of the given spherical to this instance.
  27808. *
  27809. * @param {Spherical} other - The spherical to copy.
  27810. * @return {Spherical} A reference to this spherical.
  27811. */
  27812. copy( other ) {
  27813. this.radius = other.radius;
  27814. this.phi = other.phi;
  27815. this.theta = other.theta;
  27816. return this;
  27817. }
  27818. /**
  27819. * Restricts the polar angle [page:.phi phi] to be between `0.000001` and pi -
  27820. * `0.000001`.
  27821. *
  27822. * @return {Spherical} A reference to this spherical.
  27823. */
  27824. makeSafe() {
  27825. const EPS = 0.000001;
  27826. this.phi = clamp( this.phi, EPS, Math.PI - EPS );
  27827. return this;
  27828. }
  27829. /**
  27830. * Sets the spherical components from the given vector which is assumed to hold
  27831. * Cartesian coordinates.
  27832. *
  27833. * @param {Vector3} v - The vector to set.
  27834. * @return {Spherical} A reference to this spherical.
  27835. */
  27836. setFromVector3( v ) {
  27837. return this.setFromCartesianCoords( v.x, v.y, v.z );
  27838. }
  27839. /**
  27840. * Sets the spherical components from the given Cartesian coordinates.
  27841. *
  27842. * @param {number} x - The x value.
  27843. * @param {number} y - The x value.
  27844. * @param {number} z - The x value.
  27845. * @return {Spherical} A reference to this spherical.
  27846. */
  27847. setFromCartesianCoords( x, y, z ) {
  27848. this.radius = Math.sqrt( x * x + y * y + z * z );
  27849. if ( this.radius === 0 ) {
  27850. this.theta = 0;
  27851. this.phi = 0;
  27852. } else {
  27853. this.theta = Math.atan2( x, z );
  27854. this.phi = Math.acos( clamp( y / this.radius, -1, 1 ) );
  27855. }
  27856. return this;
  27857. }
  27858. /**
  27859. * Returns a new spherical with copied values from this instance.
  27860. *
  27861. * @return {Spherical} A clone of this instance.
  27862. */
  27863. clone() {
  27864. return new this.constructor().copy( this );
  27865. }
  27866. }
  27867. /**
  27868. * This class can be used to represent points in 3D space as
  27869. * [Cylindrical coordinates]{@link https://en.wikipedia.org/wiki/Cylindrical_coordinate_system}.
  27870. */
  27871. class Cylindrical {
  27872. /**
  27873. * Constructs a new cylindrical.
  27874. *
  27875. * @param {number} [radius=1] - The distance from the origin to a point in the x-z plane.
  27876. * @param {number} [theta=0] - A counterclockwise angle in the x-z plane measured in radians from the positive z-axis.
  27877. * @param {number} [y=0] - The height above the x-z plane.
  27878. */
  27879. constructor( radius = 1, theta = 0, y = 0 ) {
  27880. /**
  27881. * The distance from the origin to a point in the x-z plane.
  27882. *
  27883. * @type {number}
  27884. * @default 1
  27885. */
  27886. this.radius = radius;
  27887. /**
  27888. * A counterclockwise angle in the x-z plane measured in radians from the positive z-axis.
  27889. *
  27890. * @type {number}
  27891. * @default 0
  27892. */
  27893. this.theta = theta;
  27894. /**
  27895. * The height above the x-z plane.
  27896. *
  27897. * @type {number}
  27898. * @default 0
  27899. */
  27900. this.y = y;
  27901. }
  27902. /**
  27903. * Sets the cylindrical components by copying the given values.
  27904. *
  27905. * @param {number} radius - The radius.
  27906. * @param {number} theta - The theta angle.
  27907. * @param {number} y - The height value.
  27908. * @return {Cylindrical} A reference to this cylindrical.
  27909. */
  27910. set( radius, theta, y ) {
  27911. this.radius = radius;
  27912. this.theta = theta;
  27913. this.y = y;
  27914. return this;
  27915. }
  27916. /**
  27917. * Copies the values of the given cylindrical to this instance.
  27918. *
  27919. * @param {Cylindrical} other - The cylindrical to copy.
  27920. * @return {Cylindrical} A reference to this cylindrical.
  27921. */
  27922. copy( other ) {
  27923. this.radius = other.radius;
  27924. this.theta = other.theta;
  27925. this.y = other.y;
  27926. return this;
  27927. }
  27928. /**
  27929. * Sets the cylindrical components from the given vector which is assumed to hold
  27930. * Cartesian coordinates.
  27931. *
  27932. * @param {Vector3} v - The vector to set.
  27933. * @return {Cylindrical} A reference to this cylindrical.
  27934. */
  27935. setFromVector3( v ) {
  27936. return this.setFromCartesianCoords( v.x, v.y, v.z );
  27937. }
  27938. /**
  27939. * Sets the cylindrical components from the given Cartesian coordinates.
  27940. *
  27941. * @param {number} x - The x value.
  27942. * @param {number} y - The x value.
  27943. * @param {number} z - The x value.
  27944. * @return {Cylindrical} A reference to this cylindrical.
  27945. */
  27946. setFromCartesianCoords( x, y, z ) {
  27947. this.radius = Math.sqrt( x * x + z * z );
  27948. this.theta = Math.atan2( x, z );
  27949. this.y = y;
  27950. return this;
  27951. }
  27952. /**
  27953. * Returns a new cylindrical with copied values from this instance.
  27954. *
  27955. * @return {Cylindrical} A clone of this instance.
  27956. */
  27957. clone() {
  27958. return new this.constructor().copy( this );
  27959. }
  27960. }
  27961. /**
  27962. * Represents a 2x2 matrix.
  27963. *
  27964. * A Note on Row-Major and Column-Major Ordering:
  27965. *
  27966. * The constructor and {@link Matrix2#set} method take arguments in
  27967. * [row-major]{@link https://en.wikipedia.org/wiki/Row-_and_column-major_order#Column-major_order}
  27968. * order, while internally they are stored in the {@link Matrix2#elements} array in column-major order.
  27969. * This means that calling:
  27970. * ```js
  27971. * const m = new THREE.Matrix2();
  27972. * m.set( 11, 12,
  27973. * 21, 22 );
  27974. * ```
  27975. * will result in the elements array containing:
  27976. * ```js
  27977. * m.elements = [ 11, 21,
  27978. * 12, 22 ];
  27979. * ```
  27980. * and internally all calculations are performed using column-major ordering.
  27981. * However, as the actual ordering makes no difference mathematically and
  27982. * most people are used to thinking about matrices in row-major order, the
  27983. * three.js documentation shows matrices in row-major order. Just bear in
  27984. * mind that if you are reading the source code, you'll have to take the
  27985. * transpose of any matrices outlined here to make sense of the calculations.
  27986. */
  27987. class Matrix2 {
  27988. /**
  27989. * Constructs a new 2x2 matrix. The arguments are supposed to be
  27990. * in row-major order. If no arguments are provided, the constructor
  27991. * initializes the matrix as an identity matrix.
  27992. *
  27993. * @param {number} [n11] - 1-1 matrix element.
  27994. * @param {number} [n12] - 1-2 matrix element.
  27995. * @param {number} [n21] - 2-1 matrix element.
  27996. * @param {number} [n22] - 2-2 matrix element.
  27997. */
  27998. constructor( n11, n12, n21, n22 ) {
  27999. /**
  28000. * This flag can be used for type testing.
  28001. *
  28002. * @type {boolean}
  28003. * @readonly
  28004. * @default true
  28005. */
  28006. Matrix2.prototype.isMatrix2 = true;
  28007. /**
  28008. * A column-major list of matrix values.
  28009. *
  28010. * @type {Array<number>}
  28011. */
  28012. this.elements = [
  28013. 1, 0,
  28014. 0, 1,
  28015. ];
  28016. if ( n11 !== undefined ) {
  28017. this.set( n11, n12, n21, n22 );
  28018. }
  28019. }
  28020. /**
  28021. * Sets this matrix to the 2x2 identity matrix.
  28022. *
  28023. * @return {Matrix2} A reference to this matrix.
  28024. */
  28025. identity() {
  28026. this.set(
  28027. 1, 0,
  28028. 0, 1,
  28029. );
  28030. return this;
  28031. }
  28032. /**
  28033. * Sets the elements of the matrix from the given array.
  28034. *
  28035. * @param {Array<number>} array - The matrix elements in column-major order.
  28036. * @param {number} [offset=0] - Index of the first element in the array.
  28037. * @return {Matrix2} A reference to this matrix.
  28038. */
  28039. fromArray( array, offset = 0 ) {
  28040. for ( let i = 0; i < 4; i ++ ) {
  28041. this.elements[ i ] = array[ i + offset ];
  28042. }
  28043. return this;
  28044. }
  28045. /**
  28046. * Sets the elements of the matrix.The arguments are supposed to be
  28047. * in row-major order.
  28048. *
  28049. * @param {number} n11 - 1-1 matrix element.
  28050. * @param {number} n12 - 1-2 matrix element.
  28051. * @param {number} n21 - 2-1 matrix element.
  28052. * @param {number} n22 - 2-2 matrix element.
  28053. * @return {Matrix2} A reference to this matrix.
  28054. */
  28055. set( n11, n12, n21, n22 ) {
  28056. const te = this.elements;
  28057. te[ 0 ] = n11; te[ 2 ] = n12;
  28058. te[ 1 ] = n21; te[ 3 ] = n22;
  28059. return this;
  28060. }
  28061. }
  28062. const _vector$4 = /*@__PURE__*/ new Vector2();
  28063. /**
  28064. * Represents an axis-aligned bounding box (AABB) in 2D space.
  28065. */
  28066. class Box2 {
  28067. /**
  28068. * Constructs a new bounding box.
  28069. *
  28070. * @param {Vector2} [min=(Infinity,Infinity)] - A vector representing the lower boundary of the box.
  28071. * @param {Vector2} [max=(-Infinity,-Infinity)] - A vector representing the upper boundary of the box.
  28072. */
  28073. constructor( min = new Vector2( + Infinity, + Infinity ), max = new Vector2( - Infinity, - Infinity ) ) {
  28074. /**
  28075. * This flag can be used for type testing.
  28076. *
  28077. * @type {boolean}
  28078. * @readonly
  28079. * @default true
  28080. */
  28081. this.isBox2 = true;
  28082. /**
  28083. * The lower boundary of the box.
  28084. *
  28085. * @type {Vector2}
  28086. */
  28087. this.min = min;
  28088. /**
  28089. * The upper boundary of the box.
  28090. *
  28091. * @type {Vector2}
  28092. */
  28093. this.max = max;
  28094. }
  28095. /**
  28096. * Sets the lower and upper boundaries of this box.
  28097. * Please note that this method only copies the values from the given objects.
  28098. *
  28099. * @param {Vector2} min - The lower boundary of the box.
  28100. * @param {Vector2} max - The upper boundary of the box.
  28101. * @return {Box2} A reference to this bounding box.
  28102. */
  28103. set( min, max ) {
  28104. this.min.copy( min );
  28105. this.max.copy( max );
  28106. return this;
  28107. }
  28108. /**
  28109. * Sets the upper and lower bounds of this box so it encloses the position data
  28110. * in the given array.
  28111. *
  28112. * @param {Array<Vector2>} points - An array holding 2D position data as instances of {@link Vector2}.
  28113. * @return {Box2} A reference to this bounding box.
  28114. */
  28115. setFromPoints( points ) {
  28116. this.makeEmpty();
  28117. for ( let i = 0, il = points.length; i < il; i ++ ) {
  28118. this.expandByPoint( points[ i ] );
  28119. }
  28120. return this;
  28121. }
  28122. /**
  28123. * Centers this box on the given center vector and sets this box's width, height and
  28124. * depth to the given size values.
  28125. *
  28126. * @param {Vector2} center - The center of the box.
  28127. * @param {Vector2} size - The x and y dimensions of the box.
  28128. * @return {Box2} A reference to this bounding box.
  28129. */
  28130. setFromCenterAndSize( center, size ) {
  28131. const halfSize = _vector$4.copy( size ).multiplyScalar( 0.5 );
  28132. this.min.copy( center ).sub( halfSize );
  28133. this.max.copy( center ).add( halfSize );
  28134. return this;
  28135. }
  28136. /**
  28137. * Returns a new box with copied values from this instance.
  28138. *
  28139. * @return {Box2} A clone of this instance.
  28140. */
  28141. clone() {
  28142. return new this.constructor().copy( this );
  28143. }
  28144. /**
  28145. * Copies the values of the given box to this instance.
  28146. *
  28147. * @param {Box2} box - The box to copy.
  28148. * @return {Box2} A reference to this bounding box.
  28149. */
  28150. copy( box ) {
  28151. this.min.copy( box.min );
  28152. this.max.copy( box.max );
  28153. return this;
  28154. }
  28155. /**
  28156. * Makes this box empty which means in encloses a zero space in 2D.
  28157. *
  28158. * @return {Box2} A reference to this bounding box.
  28159. */
  28160. makeEmpty() {
  28161. this.min.x = this.min.y = + Infinity;
  28162. this.max.x = this.max.y = - Infinity;
  28163. return this;
  28164. }
  28165. /**
  28166. * Returns true if this box includes zero points within its bounds.
  28167. * Note that a box with equal lower and upper bounds still includes one
  28168. * point, the one both bounds share.
  28169. *
  28170. * @return {boolean} Whether this box is empty or not.
  28171. */
  28172. isEmpty() {
  28173. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  28174. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y );
  28175. }
  28176. /**
  28177. * Returns the center point of this box.
  28178. *
  28179. * @param {Vector2} target - The target vector that is used to store the method's result.
  28180. * @return {Vector2} The center point.
  28181. */
  28182. getCenter( target ) {
  28183. return this.isEmpty() ? target.set( 0, 0 ) : target.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  28184. }
  28185. /**
  28186. * Returns the dimensions of this box.
  28187. *
  28188. * @param {Vector2} target - The target vector that is used to store the method's result.
  28189. * @return {Vector2} The size.
  28190. */
  28191. getSize( target ) {
  28192. return this.isEmpty() ? target.set( 0, 0 ) : target.subVectors( this.max, this.min );
  28193. }
  28194. /**
  28195. * Expands the boundaries of this box to include the given point.
  28196. *
  28197. * @param {Vector2} point - The point that should be included by the bounding box.
  28198. * @return {Box2} A reference to this bounding box.
  28199. */
  28200. expandByPoint( point ) {
  28201. this.min.min( point );
  28202. this.max.max( point );
  28203. return this;
  28204. }
  28205. /**
  28206. * Expands this box equilaterally by the given vector. The width of this
  28207. * box will be expanded by the x component of the vector in both
  28208. * directions. The height of this box will be expanded by the y component of
  28209. * the vector in both directions.
  28210. *
  28211. * @param {Vector2} vector - The vector that should expand the bounding box.
  28212. * @return {Box2} A reference to this bounding box.
  28213. */
  28214. expandByVector( vector ) {
  28215. this.min.sub( vector );
  28216. this.max.add( vector );
  28217. return this;
  28218. }
  28219. /**
  28220. * Expands each dimension of the box by the given scalar. If negative, the
  28221. * dimensions of the box will be contracted.
  28222. *
  28223. * @param {number} scalar - The scalar value that should expand the bounding box.
  28224. * @return {Box2} A reference to this bounding box.
  28225. */
  28226. expandByScalar( scalar ) {
  28227. this.min.addScalar( - scalar );
  28228. this.max.addScalar( scalar );
  28229. return this;
  28230. }
  28231. /**
  28232. * Returns `true` if the given point lies within or on the boundaries of this box.
  28233. *
  28234. * @param {Vector2} point - The point to test.
  28235. * @return {boolean} Whether the bounding box contains the given point or not.
  28236. */
  28237. containsPoint( point ) {
  28238. return point.x >= this.min.x && point.x <= this.max.x &&
  28239. point.y >= this.min.y && point.y <= this.max.y;
  28240. }
  28241. /**
  28242. * Returns `true` if this bounding box includes the entirety of the given bounding box.
  28243. * If this box and the given one are identical, this function also returns `true`.
  28244. *
  28245. * @param {Box2} box - The bounding box to test.
  28246. * @return {boolean} Whether the bounding box contains the given bounding box or not.
  28247. */
  28248. containsBox( box ) {
  28249. return this.min.x <= box.min.x && box.max.x <= this.max.x &&
  28250. this.min.y <= box.min.y && box.max.y <= this.max.y;
  28251. }
  28252. /**
  28253. * Returns a point as a proportion of this box's width and height.
  28254. *
  28255. * @param {Vector2} point - A point in 2D space.
  28256. * @param {Vector2} target - The target vector that is used to store the method's result.
  28257. * @return {Vector2} A point as a proportion of this box's width and height.
  28258. */
  28259. getParameter( point, target ) {
  28260. // This can potentially have a divide by zero if the box
  28261. // has a size dimension of 0.
  28262. return target.set(
  28263. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  28264. ( point.y - this.min.y ) / ( this.max.y - this.min.y )
  28265. );
  28266. }
  28267. /**
  28268. * Returns `true` if the given bounding box intersects with this bounding box.
  28269. *
  28270. * @param {Box2} box - The bounding box to test.
  28271. * @return {boolean} Whether the given bounding box intersects with this bounding box.
  28272. */
  28273. intersectsBox( box ) {
  28274. // using 4 splitting planes to rule out intersections
  28275. return box.max.x >= this.min.x && box.min.x <= this.max.x &&
  28276. box.max.y >= this.min.y && box.min.y <= this.max.y;
  28277. }
  28278. /**
  28279. * Clamps the given point within the bounds of this box.
  28280. *
  28281. * @param {Vector2} point - The point to clamp.
  28282. * @param {Vector2} target - The target vector that is used to store the method's result.
  28283. * @return {Vector2} The clamped point.
  28284. */
  28285. clampPoint( point, target ) {
  28286. return target.copy( point ).clamp( this.min, this.max );
  28287. }
  28288. /**
  28289. * Returns the euclidean distance from any edge of this box to the specified point. If
  28290. * the given point lies inside of this box, the distance will be `0`.
  28291. *
  28292. * @param {Vector2} point - The point to compute the distance to.
  28293. * @return {number} The euclidean distance.
  28294. */
  28295. distanceToPoint( point ) {
  28296. return this.clampPoint( point, _vector$4 ).distanceTo( point );
  28297. }
  28298. /**
  28299. * Computes the intersection of this bounding box and the given one, setting the upper
  28300. * bound of this box to the lesser of the two boxes' upper bounds and the
  28301. * lower bound of this box to the greater of the two boxes' lower bounds. If
  28302. * there's no overlap, makes this box empty.
  28303. *
  28304. * @param {Box2} box - The bounding box to intersect with.
  28305. * @return {Box2} A reference to this bounding box.
  28306. */
  28307. intersect( box ) {
  28308. this.min.max( box.min );
  28309. this.max.min( box.max );
  28310. if ( this.isEmpty() ) this.makeEmpty();
  28311. return this;
  28312. }
  28313. /**
  28314. * Computes the union of this box and another and the given one, setting the upper
  28315. * bound of this box to the greater of the two boxes' upper bounds and the
  28316. * lower bound of this box to the lesser of the two boxes' lower bounds.
  28317. *
  28318. * @param {Box2} box - The bounding box that will be unioned with this instance.
  28319. * @return {Box2} A reference to this bounding box.
  28320. */
  28321. union( box ) {
  28322. this.min.min( box.min );
  28323. this.max.max( box.max );
  28324. return this;
  28325. }
  28326. /**
  28327. * Adds the given offset to both the upper and lower bounds of this bounding box,
  28328. * effectively moving it in 2D space.
  28329. *
  28330. * @param {Vector2} offset - The offset that should be used to translate the bounding box.
  28331. * @return {Box2} A reference to this bounding box.
  28332. */
  28333. translate( offset ) {
  28334. this.min.add( offset );
  28335. this.max.add( offset );
  28336. return this;
  28337. }
  28338. /**
  28339. * Returns `true` if this bounding box is equal with the given one.
  28340. *
  28341. * @param {Box2} box - The box to test for equality.
  28342. * @return {boolean} Whether this bounding box is equal with the given one.
  28343. */
  28344. equals( box ) {
  28345. return box.min.equals( this.min ) && box.max.equals( this.max );
  28346. }
  28347. }
  28348. const _startP = /*@__PURE__*/ new Vector3();
  28349. const _startEnd = /*@__PURE__*/ new Vector3();
  28350. /**
  28351. * An analytical line segment in 3D space represented by a start and end point.
  28352. */
  28353. class Line3 {
  28354. /**
  28355. * Constructs a new line segment.
  28356. *
  28357. * @param {Vector3} [start=(0,0,0)] - Start of the line segment.
  28358. * @param {Vector3} [end=(0,0,0)] - End of the line segment.
  28359. */
  28360. constructor( start = new Vector3(), end = new Vector3() ) {
  28361. /**
  28362. * Start of the line segment.
  28363. *
  28364. * @type {Vector3}
  28365. */
  28366. this.start = start;
  28367. /**
  28368. * End of the line segment.
  28369. *
  28370. * @type {Vector3}
  28371. */
  28372. this.end = end;
  28373. }
  28374. /**
  28375. * Sets the start and end values by copying the given vectors.
  28376. *
  28377. * @param {Vector3} start - The start point.
  28378. * @param {Vector3} end - The end point.
  28379. * @return {Line3} A reference to this line segment.
  28380. */
  28381. set( start, end ) {
  28382. this.start.copy( start );
  28383. this.end.copy( end );
  28384. return this;
  28385. }
  28386. /**
  28387. * Copies the values of the given line segment to this instance.
  28388. *
  28389. * @param {Line3} line - The line segment to copy.
  28390. * @return {Line3} A reference to this line segment.
  28391. */
  28392. copy( line ) {
  28393. this.start.copy( line.start );
  28394. this.end.copy( line.end );
  28395. return this;
  28396. }
  28397. /**
  28398. * Returns the center of the line segment.
  28399. *
  28400. * @param {Vector3} target - The target vector that is used to store the method's result.
  28401. * @return {Vector3} The center point.
  28402. */
  28403. getCenter( target ) {
  28404. return target.addVectors( this.start, this.end ).multiplyScalar( 0.5 );
  28405. }
  28406. /**
  28407. * Returns the delta vector of the line segment's start and end point.
  28408. *
  28409. * @param {Vector3} target - The target vector that is used to store the method's result.
  28410. * @return {Vector3} The delta vector.
  28411. */
  28412. delta( target ) {
  28413. return target.subVectors( this.end, this.start );
  28414. }
  28415. /**
  28416. * Returns the squared Euclidean distance between the line' start and end point.
  28417. *
  28418. * @return {Vector3} The squared Euclidean distance.
  28419. */
  28420. distanceSq() {
  28421. return this.start.distanceToSquared( this.end );
  28422. }
  28423. /**
  28424. * Returns the Euclidean distance between the line' start and end point.
  28425. *
  28426. * @return {Vector3} The Euclidean distance.
  28427. */
  28428. distance() {
  28429. return this.start.distanceTo( this.end );
  28430. }
  28431. /**
  28432. * Returns a vector at a certain position along the line segment.
  28433. *
  28434. * @param {Vector3} t - A value between `[0,1]` to represent a position along the line segment.
  28435. * @param {Vector3} target - The target vector that is used to store the method's result.
  28436. * @return {Vector3} The delta vector.
  28437. */
  28438. at( t, target ) {
  28439. return this.delta( target ).multiplyScalar( t ).add( this.start );
  28440. }
  28441. /**
  28442. * Returns a point parameter based on the closest point as projected on the line segment.
  28443. *
  28444. * @param {Vector3} point - The point for which to return a point parameter.
  28445. * @param {boolean} clampToLine - Whether to clamp the result to the range `[0,1]` or not.
  28446. * @return {number} The point parameter.
  28447. */
  28448. closestPointToPointParameter( point, clampToLine ) {
  28449. _startP.subVectors( point, this.start );
  28450. _startEnd.subVectors( this.end, this.start );
  28451. const startEnd2 = _startEnd.dot( _startEnd );
  28452. const startEnd_startP = _startEnd.dot( _startP );
  28453. let t = startEnd_startP / startEnd2;
  28454. if ( clampToLine ) {
  28455. t = clamp( t, 0, 1 );
  28456. }
  28457. return t;
  28458. }
  28459. /**
  28460. * Returns the closets point on the line for a given point.
  28461. *
  28462. * @param {Vector3} point - The point to compute the closest point on the line for.
  28463. * @param {boolean} clampToLine - Whether to clamp the result to the range `[0,1]` or not.
  28464. * @param {Vector3} target - The target vector that is used to store the method's result.
  28465. * @return {Vector3} The closest point on the line.
  28466. */
  28467. closestPointToPoint( point, clampToLine, target ) {
  28468. const t = this.closestPointToPointParameter( point, clampToLine );
  28469. return this.delta( target ).multiplyScalar( t ).add( this.start );
  28470. }
  28471. /**
  28472. * Applies a 4x4 transformation matrix to this line segment.
  28473. *
  28474. * @param {Matrix4} matrix - The transformation matrix.
  28475. * @return {Line3} A reference to this line segment.
  28476. */
  28477. applyMatrix4( matrix ) {
  28478. this.start.applyMatrix4( matrix );
  28479. this.end.applyMatrix4( matrix );
  28480. return this;
  28481. }
  28482. /**
  28483. * Returns `true` if this line segment is equal with the given one.
  28484. *
  28485. * @param {Line3} line - The line segment to test for equality.
  28486. * @return {boolean} Whether this line segment is equal with the given one.
  28487. */
  28488. equals( line ) {
  28489. return line.start.equals( this.start ) && line.end.equals( this.end );
  28490. }
  28491. /**
  28492. * Returns a new line segment with copied values from this instance.
  28493. *
  28494. * @return {Line3} A clone of this instance.
  28495. */
  28496. clone() {
  28497. return new this.constructor().copy( this );
  28498. }
  28499. }
  28500. const _vector$3 = /*@__PURE__*/ new Vector3();
  28501. /**
  28502. * This displays a cone shaped helper object for a {@link SpotLight}.
  28503. *
  28504. * ```js
  28505. * const spotLight = new THREE.SpotLight( 0xffffff );
  28506. * spotLight.position.set( 10, 10, 10 );
  28507. * scene.add( spotLight );
  28508. *
  28509. * const spotLightHelper = new THREE.SpotLightHelper( spotLight );
  28510. * scene.add( spotLightHelper );
  28511. * ```
  28512. *
  28513. * @augments Object3D
  28514. */
  28515. class SpotLightHelper extends Object3D {
  28516. /**
  28517. * Constructs a new spot light helper.
  28518. *
  28519. * @param {HemisphereLight} light - The light to be visualized.
  28520. * @param {number|Color|string} [color] - The helper's color. If not set, the helper will take
  28521. * the color of the light.
  28522. */
  28523. constructor( light, color ) {
  28524. super();
  28525. /**
  28526. * The light being visualized.
  28527. *
  28528. * @type {SpotLight}
  28529. */
  28530. this.light = light;
  28531. this.matrixAutoUpdate = false;
  28532. /**
  28533. * The color parameter passed in the constructor.
  28534. * If not set, the helper will take the color of the light.
  28535. *
  28536. * @type {number|Color|string}
  28537. */
  28538. this.color = color;
  28539. this.type = 'SpotLightHelper';
  28540. const geometry = new BufferGeometry();
  28541. const positions = [
  28542. 0, 0, 0, 0, 0, 1,
  28543. 0, 0, 0, 1, 0, 1,
  28544. 0, 0, 0, -1, 0, 1,
  28545. 0, 0, 0, 0, 1, 1,
  28546. 0, 0, 0, 0, -1, 1
  28547. ];
  28548. for ( let i = 0, j = 1, l = 32; i < l; i ++, j ++ ) {
  28549. const p1 = ( i / l ) * Math.PI * 2;
  28550. const p2 = ( j / l ) * Math.PI * 2;
  28551. positions.push(
  28552. Math.cos( p1 ), Math.sin( p1 ), 1,
  28553. Math.cos( p2 ), Math.sin( p2 ), 1
  28554. );
  28555. }
  28556. geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  28557. const material = new LineBasicMaterial( { fog: false, toneMapped: false } );
  28558. this.cone = new LineSegments( geometry, material );
  28559. this.add( this.cone );
  28560. this.update();
  28561. }
  28562. /**
  28563. * Frees the GPU-related resources allocated by this instance. Call this
  28564. * method whenever this instance is no longer used in your app.
  28565. */
  28566. dispose() {
  28567. this.cone.geometry.dispose();
  28568. this.cone.material.dispose();
  28569. }
  28570. /**
  28571. * Updates the helper to match the position and direction of the
  28572. * light being visualized.
  28573. */
  28574. update() {
  28575. this.light.updateWorldMatrix( true, false );
  28576. this.light.target.updateWorldMatrix( true, false );
  28577. // update the local matrix based on the parent and light target transforms
  28578. if ( this.parent ) {
  28579. this.parent.updateWorldMatrix( true );
  28580. this.matrix
  28581. .copy( this.parent.matrixWorld )
  28582. .invert()
  28583. .multiply( this.light.matrixWorld );
  28584. } else {
  28585. this.matrix.copy( this.light.matrixWorld );
  28586. }
  28587. this.matrixWorld.copy( this.light.matrixWorld );
  28588. const coneLength = this.light.distance ? this.light.distance : 1000;
  28589. const coneWidth = coneLength * Math.tan( this.light.angle );
  28590. this.cone.scale.set( coneWidth, coneWidth, coneLength );
  28591. _vector$3.setFromMatrixPosition( this.light.target.matrixWorld );
  28592. this.cone.lookAt( _vector$3 );
  28593. if ( this.color !== undefined ) {
  28594. this.cone.material.color.set( this.color );
  28595. } else {
  28596. this.cone.material.color.copy( this.light.color );
  28597. }
  28598. }
  28599. }
  28600. const _vector$2 = /*@__PURE__*/ new Vector3();
  28601. const _boneMatrix = /*@__PURE__*/ new Matrix4();
  28602. const _matrixWorldInv = /*@__PURE__*/ new Matrix4();
  28603. /**
  28604. * A helper object to assist with visualizing a {@link Skeleton}.
  28605. *
  28606. * ```js
  28607. * const helper = new THREE.SkeletonHelper( skinnedMesh );
  28608. * scene.add( helper );
  28609. * ```
  28610. *
  28611. * @augments LineSegments
  28612. */
  28613. class SkeletonHelper extends LineSegments {
  28614. /**
  28615. * Constructs a new hemisphere light helper.
  28616. *
  28617. * @param {Object3D} object - Usually an instance of {@link SkinnedMesh}. However, any 3D object
  28618. * can be used if it represents a hierarchy of bones (see {@link Bone}).
  28619. */
  28620. constructor( object ) {
  28621. const bones = getBoneList( object );
  28622. const geometry = new BufferGeometry();
  28623. const vertices = [];
  28624. const colors = [];
  28625. const color1 = new Color( 0, 0, 1 );
  28626. const color2 = new Color( 0, 1, 0 );
  28627. for ( let i = 0; i < bones.length; i ++ ) {
  28628. const bone = bones[ i ];
  28629. if ( bone.parent && bone.parent.isBone ) {
  28630. vertices.push( 0, 0, 0 );
  28631. vertices.push( 0, 0, 0 );
  28632. colors.push( color1.r, color1.g, color1.b );
  28633. colors.push( color2.r, color2.g, color2.b );
  28634. }
  28635. }
  28636. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  28637. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  28638. const material = new LineBasicMaterial( { vertexColors: true, depthTest: false, depthWrite: false, toneMapped: false, transparent: true } );
  28639. super( geometry, material );
  28640. /**
  28641. * This flag can be used for type testing.
  28642. *
  28643. * @type {boolean}
  28644. * @readonly
  28645. * @default true
  28646. */
  28647. this.isSkeletonHelper = true;
  28648. this.type = 'SkeletonHelper';
  28649. /**
  28650. * The object being visualized.
  28651. *
  28652. * @type {Object3D}
  28653. */
  28654. this.root = object;
  28655. /**
  28656. * he list of bones that the helper visualizes.
  28657. *
  28658. * @type {Array<Bone>}
  28659. */
  28660. this.bones = bones;
  28661. this.matrix = object.matrixWorld;
  28662. this.matrixAutoUpdate = false;
  28663. }
  28664. updateMatrixWorld( force ) {
  28665. const bones = this.bones;
  28666. const geometry = this.geometry;
  28667. const position = geometry.getAttribute( 'position' );
  28668. _matrixWorldInv.copy( this.root.matrixWorld ).invert();
  28669. for ( let i = 0, j = 0; i < bones.length; i ++ ) {
  28670. const bone = bones[ i ];
  28671. if ( bone.parent && bone.parent.isBone ) {
  28672. _boneMatrix.multiplyMatrices( _matrixWorldInv, bone.matrixWorld );
  28673. _vector$2.setFromMatrixPosition( _boneMatrix );
  28674. position.setXYZ( j, _vector$2.x, _vector$2.y, _vector$2.z );
  28675. _boneMatrix.multiplyMatrices( _matrixWorldInv, bone.parent.matrixWorld );
  28676. _vector$2.setFromMatrixPosition( _boneMatrix );
  28677. position.setXYZ( j + 1, _vector$2.x, _vector$2.y, _vector$2.z );
  28678. j += 2;
  28679. }
  28680. }
  28681. geometry.getAttribute( 'position' ).needsUpdate = true;
  28682. super.updateMatrixWorld( force );
  28683. }
  28684. /**
  28685. * Frees the GPU-related resources allocated by this instance. Call this
  28686. * method whenever this instance is no longer used in your app.
  28687. */
  28688. dispose() {
  28689. this.geometry.dispose();
  28690. this.material.dispose();
  28691. }
  28692. }
  28693. function getBoneList( object ) {
  28694. const boneList = [];
  28695. if ( object.isBone === true ) {
  28696. boneList.push( object );
  28697. }
  28698. for ( let i = 0; i < object.children.length; i ++ ) {
  28699. boneList.push( ...getBoneList( object.children[ i ] ) );
  28700. }
  28701. return boneList;
  28702. }
  28703. /**
  28704. * This displays a helper object consisting of a spherical mesh for
  28705. * visualizing an instance of {@link PointLight}.
  28706. *
  28707. * ```js
  28708. * const pointLight = new THREE.PointLight( 0xff0000, 1, 100 );
  28709. * pointLight.position.set( 10, 10, 10 );
  28710. * scene.add( pointLight );
  28711. *
  28712. * const sphereSize = 1;
  28713. * const pointLightHelper = new THREE.PointLightHelper( pointLight, sphereSize );
  28714. * scene.add( pointLightHelper );
  28715. * ```
  28716. *
  28717. * @augments Mesh
  28718. */
  28719. class PointLightHelper extends Mesh {
  28720. /**
  28721. * Constructs a new point light helper.
  28722. *
  28723. * @param {PointLight} light - The light to be visualized.
  28724. * @param {number} [sphereSize=1] - The size of the sphere helper.
  28725. * @param {number|Color|string} [color] - The helper's color. If not set, the helper will take
  28726. * the color of the light.
  28727. */
  28728. constructor( light, sphereSize, color ) {
  28729. const geometry = new SphereGeometry( sphereSize, 4, 2 );
  28730. const material = new MeshBasicMaterial( { wireframe: true, fog: false, toneMapped: false } );
  28731. super( geometry, material );
  28732. /**
  28733. * The light being visualized.
  28734. *
  28735. * @type {HemisphereLight}
  28736. */
  28737. this.light = light;
  28738. /**
  28739. * The color parameter passed in the constructor.
  28740. * If not set, the helper will take the color of the light.
  28741. *
  28742. * @type {number|Color|string}
  28743. */
  28744. this.color = color;
  28745. this.type = 'PointLightHelper';
  28746. this.matrix = this.light.matrixWorld;
  28747. this.matrixAutoUpdate = false;
  28748. this.update();
  28749. /*
  28750. // TODO: delete this comment?
  28751. const distanceGeometry = new THREE.IcosahedronGeometry( 1, 2 );
  28752. const distanceMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false, wireframe: true, opacity: 0.1, transparent: true } );
  28753. this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial );
  28754. this.lightDistance = new THREE.Mesh( distanceGeometry, distanceMaterial );
  28755. const d = light.distance;
  28756. if ( d === 0.0 ) {
  28757. this.lightDistance.visible = false;
  28758. } else {
  28759. this.lightDistance.scale.set( d, d, d );
  28760. }
  28761. this.add( this.lightDistance );
  28762. */
  28763. }
  28764. /**
  28765. * Frees the GPU-related resources allocated by this instance. Call this
  28766. * method whenever this instance is no longer used in your app.
  28767. */
  28768. dispose() {
  28769. this.geometry.dispose();
  28770. this.material.dispose();
  28771. }
  28772. /**
  28773. * Updates the helper to match the position of the
  28774. * light being visualized.
  28775. */
  28776. update() {
  28777. this.light.updateWorldMatrix( true, false );
  28778. if ( this.color !== undefined ) {
  28779. this.material.color.set( this.color );
  28780. } else {
  28781. this.material.color.copy( this.light.color );
  28782. }
  28783. /*
  28784. const d = this.light.distance;
  28785. if ( d === 0.0 ) {
  28786. this.lightDistance.visible = false;
  28787. } else {
  28788. this.lightDistance.visible = true;
  28789. this.lightDistance.scale.set( d, d, d );
  28790. }
  28791. */
  28792. }
  28793. }
  28794. const _vector$1 = /*@__PURE__*/ new Vector3();
  28795. const _color1 = /*@__PURE__*/ new Color();
  28796. const _color2 = /*@__PURE__*/ new Color();
  28797. /**
  28798. * Creates a visual aid consisting of a spherical mesh for a
  28799. * given {@link HemisphereLight}.
  28800. *
  28801. * ```js
  28802. * const light = new THREE.HemisphereLight( 0xffffbb, 0x080820, 1 );
  28803. * const helper = new THREE.HemisphereLightHelper( light, 5 );
  28804. * scene.add( helper );
  28805. * ```
  28806. *
  28807. * @augments Object3D
  28808. */
  28809. class HemisphereLightHelper extends Object3D {
  28810. /**
  28811. * Constructs a new hemisphere light helper.
  28812. *
  28813. * @param {HemisphereLight} light - The light to be visualized.
  28814. * @param {number} [size=1] - The size of the mesh used to visualize the light.
  28815. * @param {number|Color|string} [color] - The helper's color. If not set, the helper will take
  28816. * the color of the light.
  28817. */
  28818. constructor( light, size, color ) {
  28819. super();
  28820. /**
  28821. * The light being visualized.
  28822. *
  28823. * @type {HemisphereLight}
  28824. */
  28825. this.light = light;
  28826. this.matrix = light.matrixWorld;
  28827. this.matrixAutoUpdate = false;
  28828. /**
  28829. * The color parameter passed in the constructor.
  28830. * If not set, the helper will take the color of the light.
  28831. *
  28832. * @type {number|Color|string}
  28833. */
  28834. this.color = color;
  28835. this.type = 'HemisphereLightHelper';
  28836. const geometry = new OctahedronGeometry( size );
  28837. geometry.rotateY( Math.PI * 0.5 );
  28838. this.material = new MeshBasicMaterial( { wireframe: true, fog: false, toneMapped: false } );
  28839. if ( this.color === undefined ) this.material.vertexColors = true;
  28840. const position = geometry.getAttribute( 'position' );
  28841. const colors = new Float32Array( position.count * 3 );
  28842. geometry.setAttribute( 'color', new BufferAttribute( colors, 3 ) );
  28843. this.add( new Mesh( geometry, this.material ) );
  28844. this.update();
  28845. }
  28846. /**
  28847. * Frees the GPU-related resources allocated by this instance. Call this
  28848. * method whenever this instance is no longer used in your app.
  28849. */
  28850. dispose() {
  28851. this.children[ 0 ].geometry.dispose();
  28852. this.children[ 0 ].material.dispose();
  28853. }
  28854. /**
  28855. * Updates the helper to match the position and direction of the
  28856. * light being visualized.
  28857. */
  28858. update() {
  28859. const mesh = this.children[ 0 ];
  28860. if ( this.color !== undefined ) {
  28861. this.material.color.set( this.color );
  28862. } else {
  28863. const colors = mesh.geometry.getAttribute( 'color' );
  28864. _color1.copy( this.light.color );
  28865. _color2.copy( this.light.groundColor );
  28866. for ( let i = 0, l = colors.count; i < l; i ++ ) {
  28867. const color = ( i < ( l / 2 ) ) ? _color1 : _color2;
  28868. colors.setXYZ( i, color.r, color.g, color.b );
  28869. }
  28870. colors.needsUpdate = true;
  28871. }
  28872. this.light.updateWorldMatrix( true, false );
  28873. mesh.lookAt( _vector$1.setFromMatrixPosition( this.light.matrixWorld ).negate() );
  28874. }
  28875. }
  28876. /**
  28877. * The helper is an object to define grids. Grids are two-dimensional
  28878. * arrays of lines.
  28879. *
  28880. * ```js
  28881. * const size = 10;
  28882. * const divisions = 10;
  28883. *
  28884. * const gridHelper = new THREE.GridHelper( size, divisions );
  28885. * scene.add( gridHelper );
  28886. * ```
  28887. *
  28888. * @augments LineSegments
  28889. */
  28890. class GridHelper extends LineSegments {
  28891. /**
  28892. * Constructs a new grid helper.
  28893. *
  28894. * @param {number} [size=10] - The size of the grid.
  28895. * @param {number} [divisions=10] - The number of divisions across the grid.
  28896. * @param {number|Color|string} [color1=0x444444] - The color of the center line.
  28897. * @param {number|Color|string} [color2=0x888888] - The color of the lines of the grid.
  28898. */
  28899. constructor( size = 10, divisions = 10, color1 = 0x444444, color2 = 0x888888 ) {
  28900. color1 = new Color( color1 );
  28901. color2 = new Color( color2 );
  28902. const center = divisions / 2;
  28903. const step = size / divisions;
  28904. const halfSize = size / 2;
  28905. const vertices = [], colors = [];
  28906. for ( let i = 0, j = 0, k = - halfSize; i <= divisions; i ++, k += step ) {
  28907. vertices.push( - halfSize, 0, k, halfSize, 0, k );
  28908. vertices.push( k, 0, - halfSize, k, 0, halfSize );
  28909. const color = i === center ? color1 : color2;
  28910. color.toArray( colors, j ); j += 3;
  28911. color.toArray( colors, j ); j += 3;
  28912. color.toArray( colors, j ); j += 3;
  28913. color.toArray( colors, j ); j += 3;
  28914. }
  28915. const geometry = new BufferGeometry();
  28916. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  28917. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  28918. const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
  28919. super( geometry, material );
  28920. this.type = 'GridHelper';
  28921. }
  28922. /**
  28923. * Frees the GPU-related resources allocated by this instance. Call this
  28924. * method whenever this instance is no longer used in your app.
  28925. */
  28926. dispose() {
  28927. this.geometry.dispose();
  28928. this.material.dispose();
  28929. }
  28930. }
  28931. /**
  28932. * This helper is an object to define polar grids. Grids are
  28933. * two-dimensional arrays of lines.
  28934. *
  28935. * ```js
  28936. * const radius = 10;
  28937. * const sectors = 16;
  28938. * const rings = 8;
  28939. * const divisions = 64;
  28940. *
  28941. * const helper = new THREE.PolarGridHelper( radius, sectors, rings, divisions );
  28942. * scene.add( helper );
  28943. * ```
  28944. *
  28945. * @augments LineSegments
  28946. */
  28947. class PolarGridHelper extends LineSegments {
  28948. /**
  28949. * Constructs a new polar grid helper.
  28950. *
  28951. * @param {number} [radius=10] - The radius of the polar grid. This can be any positive number.
  28952. * @param {number} [sectors=16] - The number of sectors the grid will be divided into. This can be any positive integer.
  28953. * @param {number} [rings=16] - The number of rings. This can be any positive integer.
  28954. * @param {number} [divisions=64] - The number of line segments used for each circle. This can be any positive integer.
  28955. * @param {number|Color|string} [color1=0x444444] - The first color used for grid elements.
  28956. * @param {number|Color|string} [color2=0x888888] - The second color used for grid elements.
  28957. */
  28958. constructor( radius = 10, sectors = 16, rings = 8, divisions = 64, color1 = 0x444444, color2 = 0x888888 ) {
  28959. color1 = new Color( color1 );
  28960. color2 = new Color( color2 );
  28961. const vertices = [];
  28962. const colors = [];
  28963. // create the sectors
  28964. if ( sectors > 1 ) {
  28965. for ( let i = 0; i < sectors; i ++ ) {
  28966. const v = ( i / sectors ) * ( Math.PI * 2 );
  28967. const x = Math.sin( v ) * radius;
  28968. const z = Math.cos( v ) * radius;
  28969. vertices.push( 0, 0, 0 );
  28970. vertices.push( x, 0, z );
  28971. const color = ( i & 1 ) ? color1 : color2;
  28972. colors.push( color.r, color.g, color.b );
  28973. colors.push( color.r, color.g, color.b );
  28974. }
  28975. }
  28976. // create the rings
  28977. for ( let i = 0; i < rings; i ++ ) {
  28978. const color = ( i & 1 ) ? color1 : color2;
  28979. const r = radius - ( radius / rings * i );
  28980. for ( let j = 0; j < divisions; j ++ ) {
  28981. // first vertex
  28982. let v = ( j / divisions ) * ( Math.PI * 2 );
  28983. let x = Math.sin( v ) * r;
  28984. let z = Math.cos( v ) * r;
  28985. vertices.push( x, 0, z );
  28986. colors.push( color.r, color.g, color.b );
  28987. // second vertex
  28988. v = ( ( j + 1 ) / divisions ) * ( Math.PI * 2 );
  28989. x = Math.sin( v ) * r;
  28990. z = Math.cos( v ) * r;
  28991. vertices.push( x, 0, z );
  28992. colors.push( color.r, color.g, color.b );
  28993. }
  28994. }
  28995. const geometry = new BufferGeometry();
  28996. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  28997. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  28998. const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
  28999. super( geometry, material );
  29000. this.type = 'PolarGridHelper';
  29001. }
  29002. /**
  29003. * Frees the GPU-related resources allocated by this instance. Call this
  29004. * method whenever this instance is no longer used in your app.
  29005. */
  29006. dispose() {
  29007. this.geometry.dispose();
  29008. this.material.dispose();
  29009. }
  29010. }
  29011. const _v1 = /*@__PURE__*/ new Vector3();
  29012. const _v2 = /*@__PURE__*/ new Vector3();
  29013. const _v3 = /*@__PURE__*/ new Vector3();
  29014. /**
  29015. * Helper object to assist with visualizing a {@link DirectionalLight}'s
  29016. * effect on the scene. This consists of plane and a line representing the
  29017. * light's position and direction.
  29018. *
  29019. * ```js
  29020. * const light = new THREE.DirectionalLight( 0xFFFFFF );
  29021. * scene.add( light );
  29022. *
  29023. * const helper = new THREE.DirectionalLightHelper( light, 5 );
  29024. * scene.add( helper );
  29025. * ```
  29026. *
  29027. * @augments Object3D
  29028. */
  29029. class DirectionalLightHelper extends Object3D {
  29030. /**
  29031. * Constructs a new directional light helper.
  29032. *
  29033. * @param {DirectionalLight} light - The light to be visualized.
  29034. * @param {number} [size=1] - The dimensions of the plane.
  29035. * @param {number|Color|string} [color] - The helper's color. If not set, the helper will take
  29036. * the color of the light.
  29037. */
  29038. constructor( light, size, color ) {
  29039. super();
  29040. /**
  29041. * The light being visualized.
  29042. *
  29043. * @type {DirectionalLight}
  29044. */
  29045. this.light = light;
  29046. this.matrix = light.matrixWorld;
  29047. this.matrixAutoUpdate = false;
  29048. /**
  29049. * The color parameter passed in the constructor.
  29050. * If not set, the helper will take the color of the light.
  29051. *
  29052. * @type {number|Color|string}
  29053. */
  29054. this.color = color;
  29055. this.type = 'DirectionalLightHelper';
  29056. if ( size === undefined ) size = 1;
  29057. let geometry = new BufferGeometry();
  29058. geometry.setAttribute( 'position', new Float32BufferAttribute( [
  29059. - size, size, 0,
  29060. size, size, 0,
  29061. size, - size, 0,
  29062. - size, - size, 0,
  29063. - size, size, 0
  29064. ], 3 ) );
  29065. const material = new LineBasicMaterial( { fog: false, toneMapped: false } );
  29066. /**
  29067. * Contains the line showing the location of the directional light.
  29068. *
  29069. * @type {Line}
  29070. */
  29071. this.lightPlane = new Line( geometry, material );
  29072. this.add( this.lightPlane );
  29073. geometry = new BufferGeometry();
  29074. geometry.setAttribute( 'position', new Float32BufferAttribute( [ 0, 0, 0, 0, 0, 1 ], 3 ) );
  29075. /**
  29076. * Represents the target line of the directional light.
  29077. *
  29078. * @type {Line}
  29079. */
  29080. this.targetLine = new Line( geometry, material );
  29081. this.add( this.targetLine );
  29082. this.update();
  29083. }
  29084. /**
  29085. * Frees the GPU-related resources allocated by this instance. Call this
  29086. * method whenever this instance is no longer used in your app.
  29087. */
  29088. dispose() {
  29089. this.lightPlane.geometry.dispose();
  29090. this.lightPlane.material.dispose();
  29091. this.targetLine.geometry.dispose();
  29092. this.targetLine.material.dispose();
  29093. }
  29094. /**
  29095. * Updates the helper to match the position and direction of the
  29096. * light being visualized.
  29097. */
  29098. update() {
  29099. this.light.updateWorldMatrix( true, false );
  29100. this.light.target.updateWorldMatrix( true, false );
  29101. _v1.setFromMatrixPosition( this.light.matrixWorld );
  29102. _v2.setFromMatrixPosition( this.light.target.matrixWorld );
  29103. _v3.subVectors( _v2, _v1 );
  29104. this.lightPlane.lookAt( _v2 );
  29105. if ( this.color !== undefined ) {
  29106. this.lightPlane.material.color.set( this.color );
  29107. this.targetLine.material.color.set( this.color );
  29108. } else {
  29109. this.lightPlane.material.color.copy( this.light.color );
  29110. this.targetLine.material.color.copy( this.light.color );
  29111. }
  29112. this.targetLine.lookAt( _v2 );
  29113. this.targetLine.scale.z = _v3.length();
  29114. }
  29115. }
  29116. const _vector = /*@__PURE__*/ new Vector3();
  29117. const _camera = /*@__PURE__*/ new Camera();
  29118. /**
  29119. * This helps with visualizing what a camera contains in its frustum. It
  29120. * visualizes the frustum of a camera using a line segments.
  29121. *
  29122. * Based on frustum visualization in [lightgl.js shadowmap example]{@link https://github.com/evanw/lightgl.js/blob/master/tests/shadowmap.html}.
  29123. *
  29124. * `CameraHelper` must be a child of the scene.
  29125. *
  29126. * ```js
  29127. * const camera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 0.1, 1000 );
  29128. * const helper = new THREE.CameraHelper( camera );
  29129. * scene.add( helper );
  29130. * ```
  29131. *
  29132. * @augments LineSegments
  29133. */
  29134. class CameraHelper extends LineSegments {
  29135. /**
  29136. * Constructs a new arror helper.
  29137. *
  29138. * @param {Camera} camera - The camera to visualize.
  29139. */
  29140. constructor( camera ) {
  29141. const geometry = new BufferGeometry();
  29142. const material = new LineBasicMaterial( { color: 0xffffff, vertexColors: true, toneMapped: false } );
  29143. const vertices = [];
  29144. const colors = [];
  29145. const pointMap = {};
  29146. // near
  29147. addLine( 'n1', 'n2' );
  29148. addLine( 'n2', 'n4' );
  29149. addLine( 'n4', 'n3' );
  29150. addLine( 'n3', 'n1' );
  29151. // far
  29152. addLine( 'f1', 'f2' );
  29153. addLine( 'f2', 'f4' );
  29154. addLine( 'f4', 'f3' );
  29155. addLine( 'f3', 'f1' );
  29156. // sides
  29157. addLine( 'n1', 'f1' );
  29158. addLine( 'n2', 'f2' );
  29159. addLine( 'n3', 'f3' );
  29160. addLine( 'n4', 'f4' );
  29161. // cone
  29162. addLine( 'p', 'n1' );
  29163. addLine( 'p', 'n2' );
  29164. addLine( 'p', 'n3' );
  29165. addLine( 'p', 'n4' );
  29166. // up
  29167. addLine( 'u1', 'u2' );
  29168. addLine( 'u2', 'u3' );
  29169. addLine( 'u3', 'u1' );
  29170. // target
  29171. addLine( 'c', 't' );
  29172. addLine( 'p', 'c' );
  29173. // cross
  29174. addLine( 'cn1', 'cn2' );
  29175. addLine( 'cn3', 'cn4' );
  29176. addLine( 'cf1', 'cf2' );
  29177. addLine( 'cf3', 'cf4' );
  29178. function addLine( a, b ) {
  29179. addPoint( a );
  29180. addPoint( b );
  29181. }
  29182. function addPoint( id ) {
  29183. vertices.push( 0, 0, 0 );
  29184. colors.push( 0, 0, 0 );
  29185. if ( pointMap[ id ] === undefined ) {
  29186. pointMap[ id ] = [];
  29187. }
  29188. pointMap[ id ].push( ( vertices.length / 3 ) - 1 );
  29189. }
  29190. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  29191. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  29192. super( geometry, material );
  29193. this.type = 'CameraHelper';
  29194. /**
  29195. * The camera being visualized.
  29196. *
  29197. * @type {Camera}
  29198. */
  29199. this.camera = camera;
  29200. if ( this.camera.updateProjectionMatrix ) this.camera.updateProjectionMatrix();
  29201. this.matrix = camera.matrixWorld;
  29202. this.matrixAutoUpdate = false;
  29203. /**
  29204. * This contains the points used to visualize the camera.
  29205. *
  29206. * @type {Object<string,Array<number>>}
  29207. */
  29208. this.pointMap = pointMap;
  29209. this.update();
  29210. // colors
  29211. const colorFrustum = new Color( 0xffaa00 );
  29212. const colorCone = new Color( 0xff0000 );
  29213. const colorUp = new Color( 0x00aaff );
  29214. const colorTarget = new Color( 0xffffff );
  29215. const colorCross = new Color( 0x333333 );
  29216. this.setColors( colorFrustum, colorCone, colorUp, colorTarget, colorCross );
  29217. }
  29218. /**
  29219. * Defines the colors of the helper.
  29220. *
  29221. * @param {Color} frustum - The frustum line color.
  29222. * @param {Color} cone - The cone line color.
  29223. * @param {Color} up - The up line color.
  29224. * @param {Color} target - The target line color.
  29225. * @param {Color} cross - The cross line color.
  29226. */
  29227. setColors( frustum, cone, up, target, cross ) {
  29228. const geometry = this.geometry;
  29229. const colorAttribute = geometry.getAttribute( 'color' );
  29230. // near
  29231. colorAttribute.setXYZ( 0, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 1, frustum.r, frustum.g, frustum.b ); // n1, n2
  29232. colorAttribute.setXYZ( 2, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 3, frustum.r, frustum.g, frustum.b ); // n2, n4
  29233. colorAttribute.setXYZ( 4, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 5, frustum.r, frustum.g, frustum.b ); // n4, n3
  29234. colorAttribute.setXYZ( 6, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 7, frustum.r, frustum.g, frustum.b ); // n3, n1
  29235. // far
  29236. colorAttribute.setXYZ( 8, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 9, frustum.r, frustum.g, frustum.b ); // f1, f2
  29237. colorAttribute.setXYZ( 10, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 11, frustum.r, frustum.g, frustum.b ); // f2, f4
  29238. colorAttribute.setXYZ( 12, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 13, frustum.r, frustum.g, frustum.b ); // f4, f3
  29239. colorAttribute.setXYZ( 14, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 15, frustum.r, frustum.g, frustum.b ); // f3, f1
  29240. // sides
  29241. colorAttribute.setXYZ( 16, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 17, frustum.r, frustum.g, frustum.b ); // n1, f1
  29242. colorAttribute.setXYZ( 18, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 19, frustum.r, frustum.g, frustum.b ); // n2, f2
  29243. colorAttribute.setXYZ( 20, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 21, frustum.r, frustum.g, frustum.b ); // n3, f3
  29244. colorAttribute.setXYZ( 22, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 23, frustum.r, frustum.g, frustum.b ); // n4, f4
  29245. // cone
  29246. colorAttribute.setXYZ( 24, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 25, cone.r, cone.g, cone.b ); // p, n1
  29247. colorAttribute.setXYZ( 26, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 27, cone.r, cone.g, cone.b ); // p, n2
  29248. colorAttribute.setXYZ( 28, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 29, cone.r, cone.g, cone.b ); // p, n3
  29249. colorAttribute.setXYZ( 30, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 31, cone.r, cone.g, cone.b ); // p, n4
  29250. // up
  29251. colorAttribute.setXYZ( 32, up.r, up.g, up.b ); colorAttribute.setXYZ( 33, up.r, up.g, up.b ); // u1, u2
  29252. colorAttribute.setXYZ( 34, up.r, up.g, up.b ); colorAttribute.setXYZ( 35, up.r, up.g, up.b ); // u2, u3
  29253. colorAttribute.setXYZ( 36, up.r, up.g, up.b ); colorAttribute.setXYZ( 37, up.r, up.g, up.b ); // u3, u1
  29254. // target
  29255. colorAttribute.setXYZ( 38, target.r, target.g, target.b ); colorAttribute.setXYZ( 39, target.r, target.g, target.b ); // c, t
  29256. colorAttribute.setXYZ( 40, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 41, cross.r, cross.g, cross.b ); // p, c
  29257. // cross
  29258. colorAttribute.setXYZ( 42, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 43, cross.r, cross.g, cross.b ); // cn1, cn2
  29259. colorAttribute.setXYZ( 44, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 45, cross.r, cross.g, cross.b ); // cn3, cn4
  29260. colorAttribute.setXYZ( 46, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 47, cross.r, cross.g, cross.b ); // cf1, cf2
  29261. colorAttribute.setXYZ( 48, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 49, cross.r, cross.g, cross.b ); // cf3, cf4
  29262. colorAttribute.needsUpdate = true;
  29263. }
  29264. /**
  29265. * Updates the helper based on the projection matrix of the camera.
  29266. */
  29267. update() {
  29268. const geometry = this.geometry;
  29269. const pointMap = this.pointMap;
  29270. const w = 1, h = 1;
  29271. // we need just camera projection matrix inverse
  29272. // world matrix must be identity
  29273. _camera.projectionMatrixInverse.copy( this.camera.projectionMatrixInverse );
  29274. // Adjust z values based on coordinate system
  29275. const nearZ = this.camera.coordinateSystem === WebGLCoordinateSystem ? -1 : 0;
  29276. // center / target
  29277. setPoint( 'c', pointMap, geometry, _camera, 0, 0, nearZ );
  29278. setPoint( 't', pointMap, geometry, _camera, 0, 0, 1 );
  29279. // near
  29280. setPoint( 'n1', pointMap, geometry, _camera, -1, -1, nearZ );
  29281. setPoint( 'n2', pointMap, geometry, _camera, w, -1, nearZ );
  29282. setPoint( 'n3', pointMap, geometry, _camera, -1, h, nearZ );
  29283. setPoint( 'n4', pointMap, geometry, _camera, w, h, nearZ );
  29284. // far
  29285. setPoint( 'f1', pointMap, geometry, _camera, -1, -1, 1 );
  29286. setPoint( 'f2', pointMap, geometry, _camera, w, -1, 1 );
  29287. setPoint( 'f3', pointMap, geometry, _camera, -1, h, 1 );
  29288. setPoint( 'f4', pointMap, geometry, _camera, w, h, 1 );
  29289. // up
  29290. setPoint( 'u1', pointMap, geometry, _camera, w * 0.7, h * 1.1, nearZ );
  29291. setPoint( 'u2', pointMap, geometry, _camera, -1 * 0.7, h * 1.1, nearZ );
  29292. setPoint( 'u3', pointMap, geometry, _camera, 0, h * 2, nearZ );
  29293. // cross
  29294. setPoint( 'cf1', pointMap, geometry, _camera, -1, 0, 1 );
  29295. setPoint( 'cf2', pointMap, geometry, _camera, w, 0, 1 );
  29296. setPoint( 'cf3', pointMap, geometry, _camera, 0, -1, 1 );
  29297. setPoint( 'cf4', pointMap, geometry, _camera, 0, h, 1 );
  29298. setPoint( 'cn1', pointMap, geometry, _camera, -1, 0, nearZ );
  29299. setPoint( 'cn2', pointMap, geometry, _camera, w, 0, nearZ );
  29300. setPoint( 'cn3', pointMap, geometry, _camera, 0, -1, nearZ );
  29301. setPoint( 'cn4', pointMap, geometry, _camera, 0, h, nearZ );
  29302. geometry.getAttribute( 'position' ).needsUpdate = true;
  29303. }
  29304. /**
  29305. * Frees the GPU-related resources allocated by this instance. Call this
  29306. * method whenever this instance is no longer used in your app.
  29307. */
  29308. dispose() {
  29309. this.geometry.dispose();
  29310. this.material.dispose();
  29311. }
  29312. }
  29313. function setPoint( point, pointMap, geometry, camera, x, y, z ) {
  29314. _vector.set( x, y, z ).unproject( camera );
  29315. const points = pointMap[ point ];
  29316. if ( points !== undefined ) {
  29317. const position = geometry.getAttribute( 'position' );
  29318. for ( let i = 0, l = points.length; i < l; i ++ ) {
  29319. position.setXYZ( points[ i ], _vector.x, _vector.y, _vector.z );
  29320. }
  29321. }
  29322. }
  29323. const _box = /*@__PURE__*/ new Box3();
  29324. /**
  29325. * Helper object to graphically show the world-axis-aligned bounding box
  29326. * around an object. The actual bounding box is handled with {@link Box3},
  29327. * this is just a visual helper for debugging. It can be automatically
  29328. * resized with {@link BoxHelper#update} when the object it's created from
  29329. * is transformed. Note that the object must have a geometry for this to work,
  29330. * so it won't work with sprites.
  29331. *
  29332. * ```js
  29333. * const sphere = new THREE.SphereGeometry();
  29334. * const object = new THREE.Mesh( sphere, new THREE.MeshBasicMaterial( 0xff0000 ) );
  29335. * const box = new THREE.BoxHelper( object, 0xffff00 );
  29336. * scene.add( box );
  29337. * ```
  29338. *
  29339. * @augments LineSegments
  29340. */
  29341. class BoxHelper extends LineSegments {
  29342. /**
  29343. * Constructs a new box helper.
  29344. *
  29345. * @param {Object3D} [object] - The 3D object to show the world-axis-aligned bounding box.
  29346. * @param {number|Color|string} [color=0xffff00] - The box's color.
  29347. */
  29348. constructor( object, color = 0xffff00 ) {
  29349. 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 ] );
  29350. const positions = new Float32Array( 8 * 3 );
  29351. const geometry = new BufferGeometry();
  29352. geometry.setIndex( new BufferAttribute( indices, 1 ) );
  29353. geometry.setAttribute( 'position', new BufferAttribute( positions, 3 ) );
  29354. super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  29355. /**
  29356. * The 3D object being visualized.
  29357. *
  29358. * @type {Object3D}
  29359. */
  29360. this.object = object;
  29361. this.type = 'BoxHelper';
  29362. this.matrixAutoUpdate = false;
  29363. this.update();
  29364. }
  29365. /**
  29366. * Updates the helper's geometry to match the dimensions of the object,
  29367. * including any children.
  29368. */
  29369. update() {
  29370. if ( this.object !== undefined ) {
  29371. _box.setFromObject( this.object );
  29372. }
  29373. if ( _box.isEmpty() ) return;
  29374. const min = _box.min;
  29375. const max = _box.max;
  29376. /*
  29377. 5____4
  29378. 1/___0/|
  29379. | 6__|_7
  29380. 2/___3/
  29381. 0: max.x, max.y, max.z
  29382. 1: min.x, max.y, max.z
  29383. 2: min.x, min.y, max.z
  29384. 3: max.x, min.y, max.z
  29385. 4: max.x, max.y, min.z
  29386. 5: min.x, max.y, min.z
  29387. 6: min.x, min.y, min.z
  29388. 7: max.x, min.y, min.z
  29389. */
  29390. const position = this.geometry.attributes.position;
  29391. const array = position.array;
  29392. array[ 0 ] = max.x; array[ 1 ] = max.y; array[ 2 ] = max.z;
  29393. array[ 3 ] = min.x; array[ 4 ] = max.y; array[ 5 ] = max.z;
  29394. array[ 6 ] = min.x; array[ 7 ] = min.y; array[ 8 ] = max.z;
  29395. array[ 9 ] = max.x; array[ 10 ] = min.y; array[ 11 ] = max.z;
  29396. array[ 12 ] = max.x; array[ 13 ] = max.y; array[ 14 ] = min.z;
  29397. array[ 15 ] = min.x; array[ 16 ] = max.y; array[ 17 ] = min.z;
  29398. array[ 18 ] = min.x; array[ 19 ] = min.y; array[ 20 ] = min.z;
  29399. array[ 21 ] = max.x; array[ 22 ] = min.y; array[ 23 ] = min.z;
  29400. position.needsUpdate = true;
  29401. this.geometry.computeBoundingSphere();
  29402. }
  29403. /**
  29404. * Updates the wireframe box for the passed object.
  29405. *
  29406. * @param {Object3D} object - The 3D object to create the helper for.
  29407. * @return {BoxHelper} A reference to this instance.
  29408. */
  29409. setFromObject( object ) {
  29410. this.object = object;
  29411. this.update();
  29412. return this;
  29413. }
  29414. copy( source, recursive ) {
  29415. super.copy( source, recursive );
  29416. this.object = source.object;
  29417. return this;
  29418. }
  29419. /**
  29420. * Frees the GPU-related resources allocated by this instance. Call this
  29421. * method whenever this instance is no longer used in your app.
  29422. */
  29423. dispose() {
  29424. this.geometry.dispose();
  29425. this.material.dispose();
  29426. }
  29427. }
  29428. /**
  29429. * A helper object to visualize an instance of {@link Box3}.
  29430. *
  29431. * ```js
  29432. * const box = new THREE.Box3();
  29433. * box.setFromCenterAndSize( new THREE.Vector3( 1, 1, 1 ), new THREE.Vector3( 2, 1, 3 ) );
  29434. *
  29435. * const helper = new THREE.Box3Helper( box, 0xffff00 );
  29436. * scene.add( helper )
  29437. * ```
  29438. *
  29439. * @augments LineSegments
  29440. */
  29441. class Box3Helper extends LineSegments {
  29442. /**
  29443. * Constructs a new box3 helper.
  29444. *
  29445. * @param {Box3} box - The box to visualize.
  29446. * @param {number|Color|string} [color=0xffff00] - The box's color.
  29447. */
  29448. constructor( box, color = 0xffff00 ) {
  29449. 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 ] );
  29450. 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 ];
  29451. const geometry = new BufferGeometry();
  29452. geometry.setIndex( new BufferAttribute( indices, 1 ) );
  29453. geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  29454. super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  29455. /**
  29456. * The box being visualized.
  29457. *
  29458. * @type {Box3}
  29459. */
  29460. this.box = box;
  29461. this.type = 'Box3Helper';
  29462. this.geometry.computeBoundingSphere();
  29463. }
  29464. updateMatrixWorld( force ) {
  29465. const box = this.box;
  29466. if ( box.isEmpty() ) return;
  29467. box.getCenter( this.position );
  29468. box.getSize( this.scale );
  29469. this.scale.multiplyScalar( 0.5 );
  29470. super.updateMatrixWorld( force );
  29471. }
  29472. /**
  29473. * Frees the GPU-related resources allocated by this instance. Call this
  29474. * method whenever this instance is no longer used in your app.
  29475. */
  29476. dispose() {
  29477. this.geometry.dispose();
  29478. this.material.dispose();
  29479. }
  29480. }
  29481. /**
  29482. * A helper object to visualize an instance of {@link Plane}.
  29483. *
  29484. * ```js
  29485. * const plane = new THREE.Plane( new THREE.Vector3( 1, 1, 0.2 ), 3 );
  29486. * const helper = new THREE.PlaneHelper( plane, 1, 0xffff00 );
  29487. * scene.add( helper );
  29488. * ```
  29489. *
  29490. * @augments Line
  29491. */
  29492. class PlaneHelper extends Line {
  29493. /**
  29494. * Constructs a new plane helper.
  29495. *
  29496. * @param {Plane} plane - The plane to be visualized.
  29497. * @param {number} [size=1] - The side length of plane helper.
  29498. * @param {number|Color|string} [hex=0xffff00] - The helper's color.
  29499. */
  29500. constructor( plane, size = 1, hex = 0xffff00 ) {
  29501. const color = hex;
  29502. 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 ];
  29503. const geometry = new BufferGeometry();
  29504. geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  29505. geometry.computeBoundingSphere();
  29506. super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  29507. this.type = 'PlaneHelper';
  29508. /**
  29509. * The plane being visualized.
  29510. *
  29511. * @type {Plane}
  29512. */
  29513. this.plane = plane;
  29514. /**
  29515. * The side length of plane helper.
  29516. *
  29517. * @type {number}
  29518. * @default 1
  29519. */
  29520. this.size = size;
  29521. const positions2 = [ 1, 1, 0, -1, 1, 0, -1, -1, 0, 1, 1, 0, -1, -1, 0, 1, -1, 0 ];
  29522. const geometry2 = new BufferGeometry();
  29523. geometry2.setAttribute( 'position', new Float32BufferAttribute( positions2, 3 ) );
  29524. geometry2.computeBoundingSphere();
  29525. this.add( new Mesh( geometry2, new MeshBasicMaterial( { color: color, opacity: 0.2, transparent: true, depthWrite: false, toneMapped: false } ) ) );
  29526. }
  29527. updateMatrixWorld( force ) {
  29528. this.position.set( 0, 0, 0 );
  29529. this.scale.set( 0.5 * this.size, 0.5 * this.size, 1 );
  29530. this.lookAt( this.plane.normal );
  29531. this.translateZ( - this.plane.constant );
  29532. super.updateMatrixWorld( force );
  29533. }
  29534. /**
  29535. * Updates the helper to match the position and direction of the
  29536. * light being visualized.
  29537. */
  29538. dispose() {
  29539. this.geometry.dispose();
  29540. this.material.dispose();
  29541. this.children[ 0 ].geometry.dispose();
  29542. this.children[ 0 ].material.dispose();
  29543. }
  29544. }
  29545. const _axis = /*@__PURE__*/ new Vector3();
  29546. let _lineGeometry, _coneGeometry;
  29547. /**
  29548. * An 3D arrow object for visualizing directions.
  29549. *
  29550. * ```js
  29551. * const dir = new THREE.Vector3( 1, 2, 0 );
  29552. *
  29553. * //normalize the direction vector (convert to vector of length 1)
  29554. * dir.normalize();
  29555. *
  29556. * const origin = new THREE.Vector3( 0, 0, 0 );
  29557. * const length = 1;
  29558. * const hex = 0xffff00;
  29559. *
  29560. * const arrowHelper = new THREE.ArrowHelper( dir, origin, length, hex );
  29561. * scene.add( arrowHelper );
  29562. * ```
  29563. *
  29564. * @augments Object3D
  29565. */
  29566. class ArrowHelper extends Object3D {
  29567. /**
  29568. * Constructs a new arror helper.
  29569. *
  29570. * @param {Vector3} [dir=(0, 0, 1)] - The (normalized) direction vector.
  29571. * @param {Vector3} [origin=(0, 0, 0)] - Point at which the arrow starts.
  29572. * @param {number} [length=1] - Length of the arrow in world units.
  29573. * @param {(number|Color|string)} [color=0xffff00] - Color of the arrow.
  29574. * @param {number} [headLength=length*0.2] - The length of the head of the arrow.
  29575. * @param {number} [headWidth=headLength*0.2] - The width of the head of the arrow.
  29576. */
  29577. 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 ) {
  29578. super();
  29579. this.type = 'ArrowHelper';
  29580. if ( _lineGeometry === undefined ) {
  29581. _lineGeometry = new BufferGeometry();
  29582. _lineGeometry.setAttribute( 'position', new Float32BufferAttribute( [ 0, 0, 0, 0, 1, 0 ], 3 ) );
  29583. _coneGeometry = new CylinderGeometry( 0, 0.5, 1, 5, 1 );
  29584. _coneGeometry.translate( 0, -0.5, 0 );
  29585. }
  29586. this.position.copy( origin );
  29587. /**
  29588. * The line part of the arrow helper.
  29589. *
  29590. * @type {Line}
  29591. */
  29592. this.line = new Line( _lineGeometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  29593. this.line.matrixAutoUpdate = false;
  29594. this.add( this.line );
  29595. /**
  29596. * The cone part of the arrow helper.
  29597. *
  29598. * @type {Mesh}
  29599. */
  29600. this.cone = new Mesh( _coneGeometry, new MeshBasicMaterial( { color: color, toneMapped: false } ) );
  29601. this.cone.matrixAutoUpdate = false;
  29602. this.add( this.cone );
  29603. this.setDirection( dir );
  29604. this.setLength( length, headLength, headWidth );
  29605. }
  29606. /**
  29607. * Sets the direction of the helper.
  29608. *
  29609. * @param {Vector3} dir - The normalized direction vector.
  29610. */
  29611. setDirection( dir ) {
  29612. // dir is assumed to be normalized
  29613. if ( dir.y > 0.99999 ) {
  29614. this.quaternion.set( 0, 0, 0, 1 );
  29615. } else if ( dir.y < -0.99999 ) {
  29616. this.quaternion.set( 1, 0, 0, 0 );
  29617. } else {
  29618. _axis.set( dir.z, 0, - dir.x ).normalize();
  29619. const radians = Math.acos( dir.y );
  29620. this.quaternion.setFromAxisAngle( _axis, radians );
  29621. }
  29622. }
  29623. /**
  29624. * Sets the length of the helper.
  29625. *
  29626. * @param {number} length - Length of the arrow in world units.
  29627. * @param {number} [headLength=length*0.2] - The length of the head of the arrow.
  29628. * @param {number} [headWidth=headLength*0.2] - The width of the head of the arrow.
  29629. */
  29630. setLength( length, headLength = length * 0.2, headWidth = headLength * 0.2 ) {
  29631. this.line.scale.set( 1, Math.max( 0.0001, length - headLength ), 1 ); // see #17458
  29632. this.line.updateMatrix();
  29633. this.cone.scale.set( headWidth, headLength, headWidth );
  29634. this.cone.position.y = length;
  29635. this.cone.updateMatrix();
  29636. }
  29637. /**
  29638. * Sets the color of the helper.
  29639. *
  29640. * @param {number|Color|string} color - The color to set.
  29641. */
  29642. setColor( color ) {
  29643. this.line.material.color.set( color );
  29644. this.cone.material.color.set( color );
  29645. }
  29646. copy( source ) {
  29647. super.copy( source, false );
  29648. this.line.copy( source.line );
  29649. this.cone.copy( source.cone );
  29650. return this;
  29651. }
  29652. /**
  29653. * Frees the GPU-related resources allocated by this instance. Call this
  29654. * method whenever this instance is no longer used in your app.
  29655. */
  29656. dispose() {
  29657. this.line.geometry.dispose();
  29658. this.line.material.dispose();
  29659. this.cone.geometry.dispose();
  29660. this.cone.material.dispose();
  29661. }
  29662. }
  29663. /**
  29664. * An axis object to visualize the 3 axes in a simple way.
  29665. * The X axis is red. The Y axis is green. The Z axis is blue.
  29666. *
  29667. * ```js
  29668. * const axesHelper = new THREE.AxesHelper( 5 );
  29669. * scene.add( axesHelper );
  29670. * ```
  29671. *
  29672. * @augments LineSegments
  29673. */
  29674. class AxesHelper extends LineSegments {
  29675. /**
  29676. * Constructs a new axes helper.
  29677. *
  29678. * @param {number} [size=1] - Size of the lines representing the axes.
  29679. */
  29680. constructor( size = 1 ) {
  29681. const vertices = [
  29682. 0, 0, 0, size, 0, 0,
  29683. 0, 0, 0, 0, size, 0,
  29684. 0, 0, 0, 0, 0, size
  29685. ];
  29686. const colors = [
  29687. 1, 0, 0, 1, 0.6, 0,
  29688. 0, 1, 0, 0.6, 1, 0,
  29689. 0, 0, 1, 0, 0.6, 1
  29690. ];
  29691. const geometry = new BufferGeometry();
  29692. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  29693. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  29694. const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
  29695. super( geometry, material );
  29696. this.type = 'AxesHelper';
  29697. }
  29698. /**
  29699. * Defines the colors of the axes helper.
  29700. *
  29701. * @param {number|Color|string} xAxisColor - The color for the x axis.
  29702. * @param {number|Color|string} yAxisColor - The color for the y axis.
  29703. * @param {number|Color|string} zAxisColor - The color for the z axis.
  29704. * @return {AxesHelper} A reference to this axes helper.
  29705. */
  29706. setColors( xAxisColor, yAxisColor, zAxisColor ) {
  29707. const color = new Color();
  29708. const array = this.geometry.attributes.color.array;
  29709. color.set( xAxisColor );
  29710. color.toArray( array, 0 );
  29711. color.toArray( array, 3 );
  29712. color.set( yAxisColor );
  29713. color.toArray( array, 6 );
  29714. color.toArray( array, 9 );
  29715. color.set( zAxisColor );
  29716. color.toArray( array, 12 );
  29717. color.toArray( array, 15 );
  29718. this.geometry.attributes.color.needsUpdate = true;
  29719. return this;
  29720. }
  29721. /**
  29722. * Frees the GPU-related resources allocated by this instance. Call this
  29723. * method whenever this instance is no longer used in your app.
  29724. */
  29725. dispose() {
  29726. this.geometry.dispose();
  29727. this.material.dispose();
  29728. }
  29729. }
  29730. /**
  29731. * This class is used to convert a series of paths to an array of
  29732. * shapes. It is specifically used in context of fonts and SVG.
  29733. */
  29734. class ShapePath {
  29735. /**
  29736. * Constructs a new shape path.
  29737. */
  29738. constructor() {
  29739. this.type = 'ShapePath';
  29740. /**
  29741. * The color of the shape.
  29742. *
  29743. * @type {Color}
  29744. */
  29745. this.color = new Color();
  29746. /**
  29747. * The paths that have been generated for this shape.
  29748. *
  29749. * @type {Array<Path>}
  29750. * @default null
  29751. */
  29752. this.subPaths = [];
  29753. /**
  29754. * The current path that is being generated.
  29755. *
  29756. * @type {?Path}
  29757. * @default null
  29758. */
  29759. this.currentPath = null;
  29760. }
  29761. /**
  29762. * Creates a new path and moves it current point to the given one.
  29763. *
  29764. * @param {number} x - The x coordinate.
  29765. * @param {number} y - The y coordinate.
  29766. * @return {ShapePath} A reference to this shape path.
  29767. */
  29768. moveTo( x, y ) {
  29769. this.currentPath = new Path();
  29770. this.subPaths.push( this.currentPath );
  29771. this.currentPath.moveTo( x, y );
  29772. return this;
  29773. }
  29774. /**
  29775. * Adds an instance of {@link LineCurve} to the path by connecting
  29776. * the current point with the given one.
  29777. *
  29778. * @param {number} x - The x coordinate of the end point.
  29779. * @param {number} y - The y coordinate of the end point.
  29780. * @return {ShapePath} A reference to this shape path.
  29781. */
  29782. lineTo( x, y ) {
  29783. this.currentPath.lineTo( x, y );
  29784. return this;
  29785. }
  29786. /**
  29787. * Adds an instance of {@link QuadraticBezierCurve} to the path by connecting
  29788. * the current point with the given one.
  29789. *
  29790. * @param {number} aCPx - The x coordinate of the control point.
  29791. * @param {number} aCPy - The y coordinate of the control point.
  29792. * @param {number} aX - The x coordinate of the end point.
  29793. * @param {number} aY - The y coordinate of the end point.
  29794. * @return {ShapePath} A reference to this shape path.
  29795. */
  29796. quadraticCurveTo( aCPx, aCPy, aX, aY ) {
  29797. this.currentPath.quadraticCurveTo( aCPx, aCPy, aX, aY );
  29798. return this;
  29799. }
  29800. /**
  29801. * Adds an instance of {@link CubicBezierCurve} to the path by connecting
  29802. * the current point with the given one.
  29803. *
  29804. * @param {number} aCP1x - The x coordinate of the first control point.
  29805. * @param {number} aCP1y - The y coordinate of the first control point.
  29806. * @param {number} aCP2x - The x coordinate of the second control point.
  29807. * @param {number} aCP2y - The y coordinate of the second control point.
  29808. * @param {number} aX - The x coordinate of the end point.
  29809. * @param {number} aY - The y coordinate of the end point.
  29810. * @return {ShapePath} A reference to this shape path.
  29811. */
  29812. bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) {
  29813. this.currentPath.bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY );
  29814. return this;
  29815. }
  29816. /**
  29817. * Adds an instance of {@link SplineCurve} to the path by connecting
  29818. * the current point with the given list of points.
  29819. *
  29820. * @param {Array<Vector2>} pts - An array of points in 2D space.
  29821. * @return {ShapePath} A reference to this shape path.
  29822. */
  29823. splineThru( pts ) {
  29824. this.currentPath.splineThru( pts );
  29825. return this;
  29826. }
  29827. /**
  29828. * Converts the paths into an array of shapes.
  29829. *
  29830. * @param {boolean} isCCW - By default solid shapes are defined clockwise (CW) and holes are defined counterclockwise (CCW).
  29831. * If this flag is set to `true`, then those are flipped.
  29832. * @return {Array<Shape>} An array of shapes.
  29833. */
  29834. toShapes( isCCW ) {
  29835. function toShapesNoHoles( inSubpaths ) {
  29836. const shapes = [];
  29837. for ( let i = 0, l = inSubpaths.length; i < l; i ++ ) {
  29838. const tmpPath = inSubpaths[ i ];
  29839. const tmpShape = new Shape();
  29840. tmpShape.curves = tmpPath.curves;
  29841. shapes.push( tmpShape );
  29842. }
  29843. return shapes;
  29844. }
  29845. function isPointInsidePolygon( inPt, inPolygon ) {
  29846. const polyLen = inPolygon.length;
  29847. // inPt on polygon contour => immediate success or
  29848. // toggling of inside/outside at every single! intersection point of an edge
  29849. // with the horizontal line through inPt, left of inPt
  29850. // not counting lowerY endpoints of edges and whole edges on that line
  29851. let inside = false;
  29852. for ( let p = polyLen - 1, q = 0; q < polyLen; p = q ++ ) {
  29853. let edgeLowPt = inPolygon[ p ];
  29854. let edgeHighPt = inPolygon[ q ];
  29855. let edgeDx = edgeHighPt.x - edgeLowPt.x;
  29856. let edgeDy = edgeHighPt.y - edgeLowPt.y;
  29857. if ( Math.abs( edgeDy ) > Number.EPSILON ) {
  29858. // not parallel
  29859. if ( edgeDy < 0 ) {
  29860. edgeLowPt = inPolygon[ q ]; edgeDx = - edgeDx;
  29861. edgeHighPt = inPolygon[ p ]; edgeDy = - edgeDy;
  29862. }
  29863. if ( ( inPt.y < edgeLowPt.y ) || ( inPt.y > edgeHighPt.y ) ) continue;
  29864. if ( inPt.y === edgeLowPt.y ) {
  29865. if ( inPt.x === edgeLowPt.x ) return true; // inPt is on contour ?
  29866. // continue; // no intersection or edgeLowPt => doesn't count !!!
  29867. } else {
  29868. const perpEdge = edgeDy * ( inPt.x - edgeLowPt.x ) - edgeDx * ( inPt.y - edgeLowPt.y );
  29869. if ( perpEdge === 0 ) return true; // inPt is on contour ?
  29870. if ( perpEdge < 0 ) continue;
  29871. inside = ! inside; // true intersection left of inPt
  29872. }
  29873. } else {
  29874. // parallel or collinear
  29875. if ( inPt.y !== edgeLowPt.y ) continue; // parallel
  29876. // edge lies on the same horizontal line as inPt
  29877. if ( ( ( edgeHighPt.x <= inPt.x ) && ( inPt.x <= edgeLowPt.x ) ) ||
  29878. ( ( edgeLowPt.x <= inPt.x ) && ( inPt.x <= edgeHighPt.x ) ) ) return true; // inPt: Point on contour !
  29879. // continue;
  29880. }
  29881. }
  29882. return inside;
  29883. }
  29884. const isClockWise = ShapeUtils.isClockWise;
  29885. const subPaths = this.subPaths;
  29886. if ( subPaths.length === 0 ) return [];
  29887. let solid, tmpPath, tmpShape;
  29888. const shapes = [];
  29889. if ( subPaths.length === 1 ) {
  29890. tmpPath = subPaths[ 0 ];
  29891. tmpShape = new Shape();
  29892. tmpShape.curves = tmpPath.curves;
  29893. shapes.push( tmpShape );
  29894. return shapes;
  29895. }
  29896. let holesFirst = ! isClockWise( subPaths[ 0 ].getPoints() );
  29897. holesFirst = isCCW ? ! holesFirst : holesFirst;
  29898. // console.log("Holes first", holesFirst);
  29899. const betterShapeHoles = [];
  29900. const newShapes = [];
  29901. let newShapeHoles = [];
  29902. let mainIdx = 0;
  29903. let tmpPoints;
  29904. newShapes[ mainIdx ] = undefined;
  29905. newShapeHoles[ mainIdx ] = [];
  29906. for ( let i = 0, l = subPaths.length; i < l; i ++ ) {
  29907. tmpPath = subPaths[ i ];
  29908. tmpPoints = tmpPath.getPoints();
  29909. solid = isClockWise( tmpPoints );
  29910. solid = isCCW ? ! solid : solid;
  29911. if ( solid ) {
  29912. if ( ( ! holesFirst ) && ( newShapes[ mainIdx ] ) ) mainIdx ++;
  29913. newShapes[ mainIdx ] = { s: new Shape(), p: tmpPoints };
  29914. newShapes[ mainIdx ].s.curves = tmpPath.curves;
  29915. if ( holesFirst ) mainIdx ++;
  29916. newShapeHoles[ mainIdx ] = [];
  29917. //console.log('cw', i);
  29918. } else {
  29919. newShapeHoles[ mainIdx ].push( { h: tmpPath, p: tmpPoints[ 0 ] } );
  29920. //console.log('ccw', i);
  29921. }
  29922. }
  29923. // only Holes? -> probably all Shapes with wrong orientation
  29924. if ( ! newShapes[ 0 ] ) return toShapesNoHoles( subPaths );
  29925. if ( newShapes.length > 1 ) {
  29926. let ambiguous = false;
  29927. let toChange = 0;
  29928. for ( let sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) {
  29929. betterShapeHoles[ sIdx ] = [];
  29930. }
  29931. for ( let sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) {
  29932. const sho = newShapeHoles[ sIdx ];
  29933. for ( let hIdx = 0; hIdx < sho.length; hIdx ++ ) {
  29934. const ho = sho[ hIdx ];
  29935. let hole_unassigned = true;
  29936. for ( let s2Idx = 0; s2Idx < newShapes.length; s2Idx ++ ) {
  29937. if ( isPointInsidePolygon( ho.p, newShapes[ s2Idx ].p ) ) {
  29938. if ( sIdx !== s2Idx ) toChange ++;
  29939. if ( hole_unassigned ) {
  29940. hole_unassigned = false;
  29941. betterShapeHoles[ s2Idx ].push( ho );
  29942. } else {
  29943. ambiguous = true;
  29944. }
  29945. }
  29946. }
  29947. if ( hole_unassigned ) {
  29948. betterShapeHoles[ sIdx ].push( ho );
  29949. }
  29950. }
  29951. }
  29952. if ( toChange > 0 && ambiguous === false ) {
  29953. newShapeHoles = betterShapeHoles;
  29954. }
  29955. }
  29956. let tmpHoles;
  29957. for ( let i = 0, il = newShapes.length; i < il; i ++ ) {
  29958. tmpShape = newShapes[ i ].s;
  29959. shapes.push( tmpShape );
  29960. tmpHoles = newShapeHoles[ i ];
  29961. for ( let j = 0, jl = tmpHoles.length; j < jl; j ++ ) {
  29962. tmpShape.holes.push( tmpHoles[ j ].h );
  29963. }
  29964. }
  29965. //console.log("shape", shapes);
  29966. return shapes;
  29967. }
  29968. }
  29969. /**
  29970. * Abstract base class for controls.
  29971. *
  29972. * @abstract
  29973. * @augments EventDispatcher
  29974. */
  29975. class Controls extends EventDispatcher {
  29976. /**
  29977. * Constructs a new controls instance.
  29978. *
  29979. * @param {Object3D} object - The object that is managed by the controls.
  29980. * @param {?HTMLDOMElement} domElement - The HTML element used for event listeners.
  29981. */
  29982. constructor( object, domElement = null ) {
  29983. super();
  29984. /**
  29985. * The object that is managed by the controls.
  29986. *
  29987. * @type {Object3D}
  29988. */
  29989. this.object = object;
  29990. /**
  29991. * The HTML element used for event listeners.
  29992. *
  29993. * @type {?HTMLDOMElement}
  29994. * @default null
  29995. */
  29996. this.domElement = domElement;
  29997. /**
  29998. * Whether the controls responds to user input or not.
  29999. *
  30000. * @type {boolean}
  30001. * @default true
  30002. */
  30003. this.enabled = true;
  30004. /**
  30005. * The internal state of the controls.
  30006. *
  30007. * @type {number}
  30008. * @default -1
  30009. */
  30010. this.state = -1;
  30011. /**
  30012. * This object defines the keyboard input of the controls.
  30013. *
  30014. * @type {Object}
  30015. */
  30016. this.keys = {};
  30017. /**
  30018. * This object defines what type of actions are assigned to the available mouse buttons.
  30019. * It depends on the control implementation what kind of mouse buttons and actions are supported.
  30020. *
  30021. * @type {{LEFT: ?number, MIDDLE: ?number, RIGHT: ?number}}
  30022. */
  30023. this.mouseButtons = { LEFT: null, MIDDLE: null, RIGHT: null };
  30024. /**
  30025. * This object defines what type of actions are assigned to what kind of touch interaction.
  30026. * It depends on the control implementation what kind of touch interaction and actions are supported.
  30027. *
  30028. * @type {{ONE: ?number, TWO: ?number}}
  30029. */
  30030. this.touches = { ONE: null, TWO: null };
  30031. }
  30032. /**
  30033. * Connects the controls to the DOM. This method has so called "side effects" since
  30034. * it adds the module's event listeners to the DOM.
  30035. */
  30036. connect() {}
  30037. /**
  30038. * Disconnects the controls from the DOM.
  30039. */
  30040. disconnect() {}
  30041. /**
  30042. * Call this method if you no longer want use to the controls. It frees all internal
  30043. * resources and removes all event listeners.
  30044. */
  30045. dispose() {}
  30046. /**
  30047. * Controls should implement this method if they have to update their internal state
  30048. * per simulation step.
  30049. *
  30050. * @param {number} [delta] - The time delta in seconds.
  30051. */
  30052. update( /* delta */ ) {}
  30053. }
  30054. /**
  30055. * Scales the texture as large as possible within its surface without cropping
  30056. * or stretching the texture. The method preserves the original aspect ratio of
  30057. * the texture. Akin to CSS `object-fit: contain`
  30058. *
  30059. * @param {Texture} texture - The texture.
  30060. * @param {number} aspect - The texture's aspect ratio.
  30061. * @return {Texture} The updated texture.
  30062. */
  30063. function contain( texture, aspect ) {
  30064. const imageAspect = ( texture.image && texture.image.width ) ? texture.image.width / texture.image.height : 1;
  30065. if ( imageAspect > aspect ) {
  30066. texture.repeat.x = 1;
  30067. texture.repeat.y = imageAspect / aspect;
  30068. texture.offset.x = 0;
  30069. texture.offset.y = ( 1 - texture.repeat.y ) / 2;
  30070. } else {
  30071. texture.repeat.x = aspect / imageAspect;
  30072. texture.repeat.y = 1;
  30073. texture.offset.x = ( 1 - texture.repeat.x ) / 2;
  30074. texture.offset.y = 0;
  30075. }
  30076. return texture;
  30077. }
  30078. /**
  30079. * Scales the texture to the smallest possible size to fill the surface, leaving
  30080. * no empty space. The method preserves the original aspect ratio of the texture.
  30081. * Akin to CSS `object-fit: cover`.
  30082. *
  30083. * @param {Texture} texture - The texture.
  30084. * @param {number} aspect - The texture's aspect ratio.
  30085. * @return {Texture} The updated texture.
  30086. */
  30087. function cover( texture, aspect ) {
  30088. const imageAspect = ( texture.image && texture.image.width ) ? texture.image.width / texture.image.height : 1;
  30089. if ( imageAspect > aspect ) {
  30090. texture.repeat.x = aspect / imageAspect;
  30091. texture.repeat.y = 1;
  30092. texture.offset.x = ( 1 - texture.repeat.x ) / 2;
  30093. texture.offset.y = 0;
  30094. } else {
  30095. texture.repeat.x = 1;
  30096. texture.repeat.y = imageAspect / aspect;
  30097. texture.offset.x = 0;
  30098. texture.offset.y = ( 1 - texture.repeat.y ) / 2;
  30099. }
  30100. return texture;
  30101. }
  30102. /**
  30103. * Configures the texture to the default transformation. Akin to CSS `object-fit: fill`.
  30104. *
  30105. * @param {Texture} texture - The texture.
  30106. * @return {Texture} The updated texture.
  30107. */
  30108. function fill( texture ) {
  30109. texture.repeat.x = 1;
  30110. texture.repeat.y = 1;
  30111. texture.offset.x = 0;
  30112. texture.offset.y = 0;
  30113. return texture;
  30114. }
  30115. /**
  30116. * Determines how many bytes must be used to represent the texture.
  30117. *
  30118. * @param {number} width - The width of the texture.
  30119. * @param {number} height - The height of the texture.
  30120. * @param {number} format - The texture's format.
  30121. * @param {number} type - The texture's type.
  30122. * @return {number} The byte length.
  30123. */
  30124. function getByteLength( width, height, format, type ) {
  30125. const typeByteLength = getTextureTypeByteLength( type );
  30126. switch ( format ) {
  30127. // https://registry.khronos.org/OpenGL-Refpages/es3.0/html/glTexImage2D.xhtml
  30128. case AlphaFormat:
  30129. return width * height;
  30130. case LuminanceFormat:
  30131. return width * height;
  30132. case LuminanceAlphaFormat:
  30133. return width * height * 2;
  30134. case RedFormat:
  30135. return ( ( width * height ) / typeByteLength.components ) * typeByteLength.byteLength;
  30136. case RedIntegerFormat:
  30137. return ( ( width * height ) / typeByteLength.components ) * typeByteLength.byteLength;
  30138. case RGFormat:
  30139. return ( ( width * height * 2 ) / typeByteLength.components ) * typeByteLength.byteLength;
  30140. case RGIntegerFormat:
  30141. return ( ( width * height * 2 ) / typeByteLength.components ) * typeByteLength.byteLength;
  30142. case RGBFormat:
  30143. return ( ( width * height * 3 ) / typeByteLength.components ) * typeByteLength.byteLength;
  30144. case RGBAFormat:
  30145. return ( ( width * height * 4 ) / typeByteLength.components ) * typeByteLength.byteLength;
  30146. case RGBAIntegerFormat:
  30147. return ( ( width * height * 4 ) / typeByteLength.components ) * typeByteLength.byteLength;
  30148. // https://registry.khronos.org/webgl/extensions/WEBGL_compressed_texture_s3tc_srgb/
  30149. case RGB_S3TC_DXT1_Format:
  30150. case RGBA_S3TC_DXT1_Format:
  30151. return Math.floor( ( width + 3 ) / 4 ) * Math.floor( ( height + 3 ) / 4 ) * 8;
  30152. case RGBA_S3TC_DXT3_Format:
  30153. case RGBA_S3TC_DXT5_Format:
  30154. return Math.floor( ( width + 3 ) / 4 ) * Math.floor( ( height + 3 ) / 4 ) * 16;
  30155. // https://registry.khronos.org/webgl/extensions/WEBGL_compressed_texture_pvrtc/
  30156. case RGB_PVRTC_2BPPV1_Format:
  30157. case RGBA_PVRTC_2BPPV1_Format:
  30158. return ( Math.max( width, 16 ) * Math.max( height, 8 ) ) / 4;
  30159. case RGB_PVRTC_4BPPV1_Format:
  30160. case RGBA_PVRTC_4BPPV1_Format:
  30161. return ( Math.max( width, 8 ) * Math.max( height, 8 ) ) / 2;
  30162. // https://registry.khronos.org/webgl/extensions/WEBGL_compressed_texture_etc/
  30163. case RGB_ETC1_Format:
  30164. case RGB_ETC2_Format:
  30165. return Math.floor( ( width + 3 ) / 4 ) * Math.floor( ( height + 3 ) / 4 ) * 8;
  30166. case RGBA_ETC2_EAC_Format:
  30167. return Math.floor( ( width + 3 ) / 4 ) * Math.floor( ( height + 3 ) / 4 ) * 16;
  30168. // https://registry.khronos.org/webgl/extensions/WEBGL_compressed_texture_astc/
  30169. case RGBA_ASTC_4x4_Format:
  30170. return Math.floor( ( width + 3 ) / 4 ) * Math.floor( ( height + 3 ) / 4 ) * 16;
  30171. case RGBA_ASTC_5x4_Format:
  30172. return Math.floor( ( width + 4 ) / 5 ) * Math.floor( ( height + 3 ) / 4 ) * 16;
  30173. case RGBA_ASTC_5x5_Format:
  30174. return Math.floor( ( width + 4 ) / 5 ) * Math.floor( ( height + 4 ) / 5 ) * 16;
  30175. case RGBA_ASTC_6x5_Format:
  30176. return Math.floor( ( width + 5 ) / 6 ) * Math.floor( ( height + 4 ) / 5 ) * 16;
  30177. case RGBA_ASTC_6x6_Format:
  30178. return Math.floor( ( width + 5 ) / 6 ) * Math.floor( ( height + 5 ) / 6 ) * 16;
  30179. case RGBA_ASTC_8x5_Format:
  30180. return Math.floor( ( width + 7 ) / 8 ) * Math.floor( ( height + 4 ) / 5 ) * 16;
  30181. case RGBA_ASTC_8x6_Format:
  30182. return Math.floor( ( width + 7 ) / 8 ) * Math.floor( ( height + 5 ) / 6 ) * 16;
  30183. case RGBA_ASTC_8x8_Format:
  30184. return Math.floor( ( width + 7 ) / 8 ) * Math.floor( ( height + 7 ) / 8 ) * 16;
  30185. case RGBA_ASTC_10x5_Format:
  30186. return Math.floor( ( width + 9 ) / 10 ) * Math.floor( ( height + 4 ) / 5 ) * 16;
  30187. case RGBA_ASTC_10x6_Format:
  30188. return Math.floor( ( width + 9 ) / 10 ) * Math.floor( ( height + 5 ) / 6 ) * 16;
  30189. case RGBA_ASTC_10x8_Format:
  30190. return Math.floor( ( width + 9 ) / 10 ) * Math.floor( ( height + 7 ) / 8 ) * 16;
  30191. case RGBA_ASTC_10x10_Format:
  30192. return Math.floor( ( width + 9 ) / 10 ) * Math.floor( ( height + 9 ) / 10 ) * 16;
  30193. case RGBA_ASTC_12x10_Format:
  30194. return Math.floor( ( width + 11 ) / 12 ) * Math.floor( ( height + 9 ) / 10 ) * 16;
  30195. case RGBA_ASTC_12x12_Format:
  30196. return Math.floor( ( width + 11 ) / 12 ) * Math.floor( ( height + 11 ) / 12 ) * 16;
  30197. // https://registry.khronos.org/webgl/extensions/EXT_texture_compression_bptc/
  30198. case RGBA_BPTC_Format:
  30199. case RGB_BPTC_SIGNED_Format:
  30200. case RGB_BPTC_UNSIGNED_Format:
  30201. return Math.ceil( width / 4 ) * Math.ceil( height / 4 ) * 16;
  30202. // https://registry.khronos.org/webgl/extensions/EXT_texture_compression_rgtc/
  30203. case RED_RGTC1_Format:
  30204. case SIGNED_RED_RGTC1_Format:
  30205. return Math.ceil( width / 4 ) * Math.ceil( height / 4 ) * 8;
  30206. case RED_GREEN_RGTC2_Format:
  30207. case SIGNED_RED_GREEN_RGTC2_Format:
  30208. return Math.ceil( width / 4 ) * Math.ceil( height / 4 ) * 16;
  30209. }
  30210. throw new Error(
  30211. `Unable to determine texture byte length for ${format} format.`,
  30212. );
  30213. }
  30214. function getTextureTypeByteLength( type ) {
  30215. switch ( type ) {
  30216. case UnsignedByteType:
  30217. case ByteType:
  30218. return { byteLength: 1, components: 1 };
  30219. case UnsignedShortType:
  30220. case ShortType:
  30221. case HalfFloatType:
  30222. return { byteLength: 2, components: 1 };
  30223. case UnsignedShort4444Type:
  30224. case UnsignedShort5551Type:
  30225. return { byteLength: 2, components: 4 };
  30226. case UnsignedIntType:
  30227. case IntType:
  30228. case FloatType:
  30229. return { byteLength: 4, components: 1 };
  30230. case UnsignedInt5999Type:
  30231. return { byteLength: 4, components: 3 };
  30232. }
  30233. throw new Error( `Unknown texture type ${type}.` );
  30234. }
  30235. /**
  30236. * A class containing utility functions for textures.
  30237. *
  30238. * @hideconstructor
  30239. */
  30240. class TextureUtils {
  30241. /**
  30242. * Scales the texture as large as possible within its surface without cropping
  30243. * or stretching the texture. The method preserves the original aspect ratio of
  30244. * the texture. Akin to CSS `object-fit: contain`
  30245. *
  30246. * @param {Texture} texture - The texture.
  30247. * @param {number} aspect - The texture's aspect ratio.
  30248. * @return {Texture} The updated texture.
  30249. */
  30250. static contain( texture, aspect ) {
  30251. return contain( texture, aspect );
  30252. }
  30253. /**
  30254. * Scales the texture to the smallest possible size to fill the surface, leaving
  30255. * no empty space. The method preserves the original aspect ratio of the texture.
  30256. * Akin to CSS `object-fit: cover`.
  30257. *
  30258. * @param {Texture} texture - The texture.
  30259. * @param {number} aspect - The texture's aspect ratio.
  30260. * @return {Texture} The updated texture.
  30261. */
  30262. static cover( texture, aspect ) {
  30263. return cover( texture, aspect );
  30264. }
  30265. /**
  30266. * Configures the texture to the default transformation. Akin to CSS `object-fit: fill`.
  30267. *
  30268. * @param {Texture} texture - The texture.
  30269. * @return {Texture} The updated texture.
  30270. */
  30271. static fill( texture ) {
  30272. return fill( texture );
  30273. }
  30274. /**
  30275. * Determines how many bytes must be used to represent the texture.
  30276. *
  30277. * @param {number} width - The width of the texture.
  30278. * @param {number} height - The height of the texture.
  30279. * @param {number} format - The texture's format.
  30280. * @param {number} type - The texture's type.
  30281. * @return {number} The byte length.
  30282. */
  30283. static getByteLength( width, height, format, type ) {
  30284. return getByteLength( width, height, format, type );
  30285. }
  30286. }
  30287. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  30288. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'register', { detail: {
  30289. revision: REVISION,
  30290. } } ) );
  30291. }
  30292. if ( typeof window !== 'undefined' ) {
  30293. if ( window.__THREE__ ) {
  30294. console.warn( 'WARNING: Multiple instances of Three.js being imported.' );
  30295. } else {
  30296. window.__THREE__ = REVISION;
  30297. }
  30298. }
  30299. export { ACESFilmicToneMapping, AddEquation, AddOperation, AdditiveAnimationBlendMode, AdditiveBlending, AgXToneMapping, AlphaFormat, AlwaysCompare, AlwaysDepth, AlwaysStencilFunc, AmbientLight, AnimationAction, AnimationClip, AnimationLoader, AnimationMixer, AnimationObjectGroup, AnimationUtils, ArcCurve, ArrayCamera, ArrowHelper, AttachedBindMode, Audio, AudioAnalyser, AudioContext, AudioListener, AudioLoader, AxesHelper, BackSide, BasicDepthPacking, BasicShadowMap, BatchedMesh, Bone, BooleanKeyframeTrack, Box2, Box3, Box3Helper, BoxGeometry, BoxHelper, BufferAttribute, BufferGeometry, BufferGeometryLoader, ByteType, Cache, Camera, CameraHelper, CanvasTexture, CapsuleGeometry, CatmullRomCurve3, CineonToneMapping, CircleGeometry, ClampToEdgeWrapping, Clock, Color, ColorKeyframeTrack, ColorManagement, CompressedArrayTexture, CompressedCubeTexture, CompressedTexture, CompressedTextureLoader, ConeGeometry, ConstantAlphaFactor, ConstantColorFactor, Controls, CubeCamera, CubeReflectionMapping, CubeRefractionMapping, CubeTexture, CubeTextureLoader, CubeUVReflectionMapping, CubicBezierCurve, CubicBezierCurve3, CubicInterpolant, CullFaceBack, CullFaceFront, CullFaceFrontBack, CullFaceNone, Curve, CurvePath, CustomBlending, CustomToneMapping, CylinderGeometry, Cylindrical, Data3DTexture, DataArrayTexture, DataTexture, DataTextureLoader, DataUtils, DecrementStencilOp, DecrementWrapStencilOp, DefaultLoadingManager, DepthFormat, DepthStencilFormat, DepthTexture, DetachedBindMode, DirectionalLight, DirectionalLightHelper, DiscreteInterpolant, DodecahedronGeometry, DoubleSide, DstAlphaFactor, DstColorFactor, DynamicCopyUsage, DynamicDrawUsage, DynamicReadUsage, EdgesGeometry, EllipseCurve, EqualCompare, EqualDepth, EqualStencilFunc, EquirectangularReflectionMapping, EquirectangularRefractionMapping, Euler, EventDispatcher, ExtrudeGeometry, FileLoader, Float16BufferAttribute, Float32BufferAttribute, FloatType, Fog, FogExp2, FramebufferTexture, FrontSide, Frustum, GLBufferAttribute, GLSL1, GLSL3, GreaterCompare, GreaterDepth, GreaterEqualCompare, GreaterEqualDepth, GreaterEqualStencilFunc, GreaterStencilFunc, GridHelper, Group, HalfFloatType, HemisphereLight, HemisphereLightHelper, IcosahedronGeometry, ImageBitmapLoader, ImageLoader, ImageUtils, IncrementStencilOp, IncrementWrapStencilOp, InstancedBufferAttribute, InstancedBufferGeometry, InstancedInterleavedBuffer, InstancedMesh, Int16BufferAttribute, Int32BufferAttribute, Int8BufferAttribute, IntType, InterleavedBuffer, InterleavedBufferAttribute, Interpolant, InterpolateDiscrete, InterpolateLinear, InterpolateSmooth, InvertStencilOp, KeepStencilOp, KeyframeTrack, LOD, LatheGeometry, Layers, LessCompare, LessDepth, LessEqualCompare, LessEqualDepth, LessEqualStencilFunc, LessStencilFunc, Light, LightProbe, Line, Line3, LineBasicMaterial, LineCurve, LineCurve3, LineDashedMaterial, LineLoop, LineSegments, LinearFilter, LinearInterpolant, LinearMipMapLinearFilter, LinearMipMapNearestFilter, LinearMipmapLinearFilter, LinearMipmapNearestFilter, LinearSRGBColorSpace, LinearToneMapping, LinearTransfer, Loader, LoaderUtils, LoadingManager, LoopOnce, LoopPingPong, LoopRepeat, LuminanceAlphaFormat, LuminanceFormat, MOUSE, Material, MaterialLoader, MathUtils, Matrix2, Matrix3, Matrix4, MaxEquation, Mesh, MeshBasicMaterial, MeshDepthMaterial, MeshDistanceMaterial, MeshLambertMaterial, MeshMatcapMaterial, MeshNormalMaterial, MeshPhongMaterial, MeshPhysicalMaterial, MeshStandardMaterial, MeshToonMaterial, MinEquation, MirroredRepeatWrapping, MixOperation, MultiplyBlending, MultiplyOperation, NearestFilter, NearestMipMapLinearFilter, NearestMipMapNearestFilter, NearestMipmapLinearFilter, NearestMipmapNearestFilter, NeutralToneMapping, NeverCompare, NeverDepth, NeverStencilFunc, NoBlending, NoColorSpace, NoToneMapping, NormalAnimationBlendMode, NormalBlending, NotEqualCompare, NotEqualDepth, NotEqualStencilFunc, NumberKeyframeTrack, Object3D, ObjectLoader, ObjectSpaceNormalMap, OctahedronGeometry, OneFactor, OneMinusConstantAlphaFactor, OneMinusConstantColorFactor, OneMinusDstAlphaFactor, OneMinusDstColorFactor, OneMinusSrcAlphaFactor, OneMinusSrcColorFactor, OrthographicCamera, PCFShadowMap, PCFSoftShadowMap, Path, PerspectiveCamera, Plane, PlaneGeometry, PlaneHelper, PointLight, PointLightHelper, Points, PointsMaterial, PolarGridHelper, PolyhedronGeometry, PositionalAudio, PropertyBinding, PropertyMixer, QuadraticBezierCurve, QuadraticBezierCurve3, Quaternion, QuaternionKeyframeTrack, QuaternionLinearInterpolant, RAD2DEG, RED_GREEN_RGTC2_Format, RED_RGTC1_Format, REVISION, RGBADepthPacking, RGBAFormat, RGBAIntegerFormat, RGBA_ASTC_10x10_Format, RGBA_ASTC_10x5_Format, RGBA_ASTC_10x6_Format, RGBA_ASTC_10x8_Format, RGBA_ASTC_12x10_Format, RGBA_ASTC_12x12_Format, RGBA_ASTC_4x4_Format, RGBA_ASTC_5x4_Format, RGBA_ASTC_5x5_Format, RGBA_ASTC_6x5_Format, RGBA_ASTC_6x6_Format, RGBA_ASTC_8x5_Format, RGBA_ASTC_8x6_Format, RGBA_ASTC_8x8_Format, RGBA_BPTC_Format, RGBA_ETC2_EAC_Format, RGBA_PVRTC_2BPPV1_Format, RGBA_PVRTC_4BPPV1_Format, RGBA_S3TC_DXT1_Format, RGBA_S3TC_DXT3_Format, RGBA_S3TC_DXT5_Format, RGBDepthPacking, RGBFormat, RGBIntegerFormat, RGB_BPTC_SIGNED_Format, RGB_BPTC_UNSIGNED_Format, RGB_ETC1_Format, RGB_ETC2_Format, RGB_PVRTC_2BPPV1_Format, RGB_PVRTC_4BPPV1_Format, RGB_S3TC_DXT1_Format, RGDepthPacking, RGFormat, RGIntegerFormat, RawShaderMaterial, Ray, Raycaster, RectAreaLight, RedFormat, RedIntegerFormat, ReinhardToneMapping, RenderTarget, RenderTarget3D, RenderTargetArray, RepeatWrapping, ReplaceStencilOp, ReverseSubtractEquation, RingGeometry, SIGNED_RED_GREEN_RGTC2_Format, SIGNED_RED_RGTC1_Format, SRGBColorSpace, SRGBTransfer, Scene, ShaderMaterial, ShadowMaterial, Shape, ShapeGeometry, ShapePath, ShapeUtils, ShortType, Skeleton, SkeletonHelper, SkinnedMesh, Source, Sphere, SphereGeometry, Spherical, SphericalHarmonics3, SplineCurve, SpotLight, SpotLightHelper, Sprite, SpriteMaterial, SrcAlphaFactor, SrcAlphaSaturateFactor, SrcColorFactor, StaticCopyUsage, StaticDrawUsage, StaticReadUsage, StereoCamera, StreamCopyUsage, StreamDrawUsage, StreamReadUsage, StringKeyframeTrack, SubtractEquation, SubtractiveBlending, TOUCH, TangentSpaceNormalMap, TetrahedronGeometry, Texture, TextureLoader, TextureUtils, TimestampQuery, TorusGeometry, TorusKnotGeometry, Triangle, TriangleFanDrawMode, TriangleStripDrawMode, TrianglesDrawMode, TubeGeometry, UVMapping, Uint16BufferAttribute, Uint32BufferAttribute, Uint8BufferAttribute, Uint8ClampedBufferAttribute, Uniform, UniformsGroup, UniformsUtils, UnsignedByteType, UnsignedInt248Type, UnsignedInt5999Type, UnsignedIntType, UnsignedShort4444Type, UnsignedShort5551Type, UnsignedShortType, VSMShadowMap, Vector2, Vector3, Vector4, VectorKeyframeTrack, VideoFrameTexture, VideoTexture, WebGL3DRenderTarget, WebGLArrayRenderTarget, WebGLCoordinateSystem, WebGLCubeRenderTarget, WebGLRenderTarget, WebGPUCoordinateSystem, WebXRController, WireframeGeometry, WrapAroundEnding, ZeroCurvatureEnding, ZeroFactor, ZeroSlopeEnding, ZeroStencilOp, arrayNeedsUint32, cloneUniforms, createCanvasElement, createElementNS, getByteLength, getUnlitUniformColorSpace, mergeUniforms, probeAsync, toNormalizedProjectionMatrix, toReversedProjectionMatrix, warnOnce };
粤ICP备19079148号