three.js 1.2 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598
  1. /**
  2. * @license
  3. * Copyright 2010-2023 Three.js Authors
  4. * SPDX-License-Identifier: MIT
  5. */
  6. (function (global, factory) {
  7. typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
  8. typeof define === 'function' && define.amd ? define(['exports'], factory) :
  9. (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.THREE = {}));
  10. })(this, (function (exports) { 'use strict';
  11. const REVISION = '149';
  12. const MOUSE = { LEFT: 0, MIDDLE: 1, RIGHT: 2, ROTATE: 0, DOLLY: 1, PAN: 2 };
  13. const TOUCH = { ROTATE: 0, PAN: 1, DOLLY_PAN: 2, DOLLY_ROTATE: 3 };
  14. const CullFaceNone = 0;
  15. const CullFaceBack = 1;
  16. const CullFaceFront = 2;
  17. const CullFaceFrontBack = 3;
  18. const BasicShadowMap = 0;
  19. const PCFShadowMap = 1;
  20. const PCFSoftShadowMap = 2;
  21. const VSMShadowMap = 3;
  22. const FrontSide = 0;
  23. const BackSide = 1;
  24. const DoubleSide = 2;
  25. const TwoPassDoubleSide = 2; // r149
  26. const NoBlending = 0;
  27. const NormalBlending = 1;
  28. const AdditiveBlending = 2;
  29. const SubtractiveBlending = 3;
  30. const MultiplyBlending = 4;
  31. const CustomBlending = 5;
  32. const AddEquation = 100;
  33. const SubtractEquation = 101;
  34. const ReverseSubtractEquation = 102;
  35. const MinEquation = 103;
  36. const MaxEquation = 104;
  37. const ZeroFactor = 200;
  38. const OneFactor = 201;
  39. const SrcColorFactor = 202;
  40. const OneMinusSrcColorFactor = 203;
  41. const SrcAlphaFactor = 204;
  42. const OneMinusSrcAlphaFactor = 205;
  43. const DstAlphaFactor = 206;
  44. const OneMinusDstAlphaFactor = 207;
  45. const DstColorFactor = 208;
  46. const OneMinusDstColorFactor = 209;
  47. const SrcAlphaSaturateFactor = 210;
  48. const NeverDepth = 0;
  49. const AlwaysDepth = 1;
  50. const LessDepth = 2;
  51. const LessEqualDepth = 3;
  52. const EqualDepth = 4;
  53. const GreaterEqualDepth = 5;
  54. const GreaterDepth = 6;
  55. const NotEqualDepth = 7;
  56. const MultiplyOperation = 0;
  57. const MixOperation = 1;
  58. const AddOperation = 2;
  59. const NoToneMapping = 0;
  60. const LinearToneMapping = 1;
  61. const ReinhardToneMapping = 2;
  62. const CineonToneMapping = 3;
  63. const ACESFilmicToneMapping = 4;
  64. const CustomToneMapping = 5;
  65. const UVMapping = 300;
  66. const CubeReflectionMapping = 301;
  67. const CubeRefractionMapping = 302;
  68. const EquirectangularReflectionMapping = 303;
  69. const EquirectangularRefractionMapping = 304;
  70. const CubeUVReflectionMapping = 306;
  71. const RepeatWrapping = 1000;
  72. const ClampToEdgeWrapping = 1001;
  73. const MirroredRepeatWrapping = 1002;
  74. const NearestFilter = 1003;
  75. const NearestMipmapNearestFilter = 1004;
  76. const NearestMipMapNearestFilter = 1004;
  77. const NearestMipmapLinearFilter = 1005;
  78. const NearestMipMapLinearFilter = 1005;
  79. const LinearFilter = 1006;
  80. const LinearMipmapNearestFilter = 1007;
  81. const LinearMipMapNearestFilter = 1007;
  82. const LinearMipmapLinearFilter = 1008;
  83. const LinearMipMapLinearFilter = 1008;
  84. const UnsignedByteType = 1009;
  85. const ByteType = 1010;
  86. const ShortType = 1011;
  87. const UnsignedShortType = 1012;
  88. const IntType = 1013;
  89. const UnsignedIntType = 1014;
  90. const FloatType = 1015;
  91. const HalfFloatType = 1016;
  92. const UnsignedShort4444Type = 1017;
  93. const UnsignedShort5551Type = 1018;
  94. const UnsignedInt248Type = 1020;
  95. const AlphaFormat = 1021;
  96. const RGBAFormat = 1023;
  97. const LuminanceFormat = 1024;
  98. const LuminanceAlphaFormat = 1025;
  99. const DepthFormat = 1026;
  100. const DepthStencilFormat = 1027;
  101. const RedFormat = 1028;
  102. const RedIntegerFormat = 1029;
  103. const RGFormat = 1030;
  104. const RGIntegerFormat = 1031;
  105. const RGBAIntegerFormat = 1033;
  106. const RGB_S3TC_DXT1_Format = 33776;
  107. const RGBA_S3TC_DXT1_Format = 33777;
  108. const RGBA_S3TC_DXT3_Format = 33778;
  109. const RGBA_S3TC_DXT5_Format = 33779;
  110. const RGB_PVRTC_4BPPV1_Format = 35840;
  111. const RGB_PVRTC_2BPPV1_Format = 35841;
  112. const RGBA_PVRTC_4BPPV1_Format = 35842;
  113. const RGBA_PVRTC_2BPPV1_Format = 35843;
  114. const RGB_ETC1_Format = 36196;
  115. const RGB_ETC2_Format = 37492;
  116. const RGBA_ETC2_EAC_Format = 37496;
  117. const RGBA_ASTC_4x4_Format = 37808;
  118. const RGBA_ASTC_5x4_Format = 37809;
  119. const RGBA_ASTC_5x5_Format = 37810;
  120. const RGBA_ASTC_6x5_Format = 37811;
  121. const RGBA_ASTC_6x6_Format = 37812;
  122. const RGBA_ASTC_8x5_Format = 37813;
  123. const RGBA_ASTC_8x6_Format = 37814;
  124. const RGBA_ASTC_8x8_Format = 37815;
  125. const RGBA_ASTC_10x5_Format = 37816;
  126. const RGBA_ASTC_10x6_Format = 37817;
  127. const RGBA_ASTC_10x8_Format = 37818;
  128. const RGBA_ASTC_10x10_Format = 37819;
  129. const RGBA_ASTC_12x10_Format = 37820;
  130. const RGBA_ASTC_12x12_Format = 37821;
  131. const RGBA_BPTC_Format = 36492;
  132. const RED_RGTC1_Format = 36283;
  133. const SIGNED_RED_RGTC1_Format = 36284;
  134. const RED_GREEN_RGTC2_Format = 36285;
  135. const SIGNED_RED_GREEN_RGTC2_Format = 36286;
  136. const LoopOnce = 2200;
  137. const LoopRepeat = 2201;
  138. const LoopPingPong = 2202;
  139. const InterpolateDiscrete = 2300;
  140. const InterpolateLinear = 2301;
  141. const InterpolateSmooth = 2302;
  142. const ZeroCurvatureEnding = 2400;
  143. const ZeroSlopeEnding = 2401;
  144. const WrapAroundEnding = 2402;
  145. const NormalAnimationBlendMode = 2500;
  146. const AdditiveAnimationBlendMode = 2501;
  147. const TrianglesDrawMode = 0;
  148. const TriangleStripDrawMode = 1;
  149. const TriangleFanDrawMode = 2;
  150. const LinearEncoding = 3000;
  151. const sRGBEncoding = 3001;
  152. const BasicDepthPacking = 3200;
  153. const RGBADepthPacking = 3201;
  154. const TangentSpaceNormalMap = 0;
  155. const ObjectSpaceNormalMap = 1;
  156. // Color space string identifiers, matching CSS Color Module Level 4 and WebGPU names where available.
  157. const NoColorSpace = '';
  158. const SRGBColorSpace = 'srgb';
  159. const LinearSRGBColorSpace = 'srgb-linear';
  160. const ZeroStencilOp = 0;
  161. const KeepStencilOp = 7680;
  162. const ReplaceStencilOp = 7681;
  163. const IncrementStencilOp = 7682;
  164. const DecrementStencilOp = 7683;
  165. const IncrementWrapStencilOp = 34055;
  166. const DecrementWrapStencilOp = 34056;
  167. const InvertStencilOp = 5386;
  168. const NeverStencilFunc = 512;
  169. const LessStencilFunc = 513;
  170. const EqualStencilFunc = 514;
  171. const LessEqualStencilFunc = 515;
  172. const GreaterStencilFunc = 516;
  173. const NotEqualStencilFunc = 517;
  174. const GreaterEqualStencilFunc = 518;
  175. const AlwaysStencilFunc = 519;
  176. const StaticDrawUsage = 35044;
  177. const DynamicDrawUsage = 35048;
  178. const StreamDrawUsage = 35040;
  179. const StaticReadUsage = 35045;
  180. const DynamicReadUsage = 35049;
  181. const StreamReadUsage = 35041;
  182. const StaticCopyUsage = 35046;
  183. const DynamicCopyUsage = 35050;
  184. const StreamCopyUsage = 35042;
  185. const GLSL1 = '100';
  186. const GLSL3 = '300 es';
  187. const _SRGBAFormat = 1035; // fallback for WebGL 1
  188. /**
  189. * https://github.com/mrdoob/eventdispatcher.js/
  190. */
  191. class EventDispatcher {
  192. addEventListener( type, listener ) {
  193. if ( this._listeners === undefined ) this._listeners = {};
  194. const listeners = this._listeners;
  195. if ( listeners[ type ] === undefined ) {
  196. listeners[ type ] = [];
  197. }
  198. if ( listeners[ type ].indexOf( listener ) === - 1 ) {
  199. listeners[ type ].push( listener );
  200. }
  201. }
  202. hasEventListener( type, listener ) {
  203. if ( this._listeners === undefined ) return false;
  204. const listeners = this._listeners;
  205. return listeners[ type ] !== undefined && listeners[ type ].indexOf( listener ) !== - 1;
  206. }
  207. removeEventListener( type, listener ) {
  208. if ( this._listeners === undefined ) return;
  209. const listeners = this._listeners;
  210. const listenerArray = listeners[ type ];
  211. if ( listenerArray !== undefined ) {
  212. const index = listenerArray.indexOf( listener );
  213. if ( index !== - 1 ) {
  214. listenerArray.splice( index, 1 );
  215. }
  216. }
  217. }
  218. dispatchEvent( event ) {
  219. if ( this._listeners === undefined ) return;
  220. const listeners = this._listeners;
  221. const listenerArray = listeners[ event.type ];
  222. if ( listenerArray !== undefined ) {
  223. event.target = this;
  224. // Make a copy, in case listeners are removed while iterating.
  225. const array = listenerArray.slice( 0 );
  226. for ( let i = 0, l = array.length; i < l; i ++ ) {
  227. array[ i ].call( this, event );
  228. }
  229. event.target = null;
  230. }
  231. }
  232. }
  233. 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' ];
  234. let _seed = 1234567;
  235. const DEG2RAD = Math.PI / 180;
  236. const RAD2DEG = 180 / Math.PI;
  237. // http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/21963136#21963136
  238. function generateUUID() {
  239. const d0 = Math.random() * 0xffffffff | 0;
  240. const d1 = Math.random() * 0xffffffff | 0;
  241. const d2 = Math.random() * 0xffffffff | 0;
  242. const d3 = Math.random() * 0xffffffff | 0;
  243. const uuid = _lut[ d0 & 0xff ] + _lut[ d0 >> 8 & 0xff ] + _lut[ d0 >> 16 & 0xff ] + _lut[ d0 >> 24 & 0xff ] + '-' +
  244. _lut[ d1 & 0xff ] + _lut[ d1 >> 8 & 0xff ] + '-' + _lut[ d1 >> 16 & 0x0f | 0x40 ] + _lut[ d1 >> 24 & 0xff ] + '-' +
  245. _lut[ d2 & 0x3f | 0x80 ] + _lut[ d2 >> 8 & 0xff ] + '-' + _lut[ d2 >> 16 & 0xff ] + _lut[ d2 >> 24 & 0xff ] +
  246. _lut[ d3 & 0xff ] + _lut[ d3 >> 8 & 0xff ] + _lut[ d3 >> 16 & 0xff ] + _lut[ d3 >> 24 & 0xff ];
  247. // .toLowerCase() here flattens concatenated strings to save heap memory space.
  248. return uuid.toLowerCase();
  249. }
  250. function clamp( value, min, max ) {
  251. return Math.max( min, Math.min( max, value ) );
  252. }
  253. // compute euclidean modulo of m % n
  254. // https://en.wikipedia.org/wiki/Modulo_operation
  255. function euclideanModulo( n, m ) {
  256. return ( ( n % m ) + m ) % m;
  257. }
  258. // Linear mapping from range <a1, a2> to range <b1, b2>
  259. function mapLinear( x, a1, a2, b1, b2 ) {
  260. return b1 + ( x - a1 ) * ( b2 - b1 ) / ( a2 - a1 );
  261. }
  262. // https://www.gamedev.net/tutorials/programming/general-and-gameplay-programming/inverse-lerp-a-super-useful-yet-often-overlooked-function-r5230/
  263. function inverseLerp( x, y, value ) {
  264. if ( x !== y ) {
  265. return ( value - x ) / ( y - x );
  266. } else {
  267. return 0;
  268. }
  269. }
  270. // https://en.wikipedia.org/wiki/Linear_interpolation
  271. function lerp( x, y, t ) {
  272. return ( 1 - t ) * x + t * y;
  273. }
  274. // http://www.rorydriscoll.com/2016/03/07/frame-rate-independent-damping-using-lerp/
  275. function damp( x, y, lambda, dt ) {
  276. return lerp( x, y, 1 - Math.exp( - lambda * dt ) );
  277. }
  278. // https://www.desmos.com/calculator/vcsjnyz7x4
  279. function pingpong( x, length = 1 ) {
  280. return length - Math.abs( euclideanModulo( x, length * 2 ) - length );
  281. }
  282. // http://en.wikipedia.org/wiki/Smoothstep
  283. function smoothstep( x, min, max ) {
  284. if ( x <= min ) return 0;
  285. if ( x >= max ) return 1;
  286. x = ( x - min ) / ( max - min );
  287. return x * x * ( 3 - 2 * x );
  288. }
  289. function smootherstep( x, min, max ) {
  290. if ( x <= min ) return 0;
  291. if ( x >= max ) return 1;
  292. x = ( x - min ) / ( max - min );
  293. return x * x * x * ( x * ( x * 6 - 15 ) + 10 );
  294. }
  295. // Random integer from <low, high> interval
  296. function randInt( low, high ) {
  297. return low + Math.floor( Math.random() * ( high - low + 1 ) );
  298. }
  299. // Random float from <low, high> interval
  300. function randFloat( low, high ) {
  301. return low + Math.random() * ( high - low );
  302. }
  303. // Random float from <-range/2, range/2> interval
  304. function randFloatSpread( range ) {
  305. return range * ( 0.5 - Math.random() );
  306. }
  307. // Deterministic pseudo-random float in the interval [ 0, 1 ]
  308. function seededRandom( s ) {
  309. if ( s !== undefined ) _seed = s;
  310. // Mulberry32 generator
  311. let t = _seed += 0x6D2B79F5;
  312. t = Math.imul( t ^ t >>> 15, t | 1 );
  313. t ^= t + Math.imul( t ^ t >>> 7, t | 61 );
  314. return ( ( t ^ t >>> 14 ) >>> 0 ) / 4294967296;
  315. }
  316. function degToRad( degrees ) {
  317. return degrees * DEG2RAD;
  318. }
  319. function radToDeg( radians ) {
  320. return radians * RAD2DEG;
  321. }
  322. function isPowerOfTwo( value ) {
  323. return ( value & ( value - 1 ) ) === 0 && value !== 0;
  324. }
  325. function ceilPowerOfTwo( value ) {
  326. return Math.pow( 2, Math.ceil( Math.log( value ) / Math.LN2 ) );
  327. }
  328. function floorPowerOfTwo( value ) {
  329. return Math.pow( 2, Math.floor( Math.log( value ) / Math.LN2 ) );
  330. }
  331. function setQuaternionFromProperEuler( q, a, b, c, order ) {
  332. // Intrinsic Proper Euler Angles - see https://en.wikipedia.org/wiki/Euler_angles
  333. // rotations are applied to the axes in the order specified by 'order'
  334. // rotation by angle 'a' is applied first, then by angle 'b', then by angle 'c'
  335. // angles are in radians
  336. const cos = Math.cos;
  337. const sin = Math.sin;
  338. const c2 = cos( b / 2 );
  339. const s2 = sin( b / 2 );
  340. const c13 = cos( ( a + c ) / 2 );
  341. const s13 = sin( ( a + c ) / 2 );
  342. const c1_3 = cos( ( a - c ) / 2 );
  343. const s1_3 = sin( ( a - c ) / 2 );
  344. const c3_1 = cos( ( c - a ) / 2 );
  345. const s3_1 = sin( ( c - a ) / 2 );
  346. switch ( order ) {
  347. case 'XYX':
  348. q.set( c2 * s13, s2 * c1_3, s2 * s1_3, c2 * c13 );
  349. break;
  350. case 'YZY':
  351. q.set( s2 * s1_3, c2 * s13, s2 * c1_3, c2 * c13 );
  352. break;
  353. case 'ZXZ':
  354. q.set( s2 * c1_3, s2 * s1_3, c2 * s13, c2 * c13 );
  355. break;
  356. case 'XZX':
  357. q.set( c2 * s13, s2 * s3_1, s2 * c3_1, c2 * c13 );
  358. break;
  359. case 'YXY':
  360. q.set( s2 * c3_1, c2 * s13, s2 * s3_1, c2 * c13 );
  361. break;
  362. case 'ZYZ':
  363. q.set( s2 * s3_1, s2 * c3_1, c2 * s13, c2 * c13 );
  364. break;
  365. default:
  366. console.warn( 'THREE.MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: ' + order );
  367. }
  368. }
  369. function denormalize( value, array ) {
  370. switch ( array.constructor ) {
  371. case Float32Array:
  372. return value;
  373. case Uint16Array:
  374. return value / 65535.0;
  375. case Uint8Array:
  376. return value / 255.0;
  377. case Int16Array:
  378. return Math.max( value / 32767.0, - 1.0 );
  379. case Int8Array:
  380. return Math.max( value / 127.0, - 1.0 );
  381. default:
  382. throw new Error( 'Invalid component type.' );
  383. }
  384. }
  385. function normalize( value, array ) {
  386. switch ( array.constructor ) {
  387. case Float32Array:
  388. return value;
  389. case Uint16Array:
  390. return Math.round( value * 65535.0 );
  391. case Uint8Array:
  392. return Math.round( value * 255.0 );
  393. case Int16Array:
  394. return Math.round( value * 32767.0 );
  395. case Int8Array:
  396. return Math.round( value * 127.0 );
  397. default:
  398. throw new Error( 'Invalid component type.' );
  399. }
  400. }
  401. var MathUtils = /*#__PURE__*/Object.freeze({
  402. __proto__: null,
  403. DEG2RAD: DEG2RAD,
  404. RAD2DEG: RAD2DEG,
  405. ceilPowerOfTwo: ceilPowerOfTwo,
  406. clamp: clamp,
  407. damp: damp,
  408. degToRad: degToRad,
  409. denormalize: denormalize,
  410. euclideanModulo: euclideanModulo,
  411. floorPowerOfTwo: floorPowerOfTwo,
  412. generateUUID: generateUUID,
  413. inverseLerp: inverseLerp,
  414. isPowerOfTwo: isPowerOfTwo,
  415. lerp: lerp,
  416. mapLinear: mapLinear,
  417. normalize: normalize,
  418. pingpong: pingpong,
  419. radToDeg: radToDeg,
  420. randFloat: randFloat,
  421. randFloatSpread: randFloatSpread,
  422. randInt: randInt,
  423. seededRandom: seededRandom,
  424. setQuaternionFromProperEuler: setQuaternionFromProperEuler,
  425. smootherstep: smootherstep,
  426. smoothstep: smoothstep
  427. });
  428. class Vector2 {
  429. constructor( x = 0, y = 0 ) {
  430. Vector2.prototype.isVector2 = true;
  431. this.x = x;
  432. this.y = y;
  433. }
  434. get width() {
  435. return this.x;
  436. }
  437. set width( value ) {
  438. this.x = value;
  439. }
  440. get height() {
  441. return this.y;
  442. }
  443. set height( value ) {
  444. this.y = value;
  445. }
  446. set( x, y ) {
  447. this.x = x;
  448. this.y = y;
  449. return this;
  450. }
  451. setScalar( scalar ) {
  452. this.x = scalar;
  453. this.y = scalar;
  454. return this;
  455. }
  456. setX( x ) {
  457. this.x = x;
  458. return this;
  459. }
  460. setY( y ) {
  461. this.y = y;
  462. return this;
  463. }
  464. setComponent( index, value ) {
  465. switch ( index ) {
  466. case 0: this.x = value; break;
  467. case 1: this.y = value; break;
  468. default: throw new Error( 'index is out of range: ' + index );
  469. }
  470. return this;
  471. }
  472. getComponent( index ) {
  473. switch ( index ) {
  474. case 0: return this.x;
  475. case 1: return this.y;
  476. default: throw new Error( 'index is out of range: ' + index );
  477. }
  478. }
  479. clone() {
  480. return new this.constructor( this.x, this.y );
  481. }
  482. copy( v ) {
  483. this.x = v.x;
  484. this.y = v.y;
  485. return this;
  486. }
  487. add( v ) {
  488. this.x += v.x;
  489. this.y += v.y;
  490. return this;
  491. }
  492. addScalar( s ) {
  493. this.x += s;
  494. this.y += s;
  495. return this;
  496. }
  497. addVectors( a, b ) {
  498. this.x = a.x + b.x;
  499. this.y = a.y + b.y;
  500. return this;
  501. }
  502. addScaledVector( v, s ) {
  503. this.x += v.x * s;
  504. this.y += v.y * s;
  505. return this;
  506. }
  507. sub( v ) {
  508. this.x -= v.x;
  509. this.y -= v.y;
  510. return this;
  511. }
  512. subScalar( s ) {
  513. this.x -= s;
  514. this.y -= s;
  515. return this;
  516. }
  517. subVectors( a, b ) {
  518. this.x = a.x - b.x;
  519. this.y = a.y - b.y;
  520. return this;
  521. }
  522. multiply( v ) {
  523. this.x *= v.x;
  524. this.y *= v.y;
  525. return this;
  526. }
  527. multiplyScalar( scalar ) {
  528. this.x *= scalar;
  529. this.y *= scalar;
  530. return this;
  531. }
  532. divide( v ) {
  533. this.x /= v.x;
  534. this.y /= v.y;
  535. return this;
  536. }
  537. divideScalar( scalar ) {
  538. return this.multiplyScalar( 1 / scalar );
  539. }
  540. applyMatrix3( m ) {
  541. const x = this.x, y = this.y;
  542. const e = m.elements;
  543. this.x = e[ 0 ] * x + e[ 3 ] * y + e[ 6 ];
  544. this.y = e[ 1 ] * x + e[ 4 ] * y + e[ 7 ];
  545. return this;
  546. }
  547. min( v ) {
  548. this.x = Math.min( this.x, v.x );
  549. this.y = Math.min( this.y, v.y );
  550. return this;
  551. }
  552. max( v ) {
  553. this.x = Math.max( this.x, v.x );
  554. this.y = Math.max( this.y, v.y );
  555. return this;
  556. }
  557. clamp( min, max ) {
  558. // assumes min < max, componentwise
  559. this.x = Math.max( min.x, Math.min( max.x, this.x ) );
  560. this.y = Math.max( min.y, Math.min( max.y, this.y ) );
  561. return this;
  562. }
  563. clampScalar( minVal, maxVal ) {
  564. this.x = Math.max( minVal, Math.min( maxVal, this.x ) );
  565. this.y = Math.max( minVal, Math.min( maxVal, this.y ) );
  566. return this;
  567. }
  568. clampLength( min, max ) {
  569. const length = this.length();
  570. return this.divideScalar( length || 1 ).multiplyScalar( Math.max( min, Math.min( max, length ) ) );
  571. }
  572. floor() {
  573. this.x = Math.floor( this.x );
  574. this.y = Math.floor( this.y );
  575. return this;
  576. }
  577. ceil() {
  578. this.x = Math.ceil( this.x );
  579. this.y = Math.ceil( this.y );
  580. return this;
  581. }
  582. round() {
  583. this.x = Math.round( this.x );
  584. this.y = Math.round( this.y );
  585. return this;
  586. }
  587. roundToZero() {
  588. this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x );
  589. this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y );
  590. return this;
  591. }
  592. negate() {
  593. this.x = - this.x;
  594. this.y = - this.y;
  595. return this;
  596. }
  597. dot( v ) {
  598. return this.x * v.x + this.y * v.y;
  599. }
  600. cross( v ) {
  601. return this.x * v.y - this.y * v.x;
  602. }
  603. lengthSq() {
  604. return this.x * this.x + this.y * this.y;
  605. }
  606. length() {
  607. return Math.sqrt( this.x * this.x + this.y * this.y );
  608. }
  609. manhattanLength() {
  610. return Math.abs( this.x ) + Math.abs( this.y );
  611. }
  612. normalize() {
  613. return this.divideScalar( this.length() || 1 );
  614. }
  615. angle() {
  616. // computes the angle in radians with respect to the positive x-axis
  617. const angle = Math.atan2( - this.y, - this.x ) + Math.PI;
  618. return angle;
  619. }
  620. distanceTo( v ) {
  621. return Math.sqrt( this.distanceToSquared( v ) );
  622. }
  623. distanceToSquared( v ) {
  624. const dx = this.x - v.x, dy = this.y - v.y;
  625. return dx * dx + dy * dy;
  626. }
  627. manhattanDistanceTo( v ) {
  628. return Math.abs( this.x - v.x ) + Math.abs( this.y - v.y );
  629. }
  630. setLength( length ) {
  631. return this.normalize().multiplyScalar( length );
  632. }
  633. lerp( v, alpha ) {
  634. this.x += ( v.x - this.x ) * alpha;
  635. this.y += ( v.y - this.y ) * alpha;
  636. return this;
  637. }
  638. lerpVectors( v1, v2, alpha ) {
  639. this.x = v1.x + ( v2.x - v1.x ) * alpha;
  640. this.y = v1.y + ( v2.y - v1.y ) * alpha;
  641. return this;
  642. }
  643. equals( v ) {
  644. return ( ( v.x === this.x ) && ( v.y === this.y ) );
  645. }
  646. fromArray( array, offset = 0 ) {
  647. this.x = array[ offset ];
  648. this.y = array[ offset + 1 ];
  649. return this;
  650. }
  651. toArray( array = [], offset = 0 ) {
  652. array[ offset ] = this.x;
  653. array[ offset + 1 ] = this.y;
  654. return array;
  655. }
  656. fromBufferAttribute( attribute, index ) {
  657. this.x = attribute.getX( index );
  658. this.y = attribute.getY( index );
  659. return this;
  660. }
  661. rotateAround( center, angle ) {
  662. const c = Math.cos( angle ), s = Math.sin( angle );
  663. const x = this.x - center.x;
  664. const y = this.y - center.y;
  665. this.x = x * c - y * s + center.x;
  666. this.y = x * s + y * c + center.y;
  667. return this;
  668. }
  669. random() {
  670. this.x = Math.random();
  671. this.y = Math.random();
  672. return this;
  673. }
  674. *[ Symbol.iterator ]() {
  675. yield this.x;
  676. yield this.y;
  677. }
  678. }
  679. class Matrix3 {
  680. constructor() {
  681. Matrix3.prototype.isMatrix3 = true;
  682. this.elements = [
  683. 1, 0, 0,
  684. 0, 1, 0,
  685. 0, 0, 1
  686. ];
  687. }
  688. set( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) {
  689. const te = this.elements;
  690. te[ 0 ] = n11; te[ 1 ] = n21; te[ 2 ] = n31;
  691. te[ 3 ] = n12; te[ 4 ] = n22; te[ 5 ] = n32;
  692. te[ 6 ] = n13; te[ 7 ] = n23; te[ 8 ] = n33;
  693. return this;
  694. }
  695. identity() {
  696. this.set(
  697. 1, 0, 0,
  698. 0, 1, 0,
  699. 0, 0, 1
  700. );
  701. return this;
  702. }
  703. copy( m ) {
  704. const te = this.elements;
  705. const me = m.elements;
  706. te[ 0 ] = me[ 0 ]; te[ 1 ] = me[ 1 ]; te[ 2 ] = me[ 2 ];
  707. te[ 3 ] = me[ 3 ]; te[ 4 ] = me[ 4 ]; te[ 5 ] = me[ 5 ];
  708. te[ 6 ] = me[ 6 ]; te[ 7 ] = me[ 7 ]; te[ 8 ] = me[ 8 ];
  709. return this;
  710. }
  711. extractBasis( xAxis, yAxis, zAxis ) {
  712. xAxis.setFromMatrix3Column( this, 0 );
  713. yAxis.setFromMatrix3Column( this, 1 );
  714. zAxis.setFromMatrix3Column( this, 2 );
  715. return this;
  716. }
  717. setFromMatrix4( m ) {
  718. const me = m.elements;
  719. this.set(
  720. me[ 0 ], me[ 4 ], me[ 8 ],
  721. me[ 1 ], me[ 5 ], me[ 9 ],
  722. me[ 2 ], me[ 6 ], me[ 10 ]
  723. );
  724. return this;
  725. }
  726. multiply( m ) {
  727. return this.multiplyMatrices( this, m );
  728. }
  729. premultiply( m ) {
  730. return this.multiplyMatrices( m, this );
  731. }
  732. multiplyMatrices( a, b ) {
  733. const ae = a.elements;
  734. const be = b.elements;
  735. const te = this.elements;
  736. const a11 = ae[ 0 ], a12 = ae[ 3 ], a13 = ae[ 6 ];
  737. const a21 = ae[ 1 ], a22 = ae[ 4 ], a23 = ae[ 7 ];
  738. const a31 = ae[ 2 ], a32 = ae[ 5 ], a33 = ae[ 8 ];
  739. const b11 = be[ 0 ], b12 = be[ 3 ], b13 = be[ 6 ];
  740. const b21 = be[ 1 ], b22 = be[ 4 ], b23 = be[ 7 ];
  741. const b31 = be[ 2 ], b32 = be[ 5 ], b33 = be[ 8 ];
  742. te[ 0 ] = a11 * b11 + a12 * b21 + a13 * b31;
  743. te[ 3 ] = a11 * b12 + a12 * b22 + a13 * b32;
  744. te[ 6 ] = a11 * b13 + a12 * b23 + a13 * b33;
  745. te[ 1 ] = a21 * b11 + a22 * b21 + a23 * b31;
  746. te[ 4 ] = a21 * b12 + a22 * b22 + a23 * b32;
  747. te[ 7 ] = a21 * b13 + a22 * b23 + a23 * b33;
  748. te[ 2 ] = a31 * b11 + a32 * b21 + a33 * b31;
  749. te[ 5 ] = a31 * b12 + a32 * b22 + a33 * b32;
  750. te[ 8 ] = a31 * b13 + a32 * b23 + a33 * b33;
  751. return this;
  752. }
  753. multiplyScalar( s ) {
  754. const te = this.elements;
  755. te[ 0 ] *= s; te[ 3 ] *= s; te[ 6 ] *= s;
  756. te[ 1 ] *= s; te[ 4 ] *= s; te[ 7 ] *= s;
  757. te[ 2 ] *= s; te[ 5 ] *= s; te[ 8 ] *= s;
  758. return this;
  759. }
  760. determinant() {
  761. const te = this.elements;
  762. const a = te[ 0 ], b = te[ 1 ], c = te[ 2 ],
  763. d = te[ 3 ], e = te[ 4 ], f = te[ 5 ],
  764. g = te[ 6 ], h = te[ 7 ], i = te[ 8 ];
  765. return a * e * i - a * f * h - b * d * i + b * f * g + c * d * h - c * e * g;
  766. }
  767. invert() {
  768. const te = this.elements,
  769. n11 = te[ 0 ], n21 = te[ 1 ], n31 = te[ 2 ],
  770. n12 = te[ 3 ], n22 = te[ 4 ], n32 = te[ 5 ],
  771. n13 = te[ 6 ], n23 = te[ 7 ], n33 = te[ 8 ],
  772. t11 = n33 * n22 - n32 * n23,
  773. t12 = n32 * n13 - n33 * n12,
  774. t13 = n23 * n12 - n22 * n13,
  775. det = n11 * t11 + n21 * t12 + n31 * t13;
  776. if ( det === 0 ) return this.set( 0, 0, 0, 0, 0, 0, 0, 0, 0 );
  777. const detInv = 1 / det;
  778. te[ 0 ] = t11 * detInv;
  779. te[ 1 ] = ( n31 * n23 - n33 * n21 ) * detInv;
  780. te[ 2 ] = ( n32 * n21 - n31 * n22 ) * detInv;
  781. te[ 3 ] = t12 * detInv;
  782. te[ 4 ] = ( n33 * n11 - n31 * n13 ) * detInv;
  783. te[ 5 ] = ( n31 * n12 - n32 * n11 ) * detInv;
  784. te[ 6 ] = t13 * detInv;
  785. te[ 7 ] = ( n21 * n13 - n23 * n11 ) * detInv;
  786. te[ 8 ] = ( n22 * n11 - n21 * n12 ) * detInv;
  787. return this;
  788. }
  789. transpose() {
  790. let tmp;
  791. const m = this.elements;
  792. tmp = m[ 1 ]; m[ 1 ] = m[ 3 ]; m[ 3 ] = tmp;
  793. tmp = m[ 2 ]; m[ 2 ] = m[ 6 ]; m[ 6 ] = tmp;
  794. tmp = m[ 5 ]; m[ 5 ] = m[ 7 ]; m[ 7 ] = tmp;
  795. return this;
  796. }
  797. getNormalMatrix( matrix4 ) {
  798. return this.setFromMatrix4( matrix4 ).invert().transpose();
  799. }
  800. transposeIntoArray( r ) {
  801. const m = this.elements;
  802. r[ 0 ] = m[ 0 ];
  803. r[ 1 ] = m[ 3 ];
  804. r[ 2 ] = m[ 6 ];
  805. r[ 3 ] = m[ 1 ];
  806. r[ 4 ] = m[ 4 ];
  807. r[ 5 ] = m[ 7 ];
  808. r[ 6 ] = m[ 2 ];
  809. r[ 7 ] = m[ 5 ];
  810. r[ 8 ] = m[ 8 ];
  811. return this;
  812. }
  813. setUvTransform( tx, ty, sx, sy, rotation, cx, cy ) {
  814. const c = Math.cos( rotation );
  815. const s = Math.sin( rotation );
  816. this.set(
  817. sx * c, sx * s, - sx * ( c * cx + s * cy ) + cx + tx,
  818. - sy * s, sy * c, - sy * ( - s * cx + c * cy ) + cy + ty,
  819. 0, 0, 1
  820. );
  821. return this;
  822. }
  823. //
  824. scale( sx, sy ) {
  825. this.premultiply( _m3.makeScale( sx, sy ) );
  826. return this;
  827. }
  828. rotate( theta ) {
  829. this.premultiply( _m3.makeRotation( - theta ) );
  830. return this;
  831. }
  832. translate( tx, ty ) {
  833. this.premultiply( _m3.makeTranslation( tx, ty ) );
  834. return this;
  835. }
  836. // for 2D Transforms
  837. makeTranslation( x, y ) {
  838. this.set(
  839. 1, 0, x,
  840. 0, 1, y,
  841. 0, 0, 1
  842. );
  843. return this;
  844. }
  845. makeRotation( theta ) {
  846. // counterclockwise
  847. const c = Math.cos( theta );
  848. const s = Math.sin( theta );
  849. this.set(
  850. c, - s, 0,
  851. s, c, 0,
  852. 0, 0, 1
  853. );
  854. return this;
  855. }
  856. makeScale( x, y ) {
  857. this.set(
  858. x, 0, 0,
  859. 0, y, 0,
  860. 0, 0, 1
  861. );
  862. return this;
  863. }
  864. //
  865. equals( matrix ) {
  866. const te = this.elements;
  867. const me = matrix.elements;
  868. for ( let i = 0; i < 9; i ++ ) {
  869. if ( te[ i ] !== me[ i ] ) return false;
  870. }
  871. return true;
  872. }
  873. fromArray( array, offset = 0 ) {
  874. for ( let i = 0; i < 9; i ++ ) {
  875. this.elements[ i ] = array[ i + offset ];
  876. }
  877. return this;
  878. }
  879. toArray( array = [], offset = 0 ) {
  880. const te = this.elements;
  881. array[ offset ] = te[ 0 ];
  882. array[ offset + 1 ] = te[ 1 ];
  883. array[ offset + 2 ] = te[ 2 ];
  884. array[ offset + 3 ] = te[ 3 ];
  885. array[ offset + 4 ] = te[ 4 ];
  886. array[ offset + 5 ] = te[ 5 ];
  887. array[ offset + 6 ] = te[ 6 ];
  888. array[ offset + 7 ] = te[ 7 ];
  889. array[ offset + 8 ] = te[ 8 ];
  890. return array;
  891. }
  892. clone() {
  893. return new this.constructor().fromArray( this.elements );
  894. }
  895. }
  896. const _m3 = /*@__PURE__*/ new Matrix3();
  897. function arrayNeedsUint32( array ) {
  898. // assumes larger values usually on last
  899. for ( let i = array.length - 1; i >= 0; -- i ) {
  900. if ( array[ i ] >= 65535 ) return true; // account for PRIMITIVE_RESTART_FIXED_INDEX, #24565
  901. }
  902. return false;
  903. }
  904. const TYPED_ARRAYS = {
  905. Int8Array: Int8Array,
  906. Uint8Array: Uint8Array,
  907. Uint8ClampedArray: Uint8ClampedArray,
  908. Int16Array: Int16Array,
  909. Uint16Array: Uint16Array,
  910. Int32Array: Int32Array,
  911. Uint32Array: Uint32Array,
  912. Float32Array: Float32Array,
  913. Float64Array: Float64Array
  914. };
  915. function getTypedArray( type, buffer ) {
  916. return new TYPED_ARRAYS[ type ]( buffer );
  917. }
  918. function createElementNS( name ) {
  919. return document.createElementNS( 'http://www.w3.org/1999/xhtml', name );
  920. }
  921. function SRGBToLinear( c ) {
  922. return ( c < 0.04045 ) ? c * 0.0773993808 : Math.pow( c * 0.9478672986 + 0.0521327014, 2.4 );
  923. }
  924. function LinearToSRGB( c ) {
  925. return ( c < 0.0031308 ) ? c * 12.92 : 1.055 * ( Math.pow( c, 0.41666 ) ) - 0.055;
  926. }
  927. // JavaScript RGB-to-RGB transforms, defined as
  928. // FN[InputColorSpace][OutputColorSpace] callback functions.
  929. const FN = {
  930. [ SRGBColorSpace ]: { [ LinearSRGBColorSpace ]: SRGBToLinear },
  931. [ LinearSRGBColorSpace ]: { [ SRGBColorSpace ]: LinearToSRGB },
  932. };
  933. const ColorManagement = {
  934. legacyMode: true,
  935. get workingColorSpace() {
  936. return LinearSRGBColorSpace;
  937. },
  938. set workingColorSpace( colorSpace ) {
  939. console.warn( 'THREE.ColorManagement: .workingColorSpace is readonly.' );
  940. },
  941. convert: function ( color, sourceColorSpace, targetColorSpace ) {
  942. if ( this.legacyMode || sourceColorSpace === targetColorSpace || ! sourceColorSpace || ! targetColorSpace ) {
  943. return color;
  944. }
  945. if ( FN[ sourceColorSpace ] && FN[ sourceColorSpace ][ targetColorSpace ] !== undefined ) {
  946. const fn = FN[ sourceColorSpace ][ targetColorSpace ];
  947. color.r = fn( color.r );
  948. color.g = fn( color.g );
  949. color.b = fn( color.b );
  950. return color;
  951. }
  952. throw new Error( 'Unsupported color space conversion.' );
  953. },
  954. fromWorkingColorSpace: function ( color, targetColorSpace ) {
  955. return this.convert( color, this.workingColorSpace, targetColorSpace );
  956. },
  957. toWorkingColorSpace: function ( color, sourceColorSpace ) {
  958. return this.convert( color, sourceColorSpace, this.workingColorSpace );
  959. },
  960. };
  961. const _colorKeywords = { 'aliceblue': 0xF0F8FF, 'antiquewhite': 0xFAEBD7, 'aqua': 0x00FFFF, 'aquamarine': 0x7FFFD4, 'azure': 0xF0FFFF,
  962. 'beige': 0xF5F5DC, 'bisque': 0xFFE4C4, 'black': 0x000000, 'blanchedalmond': 0xFFEBCD, 'blue': 0x0000FF, 'blueviolet': 0x8A2BE2,
  963. 'brown': 0xA52A2A, 'burlywood': 0xDEB887, 'cadetblue': 0x5F9EA0, 'chartreuse': 0x7FFF00, 'chocolate': 0xD2691E, 'coral': 0xFF7F50,
  964. 'cornflowerblue': 0x6495ED, 'cornsilk': 0xFFF8DC, 'crimson': 0xDC143C, 'cyan': 0x00FFFF, 'darkblue': 0x00008B, 'darkcyan': 0x008B8B,
  965. 'darkgoldenrod': 0xB8860B, 'darkgray': 0xA9A9A9, 'darkgreen': 0x006400, 'darkgrey': 0xA9A9A9, 'darkkhaki': 0xBDB76B, 'darkmagenta': 0x8B008B,
  966. 'darkolivegreen': 0x556B2F, 'darkorange': 0xFF8C00, 'darkorchid': 0x9932CC, 'darkred': 0x8B0000, 'darksalmon': 0xE9967A, 'darkseagreen': 0x8FBC8F,
  967. 'darkslateblue': 0x483D8B, 'darkslategray': 0x2F4F4F, 'darkslategrey': 0x2F4F4F, 'darkturquoise': 0x00CED1, 'darkviolet': 0x9400D3,
  968. 'deeppink': 0xFF1493, 'deepskyblue': 0x00BFFF, 'dimgray': 0x696969, 'dimgrey': 0x696969, 'dodgerblue': 0x1E90FF, 'firebrick': 0xB22222,
  969. 'floralwhite': 0xFFFAF0, 'forestgreen': 0x228B22, 'fuchsia': 0xFF00FF, 'gainsboro': 0xDCDCDC, 'ghostwhite': 0xF8F8FF, 'gold': 0xFFD700,
  970. 'goldenrod': 0xDAA520, 'gray': 0x808080, 'green': 0x008000, 'greenyellow': 0xADFF2F, 'grey': 0x808080, 'honeydew': 0xF0FFF0, 'hotpink': 0xFF69B4,
  971. 'indianred': 0xCD5C5C, 'indigo': 0x4B0082, 'ivory': 0xFFFFF0, 'khaki': 0xF0E68C, 'lavender': 0xE6E6FA, 'lavenderblush': 0xFFF0F5, 'lawngreen': 0x7CFC00,
  972. 'lemonchiffon': 0xFFFACD, 'lightblue': 0xADD8E6, 'lightcoral': 0xF08080, 'lightcyan': 0xE0FFFF, 'lightgoldenrodyellow': 0xFAFAD2, 'lightgray': 0xD3D3D3,
  973. 'lightgreen': 0x90EE90, 'lightgrey': 0xD3D3D3, 'lightpink': 0xFFB6C1, 'lightsalmon': 0xFFA07A, 'lightseagreen': 0x20B2AA, 'lightskyblue': 0x87CEFA,
  974. 'lightslategray': 0x778899, 'lightslategrey': 0x778899, 'lightsteelblue': 0xB0C4DE, 'lightyellow': 0xFFFFE0, 'lime': 0x00FF00, 'limegreen': 0x32CD32,
  975. 'linen': 0xFAF0E6, 'magenta': 0xFF00FF, 'maroon': 0x800000, 'mediumaquamarine': 0x66CDAA, 'mediumblue': 0x0000CD, 'mediumorchid': 0xBA55D3,
  976. 'mediumpurple': 0x9370DB, 'mediumseagreen': 0x3CB371, 'mediumslateblue': 0x7B68EE, 'mediumspringgreen': 0x00FA9A, 'mediumturquoise': 0x48D1CC,
  977. 'mediumvioletred': 0xC71585, 'midnightblue': 0x191970, 'mintcream': 0xF5FFFA, 'mistyrose': 0xFFE4E1, 'moccasin': 0xFFE4B5, 'navajowhite': 0xFFDEAD,
  978. 'navy': 0x000080, 'oldlace': 0xFDF5E6, 'olive': 0x808000, 'olivedrab': 0x6B8E23, 'orange': 0xFFA500, 'orangered': 0xFF4500, 'orchid': 0xDA70D6,
  979. 'palegoldenrod': 0xEEE8AA, 'palegreen': 0x98FB98, 'paleturquoise': 0xAFEEEE, 'palevioletred': 0xDB7093, 'papayawhip': 0xFFEFD5, 'peachpuff': 0xFFDAB9,
  980. 'peru': 0xCD853F, 'pink': 0xFFC0CB, 'plum': 0xDDA0DD, 'powderblue': 0xB0E0E6, 'purple': 0x800080, 'rebeccapurple': 0x663399, 'red': 0xFF0000, 'rosybrown': 0xBC8F8F,
  981. 'royalblue': 0x4169E1, 'saddlebrown': 0x8B4513, 'salmon': 0xFA8072, 'sandybrown': 0xF4A460, 'seagreen': 0x2E8B57, 'seashell': 0xFFF5EE,
  982. 'sienna': 0xA0522D, 'silver': 0xC0C0C0, 'skyblue': 0x87CEEB, 'slateblue': 0x6A5ACD, 'slategray': 0x708090, 'slategrey': 0x708090, 'snow': 0xFFFAFA,
  983. 'springgreen': 0x00FF7F, 'steelblue': 0x4682B4, 'tan': 0xD2B48C, 'teal': 0x008080, 'thistle': 0xD8BFD8, 'tomato': 0xFF6347, 'turquoise': 0x40E0D0,
  984. 'violet': 0xEE82EE, 'wheat': 0xF5DEB3, 'white': 0xFFFFFF, 'whitesmoke': 0xF5F5F5, 'yellow': 0xFFFF00, 'yellowgreen': 0x9ACD32 };
  985. const _rgb$1 = { r: 0, g: 0, b: 0 };
  986. const _hslA = { h: 0, s: 0, l: 0 };
  987. const _hslB = { h: 0, s: 0, l: 0 };
  988. function hue2rgb( p, q, t ) {
  989. if ( t < 0 ) t += 1;
  990. if ( t > 1 ) t -= 1;
  991. if ( t < 1 / 6 ) return p + ( q - p ) * 6 * t;
  992. if ( t < 1 / 2 ) return q;
  993. if ( t < 2 / 3 ) return p + ( q - p ) * 6 * ( 2 / 3 - t );
  994. return p;
  995. }
  996. function toComponents( source, target ) {
  997. target.r = source.r;
  998. target.g = source.g;
  999. target.b = source.b;
  1000. return target;
  1001. }
  1002. class Color {
  1003. constructor( r, g, b ) {
  1004. this.isColor = true;
  1005. this.r = 1;
  1006. this.g = 1;
  1007. this.b = 1;
  1008. if ( g === undefined && b === undefined ) {
  1009. // r is THREE.Color, hex or string
  1010. return this.set( r );
  1011. }
  1012. return this.setRGB( r, g, b );
  1013. }
  1014. set( value ) {
  1015. if ( value && value.isColor ) {
  1016. this.copy( value );
  1017. } else if ( typeof value === 'number' ) {
  1018. this.setHex( value );
  1019. } else if ( typeof value === 'string' ) {
  1020. this.setStyle( value );
  1021. }
  1022. return this;
  1023. }
  1024. setScalar( scalar ) {
  1025. this.r = scalar;
  1026. this.g = scalar;
  1027. this.b = scalar;
  1028. return this;
  1029. }
  1030. setHex( hex, colorSpace = SRGBColorSpace ) {
  1031. hex = Math.floor( hex );
  1032. this.r = ( hex >> 16 & 255 ) / 255;
  1033. this.g = ( hex >> 8 & 255 ) / 255;
  1034. this.b = ( hex & 255 ) / 255;
  1035. ColorManagement.toWorkingColorSpace( this, colorSpace );
  1036. return this;
  1037. }
  1038. setRGB( r, g, b, colorSpace = ColorManagement.workingColorSpace ) {
  1039. this.r = r;
  1040. this.g = g;
  1041. this.b = b;
  1042. ColorManagement.toWorkingColorSpace( this, colorSpace );
  1043. return this;
  1044. }
  1045. setHSL( h, s, l, colorSpace = ColorManagement.workingColorSpace ) {
  1046. // h,s,l ranges are in 0.0 - 1.0
  1047. h = euclideanModulo( h, 1 );
  1048. s = clamp( s, 0, 1 );
  1049. l = clamp( l, 0, 1 );
  1050. if ( s === 0 ) {
  1051. this.r = this.g = this.b = l;
  1052. } else {
  1053. const p = l <= 0.5 ? l * ( 1 + s ) : l + s - ( l * s );
  1054. const q = ( 2 * l ) - p;
  1055. this.r = hue2rgb( q, p, h + 1 / 3 );
  1056. this.g = hue2rgb( q, p, h );
  1057. this.b = hue2rgb( q, p, h - 1 / 3 );
  1058. }
  1059. ColorManagement.toWorkingColorSpace( this, colorSpace );
  1060. return this;
  1061. }
  1062. setStyle( style, colorSpace = SRGBColorSpace ) {
  1063. function handleAlpha( string ) {
  1064. if ( string === undefined ) return;
  1065. if ( parseFloat( string ) < 1 ) {
  1066. console.warn( 'THREE.Color: Alpha component of ' + style + ' will be ignored.' );
  1067. }
  1068. }
  1069. let m;
  1070. if ( m = /^((?:rgb|hsl)a?)\(([^\)]*)\)/.exec( style ) ) {
  1071. // rgb / hsl
  1072. let color;
  1073. const name = m[ 1 ];
  1074. const components = m[ 2 ];
  1075. switch ( name ) {
  1076. case 'rgb':
  1077. case 'rgba':
  1078. if ( color = /^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) {
  1079. // rgb(255,0,0) rgba(255,0,0,0.5)
  1080. this.r = Math.min( 255, parseInt( color[ 1 ], 10 ) ) / 255;
  1081. this.g = Math.min( 255, parseInt( color[ 2 ], 10 ) ) / 255;
  1082. this.b = Math.min( 255, parseInt( color[ 3 ], 10 ) ) / 255;
  1083. ColorManagement.toWorkingColorSpace( this, colorSpace );
  1084. handleAlpha( color[ 4 ] );
  1085. return this;
  1086. }
  1087. if ( color = /^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) {
  1088. // rgb(100%,0%,0%) rgba(100%,0%,0%,0.5)
  1089. this.r = Math.min( 100, parseInt( color[ 1 ], 10 ) ) / 100;
  1090. this.g = Math.min( 100, parseInt( color[ 2 ], 10 ) ) / 100;
  1091. this.b = Math.min( 100, parseInt( color[ 3 ], 10 ) ) / 100;
  1092. ColorManagement.toWorkingColorSpace( this, colorSpace );
  1093. handleAlpha( color[ 4 ] );
  1094. return this;
  1095. }
  1096. break;
  1097. case 'hsl':
  1098. case 'hsla':
  1099. if ( color = /^\s*(\d*\.?\d+)\s*,\s*(\d*\.?\d+)\%\s*,\s*(\d*\.?\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) {
  1100. // hsl(120,50%,50%) hsla(120,50%,50%,0.5)
  1101. const h = parseFloat( color[ 1 ] ) / 360;
  1102. const s = parseFloat( color[ 2 ] ) / 100;
  1103. const l = parseFloat( color[ 3 ] ) / 100;
  1104. handleAlpha( color[ 4 ] );
  1105. return this.setHSL( h, s, l, colorSpace );
  1106. }
  1107. break;
  1108. }
  1109. } else if ( m = /^\#([A-Fa-f\d]+)$/.exec( style ) ) {
  1110. // hex color
  1111. const hex = m[ 1 ];
  1112. const size = hex.length;
  1113. if ( size === 3 ) {
  1114. // #ff0
  1115. this.r = parseInt( hex.charAt( 0 ) + hex.charAt( 0 ), 16 ) / 255;
  1116. this.g = parseInt( hex.charAt( 1 ) + hex.charAt( 1 ), 16 ) / 255;
  1117. this.b = parseInt( hex.charAt( 2 ) + hex.charAt( 2 ), 16 ) / 255;
  1118. ColorManagement.toWorkingColorSpace( this, colorSpace );
  1119. return this;
  1120. } else if ( size === 6 ) {
  1121. // #ff0000
  1122. this.r = parseInt( hex.charAt( 0 ) + hex.charAt( 1 ), 16 ) / 255;
  1123. this.g = parseInt( hex.charAt( 2 ) + hex.charAt( 3 ), 16 ) / 255;
  1124. this.b = parseInt( hex.charAt( 4 ) + hex.charAt( 5 ), 16 ) / 255;
  1125. ColorManagement.toWorkingColorSpace( this, colorSpace );
  1126. return this;
  1127. }
  1128. }
  1129. if ( style && style.length > 0 ) {
  1130. return this.setColorName( style, colorSpace );
  1131. }
  1132. return this;
  1133. }
  1134. setColorName( style, colorSpace = SRGBColorSpace ) {
  1135. // color keywords
  1136. const hex = _colorKeywords[ style.toLowerCase() ];
  1137. if ( hex !== undefined ) {
  1138. // red
  1139. this.setHex( hex, colorSpace );
  1140. } else {
  1141. // unknown color
  1142. console.warn( 'THREE.Color: Unknown color ' + style );
  1143. }
  1144. return this;
  1145. }
  1146. clone() {
  1147. return new this.constructor( this.r, this.g, this.b );
  1148. }
  1149. copy( color ) {
  1150. this.r = color.r;
  1151. this.g = color.g;
  1152. this.b = color.b;
  1153. return this;
  1154. }
  1155. copySRGBToLinear( color ) {
  1156. this.r = SRGBToLinear( color.r );
  1157. this.g = SRGBToLinear( color.g );
  1158. this.b = SRGBToLinear( color.b );
  1159. return this;
  1160. }
  1161. copyLinearToSRGB( color ) {
  1162. this.r = LinearToSRGB( color.r );
  1163. this.g = LinearToSRGB( color.g );
  1164. this.b = LinearToSRGB( color.b );
  1165. return this;
  1166. }
  1167. convertSRGBToLinear() {
  1168. this.copySRGBToLinear( this );
  1169. return this;
  1170. }
  1171. convertLinearToSRGB() {
  1172. this.copyLinearToSRGB( this );
  1173. return this;
  1174. }
  1175. getHex( colorSpace = SRGBColorSpace ) {
  1176. ColorManagement.fromWorkingColorSpace( toComponents( this, _rgb$1 ), colorSpace );
  1177. return clamp( _rgb$1.r * 255, 0, 255 ) << 16 ^ clamp( _rgb$1.g * 255, 0, 255 ) << 8 ^ clamp( _rgb$1.b * 255, 0, 255 ) << 0;
  1178. }
  1179. getHexString( colorSpace = SRGBColorSpace ) {
  1180. return ( '000000' + this.getHex( colorSpace ).toString( 16 ) ).slice( - 6 );
  1181. }
  1182. getHSL( target, colorSpace = ColorManagement.workingColorSpace ) {
  1183. // h,s,l ranges are in 0.0 - 1.0
  1184. ColorManagement.fromWorkingColorSpace( toComponents( this, _rgb$1 ), colorSpace );
  1185. const r = _rgb$1.r, g = _rgb$1.g, b = _rgb$1.b;
  1186. const max = Math.max( r, g, b );
  1187. const min = Math.min( r, g, b );
  1188. let hue, saturation;
  1189. const lightness = ( min + max ) / 2.0;
  1190. if ( min === max ) {
  1191. hue = 0;
  1192. saturation = 0;
  1193. } else {
  1194. const delta = max - min;
  1195. saturation = lightness <= 0.5 ? delta / ( max + min ) : delta / ( 2 - max - min );
  1196. switch ( max ) {
  1197. case r: hue = ( g - b ) / delta + ( g < b ? 6 : 0 ); break;
  1198. case g: hue = ( b - r ) / delta + 2; break;
  1199. case b: hue = ( r - g ) / delta + 4; break;
  1200. }
  1201. hue /= 6;
  1202. }
  1203. target.h = hue;
  1204. target.s = saturation;
  1205. target.l = lightness;
  1206. return target;
  1207. }
  1208. getRGB( target, colorSpace = ColorManagement.workingColorSpace ) {
  1209. ColorManagement.fromWorkingColorSpace( toComponents( this, _rgb$1 ), colorSpace );
  1210. target.r = _rgb$1.r;
  1211. target.g = _rgb$1.g;
  1212. target.b = _rgb$1.b;
  1213. return target;
  1214. }
  1215. getStyle( colorSpace = SRGBColorSpace ) {
  1216. ColorManagement.fromWorkingColorSpace( toComponents( this, _rgb$1 ), colorSpace );
  1217. if ( colorSpace !== SRGBColorSpace ) {
  1218. // Requires CSS Color Module Level 4 (https://www.w3.org/TR/css-color-4/).
  1219. return `color(${ colorSpace } ${ _rgb$1.r } ${ _rgb$1.g } ${ _rgb$1.b })`;
  1220. }
  1221. return `rgb(${( _rgb$1.r * 255 ) | 0},${( _rgb$1.g * 255 ) | 0},${( _rgb$1.b * 255 ) | 0})`;
  1222. }
  1223. offsetHSL( h, s, l ) {
  1224. this.getHSL( _hslA );
  1225. _hslA.h += h; _hslA.s += s; _hslA.l += l;
  1226. this.setHSL( _hslA.h, _hslA.s, _hslA.l );
  1227. return this;
  1228. }
  1229. add( color ) {
  1230. this.r += color.r;
  1231. this.g += color.g;
  1232. this.b += color.b;
  1233. return this;
  1234. }
  1235. addColors( color1, color2 ) {
  1236. this.r = color1.r + color2.r;
  1237. this.g = color1.g + color2.g;
  1238. this.b = color1.b + color2.b;
  1239. return this;
  1240. }
  1241. addScalar( s ) {
  1242. this.r += s;
  1243. this.g += s;
  1244. this.b += s;
  1245. return this;
  1246. }
  1247. sub( color ) {
  1248. this.r = Math.max( 0, this.r - color.r );
  1249. this.g = Math.max( 0, this.g - color.g );
  1250. this.b = Math.max( 0, this.b - color.b );
  1251. return this;
  1252. }
  1253. multiply( color ) {
  1254. this.r *= color.r;
  1255. this.g *= color.g;
  1256. this.b *= color.b;
  1257. return this;
  1258. }
  1259. multiplyScalar( s ) {
  1260. this.r *= s;
  1261. this.g *= s;
  1262. this.b *= s;
  1263. return this;
  1264. }
  1265. lerp( color, alpha ) {
  1266. this.r += ( color.r - this.r ) * alpha;
  1267. this.g += ( color.g - this.g ) * alpha;
  1268. this.b += ( color.b - this.b ) * alpha;
  1269. return this;
  1270. }
  1271. lerpColors( color1, color2, alpha ) {
  1272. this.r = color1.r + ( color2.r - color1.r ) * alpha;
  1273. this.g = color1.g + ( color2.g - color1.g ) * alpha;
  1274. this.b = color1.b + ( color2.b - color1.b ) * alpha;
  1275. return this;
  1276. }
  1277. lerpHSL( color, alpha ) {
  1278. this.getHSL( _hslA );
  1279. color.getHSL( _hslB );
  1280. const h = lerp( _hslA.h, _hslB.h, alpha );
  1281. const s = lerp( _hslA.s, _hslB.s, alpha );
  1282. const l = lerp( _hslA.l, _hslB.l, alpha );
  1283. this.setHSL( h, s, l );
  1284. return this;
  1285. }
  1286. equals( c ) {
  1287. return ( c.r === this.r ) && ( c.g === this.g ) && ( c.b === this.b );
  1288. }
  1289. fromArray( array, offset = 0 ) {
  1290. this.r = array[ offset ];
  1291. this.g = array[ offset + 1 ];
  1292. this.b = array[ offset + 2 ];
  1293. return this;
  1294. }
  1295. toArray( array = [], offset = 0 ) {
  1296. array[ offset ] = this.r;
  1297. array[ offset + 1 ] = this.g;
  1298. array[ offset + 2 ] = this.b;
  1299. return array;
  1300. }
  1301. fromBufferAttribute( attribute, index ) {
  1302. this.r = attribute.getX( index );
  1303. this.g = attribute.getY( index );
  1304. this.b = attribute.getZ( index );
  1305. return this;
  1306. }
  1307. toJSON() {
  1308. return this.getHex();
  1309. }
  1310. *[ Symbol.iterator ]() {
  1311. yield this.r;
  1312. yield this.g;
  1313. yield this.b;
  1314. }
  1315. }
  1316. Color.NAMES = _colorKeywords;
  1317. let _canvas;
  1318. class ImageUtils {
  1319. static getDataURL( image ) {
  1320. if ( /^data:/i.test( image.src ) ) {
  1321. return image.src;
  1322. }
  1323. if ( typeof HTMLCanvasElement == 'undefined' ) {
  1324. return image.src;
  1325. }
  1326. let canvas;
  1327. if ( image instanceof HTMLCanvasElement ) {
  1328. canvas = image;
  1329. } else {
  1330. if ( _canvas === undefined ) _canvas = createElementNS( 'canvas' );
  1331. _canvas.width = image.width;
  1332. _canvas.height = image.height;
  1333. const context = _canvas.getContext( '2d' );
  1334. if ( image instanceof ImageData ) {
  1335. context.putImageData( image, 0, 0 );
  1336. } else {
  1337. context.drawImage( image, 0, 0, image.width, image.height );
  1338. }
  1339. canvas = _canvas;
  1340. }
  1341. if ( canvas.width > 2048 || canvas.height > 2048 ) {
  1342. console.warn( 'THREE.ImageUtils.getDataURL: Image converted to jpg for performance reasons', image );
  1343. return canvas.toDataURL( 'image/jpeg', 0.6 );
  1344. } else {
  1345. return canvas.toDataURL( 'image/png' );
  1346. }
  1347. }
  1348. static sRGBToLinear( image ) {
  1349. if ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) ||
  1350. ( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) ||
  1351. ( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) ) {
  1352. const canvas = createElementNS( 'canvas' );
  1353. canvas.width = image.width;
  1354. canvas.height = image.height;
  1355. const context = canvas.getContext( '2d' );
  1356. context.drawImage( image, 0, 0, image.width, image.height );
  1357. const imageData = context.getImageData( 0, 0, image.width, image.height );
  1358. const data = imageData.data;
  1359. for ( let i = 0; i < data.length; i ++ ) {
  1360. data[ i ] = SRGBToLinear( data[ i ] / 255 ) * 255;
  1361. }
  1362. context.putImageData( imageData, 0, 0 );
  1363. return canvas;
  1364. } else if ( image.data ) {
  1365. const data = image.data.slice( 0 );
  1366. for ( let i = 0; i < data.length; i ++ ) {
  1367. if ( data instanceof Uint8Array || data instanceof Uint8ClampedArray ) {
  1368. data[ i ] = Math.floor( SRGBToLinear( data[ i ] / 255 ) * 255 );
  1369. } else {
  1370. // assuming float
  1371. data[ i ] = SRGBToLinear( data[ i ] );
  1372. }
  1373. }
  1374. return {
  1375. data: data,
  1376. width: image.width,
  1377. height: image.height
  1378. };
  1379. } else {
  1380. console.warn( 'THREE.ImageUtils.sRGBToLinear(): Unsupported image type. No color space conversion applied.' );
  1381. return image;
  1382. }
  1383. }
  1384. }
  1385. class Source {
  1386. constructor( data = null ) {
  1387. this.isSource = true;
  1388. this.uuid = generateUUID();
  1389. this.data = data;
  1390. this.version = 0;
  1391. }
  1392. set needsUpdate( value ) {
  1393. if ( value === true ) this.version ++;
  1394. }
  1395. toJSON( meta ) {
  1396. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  1397. if ( ! isRootObject && meta.images[ this.uuid ] !== undefined ) {
  1398. return meta.images[ this.uuid ];
  1399. }
  1400. const output = {
  1401. uuid: this.uuid,
  1402. url: ''
  1403. };
  1404. const data = this.data;
  1405. if ( data !== null ) {
  1406. let url;
  1407. if ( Array.isArray( data ) ) {
  1408. // cube texture
  1409. url = [];
  1410. for ( let i = 0, l = data.length; i < l; i ++ ) {
  1411. if ( data[ i ].isDataTexture ) {
  1412. url.push( serializeImage( data[ i ].image ) );
  1413. } else {
  1414. url.push( serializeImage( data[ i ] ) );
  1415. }
  1416. }
  1417. } else {
  1418. // texture
  1419. url = serializeImage( data );
  1420. }
  1421. output.url = url;
  1422. }
  1423. if ( ! isRootObject ) {
  1424. meta.images[ this.uuid ] = output;
  1425. }
  1426. return output;
  1427. }
  1428. }
  1429. function serializeImage( image ) {
  1430. if ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) ||
  1431. ( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) ||
  1432. ( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) ) {
  1433. // default images
  1434. return ImageUtils.getDataURL( image );
  1435. } else {
  1436. if ( image.data ) {
  1437. // images of DataTexture
  1438. return {
  1439. data: Array.from( image.data ),
  1440. width: image.width,
  1441. height: image.height,
  1442. type: image.data.constructor.name
  1443. };
  1444. } else {
  1445. console.warn( 'THREE.Texture: Unable to serialize Texture.' );
  1446. return {};
  1447. }
  1448. }
  1449. }
  1450. let textureId = 0;
  1451. class Texture extends EventDispatcher {
  1452. 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, encoding = LinearEncoding ) {
  1453. super();
  1454. this.isTexture = true;
  1455. Object.defineProperty( this, 'id', { value: textureId ++ } );
  1456. this.uuid = generateUUID();
  1457. this.name = '';
  1458. this.source = new Source( image );
  1459. this.mipmaps = [];
  1460. this.mapping = mapping;
  1461. this.wrapS = wrapS;
  1462. this.wrapT = wrapT;
  1463. this.magFilter = magFilter;
  1464. this.minFilter = minFilter;
  1465. this.anisotropy = anisotropy;
  1466. this.format = format;
  1467. this.internalFormat = null;
  1468. this.type = type;
  1469. this.offset = new Vector2( 0, 0 );
  1470. this.repeat = new Vector2( 1, 1 );
  1471. this.center = new Vector2( 0, 0 );
  1472. this.rotation = 0;
  1473. this.matrixAutoUpdate = true;
  1474. this.matrix = new Matrix3();
  1475. this.generateMipmaps = true;
  1476. this.premultiplyAlpha = false;
  1477. this.flipY = true;
  1478. this.unpackAlignment = 4; // valid values: 1, 2, 4, 8 (see http://www.khronos.org/opengles/sdk/docs/man/xhtml/glPixelStorei.xml)
  1479. // Values of encoding !== THREE.LinearEncoding only supported on map, envMap and emissiveMap.
  1480. //
  1481. // Also changing the encoding after already used by a Material will not automatically make the Material
  1482. // update. You need to explicitly call Material.needsUpdate to trigger it to recompile.
  1483. this.encoding = encoding;
  1484. this.userData = {};
  1485. this.version = 0;
  1486. this.onUpdate = null;
  1487. this.isRenderTargetTexture = false; // indicates whether a texture belongs to a render target or not
  1488. this.needsPMREMUpdate = false; // indicates whether this texture should be processed by PMREMGenerator or not (only relevant for render target textures)
  1489. }
  1490. get image() {
  1491. return this.source.data;
  1492. }
  1493. set image( value ) {
  1494. this.source.data = value;
  1495. }
  1496. updateMatrix() {
  1497. this.matrix.setUvTransform( this.offset.x, this.offset.y, this.repeat.x, this.repeat.y, this.rotation, this.center.x, this.center.y );
  1498. }
  1499. clone() {
  1500. return new this.constructor().copy( this );
  1501. }
  1502. copy( source ) {
  1503. this.name = source.name;
  1504. this.source = source.source;
  1505. this.mipmaps = source.mipmaps.slice( 0 );
  1506. this.mapping = source.mapping;
  1507. this.wrapS = source.wrapS;
  1508. this.wrapT = source.wrapT;
  1509. this.magFilter = source.magFilter;
  1510. this.minFilter = source.minFilter;
  1511. this.anisotropy = source.anisotropy;
  1512. this.format = source.format;
  1513. this.internalFormat = source.internalFormat;
  1514. this.type = source.type;
  1515. this.offset.copy( source.offset );
  1516. this.repeat.copy( source.repeat );
  1517. this.center.copy( source.center );
  1518. this.rotation = source.rotation;
  1519. this.matrixAutoUpdate = source.matrixAutoUpdate;
  1520. this.matrix.copy( source.matrix );
  1521. this.generateMipmaps = source.generateMipmaps;
  1522. this.premultiplyAlpha = source.premultiplyAlpha;
  1523. this.flipY = source.flipY;
  1524. this.unpackAlignment = source.unpackAlignment;
  1525. this.encoding = source.encoding;
  1526. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  1527. this.needsUpdate = true;
  1528. return this;
  1529. }
  1530. toJSON( meta ) {
  1531. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  1532. if ( ! isRootObject && meta.textures[ this.uuid ] !== undefined ) {
  1533. return meta.textures[ this.uuid ];
  1534. }
  1535. const output = {
  1536. metadata: {
  1537. version: 4.5,
  1538. type: 'Texture',
  1539. generator: 'Texture.toJSON'
  1540. },
  1541. uuid: this.uuid,
  1542. name: this.name,
  1543. image: this.source.toJSON( meta ).uuid,
  1544. mapping: this.mapping,
  1545. repeat: [ this.repeat.x, this.repeat.y ],
  1546. offset: [ this.offset.x, this.offset.y ],
  1547. center: [ this.center.x, this.center.y ],
  1548. rotation: this.rotation,
  1549. wrap: [ this.wrapS, this.wrapT ],
  1550. format: this.format,
  1551. type: this.type,
  1552. encoding: this.encoding,
  1553. minFilter: this.minFilter,
  1554. magFilter: this.magFilter,
  1555. anisotropy: this.anisotropy,
  1556. flipY: this.flipY,
  1557. generateMipmaps: this.generateMipmaps,
  1558. premultiplyAlpha: this.premultiplyAlpha,
  1559. unpackAlignment: this.unpackAlignment
  1560. };
  1561. if ( Object.keys( this.userData ).length > 0 ) output.userData = this.userData;
  1562. if ( ! isRootObject ) {
  1563. meta.textures[ this.uuid ] = output;
  1564. }
  1565. return output;
  1566. }
  1567. dispose() {
  1568. this.dispatchEvent( { type: 'dispose' } );
  1569. }
  1570. transformUv( uv ) {
  1571. if ( this.mapping !== UVMapping ) return uv;
  1572. uv.applyMatrix3( this.matrix );
  1573. if ( uv.x < 0 || uv.x > 1 ) {
  1574. switch ( this.wrapS ) {
  1575. case RepeatWrapping:
  1576. uv.x = uv.x - Math.floor( uv.x );
  1577. break;
  1578. case ClampToEdgeWrapping:
  1579. uv.x = uv.x < 0 ? 0 : 1;
  1580. break;
  1581. case MirroredRepeatWrapping:
  1582. if ( Math.abs( Math.floor( uv.x ) % 2 ) === 1 ) {
  1583. uv.x = Math.ceil( uv.x ) - uv.x;
  1584. } else {
  1585. uv.x = uv.x - Math.floor( uv.x );
  1586. }
  1587. break;
  1588. }
  1589. }
  1590. if ( uv.y < 0 || uv.y > 1 ) {
  1591. switch ( this.wrapT ) {
  1592. case RepeatWrapping:
  1593. uv.y = uv.y - Math.floor( uv.y );
  1594. break;
  1595. case ClampToEdgeWrapping:
  1596. uv.y = uv.y < 0 ? 0 : 1;
  1597. break;
  1598. case MirroredRepeatWrapping:
  1599. if ( Math.abs( Math.floor( uv.y ) % 2 ) === 1 ) {
  1600. uv.y = Math.ceil( uv.y ) - uv.y;
  1601. } else {
  1602. uv.y = uv.y - Math.floor( uv.y );
  1603. }
  1604. break;
  1605. }
  1606. }
  1607. if ( this.flipY ) {
  1608. uv.y = 1 - uv.y;
  1609. }
  1610. return uv;
  1611. }
  1612. set needsUpdate( value ) {
  1613. if ( value === true ) {
  1614. this.version ++;
  1615. this.source.needsUpdate = true;
  1616. }
  1617. }
  1618. }
  1619. Texture.DEFAULT_IMAGE = null;
  1620. Texture.DEFAULT_MAPPING = UVMapping;
  1621. Texture.DEFAULT_ANISOTROPY = 1;
  1622. class Vector4 {
  1623. constructor( x = 0, y = 0, z = 0, w = 1 ) {
  1624. Vector4.prototype.isVector4 = true;
  1625. this.x = x;
  1626. this.y = y;
  1627. this.z = z;
  1628. this.w = w;
  1629. }
  1630. get width() {
  1631. return this.z;
  1632. }
  1633. set width( value ) {
  1634. this.z = value;
  1635. }
  1636. get height() {
  1637. return this.w;
  1638. }
  1639. set height( value ) {
  1640. this.w = value;
  1641. }
  1642. set( x, y, z, w ) {
  1643. this.x = x;
  1644. this.y = y;
  1645. this.z = z;
  1646. this.w = w;
  1647. return this;
  1648. }
  1649. setScalar( scalar ) {
  1650. this.x = scalar;
  1651. this.y = scalar;
  1652. this.z = scalar;
  1653. this.w = scalar;
  1654. return this;
  1655. }
  1656. setX( x ) {
  1657. this.x = x;
  1658. return this;
  1659. }
  1660. setY( y ) {
  1661. this.y = y;
  1662. return this;
  1663. }
  1664. setZ( z ) {
  1665. this.z = z;
  1666. return this;
  1667. }
  1668. setW( w ) {
  1669. this.w = w;
  1670. return this;
  1671. }
  1672. setComponent( index, value ) {
  1673. switch ( index ) {
  1674. case 0: this.x = value; break;
  1675. case 1: this.y = value; break;
  1676. case 2: this.z = value; break;
  1677. case 3: this.w = value; break;
  1678. default: throw new Error( 'index is out of range: ' + index );
  1679. }
  1680. return this;
  1681. }
  1682. getComponent( index ) {
  1683. switch ( index ) {
  1684. case 0: return this.x;
  1685. case 1: return this.y;
  1686. case 2: return this.z;
  1687. case 3: return this.w;
  1688. default: throw new Error( 'index is out of range: ' + index );
  1689. }
  1690. }
  1691. clone() {
  1692. return new this.constructor( this.x, this.y, this.z, this.w );
  1693. }
  1694. copy( v ) {
  1695. this.x = v.x;
  1696. this.y = v.y;
  1697. this.z = v.z;
  1698. this.w = ( v.w !== undefined ) ? v.w : 1;
  1699. return this;
  1700. }
  1701. add( v ) {
  1702. this.x += v.x;
  1703. this.y += v.y;
  1704. this.z += v.z;
  1705. this.w += v.w;
  1706. return this;
  1707. }
  1708. addScalar( s ) {
  1709. this.x += s;
  1710. this.y += s;
  1711. this.z += s;
  1712. this.w += s;
  1713. return this;
  1714. }
  1715. addVectors( a, b ) {
  1716. this.x = a.x + b.x;
  1717. this.y = a.y + b.y;
  1718. this.z = a.z + b.z;
  1719. this.w = a.w + b.w;
  1720. return this;
  1721. }
  1722. addScaledVector( v, s ) {
  1723. this.x += v.x * s;
  1724. this.y += v.y * s;
  1725. this.z += v.z * s;
  1726. this.w += v.w * s;
  1727. return this;
  1728. }
  1729. sub( v ) {
  1730. this.x -= v.x;
  1731. this.y -= v.y;
  1732. this.z -= v.z;
  1733. this.w -= v.w;
  1734. return this;
  1735. }
  1736. subScalar( s ) {
  1737. this.x -= s;
  1738. this.y -= s;
  1739. this.z -= s;
  1740. this.w -= s;
  1741. return this;
  1742. }
  1743. subVectors( a, b ) {
  1744. this.x = a.x - b.x;
  1745. this.y = a.y - b.y;
  1746. this.z = a.z - b.z;
  1747. this.w = a.w - b.w;
  1748. return this;
  1749. }
  1750. multiply( v ) {
  1751. this.x *= v.x;
  1752. this.y *= v.y;
  1753. this.z *= v.z;
  1754. this.w *= v.w;
  1755. return this;
  1756. }
  1757. multiplyScalar( scalar ) {
  1758. this.x *= scalar;
  1759. this.y *= scalar;
  1760. this.z *= scalar;
  1761. this.w *= scalar;
  1762. return this;
  1763. }
  1764. applyMatrix4( m ) {
  1765. const x = this.x, y = this.y, z = this.z, w = this.w;
  1766. const e = m.elements;
  1767. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] * w;
  1768. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] * w;
  1769. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] * w;
  1770. this.w = e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] * w;
  1771. return this;
  1772. }
  1773. divideScalar( scalar ) {
  1774. return this.multiplyScalar( 1 / scalar );
  1775. }
  1776. setAxisAngleFromQuaternion( q ) {
  1777. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToAngle/index.htm
  1778. // q is assumed to be normalized
  1779. this.w = 2 * Math.acos( q.w );
  1780. const s = Math.sqrt( 1 - q.w * q.w );
  1781. if ( s < 0.0001 ) {
  1782. this.x = 1;
  1783. this.y = 0;
  1784. this.z = 0;
  1785. } else {
  1786. this.x = q.x / s;
  1787. this.y = q.y / s;
  1788. this.z = q.z / s;
  1789. }
  1790. return this;
  1791. }
  1792. setAxisAngleFromRotationMatrix( m ) {
  1793. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToAngle/index.htm
  1794. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  1795. let angle, x, y, z; // variables for result
  1796. const epsilon = 0.01, // margin to allow for rounding errors
  1797. epsilon2 = 0.1, // margin to distinguish between 0 and 180 degrees
  1798. te = m.elements,
  1799. m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ],
  1800. m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ],
  1801. m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];
  1802. if ( ( Math.abs( m12 - m21 ) < epsilon ) &&
  1803. ( Math.abs( m13 - m31 ) < epsilon ) &&
  1804. ( Math.abs( m23 - m32 ) < epsilon ) ) {
  1805. // singularity found
  1806. // first check for identity matrix which must have +1 for all terms
  1807. // in leading diagonal and zero in other terms
  1808. if ( ( Math.abs( m12 + m21 ) < epsilon2 ) &&
  1809. ( Math.abs( m13 + m31 ) < epsilon2 ) &&
  1810. ( Math.abs( m23 + m32 ) < epsilon2 ) &&
  1811. ( Math.abs( m11 + m22 + m33 - 3 ) < epsilon2 ) ) {
  1812. // this singularity is identity matrix so angle = 0
  1813. this.set( 1, 0, 0, 0 );
  1814. return this; // zero angle, arbitrary axis
  1815. }
  1816. // otherwise this singularity is angle = 180
  1817. angle = Math.PI;
  1818. const xx = ( m11 + 1 ) / 2;
  1819. const yy = ( m22 + 1 ) / 2;
  1820. const zz = ( m33 + 1 ) / 2;
  1821. const xy = ( m12 + m21 ) / 4;
  1822. const xz = ( m13 + m31 ) / 4;
  1823. const yz = ( m23 + m32 ) / 4;
  1824. if ( ( xx > yy ) && ( xx > zz ) ) {
  1825. // m11 is the largest diagonal term
  1826. if ( xx < epsilon ) {
  1827. x = 0;
  1828. y = 0.707106781;
  1829. z = 0.707106781;
  1830. } else {
  1831. x = Math.sqrt( xx );
  1832. y = xy / x;
  1833. z = xz / x;
  1834. }
  1835. } else if ( yy > zz ) {
  1836. // m22 is the largest diagonal term
  1837. if ( yy < epsilon ) {
  1838. x = 0.707106781;
  1839. y = 0;
  1840. z = 0.707106781;
  1841. } else {
  1842. y = Math.sqrt( yy );
  1843. x = xy / y;
  1844. z = yz / y;
  1845. }
  1846. } else {
  1847. // m33 is the largest diagonal term so base result on this
  1848. if ( zz < epsilon ) {
  1849. x = 0.707106781;
  1850. y = 0.707106781;
  1851. z = 0;
  1852. } else {
  1853. z = Math.sqrt( zz );
  1854. x = xz / z;
  1855. y = yz / z;
  1856. }
  1857. }
  1858. this.set( x, y, z, angle );
  1859. return this; // return 180 deg rotation
  1860. }
  1861. // as we have reached here there are no singularities so we can handle normally
  1862. let s = Math.sqrt( ( m32 - m23 ) * ( m32 - m23 ) +
  1863. ( m13 - m31 ) * ( m13 - m31 ) +
  1864. ( m21 - m12 ) * ( m21 - m12 ) ); // used to normalize
  1865. if ( Math.abs( s ) < 0.001 ) s = 1;
  1866. // prevent divide by zero, should not happen if matrix is orthogonal and should be
  1867. // caught by singularity test above, but I've left it in just in case
  1868. this.x = ( m32 - m23 ) / s;
  1869. this.y = ( m13 - m31 ) / s;
  1870. this.z = ( m21 - m12 ) / s;
  1871. this.w = Math.acos( ( m11 + m22 + m33 - 1 ) / 2 );
  1872. return this;
  1873. }
  1874. min( v ) {
  1875. this.x = Math.min( this.x, v.x );
  1876. this.y = Math.min( this.y, v.y );
  1877. this.z = Math.min( this.z, v.z );
  1878. this.w = Math.min( this.w, v.w );
  1879. return this;
  1880. }
  1881. max( v ) {
  1882. this.x = Math.max( this.x, v.x );
  1883. this.y = Math.max( this.y, v.y );
  1884. this.z = Math.max( this.z, v.z );
  1885. this.w = Math.max( this.w, v.w );
  1886. return this;
  1887. }
  1888. clamp( min, max ) {
  1889. // assumes min < max, componentwise
  1890. this.x = Math.max( min.x, Math.min( max.x, this.x ) );
  1891. this.y = Math.max( min.y, Math.min( max.y, this.y ) );
  1892. this.z = Math.max( min.z, Math.min( max.z, this.z ) );
  1893. this.w = Math.max( min.w, Math.min( max.w, this.w ) );
  1894. return this;
  1895. }
  1896. clampScalar( minVal, maxVal ) {
  1897. this.x = Math.max( minVal, Math.min( maxVal, this.x ) );
  1898. this.y = Math.max( minVal, Math.min( maxVal, this.y ) );
  1899. this.z = Math.max( minVal, Math.min( maxVal, this.z ) );
  1900. this.w = Math.max( minVal, Math.min( maxVal, this.w ) );
  1901. return this;
  1902. }
  1903. clampLength( min, max ) {
  1904. const length = this.length();
  1905. return this.divideScalar( length || 1 ).multiplyScalar( Math.max( min, Math.min( max, length ) ) );
  1906. }
  1907. floor() {
  1908. this.x = Math.floor( this.x );
  1909. this.y = Math.floor( this.y );
  1910. this.z = Math.floor( this.z );
  1911. this.w = Math.floor( this.w );
  1912. return this;
  1913. }
  1914. ceil() {
  1915. this.x = Math.ceil( this.x );
  1916. this.y = Math.ceil( this.y );
  1917. this.z = Math.ceil( this.z );
  1918. this.w = Math.ceil( this.w );
  1919. return this;
  1920. }
  1921. round() {
  1922. this.x = Math.round( this.x );
  1923. this.y = Math.round( this.y );
  1924. this.z = Math.round( this.z );
  1925. this.w = Math.round( this.w );
  1926. return this;
  1927. }
  1928. roundToZero() {
  1929. this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x );
  1930. this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y );
  1931. this.z = ( this.z < 0 ) ? Math.ceil( this.z ) : Math.floor( this.z );
  1932. this.w = ( this.w < 0 ) ? Math.ceil( this.w ) : Math.floor( this.w );
  1933. return this;
  1934. }
  1935. negate() {
  1936. this.x = - this.x;
  1937. this.y = - this.y;
  1938. this.z = - this.z;
  1939. this.w = - this.w;
  1940. return this;
  1941. }
  1942. dot( v ) {
  1943. return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w;
  1944. }
  1945. lengthSq() {
  1946. return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w;
  1947. }
  1948. length() {
  1949. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w );
  1950. }
  1951. manhattanLength() {
  1952. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z ) + Math.abs( this.w );
  1953. }
  1954. normalize() {
  1955. return this.divideScalar( this.length() || 1 );
  1956. }
  1957. setLength( length ) {
  1958. return this.normalize().multiplyScalar( length );
  1959. }
  1960. lerp( v, alpha ) {
  1961. this.x += ( v.x - this.x ) * alpha;
  1962. this.y += ( v.y - this.y ) * alpha;
  1963. this.z += ( v.z - this.z ) * alpha;
  1964. this.w += ( v.w - this.w ) * alpha;
  1965. return this;
  1966. }
  1967. lerpVectors( v1, v2, alpha ) {
  1968. this.x = v1.x + ( v2.x - v1.x ) * alpha;
  1969. this.y = v1.y + ( v2.y - v1.y ) * alpha;
  1970. this.z = v1.z + ( v2.z - v1.z ) * alpha;
  1971. this.w = v1.w + ( v2.w - v1.w ) * alpha;
  1972. return this;
  1973. }
  1974. equals( v ) {
  1975. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) && ( v.w === this.w ) );
  1976. }
  1977. fromArray( array, offset = 0 ) {
  1978. this.x = array[ offset ];
  1979. this.y = array[ offset + 1 ];
  1980. this.z = array[ offset + 2 ];
  1981. this.w = array[ offset + 3 ];
  1982. return this;
  1983. }
  1984. toArray( array = [], offset = 0 ) {
  1985. array[ offset ] = this.x;
  1986. array[ offset + 1 ] = this.y;
  1987. array[ offset + 2 ] = this.z;
  1988. array[ offset + 3 ] = this.w;
  1989. return array;
  1990. }
  1991. fromBufferAttribute( attribute, index ) {
  1992. this.x = attribute.getX( index );
  1993. this.y = attribute.getY( index );
  1994. this.z = attribute.getZ( index );
  1995. this.w = attribute.getW( index );
  1996. return this;
  1997. }
  1998. random() {
  1999. this.x = Math.random();
  2000. this.y = Math.random();
  2001. this.z = Math.random();
  2002. this.w = Math.random();
  2003. return this;
  2004. }
  2005. *[ Symbol.iterator ]() {
  2006. yield this.x;
  2007. yield this.y;
  2008. yield this.z;
  2009. yield this.w;
  2010. }
  2011. }
  2012. /*
  2013. In options, we can specify:
  2014. * Texture parameters for an auto-generated target texture
  2015. * depthBuffer/stencilBuffer: Booleans to indicate if we should generate these buffers
  2016. */
  2017. class WebGLRenderTarget extends EventDispatcher {
  2018. constructor( width = 1, height = 1, options = {} ) {
  2019. super();
  2020. this.isWebGLRenderTarget = true;
  2021. this.width = width;
  2022. this.height = height;
  2023. this.depth = 1;
  2024. this.scissor = new Vector4( 0, 0, width, height );
  2025. this.scissorTest = false;
  2026. this.viewport = new Vector4( 0, 0, width, height );
  2027. const image = { width: width, height: height, depth: 1 };
  2028. this.texture = new Texture( image, options.mapping, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.encoding );
  2029. this.texture.isRenderTargetTexture = true;
  2030. this.texture.flipY = false;
  2031. this.texture.generateMipmaps = options.generateMipmaps !== undefined ? options.generateMipmaps : false;
  2032. this.texture.internalFormat = options.internalFormat !== undefined ? options.internalFormat : null;
  2033. this.texture.minFilter = options.minFilter !== undefined ? options.minFilter : LinearFilter;
  2034. this.depthBuffer = options.depthBuffer !== undefined ? options.depthBuffer : true;
  2035. this.stencilBuffer = options.stencilBuffer !== undefined ? options.stencilBuffer : false;
  2036. this.depthTexture = options.depthTexture !== undefined ? options.depthTexture : null;
  2037. this.samples = options.samples !== undefined ? options.samples : 0;
  2038. }
  2039. setSize( width, height, depth = 1 ) {
  2040. if ( this.width !== width || this.height !== height || this.depth !== depth ) {
  2041. this.width = width;
  2042. this.height = height;
  2043. this.depth = depth;
  2044. this.texture.image.width = width;
  2045. this.texture.image.height = height;
  2046. this.texture.image.depth = depth;
  2047. this.dispose();
  2048. }
  2049. this.viewport.set( 0, 0, width, height );
  2050. this.scissor.set( 0, 0, width, height );
  2051. }
  2052. clone() {
  2053. return new this.constructor().copy( this );
  2054. }
  2055. copy( source ) {
  2056. this.width = source.width;
  2057. this.height = source.height;
  2058. this.depth = source.depth;
  2059. this.viewport.copy( source.viewport );
  2060. this.texture = source.texture.clone();
  2061. this.texture.isRenderTargetTexture = true;
  2062. // ensure image object is not shared, see #20328
  2063. const image = Object.assign( {}, source.texture.image );
  2064. this.texture.source = new Source( image );
  2065. this.depthBuffer = source.depthBuffer;
  2066. this.stencilBuffer = source.stencilBuffer;
  2067. if ( source.depthTexture !== null ) this.depthTexture = source.depthTexture.clone();
  2068. this.samples = source.samples;
  2069. return this;
  2070. }
  2071. dispose() {
  2072. this.dispatchEvent( { type: 'dispose' } );
  2073. }
  2074. }
  2075. class DataArrayTexture extends Texture {
  2076. constructor( data = null, width = 1, height = 1, depth = 1 ) {
  2077. super( null );
  2078. this.isDataArrayTexture = true;
  2079. this.image = { data, width, height, depth };
  2080. this.magFilter = NearestFilter;
  2081. this.minFilter = NearestFilter;
  2082. this.wrapR = ClampToEdgeWrapping;
  2083. this.generateMipmaps = false;
  2084. this.flipY = false;
  2085. this.unpackAlignment = 1;
  2086. }
  2087. }
  2088. class WebGLArrayRenderTarget extends WebGLRenderTarget {
  2089. constructor( width = 1, height = 1, depth = 1 ) {
  2090. super( width, height );
  2091. this.isWebGLArrayRenderTarget = true;
  2092. this.depth = depth;
  2093. this.texture = new DataArrayTexture( null, width, height, depth );
  2094. this.texture.isRenderTargetTexture = true;
  2095. }
  2096. }
  2097. class Data3DTexture extends Texture {
  2098. constructor( data = null, width = 1, height = 1, depth = 1 ) {
  2099. // We're going to add .setXXX() methods for setting properties later.
  2100. // Users can still set in DataTexture3D directly.
  2101. //
  2102. // const texture = new THREE.DataTexture3D( data, width, height, depth );
  2103. // texture.anisotropy = 16;
  2104. //
  2105. // See #14839
  2106. super( null );
  2107. this.isData3DTexture = true;
  2108. this.image = { data, width, height, depth };
  2109. this.magFilter = NearestFilter;
  2110. this.minFilter = NearestFilter;
  2111. this.wrapR = ClampToEdgeWrapping;
  2112. this.generateMipmaps = false;
  2113. this.flipY = false;
  2114. this.unpackAlignment = 1;
  2115. }
  2116. }
  2117. class WebGL3DRenderTarget extends WebGLRenderTarget {
  2118. constructor( width = 1, height = 1, depth = 1 ) {
  2119. super( width, height );
  2120. this.isWebGL3DRenderTarget = true;
  2121. this.depth = depth;
  2122. this.texture = new Data3DTexture( null, width, height, depth );
  2123. this.texture.isRenderTargetTexture = true;
  2124. }
  2125. }
  2126. class WebGLMultipleRenderTargets extends WebGLRenderTarget {
  2127. constructor( width = 1, height = 1, count = 1, options = {} ) {
  2128. super( width, height, options );
  2129. this.isWebGLMultipleRenderTargets = true;
  2130. const texture = this.texture;
  2131. this.texture = [];
  2132. for ( let i = 0; i < count; i ++ ) {
  2133. this.texture[ i ] = texture.clone();
  2134. this.texture[ i ].isRenderTargetTexture = true;
  2135. }
  2136. }
  2137. setSize( width, height, depth = 1 ) {
  2138. if ( this.width !== width || this.height !== height || this.depth !== depth ) {
  2139. this.width = width;
  2140. this.height = height;
  2141. this.depth = depth;
  2142. for ( let i = 0, il = this.texture.length; i < il; i ++ ) {
  2143. this.texture[ i ].image.width = width;
  2144. this.texture[ i ].image.height = height;
  2145. this.texture[ i ].image.depth = depth;
  2146. }
  2147. this.dispose();
  2148. }
  2149. this.viewport.set( 0, 0, width, height );
  2150. this.scissor.set( 0, 0, width, height );
  2151. return this;
  2152. }
  2153. copy( source ) {
  2154. this.dispose();
  2155. this.width = source.width;
  2156. this.height = source.height;
  2157. this.depth = source.depth;
  2158. this.viewport.set( 0, 0, this.width, this.height );
  2159. this.scissor.set( 0, 0, this.width, this.height );
  2160. this.depthBuffer = source.depthBuffer;
  2161. this.stencilBuffer = source.stencilBuffer;
  2162. if ( source.depthTexture !== null ) this.depthTexture = source.depthTexture.clone();
  2163. this.texture.length = 0;
  2164. for ( let i = 0, il = source.texture.length; i < il; i ++ ) {
  2165. this.texture[ i ] = source.texture[ i ].clone();
  2166. this.texture[ i ].isRenderTargetTexture = true;
  2167. }
  2168. return this;
  2169. }
  2170. }
  2171. class Quaternion {
  2172. constructor( x = 0, y = 0, z = 0, w = 1 ) {
  2173. this.isQuaternion = true;
  2174. this._x = x;
  2175. this._y = y;
  2176. this._z = z;
  2177. this._w = w;
  2178. }
  2179. static slerpFlat( dst, dstOffset, src0, srcOffset0, src1, srcOffset1, t ) {
  2180. // fuzz-free, array-based Quaternion SLERP operation
  2181. let x0 = src0[ srcOffset0 + 0 ],
  2182. y0 = src0[ srcOffset0 + 1 ],
  2183. z0 = src0[ srcOffset0 + 2 ],
  2184. w0 = src0[ srcOffset0 + 3 ];
  2185. const x1 = src1[ srcOffset1 + 0 ],
  2186. y1 = src1[ srcOffset1 + 1 ],
  2187. z1 = src1[ srcOffset1 + 2 ],
  2188. w1 = src1[ srcOffset1 + 3 ];
  2189. if ( t === 0 ) {
  2190. dst[ dstOffset + 0 ] = x0;
  2191. dst[ dstOffset + 1 ] = y0;
  2192. dst[ dstOffset + 2 ] = z0;
  2193. dst[ dstOffset + 3 ] = w0;
  2194. return;
  2195. }
  2196. if ( t === 1 ) {
  2197. dst[ dstOffset + 0 ] = x1;
  2198. dst[ dstOffset + 1 ] = y1;
  2199. dst[ dstOffset + 2 ] = z1;
  2200. dst[ dstOffset + 3 ] = w1;
  2201. return;
  2202. }
  2203. if ( w0 !== w1 || x0 !== x1 || y0 !== y1 || z0 !== z1 ) {
  2204. let s = 1 - t;
  2205. const cos = x0 * x1 + y0 * y1 + z0 * z1 + w0 * w1,
  2206. dir = ( cos >= 0 ? 1 : - 1 ),
  2207. sqrSin = 1 - cos * cos;
  2208. // Skip the Slerp for tiny steps to avoid numeric problems:
  2209. if ( sqrSin > Number.EPSILON ) {
  2210. const sin = Math.sqrt( sqrSin ),
  2211. len = Math.atan2( sin, cos * dir );
  2212. s = Math.sin( s * len ) / sin;
  2213. t = Math.sin( t * len ) / sin;
  2214. }
  2215. const tDir = t * dir;
  2216. x0 = x0 * s + x1 * tDir;
  2217. y0 = y0 * s + y1 * tDir;
  2218. z0 = z0 * s + z1 * tDir;
  2219. w0 = w0 * s + w1 * tDir;
  2220. // Normalize in case we just did a lerp:
  2221. if ( s === 1 - t ) {
  2222. const f = 1 / Math.sqrt( x0 * x0 + y0 * y0 + z0 * z0 + w0 * w0 );
  2223. x0 *= f;
  2224. y0 *= f;
  2225. z0 *= f;
  2226. w0 *= f;
  2227. }
  2228. }
  2229. dst[ dstOffset ] = x0;
  2230. dst[ dstOffset + 1 ] = y0;
  2231. dst[ dstOffset + 2 ] = z0;
  2232. dst[ dstOffset + 3 ] = w0;
  2233. }
  2234. static multiplyQuaternionsFlat( dst, dstOffset, src0, srcOffset0, src1, srcOffset1 ) {
  2235. const x0 = src0[ srcOffset0 ];
  2236. const y0 = src0[ srcOffset0 + 1 ];
  2237. const z0 = src0[ srcOffset0 + 2 ];
  2238. const w0 = src0[ srcOffset0 + 3 ];
  2239. const x1 = src1[ srcOffset1 ];
  2240. const y1 = src1[ srcOffset1 + 1 ];
  2241. const z1 = src1[ srcOffset1 + 2 ];
  2242. const w1 = src1[ srcOffset1 + 3 ];
  2243. dst[ dstOffset ] = x0 * w1 + w0 * x1 + y0 * z1 - z0 * y1;
  2244. dst[ dstOffset + 1 ] = y0 * w1 + w0 * y1 + z0 * x1 - x0 * z1;
  2245. dst[ dstOffset + 2 ] = z0 * w1 + w0 * z1 + x0 * y1 - y0 * x1;
  2246. dst[ dstOffset + 3 ] = w0 * w1 - x0 * x1 - y0 * y1 - z0 * z1;
  2247. return dst;
  2248. }
  2249. get x() {
  2250. return this._x;
  2251. }
  2252. set x( value ) {
  2253. this._x = value;
  2254. this._onChangeCallback();
  2255. }
  2256. get y() {
  2257. return this._y;
  2258. }
  2259. set y( value ) {
  2260. this._y = value;
  2261. this._onChangeCallback();
  2262. }
  2263. get z() {
  2264. return this._z;
  2265. }
  2266. set z( value ) {
  2267. this._z = value;
  2268. this._onChangeCallback();
  2269. }
  2270. get w() {
  2271. return this._w;
  2272. }
  2273. set w( value ) {
  2274. this._w = value;
  2275. this._onChangeCallback();
  2276. }
  2277. set( x, y, z, w ) {
  2278. this._x = x;
  2279. this._y = y;
  2280. this._z = z;
  2281. this._w = w;
  2282. this._onChangeCallback();
  2283. return this;
  2284. }
  2285. clone() {
  2286. return new this.constructor( this._x, this._y, this._z, this._w );
  2287. }
  2288. copy( quaternion ) {
  2289. this._x = quaternion.x;
  2290. this._y = quaternion.y;
  2291. this._z = quaternion.z;
  2292. this._w = quaternion.w;
  2293. this._onChangeCallback();
  2294. return this;
  2295. }
  2296. setFromEuler( euler, update ) {
  2297. const x = euler._x, y = euler._y, z = euler._z, order = euler._order;
  2298. // http://www.mathworks.com/matlabcentral/fileexchange/
  2299. // 20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/
  2300. // content/SpinCalc.m
  2301. const cos = Math.cos;
  2302. const sin = Math.sin;
  2303. const c1 = cos( x / 2 );
  2304. const c2 = cos( y / 2 );
  2305. const c3 = cos( z / 2 );
  2306. const s1 = sin( x / 2 );
  2307. const s2 = sin( y / 2 );
  2308. const s3 = sin( z / 2 );
  2309. switch ( order ) {
  2310. case 'XYZ':
  2311. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  2312. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  2313. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  2314. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  2315. break;
  2316. case 'YXZ':
  2317. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  2318. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  2319. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  2320. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  2321. break;
  2322. case 'ZXY':
  2323. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  2324. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  2325. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  2326. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  2327. break;
  2328. case 'ZYX':
  2329. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  2330. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  2331. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  2332. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  2333. break;
  2334. case 'YZX':
  2335. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  2336. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  2337. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  2338. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  2339. break;
  2340. case 'XZY':
  2341. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  2342. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  2343. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  2344. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  2345. break;
  2346. default:
  2347. console.warn( 'THREE.Quaternion: .setFromEuler() encountered an unknown order: ' + order );
  2348. }
  2349. if ( update !== false ) this._onChangeCallback();
  2350. return this;
  2351. }
  2352. setFromAxisAngle( axis, angle ) {
  2353. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm
  2354. // assumes axis is normalized
  2355. const halfAngle = angle / 2, s = Math.sin( halfAngle );
  2356. this._x = axis.x * s;
  2357. this._y = axis.y * s;
  2358. this._z = axis.z * s;
  2359. this._w = Math.cos( halfAngle );
  2360. this._onChangeCallback();
  2361. return this;
  2362. }
  2363. setFromRotationMatrix( m ) {
  2364. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm
  2365. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  2366. const te = m.elements,
  2367. m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ],
  2368. m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ],
  2369. m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ],
  2370. trace = m11 + m22 + m33;
  2371. if ( trace > 0 ) {
  2372. const s = 0.5 / Math.sqrt( trace + 1.0 );
  2373. this._w = 0.25 / s;
  2374. this._x = ( m32 - m23 ) * s;
  2375. this._y = ( m13 - m31 ) * s;
  2376. this._z = ( m21 - m12 ) * s;
  2377. } else if ( m11 > m22 && m11 > m33 ) {
  2378. const s = 2.0 * Math.sqrt( 1.0 + m11 - m22 - m33 );
  2379. this._w = ( m32 - m23 ) / s;
  2380. this._x = 0.25 * s;
  2381. this._y = ( m12 + m21 ) / s;
  2382. this._z = ( m13 + m31 ) / s;
  2383. } else if ( m22 > m33 ) {
  2384. const s = 2.0 * Math.sqrt( 1.0 + m22 - m11 - m33 );
  2385. this._w = ( m13 - m31 ) / s;
  2386. this._x = ( m12 + m21 ) / s;
  2387. this._y = 0.25 * s;
  2388. this._z = ( m23 + m32 ) / s;
  2389. } else {
  2390. const s = 2.0 * Math.sqrt( 1.0 + m33 - m11 - m22 );
  2391. this._w = ( m21 - m12 ) / s;
  2392. this._x = ( m13 + m31 ) / s;
  2393. this._y = ( m23 + m32 ) / s;
  2394. this._z = 0.25 * s;
  2395. }
  2396. this._onChangeCallback();
  2397. return this;
  2398. }
  2399. setFromUnitVectors( vFrom, vTo ) {
  2400. // assumes direction vectors vFrom and vTo are normalized
  2401. let r = vFrom.dot( vTo ) + 1;
  2402. if ( r < Number.EPSILON ) {
  2403. // vFrom and vTo point in opposite directions
  2404. r = 0;
  2405. if ( Math.abs( vFrom.x ) > Math.abs( vFrom.z ) ) {
  2406. this._x = - vFrom.y;
  2407. this._y = vFrom.x;
  2408. this._z = 0;
  2409. this._w = r;
  2410. } else {
  2411. this._x = 0;
  2412. this._y = - vFrom.z;
  2413. this._z = vFrom.y;
  2414. this._w = r;
  2415. }
  2416. } else {
  2417. // crossVectors( vFrom, vTo ); // inlined to avoid cyclic dependency on Vector3
  2418. this._x = vFrom.y * vTo.z - vFrom.z * vTo.y;
  2419. this._y = vFrom.z * vTo.x - vFrom.x * vTo.z;
  2420. this._z = vFrom.x * vTo.y - vFrom.y * vTo.x;
  2421. this._w = r;
  2422. }
  2423. return this.normalize();
  2424. }
  2425. angleTo( q ) {
  2426. return 2 * Math.acos( Math.abs( clamp( this.dot( q ), - 1, 1 ) ) );
  2427. }
  2428. rotateTowards( q, step ) {
  2429. const angle = this.angleTo( q );
  2430. if ( angle === 0 ) return this;
  2431. const t = Math.min( 1, step / angle );
  2432. this.slerp( q, t );
  2433. return this;
  2434. }
  2435. identity() {
  2436. return this.set( 0, 0, 0, 1 );
  2437. }
  2438. invert() {
  2439. // quaternion is assumed to have unit length
  2440. return this.conjugate();
  2441. }
  2442. conjugate() {
  2443. this._x *= - 1;
  2444. this._y *= - 1;
  2445. this._z *= - 1;
  2446. this._onChangeCallback();
  2447. return this;
  2448. }
  2449. dot( v ) {
  2450. return this._x * v._x + this._y * v._y + this._z * v._z + this._w * v._w;
  2451. }
  2452. lengthSq() {
  2453. return this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w;
  2454. }
  2455. length() {
  2456. return Math.sqrt( this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w );
  2457. }
  2458. normalize() {
  2459. let l = this.length();
  2460. if ( l === 0 ) {
  2461. this._x = 0;
  2462. this._y = 0;
  2463. this._z = 0;
  2464. this._w = 1;
  2465. } else {
  2466. l = 1 / l;
  2467. this._x = this._x * l;
  2468. this._y = this._y * l;
  2469. this._z = this._z * l;
  2470. this._w = this._w * l;
  2471. }
  2472. this._onChangeCallback();
  2473. return this;
  2474. }
  2475. multiply( q ) {
  2476. return this.multiplyQuaternions( this, q );
  2477. }
  2478. premultiply( q ) {
  2479. return this.multiplyQuaternions( q, this );
  2480. }
  2481. multiplyQuaternions( a, b ) {
  2482. // from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm
  2483. const qax = a._x, qay = a._y, qaz = a._z, qaw = a._w;
  2484. const qbx = b._x, qby = b._y, qbz = b._z, qbw = b._w;
  2485. this._x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby;
  2486. this._y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz;
  2487. this._z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx;
  2488. this._w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz;
  2489. this._onChangeCallback();
  2490. return this;
  2491. }
  2492. slerp( qb, t ) {
  2493. if ( t === 0 ) return this;
  2494. if ( t === 1 ) return this.copy( qb );
  2495. const x = this._x, y = this._y, z = this._z, w = this._w;
  2496. // http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/
  2497. let cosHalfTheta = w * qb._w + x * qb._x + y * qb._y + z * qb._z;
  2498. if ( cosHalfTheta < 0 ) {
  2499. this._w = - qb._w;
  2500. this._x = - qb._x;
  2501. this._y = - qb._y;
  2502. this._z = - qb._z;
  2503. cosHalfTheta = - cosHalfTheta;
  2504. } else {
  2505. this.copy( qb );
  2506. }
  2507. if ( cosHalfTheta >= 1.0 ) {
  2508. this._w = w;
  2509. this._x = x;
  2510. this._y = y;
  2511. this._z = z;
  2512. return this;
  2513. }
  2514. const sqrSinHalfTheta = 1.0 - cosHalfTheta * cosHalfTheta;
  2515. if ( sqrSinHalfTheta <= Number.EPSILON ) {
  2516. const s = 1 - t;
  2517. this._w = s * w + t * this._w;
  2518. this._x = s * x + t * this._x;
  2519. this._y = s * y + t * this._y;
  2520. this._z = s * z + t * this._z;
  2521. this.normalize();
  2522. this._onChangeCallback();
  2523. return this;
  2524. }
  2525. const sinHalfTheta = Math.sqrt( sqrSinHalfTheta );
  2526. const halfTheta = Math.atan2( sinHalfTheta, cosHalfTheta );
  2527. const ratioA = Math.sin( ( 1 - t ) * halfTheta ) / sinHalfTheta,
  2528. ratioB = Math.sin( t * halfTheta ) / sinHalfTheta;
  2529. this._w = ( w * ratioA + this._w * ratioB );
  2530. this._x = ( x * ratioA + this._x * ratioB );
  2531. this._y = ( y * ratioA + this._y * ratioB );
  2532. this._z = ( z * ratioA + this._z * ratioB );
  2533. this._onChangeCallback();
  2534. return this;
  2535. }
  2536. slerpQuaternions( qa, qb, t ) {
  2537. return this.copy( qa ).slerp( qb, t );
  2538. }
  2539. random() {
  2540. // Derived from http://planning.cs.uiuc.edu/node198.html
  2541. // Note, this source uses w, x, y, z ordering,
  2542. // so we swap the order below.
  2543. const u1 = Math.random();
  2544. const sqrt1u1 = Math.sqrt( 1 - u1 );
  2545. const sqrtu1 = Math.sqrt( u1 );
  2546. const u2 = 2 * Math.PI * Math.random();
  2547. const u3 = 2 * Math.PI * Math.random();
  2548. return this.set(
  2549. sqrt1u1 * Math.cos( u2 ),
  2550. sqrtu1 * Math.sin( u3 ),
  2551. sqrtu1 * Math.cos( u3 ),
  2552. sqrt1u1 * Math.sin( u2 ),
  2553. );
  2554. }
  2555. equals( quaternion ) {
  2556. return ( quaternion._x === this._x ) && ( quaternion._y === this._y ) && ( quaternion._z === this._z ) && ( quaternion._w === this._w );
  2557. }
  2558. fromArray( array, offset = 0 ) {
  2559. this._x = array[ offset ];
  2560. this._y = array[ offset + 1 ];
  2561. this._z = array[ offset + 2 ];
  2562. this._w = array[ offset + 3 ];
  2563. this._onChangeCallback();
  2564. return this;
  2565. }
  2566. toArray( array = [], offset = 0 ) {
  2567. array[ offset ] = this._x;
  2568. array[ offset + 1 ] = this._y;
  2569. array[ offset + 2 ] = this._z;
  2570. array[ offset + 3 ] = this._w;
  2571. return array;
  2572. }
  2573. fromBufferAttribute( attribute, index ) {
  2574. this._x = attribute.getX( index );
  2575. this._y = attribute.getY( index );
  2576. this._z = attribute.getZ( index );
  2577. this._w = attribute.getW( index );
  2578. return this;
  2579. }
  2580. _onChange( callback ) {
  2581. this._onChangeCallback = callback;
  2582. return this;
  2583. }
  2584. _onChangeCallback() {}
  2585. *[ Symbol.iterator ]() {
  2586. yield this._x;
  2587. yield this._y;
  2588. yield this._z;
  2589. yield this._w;
  2590. }
  2591. }
  2592. class Vector3 {
  2593. constructor( x = 0, y = 0, z = 0 ) {
  2594. Vector3.prototype.isVector3 = true;
  2595. this.x = x;
  2596. this.y = y;
  2597. this.z = z;
  2598. }
  2599. set( x, y, z ) {
  2600. if ( z === undefined ) z = this.z; // sprite.scale.set(x,y)
  2601. this.x = x;
  2602. this.y = y;
  2603. this.z = z;
  2604. return this;
  2605. }
  2606. setScalar( scalar ) {
  2607. this.x = scalar;
  2608. this.y = scalar;
  2609. this.z = scalar;
  2610. return this;
  2611. }
  2612. setX( x ) {
  2613. this.x = x;
  2614. return this;
  2615. }
  2616. setY( y ) {
  2617. this.y = y;
  2618. return this;
  2619. }
  2620. setZ( z ) {
  2621. this.z = z;
  2622. return this;
  2623. }
  2624. setComponent( index, value ) {
  2625. switch ( index ) {
  2626. case 0: this.x = value; break;
  2627. case 1: this.y = value; break;
  2628. case 2: this.z = value; break;
  2629. default: throw new Error( 'index is out of range: ' + index );
  2630. }
  2631. return this;
  2632. }
  2633. getComponent( index ) {
  2634. switch ( index ) {
  2635. case 0: return this.x;
  2636. case 1: return this.y;
  2637. case 2: return this.z;
  2638. default: throw new Error( 'index is out of range: ' + index );
  2639. }
  2640. }
  2641. clone() {
  2642. return new this.constructor( this.x, this.y, this.z );
  2643. }
  2644. copy( v ) {
  2645. this.x = v.x;
  2646. this.y = v.y;
  2647. this.z = v.z;
  2648. return this;
  2649. }
  2650. add( v ) {
  2651. this.x += v.x;
  2652. this.y += v.y;
  2653. this.z += v.z;
  2654. return this;
  2655. }
  2656. addScalar( s ) {
  2657. this.x += s;
  2658. this.y += s;
  2659. this.z += s;
  2660. return this;
  2661. }
  2662. addVectors( a, b ) {
  2663. this.x = a.x + b.x;
  2664. this.y = a.y + b.y;
  2665. this.z = a.z + b.z;
  2666. return this;
  2667. }
  2668. addScaledVector( v, s ) {
  2669. this.x += v.x * s;
  2670. this.y += v.y * s;
  2671. this.z += v.z * s;
  2672. return this;
  2673. }
  2674. sub( v ) {
  2675. this.x -= v.x;
  2676. this.y -= v.y;
  2677. this.z -= v.z;
  2678. return this;
  2679. }
  2680. subScalar( s ) {
  2681. this.x -= s;
  2682. this.y -= s;
  2683. this.z -= s;
  2684. return this;
  2685. }
  2686. subVectors( a, b ) {
  2687. this.x = a.x - b.x;
  2688. this.y = a.y - b.y;
  2689. this.z = a.z - b.z;
  2690. return this;
  2691. }
  2692. multiply( v ) {
  2693. this.x *= v.x;
  2694. this.y *= v.y;
  2695. this.z *= v.z;
  2696. return this;
  2697. }
  2698. multiplyScalar( scalar ) {
  2699. this.x *= scalar;
  2700. this.y *= scalar;
  2701. this.z *= scalar;
  2702. return this;
  2703. }
  2704. multiplyVectors( a, b ) {
  2705. this.x = a.x * b.x;
  2706. this.y = a.y * b.y;
  2707. this.z = a.z * b.z;
  2708. return this;
  2709. }
  2710. applyEuler( euler ) {
  2711. return this.applyQuaternion( _quaternion$4.setFromEuler( euler ) );
  2712. }
  2713. applyAxisAngle( axis, angle ) {
  2714. return this.applyQuaternion( _quaternion$4.setFromAxisAngle( axis, angle ) );
  2715. }
  2716. applyMatrix3( m ) {
  2717. const x = this.x, y = this.y, z = this.z;
  2718. const e = m.elements;
  2719. this.x = e[ 0 ] * x + e[ 3 ] * y + e[ 6 ] * z;
  2720. this.y = e[ 1 ] * x + e[ 4 ] * y + e[ 7 ] * z;
  2721. this.z = e[ 2 ] * x + e[ 5 ] * y + e[ 8 ] * z;
  2722. return this;
  2723. }
  2724. applyNormalMatrix( m ) {
  2725. return this.applyMatrix3( m ).normalize();
  2726. }
  2727. applyMatrix4( m ) {
  2728. const x = this.x, y = this.y, z = this.z;
  2729. const e = m.elements;
  2730. const w = 1 / ( e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] );
  2731. this.x = ( e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] ) * w;
  2732. this.y = ( e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] ) * w;
  2733. this.z = ( e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] ) * w;
  2734. return this;
  2735. }
  2736. applyQuaternion( q ) {
  2737. const x = this.x, y = this.y, z = this.z;
  2738. const qx = q.x, qy = q.y, qz = q.z, qw = q.w;
  2739. // calculate quat * vector
  2740. const ix = qw * x + qy * z - qz * y;
  2741. const iy = qw * y + qz * x - qx * z;
  2742. const iz = qw * z + qx * y - qy * x;
  2743. const iw = - qx * x - qy * y - qz * z;
  2744. // calculate result * inverse quat
  2745. this.x = ix * qw + iw * - qx + iy * - qz - iz * - qy;
  2746. this.y = iy * qw + iw * - qy + iz * - qx - ix * - qz;
  2747. this.z = iz * qw + iw * - qz + ix * - qy - iy * - qx;
  2748. return this;
  2749. }
  2750. project( camera ) {
  2751. return this.applyMatrix4( camera.matrixWorldInverse ).applyMatrix4( camera.projectionMatrix );
  2752. }
  2753. unproject( camera ) {
  2754. return this.applyMatrix4( camera.projectionMatrixInverse ).applyMatrix4( camera.matrixWorld );
  2755. }
  2756. transformDirection( m ) {
  2757. // input: THREE.Matrix4 affine matrix
  2758. // vector interpreted as a direction
  2759. const x = this.x, y = this.y, z = this.z;
  2760. const e = m.elements;
  2761. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z;
  2762. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z;
  2763. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z;
  2764. return this.normalize();
  2765. }
  2766. divide( v ) {
  2767. this.x /= v.x;
  2768. this.y /= v.y;
  2769. this.z /= v.z;
  2770. return this;
  2771. }
  2772. divideScalar( scalar ) {
  2773. return this.multiplyScalar( 1 / scalar );
  2774. }
  2775. min( v ) {
  2776. this.x = Math.min( this.x, v.x );
  2777. this.y = Math.min( this.y, v.y );
  2778. this.z = Math.min( this.z, v.z );
  2779. return this;
  2780. }
  2781. max( v ) {
  2782. this.x = Math.max( this.x, v.x );
  2783. this.y = Math.max( this.y, v.y );
  2784. this.z = Math.max( this.z, v.z );
  2785. return this;
  2786. }
  2787. clamp( min, max ) {
  2788. // assumes min < max, componentwise
  2789. this.x = Math.max( min.x, Math.min( max.x, this.x ) );
  2790. this.y = Math.max( min.y, Math.min( max.y, this.y ) );
  2791. this.z = Math.max( min.z, Math.min( max.z, this.z ) );
  2792. return this;
  2793. }
  2794. clampScalar( minVal, maxVal ) {
  2795. this.x = Math.max( minVal, Math.min( maxVal, this.x ) );
  2796. this.y = Math.max( minVal, Math.min( maxVal, this.y ) );
  2797. this.z = Math.max( minVal, Math.min( maxVal, this.z ) );
  2798. return this;
  2799. }
  2800. clampLength( min, max ) {
  2801. const length = this.length();
  2802. return this.divideScalar( length || 1 ).multiplyScalar( Math.max( min, Math.min( max, length ) ) );
  2803. }
  2804. floor() {
  2805. this.x = Math.floor( this.x );
  2806. this.y = Math.floor( this.y );
  2807. this.z = Math.floor( this.z );
  2808. return this;
  2809. }
  2810. ceil() {
  2811. this.x = Math.ceil( this.x );
  2812. this.y = Math.ceil( this.y );
  2813. this.z = Math.ceil( this.z );
  2814. return this;
  2815. }
  2816. round() {
  2817. this.x = Math.round( this.x );
  2818. this.y = Math.round( this.y );
  2819. this.z = Math.round( this.z );
  2820. return this;
  2821. }
  2822. roundToZero() {
  2823. this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x );
  2824. this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y );
  2825. this.z = ( this.z < 0 ) ? Math.ceil( this.z ) : Math.floor( this.z );
  2826. return this;
  2827. }
  2828. negate() {
  2829. this.x = - this.x;
  2830. this.y = - this.y;
  2831. this.z = - this.z;
  2832. return this;
  2833. }
  2834. dot( v ) {
  2835. return this.x * v.x + this.y * v.y + this.z * v.z;
  2836. }
  2837. // TODO lengthSquared?
  2838. lengthSq() {
  2839. return this.x * this.x + this.y * this.y + this.z * this.z;
  2840. }
  2841. length() {
  2842. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z );
  2843. }
  2844. manhattanLength() {
  2845. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z );
  2846. }
  2847. normalize() {
  2848. return this.divideScalar( this.length() || 1 );
  2849. }
  2850. setLength( length ) {
  2851. return this.normalize().multiplyScalar( length );
  2852. }
  2853. lerp( v, alpha ) {
  2854. this.x += ( v.x - this.x ) * alpha;
  2855. this.y += ( v.y - this.y ) * alpha;
  2856. this.z += ( v.z - this.z ) * alpha;
  2857. return this;
  2858. }
  2859. lerpVectors( v1, v2, alpha ) {
  2860. this.x = v1.x + ( v2.x - v1.x ) * alpha;
  2861. this.y = v1.y + ( v2.y - v1.y ) * alpha;
  2862. this.z = v1.z + ( v2.z - v1.z ) * alpha;
  2863. return this;
  2864. }
  2865. cross( v ) {
  2866. return this.crossVectors( this, v );
  2867. }
  2868. crossVectors( a, b ) {
  2869. const ax = a.x, ay = a.y, az = a.z;
  2870. const bx = b.x, by = b.y, bz = b.z;
  2871. this.x = ay * bz - az * by;
  2872. this.y = az * bx - ax * bz;
  2873. this.z = ax * by - ay * bx;
  2874. return this;
  2875. }
  2876. projectOnVector( v ) {
  2877. const denominator = v.lengthSq();
  2878. if ( denominator === 0 ) return this.set( 0, 0, 0 );
  2879. const scalar = v.dot( this ) / denominator;
  2880. return this.copy( v ).multiplyScalar( scalar );
  2881. }
  2882. projectOnPlane( planeNormal ) {
  2883. _vector$c.copy( this ).projectOnVector( planeNormal );
  2884. return this.sub( _vector$c );
  2885. }
  2886. reflect( normal ) {
  2887. // reflect incident vector off plane orthogonal to normal
  2888. // normal is assumed to have unit length
  2889. return this.sub( _vector$c.copy( normal ).multiplyScalar( 2 * this.dot( normal ) ) );
  2890. }
  2891. angleTo( v ) {
  2892. const denominator = Math.sqrt( this.lengthSq() * v.lengthSq() );
  2893. if ( denominator === 0 ) return Math.PI / 2;
  2894. const theta = this.dot( v ) / denominator;
  2895. // clamp, to handle numerical problems
  2896. return Math.acos( clamp( theta, - 1, 1 ) );
  2897. }
  2898. distanceTo( v ) {
  2899. return Math.sqrt( this.distanceToSquared( v ) );
  2900. }
  2901. distanceToSquared( v ) {
  2902. const dx = this.x - v.x, dy = this.y - v.y, dz = this.z - v.z;
  2903. return dx * dx + dy * dy + dz * dz;
  2904. }
  2905. manhattanDistanceTo( v ) {
  2906. return Math.abs( this.x - v.x ) + Math.abs( this.y - v.y ) + Math.abs( this.z - v.z );
  2907. }
  2908. setFromSpherical( s ) {
  2909. return this.setFromSphericalCoords( s.radius, s.phi, s.theta );
  2910. }
  2911. setFromSphericalCoords( radius, phi, theta ) {
  2912. const sinPhiRadius = Math.sin( phi ) * radius;
  2913. this.x = sinPhiRadius * Math.sin( theta );
  2914. this.y = Math.cos( phi ) * radius;
  2915. this.z = sinPhiRadius * Math.cos( theta );
  2916. return this;
  2917. }
  2918. setFromCylindrical( c ) {
  2919. return this.setFromCylindricalCoords( c.radius, c.theta, c.y );
  2920. }
  2921. setFromCylindricalCoords( radius, theta, y ) {
  2922. this.x = radius * Math.sin( theta );
  2923. this.y = y;
  2924. this.z = radius * Math.cos( theta );
  2925. return this;
  2926. }
  2927. setFromMatrixPosition( m ) {
  2928. const e = m.elements;
  2929. this.x = e[ 12 ];
  2930. this.y = e[ 13 ];
  2931. this.z = e[ 14 ];
  2932. return this;
  2933. }
  2934. setFromMatrixScale( m ) {
  2935. const sx = this.setFromMatrixColumn( m, 0 ).length();
  2936. const sy = this.setFromMatrixColumn( m, 1 ).length();
  2937. const sz = this.setFromMatrixColumn( m, 2 ).length();
  2938. this.x = sx;
  2939. this.y = sy;
  2940. this.z = sz;
  2941. return this;
  2942. }
  2943. setFromMatrixColumn( m, index ) {
  2944. return this.fromArray( m.elements, index * 4 );
  2945. }
  2946. setFromMatrix3Column( m, index ) {
  2947. return this.fromArray( m.elements, index * 3 );
  2948. }
  2949. setFromEuler( e ) {
  2950. this.x = e._x;
  2951. this.y = e._y;
  2952. this.z = e._z;
  2953. return this;
  2954. }
  2955. equals( v ) {
  2956. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) );
  2957. }
  2958. fromArray( array, offset = 0 ) {
  2959. this.x = array[ offset ];
  2960. this.y = array[ offset + 1 ];
  2961. this.z = array[ offset + 2 ];
  2962. return this;
  2963. }
  2964. toArray( array = [], offset = 0 ) {
  2965. array[ offset ] = this.x;
  2966. array[ offset + 1 ] = this.y;
  2967. array[ offset + 2 ] = this.z;
  2968. return array;
  2969. }
  2970. fromBufferAttribute( attribute, index ) {
  2971. this.x = attribute.getX( index );
  2972. this.y = attribute.getY( index );
  2973. this.z = attribute.getZ( index );
  2974. return this;
  2975. }
  2976. random() {
  2977. this.x = Math.random();
  2978. this.y = Math.random();
  2979. this.z = Math.random();
  2980. return this;
  2981. }
  2982. randomDirection() {
  2983. // Derived from https://mathworld.wolfram.com/SpherePointPicking.html
  2984. const u = ( Math.random() - 0.5 ) * 2;
  2985. const t = Math.random() * Math.PI * 2;
  2986. const f = Math.sqrt( 1 - u ** 2 );
  2987. this.x = f * Math.cos( t );
  2988. this.y = f * Math.sin( t );
  2989. this.z = u;
  2990. return this;
  2991. }
  2992. *[ Symbol.iterator ]() {
  2993. yield this.x;
  2994. yield this.y;
  2995. yield this.z;
  2996. }
  2997. }
  2998. const _vector$c = /*@__PURE__*/ new Vector3();
  2999. const _quaternion$4 = /*@__PURE__*/ new Quaternion();
  3000. class Box3 {
  3001. constructor( min = new Vector3( + Infinity, + Infinity, + Infinity ), max = new Vector3( - Infinity, - Infinity, - Infinity ) ) {
  3002. this.isBox3 = true;
  3003. this.min = min;
  3004. this.max = max;
  3005. }
  3006. set( min, max ) {
  3007. this.min.copy( min );
  3008. this.max.copy( max );
  3009. return this;
  3010. }
  3011. setFromArray( array ) {
  3012. let minX = + Infinity;
  3013. let minY = + Infinity;
  3014. let minZ = + Infinity;
  3015. let maxX = - Infinity;
  3016. let maxY = - Infinity;
  3017. let maxZ = - Infinity;
  3018. for ( let i = 0, l = array.length; i < l; i += 3 ) {
  3019. const x = array[ i ];
  3020. const y = array[ i + 1 ];
  3021. const z = array[ i + 2 ];
  3022. if ( x < minX ) minX = x;
  3023. if ( y < minY ) minY = y;
  3024. if ( z < minZ ) minZ = z;
  3025. if ( x > maxX ) maxX = x;
  3026. if ( y > maxY ) maxY = y;
  3027. if ( z > maxZ ) maxZ = z;
  3028. }
  3029. this.min.set( minX, minY, minZ );
  3030. this.max.set( maxX, maxY, maxZ );
  3031. return this;
  3032. }
  3033. setFromBufferAttribute( attribute ) {
  3034. let minX = + Infinity;
  3035. let minY = + Infinity;
  3036. let minZ = + Infinity;
  3037. let maxX = - Infinity;
  3038. let maxY = - Infinity;
  3039. let maxZ = - Infinity;
  3040. for ( let i = 0, l = attribute.count; i < l; i ++ ) {
  3041. const x = attribute.getX( i );
  3042. const y = attribute.getY( i );
  3043. const z = attribute.getZ( i );
  3044. if ( x < minX ) minX = x;
  3045. if ( y < minY ) minY = y;
  3046. if ( z < minZ ) minZ = z;
  3047. if ( x > maxX ) maxX = x;
  3048. if ( y > maxY ) maxY = y;
  3049. if ( z > maxZ ) maxZ = z;
  3050. }
  3051. this.min.set( minX, minY, minZ );
  3052. this.max.set( maxX, maxY, maxZ );
  3053. return this;
  3054. }
  3055. setFromPoints( points ) {
  3056. this.makeEmpty();
  3057. for ( let i = 0, il = points.length; i < il; i ++ ) {
  3058. this.expandByPoint( points[ i ] );
  3059. }
  3060. return this;
  3061. }
  3062. setFromCenterAndSize( center, size ) {
  3063. const halfSize = _vector$b.copy( size ).multiplyScalar( 0.5 );
  3064. this.min.copy( center ).sub( halfSize );
  3065. this.max.copy( center ).add( halfSize );
  3066. return this;
  3067. }
  3068. setFromObject( object, precise = false ) {
  3069. this.makeEmpty();
  3070. return this.expandByObject( object, precise );
  3071. }
  3072. clone() {
  3073. return new this.constructor().copy( this );
  3074. }
  3075. copy( box ) {
  3076. this.min.copy( box.min );
  3077. this.max.copy( box.max );
  3078. return this;
  3079. }
  3080. makeEmpty() {
  3081. this.min.x = this.min.y = this.min.z = + Infinity;
  3082. this.max.x = this.max.y = this.max.z = - Infinity;
  3083. return this;
  3084. }
  3085. isEmpty() {
  3086. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  3087. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y ) || ( this.max.z < this.min.z );
  3088. }
  3089. getCenter( target ) {
  3090. return this.isEmpty() ? target.set( 0, 0, 0 ) : target.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  3091. }
  3092. getSize( target ) {
  3093. return this.isEmpty() ? target.set( 0, 0, 0 ) : target.subVectors( this.max, this.min );
  3094. }
  3095. expandByPoint( point ) {
  3096. this.min.min( point );
  3097. this.max.max( point );
  3098. return this;
  3099. }
  3100. expandByVector( vector ) {
  3101. this.min.sub( vector );
  3102. this.max.add( vector );
  3103. return this;
  3104. }
  3105. expandByScalar( scalar ) {
  3106. this.min.addScalar( - scalar );
  3107. this.max.addScalar( scalar );
  3108. return this;
  3109. }
  3110. expandByObject( object, precise = false ) {
  3111. // Computes the world-axis-aligned bounding box of an object (including its children),
  3112. // accounting for both the object's, and children's, world transforms
  3113. object.updateWorldMatrix( false, false );
  3114. const geometry = object.geometry;
  3115. if ( geometry !== undefined ) {
  3116. if ( precise && geometry.attributes != undefined && geometry.attributes.position !== undefined ) {
  3117. const position = geometry.attributes.position;
  3118. for ( let i = 0, l = position.count; i < l; i ++ ) {
  3119. _vector$b.fromBufferAttribute( position, i ).applyMatrix4( object.matrixWorld );
  3120. this.expandByPoint( _vector$b );
  3121. }
  3122. } else {
  3123. if ( geometry.boundingBox === null ) {
  3124. geometry.computeBoundingBox();
  3125. }
  3126. _box$3.copy( geometry.boundingBox );
  3127. _box$3.applyMatrix4( object.matrixWorld );
  3128. this.union( _box$3 );
  3129. }
  3130. }
  3131. const children = object.children;
  3132. for ( let i = 0, l = children.length; i < l; i ++ ) {
  3133. this.expandByObject( children[ i ], precise );
  3134. }
  3135. return this;
  3136. }
  3137. containsPoint( point ) {
  3138. return point.x < this.min.x || point.x > this.max.x ||
  3139. point.y < this.min.y || point.y > this.max.y ||
  3140. point.z < this.min.z || point.z > this.max.z ? false : true;
  3141. }
  3142. containsBox( box ) {
  3143. return this.min.x <= box.min.x && box.max.x <= this.max.x &&
  3144. this.min.y <= box.min.y && box.max.y <= this.max.y &&
  3145. this.min.z <= box.min.z && box.max.z <= this.max.z;
  3146. }
  3147. getParameter( point, target ) {
  3148. // This can potentially have a divide by zero if the box
  3149. // has a size dimension of 0.
  3150. return target.set(
  3151. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  3152. ( point.y - this.min.y ) / ( this.max.y - this.min.y ),
  3153. ( point.z - this.min.z ) / ( this.max.z - this.min.z )
  3154. );
  3155. }
  3156. intersectsBox( box ) {
  3157. // using 6 splitting planes to rule out intersections.
  3158. return box.max.x < this.min.x || box.min.x > this.max.x ||
  3159. box.max.y < this.min.y || box.min.y > this.max.y ||
  3160. box.max.z < this.min.z || box.min.z > this.max.z ? false : true;
  3161. }
  3162. intersectsSphere( sphere ) {
  3163. // Find the point on the AABB closest to the sphere center.
  3164. this.clampPoint( sphere.center, _vector$b );
  3165. // If that point is inside the sphere, the AABB and sphere intersect.
  3166. return _vector$b.distanceToSquared( sphere.center ) <= ( sphere.radius * sphere.radius );
  3167. }
  3168. intersectsPlane( plane ) {
  3169. // We compute the minimum and maximum dot product values. If those values
  3170. // are on the same side (back or front) of the plane, then there is no intersection.
  3171. let min, max;
  3172. if ( plane.normal.x > 0 ) {
  3173. min = plane.normal.x * this.min.x;
  3174. max = plane.normal.x * this.max.x;
  3175. } else {
  3176. min = plane.normal.x * this.max.x;
  3177. max = plane.normal.x * this.min.x;
  3178. }
  3179. if ( plane.normal.y > 0 ) {
  3180. min += plane.normal.y * this.min.y;
  3181. max += plane.normal.y * this.max.y;
  3182. } else {
  3183. min += plane.normal.y * this.max.y;
  3184. max += plane.normal.y * this.min.y;
  3185. }
  3186. if ( plane.normal.z > 0 ) {
  3187. min += plane.normal.z * this.min.z;
  3188. max += plane.normal.z * this.max.z;
  3189. } else {
  3190. min += plane.normal.z * this.max.z;
  3191. max += plane.normal.z * this.min.z;
  3192. }
  3193. return ( min <= - plane.constant && max >= - plane.constant );
  3194. }
  3195. intersectsTriangle( triangle ) {
  3196. if ( this.isEmpty() ) {
  3197. return false;
  3198. }
  3199. // compute box center and extents
  3200. this.getCenter( _center );
  3201. _extents.subVectors( this.max, _center );
  3202. // translate triangle to aabb origin
  3203. _v0$2.subVectors( triangle.a, _center );
  3204. _v1$7.subVectors( triangle.b, _center );
  3205. _v2$4.subVectors( triangle.c, _center );
  3206. // compute edge vectors for triangle
  3207. _f0.subVectors( _v1$7, _v0$2 );
  3208. _f1.subVectors( _v2$4, _v1$7 );
  3209. _f2.subVectors( _v0$2, _v2$4 );
  3210. // test against axes that are given by cross product combinations of the edges of the triangle and the edges of the aabb
  3211. // 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
  3212. // axis_ij = u_i x f_j (u0, u1, u2 = face normals of aabb = x,y,z axes vectors since aabb is axis aligned)
  3213. let axes = [
  3214. 0, - _f0.z, _f0.y, 0, - _f1.z, _f1.y, 0, - _f2.z, _f2.y,
  3215. _f0.z, 0, - _f0.x, _f1.z, 0, - _f1.x, _f2.z, 0, - _f2.x,
  3216. - _f0.y, _f0.x, 0, - _f1.y, _f1.x, 0, - _f2.y, _f2.x, 0
  3217. ];
  3218. if ( ! satForAxes( axes, _v0$2, _v1$7, _v2$4, _extents ) ) {
  3219. return false;
  3220. }
  3221. // test 3 face normals from the aabb
  3222. axes = [ 1, 0, 0, 0, 1, 0, 0, 0, 1 ];
  3223. if ( ! satForAxes( axes, _v0$2, _v1$7, _v2$4, _extents ) ) {
  3224. return false;
  3225. }
  3226. // finally testing the face normal of the triangle
  3227. // use already existing triangle edge vectors here
  3228. _triangleNormal.crossVectors( _f0, _f1 );
  3229. axes = [ _triangleNormal.x, _triangleNormal.y, _triangleNormal.z ];
  3230. return satForAxes( axes, _v0$2, _v1$7, _v2$4, _extents );
  3231. }
  3232. clampPoint( point, target ) {
  3233. return target.copy( point ).clamp( this.min, this.max );
  3234. }
  3235. distanceToPoint( point ) {
  3236. const clampedPoint = _vector$b.copy( point ).clamp( this.min, this.max );
  3237. return clampedPoint.sub( point ).length();
  3238. }
  3239. getBoundingSphere( target ) {
  3240. this.getCenter( target.center );
  3241. target.radius = this.getSize( _vector$b ).length() * 0.5;
  3242. return target;
  3243. }
  3244. intersect( box ) {
  3245. this.min.max( box.min );
  3246. this.max.min( box.max );
  3247. // 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.
  3248. if ( this.isEmpty() ) this.makeEmpty();
  3249. return this;
  3250. }
  3251. union( box ) {
  3252. this.min.min( box.min );
  3253. this.max.max( box.max );
  3254. return this;
  3255. }
  3256. applyMatrix4( matrix ) {
  3257. // transform of empty box is an empty box.
  3258. if ( this.isEmpty() ) return this;
  3259. // NOTE: I am using a binary pattern to specify all 2^3 combinations below
  3260. _points[ 0 ].set( this.min.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 000
  3261. _points[ 1 ].set( this.min.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 001
  3262. _points[ 2 ].set( this.min.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 010
  3263. _points[ 3 ].set( this.min.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 011
  3264. _points[ 4 ].set( this.max.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 100
  3265. _points[ 5 ].set( this.max.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 101
  3266. _points[ 6 ].set( this.max.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 110
  3267. _points[ 7 ].set( this.max.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 111
  3268. this.setFromPoints( _points );
  3269. return this;
  3270. }
  3271. translate( offset ) {
  3272. this.min.add( offset );
  3273. this.max.add( offset );
  3274. return this;
  3275. }
  3276. equals( box ) {
  3277. return box.min.equals( this.min ) && box.max.equals( this.max );
  3278. }
  3279. }
  3280. const _points = [
  3281. /*@__PURE__*/ new Vector3(),
  3282. /*@__PURE__*/ new Vector3(),
  3283. /*@__PURE__*/ new Vector3(),
  3284. /*@__PURE__*/ new Vector3(),
  3285. /*@__PURE__*/ new Vector3(),
  3286. /*@__PURE__*/ new Vector3(),
  3287. /*@__PURE__*/ new Vector3(),
  3288. /*@__PURE__*/ new Vector3()
  3289. ];
  3290. const _vector$b = /*@__PURE__*/ new Vector3();
  3291. const _box$3 = /*@__PURE__*/ new Box3();
  3292. // triangle centered vertices
  3293. const _v0$2 = /*@__PURE__*/ new Vector3();
  3294. const _v1$7 = /*@__PURE__*/ new Vector3();
  3295. const _v2$4 = /*@__PURE__*/ new Vector3();
  3296. // triangle edge vectors
  3297. const _f0 = /*@__PURE__*/ new Vector3();
  3298. const _f1 = /*@__PURE__*/ new Vector3();
  3299. const _f2 = /*@__PURE__*/ new Vector3();
  3300. const _center = /*@__PURE__*/ new Vector3();
  3301. const _extents = /*@__PURE__*/ new Vector3();
  3302. const _triangleNormal = /*@__PURE__*/ new Vector3();
  3303. const _testAxis = /*@__PURE__*/ new Vector3();
  3304. function satForAxes( axes, v0, v1, v2, extents ) {
  3305. for ( let i = 0, j = axes.length - 3; i <= j; i += 3 ) {
  3306. _testAxis.fromArray( axes, i );
  3307. // project the aabb onto the separating axis
  3308. const r = extents.x * Math.abs( _testAxis.x ) + extents.y * Math.abs( _testAxis.y ) + extents.z * Math.abs( _testAxis.z );
  3309. // project all 3 vertices of the triangle onto the separating axis
  3310. const p0 = v0.dot( _testAxis );
  3311. const p1 = v1.dot( _testAxis );
  3312. const p2 = v2.dot( _testAxis );
  3313. // actual test, basically see if either of the most extreme of the triangle points intersects r
  3314. if ( Math.max( - Math.max( p0, p1, p2 ), Math.min( p0, p1, p2 ) ) > r ) {
  3315. // points of the projected triangle are outside the projected half-length of the aabb
  3316. // the axis is separating and we can exit
  3317. return false;
  3318. }
  3319. }
  3320. return true;
  3321. }
  3322. const _box$2 = /*@__PURE__*/ new Box3();
  3323. const _v1$6 = /*@__PURE__*/ new Vector3();
  3324. const _v2$3 = /*@__PURE__*/ new Vector3();
  3325. class Sphere {
  3326. constructor( center = new Vector3(), radius = - 1 ) {
  3327. this.center = center;
  3328. this.radius = radius;
  3329. }
  3330. set( center, radius ) {
  3331. this.center.copy( center );
  3332. this.radius = radius;
  3333. return this;
  3334. }
  3335. setFromPoints( points, optionalCenter ) {
  3336. const center = this.center;
  3337. if ( optionalCenter !== undefined ) {
  3338. center.copy( optionalCenter );
  3339. } else {
  3340. _box$2.setFromPoints( points ).getCenter( center );
  3341. }
  3342. let maxRadiusSq = 0;
  3343. for ( let i = 0, il = points.length; i < il; i ++ ) {
  3344. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( points[ i ] ) );
  3345. }
  3346. this.radius = Math.sqrt( maxRadiusSq );
  3347. return this;
  3348. }
  3349. copy( sphere ) {
  3350. this.center.copy( sphere.center );
  3351. this.radius = sphere.radius;
  3352. return this;
  3353. }
  3354. isEmpty() {
  3355. return ( this.radius < 0 );
  3356. }
  3357. makeEmpty() {
  3358. this.center.set( 0, 0, 0 );
  3359. this.radius = - 1;
  3360. return this;
  3361. }
  3362. containsPoint( point ) {
  3363. return ( point.distanceToSquared( this.center ) <= ( this.radius * this.radius ) );
  3364. }
  3365. distanceToPoint( point ) {
  3366. return ( point.distanceTo( this.center ) - this.radius );
  3367. }
  3368. intersectsSphere( sphere ) {
  3369. const radiusSum = this.radius + sphere.radius;
  3370. return sphere.center.distanceToSquared( this.center ) <= ( radiusSum * radiusSum );
  3371. }
  3372. intersectsBox( box ) {
  3373. return box.intersectsSphere( this );
  3374. }
  3375. intersectsPlane( plane ) {
  3376. return Math.abs( plane.distanceToPoint( this.center ) ) <= this.radius;
  3377. }
  3378. clampPoint( point, target ) {
  3379. const deltaLengthSq = this.center.distanceToSquared( point );
  3380. target.copy( point );
  3381. if ( deltaLengthSq > ( this.radius * this.radius ) ) {
  3382. target.sub( this.center ).normalize();
  3383. target.multiplyScalar( this.radius ).add( this.center );
  3384. }
  3385. return target;
  3386. }
  3387. getBoundingBox( target ) {
  3388. if ( this.isEmpty() ) {
  3389. // Empty sphere produces empty bounding box
  3390. target.makeEmpty();
  3391. return target;
  3392. }
  3393. target.set( this.center, this.center );
  3394. target.expandByScalar( this.radius );
  3395. return target;
  3396. }
  3397. applyMatrix4( matrix ) {
  3398. this.center.applyMatrix4( matrix );
  3399. this.radius = this.radius * matrix.getMaxScaleOnAxis();
  3400. return this;
  3401. }
  3402. translate( offset ) {
  3403. this.center.add( offset );
  3404. return this;
  3405. }
  3406. expandByPoint( point ) {
  3407. if ( this.isEmpty() ) {
  3408. this.center.copy( point );
  3409. this.radius = 0;
  3410. return this;
  3411. }
  3412. _v1$6.subVectors( point, this.center );
  3413. const lengthSq = _v1$6.lengthSq();
  3414. if ( lengthSq > ( this.radius * this.radius ) ) {
  3415. // calculate the minimal sphere
  3416. const length = Math.sqrt( lengthSq );
  3417. const delta = ( length - this.radius ) * 0.5;
  3418. this.center.addScaledVector( _v1$6, delta / length );
  3419. this.radius += delta;
  3420. }
  3421. return this;
  3422. }
  3423. union( sphere ) {
  3424. if ( sphere.isEmpty() ) {
  3425. return this;
  3426. }
  3427. if ( this.isEmpty() ) {
  3428. this.copy( sphere );
  3429. return this;
  3430. }
  3431. if ( this.center.equals( sphere.center ) === true ) {
  3432. this.radius = Math.max( this.radius, sphere.radius );
  3433. } else {
  3434. _v2$3.subVectors( sphere.center, this.center ).setLength( sphere.radius );
  3435. this.expandByPoint( _v1$6.copy( sphere.center ).add( _v2$3 ) );
  3436. this.expandByPoint( _v1$6.copy( sphere.center ).sub( _v2$3 ) );
  3437. }
  3438. return this;
  3439. }
  3440. equals( sphere ) {
  3441. return sphere.center.equals( this.center ) && ( sphere.radius === this.radius );
  3442. }
  3443. clone() {
  3444. return new this.constructor().copy( this );
  3445. }
  3446. }
  3447. const _vector$a = /*@__PURE__*/ new Vector3();
  3448. const _segCenter = /*@__PURE__*/ new Vector3();
  3449. const _segDir = /*@__PURE__*/ new Vector3();
  3450. const _diff = /*@__PURE__*/ new Vector3();
  3451. const _edge1 = /*@__PURE__*/ new Vector3();
  3452. const _edge2 = /*@__PURE__*/ new Vector3();
  3453. const _normal$1 = /*@__PURE__*/ new Vector3();
  3454. class Ray {
  3455. constructor( origin = new Vector3(), direction = new Vector3( 0, 0, - 1 ) ) {
  3456. this.origin = origin;
  3457. this.direction = direction;
  3458. }
  3459. set( origin, direction ) {
  3460. this.origin.copy( origin );
  3461. this.direction.copy( direction );
  3462. return this;
  3463. }
  3464. copy( ray ) {
  3465. this.origin.copy( ray.origin );
  3466. this.direction.copy( ray.direction );
  3467. return this;
  3468. }
  3469. at( t, target ) {
  3470. return target.copy( this.direction ).multiplyScalar( t ).add( this.origin );
  3471. }
  3472. lookAt( v ) {
  3473. this.direction.copy( v ).sub( this.origin ).normalize();
  3474. return this;
  3475. }
  3476. recast( t ) {
  3477. this.origin.copy( this.at( t, _vector$a ) );
  3478. return this;
  3479. }
  3480. closestPointToPoint( point, target ) {
  3481. target.subVectors( point, this.origin );
  3482. const directionDistance = target.dot( this.direction );
  3483. if ( directionDistance < 0 ) {
  3484. return target.copy( this.origin );
  3485. }
  3486. return target.copy( this.direction ).multiplyScalar( directionDistance ).add( this.origin );
  3487. }
  3488. distanceToPoint( point ) {
  3489. return Math.sqrt( this.distanceSqToPoint( point ) );
  3490. }
  3491. distanceSqToPoint( point ) {
  3492. const directionDistance = _vector$a.subVectors( point, this.origin ).dot( this.direction );
  3493. // point behind the ray
  3494. if ( directionDistance < 0 ) {
  3495. return this.origin.distanceToSquared( point );
  3496. }
  3497. _vector$a.copy( this.direction ).multiplyScalar( directionDistance ).add( this.origin );
  3498. return _vector$a.distanceToSquared( point );
  3499. }
  3500. distanceSqToSegment( v0, v1, optionalPointOnRay, optionalPointOnSegment ) {
  3501. // from https://github.com/pmjoniak/GeometricTools/blob/master/GTEngine/Include/Mathematics/GteDistRaySegment.h
  3502. // It returns the min distance between the ray and the segment
  3503. // defined by v0 and v1
  3504. // It can also set two optional targets :
  3505. // - The closest point on the ray
  3506. // - The closest point on the segment
  3507. _segCenter.copy( v0 ).add( v1 ).multiplyScalar( 0.5 );
  3508. _segDir.copy( v1 ).sub( v0 ).normalize();
  3509. _diff.copy( this.origin ).sub( _segCenter );
  3510. const segExtent = v0.distanceTo( v1 ) * 0.5;
  3511. const a01 = - this.direction.dot( _segDir );
  3512. const b0 = _diff.dot( this.direction );
  3513. const b1 = - _diff.dot( _segDir );
  3514. const c = _diff.lengthSq();
  3515. const det = Math.abs( 1 - a01 * a01 );
  3516. let s0, s1, sqrDist, extDet;
  3517. if ( det > 0 ) {
  3518. // The ray and segment are not parallel.
  3519. s0 = a01 * b1 - b0;
  3520. s1 = a01 * b0 - b1;
  3521. extDet = segExtent * det;
  3522. if ( s0 >= 0 ) {
  3523. if ( s1 >= - extDet ) {
  3524. if ( s1 <= extDet ) {
  3525. // region 0
  3526. // Minimum at interior points of ray and segment.
  3527. const invDet = 1 / det;
  3528. s0 *= invDet;
  3529. s1 *= invDet;
  3530. sqrDist = s0 * ( s0 + a01 * s1 + 2 * b0 ) + s1 * ( a01 * s0 + s1 + 2 * b1 ) + c;
  3531. } else {
  3532. // region 1
  3533. s1 = segExtent;
  3534. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  3535. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3536. }
  3537. } else {
  3538. // region 5
  3539. s1 = - segExtent;
  3540. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  3541. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3542. }
  3543. } else {
  3544. if ( s1 <= - extDet ) {
  3545. // region 4
  3546. s0 = Math.max( 0, - ( - a01 * segExtent + b0 ) );
  3547. s1 = ( s0 > 0 ) ? - segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  3548. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3549. } else if ( s1 <= extDet ) {
  3550. // region 3
  3551. s0 = 0;
  3552. s1 = Math.min( Math.max( - segExtent, - b1 ), segExtent );
  3553. sqrDist = s1 * ( s1 + 2 * b1 ) + c;
  3554. } else {
  3555. // region 2
  3556. s0 = Math.max( 0, - ( a01 * segExtent + b0 ) );
  3557. s1 = ( s0 > 0 ) ? segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  3558. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3559. }
  3560. }
  3561. } else {
  3562. // Ray and segment are parallel.
  3563. s1 = ( a01 > 0 ) ? - segExtent : segExtent;
  3564. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  3565. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3566. }
  3567. if ( optionalPointOnRay ) {
  3568. optionalPointOnRay.copy( this.direction ).multiplyScalar( s0 ).add( this.origin );
  3569. }
  3570. if ( optionalPointOnSegment ) {
  3571. optionalPointOnSegment.copy( _segDir ).multiplyScalar( s1 ).add( _segCenter );
  3572. }
  3573. return sqrDist;
  3574. }
  3575. intersectSphere( sphere, target ) {
  3576. _vector$a.subVectors( sphere.center, this.origin );
  3577. const tca = _vector$a.dot( this.direction );
  3578. const d2 = _vector$a.dot( _vector$a ) - tca * tca;
  3579. const radius2 = sphere.radius * sphere.radius;
  3580. if ( d2 > radius2 ) return null;
  3581. const thc = Math.sqrt( radius2 - d2 );
  3582. // t0 = first intersect point - entrance on front of sphere
  3583. const t0 = tca - thc;
  3584. // t1 = second intersect point - exit point on back of sphere
  3585. const t1 = tca + thc;
  3586. // test to see if both t0 and t1 are behind the ray - if so, return null
  3587. if ( t0 < 0 && t1 < 0 ) return null;
  3588. // test to see if t0 is behind the ray:
  3589. // if it is, the ray is inside the sphere, so return the second exit point scaled by t1,
  3590. // in order to always return an intersect point that is in front of the ray.
  3591. if ( t0 < 0 ) return this.at( t1, target );
  3592. // else t0 is in front of the ray, so return the first collision point scaled by t0
  3593. return this.at( t0, target );
  3594. }
  3595. intersectsSphere( sphere ) {
  3596. return this.distanceSqToPoint( sphere.center ) <= ( sphere.radius * sphere.radius );
  3597. }
  3598. distanceToPlane( plane ) {
  3599. const denominator = plane.normal.dot( this.direction );
  3600. if ( denominator === 0 ) {
  3601. // line is coplanar, return origin
  3602. if ( plane.distanceToPoint( this.origin ) === 0 ) {
  3603. return 0;
  3604. }
  3605. // Null is preferable to undefined since undefined means.... it is undefined
  3606. return null;
  3607. }
  3608. const t = - ( this.origin.dot( plane.normal ) + plane.constant ) / denominator;
  3609. // Return if the ray never intersects the plane
  3610. return t >= 0 ? t : null;
  3611. }
  3612. intersectPlane( plane, target ) {
  3613. const t = this.distanceToPlane( plane );
  3614. if ( t === null ) {
  3615. return null;
  3616. }
  3617. return this.at( t, target );
  3618. }
  3619. intersectsPlane( plane ) {
  3620. // check if the ray lies on the plane first
  3621. const distToPoint = plane.distanceToPoint( this.origin );
  3622. if ( distToPoint === 0 ) {
  3623. return true;
  3624. }
  3625. const denominator = plane.normal.dot( this.direction );
  3626. if ( denominator * distToPoint < 0 ) {
  3627. return true;
  3628. }
  3629. // ray origin is behind the plane (and is pointing behind it)
  3630. return false;
  3631. }
  3632. intersectBox( box, target ) {
  3633. let tmin, tmax, tymin, tymax, tzmin, tzmax;
  3634. const invdirx = 1 / this.direction.x,
  3635. invdiry = 1 / this.direction.y,
  3636. invdirz = 1 / this.direction.z;
  3637. const origin = this.origin;
  3638. if ( invdirx >= 0 ) {
  3639. tmin = ( box.min.x - origin.x ) * invdirx;
  3640. tmax = ( box.max.x - origin.x ) * invdirx;
  3641. } else {
  3642. tmin = ( box.max.x - origin.x ) * invdirx;
  3643. tmax = ( box.min.x - origin.x ) * invdirx;
  3644. }
  3645. if ( invdiry >= 0 ) {
  3646. tymin = ( box.min.y - origin.y ) * invdiry;
  3647. tymax = ( box.max.y - origin.y ) * invdiry;
  3648. } else {
  3649. tymin = ( box.max.y - origin.y ) * invdiry;
  3650. tymax = ( box.min.y - origin.y ) * invdiry;
  3651. }
  3652. if ( ( tmin > tymax ) || ( tymin > tmax ) ) return null;
  3653. if ( tymin > tmin || isNaN( tmin ) ) tmin = tymin;
  3654. if ( tymax < tmax || isNaN( tmax ) ) tmax = tymax;
  3655. if ( invdirz >= 0 ) {
  3656. tzmin = ( box.min.z - origin.z ) * invdirz;
  3657. tzmax = ( box.max.z - origin.z ) * invdirz;
  3658. } else {
  3659. tzmin = ( box.max.z - origin.z ) * invdirz;
  3660. tzmax = ( box.min.z - origin.z ) * invdirz;
  3661. }
  3662. if ( ( tmin > tzmax ) || ( tzmin > tmax ) ) return null;
  3663. if ( tzmin > tmin || tmin !== tmin ) tmin = tzmin;
  3664. if ( tzmax < tmax || tmax !== tmax ) tmax = tzmax;
  3665. //return point closest to the ray (positive side)
  3666. if ( tmax < 0 ) return null;
  3667. return this.at( tmin >= 0 ? tmin : tmax, target );
  3668. }
  3669. intersectsBox( box ) {
  3670. return this.intersectBox( box, _vector$a ) !== null;
  3671. }
  3672. intersectTriangle( a, b, c, backfaceCulling, target ) {
  3673. // Compute the offset origin, edges, and normal.
  3674. // from https://github.com/pmjoniak/GeometricTools/blob/master/GTEngine/Include/Mathematics/GteIntrRay3Triangle3.h
  3675. _edge1.subVectors( b, a );
  3676. _edge2.subVectors( c, a );
  3677. _normal$1.crossVectors( _edge1, _edge2 );
  3678. // Solve Q + t*D = b1*E1 + b2*E2 (Q = kDiff, D = ray direction,
  3679. // E1 = kEdge1, E2 = kEdge2, N = Cross(E1,E2)) by
  3680. // |Dot(D,N)|*b1 = sign(Dot(D,N))*Dot(D,Cross(Q,E2))
  3681. // |Dot(D,N)|*b2 = sign(Dot(D,N))*Dot(D,Cross(E1,Q))
  3682. // |Dot(D,N)|*t = -sign(Dot(D,N))*Dot(Q,N)
  3683. let DdN = this.direction.dot( _normal$1 );
  3684. let sign;
  3685. if ( DdN > 0 ) {
  3686. if ( backfaceCulling ) return null;
  3687. sign = 1;
  3688. } else if ( DdN < 0 ) {
  3689. sign = - 1;
  3690. DdN = - DdN;
  3691. } else {
  3692. return null;
  3693. }
  3694. _diff.subVectors( this.origin, a );
  3695. const DdQxE2 = sign * this.direction.dot( _edge2.crossVectors( _diff, _edge2 ) );
  3696. // b1 < 0, no intersection
  3697. if ( DdQxE2 < 0 ) {
  3698. return null;
  3699. }
  3700. const DdE1xQ = sign * this.direction.dot( _edge1.cross( _diff ) );
  3701. // b2 < 0, no intersection
  3702. if ( DdE1xQ < 0 ) {
  3703. return null;
  3704. }
  3705. // b1+b2 > 1, no intersection
  3706. if ( DdQxE2 + DdE1xQ > DdN ) {
  3707. return null;
  3708. }
  3709. // Line intersects triangle, check if ray does.
  3710. const QdN = - sign * _diff.dot( _normal$1 );
  3711. // t < 0, no intersection
  3712. if ( QdN < 0 ) {
  3713. return null;
  3714. }
  3715. // Ray intersects triangle.
  3716. return this.at( QdN / DdN, target );
  3717. }
  3718. applyMatrix4( matrix4 ) {
  3719. this.origin.applyMatrix4( matrix4 );
  3720. this.direction.transformDirection( matrix4 );
  3721. return this;
  3722. }
  3723. equals( ray ) {
  3724. return ray.origin.equals( this.origin ) && ray.direction.equals( this.direction );
  3725. }
  3726. clone() {
  3727. return new this.constructor().copy( this );
  3728. }
  3729. }
  3730. class Matrix4 {
  3731. constructor() {
  3732. Matrix4.prototype.isMatrix4 = true;
  3733. this.elements = [
  3734. 1, 0, 0, 0,
  3735. 0, 1, 0, 0,
  3736. 0, 0, 1, 0,
  3737. 0, 0, 0, 1
  3738. ];
  3739. }
  3740. set( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  3741. const te = this.elements;
  3742. te[ 0 ] = n11; te[ 4 ] = n12; te[ 8 ] = n13; te[ 12 ] = n14;
  3743. te[ 1 ] = n21; te[ 5 ] = n22; te[ 9 ] = n23; te[ 13 ] = n24;
  3744. te[ 2 ] = n31; te[ 6 ] = n32; te[ 10 ] = n33; te[ 14 ] = n34;
  3745. te[ 3 ] = n41; te[ 7 ] = n42; te[ 11 ] = n43; te[ 15 ] = n44;
  3746. return this;
  3747. }
  3748. identity() {
  3749. this.set(
  3750. 1, 0, 0, 0,
  3751. 0, 1, 0, 0,
  3752. 0, 0, 1, 0,
  3753. 0, 0, 0, 1
  3754. );
  3755. return this;
  3756. }
  3757. clone() {
  3758. return new Matrix4().fromArray( this.elements );
  3759. }
  3760. copy( m ) {
  3761. const te = this.elements;
  3762. const me = m.elements;
  3763. te[ 0 ] = me[ 0 ]; te[ 1 ] = me[ 1 ]; te[ 2 ] = me[ 2 ]; te[ 3 ] = me[ 3 ];
  3764. te[ 4 ] = me[ 4 ]; te[ 5 ] = me[ 5 ]; te[ 6 ] = me[ 6 ]; te[ 7 ] = me[ 7 ];
  3765. te[ 8 ] = me[ 8 ]; te[ 9 ] = me[ 9 ]; te[ 10 ] = me[ 10 ]; te[ 11 ] = me[ 11 ];
  3766. te[ 12 ] = me[ 12 ]; te[ 13 ] = me[ 13 ]; te[ 14 ] = me[ 14 ]; te[ 15 ] = me[ 15 ];
  3767. return this;
  3768. }
  3769. copyPosition( m ) {
  3770. const te = this.elements, me = m.elements;
  3771. te[ 12 ] = me[ 12 ];
  3772. te[ 13 ] = me[ 13 ];
  3773. te[ 14 ] = me[ 14 ];
  3774. return this;
  3775. }
  3776. setFromMatrix3( m ) {
  3777. const me = m.elements;
  3778. this.set(
  3779. me[ 0 ], me[ 3 ], me[ 6 ], 0,
  3780. me[ 1 ], me[ 4 ], me[ 7 ], 0,
  3781. me[ 2 ], me[ 5 ], me[ 8 ], 0,
  3782. 0, 0, 0, 1
  3783. );
  3784. return this;
  3785. }
  3786. extractBasis( xAxis, yAxis, zAxis ) {
  3787. xAxis.setFromMatrixColumn( this, 0 );
  3788. yAxis.setFromMatrixColumn( this, 1 );
  3789. zAxis.setFromMatrixColumn( this, 2 );
  3790. return this;
  3791. }
  3792. makeBasis( xAxis, yAxis, zAxis ) {
  3793. this.set(
  3794. xAxis.x, yAxis.x, zAxis.x, 0,
  3795. xAxis.y, yAxis.y, zAxis.y, 0,
  3796. xAxis.z, yAxis.z, zAxis.z, 0,
  3797. 0, 0, 0, 1
  3798. );
  3799. return this;
  3800. }
  3801. extractRotation( m ) {
  3802. // this method does not support reflection matrices
  3803. const te = this.elements;
  3804. const me = m.elements;
  3805. const scaleX = 1 / _v1$5.setFromMatrixColumn( m, 0 ).length();
  3806. const scaleY = 1 / _v1$5.setFromMatrixColumn( m, 1 ).length();
  3807. const scaleZ = 1 / _v1$5.setFromMatrixColumn( m, 2 ).length();
  3808. te[ 0 ] = me[ 0 ] * scaleX;
  3809. te[ 1 ] = me[ 1 ] * scaleX;
  3810. te[ 2 ] = me[ 2 ] * scaleX;
  3811. te[ 3 ] = 0;
  3812. te[ 4 ] = me[ 4 ] * scaleY;
  3813. te[ 5 ] = me[ 5 ] * scaleY;
  3814. te[ 6 ] = me[ 6 ] * scaleY;
  3815. te[ 7 ] = 0;
  3816. te[ 8 ] = me[ 8 ] * scaleZ;
  3817. te[ 9 ] = me[ 9 ] * scaleZ;
  3818. te[ 10 ] = me[ 10 ] * scaleZ;
  3819. te[ 11 ] = 0;
  3820. te[ 12 ] = 0;
  3821. te[ 13 ] = 0;
  3822. te[ 14 ] = 0;
  3823. te[ 15 ] = 1;
  3824. return this;
  3825. }
  3826. makeRotationFromEuler( euler ) {
  3827. const te = this.elements;
  3828. const x = euler.x, y = euler.y, z = euler.z;
  3829. const a = Math.cos( x ), b = Math.sin( x );
  3830. const c = Math.cos( y ), d = Math.sin( y );
  3831. const e = Math.cos( z ), f = Math.sin( z );
  3832. if ( euler.order === 'XYZ' ) {
  3833. const ae = a * e, af = a * f, be = b * e, bf = b * f;
  3834. te[ 0 ] = c * e;
  3835. te[ 4 ] = - c * f;
  3836. te[ 8 ] = d;
  3837. te[ 1 ] = af + be * d;
  3838. te[ 5 ] = ae - bf * d;
  3839. te[ 9 ] = - b * c;
  3840. te[ 2 ] = bf - ae * d;
  3841. te[ 6 ] = be + af * d;
  3842. te[ 10 ] = a * c;
  3843. } else if ( euler.order === 'YXZ' ) {
  3844. const ce = c * e, cf = c * f, de = d * e, df = d * f;
  3845. te[ 0 ] = ce + df * b;
  3846. te[ 4 ] = de * b - cf;
  3847. te[ 8 ] = a * d;
  3848. te[ 1 ] = a * f;
  3849. te[ 5 ] = a * e;
  3850. te[ 9 ] = - b;
  3851. te[ 2 ] = cf * b - de;
  3852. te[ 6 ] = df + ce * b;
  3853. te[ 10 ] = a * c;
  3854. } else if ( euler.order === 'ZXY' ) {
  3855. const ce = c * e, cf = c * f, de = d * e, df = d * f;
  3856. te[ 0 ] = ce - df * b;
  3857. te[ 4 ] = - a * f;
  3858. te[ 8 ] = de + cf * b;
  3859. te[ 1 ] = cf + de * b;
  3860. te[ 5 ] = a * e;
  3861. te[ 9 ] = df - ce * b;
  3862. te[ 2 ] = - a * d;
  3863. te[ 6 ] = b;
  3864. te[ 10 ] = a * c;
  3865. } else if ( euler.order === 'ZYX' ) {
  3866. const ae = a * e, af = a * f, be = b * e, bf = b * f;
  3867. te[ 0 ] = c * e;
  3868. te[ 4 ] = be * d - af;
  3869. te[ 8 ] = ae * d + bf;
  3870. te[ 1 ] = c * f;
  3871. te[ 5 ] = bf * d + ae;
  3872. te[ 9 ] = af * d - be;
  3873. te[ 2 ] = - d;
  3874. te[ 6 ] = b * c;
  3875. te[ 10 ] = a * c;
  3876. } else if ( euler.order === 'YZX' ) {
  3877. const ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  3878. te[ 0 ] = c * e;
  3879. te[ 4 ] = bd - ac * f;
  3880. te[ 8 ] = bc * f + ad;
  3881. te[ 1 ] = f;
  3882. te[ 5 ] = a * e;
  3883. te[ 9 ] = - b * e;
  3884. te[ 2 ] = - d * e;
  3885. te[ 6 ] = ad * f + bc;
  3886. te[ 10 ] = ac - bd * f;
  3887. } else if ( euler.order === 'XZY' ) {
  3888. const ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  3889. te[ 0 ] = c * e;
  3890. te[ 4 ] = - f;
  3891. te[ 8 ] = d * e;
  3892. te[ 1 ] = ac * f + bd;
  3893. te[ 5 ] = a * e;
  3894. te[ 9 ] = ad * f - bc;
  3895. te[ 2 ] = bc * f - ad;
  3896. te[ 6 ] = b * e;
  3897. te[ 10 ] = bd * f + ac;
  3898. }
  3899. // bottom row
  3900. te[ 3 ] = 0;
  3901. te[ 7 ] = 0;
  3902. te[ 11 ] = 0;
  3903. // last column
  3904. te[ 12 ] = 0;
  3905. te[ 13 ] = 0;
  3906. te[ 14 ] = 0;
  3907. te[ 15 ] = 1;
  3908. return this;
  3909. }
  3910. makeRotationFromQuaternion( q ) {
  3911. return this.compose( _zero, q, _one );
  3912. }
  3913. lookAt( eye, target, up ) {
  3914. const te = this.elements;
  3915. _z.subVectors( eye, target );
  3916. if ( _z.lengthSq() === 0 ) {
  3917. // eye and target are in the same position
  3918. _z.z = 1;
  3919. }
  3920. _z.normalize();
  3921. _x.crossVectors( up, _z );
  3922. if ( _x.lengthSq() === 0 ) {
  3923. // up and z are parallel
  3924. if ( Math.abs( up.z ) === 1 ) {
  3925. _z.x += 0.0001;
  3926. } else {
  3927. _z.z += 0.0001;
  3928. }
  3929. _z.normalize();
  3930. _x.crossVectors( up, _z );
  3931. }
  3932. _x.normalize();
  3933. _y.crossVectors( _z, _x );
  3934. te[ 0 ] = _x.x; te[ 4 ] = _y.x; te[ 8 ] = _z.x;
  3935. te[ 1 ] = _x.y; te[ 5 ] = _y.y; te[ 9 ] = _z.y;
  3936. te[ 2 ] = _x.z; te[ 6 ] = _y.z; te[ 10 ] = _z.z;
  3937. return this;
  3938. }
  3939. multiply( m ) {
  3940. return this.multiplyMatrices( this, m );
  3941. }
  3942. premultiply( m ) {
  3943. return this.multiplyMatrices( m, this );
  3944. }
  3945. multiplyMatrices( a, b ) {
  3946. const ae = a.elements;
  3947. const be = b.elements;
  3948. const te = this.elements;
  3949. const a11 = ae[ 0 ], a12 = ae[ 4 ], a13 = ae[ 8 ], a14 = ae[ 12 ];
  3950. const a21 = ae[ 1 ], a22 = ae[ 5 ], a23 = ae[ 9 ], a24 = ae[ 13 ];
  3951. const a31 = ae[ 2 ], a32 = ae[ 6 ], a33 = ae[ 10 ], a34 = ae[ 14 ];
  3952. const a41 = ae[ 3 ], a42 = ae[ 7 ], a43 = ae[ 11 ], a44 = ae[ 15 ];
  3953. const b11 = be[ 0 ], b12 = be[ 4 ], b13 = be[ 8 ], b14 = be[ 12 ];
  3954. const b21 = be[ 1 ], b22 = be[ 5 ], b23 = be[ 9 ], b24 = be[ 13 ];
  3955. const b31 = be[ 2 ], b32 = be[ 6 ], b33 = be[ 10 ], b34 = be[ 14 ];
  3956. const b41 = be[ 3 ], b42 = be[ 7 ], b43 = be[ 11 ], b44 = be[ 15 ];
  3957. te[ 0 ] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41;
  3958. te[ 4 ] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42;
  3959. te[ 8 ] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43;
  3960. te[ 12 ] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44;
  3961. te[ 1 ] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41;
  3962. te[ 5 ] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42;
  3963. te[ 9 ] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43;
  3964. te[ 13 ] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44;
  3965. te[ 2 ] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41;
  3966. te[ 6 ] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42;
  3967. te[ 10 ] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43;
  3968. te[ 14 ] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44;
  3969. te[ 3 ] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41;
  3970. te[ 7 ] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42;
  3971. te[ 11 ] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43;
  3972. te[ 15 ] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44;
  3973. return this;
  3974. }
  3975. multiplyScalar( s ) {
  3976. const te = this.elements;
  3977. te[ 0 ] *= s; te[ 4 ] *= s; te[ 8 ] *= s; te[ 12 ] *= s;
  3978. te[ 1 ] *= s; te[ 5 ] *= s; te[ 9 ] *= s; te[ 13 ] *= s;
  3979. te[ 2 ] *= s; te[ 6 ] *= s; te[ 10 ] *= s; te[ 14 ] *= s;
  3980. te[ 3 ] *= s; te[ 7 ] *= s; te[ 11 ] *= s; te[ 15 ] *= s;
  3981. return this;
  3982. }
  3983. determinant() {
  3984. const te = this.elements;
  3985. const n11 = te[ 0 ], n12 = te[ 4 ], n13 = te[ 8 ], n14 = te[ 12 ];
  3986. const n21 = te[ 1 ], n22 = te[ 5 ], n23 = te[ 9 ], n24 = te[ 13 ];
  3987. const n31 = te[ 2 ], n32 = te[ 6 ], n33 = te[ 10 ], n34 = te[ 14 ];
  3988. const n41 = te[ 3 ], n42 = te[ 7 ], n43 = te[ 11 ], n44 = te[ 15 ];
  3989. //TODO: make this more efficient
  3990. //( based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm )
  3991. return (
  3992. n41 * (
  3993. + n14 * n23 * n32
  3994. - n13 * n24 * n32
  3995. - n14 * n22 * n33
  3996. + n12 * n24 * n33
  3997. + n13 * n22 * n34
  3998. - n12 * n23 * n34
  3999. ) +
  4000. n42 * (
  4001. + n11 * n23 * n34
  4002. - n11 * n24 * n33
  4003. + n14 * n21 * n33
  4004. - n13 * n21 * n34
  4005. + n13 * n24 * n31
  4006. - n14 * n23 * n31
  4007. ) +
  4008. n43 * (
  4009. + n11 * n24 * n32
  4010. - n11 * n22 * n34
  4011. - n14 * n21 * n32
  4012. + n12 * n21 * n34
  4013. + n14 * n22 * n31
  4014. - n12 * n24 * n31
  4015. ) +
  4016. n44 * (
  4017. - n13 * n22 * n31
  4018. - n11 * n23 * n32
  4019. + n11 * n22 * n33
  4020. + n13 * n21 * n32
  4021. - n12 * n21 * n33
  4022. + n12 * n23 * n31
  4023. )
  4024. );
  4025. }
  4026. transpose() {
  4027. const te = this.elements;
  4028. let tmp;
  4029. tmp = te[ 1 ]; te[ 1 ] = te[ 4 ]; te[ 4 ] = tmp;
  4030. tmp = te[ 2 ]; te[ 2 ] = te[ 8 ]; te[ 8 ] = tmp;
  4031. tmp = te[ 6 ]; te[ 6 ] = te[ 9 ]; te[ 9 ] = tmp;
  4032. tmp = te[ 3 ]; te[ 3 ] = te[ 12 ]; te[ 12 ] = tmp;
  4033. tmp = te[ 7 ]; te[ 7 ] = te[ 13 ]; te[ 13 ] = tmp;
  4034. tmp = te[ 11 ]; te[ 11 ] = te[ 14 ]; te[ 14 ] = tmp;
  4035. return this;
  4036. }
  4037. setPosition( x, y, z ) {
  4038. const te = this.elements;
  4039. if ( x.isVector3 ) {
  4040. te[ 12 ] = x.x;
  4041. te[ 13 ] = x.y;
  4042. te[ 14 ] = x.z;
  4043. } else {
  4044. te[ 12 ] = x;
  4045. te[ 13 ] = y;
  4046. te[ 14 ] = z;
  4047. }
  4048. return this;
  4049. }
  4050. invert() {
  4051. // based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm
  4052. const te = this.elements,
  4053. n11 = te[ 0 ], n21 = te[ 1 ], n31 = te[ 2 ], n41 = te[ 3 ],
  4054. n12 = te[ 4 ], n22 = te[ 5 ], n32 = te[ 6 ], n42 = te[ 7 ],
  4055. n13 = te[ 8 ], n23 = te[ 9 ], n33 = te[ 10 ], n43 = te[ 11 ],
  4056. n14 = te[ 12 ], n24 = te[ 13 ], n34 = te[ 14 ], n44 = te[ 15 ],
  4057. t11 = n23 * n34 * n42 - n24 * n33 * n42 + n24 * n32 * n43 - n22 * n34 * n43 - n23 * n32 * n44 + n22 * n33 * n44,
  4058. t12 = n14 * n33 * n42 - n13 * n34 * n42 - n14 * n32 * n43 + n12 * n34 * n43 + n13 * n32 * n44 - n12 * n33 * n44,
  4059. t13 = n13 * n24 * n42 - n14 * n23 * n42 + n14 * n22 * n43 - n12 * n24 * n43 - n13 * n22 * n44 + n12 * n23 * n44,
  4060. t14 = n14 * n23 * n32 - n13 * n24 * n32 - n14 * n22 * n33 + n12 * n24 * n33 + n13 * n22 * n34 - n12 * n23 * n34;
  4061. const det = n11 * t11 + n21 * t12 + n31 * t13 + n41 * t14;
  4062. if ( det === 0 ) return this.set( 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 );
  4063. const detInv = 1 / det;
  4064. te[ 0 ] = t11 * detInv;
  4065. te[ 1 ] = ( n24 * n33 * n41 - n23 * n34 * n41 - n24 * n31 * n43 + n21 * n34 * n43 + n23 * n31 * n44 - n21 * n33 * n44 ) * detInv;
  4066. te[ 2 ] = ( n22 * n34 * n41 - n24 * n32 * n41 + n24 * n31 * n42 - n21 * n34 * n42 - n22 * n31 * n44 + n21 * n32 * n44 ) * detInv;
  4067. te[ 3 ] = ( n23 * n32 * n41 - n22 * n33 * n41 - n23 * n31 * n42 + n21 * n33 * n42 + n22 * n31 * n43 - n21 * n32 * n43 ) * detInv;
  4068. te[ 4 ] = t12 * detInv;
  4069. te[ 5 ] = ( n13 * n34 * n41 - n14 * n33 * n41 + n14 * n31 * n43 - n11 * n34 * n43 - n13 * n31 * n44 + n11 * n33 * n44 ) * detInv;
  4070. te[ 6 ] = ( n14 * n32 * n41 - n12 * n34 * n41 - n14 * n31 * n42 + n11 * n34 * n42 + n12 * n31 * n44 - n11 * n32 * n44 ) * detInv;
  4071. te[ 7 ] = ( n12 * n33 * n41 - n13 * n32 * n41 + n13 * n31 * n42 - n11 * n33 * n42 - n12 * n31 * n43 + n11 * n32 * n43 ) * detInv;
  4072. te[ 8 ] = t13 * detInv;
  4073. te[ 9 ] = ( n14 * n23 * n41 - n13 * n24 * n41 - n14 * n21 * n43 + n11 * n24 * n43 + n13 * n21 * n44 - n11 * n23 * n44 ) * detInv;
  4074. te[ 10 ] = ( n12 * n24 * n41 - n14 * n22 * n41 + n14 * n21 * n42 - n11 * n24 * n42 - n12 * n21 * n44 + n11 * n22 * n44 ) * detInv;
  4075. te[ 11 ] = ( n13 * n22 * n41 - n12 * n23 * n41 - n13 * n21 * n42 + n11 * n23 * n42 + n12 * n21 * n43 - n11 * n22 * n43 ) * detInv;
  4076. te[ 12 ] = t14 * detInv;
  4077. te[ 13 ] = ( n13 * n24 * n31 - n14 * n23 * n31 + n14 * n21 * n33 - n11 * n24 * n33 - n13 * n21 * n34 + n11 * n23 * n34 ) * detInv;
  4078. te[ 14 ] = ( n14 * n22 * n31 - n12 * n24 * n31 - n14 * n21 * n32 + n11 * n24 * n32 + n12 * n21 * n34 - n11 * n22 * n34 ) * detInv;
  4079. te[ 15 ] = ( n12 * n23 * n31 - n13 * n22 * n31 + n13 * n21 * n32 - n11 * n23 * n32 - n12 * n21 * n33 + n11 * n22 * n33 ) * detInv;
  4080. return this;
  4081. }
  4082. scale( v ) {
  4083. const te = this.elements;
  4084. const x = v.x, y = v.y, z = v.z;
  4085. te[ 0 ] *= x; te[ 4 ] *= y; te[ 8 ] *= z;
  4086. te[ 1 ] *= x; te[ 5 ] *= y; te[ 9 ] *= z;
  4087. te[ 2 ] *= x; te[ 6 ] *= y; te[ 10 ] *= z;
  4088. te[ 3 ] *= x; te[ 7 ] *= y; te[ 11 ] *= z;
  4089. return this;
  4090. }
  4091. getMaxScaleOnAxis() {
  4092. const te = this.elements;
  4093. const scaleXSq = te[ 0 ] * te[ 0 ] + te[ 1 ] * te[ 1 ] + te[ 2 ] * te[ 2 ];
  4094. const scaleYSq = te[ 4 ] * te[ 4 ] + te[ 5 ] * te[ 5 ] + te[ 6 ] * te[ 6 ];
  4095. const scaleZSq = te[ 8 ] * te[ 8 ] + te[ 9 ] * te[ 9 ] + te[ 10 ] * te[ 10 ];
  4096. return Math.sqrt( Math.max( scaleXSq, scaleYSq, scaleZSq ) );
  4097. }
  4098. makeTranslation( x, y, z ) {
  4099. this.set(
  4100. 1, 0, 0, x,
  4101. 0, 1, 0, y,
  4102. 0, 0, 1, z,
  4103. 0, 0, 0, 1
  4104. );
  4105. return this;
  4106. }
  4107. makeRotationX( theta ) {
  4108. const c = Math.cos( theta ), s = Math.sin( theta );
  4109. this.set(
  4110. 1, 0, 0, 0,
  4111. 0, c, - s, 0,
  4112. 0, s, c, 0,
  4113. 0, 0, 0, 1
  4114. );
  4115. return this;
  4116. }
  4117. makeRotationY( theta ) {
  4118. const c = Math.cos( theta ), s = Math.sin( theta );
  4119. this.set(
  4120. c, 0, s, 0,
  4121. 0, 1, 0, 0,
  4122. - s, 0, c, 0,
  4123. 0, 0, 0, 1
  4124. );
  4125. return this;
  4126. }
  4127. makeRotationZ( theta ) {
  4128. const c = Math.cos( theta ), s = Math.sin( theta );
  4129. this.set(
  4130. c, - s, 0, 0,
  4131. s, c, 0, 0,
  4132. 0, 0, 1, 0,
  4133. 0, 0, 0, 1
  4134. );
  4135. return this;
  4136. }
  4137. makeRotationAxis( axis, angle ) {
  4138. // Based on http://www.gamedev.net/reference/articles/article1199.asp
  4139. const c = Math.cos( angle );
  4140. const s = Math.sin( angle );
  4141. const t = 1 - c;
  4142. const x = axis.x, y = axis.y, z = axis.z;
  4143. const tx = t * x, ty = t * y;
  4144. this.set(
  4145. tx * x + c, tx * y - s * z, tx * z + s * y, 0,
  4146. tx * y + s * z, ty * y + c, ty * z - s * x, 0,
  4147. tx * z - s * y, ty * z + s * x, t * z * z + c, 0,
  4148. 0, 0, 0, 1
  4149. );
  4150. return this;
  4151. }
  4152. makeScale( x, y, z ) {
  4153. this.set(
  4154. x, 0, 0, 0,
  4155. 0, y, 0, 0,
  4156. 0, 0, z, 0,
  4157. 0, 0, 0, 1
  4158. );
  4159. return this;
  4160. }
  4161. makeShear( xy, xz, yx, yz, zx, zy ) {
  4162. this.set(
  4163. 1, yx, zx, 0,
  4164. xy, 1, zy, 0,
  4165. xz, yz, 1, 0,
  4166. 0, 0, 0, 1
  4167. );
  4168. return this;
  4169. }
  4170. compose( position, quaternion, scale ) {
  4171. const te = this.elements;
  4172. const x = quaternion._x, y = quaternion._y, z = quaternion._z, w = quaternion._w;
  4173. const x2 = x + x, y2 = y + y, z2 = z + z;
  4174. const xx = x * x2, xy = x * y2, xz = x * z2;
  4175. const yy = y * y2, yz = y * z2, zz = z * z2;
  4176. const wx = w * x2, wy = w * y2, wz = w * z2;
  4177. const sx = scale.x, sy = scale.y, sz = scale.z;
  4178. te[ 0 ] = ( 1 - ( yy + zz ) ) * sx;
  4179. te[ 1 ] = ( xy + wz ) * sx;
  4180. te[ 2 ] = ( xz - wy ) * sx;
  4181. te[ 3 ] = 0;
  4182. te[ 4 ] = ( xy - wz ) * sy;
  4183. te[ 5 ] = ( 1 - ( xx + zz ) ) * sy;
  4184. te[ 6 ] = ( yz + wx ) * sy;
  4185. te[ 7 ] = 0;
  4186. te[ 8 ] = ( xz + wy ) * sz;
  4187. te[ 9 ] = ( yz - wx ) * sz;
  4188. te[ 10 ] = ( 1 - ( xx + yy ) ) * sz;
  4189. te[ 11 ] = 0;
  4190. te[ 12 ] = position.x;
  4191. te[ 13 ] = position.y;
  4192. te[ 14 ] = position.z;
  4193. te[ 15 ] = 1;
  4194. return this;
  4195. }
  4196. decompose( position, quaternion, scale ) {
  4197. const te = this.elements;
  4198. let sx = _v1$5.set( te[ 0 ], te[ 1 ], te[ 2 ] ).length();
  4199. const sy = _v1$5.set( te[ 4 ], te[ 5 ], te[ 6 ] ).length();
  4200. const sz = _v1$5.set( te[ 8 ], te[ 9 ], te[ 10 ] ).length();
  4201. // if determine is negative, we need to invert one scale
  4202. const det = this.determinant();
  4203. if ( det < 0 ) sx = - sx;
  4204. position.x = te[ 12 ];
  4205. position.y = te[ 13 ];
  4206. position.z = te[ 14 ];
  4207. // scale the rotation part
  4208. _m1$2.copy( this );
  4209. const invSX = 1 / sx;
  4210. const invSY = 1 / sy;
  4211. const invSZ = 1 / sz;
  4212. _m1$2.elements[ 0 ] *= invSX;
  4213. _m1$2.elements[ 1 ] *= invSX;
  4214. _m1$2.elements[ 2 ] *= invSX;
  4215. _m1$2.elements[ 4 ] *= invSY;
  4216. _m1$2.elements[ 5 ] *= invSY;
  4217. _m1$2.elements[ 6 ] *= invSY;
  4218. _m1$2.elements[ 8 ] *= invSZ;
  4219. _m1$2.elements[ 9 ] *= invSZ;
  4220. _m1$2.elements[ 10 ] *= invSZ;
  4221. quaternion.setFromRotationMatrix( _m1$2 );
  4222. scale.x = sx;
  4223. scale.y = sy;
  4224. scale.z = sz;
  4225. return this;
  4226. }
  4227. makePerspective( left, right, top, bottom, near, far ) {
  4228. const te = this.elements;
  4229. const x = 2 * near / ( right - left );
  4230. const y = 2 * near / ( top - bottom );
  4231. const a = ( right + left ) / ( right - left );
  4232. const b = ( top + bottom ) / ( top - bottom );
  4233. const c = - ( far + near ) / ( far - near );
  4234. const d = - 2 * far * near / ( far - near );
  4235. te[ 0 ] = x; te[ 4 ] = 0; te[ 8 ] = a; te[ 12 ] = 0;
  4236. te[ 1 ] = 0; te[ 5 ] = y; te[ 9 ] = b; te[ 13 ] = 0;
  4237. te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = c; te[ 14 ] = d;
  4238. te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = - 1; te[ 15 ] = 0;
  4239. return this;
  4240. }
  4241. makeOrthographic( left, right, top, bottom, near, far ) {
  4242. const te = this.elements;
  4243. const w = 1.0 / ( right - left );
  4244. const h = 1.0 / ( top - bottom );
  4245. const p = 1.0 / ( far - near );
  4246. const x = ( right + left ) * w;
  4247. const y = ( top + bottom ) * h;
  4248. const z = ( far + near ) * p;
  4249. te[ 0 ] = 2 * w; te[ 4 ] = 0; te[ 8 ] = 0; te[ 12 ] = - x;
  4250. te[ 1 ] = 0; te[ 5 ] = 2 * h; te[ 9 ] = 0; te[ 13 ] = - y;
  4251. te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = - 2 * p; te[ 14 ] = - z;
  4252. te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = 0; te[ 15 ] = 1;
  4253. return this;
  4254. }
  4255. equals( matrix ) {
  4256. const te = this.elements;
  4257. const me = matrix.elements;
  4258. for ( let i = 0; i < 16; i ++ ) {
  4259. if ( te[ i ] !== me[ i ] ) return false;
  4260. }
  4261. return true;
  4262. }
  4263. fromArray( array, offset = 0 ) {
  4264. for ( let i = 0; i < 16; i ++ ) {
  4265. this.elements[ i ] = array[ i + offset ];
  4266. }
  4267. return this;
  4268. }
  4269. toArray( array = [], offset = 0 ) {
  4270. const te = this.elements;
  4271. array[ offset ] = te[ 0 ];
  4272. array[ offset + 1 ] = te[ 1 ];
  4273. array[ offset + 2 ] = te[ 2 ];
  4274. array[ offset + 3 ] = te[ 3 ];
  4275. array[ offset + 4 ] = te[ 4 ];
  4276. array[ offset + 5 ] = te[ 5 ];
  4277. array[ offset + 6 ] = te[ 6 ];
  4278. array[ offset + 7 ] = te[ 7 ];
  4279. array[ offset + 8 ] = te[ 8 ];
  4280. array[ offset + 9 ] = te[ 9 ];
  4281. array[ offset + 10 ] = te[ 10 ];
  4282. array[ offset + 11 ] = te[ 11 ];
  4283. array[ offset + 12 ] = te[ 12 ];
  4284. array[ offset + 13 ] = te[ 13 ];
  4285. array[ offset + 14 ] = te[ 14 ];
  4286. array[ offset + 15 ] = te[ 15 ];
  4287. return array;
  4288. }
  4289. }
  4290. const _v1$5 = /*@__PURE__*/ new Vector3();
  4291. const _m1$2 = /*@__PURE__*/ new Matrix4();
  4292. const _zero = /*@__PURE__*/ new Vector3( 0, 0, 0 );
  4293. const _one = /*@__PURE__*/ new Vector3( 1, 1, 1 );
  4294. const _x = /*@__PURE__*/ new Vector3();
  4295. const _y = /*@__PURE__*/ new Vector3();
  4296. const _z = /*@__PURE__*/ new Vector3();
  4297. const _matrix$1 = /*@__PURE__*/ new Matrix4();
  4298. const _quaternion$3 = /*@__PURE__*/ new Quaternion();
  4299. class Euler {
  4300. constructor( x = 0, y = 0, z = 0, order = Euler.DEFAULT_ORDER ) {
  4301. this.isEuler = true;
  4302. this._x = x;
  4303. this._y = y;
  4304. this._z = z;
  4305. this._order = order;
  4306. }
  4307. get x() {
  4308. return this._x;
  4309. }
  4310. set x( value ) {
  4311. this._x = value;
  4312. this._onChangeCallback();
  4313. }
  4314. get y() {
  4315. return this._y;
  4316. }
  4317. set y( value ) {
  4318. this._y = value;
  4319. this._onChangeCallback();
  4320. }
  4321. get z() {
  4322. return this._z;
  4323. }
  4324. set z( value ) {
  4325. this._z = value;
  4326. this._onChangeCallback();
  4327. }
  4328. get order() {
  4329. return this._order;
  4330. }
  4331. set order( value ) {
  4332. this._order = value;
  4333. this._onChangeCallback();
  4334. }
  4335. set( x, y, z, order = this._order ) {
  4336. this._x = x;
  4337. this._y = y;
  4338. this._z = z;
  4339. this._order = order;
  4340. this._onChangeCallback();
  4341. return this;
  4342. }
  4343. clone() {
  4344. return new this.constructor( this._x, this._y, this._z, this._order );
  4345. }
  4346. copy( euler ) {
  4347. this._x = euler._x;
  4348. this._y = euler._y;
  4349. this._z = euler._z;
  4350. this._order = euler._order;
  4351. this._onChangeCallback();
  4352. return this;
  4353. }
  4354. setFromRotationMatrix( m, order = this._order, update = true ) {
  4355. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  4356. const te = m.elements;
  4357. const m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ];
  4358. const m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ];
  4359. const m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];
  4360. switch ( order ) {
  4361. case 'XYZ':
  4362. this._y = Math.asin( clamp( m13, - 1, 1 ) );
  4363. if ( Math.abs( m13 ) < 0.9999999 ) {
  4364. this._x = Math.atan2( - m23, m33 );
  4365. this._z = Math.atan2( - m12, m11 );
  4366. } else {
  4367. this._x = Math.atan2( m32, m22 );
  4368. this._z = 0;
  4369. }
  4370. break;
  4371. case 'YXZ':
  4372. this._x = Math.asin( - clamp( m23, - 1, 1 ) );
  4373. if ( Math.abs( m23 ) < 0.9999999 ) {
  4374. this._y = Math.atan2( m13, m33 );
  4375. this._z = Math.atan2( m21, m22 );
  4376. } else {
  4377. this._y = Math.atan2( - m31, m11 );
  4378. this._z = 0;
  4379. }
  4380. break;
  4381. case 'ZXY':
  4382. this._x = Math.asin( clamp( m32, - 1, 1 ) );
  4383. if ( Math.abs( m32 ) < 0.9999999 ) {
  4384. this._y = Math.atan2( - m31, m33 );
  4385. this._z = Math.atan2( - m12, m22 );
  4386. } else {
  4387. this._y = 0;
  4388. this._z = Math.atan2( m21, m11 );
  4389. }
  4390. break;
  4391. case 'ZYX':
  4392. this._y = Math.asin( - clamp( m31, - 1, 1 ) );
  4393. if ( Math.abs( m31 ) < 0.9999999 ) {
  4394. this._x = Math.atan2( m32, m33 );
  4395. this._z = Math.atan2( m21, m11 );
  4396. } else {
  4397. this._x = 0;
  4398. this._z = Math.atan2( - m12, m22 );
  4399. }
  4400. break;
  4401. case 'YZX':
  4402. this._z = Math.asin( clamp( m21, - 1, 1 ) );
  4403. if ( Math.abs( m21 ) < 0.9999999 ) {
  4404. this._x = Math.atan2( - m23, m22 );
  4405. this._y = Math.atan2( - m31, m11 );
  4406. } else {
  4407. this._x = 0;
  4408. this._y = Math.atan2( m13, m33 );
  4409. }
  4410. break;
  4411. case 'XZY':
  4412. this._z = Math.asin( - clamp( m12, - 1, 1 ) );
  4413. if ( Math.abs( m12 ) < 0.9999999 ) {
  4414. this._x = Math.atan2( m32, m22 );
  4415. this._y = Math.atan2( m13, m11 );
  4416. } else {
  4417. this._x = Math.atan2( - m23, m33 );
  4418. this._y = 0;
  4419. }
  4420. break;
  4421. default:
  4422. console.warn( 'THREE.Euler: .setFromRotationMatrix() encountered an unknown order: ' + order );
  4423. }
  4424. this._order = order;
  4425. if ( update === true ) this._onChangeCallback();
  4426. return this;
  4427. }
  4428. setFromQuaternion( q, order, update ) {
  4429. _matrix$1.makeRotationFromQuaternion( q );
  4430. return this.setFromRotationMatrix( _matrix$1, order, update );
  4431. }
  4432. setFromVector3( v, order = this._order ) {
  4433. return this.set( v.x, v.y, v.z, order );
  4434. }
  4435. reorder( newOrder ) {
  4436. // WARNING: this discards revolution information -bhouston
  4437. _quaternion$3.setFromEuler( this );
  4438. return this.setFromQuaternion( _quaternion$3, newOrder );
  4439. }
  4440. equals( euler ) {
  4441. return ( euler._x === this._x ) && ( euler._y === this._y ) && ( euler._z === this._z ) && ( euler._order === this._order );
  4442. }
  4443. fromArray( array ) {
  4444. this._x = array[ 0 ];
  4445. this._y = array[ 1 ];
  4446. this._z = array[ 2 ];
  4447. if ( array[ 3 ] !== undefined ) this._order = array[ 3 ];
  4448. this._onChangeCallback();
  4449. return this;
  4450. }
  4451. toArray( array = [], offset = 0 ) {
  4452. array[ offset ] = this._x;
  4453. array[ offset + 1 ] = this._y;
  4454. array[ offset + 2 ] = this._z;
  4455. array[ offset + 3 ] = this._order;
  4456. return array;
  4457. }
  4458. _onChange( callback ) {
  4459. this._onChangeCallback = callback;
  4460. return this;
  4461. }
  4462. _onChangeCallback() {}
  4463. *[ Symbol.iterator ]() {
  4464. yield this._x;
  4465. yield this._y;
  4466. yield this._z;
  4467. yield this._order;
  4468. }
  4469. }
  4470. Euler.DEFAULT_ORDER = 'XYZ';
  4471. class Layers {
  4472. constructor() {
  4473. this.mask = 1 | 0;
  4474. }
  4475. set( channel ) {
  4476. this.mask = ( 1 << channel | 0 ) >>> 0;
  4477. }
  4478. enable( channel ) {
  4479. this.mask |= 1 << channel | 0;
  4480. }
  4481. enableAll() {
  4482. this.mask = 0xffffffff | 0;
  4483. }
  4484. toggle( channel ) {
  4485. this.mask ^= 1 << channel | 0;
  4486. }
  4487. disable( channel ) {
  4488. this.mask &= ~ ( 1 << channel | 0 );
  4489. }
  4490. disableAll() {
  4491. this.mask = 0;
  4492. }
  4493. test( layers ) {
  4494. return ( this.mask & layers.mask ) !== 0;
  4495. }
  4496. isEnabled( channel ) {
  4497. return ( this.mask & ( 1 << channel | 0 ) ) !== 0;
  4498. }
  4499. }
  4500. let _object3DId = 0;
  4501. const _v1$4 = /*@__PURE__*/ new Vector3();
  4502. const _q1 = /*@__PURE__*/ new Quaternion();
  4503. const _m1$1 = /*@__PURE__*/ new Matrix4();
  4504. const _target = /*@__PURE__*/ new Vector3();
  4505. const _position$3 = /*@__PURE__*/ new Vector3();
  4506. const _scale$2 = /*@__PURE__*/ new Vector3();
  4507. const _quaternion$2 = /*@__PURE__*/ new Quaternion();
  4508. const _xAxis = /*@__PURE__*/ new Vector3( 1, 0, 0 );
  4509. const _yAxis = /*@__PURE__*/ new Vector3( 0, 1, 0 );
  4510. const _zAxis = /*@__PURE__*/ new Vector3( 0, 0, 1 );
  4511. const _addedEvent = { type: 'added' };
  4512. const _removedEvent = { type: 'removed' };
  4513. class Object3D extends EventDispatcher {
  4514. constructor() {
  4515. super();
  4516. this.isObject3D = true;
  4517. Object.defineProperty( this, 'id', { value: _object3DId ++ } );
  4518. this.uuid = generateUUID();
  4519. this.name = '';
  4520. this.type = 'Object3D';
  4521. this.parent = null;
  4522. this.children = [];
  4523. this.up = Object3D.DEFAULT_UP.clone();
  4524. const position = new Vector3();
  4525. const rotation = new Euler();
  4526. const quaternion = new Quaternion();
  4527. const scale = new Vector3( 1, 1, 1 );
  4528. function onRotationChange() {
  4529. quaternion.setFromEuler( rotation, false );
  4530. }
  4531. function onQuaternionChange() {
  4532. rotation.setFromQuaternion( quaternion, undefined, false );
  4533. }
  4534. rotation._onChange( onRotationChange );
  4535. quaternion._onChange( onQuaternionChange );
  4536. Object.defineProperties( this, {
  4537. position: {
  4538. configurable: true,
  4539. enumerable: true,
  4540. value: position
  4541. },
  4542. rotation: {
  4543. configurable: true,
  4544. enumerable: true,
  4545. value: rotation
  4546. },
  4547. quaternion: {
  4548. configurable: true,
  4549. enumerable: true,
  4550. value: quaternion
  4551. },
  4552. scale: {
  4553. configurable: true,
  4554. enumerable: true,
  4555. value: scale
  4556. },
  4557. modelViewMatrix: {
  4558. value: new Matrix4()
  4559. },
  4560. normalMatrix: {
  4561. value: new Matrix3()
  4562. }
  4563. } );
  4564. this.matrix = new Matrix4();
  4565. this.matrixWorld = new Matrix4();
  4566. this.matrixAutoUpdate = Object3D.DEFAULT_MATRIX_AUTO_UPDATE;
  4567. this.matrixWorldNeedsUpdate = false;
  4568. this.matrixWorldAutoUpdate = Object3D.DEFAULT_MATRIX_WORLD_AUTO_UPDATE; // checked by the renderer
  4569. this.layers = new Layers();
  4570. this.visible = true;
  4571. this.castShadow = false;
  4572. this.receiveShadow = false;
  4573. this.frustumCulled = true;
  4574. this.renderOrder = 0;
  4575. this.animations = [];
  4576. this.userData = {};
  4577. }
  4578. onBeforeRender( /* renderer, scene, camera, geometry, material, group */ ) {}
  4579. onAfterRender( /* renderer, scene, camera, geometry, material, group */ ) {}
  4580. applyMatrix4( matrix ) {
  4581. if ( this.matrixAutoUpdate ) this.updateMatrix();
  4582. this.matrix.premultiply( matrix );
  4583. this.matrix.decompose( this.position, this.quaternion, this.scale );
  4584. }
  4585. applyQuaternion( q ) {
  4586. this.quaternion.premultiply( q );
  4587. return this;
  4588. }
  4589. setRotationFromAxisAngle( axis, angle ) {
  4590. // assumes axis is normalized
  4591. this.quaternion.setFromAxisAngle( axis, angle );
  4592. }
  4593. setRotationFromEuler( euler ) {
  4594. this.quaternion.setFromEuler( euler, true );
  4595. }
  4596. setRotationFromMatrix( m ) {
  4597. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  4598. this.quaternion.setFromRotationMatrix( m );
  4599. }
  4600. setRotationFromQuaternion( q ) {
  4601. // assumes q is normalized
  4602. this.quaternion.copy( q );
  4603. }
  4604. rotateOnAxis( axis, angle ) {
  4605. // rotate object on axis in object space
  4606. // axis is assumed to be normalized
  4607. _q1.setFromAxisAngle( axis, angle );
  4608. this.quaternion.multiply( _q1 );
  4609. return this;
  4610. }
  4611. rotateOnWorldAxis( axis, angle ) {
  4612. // rotate object on axis in world space
  4613. // axis is assumed to be normalized
  4614. // method assumes no rotated parent
  4615. _q1.setFromAxisAngle( axis, angle );
  4616. this.quaternion.premultiply( _q1 );
  4617. return this;
  4618. }
  4619. rotateX( angle ) {
  4620. return this.rotateOnAxis( _xAxis, angle );
  4621. }
  4622. rotateY( angle ) {
  4623. return this.rotateOnAxis( _yAxis, angle );
  4624. }
  4625. rotateZ( angle ) {
  4626. return this.rotateOnAxis( _zAxis, angle );
  4627. }
  4628. translateOnAxis( axis, distance ) {
  4629. // translate object by distance along axis in object space
  4630. // axis is assumed to be normalized
  4631. _v1$4.copy( axis ).applyQuaternion( this.quaternion );
  4632. this.position.add( _v1$4.multiplyScalar( distance ) );
  4633. return this;
  4634. }
  4635. translateX( distance ) {
  4636. return this.translateOnAxis( _xAxis, distance );
  4637. }
  4638. translateY( distance ) {
  4639. return this.translateOnAxis( _yAxis, distance );
  4640. }
  4641. translateZ( distance ) {
  4642. return this.translateOnAxis( _zAxis, distance );
  4643. }
  4644. localToWorld( vector ) {
  4645. this.updateWorldMatrix( true, false );
  4646. return vector.applyMatrix4( this.matrixWorld );
  4647. }
  4648. worldToLocal( vector ) {
  4649. this.updateWorldMatrix( true, false );
  4650. return vector.applyMatrix4( _m1$1.copy( this.matrixWorld ).invert() );
  4651. }
  4652. lookAt( x, y, z ) {
  4653. // This method does not support objects having non-uniformly-scaled parent(s)
  4654. if ( x.isVector3 ) {
  4655. _target.copy( x );
  4656. } else {
  4657. _target.set( x, y, z );
  4658. }
  4659. const parent = this.parent;
  4660. this.updateWorldMatrix( true, false );
  4661. _position$3.setFromMatrixPosition( this.matrixWorld );
  4662. if ( this.isCamera || this.isLight ) {
  4663. _m1$1.lookAt( _position$3, _target, this.up );
  4664. } else {
  4665. _m1$1.lookAt( _target, _position$3, this.up );
  4666. }
  4667. this.quaternion.setFromRotationMatrix( _m1$1 );
  4668. if ( parent ) {
  4669. _m1$1.extractRotation( parent.matrixWorld );
  4670. _q1.setFromRotationMatrix( _m1$1 );
  4671. this.quaternion.premultiply( _q1.invert() );
  4672. }
  4673. }
  4674. add( object ) {
  4675. if ( arguments.length > 1 ) {
  4676. for ( let i = 0; i < arguments.length; i ++ ) {
  4677. this.add( arguments[ i ] );
  4678. }
  4679. return this;
  4680. }
  4681. if ( object === this ) {
  4682. console.error( 'THREE.Object3D.add: object can\'t be added as a child of itself.', object );
  4683. return this;
  4684. }
  4685. if ( object && object.isObject3D ) {
  4686. if ( object.parent !== null ) {
  4687. object.parent.remove( object );
  4688. }
  4689. object.parent = this;
  4690. this.children.push( object );
  4691. object.dispatchEvent( _addedEvent );
  4692. } else {
  4693. console.error( 'THREE.Object3D.add: object not an instance of THREE.Object3D.', object );
  4694. }
  4695. return this;
  4696. }
  4697. remove( object ) {
  4698. if ( arguments.length > 1 ) {
  4699. for ( let i = 0; i < arguments.length; i ++ ) {
  4700. this.remove( arguments[ i ] );
  4701. }
  4702. return this;
  4703. }
  4704. const index = this.children.indexOf( object );
  4705. if ( index !== - 1 ) {
  4706. object.parent = null;
  4707. this.children.splice( index, 1 );
  4708. object.dispatchEvent( _removedEvent );
  4709. }
  4710. return this;
  4711. }
  4712. removeFromParent() {
  4713. const parent = this.parent;
  4714. if ( parent !== null ) {
  4715. parent.remove( this );
  4716. }
  4717. return this;
  4718. }
  4719. clear() {
  4720. for ( let i = 0; i < this.children.length; i ++ ) {
  4721. const object = this.children[ i ];
  4722. object.parent = null;
  4723. object.dispatchEvent( _removedEvent );
  4724. }
  4725. this.children.length = 0;
  4726. return this;
  4727. }
  4728. attach( object ) {
  4729. // adds object as a child of this, while maintaining the object's world transform
  4730. // Note: This method does not support scene graphs having non-uniformly-scaled nodes(s)
  4731. this.updateWorldMatrix( true, false );
  4732. _m1$1.copy( this.matrixWorld ).invert();
  4733. if ( object.parent !== null ) {
  4734. object.parent.updateWorldMatrix( true, false );
  4735. _m1$1.multiply( object.parent.matrixWorld );
  4736. }
  4737. object.applyMatrix4( _m1$1 );
  4738. this.add( object );
  4739. object.updateWorldMatrix( false, true );
  4740. return this;
  4741. }
  4742. getObjectById( id ) {
  4743. return this.getObjectByProperty( 'id', id );
  4744. }
  4745. getObjectByName( name ) {
  4746. return this.getObjectByProperty( 'name', name );
  4747. }
  4748. getObjectByProperty( name, value ) {
  4749. if ( this[ name ] === value ) return this;
  4750. for ( let i = 0, l = this.children.length; i < l; i ++ ) {
  4751. const child = this.children[ i ];
  4752. const object = child.getObjectByProperty( name, value );
  4753. if ( object !== undefined ) {
  4754. return object;
  4755. }
  4756. }
  4757. return undefined;
  4758. }
  4759. getObjectsByProperty( name, value ) {
  4760. let result = [];
  4761. if ( this[ name ] === value ) result.push( this );
  4762. for ( let i = 0, l = this.children.length; i < l; i ++ ) {
  4763. const childResult = this.children[ i ].getObjectsByProperty( name, value );
  4764. if ( childResult.length > 0 ) {
  4765. result = result.concat( childResult );
  4766. }
  4767. }
  4768. return result;
  4769. }
  4770. getWorldPosition( target ) {
  4771. this.updateWorldMatrix( true, false );
  4772. return target.setFromMatrixPosition( this.matrixWorld );
  4773. }
  4774. getWorldQuaternion( target ) {
  4775. this.updateWorldMatrix( true, false );
  4776. this.matrixWorld.decompose( _position$3, target, _scale$2 );
  4777. return target;
  4778. }
  4779. getWorldScale( target ) {
  4780. this.updateWorldMatrix( true, false );
  4781. this.matrixWorld.decompose( _position$3, _quaternion$2, target );
  4782. return target;
  4783. }
  4784. getWorldDirection( target ) {
  4785. this.updateWorldMatrix( true, false );
  4786. const e = this.matrixWorld.elements;
  4787. return target.set( e[ 8 ], e[ 9 ], e[ 10 ] ).normalize();
  4788. }
  4789. raycast( /* raycaster, intersects */ ) {}
  4790. traverse( callback ) {
  4791. callback( this );
  4792. const children = this.children;
  4793. for ( let i = 0, l = children.length; i < l; i ++ ) {
  4794. children[ i ].traverse( callback );
  4795. }
  4796. }
  4797. traverseVisible( callback ) {
  4798. if ( this.visible === false ) return;
  4799. callback( this );
  4800. const children = this.children;
  4801. for ( let i = 0, l = children.length; i < l; i ++ ) {
  4802. children[ i ].traverseVisible( callback );
  4803. }
  4804. }
  4805. traverseAncestors( callback ) {
  4806. const parent = this.parent;
  4807. if ( parent !== null ) {
  4808. callback( parent );
  4809. parent.traverseAncestors( callback );
  4810. }
  4811. }
  4812. updateMatrix() {
  4813. this.matrix.compose( this.position, this.quaternion, this.scale );
  4814. this.matrixWorldNeedsUpdate = true;
  4815. }
  4816. updateMatrixWorld( force ) {
  4817. if ( this.matrixAutoUpdate ) this.updateMatrix();
  4818. if ( this.matrixWorldNeedsUpdate || force ) {
  4819. if ( this.parent === null ) {
  4820. this.matrixWorld.copy( this.matrix );
  4821. } else {
  4822. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  4823. }
  4824. this.matrixWorldNeedsUpdate = false;
  4825. force = true;
  4826. }
  4827. // update children
  4828. const children = this.children;
  4829. for ( let i = 0, l = children.length; i < l; i ++ ) {
  4830. const child = children[ i ];
  4831. if ( child.matrixWorldAutoUpdate === true || force === true ) {
  4832. child.updateMatrixWorld( force );
  4833. }
  4834. }
  4835. }
  4836. updateWorldMatrix( updateParents, updateChildren ) {
  4837. const parent = this.parent;
  4838. if ( updateParents === true && parent !== null && parent.matrixWorldAutoUpdate === true ) {
  4839. parent.updateWorldMatrix( true, false );
  4840. }
  4841. if ( this.matrixAutoUpdate ) this.updateMatrix();
  4842. if ( this.parent === null ) {
  4843. this.matrixWorld.copy( this.matrix );
  4844. } else {
  4845. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  4846. }
  4847. // update children
  4848. if ( updateChildren === true ) {
  4849. const children = this.children;
  4850. for ( let i = 0, l = children.length; i < l; i ++ ) {
  4851. const child = children[ i ];
  4852. if ( child.matrixWorldAutoUpdate === true ) {
  4853. child.updateWorldMatrix( false, true );
  4854. }
  4855. }
  4856. }
  4857. }
  4858. toJSON( meta ) {
  4859. // meta is a string when called from JSON.stringify
  4860. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  4861. const output = {};
  4862. // meta is a hash used to collect geometries, materials.
  4863. // not providing it implies that this is the root object
  4864. // being serialized.
  4865. if ( isRootObject ) {
  4866. // initialize meta obj
  4867. meta = {
  4868. geometries: {},
  4869. materials: {},
  4870. textures: {},
  4871. images: {},
  4872. shapes: {},
  4873. skeletons: {},
  4874. animations: {},
  4875. nodes: {}
  4876. };
  4877. output.metadata = {
  4878. version: 4.5,
  4879. type: 'Object',
  4880. generator: 'Object3D.toJSON'
  4881. };
  4882. }
  4883. // standard Object3D serialization
  4884. const object = {};
  4885. object.uuid = this.uuid;
  4886. object.type = this.type;
  4887. if ( this.name !== '' ) object.name = this.name;
  4888. if ( this.castShadow === true ) object.castShadow = true;
  4889. if ( this.receiveShadow === true ) object.receiveShadow = true;
  4890. if ( this.visible === false ) object.visible = false;
  4891. if ( this.frustumCulled === false ) object.frustumCulled = false;
  4892. if ( this.renderOrder !== 0 ) object.renderOrder = this.renderOrder;
  4893. if ( Object.keys( this.userData ).length > 0 ) object.userData = this.userData;
  4894. object.layers = this.layers.mask;
  4895. object.matrix = this.matrix.toArray();
  4896. if ( this.matrixAutoUpdate === false ) object.matrixAutoUpdate = false;
  4897. // object specific properties
  4898. if ( this.isInstancedMesh ) {
  4899. object.type = 'InstancedMesh';
  4900. object.count = this.count;
  4901. object.instanceMatrix = this.instanceMatrix.toJSON();
  4902. if ( this.instanceColor !== null ) object.instanceColor = this.instanceColor.toJSON();
  4903. }
  4904. //
  4905. function serialize( library, element ) {
  4906. if ( library[ element.uuid ] === undefined ) {
  4907. library[ element.uuid ] = element.toJSON( meta );
  4908. }
  4909. return element.uuid;
  4910. }
  4911. if ( this.isScene ) {
  4912. if ( this.background ) {
  4913. if ( this.background.isColor ) {
  4914. object.background = this.background.toJSON();
  4915. } else if ( this.background.isTexture ) {
  4916. object.background = this.background.toJSON( meta ).uuid;
  4917. }
  4918. }
  4919. if ( this.environment && this.environment.isTexture && this.environment.isRenderTargetTexture !== true ) {
  4920. object.environment = this.environment.toJSON( meta ).uuid;
  4921. }
  4922. } else if ( this.isMesh || this.isLine || this.isPoints ) {
  4923. object.geometry = serialize( meta.geometries, this.geometry );
  4924. const parameters = this.geometry.parameters;
  4925. if ( parameters !== undefined && parameters.shapes !== undefined ) {
  4926. const shapes = parameters.shapes;
  4927. if ( Array.isArray( shapes ) ) {
  4928. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  4929. const shape = shapes[ i ];
  4930. serialize( meta.shapes, shape );
  4931. }
  4932. } else {
  4933. serialize( meta.shapes, shapes );
  4934. }
  4935. }
  4936. }
  4937. if ( this.isSkinnedMesh ) {
  4938. object.bindMode = this.bindMode;
  4939. object.bindMatrix = this.bindMatrix.toArray();
  4940. if ( this.skeleton !== undefined ) {
  4941. serialize( meta.skeletons, this.skeleton );
  4942. object.skeleton = this.skeleton.uuid;
  4943. }
  4944. }
  4945. if ( this.material !== undefined ) {
  4946. if ( Array.isArray( this.material ) ) {
  4947. const uuids = [];
  4948. for ( let i = 0, l = this.material.length; i < l; i ++ ) {
  4949. uuids.push( serialize( meta.materials, this.material[ i ] ) );
  4950. }
  4951. object.material = uuids;
  4952. } else {
  4953. object.material = serialize( meta.materials, this.material );
  4954. }
  4955. }
  4956. //
  4957. if ( this.children.length > 0 ) {
  4958. object.children = [];
  4959. for ( let i = 0; i < this.children.length; i ++ ) {
  4960. object.children.push( this.children[ i ].toJSON( meta ).object );
  4961. }
  4962. }
  4963. //
  4964. if ( this.animations.length > 0 ) {
  4965. object.animations = [];
  4966. for ( let i = 0; i < this.animations.length; i ++ ) {
  4967. const animation = this.animations[ i ];
  4968. object.animations.push( serialize( meta.animations, animation ) );
  4969. }
  4970. }
  4971. if ( isRootObject ) {
  4972. const geometries = extractFromCache( meta.geometries );
  4973. const materials = extractFromCache( meta.materials );
  4974. const textures = extractFromCache( meta.textures );
  4975. const images = extractFromCache( meta.images );
  4976. const shapes = extractFromCache( meta.shapes );
  4977. const skeletons = extractFromCache( meta.skeletons );
  4978. const animations = extractFromCache( meta.animations );
  4979. const nodes = extractFromCache( meta.nodes );
  4980. if ( geometries.length > 0 ) output.geometries = geometries;
  4981. if ( materials.length > 0 ) output.materials = materials;
  4982. if ( textures.length > 0 ) output.textures = textures;
  4983. if ( images.length > 0 ) output.images = images;
  4984. if ( shapes.length > 0 ) output.shapes = shapes;
  4985. if ( skeletons.length > 0 ) output.skeletons = skeletons;
  4986. if ( animations.length > 0 ) output.animations = animations;
  4987. if ( nodes.length > 0 ) output.nodes = nodes;
  4988. }
  4989. output.object = object;
  4990. return output;
  4991. // extract data from the cache hash
  4992. // remove metadata on each item
  4993. // and return as array
  4994. function extractFromCache( cache ) {
  4995. const values = [];
  4996. for ( const key in cache ) {
  4997. const data = cache[ key ];
  4998. delete data.metadata;
  4999. values.push( data );
  5000. }
  5001. return values;
  5002. }
  5003. }
  5004. clone( recursive ) {
  5005. return new this.constructor().copy( this, recursive );
  5006. }
  5007. copy( source, recursive = true ) {
  5008. this.name = source.name;
  5009. this.up.copy( source.up );
  5010. this.position.copy( source.position );
  5011. this.rotation.order = source.rotation.order;
  5012. this.quaternion.copy( source.quaternion );
  5013. this.scale.copy( source.scale );
  5014. this.matrix.copy( source.matrix );
  5015. this.matrixWorld.copy( source.matrixWorld );
  5016. this.matrixAutoUpdate = source.matrixAutoUpdate;
  5017. this.matrixWorldNeedsUpdate = source.matrixWorldNeedsUpdate;
  5018. this.matrixWorldAutoUpdate = source.matrixWorldAutoUpdate;
  5019. this.layers.mask = source.layers.mask;
  5020. this.visible = source.visible;
  5021. this.castShadow = source.castShadow;
  5022. this.receiveShadow = source.receiveShadow;
  5023. this.frustumCulled = source.frustumCulled;
  5024. this.renderOrder = source.renderOrder;
  5025. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  5026. if ( recursive === true ) {
  5027. for ( let i = 0; i < source.children.length; i ++ ) {
  5028. const child = source.children[ i ];
  5029. this.add( child.clone() );
  5030. }
  5031. }
  5032. return this;
  5033. }
  5034. }
  5035. Object3D.DEFAULT_UP = /*@__PURE__*/ new Vector3( 0, 1, 0 );
  5036. Object3D.DEFAULT_MATRIX_AUTO_UPDATE = true;
  5037. Object3D.DEFAULT_MATRIX_WORLD_AUTO_UPDATE = true;
  5038. const _v0$1 = /*@__PURE__*/ new Vector3();
  5039. const _v1$3 = /*@__PURE__*/ new Vector3();
  5040. const _v2$2 = /*@__PURE__*/ new Vector3();
  5041. const _v3$1 = /*@__PURE__*/ new Vector3();
  5042. const _vab = /*@__PURE__*/ new Vector3();
  5043. const _vac = /*@__PURE__*/ new Vector3();
  5044. const _vbc = /*@__PURE__*/ new Vector3();
  5045. const _vap = /*@__PURE__*/ new Vector3();
  5046. const _vbp = /*@__PURE__*/ new Vector3();
  5047. const _vcp = /*@__PURE__*/ new Vector3();
  5048. class Triangle {
  5049. constructor( a = new Vector3(), b = new Vector3(), c = new Vector3() ) {
  5050. this.a = a;
  5051. this.b = b;
  5052. this.c = c;
  5053. }
  5054. static getNormal( a, b, c, target ) {
  5055. target.subVectors( c, b );
  5056. _v0$1.subVectors( a, b );
  5057. target.cross( _v0$1 );
  5058. const targetLengthSq = target.lengthSq();
  5059. if ( targetLengthSq > 0 ) {
  5060. return target.multiplyScalar( 1 / Math.sqrt( targetLengthSq ) );
  5061. }
  5062. return target.set( 0, 0, 0 );
  5063. }
  5064. // static/instance method to calculate barycentric coordinates
  5065. // based on: http://www.blackpawn.com/texts/pointinpoly/default.html
  5066. static getBarycoord( point, a, b, c, target ) {
  5067. _v0$1.subVectors( c, a );
  5068. _v1$3.subVectors( b, a );
  5069. _v2$2.subVectors( point, a );
  5070. const dot00 = _v0$1.dot( _v0$1 );
  5071. const dot01 = _v0$1.dot( _v1$3 );
  5072. const dot02 = _v0$1.dot( _v2$2 );
  5073. const dot11 = _v1$3.dot( _v1$3 );
  5074. const dot12 = _v1$3.dot( _v2$2 );
  5075. const denom = ( dot00 * dot11 - dot01 * dot01 );
  5076. // collinear or singular triangle
  5077. if ( denom === 0 ) {
  5078. // arbitrary location outside of triangle?
  5079. // not sure if this is the best idea, maybe should be returning undefined
  5080. return target.set( - 2, - 1, - 1 );
  5081. }
  5082. const invDenom = 1 / denom;
  5083. const u = ( dot11 * dot02 - dot01 * dot12 ) * invDenom;
  5084. const v = ( dot00 * dot12 - dot01 * dot02 ) * invDenom;
  5085. // barycentric coordinates must always sum to 1
  5086. return target.set( 1 - u - v, v, u );
  5087. }
  5088. static containsPoint( point, a, b, c ) {
  5089. this.getBarycoord( point, a, b, c, _v3$1 );
  5090. return ( _v3$1.x >= 0 ) && ( _v3$1.y >= 0 ) && ( ( _v3$1.x + _v3$1.y ) <= 1 );
  5091. }
  5092. static getUV( point, p1, p2, p3, uv1, uv2, uv3, target ) {
  5093. this.getBarycoord( point, p1, p2, p3, _v3$1 );
  5094. target.set( 0, 0 );
  5095. target.addScaledVector( uv1, _v3$1.x );
  5096. target.addScaledVector( uv2, _v3$1.y );
  5097. target.addScaledVector( uv3, _v3$1.z );
  5098. return target;
  5099. }
  5100. static isFrontFacing( a, b, c, direction ) {
  5101. _v0$1.subVectors( c, b );
  5102. _v1$3.subVectors( a, b );
  5103. // strictly front facing
  5104. return ( _v0$1.cross( _v1$3 ).dot( direction ) < 0 ) ? true : false;
  5105. }
  5106. set( a, b, c ) {
  5107. this.a.copy( a );
  5108. this.b.copy( b );
  5109. this.c.copy( c );
  5110. return this;
  5111. }
  5112. setFromPointsAndIndices( points, i0, i1, i2 ) {
  5113. this.a.copy( points[ i0 ] );
  5114. this.b.copy( points[ i1 ] );
  5115. this.c.copy( points[ i2 ] );
  5116. return this;
  5117. }
  5118. setFromAttributeAndIndices( attribute, i0, i1, i2 ) {
  5119. this.a.fromBufferAttribute( attribute, i0 );
  5120. this.b.fromBufferAttribute( attribute, i1 );
  5121. this.c.fromBufferAttribute( attribute, i2 );
  5122. return this;
  5123. }
  5124. clone() {
  5125. return new this.constructor().copy( this );
  5126. }
  5127. copy( triangle ) {
  5128. this.a.copy( triangle.a );
  5129. this.b.copy( triangle.b );
  5130. this.c.copy( triangle.c );
  5131. return this;
  5132. }
  5133. getArea() {
  5134. _v0$1.subVectors( this.c, this.b );
  5135. _v1$3.subVectors( this.a, this.b );
  5136. return _v0$1.cross( _v1$3 ).length() * 0.5;
  5137. }
  5138. getMidpoint( target ) {
  5139. return target.addVectors( this.a, this.b ).add( this.c ).multiplyScalar( 1 / 3 );
  5140. }
  5141. getNormal( target ) {
  5142. return Triangle.getNormal( this.a, this.b, this.c, target );
  5143. }
  5144. getPlane( target ) {
  5145. return target.setFromCoplanarPoints( this.a, this.b, this.c );
  5146. }
  5147. getBarycoord( point, target ) {
  5148. return Triangle.getBarycoord( point, this.a, this.b, this.c, target );
  5149. }
  5150. getUV( point, uv1, uv2, uv3, target ) {
  5151. return Triangle.getUV( point, this.a, this.b, this.c, uv1, uv2, uv3, target );
  5152. }
  5153. containsPoint( point ) {
  5154. return Triangle.containsPoint( point, this.a, this.b, this.c );
  5155. }
  5156. isFrontFacing( direction ) {
  5157. return Triangle.isFrontFacing( this.a, this.b, this.c, direction );
  5158. }
  5159. intersectsBox( box ) {
  5160. return box.intersectsTriangle( this );
  5161. }
  5162. closestPointToPoint( p, target ) {
  5163. const a = this.a, b = this.b, c = this.c;
  5164. let v, w;
  5165. // algorithm thanks to Real-Time Collision Detection by Christer Ericson,
  5166. // published by Morgan Kaufmann Publishers, (c) 2005 Elsevier Inc.,
  5167. // under the accompanying license; see chapter 5.1.5 for detailed explanation.
  5168. // basically, we're distinguishing which of the voronoi regions of the triangle
  5169. // the point lies in with the minimum amount of redundant computation.
  5170. _vab.subVectors( b, a );
  5171. _vac.subVectors( c, a );
  5172. _vap.subVectors( p, a );
  5173. const d1 = _vab.dot( _vap );
  5174. const d2 = _vac.dot( _vap );
  5175. if ( d1 <= 0 && d2 <= 0 ) {
  5176. // vertex region of A; barycentric coords (1, 0, 0)
  5177. return target.copy( a );
  5178. }
  5179. _vbp.subVectors( p, b );
  5180. const d3 = _vab.dot( _vbp );
  5181. const d4 = _vac.dot( _vbp );
  5182. if ( d3 >= 0 && d4 <= d3 ) {
  5183. // vertex region of B; barycentric coords (0, 1, 0)
  5184. return target.copy( b );
  5185. }
  5186. const vc = d1 * d4 - d3 * d2;
  5187. if ( vc <= 0 && d1 >= 0 && d3 <= 0 ) {
  5188. v = d1 / ( d1 - d3 );
  5189. // edge region of AB; barycentric coords (1-v, v, 0)
  5190. return target.copy( a ).addScaledVector( _vab, v );
  5191. }
  5192. _vcp.subVectors( p, c );
  5193. const d5 = _vab.dot( _vcp );
  5194. const d6 = _vac.dot( _vcp );
  5195. if ( d6 >= 0 && d5 <= d6 ) {
  5196. // vertex region of C; barycentric coords (0, 0, 1)
  5197. return target.copy( c );
  5198. }
  5199. const vb = d5 * d2 - d1 * d6;
  5200. if ( vb <= 0 && d2 >= 0 && d6 <= 0 ) {
  5201. w = d2 / ( d2 - d6 );
  5202. // edge region of AC; barycentric coords (1-w, 0, w)
  5203. return target.copy( a ).addScaledVector( _vac, w );
  5204. }
  5205. const va = d3 * d6 - d5 * d4;
  5206. if ( va <= 0 && ( d4 - d3 ) >= 0 && ( d5 - d6 ) >= 0 ) {
  5207. _vbc.subVectors( c, b );
  5208. w = ( d4 - d3 ) / ( ( d4 - d3 ) + ( d5 - d6 ) );
  5209. // edge region of BC; barycentric coords (0, 1-w, w)
  5210. return target.copy( b ).addScaledVector( _vbc, w ); // edge region of BC
  5211. }
  5212. // face region
  5213. const denom = 1 / ( va + vb + vc );
  5214. // u = va * denom
  5215. v = vb * denom;
  5216. w = vc * denom;
  5217. return target.copy( a ).addScaledVector( _vab, v ).addScaledVector( _vac, w );
  5218. }
  5219. equals( triangle ) {
  5220. return triangle.a.equals( this.a ) && triangle.b.equals( this.b ) && triangle.c.equals( this.c );
  5221. }
  5222. }
  5223. let materialId = 0;
  5224. class Material extends EventDispatcher {
  5225. constructor() {
  5226. super();
  5227. this.isMaterial = true;
  5228. Object.defineProperty( this, 'id', { value: materialId ++ } );
  5229. this.uuid = generateUUID();
  5230. this.name = '';
  5231. this.type = 'Material';
  5232. this.blending = NormalBlending;
  5233. this.side = FrontSide;
  5234. this.vertexColors = false;
  5235. this.opacity = 1;
  5236. this.transparent = false;
  5237. this.blendSrc = SrcAlphaFactor;
  5238. this.blendDst = OneMinusSrcAlphaFactor;
  5239. this.blendEquation = AddEquation;
  5240. this.blendSrcAlpha = null;
  5241. this.blendDstAlpha = null;
  5242. this.blendEquationAlpha = null;
  5243. this.depthFunc = LessEqualDepth;
  5244. this.depthTest = true;
  5245. this.depthWrite = true;
  5246. this.stencilWriteMask = 0xff;
  5247. this.stencilFunc = AlwaysStencilFunc;
  5248. this.stencilRef = 0;
  5249. this.stencilFuncMask = 0xff;
  5250. this.stencilFail = KeepStencilOp;
  5251. this.stencilZFail = KeepStencilOp;
  5252. this.stencilZPass = KeepStencilOp;
  5253. this.stencilWrite = false;
  5254. this.clippingPlanes = null;
  5255. this.clipIntersection = false;
  5256. this.clipShadows = false;
  5257. this.shadowSide = null;
  5258. this.colorWrite = true;
  5259. this.precision = null; // override the renderer's default precision for this material
  5260. this.polygonOffset = false;
  5261. this.polygonOffsetFactor = 0;
  5262. this.polygonOffsetUnits = 0;
  5263. this.dithering = false;
  5264. this.alphaToCoverage = false;
  5265. this.premultipliedAlpha = false;
  5266. this.forceSinglePass = false;
  5267. this.visible = true;
  5268. this.toneMapped = true;
  5269. this.userData = {};
  5270. this.version = 0;
  5271. this._alphaTest = 0;
  5272. }
  5273. get alphaTest() {
  5274. return this._alphaTest;
  5275. }
  5276. set alphaTest( value ) {
  5277. if ( this._alphaTest > 0 !== value > 0 ) {
  5278. this.version ++;
  5279. }
  5280. this._alphaTest = value;
  5281. }
  5282. onBuild( /* shaderobject, renderer */ ) {}
  5283. onBeforeRender( /* renderer, scene, camera, geometry, object, group */ ) {}
  5284. onBeforeCompile( /* shaderobject, renderer */ ) {}
  5285. customProgramCacheKey() {
  5286. return this.onBeforeCompile.toString();
  5287. }
  5288. setValues( values ) {
  5289. if ( values === undefined ) return;
  5290. for ( const key in values ) {
  5291. const newValue = values[ key ];
  5292. if ( newValue === undefined ) {
  5293. console.warn( 'THREE.Material: \'' + key + '\' parameter is undefined.' );
  5294. continue;
  5295. }
  5296. const currentValue = this[ key ];
  5297. if ( currentValue === undefined ) {
  5298. console.warn( 'THREE.' + this.type + ': \'' + key + '\' is not a property of this material.' );
  5299. continue;
  5300. }
  5301. if ( currentValue && currentValue.isColor ) {
  5302. currentValue.set( newValue );
  5303. } else if ( ( currentValue && currentValue.isVector3 ) && ( newValue && newValue.isVector3 ) ) {
  5304. currentValue.copy( newValue );
  5305. } else {
  5306. this[ key ] = newValue;
  5307. }
  5308. }
  5309. }
  5310. toJSON( meta ) {
  5311. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  5312. if ( isRootObject ) {
  5313. meta = {
  5314. textures: {},
  5315. images: {}
  5316. };
  5317. }
  5318. const data = {
  5319. metadata: {
  5320. version: 4.5,
  5321. type: 'Material',
  5322. generator: 'Material.toJSON'
  5323. }
  5324. };
  5325. // standard Material serialization
  5326. data.uuid = this.uuid;
  5327. data.type = this.type;
  5328. if ( this.name !== '' ) data.name = this.name;
  5329. if ( this.color && this.color.isColor ) data.color = this.color.getHex();
  5330. if ( this.roughness !== undefined ) data.roughness = this.roughness;
  5331. if ( this.metalness !== undefined ) data.metalness = this.metalness;
  5332. if ( this.sheen !== undefined ) data.sheen = this.sheen;
  5333. if ( this.sheenColor && this.sheenColor.isColor ) data.sheenColor = this.sheenColor.getHex();
  5334. if ( this.sheenRoughness !== undefined ) data.sheenRoughness = this.sheenRoughness;
  5335. if ( this.emissive && this.emissive.isColor ) data.emissive = this.emissive.getHex();
  5336. if ( this.emissiveIntensity && this.emissiveIntensity !== 1 ) data.emissiveIntensity = this.emissiveIntensity;
  5337. if ( this.specular && this.specular.isColor ) data.specular = this.specular.getHex();
  5338. if ( this.specularIntensity !== undefined ) data.specularIntensity = this.specularIntensity;
  5339. if ( this.specularColor && this.specularColor.isColor ) data.specularColor = this.specularColor.getHex();
  5340. if ( this.shininess !== undefined ) data.shininess = this.shininess;
  5341. if ( this.clearcoat !== undefined ) data.clearcoat = this.clearcoat;
  5342. if ( this.clearcoatRoughness !== undefined ) data.clearcoatRoughness = this.clearcoatRoughness;
  5343. if ( this.clearcoatMap && this.clearcoatMap.isTexture ) {
  5344. data.clearcoatMap = this.clearcoatMap.toJSON( meta ).uuid;
  5345. }
  5346. if ( this.clearcoatRoughnessMap && this.clearcoatRoughnessMap.isTexture ) {
  5347. data.clearcoatRoughnessMap = this.clearcoatRoughnessMap.toJSON( meta ).uuid;
  5348. }
  5349. if ( this.clearcoatNormalMap && this.clearcoatNormalMap.isTexture ) {
  5350. data.clearcoatNormalMap = this.clearcoatNormalMap.toJSON( meta ).uuid;
  5351. data.clearcoatNormalScale = this.clearcoatNormalScale.toArray();
  5352. }
  5353. if ( this.iridescence !== undefined ) data.iridescence = this.iridescence;
  5354. if ( this.iridescenceIOR !== undefined ) data.iridescenceIOR = this.iridescenceIOR;
  5355. if ( this.iridescenceThicknessRange !== undefined ) data.iridescenceThicknessRange = this.iridescenceThicknessRange;
  5356. if ( this.iridescenceMap && this.iridescenceMap.isTexture ) {
  5357. data.iridescenceMap = this.iridescenceMap.toJSON( meta ).uuid;
  5358. }
  5359. if ( this.iridescenceThicknessMap && this.iridescenceThicknessMap.isTexture ) {
  5360. data.iridescenceThicknessMap = this.iridescenceThicknessMap.toJSON( meta ).uuid;
  5361. }
  5362. if ( this.map && this.map.isTexture ) data.map = this.map.toJSON( meta ).uuid;
  5363. if ( this.matcap && this.matcap.isTexture ) data.matcap = this.matcap.toJSON( meta ).uuid;
  5364. if ( this.alphaMap && this.alphaMap.isTexture ) data.alphaMap = this.alphaMap.toJSON( meta ).uuid;
  5365. if ( this.lightMap && this.lightMap.isTexture ) {
  5366. data.lightMap = this.lightMap.toJSON( meta ).uuid;
  5367. data.lightMapIntensity = this.lightMapIntensity;
  5368. }
  5369. if ( this.aoMap && this.aoMap.isTexture ) {
  5370. data.aoMap = this.aoMap.toJSON( meta ).uuid;
  5371. data.aoMapIntensity = this.aoMapIntensity;
  5372. }
  5373. if ( this.bumpMap && this.bumpMap.isTexture ) {
  5374. data.bumpMap = this.bumpMap.toJSON( meta ).uuid;
  5375. data.bumpScale = this.bumpScale;
  5376. }
  5377. if ( this.normalMap && this.normalMap.isTexture ) {
  5378. data.normalMap = this.normalMap.toJSON( meta ).uuid;
  5379. data.normalMapType = this.normalMapType;
  5380. data.normalScale = this.normalScale.toArray();
  5381. }
  5382. if ( this.displacementMap && this.displacementMap.isTexture ) {
  5383. data.displacementMap = this.displacementMap.toJSON( meta ).uuid;
  5384. data.displacementScale = this.displacementScale;
  5385. data.displacementBias = this.displacementBias;
  5386. }
  5387. if ( this.roughnessMap && this.roughnessMap.isTexture ) data.roughnessMap = this.roughnessMap.toJSON( meta ).uuid;
  5388. if ( this.metalnessMap && this.metalnessMap.isTexture ) data.metalnessMap = this.metalnessMap.toJSON( meta ).uuid;
  5389. if ( this.emissiveMap && this.emissiveMap.isTexture ) data.emissiveMap = this.emissiveMap.toJSON( meta ).uuid;
  5390. if ( this.specularMap && this.specularMap.isTexture ) data.specularMap = this.specularMap.toJSON( meta ).uuid;
  5391. if ( this.specularIntensityMap && this.specularIntensityMap.isTexture ) data.specularIntensityMap = this.specularIntensityMap.toJSON( meta ).uuid;
  5392. if ( this.specularColorMap && this.specularColorMap.isTexture ) data.specularColorMap = this.specularColorMap.toJSON( meta ).uuid;
  5393. if ( this.envMap && this.envMap.isTexture ) {
  5394. data.envMap = this.envMap.toJSON( meta ).uuid;
  5395. if ( this.combine !== undefined ) data.combine = this.combine;
  5396. }
  5397. if ( this.envMapIntensity !== undefined ) data.envMapIntensity = this.envMapIntensity;
  5398. if ( this.reflectivity !== undefined ) data.reflectivity = this.reflectivity;
  5399. if ( this.refractionRatio !== undefined ) data.refractionRatio = this.refractionRatio;
  5400. if ( this.gradientMap && this.gradientMap.isTexture ) {
  5401. data.gradientMap = this.gradientMap.toJSON( meta ).uuid;
  5402. }
  5403. if ( this.transmission !== undefined ) data.transmission = this.transmission;
  5404. if ( this.transmissionMap && this.transmissionMap.isTexture ) data.transmissionMap = this.transmissionMap.toJSON( meta ).uuid;
  5405. if ( this.thickness !== undefined ) data.thickness = this.thickness;
  5406. if ( this.thicknessMap && this.thicknessMap.isTexture ) data.thicknessMap = this.thicknessMap.toJSON( meta ).uuid;
  5407. if ( this.attenuationDistance !== undefined && this.attenuationDistance !== Infinity ) data.attenuationDistance = this.attenuationDistance;
  5408. if ( this.attenuationColor !== undefined ) data.attenuationColor = this.attenuationColor.getHex();
  5409. if ( this.size !== undefined ) data.size = this.size;
  5410. if ( this.shadowSide !== null ) data.shadowSide = this.shadowSide;
  5411. if ( this.sizeAttenuation !== undefined ) data.sizeAttenuation = this.sizeAttenuation;
  5412. if ( this.blending !== NormalBlending ) data.blending = this.blending;
  5413. if ( this.side !== FrontSide ) data.side = this.side;
  5414. if ( this.vertexColors ) data.vertexColors = true;
  5415. if ( this.opacity < 1 ) data.opacity = this.opacity;
  5416. if ( this.transparent === true ) data.transparent = this.transparent;
  5417. data.depthFunc = this.depthFunc;
  5418. data.depthTest = this.depthTest;
  5419. data.depthWrite = this.depthWrite;
  5420. data.colorWrite = this.colorWrite;
  5421. data.stencilWrite = this.stencilWrite;
  5422. data.stencilWriteMask = this.stencilWriteMask;
  5423. data.stencilFunc = this.stencilFunc;
  5424. data.stencilRef = this.stencilRef;
  5425. data.stencilFuncMask = this.stencilFuncMask;
  5426. data.stencilFail = this.stencilFail;
  5427. data.stencilZFail = this.stencilZFail;
  5428. data.stencilZPass = this.stencilZPass;
  5429. // rotation (SpriteMaterial)
  5430. if ( this.rotation !== undefined && this.rotation !== 0 ) data.rotation = this.rotation;
  5431. if ( this.polygonOffset === true ) data.polygonOffset = true;
  5432. if ( this.polygonOffsetFactor !== 0 ) data.polygonOffsetFactor = this.polygonOffsetFactor;
  5433. if ( this.polygonOffsetUnits !== 0 ) data.polygonOffsetUnits = this.polygonOffsetUnits;
  5434. if ( this.linewidth !== undefined && this.linewidth !== 1 ) data.linewidth = this.linewidth;
  5435. if ( this.dashSize !== undefined ) data.dashSize = this.dashSize;
  5436. if ( this.gapSize !== undefined ) data.gapSize = this.gapSize;
  5437. if ( this.scale !== undefined ) data.scale = this.scale;
  5438. if ( this.dithering === true ) data.dithering = true;
  5439. if ( this.alphaTest > 0 ) data.alphaTest = this.alphaTest;
  5440. if ( this.alphaToCoverage === true ) data.alphaToCoverage = this.alphaToCoverage;
  5441. if ( this.premultipliedAlpha === true ) data.premultipliedAlpha = this.premultipliedAlpha;
  5442. if ( this.forceSinglePass === true ) data.forceSinglePass = this.forceSinglePass;
  5443. if ( this.wireframe === true ) data.wireframe = this.wireframe;
  5444. if ( this.wireframeLinewidth > 1 ) data.wireframeLinewidth = this.wireframeLinewidth;
  5445. if ( this.wireframeLinecap !== 'round' ) data.wireframeLinecap = this.wireframeLinecap;
  5446. if ( this.wireframeLinejoin !== 'round' ) data.wireframeLinejoin = this.wireframeLinejoin;
  5447. if ( this.flatShading === true ) data.flatShading = this.flatShading;
  5448. if ( this.visible === false ) data.visible = false;
  5449. if ( this.toneMapped === false ) data.toneMapped = false;
  5450. if ( this.fog === false ) data.fog = false;
  5451. if ( Object.keys( this.userData ).length > 0 ) data.userData = this.userData;
  5452. // TODO: Copied from Object3D.toJSON
  5453. function extractFromCache( cache ) {
  5454. const values = [];
  5455. for ( const key in cache ) {
  5456. const data = cache[ key ];
  5457. delete data.metadata;
  5458. values.push( data );
  5459. }
  5460. return values;
  5461. }
  5462. if ( isRootObject ) {
  5463. const textures = extractFromCache( meta.textures );
  5464. const images = extractFromCache( meta.images );
  5465. if ( textures.length > 0 ) data.textures = textures;
  5466. if ( images.length > 0 ) data.images = images;
  5467. }
  5468. return data;
  5469. }
  5470. clone() {
  5471. return new this.constructor().copy( this );
  5472. }
  5473. copy( source ) {
  5474. this.name = source.name;
  5475. this.blending = source.blending;
  5476. this.side = source.side;
  5477. this.vertexColors = source.vertexColors;
  5478. this.opacity = source.opacity;
  5479. this.transparent = source.transparent;
  5480. this.blendSrc = source.blendSrc;
  5481. this.blendDst = source.blendDst;
  5482. this.blendEquation = source.blendEquation;
  5483. this.blendSrcAlpha = source.blendSrcAlpha;
  5484. this.blendDstAlpha = source.blendDstAlpha;
  5485. this.blendEquationAlpha = source.blendEquationAlpha;
  5486. this.depthFunc = source.depthFunc;
  5487. this.depthTest = source.depthTest;
  5488. this.depthWrite = source.depthWrite;
  5489. this.stencilWriteMask = source.stencilWriteMask;
  5490. this.stencilFunc = source.stencilFunc;
  5491. this.stencilRef = source.stencilRef;
  5492. this.stencilFuncMask = source.stencilFuncMask;
  5493. this.stencilFail = source.stencilFail;
  5494. this.stencilZFail = source.stencilZFail;
  5495. this.stencilZPass = source.stencilZPass;
  5496. this.stencilWrite = source.stencilWrite;
  5497. const srcPlanes = source.clippingPlanes;
  5498. let dstPlanes = null;
  5499. if ( srcPlanes !== null ) {
  5500. const n = srcPlanes.length;
  5501. dstPlanes = new Array( n );
  5502. for ( let i = 0; i !== n; ++ i ) {
  5503. dstPlanes[ i ] = srcPlanes[ i ].clone();
  5504. }
  5505. }
  5506. this.clippingPlanes = dstPlanes;
  5507. this.clipIntersection = source.clipIntersection;
  5508. this.clipShadows = source.clipShadows;
  5509. this.shadowSide = source.shadowSide;
  5510. this.colorWrite = source.colorWrite;
  5511. this.precision = source.precision;
  5512. this.polygonOffset = source.polygonOffset;
  5513. this.polygonOffsetFactor = source.polygonOffsetFactor;
  5514. this.polygonOffsetUnits = source.polygonOffsetUnits;
  5515. this.dithering = source.dithering;
  5516. this.alphaTest = source.alphaTest;
  5517. this.alphaToCoverage = source.alphaToCoverage;
  5518. this.premultipliedAlpha = source.premultipliedAlpha;
  5519. this.forceSinglePass = source.forceSinglePass;
  5520. this.visible = source.visible;
  5521. this.toneMapped = source.toneMapped;
  5522. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  5523. return this;
  5524. }
  5525. dispose() {
  5526. this.dispatchEvent( { type: 'dispose' } );
  5527. }
  5528. set needsUpdate( value ) {
  5529. if ( value === true ) this.version ++;
  5530. }
  5531. }
  5532. class MeshBasicMaterial extends Material {
  5533. constructor( parameters ) {
  5534. super();
  5535. this.isMeshBasicMaterial = true;
  5536. this.type = 'MeshBasicMaterial';
  5537. this.color = new Color( 0xffffff ); // emissive
  5538. this.map = null;
  5539. this.lightMap = null;
  5540. this.lightMapIntensity = 1.0;
  5541. this.aoMap = null;
  5542. this.aoMapIntensity = 1.0;
  5543. this.specularMap = null;
  5544. this.alphaMap = null;
  5545. this.envMap = null;
  5546. this.combine = MultiplyOperation;
  5547. this.reflectivity = 1;
  5548. this.refractionRatio = 0.98;
  5549. this.wireframe = false;
  5550. this.wireframeLinewidth = 1;
  5551. this.wireframeLinecap = 'round';
  5552. this.wireframeLinejoin = 'round';
  5553. this.fog = true;
  5554. this.setValues( parameters );
  5555. }
  5556. copy( source ) {
  5557. super.copy( source );
  5558. this.color.copy( source.color );
  5559. this.map = source.map;
  5560. this.lightMap = source.lightMap;
  5561. this.lightMapIntensity = source.lightMapIntensity;
  5562. this.aoMap = source.aoMap;
  5563. this.aoMapIntensity = source.aoMapIntensity;
  5564. this.specularMap = source.specularMap;
  5565. this.alphaMap = source.alphaMap;
  5566. this.envMap = source.envMap;
  5567. this.combine = source.combine;
  5568. this.reflectivity = source.reflectivity;
  5569. this.refractionRatio = source.refractionRatio;
  5570. this.wireframe = source.wireframe;
  5571. this.wireframeLinewidth = source.wireframeLinewidth;
  5572. this.wireframeLinecap = source.wireframeLinecap;
  5573. this.wireframeLinejoin = source.wireframeLinejoin;
  5574. this.fog = source.fog;
  5575. return this;
  5576. }
  5577. }
  5578. const _vector$9 = /*@__PURE__*/ new Vector3();
  5579. const _vector2$1 = /*@__PURE__*/ new Vector2();
  5580. class BufferAttribute {
  5581. constructor( array, itemSize, normalized = false ) {
  5582. if ( Array.isArray( array ) ) {
  5583. throw new TypeError( 'THREE.BufferAttribute: array should be a Typed Array.' );
  5584. }
  5585. this.isBufferAttribute = true;
  5586. this.name = '';
  5587. this.array = array;
  5588. this.itemSize = itemSize;
  5589. this.count = array !== undefined ? array.length / itemSize : 0;
  5590. this.normalized = normalized;
  5591. this.usage = StaticDrawUsage;
  5592. this.updateRange = { offset: 0, count: - 1 };
  5593. this.version = 0;
  5594. }
  5595. onUploadCallback() {}
  5596. set needsUpdate( value ) {
  5597. if ( value === true ) this.version ++;
  5598. }
  5599. setUsage( value ) {
  5600. this.usage = value;
  5601. return this;
  5602. }
  5603. copy( source ) {
  5604. this.name = source.name;
  5605. this.array = new source.array.constructor( source.array );
  5606. this.itemSize = source.itemSize;
  5607. this.count = source.count;
  5608. this.normalized = source.normalized;
  5609. this.usage = source.usage;
  5610. return this;
  5611. }
  5612. copyAt( index1, attribute, index2 ) {
  5613. index1 *= this.itemSize;
  5614. index2 *= attribute.itemSize;
  5615. for ( let i = 0, l = this.itemSize; i < l; i ++ ) {
  5616. this.array[ index1 + i ] = attribute.array[ index2 + i ];
  5617. }
  5618. return this;
  5619. }
  5620. copyArray( array ) {
  5621. this.array.set( array );
  5622. return this;
  5623. }
  5624. applyMatrix3( m ) {
  5625. if ( this.itemSize === 2 ) {
  5626. for ( let i = 0, l = this.count; i < l; i ++ ) {
  5627. _vector2$1.fromBufferAttribute( this, i );
  5628. _vector2$1.applyMatrix3( m );
  5629. this.setXY( i, _vector2$1.x, _vector2$1.y );
  5630. }
  5631. } else if ( this.itemSize === 3 ) {
  5632. for ( let i = 0, l = this.count; i < l; i ++ ) {
  5633. _vector$9.fromBufferAttribute( this, i );
  5634. _vector$9.applyMatrix3( m );
  5635. this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  5636. }
  5637. }
  5638. return this;
  5639. }
  5640. applyMatrix4( m ) {
  5641. for ( let i = 0, l = this.count; i < l; i ++ ) {
  5642. _vector$9.fromBufferAttribute( this, i );
  5643. _vector$9.applyMatrix4( m );
  5644. this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  5645. }
  5646. return this;
  5647. }
  5648. applyNormalMatrix( m ) {
  5649. for ( let i = 0, l = this.count; i < l; i ++ ) {
  5650. _vector$9.fromBufferAttribute( this, i );
  5651. _vector$9.applyNormalMatrix( m );
  5652. this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  5653. }
  5654. return this;
  5655. }
  5656. transformDirection( m ) {
  5657. for ( let i = 0, l = this.count; i < l; i ++ ) {
  5658. _vector$9.fromBufferAttribute( this, i );
  5659. _vector$9.transformDirection( m );
  5660. this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  5661. }
  5662. return this;
  5663. }
  5664. set( value, offset = 0 ) {
  5665. // Matching BufferAttribute constructor, do not normalize the array.
  5666. this.array.set( value, offset );
  5667. return this;
  5668. }
  5669. getX( index ) {
  5670. let x = this.array[ index * this.itemSize ];
  5671. if ( this.normalized ) x = denormalize( x, this.array );
  5672. return x;
  5673. }
  5674. setX( index, x ) {
  5675. if ( this.normalized ) x = normalize( x, this.array );
  5676. this.array[ index * this.itemSize ] = x;
  5677. return this;
  5678. }
  5679. getY( index ) {
  5680. let y = this.array[ index * this.itemSize + 1 ];
  5681. if ( this.normalized ) y = denormalize( y, this.array );
  5682. return y;
  5683. }
  5684. setY( index, y ) {
  5685. if ( this.normalized ) y = normalize( y, this.array );
  5686. this.array[ index * this.itemSize + 1 ] = y;
  5687. return this;
  5688. }
  5689. getZ( index ) {
  5690. let z = this.array[ index * this.itemSize + 2 ];
  5691. if ( this.normalized ) z = denormalize( z, this.array );
  5692. return z;
  5693. }
  5694. setZ( index, z ) {
  5695. if ( this.normalized ) z = normalize( z, this.array );
  5696. this.array[ index * this.itemSize + 2 ] = z;
  5697. return this;
  5698. }
  5699. getW( index ) {
  5700. let w = this.array[ index * this.itemSize + 3 ];
  5701. if ( this.normalized ) w = denormalize( w, this.array );
  5702. return w;
  5703. }
  5704. setW( index, w ) {
  5705. if ( this.normalized ) w = normalize( w, this.array );
  5706. this.array[ index * this.itemSize + 3 ] = w;
  5707. return this;
  5708. }
  5709. setXY( index, x, y ) {
  5710. index *= this.itemSize;
  5711. if ( this.normalized ) {
  5712. x = normalize( x, this.array );
  5713. y = normalize( y, this.array );
  5714. }
  5715. this.array[ index + 0 ] = x;
  5716. this.array[ index + 1 ] = y;
  5717. return this;
  5718. }
  5719. setXYZ( index, x, y, z ) {
  5720. index *= this.itemSize;
  5721. if ( this.normalized ) {
  5722. x = normalize( x, this.array );
  5723. y = normalize( y, this.array );
  5724. z = normalize( z, this.array );
  5725. }
  5726. this.array[ index + 0 ] = x;
  5727. this.array[ index + 1 ] = y;
  5728. this.array[ index + 2 ] = z;
  5729. return this;
  5730. }
  5731. setXYZW( index, x, y, z, w ) {
  5732. index *= this.itemSize;
  5733. if ( this.normalized ) {
  5734. x = normalize( x, this.array );
  5735. y = normalize( y, this.array );
  5736. z = normalize( z, this.array );
  5737. w = normalize( w, this.array );
  5738. }
  5739. this.array[ index + 0 ] = x;
  5740. this.array[ index + 1 ] = y;
  5741. this.array[ index + 2 ] = z;
  5742. this.array[ index + 3 ] = w;
  5743. return this;
  5744. }
  5745. onUpload( callback ) {
  5746. this.onUploadCallback = callback;
  5747. return this;
  5748. }
  5749. clone() {
  5750. return new this.constructor( this.array, this.itemSize ).copy( this );
  5751. }
  5752. toJSON() {
  5753. const data = {
  5754. itemSize: this.itemSize,
  5755. type: this.array.constructor.name,
  5756. array: Array.from( this.array ),
  5757. normalized: this.normalized
  5758. };
  5759. if ( this.name !== '' ) data.name = this.name;
  5760. if ( this.usage !== StaticDrawUsage ) data.usage = this.usage;
  5761. if ( this.updateRange.offset !== 0 || this.updateRange.count !== - 1 ) data.updateRange = this.updateRange;
  5762. return data;
  5763. }
  5764. // @deprecated
  5765. copyColorsArray() {
  5766. console.error( 'THREE.BufferAttribute: copyColorsArray() was removed in r144.' );
  5767. }
  5768. copyVector2sArray() {
  5769. console.error( 'THREE.BufferAttribute: copyVector2sArray() was removed in r144.' );
  5770. }
  5771. copyVector3sArray() {
  5772. console.error( 'THREE.BufferAttribute: copyVector3sArray() was removed in r144.' );
  5773. }
  5774. copyVector4sArray() {
  5775. console.error( 'THREE.BufferAttribute: copyVector4sArray() was removed in r144.' );
  5776. }
  5777. }
  5778. //
  5779. class Int8BufferAttribute extends BufferAttribute {
  5780. constructor( array, itemSize, normalized ) {
  5781. super( new Int8Array( array ), itemSize, normalized );
  5782. }
  5783. }
  5784. class Uint8BufferAttribute extends BufferAttribute {
  5785. constructor( array, itemSize, normalized ) {
  5786. super( new Uint8Array( array ), itemSize, normalized );
  5787. }
  5788. }
  5789. class Uint8ClampedBufferAttribute extends BufferAttribute {
  5790. constructor( array, itemSize, normalized ) {
  5791. super( new Uint8ClampedArray( array ), itemSize, normalized );
  5792. }
  5793. }
  5794. class Int16BufferAttribute extends BufferAttribute {
  5795. constructor( array, itemSize, normalized ) {
  5796. super( new Int16Array( array ), itemSize, normalized );
  5797. }
  5798. }
  5799. class Uint16BufferAttribute extends BufferAttribute {
  5800. constructor( array, itemSize, normalized ) {
  5801. super( new Uint16Array( array ), itemSize, normalized );
  5802. }
  5803. }
  5804. class Int32BufferAttribute extends BufferAttribute {
  5805. constructor( array, itemSize, normalized ) {
  5806. super( new Int32Array( array ), itemSize, normalized );
  5807. }
  5808. }
  5809. class Uint32BufferAttribute extends BufferAttribute {
  5810. constructor( array, itemSize, normalized ) {
  5811. super( new Uint32Array( array ), itemSize, normalized );
  5812. }
  5813. }
  5814. class Float16BufferAttribute extends BufferAttribute {
  5815. constructor( array, itemSize, normalized ) {
  5816. super( new Uint16Array( array ), itemSize, normalized );
  5817. this.isFloat16BufferAttribute = true;
  5818. }
  5819. }
  5820. class Float32BufferAttribute extends BufferAttribute {
  5821. constructor( array, itemSize, normalized ) {
  5822. super( new Float32Array( array ), itemSize, normalized );
  5823. }
  5824. }
  5825. class Float64BufferAttribute extends BufferAttribute {
  5826. constructor( array, itemSize, normalized ) {
  5827. super( new Float64Array( array ), itemSize, normalized );
  5828. }
  5829. }
  5830. let _id$1 = 0;
  5831. const _m1 = /*@__PURE__*/ new Matrix4();
  5832. const _obj = /*@__PURE__*/ new Object3D();
  5833. const _offset = /*@__PURE__*/ new Vector3();
  5834. const _box$1 = /*@__PURE__*/ new Box3();
  5835. const _boxMorphTargets = /*@__PURE__*/ new Box3();
  5836. const _vector$8 = /*@__PURE__*/ new Vector3();
  5837. class BufferGeometry extends EventDispatcher {
  5838. constructor() {
  5839. super();
  5840. this.isBufferGeometry = true;
  5841. Object.defineProperty( this, 'id', { value: _id$1 ++ } );
  5842. this.uuid = generateUUID();
  5843. this.name = '';
  5844. this.type = 'BufferGeometry';
  5845. this.index = null;
  5846. this.attributes = {};
  5847. this.morphAttributes = {};
  5848. this.morphTargetsRelative = false;
  5849. this.groups = [];
  5850. this.boundingBox = null;
  5851. this.boundingSphere = null;
  5852. this.drawRange = { start: 0, count: Infinity };
  5853. this.userData = {};
  5854. }
  5855. getIndex() {
  5856. return this.index;
  5857. }
  5858. setIndex( index ) {
  5859. if ( Array.isArray( index ) ) {
  5860. this.index = new ( arrayNeedsUint32( index ) ? Uint32BufferAttribute : Uint16BufferAttribute )( index, 1 );
  5861. } else {
  5862. this.index = index;
  5863. }
  5864. return this;
  5865. }
  5866. getAttribute( name ) {
  5867. return this.attributes[ name ];
  5868. }
  5869. setAttribute( name, attribute ) {
  5870. this.attributes[ name ] = attribute;
  5871. return this;
  5872. }
  5873. deleteAttribute( name ) {
  5874. delete this.attributes[ name ];
  5875. return this;
  5876. }
  5877. hasAttribute( name ) {
  5878. return this.attributes[ name ] !== undefined;
  5879. }
  5880. addGroup( start, count, materialIndex = 0 ) {
  5881. this.groups.push( {
  5882. start: start,
  5883. count: count,
  5884. materialIndex: materialIndex
  5885. } );
  5886. }
  5887. clearGroups() {
  5888. this.groups = [];
  5889. }
  5890. setDrawRange( start, count ) {
  5891. this.drawRange.start = start;
  5892. this.drawRange.count = count;
  5893. }
  5894. applyMatrix4( matrix ) {
  5895. const position = this.attributes.position;
  5896. if ( position !== undefined ) {
  5897. position.applyMatrix4( matrix );
  5898. position.needsUpdate = true;
  5899. }
  5900. const normal = this.attributes.normal;
  5901. if ( normal !== undefined ) {
  5902. const normalMatrix = new Matrix3().getNormalMatrix( matrix );
  5903. normal.applyNormalMatrix( normalMatrix );
  5904. normal.needsUpdate = true;
  5905. }
  5906. const tangent = this.attributes.tangent;
  5907. if ( tangent !== undefined ) {
  5908. tangent.transformDirection( matrix );
  5909. tangent.needsUpdate = true;
  5910. }
  5911. if ( this.boundingBox !== null ) {
  5912. this.computeBoundingBox();
  5913. }
  5914. if ( this.boundingSphere !== null ) {
  5915. this.computeBoundingSphere();
  5916. }
  5917. return this;
  5918. }
  5919. applyQuaternion( q ) {
  5920. _m1.makeRotationFromQuaternion( q );
  5921. this.applyMatrix4( _m1 );
  5922. return this;
  5923. }
  5924. rotateX( angle ) {
  5925. // rotate geometry around world x-axis
  5926. _m1.makeRotationX( angle );
  5927. this.applyMatrix4( _m1 );
  5928. return this;
  5929. }
  5930. rotateY( angle ) {
  5931. // rotate geometry around world y-axis
  5932. _m1.makeRotationY( angle );
  5933. this.applyMatrix4( _m1 );
  5934. return this;
  5935. }
  5936. rotateZ( angle ) {
  5937. // rotate geometry around world z-axis
  5938. _m1.makeRotationZ( angle );
  5939. this.applyMatrix4( _m1 );
  5940. return this;
  5941. }
  5942. translate( x, y, z ) {
  5943. // translate geometry
  5944. _m1.makeTranslation( x, y, z );
  5945. this.applyMatrix4( _m1 );
  5946. return this;
  5947. }
  5948. scale( x, y, z ) {
  5949. // scale geometry
  5950. _m1.makeScale( x, y, z );
  5951. this.applyMatrix4( _m1 );
  5952. return this;
  5953. }
  5954. lookAt( vector ) {
  5955. _obj.lookAt( vector );
  5956. _obj.updateMatrix();
  5957. this.applyMatrix4( _obj.matrix );
  5958. return this;
  5959. }
  5960. center() {
  5961. this.computeBoundingBox();
  5962. this.boundingBox.getCenter( _offset ).negate();
  5963. this.translate( _offset.x, _offset.y, _offset.z );
  5964. return this;
  5965. }
  5966. setFromPoints( points ) {
  5967. const position = [];
  5968. for ( let i = 0, l = points.length; i < l; i ++ ) {
  5969. const point = points[ i ];
  5970. position.push( point.x, point.y, point.z || 0 );
  5971. }
  5972. this.setAttribute( 'position', new Float32BufferAttribute( position, 3 ) );
  5973. return this;
  5974. }
  5975. computeBoundingBox() {
  5976. if ( this.boundingBox === null ) {
  5977. this.boundingBox = new Box3();
  5978. }
  5979. const position = this.attributes.position;
  5980. const morphAttributesPosition = this.morphAttributes.position;
  5981. if ( position && position.isGLBufferAttribute ) {
  5982. console.error( 'THREE.BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box. Alternatively set "mesh.frustumCulled" to "false".', this );
  5983. this.boundingBox.set(
  5984. new Vector3( - Infinity, - Infinity, - Infinity ),
  5985. new Vector3( + Infinity, + Infinity, + Infinity )
  5986. );
  5987. return;
  5988. }
  5989. if ( position !== undefined ) {
  5990. this.boundingBox.setFromBufferAttribute( position );
  5991. // process morph attributes if present
  5992. if ( morphAttributesPosition ) {
  5993. for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  5994. const morphAttribute = morphAttributesPosition[ i ];
  5995. _box$1.setFromBufferAttribute( morphAttribute );
  5996. if ( this.morphTargetsRelative ) {
  5997. _vector$8.addVectors( this.boundingBox.min, _box$1.min );
  5998. this.boundingBox.expandByPoint( _vector$8 );
  5999. _vector$8.addVectors( this.boundingBox.max, _box$1.max );
  6000. this.boundingBox.expandByPoint( _vector$8 );
  6001. } else {
  6002. this.boundingBox.expandByPoint( _box$1.min );
  6003. this.boundingBox.expandByPoint( _box$1.max );
  6004. }
  6005. }
  6006. }
  6007. } else {
  6008. this.boundingBox.makeEmpty();
  6009. }
  6010. if ( isNaN( this.boundingBox.min.x ) || isNaN( this.boundingBox.min.y ) || isNaN( this.boundingBox.min.z ) ) {
  6011. console.error( 'THREE.BufferGeometry.computeBoundingBox(): Computed min/max have NaN values. The "position" attribute is likely to have NaN values.', this );
  6012. }
  6013. }
  6014. computeBoundingSphere() {
  6015. if ( this.boundingSphere === null ) {
  6016. this.boundingSphere = new Sphere();
  6017. }
  6018. const position = this.attributes.position;
  6019. const morphAttributesPosition = this.morphAttributes.position;
  6020. if ( position && position.isGLBufferAttribute ) {
  6021. console.error( 'THREE.BufferGeometry.computeBoundingSphere(): GLBufferAttribute requires a manual bounding sphere. Alternatively set "mesh.frustumCulled" to "false".', this );
  6022. this.boundingSphere.set( new Vector3(), Infinity );
  6023. return;
  6024. }
  6025. if ( position ) {
  6026. // first, find the center of the bounding sphere
  6027. const center = this.boundingSphere.center;
  6028. _box$1.setFromBufferAttribute( position );
  6029. // process morph attributes if present
  6030. if ( morphAttributesPosition ) {
  6031. for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  6032. const morphAttribute = morphAttributesPosition[ i ];
  6033. _boxMorphTargets.setFromBufferAttribute( morphAttribute );
  6034. if ( this.morphTargetsRelative ) {
  6035. _vector$8.addVectors( _box$1.min, _boxMorphTargets.min );
  6036. _box$1.expandByPoint( _vector$8 );
  6037. _vector$8.addVectors( _box$1.max, _boxMorphTargets.max );
  6038. _box$1.expandByPoint( _vector$8 );
  6039. } else {
  6040. _box$1.expandByPoint( _boxMorphTargets.min );
  6041. _box$1.expandByPoint( _boxMorphTargets.max );
  6042. }
  6043. }
  6044. }
  6045. _box$1.getCenter( center );
  6046. // second, try to find a boundingSphere with a radius smaller than the
  6047. // boundingSphere of the boundingBox: sqrt(3) smaller in the best case
  6048. let maxRadiusSq = 0;
  6049. for ( let i = 0, il = position.count; i < il; i ++ ) {
  6050. _vector$8.fromBufferAttribute( position, i );
  6051. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( _vector$8 ) );
  6052. }
  6053. // process morph attributes if present
  6054. if ( morphAttributesPosition ) {
  6055. for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  6056. const morphAttribute = morphAttributesPosition[ i ];
  6057. const morphTargetsRelative = this.morphTargetsRelative;
  6058. for ( let j = 0, jl = morphAttribute.count; j < jl; j ++ ) {
  6059. _vector$8.fromBufferAttribute( morphAttribute, j );
  6060. if ( morphTargetsRelative ) {
  6061. _offset.fromBufferAttribute( position, j );
  6062. _vector$8.add( _offset );
  6063. }
  6064. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( _vector$8 ) );
  6065. }
  6066. }
  6067. }
  6068. this.boundingSphere.radius = Math.sqrt( maxRadiusSq );
  6069. if ( isNaN( this.boundingSphere.radius ) ) {
  6070. console.error( 'THREE.BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.', this );
  6071. }
  6072. }
  6073. }
  6074. computeTangents() {
  6075. const index = this.index;
  6076. const attributes = this.attributes;
  6077. // based on http://www.terathon.com/code/tangent.html
  6078. // (per vertex tangents)
  6079. if ( index === null ||
  6080. attributes.position === undefined ||
  6081. attributes.normal === undefined ||
  6082. attributes.uv === undefined ) {
  6083. console.error( 'THREE.BufferGeometry: .computeTangents() failed. Missing required attributes (index, position, normal or uv)' );
  6084. return;
  6085. }
  6086. const indices = index.array;
  6087. const positions = attributes.position.array;
  6088. const normals = attributes.normal.array;
  6089. const uvs = attributes.uv.array;
  6090. const nVertices = positions.length / 3;
  6091. if ( this.hasAttribute( 'tangent' ) === false ) {
  6092. this.setAttribute( 'tangent', new BufferAttribute( new Float32Array( 4 * nVertices ), 4 ) );
  6093. }
  6094. const tangents = this.getAttribute( 'tangent' ).array;
  6095. const tan1 = [], tan2 = [];
  6096. for ( let i = 0; i < nVertices; i ++ ) {
  6097. tan1[ i ] = new Vector3();
  6098. tan2[ i ] = new Vector3();
  6099. }
  6100. const vA = new Vector3(),
  6101. vB = new Vector3(),
  6102. vC = new Vector3(),
  6103. uvA = new Vector2(),
  6104. uvB = new Vector2(),
  6105. uvC = new Vector2(),
  6106. sdir = new Vector3(),
  6107. tdir = new Vector3();
  6108. function handleTriangle( a, b, c ) {
  6109. vA.fromArray( positions, a * 3 );
  6110. vB.fromArray( positions, b * 3 );
  6111. vC.fromArray( positions, c * 3 );
  6112. uvA.fromArray( uvs, a * 2 );
  6113. uvB.fromArray( uvs, b * 2 );
  6114. uvC.fromArray( uvs, c * 2 );
  6115. vB.sub( vA );
  6116. vC.sub( vA );
  6117. uvB.sub( uvA );
  6118. uvC.sub( uvA );
  6119. const r = 1.0 / ( uvB.x * uvC.y - uvC.x * uvB.y );
  6120. // silently ignore degenerate uv triangles having coincident or colinear vertices
  6121. if ( ! isFinite( r ) ) return;
  6122. sdir.copy( vB ).multiplyScalar( uvC.y ).addScaledVector( vC, - uvB.y ).multiplyScalar( r );
  6123. tdir.copy( vC ).multiplyScalar( uvB.x ).addScaledVector( vB, - uvC.x ).multiplyScalar( r );
  6124. tan1[ a ].add( sdir );
  6125. tan1[ b ].add( sdir );
  6126. tan1[ c ].add( sdir );
  6127. tan2[ a ].add( tdir );
  6128. tan2[ b ].add( tdir );
  6129. tan2[ c ].add( tdir );
  6130. }
  6131. let groups = this.groups;
  6132. if ( groups.length === 0 ) {
  6133. groups = [ {
  6134. start: 0,
  6135. count: indices.length
  6136. } ];
  6137. }
  6138. for ( let i = 0, il = groups.length; i < il; ++ i ) {
  6139. const group = groups[ i ];
  6140. const start = group.start;
  6141. const count = group.count;
  6142. for ( let j = start, jl = start + count; j < jl; j += 3 ) {
  6143. handleTriangle(
  6144. indices[ j + 0 ],
  6145. indices[ j + 1 ],
  6146. indices[ j + 2 ]
  6147. );
  6148. }
  6149. }
  6150. const tmp = new Vector3(), tmp2 = new Vector3();
  6151. const n = new Vector3(), n2 = new Vector3();
  6152. function handleVertex( v ) {
  6153. n.fromArray( normals, v * 3 );
  6154. n2.copy( n );
  6155. const t = tan1[ v ];
  6156. // Gram-Schmidt orthogonalize
  6157. tmp.copy( t );
  6158. tmp.sub( n.multiplyScalar( n.dot( t ) ) ).normalize();
  6159. // Calculate handedness
  6160. tmp2.crossVectors( n2, t );
  6161. const test = tmp2.dot( tan2[ v ] );
  6162. const w = ( test < 0.0 ) ? - 1.0 : 1.0;
  6163. tangents[ v * 4 ] = tmp.x;
  6164. tangents[ v * 4 + 1 ] = tmp.y;
  6165. tangents[ v * 4 + 2 ] = tmp.z;
  6166. tangents[ v * 4 + 3 ] = w;
  6167. }
  6168. for ( let i = 0, il = groups.length; i < il; ++ i ) {
  6169. const group = groups[ i ];
  6170. const start = group.start;
  6171. const count = group.count;
  6172. for ( let j = start, jl = start + count; j < jl; j += 3 ) {
  6173. handleVertex( indices[ j + 0 ] );
  6174. handleVertex( indices[ j + 1 ] );
  6175. handleVertex( indices[ j + 2 ] );
  6176. }
  6177. }
  6178. }
  6179. computeVertexNormals() {
  6180. const index = this.index;
  6181. const positionAttribute = this.getAttribute( 'position' );
  6182. if ( positionAttribute !== undefined ) {
  6183. let normalAttribute = this.getAttribute( 'normal' );
  6184. if ( normalAttribute === undefined ) {
  6185. normalAttribute = new BufferAttribute( new Float32Array( positionAttribute.count * 3 ), 3 );
  6186. this.setAttribute( 'normal', normalAttribute );
  6187. } else {
  6188. // reset existing normals to zero
  6189. for ( let i = 0, il = normalAttribute.count; i < il; i ++ ) {
  6190. normalAttribute.setXYZ( i, 0, 0, 0 );
  6191. }
  6192. }
  6193. const pA = new Vector3(), pB = new Vector3(), pC = new Vector3();
  6194. const nA = new Vector3(), nB = new Vector3(), nC = new Vector3();
  6195. const cb = new Vector3(), ab = new Vector3();
  6196. // indexed elements
  6197. if ( index ) {
  6198. for ( let i = 0, il = index.count; i < il; i += 3 ) {
  6199. const vA = index.getX( i + 0 );
  6200. const vB = index.getX( i + 1 );
  6201. const vC = index.getX( i + 2 );
  6202. pA.fromBufferAttribute( positionAttribute, vA );
  6203. pB.fromBufferAttribute( positionAttribute, vB );
  6204. pC.fromBufferAttribute( positionAttribute, vC );
  6205. cb.subVectors( pC, pB );
  6206. ab.subVectors( pA, pB );
  6207. cb.cross( ab );
  6208. nA.fromBufferAttribute( normalAttribute, vA );
  6209. nB.fromBufferAttribute( normalAttribute, vB );
  6210. nC.fromBufferAttribute( normalAttribute, vC );
  6211. nA.add( cb );
  6212. nB.add( cb );
  6213. nC.add( cb );
  6214. normalAttribute.setXYZ( vA, nA.x, nA.y, nA.z );
  6215. normalAttribute.setXYZ( vB, nB.x, nB.y, nB.z );
  6216. normalAttribute.setXYZ( vC, nC.x, nC.y, nC.z );
  6217. }
  6218. } else {
  6219. // non-indexed elements (unconnected triangle soup)
  6220. for ( let i = 0, il = positionAttribute.count; i < il; i += 3 ) {
  6221. pA.fromBufferAttribute( positionAttribute, i + 0 );
  6222. pB.fromBufferAttribute( positionAttribute, i + 1 );
  6223. pC.fromBufferAttribute( positionAttribute, i + 2 );
  6224. cb.subVectors( pC, pB );
  6225. ab.subVectors( pA, pB );
  6226. cb.cross( ab );
  6227. normalAttribute.setXYZ( i + 0, cb.x, cb.y, cb.z );
  6228. normalAttribute.setXYZ( i + 1, cb.x, cb.y, cb.z );
  6229. normalAttribute.setXYZ( i + 2, cb.x, cb.y, cb.z );
  6230. }
  6231. }
  6232. this.normalizeNormals();
  6233. normalAttribute.needsUpdate = true;
  6234. }
  6235. }
  6236. // @deprecated since r144
  6237. merge() {
  6238. console.error( 'THREE.BufferGeometry.merge() has been removed. Use THREE.BufferGeometryUtils.mergeBufferGeometries() instead.' );
  6239. return this;
  6240. }
  6241. normalizeNormals() {
  6242. const normals = this.attributes.normal;
  6243. for ( let i = 0, il = normals.count; i < il; i ++ ) {
  6244. _vector$8.fromBufferAttribute( normals, i );
  6245. _vector$8.normalize();
  6246. normals.setXYZ( i, _vector$8.x, _vector$8.y, _vector$8.z );
  6247. }
  6248. }
  6249. toNonIndexed() {
  6250. function convertBufferAttribute( attribute, indices ) {
  6251. const array = attribute.array;
  6252. const itemSize = attribute.itemSize;
  6253. const normalized = attribute.normalized;
  6254. const array2 = new array.constructor( indices.length * itemSize );
  6255. let index = 0, index2 = 0;
  6256. for ( let i = 0, l = indices.length; i < l; i ++ ) {
  6257. if ( attribute.isInterleavedBufferAttribute ) {
  6258. index = indices[ i ] * attribute.data.stride + attribute.offset;
  6259. } else {
  6260. index = indices[ i ] * itemSize;
  6261. }
  6262. for ( let j = 0; j < itemSize; j ++ ) {
  6263. array2[ index2 ++ ] = array[ index ++ ];
  6264. }
  6265. }
  6266. return new BufferAttribute( array2, itemSize, normalized );
  6267. }
  6268. //
  6269. if ( this.index === null ) {
  6270. console.warn( 'THREE.BufferGeometry.toNonIndexed(): BufferGeometry is already non-indexed.' );
  6271. return this;
  6272. }
  6273. const geometry2 = new BufferGeometry();
  6274. const indices = this.index.array;
  6275. const attributes = this.attributes;
  6276. // attributes
  6277. for ( const name in attributes ) {
  6278. const attribute = attributes[ name ];
  6279. const newAttribute = convertBufferAttribute( attribute, indices );
  6280. geometry2.setAttribute( name, newAttribute );
  6281. }
  6282. // morph attributes
  6283. const morphAttributes = this.morphAttributes;
  6284. for ( const name in morphAttributes ) {
  6285. const morphArray = [];
  6286. const morphAttribute = morphAttributes[ name ]; // morphAttribute: array of Float32BufferAttributes
  6287. for ( let i = 0, il = morphAttribute.length; i < il; i ++ ) {
  6288. const attribute = morphAttribute[ i ];
  6289. const newAttribute = convertBufferAttribute( attribute, indices );
  6290. morphArray.push( newAttribute );
  6291. }
  6292. geometry2.morphAttributes[ name ] = morphArray;
  6293. }
  6294. geometry2.morphTargetsRelative = this.morphTargetsRelative;
  6295. // groups
  6296. const groups = this.groups;
  6297. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  6298. const group = groups[ i ];
  6299. geometry2.addGroup( group.start, group.count, group.materialIndex );
  6300. }
  6301. return geometry2;
  6302. }
  6303. toJSON() {
  6304. const data = {
  6305. metadata: {
  6306. version: 4.5,
  6307. type: 'BufferGeometry',
  6308. generator: 'BufferGeometry.toJSON'
  6309. }
  6310. };
  6311. // standard BufferGeometry serialization
  6312. data.uuid = this.uuid;
  6313. data.type = this.type;
  6314. if ( this.name !== '' ) data.name = this.name;
  6315. if ( Object.keys( this.userData ).length > 0 ) data.userData = this.userData;
  6316. if ( this.parameters !== undefined ) {
  6317. const parameters = this.parameters;
  6318. for ( const key in parameters ) {
  6319. if ( parameters[ key ] !== undefined ) data[ key ] = parameters[ key ];
  6320. }
  6321. return data;
  6322. }
  6323. // for simplicity the code assumes attributes are not shared across geometries, see #15811
  6324. data.data = { attributes: {} };
  6325. const index = this.index;
  6326. if ( index !== null ) {
  6327. data.data.index = {
  6328. type: index.array.constructor.name,
  6329. array: Array.prototype.slice.call( index.array )
  6330. };
  6331. }
  6332. const attributes = this.attributes;
  6333. for ( const key in attributes ) {
  6334. const attribute = attributes[ key ];
  6335. data.data.attributes[ key ] = attribute.toJSON( data.data );
  6336. }
  6337. const morphAttributes = {};
  6338. let hasMorphAttributes = false;
  6339. for ( const key in this.morphAttributes ) {
  6340. const attributeArray = this.morphAttributes[ key ];
  6341. const array = [];
  6342. for ( let i = 0, il = attributeArray.length; i < il; i ++ ) {
  6343. const attribute = attributeArray[ i ];
  6344. array.push( attribute.toJSON( data.data ) );
  6345. }
  6346. if ( array.length > 0 ) {
  6347. morphAttributes[ key ] = array;
  6348. hasMorphAttributes = true;
  6349. }
  6350. }
  6351. if ( hasMorphAttributes ) {
  6352. data.data.morphAttributes = morphAttributes;
  6353. data.data.morphTargetsRelative = this.morphTargetsRelative;
  6354. }
  6355. const groups = this.groups;
  6356. if ( groups.length > 0 ) {
  6357. data.data.groups = JSON.parse( JSON.stringify( groups ) );
  6358. }
  6359. const boundingSphere = this.boundingSphere;
  6360. if ( boundingSphere !== null ) {
  6361. data.data.boundingSphere = {
  6362. center: boundingSphere.center.toArray(),
  6363. radius: boundingSphere.radius
  6364. };
  6365. }
  6366. return data;
  6367. }
  6368. clone() {
  6369. return new this.constructor().copy( this );
  6370. }
  6371. copy( source ) {
  6372. // reset
  6373. this.index = null;
  6374. this.attributes = {};
  6375. this.morphAttributes = {};
  6376. this.groups = [];
  6377. this.boundingBox = null;
  6378. this.boundingSphere = null;
  6379. // used for storing cloned, shared data
  6380. const data = {};
  6381. // name
  6382. this.name = source.name;
  6383. // index
  6384. const index = source.index;
  6385. if ( index !== null ) {
  6386. this.setIndex( index.clone( data ) );
  6387. }
  6388. // attributes
  6389. const attributes = source.attributes;
  6390. for ( const name in attributes ) {
  6391. const attribute = attributes[ name ];
  6392. this.setAttribute( name, attribute.clone( data ) );
  6393. }
  6394. // morph attributes
  6395. const morphAttributes = source.morphAttributes;
  6396. for ( const name in morphAttributes ) {
  6397. const array = [];
  6398. const morphAttribute = morphAttributes[ name ]; // morphAttribute: array of Float32BufferAttributes
  6399. for ( let i = 0, l = morphAttribute.length; i < l; i ++ ) {
  6400. array.push( morphAttribute[ i ].clone( data ) );
  6401. }
  6402. this.morphAttributes[ name ] = array;
  6403. }
  6404. this.morphTargetsRelative = source.morphTargetsRelative;
  6405. // groups
  6406. const groups = source.groups;
  6407. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  6408. const group = groups[ i ];
  6409. this.addGroup( group.start, group.count, group.materialIndex );
  6410. }
  6411. // bounding box
  6412. const boundingBox = source.boundingBox;
  6413. if ( boundingBox !== null ) {
  6414. this.boundingBox = boundingBox.clone();
  6415. }
  6416. // bounding sphere
  6417. const boundingSphere = source.boundingSphere;
  6418. if ( boundingSphere !== null ) {
  6419. this.boundingSphere = boundingSphere.clone();
  6420. }
  6421. // draw range
  6422. this.drawRange.start = source.drawRange.start;
  6423. this.drawRange.count = source.drawRange.count;
  6424. // user data
  6425. this.userData = source.userData;
  6426. // geometry generator parameters
  6427. if ( source.parameters !== undefined ) this.parameters = Object.assign( {}, source.parameters );
  6428. return this;
  6429. }
  6430. dispose() {
  6431. this.dispatchEvent( { type: 'dispose' } );
  6432. }
  6433. }
  6434. const _inverseMatrix$2 = /*@__PURE__*/ new Matrix4();
  6435. const _ray$2 = /*@__PURE__*/ new Ray();
  6436. const _sphere$3 = /*@__PURE__*/ new Sphere();
  6437. const _vA$1 = /*@__PURE__*/ new Vector3();
  6438. const _vB$1 = /*@__PURE__*/ new Vector3();
  6439. const _vC$1 = /*@__PURE__*/ new Vector3();
  6440. const _tempA = /*@__PURE__*/ new Vector3();
  6441. const _morphA = /*@__PURE__*/ new Vector3();
  6442. const _uvA$1 = /*@__PURE__*/ new Vector2();
  6443. const _uvB$1 = /*@__PURE__*/ new Vector2();
  6444. const _uvC$1 = /*@__PURE__*/ new Vector2();
  6445. const _intersectionPoint = /*@__PURE__*/ new Vector3();
  6446. const _intersectionPointWorld = /*@__PURE__*/ new Vector3();
  6447. class Mesh extends Object3D {
  6448. constructor( geometry = new BufferGeometry(), material = new MeshBasicMaterial() ) {
  6449. super();
  6450. this.isMesh = true;
  6451. this.type = 'Mesh';
  6452. this.geometry = geometry;
  6453. this.material = material;
  6454. this.updateMorphTargets();
  6455. }
  6456. copy( source, recursive ) {
  6457. super.copy( source, recursive );
  6458. if ( source.morphTargetInfluences !== undefined ) {
  6459. this.morphTargetInfluences = source.morphTargetInfluences.slice();
  6460. }
  6461. if ( source.morphTargetDictionary !== undefined ) {
  6462. this.morphTargetDictionary = Object.assign( {}, source.morphTargetDictionary );
  6463. }
  6464. this.material = source.material;
  6465. this.geometry = source.geometry;
  6466. return this;
  6467. }
  6468. updateMorphTargets() {
  6469. const geometry = this.geometry;
  6470. const morphAttributes = geometry.morphAttributes;
  6471. const keys = Object.keys( morphAttributes );
  6472. if ( keys.length > 0 ) {
  6473. const morphAttribute = morphAttributes[ keys[ 0 ] ];
  6474. if ( morphAttribute !== undefined ) {
  6475. this.morphTargetInfluences = [];
  6476. this.morphTargetDictionary = {};
  6477. for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  6478. const name = morphAttribute[ m ].name || String( m );
  6479. this.morphTargetInfluences.push( 0 );
  6480. this.morphTargetDictionary[ name ] = m;
  6481. }
  6482. }
  6483. }
  6484. }
  6485. getVertexPosition( index, target ) {
  6486. const geometry = this.geometry;
  6487. const position = geometry.attributes.position;
  6488. const morphPosition = geometry.morphAttributes.position;
  6489. const morphTargetsRelative = geometry.morphTargetsRelative;
  6490. target.fromBufferAttribute( position, index );
  6491. const morphInfluences = this.morphTargetInfluences;
  6492. if ( morphPosition && morphInfluences ) {
  6493. _morphA.set( 0, 0, 0 );
  6494. for ( let i = 0, il = morphPosition.length; i < il; i ++ ) {
  6495. const influence = morphInfluences[ i ];
  6496. const morphAttribute = morphPosition[ i ];
  6497. if ( influence === 0 ) continue;
  6498. _tempA.fromBufferAttribute( morphAttribute, index );
  6499. if ( morphTargetsRelative ) {
  6500. _morphA.addScaledVector( _tempA, influence );
  6501. } else {
  6502. _morphA.addScaledVector( _tempA.sub( target ), influence );
  6503. }
  6504. }
  6505. target.add( _morphA );
  6506. }
  6507. if ( this.isSkinnedMesh ) {
  6508. this.boneTransform( index, target );
  6509. }
  6510. return target;
  6511. }
  6512. raycast( raycaster, intersects ) {
  6513. const geometry = this.geometry;
  6514. const material = this.material;
  6515. const matrixWorld = this.matrixWorld;
  6516. if ( material === undefined ) return;
  6517. // Checking boundingSphere distance to ray
  6518. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  6519. _sphere$3.copy( geometry.boundingSphere );
  6520. _sphere$3.applyMatrix4( matrixWorld );
  6521. if ( raycaster.ray.intersectsSphere( _sphere$3 ) === false ) return;
  6522. //
  6523. _inverseMatrix$2.copy( matrixWorld ).invert();
  6524. _ray$2.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$2 );
  6525. // Check boundingBox before continuing
  6526. if ( geometry.boundingBox !== null ) {
  6527. if ( _ray$2.intersectsBox( geometry.boundingBox ) === false ) return;
  6528. }
  6529. let intersection;
  6530. const index = geometry.index;
  6531. const position = geometry.attributes.position;
  6532. const uv = geometry.attributes.uv;
  6533. const uv2 = geometry.attributes.uv2;
  6534. const groups = geometry.groups;
  6535. const drawRange = geometry.drawRange;
  6536. if ( index !== null ) {
  6537. // indexed buffer geometry
  6538. if ( Array.isArray( material ) ) {
  6539. for ( let i = 0, il = groups.length; i < il; i ++ ) {
  6540. const group = groups[ i ];
  6541. const groupMaterial = material[ group.materialIndex ];
  6542. const start = Math.max( group.start, drawRange.start );
  6543. const end = Math.min( index.count, Math.min( ( group.start + group.count ), ( drawRange.start + drawRange.count ) ) );
  6544. for ( let j = start, jl = end; j < jl; j += 3 ) {
  6545. const a = index.getX( j );
  6546. const b = index.getX( j + 1 );
  6547. const c = index.getX( j + 2 );
  6548. intersection = checkBufferGeometryIntersection( this, groupMaterial, raycaster, _ray$2, uv, uv2, a, b, c );
  6549. if ( intersection ) {
  6550. intersection.faceIndex = Math.floor( j / 3 ); // triangle number in indexed buffer semantics
  6551. intersection.face.materialIndex = group.materialIndex;
  6552. intersects.push( intersection );
  6553. }
  6554. }
  6555. }
  6556. } else {
  6557. const start = Math.max( 0, drawRange.start );
  6558. const end = Math.min( index.count, ( drawRange.start + drawRange.count ) );
  6559. for ( let i = start, il = end; i < il; i += 3 ) {
  6560. const a = index.getX( i );
  6561. const b = index.getX( i + 1 );
  6562. const c = index.getX( i + 2 );
  6563. intersection = checkBufferGeometryIntersection( this, material, raycaster, _ray$2, uv, uv2, a, b, c );
  6564. if ( intersection ) {
  6565. intersection.faceIndex = Math.floor( i / 3 ); // triangle number in indexed buffer semantics
  6566. intersects.push( intersection );
  6567. }
  6568. }
  6569. }
  6570. } else if ( position !== undefined ) {
  6571. // non-indexed buffer geometry
  6572. if ( Array.isArray( material ) ) {
  6573. for ( let i = 0, il = groups.length; i < il; i ++ ) {
  6574. const group = groups[ i ];
  6575. const groupMaterial = material[ group.materialIndex ];
  6576. const start = Math.max( group.start, drawRange.start );
  6577. const end = Math.min( position.count, Math.min( ( group.start + group.count ), ( drawRange.start + drawRange.count ) ) );
  6578. for ( let j = start, jl = end; j < jl; j += 3 ) {
  6579. const a = j;
  6580. const b = j + 1;
  6581. const c = j + 2;
  6582. intersection = checkBufferGeometryIntersection( this, groupMaterial, raycaster, _ray$2, uv, uv2, a, b, c );
  6583. if ( intersection ) {
  6584. intersection.faceIndex = Math.floor( j / 3 ); // triangle number in non-indexed buffer semantics
  6585. intersection.face.materialIndex = group.materialIndex;
  6586. intersects.push( intersection );
  6587. }
  6588. }
  6589. }
  6590. } else {
  6591. const start = Math.max( 0, drawRange.start );
  6592. const end = Math.min( position.count, ( drawRange.start + drawRange.count ) );
  6593. for ( let i = start, il = end; i < il; i += 3 ) {
  6594. const a = i;
  6595. const b = i + 1;
  6596. const c = i + 2;
  6597. intersection = checkBufferGeometryIntersection( this, material, raycaster, _ray$2, uv, uv2, a, b, c );
  6598. if ( intersection ) {
  6599. intersection.faceIndex = Math.floor( i / 3 ); // triangle number in non-indexed buffer semantics
  6600. intersects.push( intersection );
  6601. }
  6602. }
  6603. }
  6604. }
  6605. }
  6606. }
  6607. function checkIntersection( object, material, raycaster, ray, pA, pB, pC, point ) {
  6608. let intersect;
  6609. if ( material.side === BackSide ) {
  6610. intersect = ray.intersectTriangle( pC, pB, pA, true, point );
  6611. } else {
  6612. intersect = ray.intersectTriangle( pA, pB, pC, ( material.side === FrontSide ), point );
  6613. }
  6614. if ( intersect === null ) return null;
  6615. _intersectionPointWorld.copy( point );
  6616. _intersectionPointWorld.applyMatrix4( object.matrixWorld );
  6617. const distance = raycaster.ray.origin.distanceTo( _intersectionPointWorld );
  6618. if ( distance < raycaster.near || distance > raycaster.far ) return null;
  6619. return {
  6620. distance: distance,
  6621. point: _intersectionPointWorld.clone(),
  6622. object: object
  6623. };
  6624. }
  6625. function checkBufferGeometryIntersection( object, material, raycaster, ray, uv, uv2, a, b, c ) {
  6626. object.getVertexPosition( a, _vA$1 );
  6627. object.getVertexPosition( b, _vB$1 );
  6628. object.getVertexPosition( c, _vC$1 );
  6629. const intersection = checkIntersection( object, material, raycaster, ray, _vA$1, _vB$1, _vC$1, _intersectionPoint );
  6630. if ( intersection ) {
  6631. if ( uv ) {
  6632. _uvA$1.fromBufferAttribute( uv, a );
  6633. _uvB$1.fromBufferAttribute( uv, b );
  6634. _uvC$1.fromBufferAttribute( uv, c );
  6635. intersection.uv = Triangle.getUV( _intersectionPoint, _vA$1, _vB$1, _vC$1, _uvA$1, _uvB$1, _uvC$1, new Vector2() );
  6636. }
  6637. if ( uv2 ) {
  6638. _uvA$1.fromBufferAttribute( uv2, a );
  6639. _uvB$1.fromBufferAttribute( uv2, b );
  6640. _uvC$1.fromBufferAttribute( uv2, c );
  6641. intersection.uv2 = Triangle.getUV( _intersectionPoint, _vA$1, _vB$1, _vC$1, _uvA$1, _uvB$1, _uvC$1, new Vector2() );
  6642. }
  6643. const face = {
  6644. a: a,
  6645. b: b,
  6646. c: c,
  6647. normal: new Vector3(),
  6648. materialIndex: 0
  6649. };
  6650. Triangle.getNormal( _vA$1, _vB$1, _vC$1, face.normal );
  6651. intersection.face = face;
  6652. }
  6653. return intersection;
  6654. }
  6655. class BoxGeometry extends BufferGeometry {
  6656. constructor( width = 1, height = 1, depth = 1, widthSegments = 1, heightSegments = 1, depthSegments = 1 ) {
  6657. super();
  6658. this.type = 'BoxGeometry';
  6659. this.parameters = {
  6660. width: width,
  6661. height: height,
  6662. depth: depth,
  6663. widthSegments: widthSegments,
  6664. heightSegments: heightSegments,
  6665. depthSegments: depthSegments
  6666. };
  6667. const scope = this;
  6668. // segments
  6669. widthSegments = Math.floor( widthSegments );
  6670. heightSegments = Math.floor( heightSegments );
  6671. depthSegments = Math.floor( depthSegments );
  6672. // buffers
  6673. const indices = [];
  6674. const vertices = [];
  6675. const normals = [];
  6676. const uvs = [];
  6677. // helper variables
  6678. let numberOfVertices = 0;
  6679. let groupStart = 0;
  6680. // build each side of the box geometry
  6681. buildPlane( 'z', 'y', 'x', - 1, - 1, depth, height, width, depthSegments, heightSegments, 0 ); // px
  6682. buildPlane( 'z', 'y', 'x', 1, - 1, depth, height, - width, depthSegments, heightSegments, 1 ); // nx
  6683. buildPlane( 'x', 'z', 'y', 1, 1, width, depth, height, widthSegments, depthSegments, 2 ); // py
  6684. buildPlane( 'x', 'z', 'y', 1, - 1, width, depth, - height, widthSegments, depthSegments, 3 ); // ny
  6685. buildPlane( 'x', 'y', 'z', 1, - 1, width, height, depth, widthSegments, heightSegments, 4 ); // pz
  6686. buildPlane( 'x', 'y', 'z', - 1, - 1, width, height, - depth, widthSegments, heightSegments, 5 ); // nz
  6687. // build geometry
  6688. this.setIndex( indices );
  6689. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  6690. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  6691. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  6692. function buildPlane( u, v, w, udir, vdir, width, height, depth, gridX, gridY, materialIndex ) {
  6693. const segmentWidth = width / gridX;
  6694. const segmentHeight = height / gridY;
  6695. const widthHalf = width / 2;
  6696. const heightHalf = height / 2;
  6697. const depthHalf = depth / 2;
  6698. const gridX1 = gridX + 1;
  6699. const gridY1 = gridY + 1;
  6700. let vertexCounter = 0;
  6701. let groupCount = 0;
  6702. const vector = new Vector3();
  6703. // generate vertices, normals and uvs
  6704. for ( let iy = 0; iy < gridY1; iy ++ ) {
  6705. const y = iy * segmentHeight - heightHalf;
  6706. for ( let ix = 0; ix < gridX1; ix ++ ) {
  6707. const x = ix * segmentWidth - widthHalf;
  6708. // set values to correct vector component
  6709. vector[ u ] = x * udir;
  6710. vector[ v ] = y * vdir;
  6711. vector[ w ] = depthHalf;
  6712. // now apply vector to vertex buffer
  6713. vertices.push( vector.x, vector.y, vector.z );
  6714. // set values to correct vector component
  6715. vector[ u ] = 0;
  6716. vector[ v ] = 0;
  6717. vector[ w ] = depth > 0 ? 1 : - 1;
  6718. // now apply vector to normal buffer
  6719. normals.push( vector.x, vector.y, vector.z );
  6720. // uvs
  6721. uvs.push( ix / gridX );
  6722. uvs.push( 1 - ( iy / gridY ) );
  6723. // counters
  6724. vertexCounter += 1;
  6725. }
  6726. }
  6727. // indices
  6728. // 1. you need three indices to draw a single face
  6729. // 2. a single segment consists of two faces
  6730. // 3. so we need to generate six (2*3) indices per segment
  6731. for ( let iy = 0; iy < gridY; iy ++ ) {
  6732. for ( let ix = 0; ix < gridX; ix ++ ) {
  6733. const a = numberOfVertices + ix + gridX1 * iy;
  6734. const b = numberOfVertices + ix + gridX1 * ( iy + 1 );
  6735. const c = numberOfVertices + ( ix + 1 ) + gridX1 * ( iy + 1 );
  6736. const d = numberOfVertices + ( ix + 1 ) + gridX1 * iy;
  6737. // faces
  6738. indices.push( a, b, d );
  6739. indices.push( b, c, d );
  6740. // increase counter
  6741. groupCount += 6;
  6742. }
  6743. }
  6744. // add a group to the geometry. this will ensure multi material support
  6745. scope.addGroup( groupStart, groupCount, materialIndex );
  6746. // calculate new start value for groups
  6747. groupStart += groupCount;
  6748. // update total number of vertices
  6749. numberOfVertices += vertexCounter;
  6750. }
  6751. }
  6752. static fromJSON( data ) {
  6753. return new BoxGeometry( data.width, data.height, data.depth, data.widthSegments, data.heightSegments, data.depthSegments );
  6754. }
  6755. }
  6756. /**
  6757. * Uniform Utilities
  6758. */
  6759. function cloneUniforms( src ) {
  6760. const dst = {};
  6761. for ( const u in src ) {
  6762. dst[ u ] = {};
  6763. for ( const p in src[ u ] ) {
  6764. const property = src[ u ][ p ];
  6765. if ( property && ( property.isColor ||
  6766. property.isMatrix3 || property.isMatrix4 ||
  6767. property.isVector2 || property.isVector3 || property.isVector4 ||
  6768. property.isTexture || property.isQuaternion ) ) {
  6769. dst[ u ][ p ] = property.clone();
  6770. } else if ( Array.isArray( property ) ) {
  6771. dst[ u ][ p ] = property.slice();
  6772. } else {
  6773. dst[ u ][ p ] = property;
  6774. }
  6775. }
  6776. }
  6777. return dst;
  6778. }
  6779. function mergeUniforms( uniforms ) {
  6780. const merged = {};
  6781. for ( let u = 0; u < uniforms.length; u ++ ) {
  6782. const tmp = cloneUniforms( uniforms[ u ] );
  6783. for ( const p in tmp ) {
  6784. merged[ p ] = tmp[ p ];
  6785. }
  6786. }
  6787. return merged;
  6788. }
  6789. function cloneUniformsGroups( src ) {
  6790. const dst = [];
  6791. for ( let u = 0; u < src.length; u ++ ) {
  6792. dst.push( src[ u ].clone() );
  6793. }
  6794. return dst;
  6795. }
  6796. function getUnlitUniformColorSpace( renderer ) {
  6797. if ( renderer.getRenderTarget() === null ) {
  6798. // https://github.com/mrdoob/three.js/pull/23937#issuecomment-1111067398
  6799. return renderer.outputEncoding === sRGBEncoding ? SRGBColorSpace : LinearSRGBColorSpace;
  6800. }
  6801. return LinearSRGBColorSpace;
  6802. }
  6803. // Legacy
  6804. const UniformsUtils = { clone: cloneUniforms, merge: mergeUniforms };
  6805. var default_vertex = "void main() {\n\tgl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n}";
  6806. var default_fragment = "void main() {\n\tgl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );\n}";
  6807. class ShaderMaterial extends Material {
  6808. constructor( parameters ) {
  6809. super();
  6810. this.isShaderMaterial = true;
  6811. this.type = 'ShaderMaterial';
  6812. this.defines = {};
  6813. this.uniforms = {};
  6814. this.uniformsGroups = [];
  6815. this.vertexShader = default_vertex;
  6816. this.fragmentShader = default_fragment;
  6817. this.linewidth = 1;
  6818. this.wireframe = false;
  6819. this.wireframeLinewidth = 1;
  6820. this.fog = false; // set to use scene fog
  6821. this.lights = false; // set to use scene lights
  6822. this.clipping = false; // set to use user-defined clipping planes
  6823. this.extensions = {
  6824. derivatives: false, // set to use derivatives
  6825. fragDepth: false, // set to use fragment depth values
  6826. drawBuffers: false, // set to use draw buffers
  6827. shaderTextureLOD: false // set to use shader texture LOD
  6828. };
  6829. // When rendered geometry doesn't include these attributes but the material does,
  6830. // use these default values in WebGL. This avoids errors when buffer data is missing.
  6831. this.defaultAttributeValues = {
  6832. 'color': [ 1, 1, 1 ],
  6833. 'uv': [ 0, 0 ],
  6834. 'uv2': [ 0, 0 ]
  6835. };
  6836. this.index0AttributeName = undefined;
  6837. this.uniformsNeedUpdate = false;
  6838. this.glslVersion = null;
  6839. if ( parameters !== undefined ) {
  6840. this.setValues( parameters );
  6841. }
  6842. }
  6843. copy( source ) {
  6844. super.copy( source );
  6845. this.fragmentShader = source.fragmentShader;
  6846. this.vertexShader = source.vertexShader;
  6847. this.uniforms = cloneUniforms( source.uniforms );
  6848. this.uniformsGroups = cloneUniformsGroups( source.uniformsGroups );
  6849. this.defines = Object.assign( {}, source.defines );
  6850. this.wireframe = source.wireframe;
  6851. this.wireframeLinewidth = source.wireframeLinewidth;
  6852. this.fog = source.fog;
  6853. this.lights = source.lights;
  6854. this.clipping = source.clipping;
  6855. this.extensions = Object.assign( {}, source.extensions );
  6856. this.glslVersion = source.glslVersion;
  6857. return this;
  6858. }
  6859. toJSON( meta ) {
  6860. const data = super.toJSON( meta );
  6861. data.glslVersion = this.glslVersion;
  6862. data.uniforms = {};
  6863. for ( const name in this.uniforms ) {
  6864. const uniform = this.uniforms[ name ];
  6865. const value = uniform.value;
  6866. if ( value && value.isTexture ) {
  6867. data.uniforms[ name ] = {
  6868. type: 't',
  6869. value: value.toJSON( meta ).uuid
  6870. };
  6871. } else if ( value && value.isColor ) {
  6872. data.uniforms[ name ] = {
  6873. type: 'c',
  6874. value: value.getHex()
  6875. };
  6876. } else if ( value && value.isVector2 ) {
  6877. data.uniforms[ name ] = {
  6878. type: 'v2',
  6879. value: value.toArray()
  6880. };
  6881. } else if ( value && value.isVector3 ) {
  6882. data.uniforms[ name ] = {
  6883. type: 'v3',
  6884. value: value.toArray()
  6885. };
  6886. } else if ( value && value.isVector4 ) {
  6887. data.uniforms[ name ] = {
  6888. type: 'v4',
  6889. value: value.toArray()
  6890. };
  6891. } else if ( value && value.isMatrix3 ) {
  6892. data.uniforms[ name ] = {
  6893. type: 'm3',
  6894. value: value.toArray()
  6895. };
  6896. } else if ( value && value.isMatrix4 ) {
  6897. data.uniforms[ name ] = {
  6898. type: 'm4',
  6899. value: value.toArray()
  6900. };
  6901. } else {
  6902. data.uniforms[ name ] = {
  6903. value: value
  6904. };
  6905. // note: the array variants v2v, v3v, v4v, m4v and tv are not supported so far
  6906. }
  6907. }
  6908. if ( Object.keys( this.defines ).length > 0 ) data.defines = this.defines;
  6909. data.vertexShader = this.vertexShader;
  6910. data.fragmentShader = this.fragmentShader;
  6911. const extensions = {};
  6912. for ( const key in this.extensions ) {
  6913. if ( this.extensions[ key ] === true ) extensions[ key ] = true;
  6914. }
  6915. if ( Object.keys( extensions ).length > 0 ) data.extensions = extensions;
  6916. return data;
  6917. }
  6918. }
  6919. class Camera extends Object3D {
  6920. constructor() {
  6921. super();
  6922. this.isCamera = true;
  6923. this.type = 'Camera';
  6924. this.matrixWorldInverse = new Matrix4();
  6925. this.projectionMatrix = new Matrix4();
  6926. this.projectionMatrixInverse = new Matrix4();
  6927. }
  6928. copy( source, recursive ) {
  6929. super.copy( source, recursive );
  6930. this.matrixWorldInverse.copy( source.matrixWorldInverse );
  6931. this.projectionMatrix.copy( source.projectionMatrix );
  6932. this.projectionMatrixInverse.copy( source.projectionMatrixInverse );
  6933. return this;
  6934. }
  6935. getWorldDirection( target ) {
  6936. this.updateWorldMatrix( true, false );
  6937. const e = this.matrixWorld.elements;
  6938. return target.set( - e[ 8 ], - e[ 9 ], - e[ 10 ] ).normalize();
  6939. }
  6940. updateMatrixWorld( force ) {
  6941. super.updateMatrixWorld( force );
  6942. this.matrixWorldInverse.copy( this.matrixWorld ).invert();
  6943. }
  6944. updateWorldMatrix( updateParents, updateChildren ) {
  6945. super.updateWorldMatrix( updateParents, updateChildren );
  6946. this.matrixWorldInverse.copy( this.matrixWorld ).invert();
  6947. }
  6948. clone() {
  6949. return new this.constructor().copy( this );
  6950. }
  6951. }
  6952. class PerspectiveCamera extends Camera {
  6953. constructor( fov = 50, aspect = 1, near = 0.1, far = 2000 ) {
  6954. super();
  6955. this.isPerspectiveCamera = true;
  6956. this.type = 'PerspectiveCamera';
  6957. this.fov = fov;
  6958. this.zoom = 1;
  6959. this.near = near;
  6960. this.far = far;
  6961. this.focus = 10;
  6962. this.aspect = aspect;
  6963. this.view = null;
  6964. this.filmGauge = 35; // width of the film (default in millimeters)
  6965. this.filmOffset = 0; // horizontal film offset (same unit as gauge)
  6966. this.updateProjectionMatrix();
  6967. }
  6968. copy( source, recursive ) {
  6969. super.copy( source, recursive );
  6970. this.fov = source.fov;
  6971. this.zoom = source.zoom;
  6972. this.near = source.near;
  6973. this.far = source.far;
  6974. this.focus = source.focus;
  6975. this.aspect = source.aspect;
  6976. this.view = source.view === null ? null : Object.assign( {}, source.view );
  6977. this.filmGauge = source.filmGauge;
  6978. this.filmOffset = source.filmOffset;
  6979. return this;
  6980. }
  6981. /**
  6982. * Sets the FOV by focal length in respect to the current .filmGauge.
  6983. *
  6984. * The default film gauge is 35, so that the focal length can be specified for
  6985. * a 35mm (full frame) camera.
  6986. *
  6987. * Values for focal length and film gauge must have the same unit.
  6988. */
  6989. setFocalLength( focalLength ) {
  6990. /** see {@link http://www.bobatkins.com/photography/technical/field_of_view.html} */
  6991. const vExtentSlope = 0.5 * this.getFilmHeight() / focalLength;
  6992. this.fov = RAD2DEG * 2 * Math.atan( vExtentSlope );
  6993. this.updateProjectionMatrix();
  6994. }
  6995. /**
  6996. * Calculates the focal length from the current .fov and .filmGauge.
  6997. */
  6998. getFocalLength() {
  6999. const vExtentSlope = Math.tan( DEG2RAD * 0.5 * this.fov );
  7000. return 0.5 * this.getFilmHeight() / vExtentSlope;
  7001. }
  7002. getEffectiveFOV() {
  7003. return RAD2DEG * 2 * Math.atan(
  7004. Math.tan( DEG2RAD * 0.5 * this.fov ) / this.zoom );
  7005. }
  7006. getFilmWidth() {
  7007. // film not completely covered in portrait format (aspect < 1)
  7008. return this.filmGauge * Math.min( this.aspect, 1 );
  7009. }
  7010. getFilmHeight() {
  7011. // film not completely covered in landscape format (aspect > 1)
  7012. return this.filmGauge / Math.max( this.aspect, 1 );
  7013. }
  7014. /**
  7015. * Sets an offset in a larger frustum. This is useful for multi-window or
  7016. * multi-monitor/multi-machine setups.
  7017. *
  7018. * For example, if you have 3x2 monitors and each monitor is 1920x1080 and
  7019. * the monitors are in grid like this
  7020. *
  7021. * +---+---+---+
  7022. * | A | B | C |
  7023. * +---+---+---+
  7024. * | D | E | F |
  7025. * +---+---+---+
  7026. *
  7027. * then for each monitor you would call it like this
  7028. *
  7029. * const w = 1920;
  7030. * const h = 1080;
  7031. * const fullWidth = w * 3;
  7032. * const fullHeight = h * 2;
  7033. *
  7034. * --A--
  7035. * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 0, w, h );
  7036. * --B--
  7037. * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 0, w, h );
  7038. * --C--
  7039. * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 0, w, h );
  7040. * --D--
  7041. * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 1, w, h );
  7042. * --E--
  7043. * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 1, w, h );
  7044. * --F--
  7045. * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 1, w, h );
  7046. *
  7047. * Note there is no reason monitors have to be the same size or in a grid.
  7048. */
  7049. setViewOffset( fullWidth, fullHeight, x, y, width, height ) {
  7050. this.aspect = fullWidth / fullHeight;
  7051. if ( this.view === null ) {
  7052. this.view = {
  7053. enabled: true,
  7054. fullWidth: 1,
  7055. fullHeight: 1,
  7056. offsetX: 0,
  7057. offsetY: 0,
  7058. width: 1,
  7059. height: 1
  7060. };
  7061. }
  7062. this.view.enabled = true;
  7063. this.view.fullWidth = fullWidth;
  7064. this.view.fullHeight = fullHeight;
  7065. this.view.offsetX = x;
  7066. this.view.offsetY = y;
  7067. this.view.width = width;
  7068. this.view.height = height;
  7069. this.updateProjectionMatrix();
  7070. }
  7071. clearViewOffset() {
  7072. if ( this.view !== null ) {
  7073. this.view.enabled = false;
  7074. }
  7075. this.updateProjectionMatrix();
  7076. }
  7077. updateProjectionMatrix() {
  7078. const near = this.near;
  7079. let top = near * Math.tan( DEG2RAD * 0.5 * this.fov ) / this.zoom;
  7080. let height = 2 * top;
  7081. let width = this.aspect * height;
  7082. let left = - 0.5 * width;
  7083. const view = this.view;
  7084. if ( this.view !== null && this.view.enabled ) {
  7085. const fullWidth = view.fullWidth,
  7086. fullHeight = view.fullHeight;
  7087. left += view.offsetX * width / fullWidth;
  7088. top -= view.offsetY * height / fullHeight;
  7089. width *= view.width / fullWidth;
  7090. height *= view.height / fullHeight;
  7091. }
  7092. const skew = this.filmOffset;
  7093. if ( skew !== 0 ) left += near * skew / this.getFilmWidth();
  7094. this.projectionMatrix.makePerspective( left, left + width, top, top - height, near, this.far );
  7095. this.projectionMatrixInverse.copy( this.projectionMatrix ).invert();
  7096. }
  7097. toJSON( meta ) {
  7098. const data = super.toJSON( meta );
  7099. data.object.fov = this.fov;
  7100. data.object.zoom = this.zoom;
  7101. data.object.near = this.near;
  7102. data.object.far = this.far;
  7103. data.object.focus = this.focus;
  7104. data.object.aspect = this.aspect;
  7105. if ( this.view !== null ) data.object.view = Object.assign( {}, this.view );
  7106. data.object.filmGauge = this.filmGauge;
  7107. data.object.filmOffset = this.filmOffset;
  7108. return data;
  7109. }
  7110. }
  7111. const fov = - 90; // negative fov is not an error
  7112. const aspect = 1;
  7113. class CubeCamera extends Object3D {
  7114. constructor( near, far, renderTarget ) {
  7115. super();
  7116. this.type = 'CubeCamera';
  7117. this.renderTarget = renderTarget;
  7118. const cameraPX = new PerspectiveCamera( fov, aspect, near, far );
  7119. cameraPX.layers = this.layers;
  7120. cameraPX.up.set( 0, 1, 0 );
  7121. cameraPX.lookAt( 1, 0, 0 );
  7122. this.add( cameraPX );
  7123. const cameraNX = new PerspectiveCamera( fov, aspect, near, far );
  7124. cameraNX.layers = this.layers;
  7125. cameraNX.up.set( 0, 1, 0 );
  7126. cameraNX.lookAt( - 1, 0, 0 );
  7127. this.add( cameraNX );
  7128. const cameraPY = new PerspectiveCamera( fov, aspect, near, far );
  7129. cameraPY.layers = this.layers;
  7130. cameraPY.up.set( 0, 0, - 1 );
  7131. cameraPY.lookAt( 0, 1, 0 );
  7132. this.add( cameraPY );
  7133. const cameraNY = new PerspectiveCamera( fov, aspect, near, far );
  7134. cameraNY.layers = this.layers;
  7135. cameraNY.up.set( 0, 0, 1 );
  7136. cameraNY.lookAt( 0, - 1, 0 );
  7137. this.add( cameraNY );
  7138. const cameraPZ = new PerspectiveCamera( fov, aspect, near, far );
  7139. cameraPZ.layers = this.layers;
  7140. cameraPZ.up.set( 0, 1, 0 );
  7141. cameraPZ.lookAt( 0, 0, 1 );
  7142. this.add( cameraPZ );
  7143. const cameraNZ = new PerspectiveCamera( fov, aspect, near, far );
  7144. cameraNZ.layers = this.layers;
  7145. cameraNZ.up.set( 0, 1, 0 );
  7146. cameraNZ.lookAt( 0, 0, - 1 );
  7147. this.add( cameraNZ );
  7148. }
  7149. update( renderer, scene ) {
  7150. if ( this.parent === null ) this.updateMatrixWorld();
  7151. const renderTarget = this.renderTarget;
  7152. const [ cameraPX, cameraNX, cameraPY, cameraNY, cameraPZ, cameraNZ ] = this.children;
  7153. const currentRenderTarget = renderer.getRenderTarget();
  7154. const currentToneMapping = renderer.toneMapping;
  7155. const currentXrEnabled = renderer.xr.enabled;
  7156. renderer.toneMapping = NoToneMapping;
  7157. renderer.xr.enabled = false;
  7158. const generateMipmaps = renderTarget.texture.generateMipmaps;
  7159. renderTarget.texture.generateMipmaps = false;
  7160. renderer.setRenderTarget( renderTarget, 0 );
  7161. renderer.render( scene, cameraPX );
  7162. renderer.setRenderTarget( renderTarget, 1 );
  7163. renderer.render( scene, cameraNX );
  7164. renderer.setRenderTarget( renderTarget, 2 );
  7165. renderer.render( scene, cameraPY );
  7166. renderer.setRenderTarget( renderTarget, 3 );
  7167. renderer.render( scene, cameraNY );
  7168. renderer.setRenderTarget( renderTarget, 4 );
  7169. renderer.render( scene, cameraPZ );
  7170. renderTarget.texture.generateMipmaps = generateMipmaps;
  7171. renderer.setRenderTarget( renderTarget, 5 );
  7172. renderer.render( scene, cameraNZ );
  7173. renderer.setRenderTarget( currentRenderTarget );
  7174. renderer.toneMapping = currentToneMapping;
  7175. renderer.xr.enabled = currentXrEnabled;
  7176. renderTarget.texture.needsPMREMUpdate = true;
  7177. }
  7178. }
  7179. class CubeTexture extends Texture {
  7180. constructor( images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding ) {
  7181. images = images !== undefined ? images : [];
  7182. mapping = mapping !== undefined ? mapping : CubeReflectionMapping;
  7183. super( images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding );
  7184. this.isCubeTexture = true;
  7185. this.flipY = false;
  7186. }
  7187. get images() {
  7188. return this.image;
  7189. }
  7190. set images( value ) {
  7191. this.image = value;
  7192. }
  7193. }
  7194. class WebGLCubeRenderTarget extends WebGLRenderTarget {
  7195. constructor( size = 1, options = {} ) {
  7196. super( size, size, options );
  7197. this.isWebGLCubeRenderTarget = true;
  7198. const image = { width: size, height: size, depth: 1 };
  7199. const images = [ image, image, image, image, image, image ];
  7200. this.texture = new CubeTexture( images, options.mapping, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.encoding );
  7201. // By convention -- likely based on the RenderMan spec from the 1990's -- cube maps are specified by WebGL (and three.js)
  7202. // in a coordinate system in which positive-x is to the right when looking up the positive-z axis -- in other words,
  7203. // in a left-handed coordinate system. By continuing this convention, preexisting cube maps continued to render correctly.
  7204. // three.js uses a right-handed coordinate system. So environment maps used in three.js appear to have px and nx swapped
  7205. // and the flag isRenderTargetTexture controls this conversion. The flip is not required when using WebGLCubeRenderTarget.texture
  7206. // as a cube texture (this is detected when isRenderTargetTexture is set to true for cube textures).
  7207. this.texture.isRenderTargetTexture = true;
  7208. this.texture.generateMipmaps = options.generateMipmaps !== undefined ? options.generateMipmaps : false;
  7209. this.texture.minFilter = options.minFilter !== undefined ? options.minFilter : LinearFilter;
  7210. }
  7211. fromEquirectangularTexture( renderer, texture ) {
  7212. this.texture.type = texture.type;
  7213. this.texture.encoding = texture.encoding;
  7214. this.texture.generateMipmaps = texture.generateMipmaps;
  7215. this.texture.minFilter = texture.minFilter;
  7216. this.texture.magFilter = texture.magFilter;
  7217. const shader = {
  7218. uniforms: {
  7219. tEquirect: { value: null },
  7220. },
  7221. vertexShader: /* glsl */`
  7222. varying vec3 vWorldDirection;
  7223. vec3 transformDirection( in vec3 dir, in mat4 matrix ) {
  7224. return normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );
  7225. }
  7226. void main() {
  7227. vWorldDirection = transformDirection( position, modelMatrix );
  7228. #include <begin_vertex>
  7229. #include <project_vertex>
  7230. }
  7231. `,
  7232. fragmentShader: /* glsl */`
  7233. uniform sampler2D tEquirect;
  7234. varying vec3 vWorldDirection;
  7235. #include <common>
  7236. void main() {
  7237. vec3 direction = normalize( vWorldDirection );
  7238. vec2 sampleUV = equirectUv( direction );
  7239. gl_FragColor = texture2D( tEquirect, sampleUV );
  7240. }
  7241. `
  7242. };
  7243. const geometry = new BoxGeometry( 5, 5, 5 );
  7244. const material = new ShaderMaterial( {
  7245. name: 'CubemapFromEquirect',
  7246. uniforms: cloneUniforms( shader.uniforms ),
  7247. vertexShader: shader.vertexShader,
  7248. fragmentShader: shader.fragmentShader,
  7249. side: BackSide,
  7250. blending: NoBlending
  7251. } );
  7252. material.uniforms.tEquirect.value = texture;
  7253. const mesh = new Mesh( geometry, material );
  7254. const currentMinFilter = texture.minFilter;
  7255. // Avoid blurred poles
  7256. if ( texture.minFilter === LinearMipmapLinearFilter ) texture.minFilter = LinearFilter;
  7257. const camera = new CubeCamera( 1, 10, this );
  7258. camera.update( renderer, mesh );
  7259. texture.minFilter = currentMinFilter;
  7260. mesh.geometry.dispose();
  7261. mesh.material.dispose();
  7262. return this;
  7263. }
  7264. clear( renderer, color, depth, stencil ) {
  7265. const currentRenderTarget = renderer.getRenderTarget();
  7266. for ( let i = 0; i < 6; i ++ ) {
  7267. renderer.setRenderTarget( this, i );
  7268. renderer.clear( color, depth, stencil );
  7269. }
  7270. renderer.setRenderTarget( currentRenderTarget );
  7271. }
  7272. }
  7273. const _vector1 = /*@__PURE__*/ new Vector3();
  7274. const _vector2 = /*@__PURE__*/ new Vector3();
  7275. const _normalMatrix = /*@__PURE__*/ new Matrix3();
  7276. class Plane {
  7277. constructor( normal = new Vector3( 1, 0, 0 ), constant = 0 ) {
  7278. this.isPlane = true;
  7279. // normal is assumed to be normalized
  7280. this.normal = normal;
  7281. this.constant = constant;
  7282. }
  7283. set( normal, constant ) {
  7284. this.normal.copy( normal );
  7285. this.constant = constant;
  7286. return this;
  7287. }
  7288. setComponents( x, y, z, w ) {
  7289. this.normal.set( x, y, z );
  7290. this.constant = w;
  7291. return this;
  7292. }
  7293. setFromNormalAndCoplanarPoint( normal, point ) {
  7294. this.normal.copy( normal );
  7295. this.constant = - point.dot( this.normal );
  7296. return this;
  7297. }
  7298. setFromCoplanarPoints( a, b, c ) {
  7299. const normal = _vector1.subVectors( c, b ).cross( _vector2.subVectors( a, b ) ).normalize();
  7300. // Q: should an error be thrown if normal is zero (e.g. degenerate plane)?
  7301. this.setFromNormalAndCoplanarPoint( normal, a );
  7302. return this;
  7303. }
  7304. copy( plane ) {
  7305. this.normal.copy( plane.normal );
  7306. this.constant = plane.constant;
  7307. return this;
  7308. }
  7309. normalize() {
  7310. // Note: will lead to a divide by zero if the plane is invalid.
  7311. const inverseNormalLength = 1.0 / this.normal.length();
  7312. this.normal.multiplyScalar( inverseNormalLength );
  7313. this.constant *= inverseNormalLength;
  7314. return this;
  7315. }
  7316. negate() {
  7317. this.constant *= - 1;
  7318. this.normal.negate();
  7319. return this;
  7320. }
  7321. distanceToPoint( point ) {
  7322. return this.normal.dot( point ) + this.constant;
  7323. }
  7324. distanceToSphere( sphere ) {
  7325. return this.distanceToPoint( sphere.center ) - sphere.radius;
  7326. }
  7327. projectPoint( point, target ) {
  7328. return target.copy( this.normal ).multiplyScalar( - this.distanceToPoint( point ) ).add( point );
  7329. }
  7330. intersectLine( line, target ) {
  7331. const direction = line.delta( _vector1 );
  7332. const denominator = this.normal.dot( direction );
  7333. if ( denominator === 0 ) {
  7334. // line is coplanar, return origin
  7335. if ( this.distanceToPoint( line.start ) === 0 ) {
  7336. return target.copy( line.start );
  7337. }
  7338. // Unsure if this is the correct method to handle this case.
  7339. return null;
  7340. }
  7341. const t = - ( line.start.dot( this.normal ) + this.constant ) / denominator;
  7342. if ( t < 0 || t > 1 ) {
  7343. return null;
  7344. }
  7345. return target.copy( direction ).multiplyScalar( t ).add( line.start );
  7346. }
  7347. intersectsLine( line ) {
  7348. // Note: this tests if a line intersects the plane, not whether it (or its end-points) are coplanar with it.
  7349. const startSign = this.distanceToPoint( line.start );
  7350. const endSign = this.distanceToPoint( line.end );
  7351. return ( startSign < 0 && endSign > 0 ) || ( endSign < 0 && startSign > 0 );
  7352. }
  7353. intersectsBox( box ) {
  7354. return box.intersectsPlane( this );
  7355. }
  7356. intersectsSphere( sphere ) {
  7357. return sphere.intersectsPlane( this );
  7358. }
  7359. coplanarPoint( target ) {
  7360. return target.copy( this.normal ).multiplyScalar( - this.constant );
  7361. }
  7362. applyMatrix4( matrix, optionalNormalMatrix ) {
  7363. const normalMatrix = optionalNormalMatrix || _normalMatrix.getNormalMatrix( matrix );
  7364. const referencePoint = this.coplanarPoint( _vector1 ).applyMatrix4( matrix );
  7365. const normal = this.normal.applyMatrix3( normalMatrix ).normalize();
  7366. this.constant = - referencePoint.dot( normal );
  7367. return this;
  7368. }
  7369. translate( offset ) {
  7370. this.constant -= offset.dot( this.normal );
  7371. return this;
  7372. }
  7373. equals( plane ) {
  7374. return plane.normal.equals( this.normal ) && ( plane.constant === this.constant );
  7375. }
  7376. clone() {
  7377. return new this.constructor().copy( this );
  7378. }
  7379. }
  7380. const _sphere$2 = /*@__PURE__*/ new Sphere();
  7381. const _vector$7 = /*@__PURE__*/ new Vector3();
  7382. class Frustum {
  7383. constructor( p0 = new Plane(), p1 = new Plane(), p2 = new Plane(), p3 = new Plane(), p4 = new Plane(), p5 = new Plane() ) {
  7384. this.planes = [ p0, p1, p2, p3, p4, p5 ];
  7385. }
  7386. set( p0, p1, p2, p3, p4, p5 ) {
  7387. const planes = this.planes;
  7388. planes[ 0 ].copy( p0 );
  7389. planes[ 1 ].copy( p1 );
  7390. planes[ 2 ].copy( p2 );
  7391. planes[ 3 ].copy( p3 );
  7392. planes[ 4 ].copy( p4 );
  7393. planes[ 5 ].copy( p5 );
  7394. return this;
  7395. }
  7396. copy( frustum ) {
  7397. const planes = this.planes;
  7398. for ( let i = 0; i < 6; i ++ ) {
  7399. planes[ i ].copy( frustum.planes[ i ] );
  7400. }
  7401. return this;
  7402. }
  7403. setFromProjectionMatrix( m ) {
  7404. const planes = this.planes;
  7405. const me = m.elements;
  7406. const me0 = me[ 0 ], me1 = me[ 1 ], me2 = me[ 2 ], me3 = me[ 3 ];
  7407. const me4 = me[ 4 ], me5 = me[ 5 ], me6 = me[ 6 ], me7 = me[ 7 ];
  7408. const me8 = me[ 8 ], me9 = me[ 9 ], me10 = me[ 10 ], me11 = me[ 11 ];
  7409. const me12 = me[ 12 ], me13 = me[ 13 ], me14 = me[ 14 ], me15 = me[ 15 ];
  7410. planes[ 0 ].setComponents( me3 - me0, me7 - me4, me11 - me8, me15 - me12 ).normalize();
  7411. planes[ 1 ].setComponents( me3 + me0, me7 + me4, me11 + me8, me15 + me12 ).normalize();
  7412. planes[ 2 ].setComponents( me3 + me1, me7 + me5, me11 + me9, me15 + me13 ).normalize();
  7413. planes[ 3 ].setComponents( me3 - me1, me7 - me5, me11 - me9, me15 - me13 ).normalize();
  7414. planes[ 4 ].setComponents( me3 - me2, me7 - me6, me11 - me10, me15 - me14 ).normalize();
  7415. planes[ 5 ].setComponents( me3 + me2, me7 + me6, me11 + me10, me15 + me14 ).normalize();
  7416. return this;
  7417. }
  7418. intersectsObject( object ) {
  7419. const geometry = object.geometry;
  7420. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  7421. _sphere$2.copy( geometry.boundingSphere ).applyMatrix4( object.matrixWorld );
  7422. return this.intersectsSphere( _sphere$2 );
  7423. }
  7424. intersectsSprite( sprite ) {
  7425. _sphere$2.center.set( 0, 0, 0 );
  7426. _sphere$2.radius = 0.7071067811865476;
  7427. _sphere$2.applyMatrix4( sprite.matrixWorld );
  7428. return this.intersectsSphere( _sphere$2 );
  7429. }
  7430. intersectsSphere( sphere ) {
  7431. const planes = this.planes;
  7432. const center = sphere.center;
  7433. const negRadius = - sphere.radius;
  7434. for ( let i = 0; i < 6; i ++ ) {
  7435. const distance = planes[ i ].distanceToPoint( center );
  7436. if ( distance < negRadius ) {
  7437. return false;
  7438. }
  7439. }
  7440. return true;
  7441. }
  7442. intersectsBox( box ) {
  7443. const planes = this.planes;
  7444. for ( let i = 0; i < 6; i ++ ) {
  7445. const plane = planes[ i ];
  7446. // corner at max distance
  7447. _vector$7.x = plane.normal.x > 0 ? box.max.x : box.min.x;
  7448. _vector$7.y = plane.normal.y > 0 ? box.max.y : box.min.y;
  7449. _vector$7.z = plane.normal.z > 0 ? box.max.z : box.min.z;
  7450. if ( plane.distanceToPoint( _vector$7 ) < 0 ) {
  7451. return false;
  7452. }
  7453. }
  7454. return true;
  7455. }
  7456. containsPoint( point ) {
  7457. const planes = this.planes;
  7458. for ( let i = 0; i < 6; i ++ ) {
  7459. if ( planes[ i ].distanceToPoint( point ) < 0 ) {
  7460. return false;
  7461. }
  7462. }
  7463. return true;
  7464. }
  7465. clone() {
  7466. return new this.constructor().copy( this );
  7467. }
  7468. }
  7469. function WebGLAnimation() {
  7470. let context = null;
  7471. let isAnimating = false;
  7472. let animationLoop = null;
  7473. let requestId = null;
  7474. function onAnimationFrame( time, frame ) {
  7475. animationLoop( time, frame );
  7476. requestId = context.requestAnimationFrame( onAnimationFrame );
  7477. }
  7478. return {
  7479. start: function () {
  7480. if ( isAnimating === true ) return;
  7481. if ( animationLoop === null ) return;
  7482. requestId = context.requestAnimationFrame( onAnimationFrame );
  7483. isAnimating = true;
  7484. },
  7485. stop: function () {
  7486. context.cancelAnimationFrame( requestId );
  7487. isAnimating = false;
  7488. },
  7489. setAnimationLoop: function ( callback ) {
  7490. animationLoop = callback;
  7491. },
  7492. setContext: function ( value ) {
  7493. context = value;
  7494. }
  7495. };
  7496. }
  7497. function WebGLAttributes( gl, capabilities ) {
  7498. const isWebGL2 = capabilities.isWebGL2;
  7499. const buffers = new WeakMap();
  7500. function createBuffer( attribute, bufferType ) {
  7501. const array = attribute.array;
  7502. const usage = attribute.usage;
  7503. const buffer = gl.createBuffer();
  7504. gl.bindBuffer( bufferType, buffer );
  7505. gl.bufferData( bufferType, array, usage );
  7506. attribute.onUploadCallback();
  7507. let type;
  7508. if ( array instanceof Float32Array ) {
  7509. type = gl.FLOAT;
  7510. } else if ( array instanceof Uint16Array ) {
  7511. if ( attribute.isFloat16BufferAttribute ) {
  7512. if ( isWebGL2 ) {
  7513. type = gl.HALF_FLOAT;
  7514. } else {
  7515. throw new Error( 'THREE.WebGLAttributes: Usage of Float16BufferAttribute requires WebGL2.' );
  7516. }
  7517. } else {
  7518. type = gl.UNSIGNED_SHORT;
  7519. }
  7520. } else if ( array instanceof Int16Array ) {
  7521. type = gl.SHORT;
  7522. } else if ( array instanceof Uint32Array ) {
  7523. type = gl.UNSIGNED_INT;
  7524. } else if ( array instanceof Int32Array ) {
  7525. type = gl.INT;
  7526. } else if ( array instanceof Int8Array ) {
  7527. type = gl.BYTE;
  7528. } else if ( array instanceof Uint8Array ) {
  7529. type = gl.UNSIGNED_BYTE;
  7530. } else if ( array instanceof Uint8ClampedArray ) {
  7531. type = gl.UNSIGNED_BYTE;
  7532. } else {
  7533. throw new Error( 'THREE.WebGLAttributes: Unsupported buffer data format: ' + array );
  7534. }
  7535. return {
  7536. buffer: buffer,
  7537. type: type,
  7538. bytesPerElement: array.BYTES_PER_ELEMENT,
  7539. version: attribute.version
  7540. };
  7541. }
  7542. function updateBuffer( buffer, attribute, bufferType ) {
  7543. const array = attribute.array;
  7544. const updateRange = attribute.updateRange;
  7545. gl.bindBuffer( bufferType, buffer );
  7546. if ( updateRange.count === - 1 ) {
  7547. // Not using update ranges
  7548. gl.bufferSubData( bufferType, 0, array );
  7549. } else {
  7550. if ( isWebGL2 ) {
  7551. gl.bufferSubData( bufferType, updateRange.offset * array.BYTES_PER_ELEMENT,
  7552. array, updateRange.offset, updateRange.count );
  7553. } else {
  7554. gl.bufferSubData( bufferType, updateRange.offset * array.BYTES_PER_ELEMENT,
  7555. array.subarray( updateRange.offset, updateRange.offset + updateRange.count ) );
  7556. }
  7557. updateRange.count = - 1; // reset range
  7558. }
  7559. attribute.onUploadCallback();
  7560. }
  7561. //
  7562. function get( attribute ) {
  7563. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  7564. return buffers.get( attribute );
  7565. }
  7566. function remove( attribute ) {
  7567. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  7568. const data = buffers.get( attribute );
  7569. if ( data ) {
  7570. gl.deleteBuffer( data.buffer );
  7571. buffers.delete( attribute );
  7572. }
  7573. }
  7574. function update( attribute, bufferType ) {
  7575. if ( attribute.isGLBufferAttribute ) {
  7576. const cached = buffers.get( attribute );
  7577. if ( ! cached || cached.version < attribute.version ) {
  7578. buffers.set( attribute, {
  7579. buffer: attribute.buffer,
  7580. type: attribute.type,
  7581. bytesPerElement: attribute.elementSize,
  7582. version: attribute.version
  7583. } );
  7584. }
  7585. return;
  7586. }
  7587. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  7588. const data = buffers.get( attribute );
  7589. if ( data === undefined ) {
  7590. buffers.set( attribute, createBuffer( attribute, bufferType ) );
  7591. } else if ( data.version < attribute.version ) {
  7592. updateBuffer( data.buffer, attribute, bufferType );
  7593. data.version = attribute.version;
  7594. }
  7595. }
  7596. return {
  7597. get: get,
  7598. remove: remove,
  7599. update: update
  7600. };
  7601. }
  7602. class PlaneGeometry extends BufferGeometry {
  7603. constructor( width = 1, height = 1, widthSegments = 1, heightSegments = 1 ) {
  7604. super();
  7605. this.type = 'PlaneGeometry';
  7606. this.parameters = {
  7607. width: width,
  7608. height: height,
  7609. widthSegments: widthSegments,
  7610. heightSegments: heightSegments
  7611. };
  7612. const width_half = width / 2;
  7613. const height_half = height / 2;
  7614. const gridX = Math.floor( widthSegments );
  7615. const gridY = Math.floor( heightSegments );
  7616. const gridX1 = gridX + 1;
  7617. const gridY1 = gridY + 1;
  7618. const segment_width = width / gridX;
  7619. const segment_height = height / gridY;
  7620. //
  7621. const indices = [];
  7622. const vertices = [];
  7623. const normals = [];
  7624. const uvs = [];
  7625. for ( let iy = 0; iy < gridY1; iy ++ ) {
  7626. const y = iy * segment_height - height_half;
  7627. for ( let ix = 0; ix < gridX1; ix ++ ) {
  7628. const x = ix * segment_width - width_half;
  7629. vertices.push( x, - y, 0 );
  7630. normals.push( 0, 0, 1 );
  7631. uvs.push( ix / gridX );
  7632. uvs.push( 1 - ( iy / gridY ) );
  7633. }
  7634. }
  7635. for ( let iy = 0; iy < gridY; iy ++ ) {
  7636. for ( let ix = 0; ix < gridX; ix ++ ) {
  7637. const a = ix + gridX1 * iy;
  7638. const b = ix + gridX1 * ( iy + 1 );
  7639. const c = ( ix + 1 ) + gridX1 * ( iy + 1 );
  7640. const d = ( ix + 1 ) + gridX1 * iy;
  7641. indices.push( a, b, d );
  7642. indices.push( b, c, d );
  7643. }
  7644. }
  7645. this.setIndex( indices );
  7646. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  7647. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  7648. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  7649. }
  7650. static fromJSON( data ) {
  7651. return new PlaneGeometry( data.width, data.height, data.widthSegments, data.heightSegments );
  7652. }
  7653. }
  7654. var alphamap_fragment = "#ifdef USE_ALPHAMAP\n\tdiffuseColor.a *= texture2D( alphaMap, vUv ).g;\n#endif";
  7655. var alphamap_pars_fragment = "#ifdef USE_ALPHAMAP\n\tuniform sampler2D alphaMap;\n#endif";
  7656. var alphatest_fragment = "#ifdef USE_ALPHATEST\n\tif ( diffuseColor.a < alphaTest ) discard;\n#endif";
  7657. var alphatest_pars_fragment = "#ifdef USE_ALPHATEST\n\tuniform float alphaTest;\n#endif";
  7658. var aomap_fragment = "#ifdef USE_AOMAP\n\tfloat ambientOcclusion = ( texture2D( aoMap, vUv2 ).r - 1.0 ) * aoMapIntensity + 1.0;\n\treflectedLight.indirectDiffuse *= ambientOcclusion;\n\t#if defined( USE_ENVMAP ) && defined( STANDARD )\n\t\tfloat dotNV = saturate( dot( geometry.normal, geometry.viewDir ) );\n\t\treflectedLight.indirectSpecular *= computeSpecularOcclusion( dotNV, ambientOcclusion, material.roughness );\n\t#endif\n#endif";
  7659. var aomap_pars_fragment = "#ifdef USE_AOMAP\n\tuniform sampler2D aoMap;\n\tuniform float aoMapIntensity;\n#endif";
  7660. var begin_vertex = "vec3 transformed = vec3( position );";
  7661. var beginnormal_vertex = "vec3 objectNormal = vec3( normal );\n#ifdef USE_TANGENT\n\tvec3 objectTangent = vec3( tangent.xyz );\n#endif";
  7662. var bsdfs = "vec3 BRDF_Lambert( const in vec3 diffuseColor ) {\n\treturn RECIPROCAL_PI * diffuseColor;\n}\nvec3 F_Schlick( const in vec3 f0, const in float f90, const in float dotVH ) {\n\tfloat fresnel = exp2( ( - 5.55473 * dotVH - 6.98316 ) * dotVH );\n\treturn f0 * ( 1.0 - fresnel ) + ( f90 * fresnel );\n}\nfloat F_Schlick( const in float f0, const in float f90, const in float dotVH ) {\n\tfloat fresnel = exp2( ( - 5.55473 * dotVH - 6.98316 ) * dotVH );\n\treturn f0 * ( 1.0 - fresnel ) + ( f90 * fresnel );\n}\nvec3 Schlick_to_F0( const in vec3 f, const in float f90, const in float dotVH ) {\n float x = clamp( 1.0 - dotVH, 0.0, 1.0 );\n float x2 = x * x;\n float x5 = clamp( x * x2 * x2, 0.0, 0.9999 );\n return ( f - vec3( f90 ) * x5 ) / ( 1.0 - x5 );\n}\nfloat V_GGX_SmithCorrelated( const in float alpha, const in float dotNL, const in float dotNV ) {\n\tfloat a2 = pow2( alpha );\n\tfloat gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNV ) );\n\tfloat gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNL ) );\n\treturn 0.5 / max( gv + gl, EPSILON );\n}\nfloat D_GGX( const in float alpha, const in float dotNH ) {\n\tfloat a2 = pow2( alpha );\n\tfloat denom = pow2( dotNH ) * ( a2 - 1.0 ) + 1.0;\n\treturn RECIPROCAL_PI * a2 / pow2( denom );\n}\nvec3 BRDF_GGX( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in vec3 f0, const in float f90, const in float roughness ) {\n\tfloat alpha = pow2( roughness );\n\tvec3 halfDir = normalize( lightDir + viewDir );\n\tfloat dotNL = saturate( dot( normal, lightDir ) );\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tfloat dotNH = saturate( dot( normal, halfDir ) );\n\tfloat dotVH = saturate( dot( viewDir, halfDir ) );\n\tvec3 F = F_Schlick( f0, f90, dotVH );\n\tfloat V = V_GGX_SmithCorrelated( alpha, dotNL, dotNV );\n\tfloat D = D_GGX( alpha, dotNH );\n\treturn F * ( V * D );\n}\n#ifdef USE_IRIDESCENCE\n\tvec3 BRDF_GGX_Iridescence( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in vec3 f0, const in float f90, const in float iridescence, const in vec3 iridescenceFresnel, const in float roughness ) {\n\t\tfloat alpha = pow2( roughness );\n\t\tvec3 halfDir = normalize( lightDir + viewDir );\n\t\tfloat dotNL = saturate( dot( normal, lightDir ) );\n\t\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\t\tfloat dotNH = saturate( dot( normal, halfDir ) );\n\t\tfloat dotVH = saturate( dot( viewDir, halfDir ) );\n\t\tvec3 F = mix( F_Schlick( f0, f90, dotVH ), iridescenceFresnel, iridescence );\n\t\tfloat V = V_GGX_SmithCorrelated( alpha, dotNL, dotNV );\n\t\tfloat D = D_GGX( alpha, dotNH );\n\t\treturn F * ( V * D );\n\t}\n#endif\nvec2 LTC_Uv( const in vec3 N, const in vec3 V, const in float roughness ) {\n\tconst float LUT_SIZE = 64.0;\n\tconst float LUT_SCALE = ( LUT_SIZE - 1.0 ) / LUT_SIZE;\n\tconst float LUT_BIAS = 0.5 / LUT_SIZE;\n\tfloat dotNV = saturate( dot( N, V ) );\n\tvec2 uv = vec2( roughness, sqrt( 1.0 - dotNV ) );\n\tuv = uv * LUT_SCALE + LUT_BIAS;\n\treturn uv;\n}\nfloat LTC_ClippedSphereFormFactor( const in vec3 f ) {\n\tfloat l = length( f );\n\treturn max( ( l * l + f.z ) / ( l + 1.0 ), 0.0 );\n}\nvec3 LTC_EdgeVectorFormFactor( const in vec3 v1, const in vec3 v2 ) {\n\tfloat x = dot( v1, v2 );\n\tfloat y = abs( x );\n\tfloat a = 0.8543985 + ( 0.4965155 + 0.0145206 * y ) * y;\n\tfloat b = 3.4175940 + ( 4.1616724 + y ) * y;\n\tfloat v = a / b;\n\tfloat theta_sintheta = ( x > 0.0 ) ? v : 0.5 * inversesqrt( max( 1.0 - x * x, 1e-7 ) ) - v;\n\treturn cross( v1, v2 ) * theta_sintheta;\n}\nvec3 LTC_Evaluate( const in vec3 N, const in vec3 V, const in vec3 P, const in mat3 mInv, const in vec3 rectCoords[ 4 ] ) {\n\tvec3 v1 = rectCoords[ 1 ] - rectCoords[ 0 ];\n\tvec3 v2 = rectCoords[ 3 ] - rectCoords[ 0 ];\n\tvec3 lightNormal = cross( v1, v2 );\n\tif( dot( lightNormal, P - rectCoords[ 0 ] ) < 0.0 ) return vec3( 0.0 );\n\tvec3 T1, T2;\n\tT1 = normalize( V - N * dot( V, N ) );\n\tT2 = - cross( N, T1 );\n\tmat3 mat = mInv * transposeMat3( mat3( T1, T2, N ) );\n\tvec3 coords[ 4 ];\n\tcoords[ 0 ] = mat * ( rectCoords[ 0 ] - P );\n\tcoords[ 1 ] = mat * ( rectCoords[ 1 ] - P );\n\tcoords[ 2 ] = mat * ( rectCoords[ 2 ] - P );\n\tcoords[ 3 ] = mat * ( rectCoords[ 3 ] - P );\n\tcoords[ 0 ] = normalize( coords[ 0 ] );\n\tcoords[ 1 ] = normalize( coords[ 1 ] );\n\tcoords[ 2 ] = normalize( coords[ 2 ] );\n\tcoords[ 3 ] = normalize( coords[ 3 ] );\n\tvec3 vectorFormFactor = vec3( 0.0 );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 0 ], coords[ 1 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 1 ], coords[ 2 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 2 ], coords[ 3 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 3 ], coords[ 0 ] );\n\tfloat result = LTC_ClippedSphereFormFactor( vectorFormFactor );\n\treturn vec3( result );\n}\nfloat G_BlinnPhong_Implicit( ) {\n\treturn 0.25;\n}\nfloat D_BlinnPhong( const in float shininess, const in float dotNH ) {\n\treturn RECIPROCAL_PI * ( shininess * 0.5 + 1.0 ) * pow( dotNH, shininess );\n}\nvec3 BRDF_BlinnPhong( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in vec3 specularColor, const in float shininess ) {\n\tvec3 halfDir = normalize( lightDir + viewDir );\n\tfloat dotNH = saturate( dot( normal, halfDir ) );\n\tfloat dotVH = saturate( dot( viewDir, halfDir ) );\n\tvec3 F = F_Schlick( specularColor, 1.0, dotVH );\n\tfloat G = G_BlinnPhong_Implicit( );\n\tfloat D = D_BlinnPhong( shininess, dotNH );\n\treturn F * ( G * D );\n}\n#if defined( USE_SHEEN )\nfloat D_Charlie( float roughness, float dotNH ) {\n\tfloat alpha = pow2( roughness );\n\tfloat invAlpha = 1.0 / alpha;\n\tfloat cos2h = dotNH * dotNH;\n\tfloat sin2h = max( 1.0 - cos2h, 0.0078125 );\n\treturn ( 2.0 + invAlpha ) * pow( sin2h, invAlpha * 0.5 ) / ( 2.0 * PI );\n}\nfloat V_Neubelt( float dotNV, float dotNL ) {\n\treturn saturate( 1.0 / ( 4.0 * ( dotNL + dotNV - dotNL * dotNV ) ) );\n}\nvec3 BRDF_Sheen( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, vec3 sheenColor, const in float sheenRoughness ) {\n\tvec3 halfDir = normalize( lightDir + viewDir );\n\tfloat dotNL = saturate( dot( normal, lightDir ) );\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tfloat dotNH = saturate( dot( normal, halfDir ) );\n\tfloat D = D_Charlie( sheenRoughness, dotNH );\n\tfloat V = V_Neubelt( dotNV, dotNL );\n\treturn sheenColor * ( D * V );\n}\n#endif";
  7663. var iridescence_fragment = "#ifdef USE_IRIDESCENCE\n\tconst mat3 XYZ_TO_REC709 = mat3(\n\t\t 3.2404542, -0.9692660, 0.0556434,\n\t\t-1.5371385, 1.8760108, -0.2040259,\n\t\t-0.4985314, 0.0415560, 1.0572252\n\t);\n\tvec3 Fresnel0ToIor( vec3 fresnel0 ) {\n\t\tvec3 sqrtF0 = sqrt( fresnel0 );\n\t\treturn ( vec3( 1.0 ) + sqrtF0 ) / ( vec3( 1.0 ) - sqrtF0 );\n\t}\n\tvec3 IorToFresnel0( vec3 transmittedIor, float incidentIor ) {\n\t\treturn pow2( ( transmittedIor - vec3( incidentIor ) ) / ( transmittedIor + vec3( incidentIor ) ) );\n\t}\n\tfloat IorToFresnel0( float transmittedIor, float incidentIor ) {\n\t\treturn pow2( ( transmittedIor - incidentIor ) / ( transmittedIor + incidentIor ));\n\t}\n\tvec3 evalSensitivity( float OPD, vec3 shift ) {\n\t\tfloat phase = 2.0 * PI * OPD * 1.0e-9;\n\t\tvec3 val = vec3( 5.4856e-13, 4.4201e-13, 5.2481e-13 );\n\t\tvec3 pos = vec3( 1.6810e+06, 1.7953e+06, 2.2084e+06 );\n\t\tvec3 var = vec3( 4.3278e+09, 9.3046e+09, 6.6121e+09 );\n\t\tvec3 xyz = val * sqrt( 2.0 * PI * var ) * cos( pos * phase + shift ) * exp( - pow2( phase ) * var );\n\t\txyz.x += 9.7470e-14 * sqrt( 2.0 * PI * 4.5282e+09 ) * cos( 2.2399e+06 * phase + shift[ 0 ] ) * exp( - 4.5282e+09 * pow2( phase ) );\n\t\txyz /= 1.0685e-7;\n\t\tvec3 rgb = XYZ_TO_REC709 * xyz;\n\t\treturn rgb;\n\t}\n\tvec3 evalIridescence( float outsideIOR, float eta2, float cosTheta1, float thinFilmThickness, vec3 baseF0 ) {\n\t\tvec3 I;\n\t\tfloat iridescenceIOR = mix( outsideIOR, eta2, smoothstep( 0.0, 0.03, thinFilmThickness ) );\n\t\tfloat sinTheta2Sq = pow2( outsideIOR / iridescenceIOR ) * ( 1.0 - pow2( cosTheta1 ) );\n\t\tfloat cosTheta2Sq = 1.0 - sinTheta2Sq;\n\t\tif ( cosTheta2Sq < 0.0 ) {\n\t\t\t return vec3( 1.0 );\n\t\t}\n\t\tfloat cosTheta2 = sqrt( cosTheta2Sq );\n\t\tfloat R0 = IorToFresnel0( iridescenceIOR, outsideIOR );\n\t\tfloat R12 = F_Schlick( R0, 1.0, cosTheta1 );\n\t\tfloat R21 = R12;\n\t\tfloat T121 = 1.0 - R12;\n\t\tfloat phi12 = 0.0;\n\t\tif ( iridescenceIOR < outsideIOR ) phi12 = PI;\n\t\tfloat phi21 = PI - phi12;\n\t\tvec3 baseIOR = Fresnel0ToIor( clamp( baseF0, 0.0, 0.9999 ) );\t\tvec3 R1 = IorToFresnel0( baseIOR, iridescenceIOR );\n\t\tvec3 R23 = F_Schlick( R1, 1.0, cosTheta2 );\n\t\tvec3 phi23 = vec3( 0.0 );\n\t\tif ( baseIOR[ 0 ] < iridescenceIOR ) phi23[ 0 ] = PI;\n\t\tif ( baseIOR[ 1 ] < iridescenceIOR ) phi23[ 1 ] = PI;\n\t\tif ( baseIOR[ 2 ] < iridescenceIOR ) phi23[ 2 ] = PI;\n\t\tfloat OPD = 2.0 * iridescenceIOR * thinFilmThickness * cosTheta2;\n\t\tvec3 phi = vec3( phi21 ) + phi23;\n\t\tvec3 R123 = clamp( R12 * R23, 1e-5, 0.9999 );\n\t\tvec3 r123 = sqrt( R123 );\n\t\tvec3 Rs = pow2( T121 ) * R23 / ( vec3( 1.0 ) - R123 );\n\t\tvec3 C0 = R12 + Rs;\n\t\tI = C0;\n\t\tvec3 Cm = Rs - T121;\n\t\tfor ( int m = 1; m <= 2; ++ m ) {\n\t\t\tCm *= r123;\n\t\t\tvec3 Sm = 2.0 * evalSensitivity( float( m ) * OPD, float( m ) * phi );\n\t\t\tI += Cm * Sm;\n\t\t}\n\t\treturn max( I, vec3( 0.0 ) );\n\t}\n#endif";
  7664. var bumpmap_pars_fragment = "#ifdef USE_BUMPMAP\n\tuniform sampler2D bumpMap;\n\tuniform float bumpScale;\n\tvec2 dHdxy_fwd() {\n\t\tvec2 dSTdx = dFdx( vUv );\n\t\tvec2 dSTdy = dFdy( vUv );\n\t\tfloat Hll = bumpScale * texture2D( bumpMap, vUv ).x;\n\t\tfloat dBx = bumpScale * texture2D( bumpMap, vUv + dSTdx ).x - Hll;\n\t\tfloat dBy = bumpScale * texture2D( bumpMap, vUv + dSTdy ).x - Hll;\n\t\treturn vec2( dBx, dBy );\n\t}\n\tvec3 perturbNormalArb( vec3 surf_pos, vec3 surf_norm, vec2 dHdxy, float faceDirection ) {\n\t\tvec3 vSigmaX = dFdx( surf_pos.xyz );\n\t\tvec3 vSigmaY = dFdy( surf_pos.xyz );\n\t\tvec3 vN = surf_norm;\n\t\tvec3 R1 = cross( vSigmaY, vN );\n\t\tvec3 R2 = cross( vN, vSigmaX );\n\t\tfloat fDet = dot( vSigmaX, R1 ) * faceDirection;\n\t\tvec3 vGrad = sign( fDet ) * ( dHdxy.x * R1 + dHdxy.y * R2 );\n\t\treturn normalize( abs( fDet ) * surf_norm - vGrad );\n\t}\n#endif";
  7665. var clipping_planes_fragment = "#if NUM_CLIPPING_PLANES > 0\n\tvec4 plane;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < UNION_CLIPPING_PLANES; i ++ ) {\n\t\tplane = clippingPlanes[ i ];\n\t\tif ( dot( vClipPosition, plane.xyz ) > plane.w ) discard;\n\t}\n\t#pragma unroll_loop_end\n\t#if UNION_CLIPPING_PLANES < NUM_CLIPPING_PLANES\n\t\tbool clipped = true;\n\t\t#pragma unroll_loop_start\n\t\tfor ( int i = UNION_CLIPPING_PLANES; i < NUM_CLIPPING_PLANES; i ++ ) {\n\t\t\tplane = clippingPlanes[ i ];\n\t\t\tclipped = ( dot( vClipPosition, plane.xyz ) > plane.w ) && clipped;\n\t\t}\n\t\t#pragma unroll_loop_end\n\t\tif ( clipped ) discard;\n\t#endif\n#endif";
  7666. var clipping_planes_pars_fragment = "#if NUM_CLIPPING_PLANES > 0\n\tvarying vec3 vClipPosition;\n\tuniform vec4 clippingPlanes[ NUM_CLIPPING_PLANES ];\n#endif";
  7667. var clipping_planes_pars_vertex = "#if NUM_CLIPPING_PLANES > 0\n\tvarying vec3 vClipPosition;\n#endif";
  7668. var clipping_planes_vertex = "#if NUM_CLIPPING_PLANES > 0\n\tvClipPosition = - mvPosition.xyz;\n#endif";
  7669. var color_fragment = "#if defined( USE_COLOR_ALPHA )\n\tdiffuseColor *= vColor;\n#elif defined( USE_COLOR )\n\tdiffuseColor.rgb *= vColor;\n#endif";
  7670. var color_pars_fragment = "#if defined( USE_COLOR_ALPHA )\n\tvarying vec4 vColor;\n#elif defined( USE_COLOR )\n\tvarying vec3 vColor;\n#endif";
  7671. var color_pars_vertex = "#if defined( USE_COLOR_ALPHA )\n\tvarying vec4 vColor;\n#elif defined( USE_COLOR ) || defined( USE_INSTANCING_COLOR )\n\tvarying vec3 vColor;\n#endif";
  7672. var color_vertex = "#if defined( USE_COLOR_ALPHA )\n\tvColor = vec4( 1.0 );\n#elif defined( USE_COLOR ) || defined( USE_INSTANCING_COLOR )\n\tvColor = vec3( 1.0 );\n#endif\n#ifdef USE_COLOR\n\tvColor *= color;\n#endif\n#ifdef USE_INSTANCING_COLOR\n\tvColor.xyz *= instanceColor.xyz;\n#endif";
  7673. var common = "#define PI 3.141592653589793\n#define PI2 6.283185307179586\n#define PI_HALF 1.5707963267948966\n#define RECIPROCAL_PI 0.3183098861837907\n#define RECIPROCAL_PI2 0.15915494309189535\n#define EPSILON 1e-6\n#ifndef saturate\n#define saturate( a ) clamp( a, 0.0, 1.0 )\n#endif\n#define whiteComplement( a ) ( 1.0 - saturate( a ) )\nfloat pow2( const in float x ) { return x*x; }\nvec3 pow2( const in vec3 x ) { return x*x; }\nfloat pow3( const in float x ) { return x*x*x; }\nfloat pow4( const in float x ) { float x2 = x*x; return x2*x2; }\nfloat max3( const in vec3 v ) { return max( max( v.x, v.y ), v.z ); }\nfloat average( const in vec3 v ) { return dot( v, vec3( 0.3333333 ) ); }\nhighp float rand( const in vec2 uv ) {\n\tconst highp float a = 12.9898, b = 78.233, c = 43758.5453;\n\thighp float dt = dot( uv.xy, vec2( a,b ) ), sn = mod( dt, PI );\n\treturn fract( sin( sn ) * c );\n}\n#ifdef HIGH_PRECISION\n\tfloat precisionSafeLength( vec3 v ) { return length( v ); }\n#else\n\tfloat precisionSafeLength( vec3 v ) {\n\t\tfloat maxComponent = max3( abs( v ) );\n\t\treturn length( v / maxComponent ) * maxComponent;\n\t}\n#endif\nstruct IncidentLight {\n\tvec3 color;\n\tvec3 direction;\n\tbool visible;\n};\nstruct ReflectedLight {\n\tvec3 directDiffuse;\n\tvec3 directSpecular;\n\tvec3 indirectDiffuse;\n\tvec3 indirectSpecular;\n};\nstruct GeometricContext {\n\tvec3 position;\n\tvec3 normal;\n\tvec3 viewDir;\n#ifdef USE_CLEARCOAT\n\tvec3 clearcoatNormal;\n#endif\n};\nvec3 transformDirection( in vec3 dir, in mat4 matrix ) {\n\treturn normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );\n}\nvec3 inverseTransformDirection( in vec3 dir, in mat4 matrix ) {\n\treturn normalize( ( vec4( dir, 0.0 ) * matrix ).xyz );\n}\nmat3 transposeMat3( const in mat3 m ) {\n\tmat3 tmp;\n\ttmp[ 0 ] = vec3( m[ 0 ].x, m[ 1 ].x, m[ 2 ].x );\n\ttmp[ 1 ] = vec3( m[ 0 ].y, m[ 1 ].y, m[ 2 ].y );\n\ttmp[ 2 ] = vec3( m[ 0 ].z, m[ 1 ].z, m[ 2 ].z );\n\treturn tmp;\n}\nfloat luminance( const in vec3 rgb ) {\n\tconst vec3 weights = vec3( 0.2126729, 0.7151522, 0.0721750 );\n\treturn dot( weights, rgb );\n}\nbool isPerspectiveMatrix( mat4 m ) {\n\treturn m[ 2 ][ 3 ] == - 1.0;\n}\nvec2 equirectUv( in vec3 dir ) {\n\tfloat u = atan( dir.z, dir.x ) * RECIPROCAL_PI2 + 0.5;\n\tfloat v = asin( clamp( dir.y, - 1.0, 1.0 ) ) * RECIPROCAL_PI + 0.5;\n\treturn vec2( u, v );\n}";
  7674. var cube_uv_reflection_fragment = "#ifdef ENVMAP_TYPE_CUBE_UV\n\t#define cubeUV_minMipLevel 4.0\n\t#define cubeUV_minTileSize 16.0\n\tfloat getFace( vec3 direction ) {\n\t\tvec3 absDirection = abs( direction );\n\t\tfloat face = - 1.0;\n\t\tif ( absDirection.x > absDirection.z ) {\n\t\t\tif ( absDirection.x > absDirection.y )\n\t\t\t\tface = direction.x > 0.0 ? 0.0 : 3.0;\n\t\t\telse\n\t\t\t\tface = direction.y > 0.0 ? 1.0 : 4.0;\n\t\t} else {\n\t\t\tif ( absDirection.z > absDirection.y )\n\t\t\t\tface = direction.z > 0.0 ? 2.0 : 5.0;\n\t\t\telse\n\t\t\t\tface = direction.y > 0.0 ? 1.0 : 4.0;\n\t\t}\n\t\treturn face;\n\t}\n\tvec2 getUV( vec3 direction, float face ) {\n\t\tvec2 uv;\n\t\tif ( face == 0.0 ) {\n\t\t\tuv = vec2( direction.z, direction.y ) / abs( direction.x );\n\t\t} else if ( face == 1.0 ) {\n\t\t\tuv = vec2( - direction.x, - direction.z ) / abs( direction.y );\n\t\t} else if ( face == 2.0 ) {\n\t\t\tuv = vec2( - direction.x, direction.y ) / abs( direction.z );\n\t\t} else if ( face == 3.0 ) {\n\t\t\tuv = vec2( - direction.z, direction.y ) / abs( direction.x );\n\t\t} else if ( face == 4.0 ) {\n\t\t\tuv = vec2( - direction.x, direction.z ) / abs( direction.y );\n\t\t} else {\n\t\t\tuv = vec2( direction.x, direction.y ) / abs( direction.z );\n\t\t}\n\t\treturn 0.5 * ( uv + 1.0 );\n\t}\n\tvec3 bilinearCubeUV( sampler2D envMap, vec3 direction, float mipInt ) {\n\t\tfloat face = getFace( direction );\n\t\tfloat filterInt = max( cubeUV_minMipLevel - mipInt, 0.0 );\n\t\tmipInt = max( mipInt, cubeUV_minMipLevel );\n\t\tfloat faceSize = exp2( mipInt );\n\t\thighp vec2 uv = getUV( direction, face ) * ( faceSize - 2.0 ) + 1.0;\n\t\tif ( face > 2.0 ) {\n\t\t\tuv.y += faceSize;\n\t\t\tface -= 3.0;\n\t\t}\n\t\tuv.x += face * faceSize;\n\t\tuv.x += filterInt * 3.0 * cubeUV_minTileSize;\n\t\tuv.y += 4.0 * ( exp2( CUBEUV_MAX_MIP ) - faceSize );\n\t\tuv.x *= CUBEUV_TEXEL_WIDTH;\n\t\tuv.y *= CUBEUV_TEXEL_HEIGHT;\n\t\t#ifdef texture2DGradEXT\n\t\t\treturn texture2DGradEXT( envMap, uv, vec2( 0.0 ), vec2( 0.0 ) ).rgb;\n\t\t#else\n\t\t\treturn texture2D( envMap, uv ).rgb;\n\t\t#endif\n\t}\n\t#define cubeUV_r0 1.0\n\t#define cubeUV_v0 0.339\n\t#define cubeUV_m0 - 2.0\n\t#define cubeUV_r1 0.8\n\t#define cubeUV_v1 0.276\n\t#define cubeUV_m1 - 1.0\n\t#define cubeUV_r4 0.4\n\t#define cubeUV_v4 0.046\n\t#define cubeUV_m4 2.0\n\t#define cubeUV_r5 0.305\n\t#define cubeUV_v5 0.016\n\t#define cubeUV_m5 3.0\n\t#define cubeUV_r6 0.21\n\t#define cubeUV_v6 0.0038\n\t#define cubeUV_m6 4.0\n\tfloat roughnessToMip( float roughness ) {\n\t\tfloat mip = 0.0;\n\t\tif ( roughness >= cubeUV_r1 ) {\n\t\t\tmip = ( cubeUV_r0 - roughness ) * ( cubeUV_m1 - cubeUV_m0 ) / ( cubeUV_r0 - cubeUV_r1 ) + cubeUV_m0;\n\t\t} else if ( roughness >= cubeUV_r4 ) {\n\t\t\tmip = ( cubeUV_r1 - roughness ) * ( cubeUV_m4 - cubeUV_m1 ) / ( cubeUV_r1 - cubeUV_r4 ) + cubeUV_m1;\n\t\t} else if ( roughness >= cubeUV_r5 ) {\n\t\t\tmip = ( cubeUV_r4 - roughness ) * ( cubeUV_m5 - cubeUV_m4 ) / ( cubeUV_r4 - cubeUV_r5 ) + cubeUV_m4;\n\t\t} else if ( roughness >= cubeUV_r6 ) {\n\t\t\tmip = ( cubeUV_r5 - roughness ) * ( cubeUV_m6 - cubeUV_m5 ) / ( cubeUV_r5 - cubeUV_r6 ) + cubeUV_m5;\n\t\t} else {\n\t\t\tmip = - 2.0 * log2( 1.16 * roughness );\t\t}\n\t\treturn mip;\n\t}\n\tvec4 textureCubeUV( sampler2D envMap, vec3 sampleDir, float roughness ) {\n\t\tfloat mip = clamp( roughnessToMip( roughness ), cubeUV_m0, CUBEUV_MAX_MIP );\n\t\tfloat mipF = fract( mip );\n\t\tfloat mipInt = floor( mip );\n\t\tvec3 color0 = bilinearCubeUV( envMap, sampleDir, mipInt );\n\t\tif ( mipF == 0.0 ) {\n\t\t\treturn vec4( color0, 1.0 );\n\t\t} else {\n\t\t\tvec3 color1 = bilinearCubeUV( envMap, sampleDir, mipInt + 1.0 );\n\t\t\treturn vec4( mix( color0, color1, mipF ), 1.0 );\n\t\t}\n\t}\n#endif";
  7675. var defaultnormal_vertex = "vec3 transformedNormal = objectNormal;\n#ifdef USE_INSTANCING\n\tmat3 m = mat3( instanceMatrix );\n\ttransformedNormal /= vec3( dot( m[ 0 ], m[ 0 ] ), dot( m[ 1 ], m[ 1 ] ), dot( m[ 2 ], m[ 2 ] ) );\n\ttransformedNormal = m * transformedNormal;\n#endif\ntransformedNormal = normalMatrix * transformedNormal;\n#ifdef FLIP_SIDED\n\ttransformedNormal = - transformedNormal;\n#endif\n#ifdef USE_TANGENT\n\tvec3 transformedTangent = ( modelViewMatrix * vec4( objectTangent, 0.0 ) ).xyz;\n\t#ifdef FLIP_SIDED\n\t\ttransformedTangent = - transformedTangent;\n\t#endif\n#endif";
  7676. var displacementmap_pars_vertex = "#ifdef USE_DISPLACEMENTMAP\n\tuniform sampler2D displacementMap;\n\tuniform float displacementScale;\n\tuniform float displacementBias;\n#endif";
  7677. var displacementmap_vertex = "#ifdef USE_DISPLACEMENTMAP\n\ttransformed += normalize( objectNormal ) * ( texture2D( displacementMap, vUv ).x * displacementScale + displacementBias );\n#endif";
  7678. var emissivemap_fragment = "#ifdef USE_EMISSIVEMAP\n\tvec4 emissiveColor = texture2D( emissiveMap, vUv );\n\ttotalEmissiveRadiance *= emissiveColor.rgb;\n#endif";
  7679. var emissivemap_pars_fragment = "#ifdef USE_EMISSIVEMAP\n\tuniform sampler2D emissiveMap;\n#endif";
  7680. var encodings_fragment = "gl_FragColor = linearToOutputTexel( gl_FragColor );";
  7681. var encodings_pars_fragment = "vec4 LinearToLinear( in vec4 value ) {\n\treturn value;\n}\nvec4 LinearTosRGB( in vec4 value ) {\n\treturn vec4( mix( pow( value.rgb, vec3( 0.41666 ) ) * 1.055 - vec3( 0.055 ), value.rgb * 12.92, vec3( lessThanEqual( value.rgb, vec3( 0.0031308 ) ) ) ), value.a );\n}";
  7682. var envmap_fragment = "#ifdef USE_ENVMAP\n\t#ifdef ENV_WORLDPOS\n\t\tvec3 cameraToFrag;\n\t\tif ( isOrthographic ) {\n\t\t\tcameraToFrag = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) );\n\t\t} else {\n\t\t\tcameraToFrag = normalize( vWorldPosition - cameraPosition );\n\t\t}\n\t\tvec3 worldNormal = inverseTransformDirection( normal, viewMatrix );\n\t\t#ifdef ENVMAP_MODE_REFLECTION\n\t\t\tvec3 reflectVec = reflect( cameraToFrag, worldNormal );\n\t\t#else\n\t\t\tvec3 reflectVec = refract( cameraToFrag, worldNormal, refractionRatio );\n\t\t#endif\n\t#else\n\t\tvec3 reflectVec = vReflect;\n\t#endif\n\t#ifdef ENVMAP_TYPE_CUBE\n\t\tvec4 envColor = textureCube( envMap, vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );\n\t#else\n\t\tvec4 envColor = vec4( 0.0 );\n\t#endif\n\t#ifdef ENVMAP_BLENDING_MULTIPLY\n\t\toutgoingLight = mix( outgoingLight, outgoingLight * envColor.xyz, specularStrength * reflectivity );\n\t#elif defined( ENVMAP_BLENDING_MIX )\n\t\toutgoingLight = mix( outgoingLight, envColor.xyz, specularStrength * reflectivity );\n\t#elif defined( ENVMAP_BLENDING_ADD )\n\t\toutgoingLight += envColor.xyz * specularStrength * reflectivity;\n\t#endif\n#endif";
  7683. var envmap_common_pars_fragment = "#ifdef USE_ENVMAP\n\tuniform float envMapIntensity;\n\tuniform float flipEnvMap;\n\t#ifdef ENVMAP_TYPE_CUBE\n\t\tuniform samplerCube envMap;\n\t#else\n\t\tuniform sampler2D envMap;\n\t#endif\n\t\n#endif";
  7684. var envmap_pars_fragment = "#ifdef USE_ENVMAP\n\tuniform float reflectivity;\n\t#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) || defined( LAMBERT )\n\t\t#define ENV_WORLDPOS\n\t#endif\n\t#ifdef ENV_WORLDPOS\n\t\tvarying vec3 vWorldPosition;\n\t\tuniform float refractionRatio;\n\t#else\n\t\tvarying vec3 vReflect;\n\t#endif\n#endif";
  7685. var envmap_pars_vertex = "#ifdef USE_ENVMAP\n\t#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) || defined( LAMBERT )\n\t\t#define ENV_WORLDPOS\n\t#endif\n\t#ifdef ENV_WORLDPOS\n\t\t\n\t\tvarying vec3 vWorldPosition;\n\t#else\n\t\tvarying vec3 vReflect;\n\t\tuniform float refractionRatio;\n\t#endif\n#endif";
  7686. var envmap_vertex = "#ifdef USE_ENVMAP\n\t#ifdef ENV_WORLDPOS\n\t\tvWorldPosition = worldPosition.xyz;\n\t#else\n\t\tvec3 cameraToVertex;\n\t\tif ( isOrthographic ) {\n\t\t\tcameraToVertex = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) );\n\t\t} else {\n\t\t\tcameraToVertex = normalize( worldPosition.xyz - cameraPosition );\n\t\t}\n\t\tvec3 worldNormal = inverseTransformDirection( transformedNormal, viewMatrix );\n\t\t#ifdef ENVMAP_MODE_REFLECTION\n\t\t\tvReflect = reflect( cameraToVertex, worldNormal );\n\t\t#else\n\t\t\tvReflect = refract( cameraToVertex, worldNormal, refractionRatio );\n\t\t#endif\n\t#endif\n#endif";
  7687. var fog_vertex = "#ifdef USE_FOG\n\tvFogDepth = - mvPosition.z;\n#endif";
  7688. var fog_pars_vertex = "#ifdef USE_FOG\n\tvarying float vFogDepth;\n#endif";
  7689. var fog_fragment = "#ifdef USE_FOG\n\t#ifdef FOG_EXP2\n\t\tfloat fogFactor = 1.0 - exp( - fogDensity * fogDensity * vFogDepth * vFogDepth );\n\t#else\n\t\tfloat fogFactor = smoothstep( fogNear, fogFar, vFogDepth );\n\t#endif\n\tgl_FragColor.rgb = mix( gl_FragColor.rgb, fogColor, fogFactor );\n#endif";
  7690. var fog_pars_fragment = "#ifdef USE_FOG\n\tuniform vec3 fogColor;\n\tvarying float vFogDepth;\n\t#ifdef FOG_EXP2\n\t\tuniform float fogDensity;\n\t#else\n\t\tuniform float fogNear;\n\t\tuniform float fogFar;\n\t#endif\n#endif";
  7691. var gradientmap_pars_fragment = "#ifdef USE_GRADIENTMAP\n\tuniform sampler2D gradientMap;\n#endif\nvec3 getGradientIrradiance( vec3 normal, vec3 lightDirection ) {\n\tfloat dotNL = dot( normal, lightDirection );\n\tvec2 coord = vec2( dotNL * 0.5 + 0.5, 0.0 );\n\t#ifdef USE_GRADIENTMAP\n\t\treturn vec3( texture2D( gradientMap, coord ).r );\n\t#else\n\t\tvec2 fw = fwidth( coord ) * 0.5;\n\t\treturn mix( vec3( 0.7 ), vec3( 1.0 ), smoothstep( 0.7 - fw.x, 0.7 + fw.x, coord.x ) );\n\t#endif\n}";
  7692. var lightmap_fragment = "#ifdef USE_LIGHTMAP\n\tvec4 lightMapTexel = texture2D( lightMap, vUv2 );\n\tvec3 lightMapIrradiance = lightMapTexel.rgb * lightMapIntensity;\n\treflectedLight.indirectDiffuse += lightMapIrradiance;\n#endif";
  7693. var lightmap_pars_fragment = "#ifdef USE_LIGHTMAP\n\tuniform sampler2D lightMap;\n\tuniform float lightMapIntensity;\n#endif";
  7694. var lights_lambert_fragment = "LambertMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularStrength = specularStrength;";
  7695. var lights_lambert_pars_fragment = "varying vec3 vViewPosition;\nstruct LambertMaterial {\n\tvec3 diffuseColor;\n\tfloat specularStrength;\n};\nvoid RE_Direct_Lambert( const in IncidentLight directLight, const in GeometricContext geometry, const in LambertMaterial material, inout ReflectedLight reflectedLight ) {\n\tfloat dotNL = saturate( dot( geometry.normal, directLight.direction ) );\n\tvec3 irradiance = dotNL * directLight.color;\n\treflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectDiffuse_Lambert( const in vec3 irradiance, const in GeometricContext geometry, const in LambertMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\n#define RE_Direct\t\t\t\tRE_Direct_Lambert\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_Lambert";
  7696. var lights_pars_begin = "uniform bool receiveShadow;\nuniform vec3 ambientLightColor;\nuniform vec3 lightProbe[ 9 ];\nvec3 shGetIrradianceAt( in vec3 normal, in vec3 shCoefficients[ 9 ] ) {\n\tfloat x = normal.x, y = normal.y, z = normal.z;\n\tvec3 result = shCoefficients[ 0 ] * 0.886227;\n\tresult += shCoefficients[ 1 ] * 2.0 * 0.511664 * y;\n\tresult += shCoefficients[ 2 ] * 2.0 * 0.511664 * z;\n\tresult += shCoefficients[ 3 ] * 2.0 * 0.511664 * x;\n\tresult += shCoefficients[ 4 ] * 2.0 * 0.429043 * x * y;\n\tresult += shCoefficients[ 5 ] * 2.0 * 0.429043 * y * z;\n\tresult += shCoefficients[ 6 ] * ( 0.743125 * z * z - 0.247708 );\n\tresult += shCoefficients[ 7 ] * 2.0 * 0.429043 * x * z;\n\tresult += shCoefficients[ 8 ] * 0.429043 * ( x * x - y * y );\n\treturn result;\n}\nvec3 getLightProbeIrradiance( const in vec3 lightProbe[ 9 ], const in vec3 normal ) {\n\tvec3 worldNormal = inverseTransformDirection( normal, viewMatrix );\n\tvec3 irradiance = shGetIrradianceAt( worldNormal, lightProbe );\n\treturn irradiance;\n}\nvec3 getAmbientLightIrradiance( const in vec3 ambientLightColor ) {\n\tvec3 irradiance = ambientLightColor;\n\treturn irradiance;\n}\nfloat getDistanceAttenuation( const in float lightDistance, const in float cutoffDistance, const in float decayExponent ) {\n\t#if defined ( PHYSICALLY_CORRECT_LIGHTS )\n\t\tfloat distanceFalloff = 1.0 / max( pow( lightDistance, decayExponent ), 0.01 );\n\t\tif ( cutoffDistance > 0.0 ) {\n\t\t\tdistanceFalloff *= pow2( saturate( 1.0 - pow4( lightDistance / cutoffDistance ) ) );\n\t\t}\n\t\treturn distanceFalloff;\n\t#else\n\t\tif ( cutoffDistance > 0.0 && decayExponent > 0.0 ) {\n\t\t\treturn pow( saturate( - lightDistance / cutoffDistance + 1.0 ), decayExponent );\n\t\t}\n\t\treturn 1.0;\n\t#endif\n}\nfloat getSpotAttenuation( const in float coneCosine, const in float penumbraCosine, const in float angleCosine ) {\n\treturn smoothstep( coneCosine, penumbraCosine, angleCosine );\n}\n#if NUM_DIR_LIGHTS > 0\n\tstruct DirectionalLight {\n\t\tvec3 direction;\n\t\tvec3 color;\n\t};\n\tuniform DirectionalLight directionalLights[ NUM_DIR_LIGHTS ];\n\tvoid getDirectionalLightInfo( const in DirectionalLight directionalLight, const in GeometricContext geometry, out IncidentLight light ) {\n\t\tlight.color = directionalLight.color;\n\t\tlight.direction = directionalLight.direction;\n\t\tlight.visible = true;\n\t}\n#endif\n#if NUM_POINT_LIGHTS > 0\n\tstruct PointLight {\n\t\tvec3 position;\n\t\tvec3 color;\n\t\tfloat distance;\n\t\tfloat decay;\n\t};\n\tuniform PointLight pointLights[ NUM_POINT_LIGHTS ];\n\tvoid getPointLightInfo( const in PointLight pointLight, const in GeometricContext geometry, out IncidentLight light ) {\n\t\tvec3 lVector = pointLight.position - geometry.position;\n\t\tlight.direction = normalize( lVector );\n\t\tfloat lightDistance = length( lVector );\n\t\tlight.color = pointLight.color;\n\t\tlight.color *= getDistanceAttenuation( lightDistance, pointLight.distance, pointLight.decay );\n\t\tlight.visible = ( light.color != vec3( 0.0 ) );\n\t}\n#endif\n#if NUM_SPOT_LIGHTS > 0\n\tstruct SpotLight {\n\t\tvec3 position;\n\t\tvec3 direction;\n\t\tvec3 color;\n\t\tfloat distance;\n\t\tfloat decay;\n\t\tfloat coneCos;\n\t\tfloat penumbraCos;\n\t};\n\tuniform SpotLight spotLights[ NUM_SPOT_LIGHTS ];\n\tvoid getSpotLightInfo( const in SpotLight spotLight, const in GeometricContext geometry, out IncidentLight light ) {\n\t\tvec3 lVector = spotLight.position - geometry.position;\n\t\tlight.direction = normalize( lVector );\n\t\tfloat angleCos = dot( light.direction, spotLight.direction );\n\t\tfloat spotAttenuation = getSpotAttenuation( spotLight.coneCos, spotLight.penumbraCos, angleCos );\n\t\tif ( spotAttenuation > 0.0 ) {\n\t\t\tfloat lightDistance = length( lVector );\n\t\t\tlight.color = spotLight.color * spotAttenuation;\n\t\t\tlight.color *= getDistanceAttenuation( lightDistance, spotLight.distance, spotLight.decay );\n\t\t\tlight.visible = ( light.color != vec3( 0.0 ) );\n\t\t} else {\n\t\t\tlight.color = vec3( 0.0 );\n\t\t\tlight.visible = false;\n\t\t}\n\t}\n#endif\n#if NUM_RECT_AREA_LIGHTS > 0\n\tstruct RectAreaLight {\n\t\tvec3 color;\n\t\tvec3 position;\n\t\tvec3 halfWidth;\n\t\tvec3 halfHeight;\n\t};\n\tuniform sampler2D ltc_1;\tuniform sampler2D ltc_2;\n\tuniform RectAreaLight rectAreaLights[ NUM_RECT_AREA_LIGHTS ];\n#endif\n#if NUM_HEMI_LIGHTS > 0\n\tstruct HemisphereLight {\n\t\tvec3 direction;\n\t\tvec3 skyColor;\n\t\tvec3 groundColor;\n\t};\n\tuniform HemisphereLight hemisphereLights[ NUM_HEMI_LIGHTS ];\n\tvec3 getHemisphereLightIrradiance( const in HemisphereLight hemiLight, const in vec3 normal ) {\n\t\tfloat dotNL = dot( normal, hemiLight.direction );\n\t\tfloat hemiDiffuseWeight = 0.5 * dotNL + 0.5;\n\t\tvec3 irradiance = mix( hemiLight.groundColor, hemiLight.skyColor, hemiDiffuseWeight );\n\t\treturn irradiance;\n\t}\n#endif";
  7697. var envmap_physical_pars_fragment = "#if defined( USE_ENVMAP )\n\tvec3 getIBLIrradiance( const in vec3 normal ) {\n\t\t#if defined( ENVMAP_TYPE_CUBE_UV )\n\t\t\tvec3 worldNormal = inverseTransformDirection( normal, viewMatrix );\n\t\t\tvec4 envMapColor = textureCubeUV( envMap, worldNormal, 1.0 );\n\t\t\treturn PI * envMapColor.rgb * envMapIntensity;\n\t\t#else\n\t\t\treturn vec3( 0.0 );\n\t\t#endif\n\t}\n\tvec3 getIBLRadiance( const in vec3 viewDir, const in vec3 normal, const in float roughness ) {\n\t\t#if defined( ENVMAP_TYPE_CUBE_UV )\n\t\t\tvec3 reflectVec = reflect( - viewDir, normal );\n\t\t\treflectVec = normalize( mix( reflectVec, normal, roughness * roughness) );\n\t\t\treflectVec = inverseTransformDirection( reflectVec, viewMatrix );\n\t\t\tvec4 envMapColor = textureCubeUV( envMap, reflectVec, roughness );\n\t\t\treturn envMapColor.rgb * envMapIntensity;\n\t\t#else\n\t\t\treturn vec3( 0.0 );\n\t\t#endif\n\t}\n#endif";
  7698. var lights_toon_fragment = "ToonMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;";
  7699. var lights_toon_pars_fragment = "varying vec3 vViewPosition;\nstruct ToonMaterial {\n\tvec3 diffuseColor;\n};\nvoid RE_Direct_Toon( const in IncidentLight directLight, const in GeometricContext geometry, const in ToonMaterial material, inout ReflectedLight reflectedLight ) {\n\tvec3 irradiance = getGradientIrradiance( geometry.normal, directLight.direction ) * directLight.color;\n\treflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectDiffuse_Toon( const in vec3 irradiance, const in GeometricContext geometry, const in ToonMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\n#define RE_Direct\t\t\t\tRE_Direct_Toon\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_Toon";
  7700. var lights_phong_fragment = "BlinnPhongMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularColor = specular;\nmaterial.specularShininess = shininess;\nmaterial.specularStrength = specularStrength;";
  7701. var lights_phong_pars_fragment = "varying vec3 vViewPosition;\nstruct BlinnPhongMaterial {\n\tvec3 diffuseColor;\n\tvec3 specularColor;\n\tfloat specularShininess;\n\tfloat specularStrength;\n};\nvoid RE_Direct_BlinnPhong( const in IncidentLight directLight, const in GeometricContext geometry, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {\n\tfloat dotNL = saturate( dot( geometry.normal, directLight.direction ) );\n\tvec3 irradiance = dotNL * directLight.color;\n\treflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n\treflectedLight.directSpecular += irradiance * BRDF_BlinnPhong( directLight.direction, geometry.viewDir, geometry.normal, material.specularColor, material.specularShininess ) * material.specularStrength;\n}\nvoid RE_IndirectDiffuse_BlinnPhong( const in vec3 irradiance, const in GeometricContext geometry, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\n#define RE_Direct\t\t\t\tRE_Direct_BlinnPhong\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_BlinnPhong";
  7702. var lights_physical_fragment = "PhysicalMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb * ( 1.0 - metalnessFactor );\nvec3 dxy = max( abs( dFdx( geometryNormal ) ), abs( dFdy( geometryNormal ) ) );\nfloat geometryRoughness = max( max( dxy.x, dxy.y ), dxy.z );\nmaterial.roughness = max( roughnessFactor, 0.0525 );material.roughness += geometryRoughness;\nmaterial.roughness = min( material.roughness, 1.0 );\n#ifdef IOR\n\tmaterial.ior = ior;\n\t#ifdef SPECULAR\n\t\tfloat specularIntensityFactor = specularIntensity;\n\t\tvec3 specularColorFactor = specularColor;\n\t\t#ifdef USE_SPECULARINTENSITYMAP\n\t\t\tspecularIntensityFactor *= texture2D( specularIntensityMap, vUv ).a;\n\t\t#endif\n\t\t#ifdef USE_SPECULARCOLORMAP\n\t\t\tspecularColorFactor *= texture2D( specularColorMap, vUv ).rgb;\n\t\t#endif\n\t\tmaterial.specularF90 = mix( specularIntensityFactor, 1.0, metalnessFactor );\n\t#else\n\t\tfloat specularIntensityFactor = 1.0;\n\t\tvec3 specularColorFactor = vec3( 1.0 );\n\t\tmaterial.specularF90 = 1.0;\n\t#endif\n\tmaterial.specularColor = mix( min( pow2( ( material.ior - 1.0 ) / ( material.ior + 1.0 ) ) * specularColorFactor, vec3( 1.0 ) ) * specularIntensityFactor, diffuseColor.rgb, metalnessFactor );\n#else\n\tmaterial.specularColor = mix( vec3( 0.04 ), diffuseColor.rgb, metalnessFactor );\n\tmaterial.specularF90 = 1.0;\n#endif\n#ifdef USE_CLEARCOAT\n\tmaterial.clearcoat = clearcoat;\n\tmaterial.clearcoatRoughness = clearcoatRoughness;\n\tmaterial.clearcoatF0 = vec3( 0.04 );\n\tmaterial.clearcoatF90 = 1.0;\n\t#ifdef USE_CLEARCOATMAP\n\t\tmaterial.clearcoat *= texture2D( clearcoatMap, vUv ).x;\n\t#endif\n\t#ifdef USE_CLEARCOAT_ROUGHNESSMAP\n\t\tmaterial.clearcoatRoughness *= texture2D( clearcoatRoughnessMap, vUv ).y;\n\t#endif\n\tmaterial.clearcoat = saturate( material.clearcoat );\tmaterial.clearcoatRoughness = max( material.clearcoatRoughness, 0.0525 );\n\tmaterial.clearcoatRoughness += geometryRoughness;\n\tmaterial.clearcoatRoughness = min( material.clearcoatRoughness, 1.0 );\n#endif\n#ifdef USE_IRIDESCENCE\n\tmaterial.iridescence = iridescence;\n\tmaterial.iridescenceIOR = iridescenceIOR;\n\t#ifdef USE_IRIDESCENCEMAP\n\t\tmaterial.iridescence *= texture2D( iridescenceMap, vUv ).r;\n\t#endif\n\t#ifdef USE_IRIDESCENCE_THICKNESSMAP\n\t\tmaterial.iridescenceThickness = (iridescenceThicknessMaximum - iridescenceThicknessMinimum) * texture2D( iridescenceThicknessMap, vUv ).g + iridescenceThicknessMinimum;\n\t#else\n\t\tmaterial.iridescenceThickness = iridescenceThicknessMaximum;\n\t#endif\n#endif\n#ifdef USE_SHEEN\n\tmaterial.sheenColor = sheenColor;\n\t#ifdef USE_SHEENCOLORMAP\n\t\tmaterial.sheenColor *= texture2D( sheenColorMap, vUv ).rgb;\n\t#endif\n\tmaterial.sheenRoughness = clamp( sheenRoughness, 0.07, 1.0 );\n\t#ifdef USE_SHEENROUGHNESSMAP\n\t\tmaterial.sheenRoughness *= texture2D( sheenRoughnessMap, vUv ).a;\n\t#endif\n#endif";
  7703. var lights_physical_pars_fragment = "struct PhysicalMaterial {\n\tvec3 diffuseColor;\n\tfloat roughness;\n\tvec3 specularColor;\n\tfloat specularF90;\n\t#ifdef USE_CLEARCOAT\n\t\tfloat clearcoat;\n\t\tfloat clearcoatRoughness;\n\t\tvec3 clearcoatF0;\n\t\tfloat clearcoatF90;\n\t#endif\n\t#ifdef USE_IRIDESCENCE\n\t\tfloat iridescence;\n\t\tfloat iridescenceIOR;\n\t\tfloat iridescenceThickness;\n\t\tvec3 iridescenceFresnel;\n\t\tvec3 iridescenceF0;\n\t#endif\n\t#ifdef USE_SHEEN\n\t\tvec3 sheenColor;\n\t\tfloat sheenRoughness;\n\t#endif\n\t#ifdef IOR\n\t\tfloat ior;\n\t#endif\n\t#ifdef USE_TRANSMISSION\n\t\tfloat transmission;\n\t\tfloat transmissionAlpha;\n\t\tfloat thickness;\n\t\tfloat attenuationDistance;\n\t\tvec3 attenuationColor;\n\t#endif\n};\nvec3 clearcoatSpecular = vec3( 0.0 );\nvec3 sheenSpecular = vec3( 0.0 );\nfloat IBLSheenBRDF( const in vec3 normal, const in vec3 viewDir, const in float roughness ) {\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tfloat r2 = roughness * roughness;\n\tfloat a = roughness < 0.25 ? -339.2 * r2 + 161.4 * roughness - 25.9 : -8.48 * r2 + 14.3 * roughness - 9.95;\n\tfloat b = roughness < 0.25 ? 44.0 * r2 - 23.7 * roughness + 3.26 : 1.97 * r2 - 3.27 * roughness + 0.72;\n\tfloat DG = exp( a * dotNV + b ) + ( roughness < 0.25 ? 0.0 : 0.1 * ( roughness - 0.25 ) );\n\treturn saturate( DG * RECIPROCAL_PI );\n}\nvec2 DFGApprox( const in vec3 normal, const in vec3 viewDir, const in float roughness ) {\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tconst vec4 c0 = vec4( - 1, - 0.0275, - 0.572, 0.022 );\n\tconst vec4 c1 = vec4( 1, 0.0425, 1.04, - 0.04 );\n\tvec4 r = roughness * c0 + c1;\n\tfloat a004 = min( r.x * r.x, exp2( - 9.28 * dotNV ) ) * r.x + r.y;\n\tvec2 fab = vec2( - 1.04, 1.04 ) * a004 + r.zw;\n\treturn fab;\n}\nvec3 EnvironmentBRDF( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float roughness ) {\n\tvec2 fab = DFGApprox( normal, viewDir, roughness );\n\treturn specularColor * fab.x + specularF90 * fab.y;\n}\n#ifdef USE_IRIDESCENCE\nvoid computeMultiscatteringIridescence( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float iridescence, const in vec3 iridescenceF0, const in float roughness, inout vec3 singleScatter, inout vec3 multiScatter ) {\n#else\nvoid computeMultiscattering( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float roughness, inout vec3 singleScatter, inout vec3 multiScatter ) {\n#endif\n\tvec2 fab = DFGApprox( normal, viewDir, roughness );\n\t#ifdef USE_IRIDESCENCE\n\t\tvec3 Fr = mix( specularColor, iridescenceF0, iridescence );\n\t#else\n\t\tvec3 Fr = specularColor;\n\t#endif\n\tvec3 FssEss = Fr * fab.x + specularF90 * fab.y;\n\tfloat Ess = fab.x + fab.y;\n\tfloat Ems = 1.0 - Ess;\n\tvec3 Favg = Fr + ( 1.0 - Fr ) * 0.047619;\tvec3 Fms = FssEss * Favg / ( 1.0 - Ems * Favg );\n\tsingleScatter += FssEss;\n\tmultiScatter += Fms * Ems;\n}\n#if NUM_RECT_AREA_LIGHTS > 0\n\tvoid RE_Direct_RectArea_Physical( const in RectAreaLight rectAreaLight, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\t\tvec3 normal = geometry.normal;\n\t\tvec3 viewDir = geometry.viewDir;\n\t\tvec3 position = geometry.position;\n\t\tvec3 lightPos = rectAreaLight.position;\n\t\tvec3 halfWidth = rectAreaLight.halfWidth;\n\t\tvec3 halfHeight = rectAreaLight.halfHeight;\n\t\tvec3 lightColor = rectAreaLight.color;\n\t\tfloat roughness = material.roughness;\n\t\tvec3 rectCoords[ 4 ];\n\t\trectCoords[ 0 ] = lightPos + halfWidth - halfHeight;\t\trectCoords[ 1 ] = lightPos - halfWidth - halfHeight;\n\t\trectCoords[ 2 ] = lightPos - halfWidth + halfHeight;\n\t\trectCoords[ 3 ] = lightPos + halfWidth + halfHeight;\n\t\tvec2 uv = LTC_Uv( normal, viewDir, roughness );\n\t\tvec4 t1 = texture2D( ltc_1, uv );\n\t\tvec4 t2 = texture2D( ltc_2, uv );\n\t\tmat3 mInv = mat3(\n\t\t\tvec3( t1.x, 0, t1.y ),\n\t\t\tvec3( 0, 1, 0 ),\n\t\t\tvec3( t1.z, 0, t1.w )\n\t\t);\n\t\tvec3 fresnel = ( material.specularColor * t2.x + ( vec3( 1.0 ) - material.specularColor ) * t2.y );\n\t\treflectedLight.directSpecular += lightColor * fresnel * LTC_Evaluate( normal, viewDir, position, mInv, rectCoords );\n\t\treflectedLight.directDiffuse += lightColor * material.diffuseColor * LTC_Evaluate( normal, viewDir, position, mat3( 1.0 ), rectCoords );\n\t}\n#endif\nvoid RE_Direct_Physical( const in IncidentLight directLight, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\tfloat dotNL = saturate( dot( geometry.normal, directLight.direction ) );\n\tvec3 irradiance = dotNL * directLight.color;\n\t#ifdef USE_CLEARCOAT\n\t\tfloat dotNLcc = saturate( dot( geometry.clearcoatNormal, directLight.direction ) );\n\t\tvec3 ccIrradiance = dotNLcc * directLight.color;\n\t\tclearcoatSpecular += ccIrradiance * BRDF_GGX( directLight.direction, geometry.viewDir, geometry.clearcoatNormal, material.clearcoatF0, material.clearcoatF90, material.clearcoatRoughness );\n\t#endif\n\t#ifdef USE_SHEEN\n\t\tsheenSpecular += irradiance * BRDF_Sheen( directLight.direction, geometry.viewDir, geometry.normal, material.sheenColor, material.sheenRoughness );\n\t#endif\n\t#ifdef USE_IRIDESCENCE\n\t\treflectedLight.directSpecular += irradiance * BRDF_GGX_Iridescence( directLight.direction, geometry.viewDir, geometry.normal, material.specularColor, material.specularF90, material.iridescence, material.iridescenceFresnel, material.roughness );\n\t#else\n\t\treflectedLight.directSpecular += irradiance * BRDF_GGX( directLight.direction, geometry.viewDir, geometry.normal, material.specularColor, material.specularF90, material.roughness );\n\t#endif\n\treflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectDiffuse_Physical( const in vec3 irradiance, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectSpecular_Physical( const in vec3 radiance, const in vec3 irradiance, const in vec3 clearcoatRadiance, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight) {\n\t#ifdef USE_CLEARCOAT\n\t\tclearcoatSpecular += clearcoatRadiance * EnvironmentBRDF( geometry.clearcoatNormal, geometry.viewDir, material.clearcoatF0, material.clearcoatF90, material.clearcoatRoughness );\n\t#endif\n\t#ifdef USE_SHEEN\n\t\tsheenSpecular += irradiance * material.sheenColor * IBLSheenBRDF( geometry.normal, geometry.viewDir, material.sheenRoughness );\n\t#endif\n\tvec3 singleScattering = vec3( 0.0 );\n\tvec3 multiScattering = vec3( 0.0 );\n\tvec3 cosineWeightedIrradiance = irradiance * RECIPROCAL_PI;\n\t#ifdef USE_IRIDESCENCE\n\t\tcomputeMultiscatteringIridescence( geometry.normal, geometry.viewDir, material.specularColor, material.specularF90, material.iridescence, material.iridescenceFresnel, material.roughness, singleScattering, multiScattering );\n\t#else\n\t\tcomputeMultiscattering( geometry.normal, geometry.viewDir, material.specularColor, material.specularF90, material.roughness, singleScattering, multiScattering );\n\t#endif\n\tvec3 totalScattering = singleScattering + multiScattering;\n\tvec3 diffuse = material.diffuseColor * ( 1.0 - max( max( totalScattering.r, totalScattering.g ), totalScattering.b ) );\n\treflectedLight.indirectSpecular += radiance * singleScattering;\n\treflectedLight.indirectSpecular += multiScattering * cosineWeightedIrradiance;\n\treflectedLight.indirectDiffuse += diffuse * cosineWeightedIrradiance;\n}\n#define RE_Direct\t\t\t\tRE_Direct_Physical\n#define RE_Direct_RectArea\t\tRE_Direct_RectArea_Physical\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_Physical\n#define RE_IndirectSpecular\t\tRE_IndirectSpecular_Physical\nfloat computeSpecularOcclusion( const in float dotNV, const in float ambientOcclusion, const in float roughness ) {\n\treturn saturate( pow( dotNV + ambientOcclusion, exp2( - 16.0 * roughness - 1.0 ) ) - 1.0 + ambientOcclusion );\n}";
  7704. var lights_fragment_begin = "\nGeometricContext geometry;\ngeometry.position = - vViewPosition;\ngeometry.normal = normal;\ngeometry.viewDir = ( isOrthographic ) ? vec3( 0, 0, 1 ) : normalize( vViewPosition );\n#ifdef USE_CLEARCOAT\n\tgeometry.clearcoatNormal = clearcoatNormal;\n#endif\n#ifdef USE_IRIDESCENCE\n\tfloat dotNVi = saturate( dot( normal, geometry.viewDir ) );\n\tif ( material.iridescenceThickness == 0.0 ) {\n\t\tmaterial.iridescence = 0.0;\n\t} else {\n\t\tmaterial.iridescence = saturate( material.iridescence );\n\t}\n\tif ( material.iridescence > 0.0 ) {\n\t\tmaterial.iridescenceFresnel = evalIridescence( 1.0, material.iridescenceIOR, dotNVi, material.iridescenceThickness, material.specularColor );\n\t\tmaterial.iridescenceF0 = Schlick_to_F0( material.iridescenceFresnel, 1.0, dotNVi );\n\t}\n#endif\nIncidentLight directLight;\n#if ( NUM_POINT_LIGHTS > 0 ) && defined( RE_Direct )\n\tPointLight pointLight;\n\t#if defined( USE_SHADOWMAP ) && NUM_POINT_LIGHT_SHADOWS > 0\n\tPointLightShadow pointLightShadow;\n\t#endif\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n\t\tpointLight = pointLights[ i ];\n\t\tgetPointLightInfo( pointLight, geometry, directLight );\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_POINT_LIGHT_SHADOWS )\n\t\tpointLightShadow = pointLightShadows[ i ];\n\t\tdirectLight.color *= ( directLight.visible && receiveShadow ) ? getPointShadow( pointShadowMap[ i ], pointLightShadow.shadowMapSize, pointLightShadow.shadowBias, pointLightShadow.shadowRadius, vPointShadowCoord[ i ], pointLightShadow.shadowCameraNear, pointLightShadow.shadowCameraFar ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if ( NUM_SPOT_LIGHTS > 0 ) && defined( RE_Direct )\n\tSpotLight spotLight;\n\tvec4 spotColor;\n\tvec3 spotLightCoord;\n\tbool inSpotLightMap;\n\t#if defined( USE_SHADOWMAP ) && NUM_SPOT_LIGHT_SHADOWS > 0\n\tSpotLightShadow spotLightShadow;\n\t#endif\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n\t\tspotLight = spotLights[ i ];\n\t\tgetSpotLightInfo( spotLight, geometry, directLight );\n\t\t#if ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS )\n\t\t#define SPOT_LIGHT_MAP_INDEX UNROLLED_LOOP_INDEX\n\t\t#elif ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )\n\t\t#define SPOT_LIGHT_MAP_INDEX NUM_SPOT_LIGHT_MAPS\n\t\t#else\n\t\t#define SPOT_LIGHT_MAP_INDEX ( UNROLLED_LOOP_INDEX - NUM_SPOT_LIGHT_SHADOWS + NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS )\n\t\t#endif\n\t\t#if ( SPOT_LIGHT_MAP_INDEX < NUM_SPOT_LIGHT_MAPS )\n\t\t\tspotLightCoord = vSpotLightCoord[ i ].xyz / vSpotLightCoord[ i ].w;\n\t\t\tinSpotLightMap = all( lessThan( abs( spotLightCoord * 2. - 1. ), vec3( 1.0 ) ) );\n\t\t\tspotColor = texture2D( spotLightMap[ SPOT_LIGHT_MAP_INDEX ], spotLightCoord.xy );\n\t\t\tdirectLight.color = inSpotLightMap ? directLight.color * spotColor.rgb : directLight.color;\n\t\t#endif\n\t\t#undef SPOT_LIGHT_MAP_INDEX\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )\n\t\tspotLightShadow = spotLightShadows[ i ];\n\t\tdirectLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( spotShadowMap[ i ], spotLightShadow.shadowMapSize, spotLightShadow.shadowBias, spotLightShadow.shadowRadius, vSpotLightCoord[ i ] ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if ( NUM_DIR_LIGHTS > 0 ) && defined( RE_Direct )\n\tDirectionalLight directionalLight;\n\t#if defined( USE_SHADOWMAP ) && NUM_DIR_LIGHT_SHADOWS > 0\n\tDirectionalLightShadow directionalLightShadow;\n\t#endif\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n\t\tdirectionalLight = directionalLights[ i ];\n\t\tgetDirectionalLightInfo( directionalLight, geometry, directLight );\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_DIR_LIGHT_SHADOWS )\n\t\tdirectionalLightShadow = directionalLightShadows[ i ];\n\t\tdirectLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( directionalShadowMap[ i ], directionalLightShadow.shadowMapSize, directionalLightShadow.shadowBias, directionalLightShadow.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if ( NUM_RECT_AREA_LIGHTS > 0 ) && defined( RE_Direct_RectArea )\n\tRectAreaLight rectAreaLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_RECT_AREA_LIGHTS; i ++ ) {\n\t\trectAreaLight = rectAreaLights[ i ];\n\t\tRE_Direct_RectArea( rectAreaLight, geometry, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if defined( RE_IndirectDiffuse )\n\tvec3 iblIrradiance = vec3( 0.0 );\n\tvec3 irradiance = getAmbientLightIrradiance( ambientLightColor );\n\tirradiance += getLightProbeIrradiance( lightProbe, geometry.normal );\n\t#if ( NUM_HEMI_LIGHTS > 0 )\n\t\t#pragma unroll_loop_start\n\t\tfor ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) {\n\t\t\tirradiance += getHemisphereLightIrradiance( hemisphereLights[ i ], geometry.normal );\n\t\t}\n\t\t#pragma unroll_loop_end\n\t#endif\n#endif\n#if defined( RE_IndirectSpecular )\n\tvec3 radiance = vec3( 0.0 );\n\tvec3 clearcoatRadiance = vec3( 0.0 );\n#endif";
  7705. var lights_fragment_maps = "#if defined( RE_IndirectDiffuse )\n\t#ifdef USE_LIGHTMAP\n\t\tvec4 lightMapTexel = texture2D( lightMap, vUv2 );\n\t\tvec3 lightMapIrradiance = lightMapTexel.rgb * lightMapIntensity;\n\t\tirradiance += lightMapIrradiance;\n\t#endif\n\t#if defined( USE_ENVMAP ) && defined( STANDARD ) && defined( ENVMAP_TYPE_CUBE_UV )\n\t\tiblIrradiance += getIBLIrradiance( geometry.normal );\n\t#endif\n#endif\n#if defined( USE_ENVMAP ) && defined( RE_IndirectSpecular )\n\tradiance += getIBLRadiance( geometry.viewDir, geometry.normal, material.roughness );\n\t#ifdef USE_CLEARCOAT\n\t\tclearcoatRadiance += getIBLRadiance( geometry.viewDir, geometry.clearcoatNormal, material.clearcoatRoughness );\n\t#endif\n#endif";
  7706. var lights_fragment_end = "#if defined( RE_IndirectDiffuse )\n\tRE_IndirectDiffuse( irradiance, geometry, material, reflectedLight );\n#endif\n#if defined( RE_IndirectSpecular )\n\tRE_IndirectSpecular( radiance, iblIrradiance, clearcoatRadiance, geometry, material, reflectedLight );\n#endif";
  7707. var logdepthbuf_fragment = "#if defined( USE_LOGDEPTHBUF ) && defined( USE_LOGDEPTHBUF_EXT )\n\tgl_FragDepthEXT = vIsPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;\n#endif";
  7708. var logdepthbuf_pars_fragment = "#if defined( USE_LOGDEPTHBUF ) && defined( USE_LOGDEPTHBUF_EXT )\n\tuniform float logDepthBufFC;\n\tvarying float vFragDepth;\n\tvarying float vIsPerspective;\n#endif";
  7709. var logdepthbuf_pars_vertex = "#ifdef USE_LOGDEPTHBUF\n\t#ifdef USE_LOGDEPTHBUF_EXT\n\t\tvarying float vFragDepth;\n\t\tvarying float vIsPerspective;\n\t#else\n\t\tuniform float logDepthBufFC;\n\t#endif\n#endif";
  7710. var logdepthbuf_vertex = "#ifdef USE_LOGDEPTHBUF\n\t#ifdef USE_LOGDEPTHBUF_EXT\n\t\tvFragDepth = 1.0 + gl_Position.w;\n\t\tvIsPerspective = float( isPerspectiveMatrix( projectionMatrix ) );\n\t#else\n\t\tif ( isPerspectiveMatrix( projectionMatrix ) ) {\n\t\t\tgl_Position.z = log2( max( EPSILON, gl_Position.w + 1.0 ) ) * logDepthBufFC - 1.0;\n\t\t\tgl_Position.z *= gl_Position.w;\n\t\t}\n\t#endif\n#endif";
  7711. var map_fragment = "#ifdef USE_MAP\n\tvec4 sampledDiffuseColor = texture2D( map, vUv );\n\t#ifdef DECODE_VIDEO_TEXTURE\n\t\tsampledDiffuseColor = vec4( mix( pow( sampledDiffuseColor.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), sampledDiffuseColor.rgb * 0.0773993808, vec3( lessThanEqual( sampledDiffuseColor.rgb, vec3( 0.04045 ) ) ) ), sampledDiffuseColor.w );\n\t#endif\n\tdiffuseColor *= sampledDiffuseColor;\n#endif";
  7712. var map_pars_fragment = "#ifdef USE_MAP\n\tuniform sampler2D map;\n#endif";
  7713. var map_particle_fragment = "#if defined( USE_MAP ) || defined( USE_ALPHAMAP )\n\tvec2 uv = ( uvTransform * vec3( gl_PointCoord.x, 1.0 - gl_PointCoord.y, 1 ) ).xy;\n#endif\n#ifdef USE_MAP\n\tdiffuseColor *= texture2D( map, uv );\n#endif\n#ifdef USE_ALPHAMAP\n\tdiffuseColor.a *= texture2D( alphaMap, uv ).g;\n#endif";
  7714. var map_particle_pars_fragment = "#if defined( USE_MAP ) || defined( USE_ALPHAMAP )\n\tuniform mat3 uvTransform;\n#endif\n#ifdef USE_MAP\n\tuniform sampler2D map;\n#endif\n#ifdef USE_ALPHAMAP\n\tuniform sampler2D alphaMap;\n#endif";
  7715. var metalnessmap_fragment = "float metalnessFactor = metalness;\n#ifdef USE_METALNESSMAP\n\tvec4 texelMetalness = texture2D( metalnessMap, vUv );\n\tmetalnessFactor *= texelMetalness.b;\n#endif";
  7716. var metalnessmap_pars_fragment = "#ifdef USE_METALNESSMAP\n\tuniform sampler2D metalnessMap;\n#endif";
  7717. var morphcolor_vertex = "#if defined( USE_MORPHCOLORS ) && defined( MORPHTARGETS_TEXTURE )\n\tvColor *= morphTargetBaseInfluence;\n\tfor ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {\n\t\t#if defined( USE_COLOR_ALPHA )\n\t\t\tif ( morphTargetInfluences[ i ] != 0.0 ) vColor += getMorph( gl_VertexID, i, 2 ) * morphTargetInfluences[ i ];\n\t\t#elif defined( USE_COLOR )\n\t\t\tif ( morphTargetInfluences[ i ] != 0.0 ) vColor += getMorph( gl_VertexID, i, 2 ).rgb * morphTargetInfluences[ i ];\n\t\t#endif\n\t}\n#endif";
  7718. var morphnormal_vertex = "#ifdef USE_MORPHNORMALS\n\tobjectNormal *= morphTargetBaseInfluence;\n\t#ifdef MORPHTARGETS_TEXTURE\n\t\tfor ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {\n\t\t\tif ( morphTargetInfluences[ i ] != 0.0 ) objectNormal += getMorph( gl_VertexID, i, 1 ).xyz * morphTargetInfluences[ i ];\n\t\t}\n\t#else\n\t\tobjectNormal += morphNormal0 * morphTargetInfluences[ 0 ];\n\t\tobjectNormal += morphNormal1 * morphTargetInfluences[ 1 ];\n\t\tobjectNormal += morphNormal2 * morphTargetInfluences[ 2 ];\n\t\tobjectNormal += morphNormal3 * morphTargetInfluences[ 3 ];\n\t#endif\n#endif";
  7719. var morphtarget_pars_vertex = "#ifdef USE_MORPHTARGETS\n\tuniform float morphTargetBaseInfluence;\n\t#ifdef MORPHTARGETS_TEXTURE\n\t\tuniform float morphTargetInfluences[ MORPHTARGETS_COUNT ];\n\t\tuniform sampler2DArray morphTargetsTexture;\n\t\tuniform ivec2 morphTargetsTextureSize;\n\t\tvec4 getMorph( const in int vertexIndex, const in int morphTargetIndex, const in int offset ) {\n\t\t\tint texelIndex = vertexIndex * MORPHTARGETS_TEXTURE_STRIDE + offset;\n\t\t\tint y = texelIndex / morphTargetsTextureSize.x;\n\t\t\tint x = texelIndex - y * morphTargetsTextureSize.x;\n\t\t\tivec3 morphUV = ivec3( x, y, morphTargetIndex );\n\t\t\treturn texelFetch( morphTargetsTexture, morphUV, 0 );\n\t\t}\n\t#else\n\t\t#ifndef USE_MORPHNORMALS\n\t\t\tuniform float morphTargetInfluences[ 8 ];\n\t\t#else\n\t\t\tuniform float morphTargetInfluences[ 4 ];\n\t\t#endif\n\t#endif\n#endif";
  7720. var morphtarget_vertex = "#ifdef USE_MORPHTARGETS\n\ttransformed *= morphTargetBaseInfluence;\n\t#ifdef MORPHTARGETS_TEXTURE\n\t\tfor ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {\n\t\t\tif ( morphTargetInfluences[ i ] != 0.0 ) transformed += getMorph( gl_VertexID, i, 0 ).xyz * morphTargetInfluences[ i ];\n\t\t}\n\t#else\n\t\ttransformed += morphTarget0 * morphTargetInfluences[ 0 ];\n\t\ttransformed += morphTarget1 * morphTargetInfluences[ 1 ];\n\t\ttransformed += morphTarget2 * morphTargetInfluences[ 2 ];\n\t\ttransformed += morphTarget3 * morphTargetInfluences[ 3 ];\n\t\t#ifndef USE_MORPHNORMALS\n\t\t\ttransformed += morphTarget4 * morphTargetInfluences[ 4 ];\n\t\t\ttransformed += morphTarget5 * morphTargetInfluences[ 5 ];\n\t\t\ttransformed += morphTarget6 * morphTargetInfluences[ 6 ];\n\t\t\ttransformed += morphTarget7 * morphTargetInfluences[ 7 ];\n\t\t#endif\n\t#endif\n#endif";
  7721. var normal_fragment_begin = "float faceDirection = gl_FrontFacing ? 1.0 : - 1.0;\n#ifdef FLAT_SHADED\n\tvec3 fdx = dFdx( vViewPosition );\n\tvec3 fdy = dFdy( vViewPosition );\n\tvec3 normal = normalize( cross( fdx, fdy ) );\n#else\n\tvec3 normal = normalize( vNormal );\n\t#ifdef DOUBLE_SIDED\n\t\tnormal = normal * faceDirection;\n\t#endif\n\t#ifdef USE_TANGENT\n\t\tvec3 tangent = normalize( vTangent );\n\t\tvec3 bitangent = normalize( vBitangent );\n\t\t#ifdef DOUBLE_SIDED\n\t\t\ttangent = tangent * faceDirection;\n\t\t\tbitangent = bitangent * faceDirection;\n\t\t#endif\n\t\t#if defined( TANGENTSPACE_NORMALMAP ) || defined( USE_CLEARCOAT_NORMALMAP )\n\t\t\tmat3 vTBN = mat3( tangent, bitangent, normal );\n\t\t#endif\n\t#endif\n#endif\nvec3 geometryNormal = normal;";
  7722. var normal_fragment_maps = "#ifdef OBJECTSPACE_NORMALMAP\n\tnormal = texture2D( normalMap, vUv ).xyz * 2.0 - 1.0;\n\t#ifdef FLIP_SIDED\n\t\tnormal = - normal;\n\t#endif\n\t#ifdef DOUBLE_SIDED\n\t\tnormal = normal * faceDirection;\n\t#endif\n\tnormal = normalize( normalMatrix * normal );\n#elif defined( TANGENTSPACE_NORMALMAP )\n\tvec3 mapN = texture2D( normalMap, vUv ).xyz * 2.0 - 1.0;\n\tmapN.xy *= normalScale;\n\t#ifdef USE_TANGENT\n\t\tnormal = normalize( vTBN * mapN );\n\t#else\n\t\tnormal = perturbNormal2Arb( - vViewPosition, normal, mapN, faceDirection );\n\t#endif\n#elif defined( USE_BUMPMAP )\n\tnormal = perturbNormalArb( - vViewPosition, normal, dHdxy_fwd(), faceDirection );\n#endif";
  7723. var normal_pars_fragment = "#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n\t#ifdef USE_TANGENT\n\t\tvarying vec3 vTangent;\n\t\tvarying vec3 vBitangent;\n\t#endif\n#endif";
  7724. var normal_pars_vertex = "#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n\t#ifdef USE_TANGENT\n\t\tvarying vec3 vTangent;\n\t\tvarying vec3 vBitangent;\n\t#endif\n#endif";
  7725. var normal_vertex = "#ifndef FLAT_SHADED\n\tvNormal = normalize( transformedNormal );\n\t#ifdef USE_TANGENT\n\t\tvTangent = normalize( transformedTangent );\n\t\tvBitangent = normalize( cross( vNormal, vTangent ) * tangent.w );\n\t#endif\n#endif";
  7726. var normalmap_pars_fragment = "#ifdef USE_NORMALMAP\n\tuniform sampler2D normalMap;\n\tuniform vec2 normalScale;\n#endif\n#ifdef OBJECTSPACE_NORMALMAP\n\tuniform mat3 normalMatrix;\n#endif\n#if ! defined ( USE_TANGENT ) && ( defined ( TANGENTSPACE_NORMALMAP ) || defined ( USE_CLEARCOAT_NORMALMAP ) )\n\tvec3 perturbNormal2Arb( vec3 eye_pos, vec3 surf_norm, vec3 mapN, float faceDirection ) {\n\t\tvec3 q0 = dFdx( eye_pos.xyz );\n\t\tvec3 q1 = dFdy( eye_pos.xyz );\n\t\tvec2 st0 = dFdx( vUv.st );\n\t\tvec2 st1 = dFdy( vUv.st );\n\t\tvec3 N = surf_norm;\n\t\tvec3 q1perp = cross( q1, N );\n\t\tvec3 q0perp = cross( N, q0 );\n\t\tvec3 T = q1perp * st0.x + q0perp * st1.x;\n\t\tvec3 B = q1perp * st0.y + q0perp * st1.y;\n\t\tfloat det = max( dot( T, T ), dot( B, B ) );\n\t\tfloat scale = ( det == 0.0 ) ? 0.0 : faceDirection * inversesqrt( det );\n\t\treturn normalize( T * ( mapN.x * scale ) + B * ( mapN.y * scale ) + N * mapN.z );\n\t}\n#endif";
  7727. var clearcoat_normal_fragment_begin = "#ifdef USE_CLEARCOAT\n\tvec3 clearcoatNormal = geometryNormal;\n#endif";
  7728. var clearcoat_normal_fragment_maps = "#ifdef USE_CLEARCOAT_NORMALMAP\n\tvec3 clearcoatMapN = texture2D( clearcoatNormalMap, vUv ).xyz * 2.0 - 1.0;\n\tclearcoatMapN.xy *= clearcoatNormalScale;\n\t#ifdef USE_TANGENT\n\t\tclearcoatNormal = normalize( vTBN * clearcoatMapN );\n\t#else\n\t\tclearcoatNormal = perturbNormal2Arb( - vViewPosition, clearcoatNormal, clearcoatMapN, faceDirection );\n\t#endif\n#endif";
  7729. var clearcoat_pars_fragment = "#ifdef USE_CLEARCOATMAP\n\tuniform sampler2D clearcoatMap;\n#endif\n#ifdef USE_CLEARCOAT_ROUGHNESSMAP\n\tuniform sampler2D clearcoatRoughnessMap;\n#endif\n#ifdef USE_CLEARCOAT_NORMALMAP\n\tuniform sampler2D clearcoatNormalMap;\n\tuniform vec2 clearcoatNormalScale;\n#endif";
  7730. var iridescence_pars_fragment = "#ifdef USE_IRIDESCENCEMAP\n\tuniform sampler2D iridescenceMap;\n#endif\n#ifdef USE_IRIDESCENCE_THICKNESSMAP\n\tuniform sampler2D iridescenceThicknessMap;\n#endif";
  7731. var output_fragment = "#ifdef OPAQUE\ndiffuseColor.a = 1.0;\n#endif\n#ifdef USE_TRANSMISSION\ndiffuseColor.a *= material.transmissionAlpha + 0.1;\n#endif\ngl_FragColor = vec4( outgoingLight, diffuseColor.a );";
  7732. var packing = "vec3 packNormalToRGB( const in vec3 normal ) {\n\treturn normalize( normal ) * 0.5 + 0.5;\n}\nvec3 unpackRGBToNormal( const in vec3 rgb ) {\n\treturn 2.0 * rgb.xyz - 1.0;\n}\nconst float PackUpscale = 256. / 255.;const float UnpackDownscale = 255. / 256.;\nconst vec3 PackFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );\nconst vec4 UnpackFactors = UnpackDownscale / vec4( PackFactors, 1. );\nconst float ShiftRight8 = 1. / 256.;\nvec4 packDepthToRGBA( const in float v ) {\n\tvec4 r = vec4( fract( v * PackFactors ), v );\n\tr.yzw -= r.xyz * ShiftRight8;\treturn r * PackUpscale;\n}\nfloat unpackRGBAToDepth( const in vec4 v ) {\n\treturn dot( v, UnpackFactors );\n}\nvec2 packDepthToRG( in highp float v ) {\n\treturn packDepthToRGBA( v ).yx;\n}\nfloat unpackRGToDepth( const in highp vec2 v ) {\n\treturn unpackRGBAToDepth( vec4( v.xy, 0.0, 0.0 ) );\n}\nvec4 pack2HalfToRGBA( vec2 v ) {\n\tvec4 r = vec4( v.x, fract( v.x * 255.0 ), v.y, fract( v.y * 255.0 ) );\n\treturn vec4( r.x - r.y / 255.0, r.y, r.z - r.w / 255.0, r.w );\n}\nvec2 unpackRGBATo2Half( vec4 v ) {\n\treturn vec2( v.x + ( v.y / 255.0 ), v.z + ( v.w / 255.0 ) );\n}\nfloat viewZToOrthographicDepth( const in float viewZ, const in float near, const in float far ) {\n\treturn ( viewZ + near ) / ( near - far );\n}\nfloat orthographicDepthToViewZ( const in float linearClipZ, const in float near, const in float far ) {\n\treturn linearClipZ * ( near - far ) - near;\n}\nfloat viewZToPerspectiveDepth( const in float viewZ, const in float near, const in float far ) {\n\treturn ( ( near + viewZ ) * far ) / ( ( far - near ) * viewZ );\n}\nfloat perspectiveDepthToViewZ( const in float invClipZ, const in float near, const in float far ) {\n\treturn ( near * far ) / ( ( far - near ) * invClipZ - far );\n}";
  7733. var premultiplied_alpha_fragment = "#ifdef PREMULTIPLIED_ALPHA\n\tgl_FragColor.rgb *= gl_FragColor.a;\n#endif";
  7734. var project_vertex = "vec4 mvPosition = vec4( transformed, 1.0 );\n#ifdef USE_INSTANCING\n\tmvPosition = instanceMatrix * mvPosition;\n#endif\nmvPosition = modelViewMatrix * mvPosition;\ngl_Position = projectionMatrix * mvPosition;";
  7735. var dithering_fragment = "#ifdef DITHERING\n\tgl_FragColor.rgb = dithering( gl_FragColor.rgb );\n#endif";
  7736. var dithering_pars_fragment = "#ifdef DITHERING\n\tvec3 dithering( vec3 color ) {\n\t\tfloat grid_position = rand( gl_FragCoord.xy );\n\t\tvec3 dither_shift_RGB = vec3( 0.25 / 255.0, -0.25 / 255.0, 0.25 / 255.0 );\n\t\tdither_shift_RGB = mix( 2.0 * dither_shift_RGB, -2.0 * dither_shift_RGB, grid_position );\n\t\treturn color + dither_shift_RGB;\n\t}\n#endif";
  7737. var roughnessmap_fragment = "float roughnessFactor = roughness;\n#ifdef USE_ROUGHNESSMAP\n\tvec4 texelRoughness = texture2D( roughnessMap, vUv );\n\troughnessFactor *= texelRoughness.g;\n#endif";
  7738. var roughnessmap_pars_fragment = "#ifdef USE_ROUGHNESSMAP\n\tuniform sampler2D roughnessMap;\n#endif";
  7739. var shadowmap_pars_fragment = "#if NUM_SPOT_LIGHT_COORDS > 0\n varying vec4 vSpotLightCoord[ NUM_SPOT_LIGHT_COORDS ];\n#endif\n#if NUM_SPOT_LIGHT_MAPS > 0\n uniform sampler2D spotLightMap[ NUM_SPOT_LIGHT_MAPS ];\n#endif\n#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\t\tuniform sampler2D directionalShadowMap[ NUM_DIR_LIGHT_SHADOWS ];\n\t\tvarying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ];\n\t\tstruct DirectionalLightShadow {\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\t\tuniform DirectionalLightShadow directionalLightShadows[ NUM_DIR_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_SPOT_LIGHT_SHADOWS > 0\n\t\tuniform sampler2D spotShadowMap[ NUM_SPOT_LIGHT_SHADOWS ];\n\t\tstruct SpotLightShadow {\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\t\tuniform SpotLightShadow spotLightShadows[ NUM_SPOT_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\t\tuniform sampler2D pointShadowMap[ NUM_POINT_LIGHT_SHADOWS ];\n\t\tvarying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ];\n\t\tstruct PointLightShadow {\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t\tfloat shadowCameraNear;\n\t\t\tfloat shadowCameraFar;\n\t\t};\n\t\tuniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ];\n\t#endif\n\tfloat texture2DCompare( sampler2D depths, vec2 uv, float compare ) {\n\t\treturn step( compare, unpackRGBAToDepth( texture2D( depths, uv ) ) );\n\t}\n\tvec2 texture2DDistribution( sampler2D shadow, vec2 uv ) {\n\t\treturn unpackRGBATo2Half( texture2D( shadow, uv ) );\n\t}\n\tfloat VSMShadow (sampler2D shadow, vec2 uv, float compare ){\n\t\tfloat occlusion = 1.0;\n\t\tvec2 distribution = texture2DDistribution( shadow, uv );\n\t\tfloat hard_shadow = step( compare , distribution.x );\n\t\tif (hard_shadow != 1.0 ) {\n\t\t\tfloat distance = compare - distribution.x ;\n\t\t\tfloat variance = max( 0.00000, distribution.y * distribution.y );\n\t\t\tfloat softness_probability = variance / (variance + distance * distance );\t\t\tsoftness_probability = clamp( ( softness_probability - 0.3 ) / ( 0.95 - 0.3 ), 0.0, 1.0 );\t\t\tocclusion = clamp( max( hard_shadow, softness_probability ), 0.0, 1.0 );\n\t\t}\n\t\treturn occlusion;\n\t}\n\tfloat getShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowBias, float shadowRadius, vec4 shadowCoord ) {\n\t\tfloat shadow = 1.0;\n\t\tshadowCoord.xyz /= shadowCoord.w;\n\t\tshadowCoord.z += shadowBias;\n\t\tbool inFrustum = shadowCoord.x >= 0.0 && shadowCoord.x <= 1.0 && shadowCoord.y >= 0.0 && shadowCoord.y <= 1.0;\n\t\tbool frustumTest = inFrustum && shadowCoord.z <= 1.0;\n\t\tif ( frustumTest ) {\n\t\t#if defined( SHADOWMAP_TYPE_PCF )\n\t\t\tvec2 texelSize = vec2( 1.0 ) / shadowMapSize;\n\t\t\tfloat dx0 = - texelSize.x * shadowRadius;\n\t\t\tfloat dy0 = - texelSize.y * shadowRadius;\n\t\t\tfloat dx1 = + texelSize.x * shadowRadius;\n\t\t\tfloat dy1 = + texelSize.y * shadowRadius;\n\t\t\tfloat dx2 = dx0 / 2.0;\n\t\t\tfloat dy2 = dy0 / 2.0;\n\t\t\tfloat dx3 = dx1 / 2.0;\n\t\t\tfloat dy3 = dy1 / 2.0;\n\t\t\tshadow = (\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, dy2 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy2 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, dy2 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, dy3 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy3 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, dy3 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy1 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy1 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy1 ), shadowCoord.z )\n\t\t\t) * ( 1.0 / 17.0 );\n\t\t#elif defined( SHADOWMAP_TYPE_PCF_SOFT )\n\t\t\tvec2 texelSize = vec2( 1.0 ) / shadowMapSize;\n\t\t\tfloat dx = texelSize.x;\n\t\t\tfloat dy = texelSize.y;\n\t\t\tvec2 uv = shadowCoord.xy;\n\t\t\tvec2 f = fract( uv * shadowMapSize + 0.5 );\n\t\t\tuv -= f * texelSize;\n\t\t\tshadow = (\n\t\t\t\ttexture2DCompare( shadowMap, uv, shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, uv + vec2( dx, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, uv + vec2( 0.0, dy ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, uv + texelSize, shadowCoord.z ) +\n\t\t\t\tmix( texture2DCompare( shadowMap, uv + vec2( -dx, 0.0 ), shadowCoord.z ),\n\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, 0.0 ), shadowCoord.z ),\n\t\t\t\t\t f.x ) +\n\t\t\t\tmix( texture2DCompare( shadowMap, uv + vec2( -dx, dy ), shadowCoord.z ),\n\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, dy ), shadowCoord.z ),\n\t\t\t\t\t f.x ) +\n\t\t\t\tmix( texture2DCompare( shadowMap, uv + vec2( 0.0, -dy ), shadowCoord.z ),\n\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 0.0, 2.0 * dy ), shadowCoord.z ),\n\t\t\t\t\t f.y ) +\n\t\t\t\tmix( texture2DCompare( shadowMap, uv + vec2( dx, -dy ), shadowCoord.z ),\n\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( dx, 2.0 * dy ), shadowCoord.z ),\n\t\t\t\t\t f.y ) +\n\t\t\t\tmix( mix( texture2DCompare( shadowMap, uv + vec2( -dx, -dy ), shadowCoord.z ),\n\t\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, -dy ), shadowCoord.z ),\n\t\t\t\t\t\t f.x ),\n\t\t\t\t\t mix( texture2DCompare( shadowMap, uv + vec2( -dx, 2.0 * dy ), shadowCoord.z ),\n\t\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, 2.0 * dy ), shadowCoord.z ),\n\t\t\t\t\t\t f.x ),\n\t\t\t\t\t f.y )\n\t\t\t) * ( 1.0 / 9.0 );\n\t\t#elif defined( SHADOWMAP_TYPE_VSM )\n\t\t\tshadow = VSMShadow( shadowMap, shadowCoord.xy, shadowCoord.z );\n\t\t#else\n\t\t\tshadow = texture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z );\n\t\t#endif\n\t\t}\n\t\treturn shadow;\n\t}\n\tvec2 cubeToUV( vec3 v, float texelSizeY ) {\n\t\tvec3 absV = abs( v );\n\t\tfloat scaleToCube = 1.0 / max( absV.x, max( absV.y, absV.z ) );\n\t\tabsV *= scaleToCube;\n\t\tv *= scaleToCube * ( 1.0 - 2.0 * texelSizeY );\n\t\tvec2 planar = v.xy;\n\t\tfloat almostATexel = 1.5 * texelSizeY;\n\t\tfloat almostOne = 1.0 - almostATexel;\n\t\tif ( absV.z >= almostOne ) {\n\t\t\tif ( v.z > 0.0 )\n\t\t\t\tplanar.x = 4.0 - v.x;\n\t\t} else if ( absV.x >= almostOne ) {\n\t\t\tfloat signX = sign( v.x );\n\t\t\tplanar.x = v.z * signX + 2.0 * signX;\n\t\t} else if ( absV.y >= almostOne ) {\n\t\t\tfloat signY = sign( v.y );\n\t\t\tplanar.x = v.x + 2.0 * signY + 2.0;\n\t\t\tplanar.y = v.z * signY - 2.0;\n\t\t}\n\t\treturn vec2( 0.125, 0.25 ) * planar + vec2( 0.375, 0.75 );\n\t}\n\tfloat getPointShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowBias, float shadowRadius, vec4 shadowCoord, float shadowCameraNear, float shadowCameraFar ) {\n\t\tvec2 texelSize = vec2( 1.0 ) / ( shadowMapSize * vec2( 4.0, 2.0 ) );\n\t\tvec3 lightToPosition = shadowCoord.xyz;\n\t\tfloat dp = ( length( lightToPosition ) - shadowCameraNear ) / ( shadowCameraFar - shadowCameraNear );\t\tdp += shadowBias;\n\t\tvec3 bd3D = normalize( lightToPosition );\n\t\t#if defined( SHADOWMAP_TYPE_PCF ) || defined( SHADOWMAP_TYPE_PCF_SOFT ) || defined( SHADOWMAP_TYPE_VSM )\n\t\t\tvec2 offset = vec2( - 1, 1 ) * shadowRadius * texelSize.y;\n\t\t\treturn (\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyx, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyx, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxx, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxx, texelSize.y ), dp )\n\t\t\t) * ( 1.0 / 9.0 );\n\t\t#else\n\t\t\treturn texture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp );\n\t\t#endif\n\t}\n#endif";
  7740. var shadowmap_pars_vertex = "#if NUM_SPOT_LIGHT_COORDS > 0\n uniform mat4 spotLightMatrix[ NUM_SPOT_LIGHT_COORDS ];\n varying vec4 vSpotLightCoord[ NUM_SPOT_LIGHT_COORDS ];\n#endif\n#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\t\tuniform mat4 directionalShadowMatrix[ NUM_DIR_LIGHT_SHADOWS ];\n\t\tvarying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ];\n\t\tstruct DirectionalLightShadow {\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\t\tuniform DirectionalLightShadow directionalLightShadows[ NUM_DIR_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_SPOT_LIGHT_SHADOWS > 0\n\t\tstruct SpotLightShadow {\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\t\tuniform SpotLightShadow spotLightShadows[ NUM_SPOT_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\t\tuniform mat4 pointShadowMatrix[ NUM_POINT_LIGHT_SHADOWS ];\n\t\tvarying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ];\n\t\tstruct PointLightShadow {\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t\tfloat shadowCameraNear;\n\t\t\tfloat shadowCameraFar;\n\t\t};\n\t\tuniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ];\n\t#endif\n#endif";
  7741. var shadowmap_vertex = "#if ( defined( USE_SHADOWMAP ) && ( NUM_DIR_LIGHT_SHADOWS > 0 || NUM_POINT_LIGHT_SHADOWS > 0 ) ) || ( NUM_SPOT_LIGHT_COORDS > 0 )\n\tvec3 shadowWorldNormal = inverseTransformDirection( transformedNormal, viewMatrix );\n\tvec4 shadowWorldPosition;\n#endif\n#if defined( USE_SHADOWMAP )\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\t\t#pragma unroll_loop_start\n\t\tfor ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) {\n\t\t\tshadowWorldPosition = worldPosition + vec4( shadowWorldNormal * directionalLightShadows[ i ].shadowNormalBias, 0 );\n\t\t\tvDirectionalShadowCoord[ i ] = directionalShadowMatrix[ i ] * shadowWorldPosition;\n\t\t}\n\t\t#pragma unroll_loop_end\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\t\t#pragma unroll_loop_start\n\t\tfor ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) {\n\t\t\tshadowWorldPosition = worldPosition + vec4( shadowWorldNormal * pointLightShadows[ i ].shadowNormalBias, 0 );\n\t\t\tvPointShadowCoord[ i ] = pointShadowMatrix[ i ] * shadowWorldPosition;\n\t\t}\n\t\t#pragma unroll_loop_end\n\t#endif\n#endif\n#if NUM_SPOT_LIGHT_COORDS > 0\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_SPOT_LIGHT_COORDS; i ++ ) {\n\t\tshadowWorldPosition = worldPosition;\n\t\t#if ( defined( USE_SHADOWMAP ) && UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )\n\t\t\tshadowWorldPosition.xyz += shadowWorldNormal * spotLightShadows[ i ].shadowNormalBias;\n\t\t#endif\n\t\tvSpotLightCoord[ i ] = spotLightMatrix[ i ] * shadowWorldPosition;\n\t}\n\t#pragma unroll_loop_end\n#endif";
  7742. var shadowmask_pars_fragment = "float getShadowMask() {\n\tfloat shadow = 1.0;\n\t#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\tDirectionalLightShadow directionalLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) {\n\t\tdirectionalLight = directionalLightShadows[ i ];\n\t\tshadow *= receiveShadow ? getShadow( directionalShadowMap[ i ], directionalLight.shadowMapSize, directionalLight.shadowBias, directionalLight.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n\t#if NUM_SPOT_LIGHT_SHADOWS > 0\n\tSpotLightShadow spotLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_SPOT_LIGHT_SHADOWS; i ++ ) {\n\t\tspotLight = spotLightShadows[ i ];\n\t\tshadow *= receiveShadow ? getShadow( spotShadowMap[ i ], spotLight.shadowMapSize, spotLight.shadowBias, spotLight.shadowRadius, vSpotLightCoord[ i ] ) : 1.0;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\tPointLightShadow pointLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) {\n\t\tpointLight = pointLightShadows[ i ];\n\t\tshadow *= receiveShadow ? getPointShadow( pointShadowMap[ i ], pointLight.shadowMapSize, pointLight.shadowBias, pointLight.shadowRadius, vPointShadowCoord[ i ], pointLight.shadowCameraNear, pointLight.shadowCameraFar ) : 1.0;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n\t#endif\n\treturn shadow;\n}";
  7743. var skinbase_vertex = "#ifdef USE_SKINNING\n\tmat4 boneMatX = getBoneMatrix( skinIndex.x );\n\tmat4 boneMatY = getBoneMatrix( skinIndex.y );\n\tmat4 boneMatZ = getBoneMatrix( skinIndex.z );\n\tmat4 boneMatW = getBoneMatrix( skinIndex.w );\n#endif";
  7744. var skinning_pars_vertex = "#ifdef USE_SKINNING\n\tuniform mat4 bindMatrix;\n\tuniform mat4 bindMatrixInverse;\n\tuniform highp sampler2D boneTexture;\n\tuniform int boneTextureSize;\n\tmat4 getBoneMatrix( const in float i ) {\n\t\tfloat j = i * 4.0;\n\t\tfloat x = mod( j, float( boneTextureSize ) );\n\t\tfloat y = floor( j / float( boneTextureSize ) );\n\t\tfloat dx = 1.0 / float( boneTextureSize );\n\t\tfloat dy = 1.0 / float( boneTextureSize );\n\t\ty = dy * ( y + 0.5 );\n\t\tvec4 v1 = texture2D( boneTexture, vec2( dx * ( x + 0.5 ), y ) );\n\t\tvec4 v2 = texture2D( boneTexture, vec2( dx * ( x + 1.5 ), y ) );\n\t\tvec4 v3 = texture2D( boneTexture, vec2( dx * ( x + 2.5 ), y ) );\n\t\tvec4 v4 = texture2D( boneTexture, vec2( dx * ( x + 3.5 ), y ) );\n\t\tmat4 bone = mat4( v1, v2, v3, v4 );\n\t\treturn bone;\n\t}\n#endif";
  7745. var skinning_vertex = "#ifdef USE_SKINNING\n\tvec4 skinVertex = bindMatrix * vec4( transformed, 1.0 );\n\tvec4 skinned = vec4( 0.0 );\n\tskinned += boneMatX * skinVertex * skinWeight.x;\n\tskinned += boneMatY * skinVertex * skinWeight.y;\n\tskinned += boneMatZ * skinVertex * skinWeight.z;\n\tskinned += boneMatW * skinVertex * skinWeight.w;\n\ttransformed = ( bindMatrixInverse * skinned ).xyz;\n#endif";
  7746. var skinnormal_vertex = "#ifdef USE_SKINNING\n\tmat4 skinMatrix = mat4( 0.0 );\n\tskinMatrix += skinWeight.x * boneMatX;\n\tskinMatrix += skinWeight.y * boneMatY;\n\tskinMatrix += skinWeight.z * boneMatZ;\n\tskinMatrix += skinWeight.w * boneMatW;\n\tskinMatrix = bindMatrixInverse * skinMatrix * bindMatrix;\n\tobjectNormal = vec4( skinMatrix * vec4( objectNormal, 0.0 ) ).xyz;\n\t#ifdef USE_TANGENT\n\t\tobjectTangent = vec4( skinMatrix * vec4( objectTangent, 0.0 ) ).xyz;\n\t#endif\n#endif";
  7747. var specularmap_fragment = "float specularStrength;\n#ifdef USE_SPECULARMAP\n\tvec4 texelSpecular = texture2D( specularMap, vUv );\n\tspecularStrength = texelSpecular.r;\n#else\n\tspecularStrength = 1.0;\n#endif";
  7748. var specularmap_pars_fragment = "#ifdef USE_SPECULARMAP\n\tuniform sampler2D specularMap;\n#endif";
  7749. var tonemapping_fragment = "#if defined( TONE_MAPPING )\n\tgl_FragColor.rgb = toneMapping( gl_FragColor.rgb );\n#endif";
  7750. var tonemapping_pars_fragment = "#ifndef saturate\n#define saturate( a ) clamp( a, 0.0, 1.0 )\n#endif\nuniform float toneMappingExposure;\nvec3 LinearToneMapping( vec3 color ) {\n\treturn toneMappingExposure * color;\n}\nvec3 ReinhardToneMapping( vec3 color ) {\n\tcolor *= toneMappingExposure;\n\treturn saturate( color / ( vec3( 1.0 ) + color ) );\n}\nvec3 OptimizedCineonToneMapping( vec3 color ) {\n\tcolor *= toneMappingExposure;\n\tcolor = max( vec3( 0.0 ), color - 0.004 );\n\treturn pow( ( color * ( 6.2 * color + 0.5 ) ) / ( color * ( 6.2 * color + 1.7 ) + 0.06 ), vec3( 2.2 ) );\n}\nvec3 RRTAndODTFit( vec3 v ) {\n\tvec3 a = v * ( v + 0.0245786 ) - 0.000090537;\n\tvec3 b = v * ( 0.983729 * v + 0.4329510 ) + 0.238081;\n\treturn a / b;\n}\nvec3 ACESFilmicToneMapping( vec3 color ) {\n\tconst mat3 ACESInputMat = mat3(\n\t\tvec3( 0.59719, 0.07600, 0.02840 ),\t\tvec3( 0.35458, 0.90834, 0.13383 ),\n\t\tvec3( 0.04823, 0.01566, 0.83777 )\n\t);\n\tconst mat3 ACESOutputMat = mat3(\n\t\tvec3( 1.60475, -0.10208, -0.00327 ),\t\tvec3( -0.53108, 1.10813, -0.07276 ),\n\t\tvec3( -0.07367, -0.00605, 1.07602 )\n\t);\n\tcolor *= toneMappingExposure / 0.6;\n\tcolor = ACESInputMat * color;\n\tcolor = RRTAndODTFit( color );\n\tcolor = ACESOutputMat * color;\n\treturn saturate( color );\n}\nvec3 CustomToneMapping( vec3 color ) { return color; }";
  7751. var transmission_fragment = "#ifdef USE_TRANSMISSION\n\tmaterial.transmission = transmission;\n\tmaterial.transmissionAlpha = 1.0;\n\tmaterial.thickness = thickness;\n\tmaterial.attenuationDistance = attenuationDistance;\n\tmaterial.attenuationColor = attenuationColor;\n\t#ifdef USE_TRANSMISSIONMAP\n\t\tmaterial.transmission *= texture2D( transmissionMap, vUv ).r;\n\t#endif\n\t#ifdef USE_THICKNESSMAP\n\t\tmaterial.thickness *= texture2D( thicknessMap, vUv ).g;\n\t#endif\n\tvec3 pos = vWorldPosition;\n\tvec3 v = normalize( cameraPosition - pos );\n\tvec3 n = inverseTransformDirection( normal, viewMatrix );\n\tvec4 transmission = getIBLVolumeRefraction(\n\t\tn, v, material.roughness, material.diffuseColor, material.specularColor, material.specularF90,\n\t\tpos, modelMatrix, viewMatrix, projectionMatrix, material.ior, material.thickness,\n\t\tmaterial.attenuationColor, material.attenuationDistance );\n\tmaterial.transmissionAlpha = mix( material.transmissionAlpha, transmission.a, material.transmission );\n\ttotalDiffuse = mix( totalDiffuse, transmission.rgb, material.transmission );\n#endif";
  7752. var transmission_pars_fragment = "#ifdef USE_TRANSMISSION\n\tuniform float transmission;\n\tuniform float thickness;\n\tuniform float attenuationDistance;\n\tuniform vec3 attenuationColor;\n\t#ifdef USE_TRANSMISSIONMAP\n\t\tuniform sampler2D transmissionMap;\n\t#endif\n\t#ifdef USE_THICKNESSMAP\n\t\tuniform sampler2D thicknessMap;\n\t#endif\n\tuniform vec2 transmissionSamplerSize;\n\tuniform sampler2D transmissionSamplerMap;\n\tuniform mat4 modelMatrix;\n\tuniform mat4 projectionMatrix;\n\tvarying vec3 vWorldPosition;\n\tvec3 getVolumeTransmissionRay( const in vec3 n, const in vec3 v, const in float thickness, const in float ior, const in mat4 modelMatrix ) {\n\t\tvec3 refractionVector = refract( - v, normalize( n ), 1.0 / ior );\n\t\tvec3 modelScale;\n\t\tmodelScale.x = length( vec3( modelMatrix[ 0 ].xyz ) );\n\t\tmodelScale.y = length( vec3( modelMatrix[ 1 ].xyz ) );\n\t\tmodelScale.z = length( vec3( modelMatrix[ 2 ].xyz ) );\n\t\treturn normalize( refractionVector ) * thickness * modelScale;\n\t}\n\tfloat applyIorToRoughness( const in float roughness, const in float ior ) {\n\t\treturn roughness * clamp( ior * 2.0 - 2.0, 0.0, 1.0 );\n\t}\n\tvec4 getTransmissionSample( const in vec2 fragCoord, const in float roughness, const in float ior ) {\n\t\tfloat framebufferLod = log2( transmissionSamplerSize.x ) * applyIorToRoughness( roughness, ior );\n\t\t#ifdef texture2DLodEXT\n\t\t\treturn texture2DLodEXT( transmissionSamplerMap, fragCoord.xy, framebufferLod );\n\t\t#else\n\t\t\treturn texture2D( transmissionSamplerMap, fragCoord.xy, framebufferLod );\n\t\t#endif\n\t}\n\tvec3 applyVolumeAttenuation( const in vec3 radiance, const in float transmissionDistance, const in vec3 attenuationColor, const in float attenuationDistance ) {\n\t\tif ( isinf( attenuationDistance ) ) {\n\t\t\treturn radiance;\n\t\t} else {\n\t\t\tvec3 attenuationCoefficient = -log( attenuationColor ) / attenuationDistance;\n\t\t\tvec3 transmittance = exp( - attenuationCoefficient * transmissionDistance );\t\t\treturn transmittance * radiance;\n\t\t}\n\t}\n\tvec4 getIBLVolumeRefraction( const in vec3 n, const in vec3 v, const in float roughness, const in vec3 diffuseColor,\n\t\tconst in vec3 specularColor, const in float specularF90, const in vec3 position, const in mat4 modelMatrix,\n\t\tconst in mat4 viewMatrix, const in mat4 projMatrix, const in float ior, const in float thickness,\n\t\tconst in vec3 attenuationColor, const in float attenuationDistance ) {\n\t\tvec3 transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix );\n\t\tvec3 refractedRayExit = position + transmissionRay;\n\t\tvec4 ndcPos = projMatrix * viewMatrix * vec4( refractedRayExit, 1.0 );\n\t\tvec2 refractionCoords = ndcPos.xy / ndcPos.w;\n\t\trefractionCoords += 1.0;\n\t\trefractionCoords /= 2.0;\n\t\tvec4 transmittedLight = getTransmissionSample( refractionCoords, roughness, ior );\n\t\tvec3 attenuatedColor = applyVolumeAttenuation( transmittedLight.rgb, length( transmissionRay ), attenuationColor, attenuationDistance );\n\t\tvec3 F = EnvironmentBRDF( n, v, specularColor, specularF90, roughness );\n\t\treturn vec4( ( 1.0 - F ) * attenuatedColor * diffuseColor, transmittedLight.a );\n\t}\n#endif";
  7753. var uv_pars_fragment = "#if ( defined( USE_UV ) && ! defined( UVS_VERTEX_ONLY ) )\n\tvarying vec2 vUv;\n#endif";
  7754. var uv_pars_vertex = "#ifdef USE_UV\n\t#ifdef UVS_VERTEX_ONLY\n\t\tvec2 vUv;\n\t#else\n\t\tvarying vec2 vUv;\n\t#endif\n\tuniform mat3 uvTransform;\n#endif";
  7755. var uv_vertex = "#ifdef USE_UV\n\tvUv = ( uvTransform * vec3( uv, 1 ) ).xy;\n#endif";
  7756. var uv2_pars_fragment = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tvarying vec2 vUv2;\n#endif";
  7757. var uv2_pars_vertex = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tattribute vec2 uv2;\n\tvarying vec2 vUv2;\n\tuniform mat3 uv2Transform;\n#endif";
  7758. var uv2_vertex = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tvUv2 = ( uv2Transform * vec3( uv2, 1 ) ).xy;\n#endif";
  7759. var worldpos_vertex = "#if defined( USE_ENVMAP ) || defined( DISTANCE ) || defined ( USE_SHADOWMAP ) || defined ( USE_TRANSMISSION ) || NUM_SPOT_LIGHT_COORDS > 0\n\tvec4 worldPosition = vec4( transformed, 1.0 );\n\t#ifdef USE_INSTANCING\n\t\tworldPosition = instanceMatrix * worldPosition;\n\t#endif\n\tworldPosition = modelMatrix * worldPosition;\n#endif";
  7760. const vertex$h = "varying vec2 vUv;\nuniform mat3 uvTransform;\nvoid main() {\n\tvUv = ( uvTransform * vec3( uv, 1 ) ).xy;\n\tgl_Position = vec4( position.xy, 1.0, 1.0 );\n}";
  7761. const fragment$h = "uniform sampler2D t2D;\nuniform float backgroundIntensity;\nvarying vec2 vUv;\nvoid main() {\n\tvec4 texColor = texture2D( t2D, vUv );\n\t#ifdef DECODE_VIDEO_TEXTURE\n\t\ttexColor = vec4( mix( pow( texColor.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), texColor.rgb * 0.0773993808, vec3( lessThanEqual( texColor.rgb, vec3( 0.04045 ) ) ) ), texColor.w );\n\t#endif\n\ttexColor.rgb *= backgroundIntensity;\n\tgl_FragColor = texColor;\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n}";
  7762. const vertex$g = "varying vec3 vWorldDirection;\n#include <common>\nvoid main() {\n\tvWorldDirection = transformDirection( position, modelMatrix );\n\t#include <begin_vertex>\n\t#include <project_vertex>\n\tgl_Position.z = gl_Position.w;\n}";
  7763. const fragment$g = "#ifdef ENVMAP_TYPE_CUBE\n\tuniform samplerCube envMap;\n#elif defined( ENVMAP_TYPE_CUBE_UV )\n\tuniform sampler2D envMap;\n#endif\nuniform float flipEnvMap;\nuniform float backgroundBlurriness;\nuniform float backgroundIntensity;\nvarying vec3 vWorldDirection;\n#include <cube_uv_reflection_fragment>\nvoid main() {\n\t#ifdef ENVMAP_TYPE_CUBE\n\t\tvec4 texColor = textureCube( envMap, vec3( flipEnvMap * vWorldDirection.x, vWorldDirection.yz ) );\n\t#elif defined( ENVMAP_TYPE_CUBE_UV )\n\t\tvec4 texColor = textureCubeUV( envMap, vWorldDirection, backgroundBlurriness );\n\t#else\n\t\tvec4 texColor = vec4( 0.0, 0.0, 0.0, 1.0 );\n\t#endif\n\ttexColor.rgb *= backgroundIntensity;\n\tgl_FragColor = texColor;\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n}";
  7764. const vertex$f = "varying vec3 vWorldDirection;\n#include <common>\nvoid main() {\n\tvWorldDirection = transformDirection( position, modelMatrix );\n\t#include <begin_vertex>\n\t#include <project_vertex>\n\tgl_Position.z = gl_Position.w;\n}";
  7765. const fragment$f = "uniform samplerCube tCube;\nuniform float tFlip;\nuniform float opacity;\nvarying vec3 vWorldDirection;\nvoid main() {\n\tvec4 texColor = textureCube( tCube, vec3( tFlip * vWorldDirection.x, vWorldDirection.yz ) );\n\tgl_FragColor = texColor;\n\tgl_FragColor.a *= opacity;\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n}";
  7766. const vertex$e = "#include <common>\n#include <uv_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvarying vec2 vHighPrecisionZW;\nvoid main() {\n\t#include <uv_vertex>\n\t#include <skinbase_vertex>\n\t#ifdef USE_DISPLACEMENTMAP\n\t\t#include <beginnormal_vertex>\n\t\t#include <morphnormal_vertex>\n\t\t#include <skinnormal_vertex>\n\t#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\tvHighPrecisionZW = gl_Position.zw;\n}";
  7767. const fragment$e = "#if DEPTH_PACKING == 3200\n\tuniform float opacity;\n#endif\n#include <common>\n#include <packing>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvarying vec2 vHighPrecisionZW;\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( 1.0 );\n\t#if DEPTH_PACKING == 3200\n\t\tdiffuseColor.a = opacity;\n\t#endif\n\t#include <map_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <logdepthbuf_fragment>\n\tfloat fragCoordZ = 0.5 * vHighPrecisionZW[0] / vHighPrecisionZW[1] + 0.5;\n\t#if DEPTH_PACKING == 3200\n\t\tgl_FragColor = vec4( vec3( 1.0 - fragCoordZ ), opacity );\n\t#elif DEPTH_PACKING == 3201\n\t\tgl_FragColor = packDepthToRGBA( fragCoordZ );\n\t#endif\n}";
  7768. const vertex$d = "#define DISTANCE\nvarying vec3 vWorldPosition;\n#include <common>\n#include <uv_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <skinbase_vertex>\n\t#ifdef USE_DISPLACEMENTMAP\n\t\t#include <beginnormal_vertex>\n\t\t#include <morphnormal_vertex>\n\t\t#include <skinnormal_vertex>\n\t#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <worldpos_vertex>\n\t#include <clipping_planes_vertex>\n\tvWorldPosition = worldPosition.xyz;\n}";
  7769. const fragment$d = "#define DISTANCE\nuniform vec3 referencePosition;\nuniform float nearDistance;\nuniform float farDistance;\nvarying vec3 vWorldPosition;\n#include <common>\n#include <packing>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main () {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( 1.0 );\n\t#include <map_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\tfloat dist = length( vWorldPosition - referencePosition );\n\tdist = ( dist - nearDistance ) / ( farDistance - nearDistance );\n\tdist = saturate( dist );\n\tgl_FragColor = packDepthToRGBA( dist );\n}";
  7770. const vertex$c = "varying vec3 vWorldDirection;\n#include <common>\nvoid main() {\n\tvWorldDirection = transformDirection( position, modelMatrix );\n\t#include <begin_vertex>\n\t#include <project_vertex>\n}";
  7771. const fragment$c = "uniform sampler2D tEquirect;\nvarying vec3 vWorldDirection;\n#include <common>\nvoid main() {\n\tvec3 direction = normalize( vWorldDirection );\n\tvec2 sampleUV = equirectUv( direction );\n\tgl_FragColor = texture2D( tEquirect, sampleUV );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n}";
  7772. const vertex$b = "uniform float scale;\nattribute float lineDistance;\nvarying float vLineDistance;\n#include <common>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\tvLineDistance = scale * lineDistance;\n\t#include <color_vertex>\n\t#include <morphcolor_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <fog_vertex>\n}";
  7773. const fragment$b = "uniform vec3 diffuse;\nuniform float opacity;\nuniform float dashSize;\nuniform float totalSize;\nvarying float vLineDistance;\n#include <common>\n#include <color_pars_fragment>\n#include <fog_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tif ( mod( vLineDistance, totalSize ) > dashSize ) {\n\t\tdiscard;\n\t}\n\tvec3 outgoingLight = vec3( 0.0 );\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <logdepthbuf_fragment>\n\t#include <color_fragment>\n\toutgoingLight = diffuseColor.rgb;\n\t#include <output_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n}";
  7774. const vertex$a = "#include <common>\n#include <uv_pars_vertex>\n#include <uv2_pars_vertex>\n#include <envmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <uv2_vertex>\n\t#include <color_vertex>\n\t#include <morphcolor_vertex>\n\t#if defined ( USE_ENVMAP ) || defined ( USE_SKINNING )\n\t\t#include <beginnormal_vertex>\n\t\t#include <morphnormal_vertex>\n\t\t#include <skinbase_vertex>\n\t\t#include <skinnormal_vertex>\n\t\t#include <defaultnormal_vertex>\n\t#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <worldpos_vertex>\n\t#include <envmap_vertex>\n\t#include <fog_vertex>\n}";
  7775. const fragment$a = "uniform vec3 diffuse;\nuniform float opacity;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include <common>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <uv2_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <envmap_common_pars_fragment>\n#include <envmap_pars_fragment>\n#include <fog_pars_fragment>\n#include <specularmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <specularmap_fragment>\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\t#ifdef USE_LIGHTMAP\n\t\tvec4 lightMapTexel = texture2D( lightMap, vUv2 );\n\t\treflectedLight.indirectDiffuse += lightMapTexel.rgb * lightMapIntensity * RECIPROCAL_PI;\n\t#else\n\t\treflectedLight.indirectDiffuse += vec3( 1.0 );\n\t#endif\n\t#include <aomap_fragment>\n\treflectedLight.indirectDiffuse *= diffuseColor.rgb;\n\tvec3 outgoingLight = reflectedLight.indirectDiffuse;\n\t#include <envmap_fragment>\n\t#include <output_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";
  7776. const vertex$9 = "#define LAMBERT\nvarying vec3 vViewPosition;\n#include <common>\n#include <uv_pars_vertex>\n#include <uv2_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <envmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <normal_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <uv2_vertex>\n\t#include <color_vertex>\n\t#include <morphcolor_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#include <normal_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\tvViewPosition = - mvPosition.xyz;\n\t#include <worldpos_vertex>\n\t#include <envmap_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n}";
  7777. const fragment$9 = "#define LAMBERT\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float opacity;\n#include <common>\n#include <packing>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <uv2_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <envmap_common_pars_fragment>\n#include <envmap_pars_fragment>\n#include <fog_pars_fragment>\n#include <bsdfs>\n#include <lights_pars_begin>\n#include <normal_pars_fragment>\n#include <lights_lambert_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <specularmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <specularmap_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\t#include <emissivemap_fragment>\n\t#include <lights_lambert_fragment>\n\t#include <lights_fragment_begin>\n\t#include <lights_fragment_maps>\n\t#include <lights_fragment_end>\n\t#include <aomap_fragment>\n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance;\n\t#include <envmap_fragment>\n\t#include <output_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";
  7778. const vertex$8 = "#define MATCAP\nvarying vec3 vViewPosition;\n#include <common>\n#include <uv_pars_vertex>\n#include <color_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <fog_pars_vertex>\n#include <normal_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <color_vertex>\n\t#include <morphcolor_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#include <normal_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <fog_vertex>\n\tvViewPosition = - mvPosition.xyz;\n}";
  7779. const fragment$8 = "#define MATCAP\nuniform vec3 diffuse;\nuniform float opacity;\nuniform sampler2D matcap;\nvarying vec3 vViewPosition;\n#include <common>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <fog_pars_fragment>\n#include <normal_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\tvec3 viewDir = normalize( vViewPosition );\n\tvec3 x = normalize( vec3( viewDir.z, 0.0, - viewDir.x ) );\n\tvec3 y = cross( viewDir, x );\n\tvec2 uv = vec2( dot( x, normal ), dot( y, normal ) ) * 0.495 + 0.5;\n\t#ifdef USE_MATCAP\n\t\tvec4 matcapColor = texture2D( matcap, uv );\n\t#else\n\t\tvec4 matcapColor = vec4( vec3( mix( 0.2, 0.8, uv.y ) ), 1.0 );\n\t#endif\n\tvec3 outgoingLight = diffuseColor.rgb * matcapColor.rgb;\n\t#include <output_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";
  7780. const vertex$7 = "#define NORMAL\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( TANGENTSPACE_NORMALMAP )\n\tvarying vec3 vViewPosition;\n#endif\n#include <common>\n#include <uv_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <normal_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#include <normal_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( TANGENTSPACE_NORMALMAP )\n\tvViewPosition = - mvPosition.xyz;\n#endif\n}";
  7781. const fragment$7 = "#define NORMAL\nuniform float opacity;\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( TANGENTSPACE_NORMALMAP )\n\tvarying vec3 vViewPosition;\n#endif\n#include <packing>\n#include <uv_pars_fragment>\n#include <normal_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\t#include <logdepthbuf_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\tgl_FragColor = vec4( packNormalToRGB( normal ), opacity );\n\t#ifdef OPAQUE\n\t\tgl_FragColor.a = 1.0;\n\t#endif\n}";
  7782. const vertex$6 = "#define PHONG\nvarying vec3 vViewPosition;\n#include <common>\n#include <uv_pars_vertex>\n#include <uv2_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <envmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <normal_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <uv2_vertex>\n\t#include <color_vertex>\n\t#include <morphcolor_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#include <normal_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\tvViewPosition = - mvPosition.xyz;\n\t#include <worldpos_vertex>\n\t#include <envmap_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n}";
  7783. const fragment$6 = "#define PHONG\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform vec3 specular;\nuniform float shininess;\nuniform float opacity;\n#include <common>\n#include <packing>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <uv2_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <envmap_common_pars_fragment>\n#include <envmap_pars_fragment>\n#include <fog_pars_fragment>\n#include <bsdfs>\n#include <lights_pars_begin>\n#include <normal_pars_fragment>\n#include <lights_phong_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <specularmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <specularmap_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\t#include <emissivemap_fragment>\n\t#include <lights_phong_fragment>\n\t#include <lights_fragment_begin>\n\t#include <lights_fragment_maps>\n\t#include <lights_fragment_end>\n\t#include <aomap_fragment>\n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance;\n\t#include <envmap_fragment>\n\t#include <output_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";
  7784. const vertex$5 = "#define STANDARD\nvarying vec3 vViewPosition;\n#ifdef USE_TRANSMISSION\n\tvarying vec3 vWorldPosition;\n#endif\n#include <common>\n#include <uv_pars_vertex>\n#include <uv2_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <normal_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <uv2_vertex>\n\t#include <color_vertex>\n\t#include <morphcolor_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#include <normal_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\tvViewPosition = - mvPosition.xyz;\n\t#include <worldpos_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n#ifdef USE_TRANSMISSION\n\tvWorldPosition = worldPosition.xyz;\n#endif\n}";
  7785. const fragment$5 = "#define STANDARD\n#ifdef PHYSICAL\n\t#define IOR\n\t#define SPECULAR\n#endif\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float roughness;\nuniform float metalness;\nuniform float opacity;\n#ifdef IOR\n\tuniform float ior;\n#endif\n#ifdef SPECULAR\n\tuniform float specularIntensity;\n\tuniform vec3 specularColor;\n\t#ifdef USE_SPECULARINTENSITYMAP\n\t\tuniform sampler2D specularIntensityMap;\n\t#endif\n\t#ifdef USE_SPECULARCOLORMAP\n\t\tuniform sampler2D specularColorMap;\n\t#endif\n#endif\n#ifdef USE_CLEARCOAT\n\tuniform float clearcoat;\n\tuniform float clearcoatRoughness;\n#endif\n#ifdef USE_IRIDESCENCE\n\tuniform float iridescence;\n\tuniform float iridescenceIOR;\n\tuniform float iridescenceThicknessMinimum;\n\tuniform float iridescenceThicknessMaximum;\n#endif\n#ifdef USE_SHEEN\n\tuniform vec3 sheenColor;\n\tuniform float sheenRoughness;\n\t#ifdef USE_SHEENCOLORMAP\n\t\tuniform sampler2D sheenColorMap;\n\t#endif\n\t#ifdef USE_SHEENROUGHNESSMAP\n\t\tuniform sampler2D sheenRoughnessMap;\n\t#endif\n#endif\nvarying vec3 vViewPosition;\n#include <common>\n#include <packing>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <uv2_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <bsdfs>\n#include <iridescence_fragment>\n#include <cube_uv_reflection_fragment>\n#include <envmap_common_pars_fragment>\n#include <envmap_physical_pars_fragment>\n#include <fog_pars_fragment>\n#include <lights_pars_begin>\n#include <normal_pars_fragment>\n#include <lights_physical_pars_fragment>\n#include <transmission_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <clearcoat_pars_fragment>\n#include <iridescence_pars_fragment>\n#include <roughnessmap_pars_fragment>\n#include <metalnessmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <roughnessmap_fragment>\n\t#include <metalnessmap_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\t#include <clearcoat_normal_fragment_begin>\n\t#include <clearcoat_normal_fragment_maps>\n\t#include <emissivemap_fragment>\n\t#include <lights_physical_fragment>\n\t#include <lights_fragment_begin>\n\t#include <lights_fragment_maps>\n\t#include <lights_fragment_end>\n\t#include <aomap_fragment>\n\tvec3 totalDiffuse = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse;\n\tvec3 totalSpecular = reflectedLight.directSpecular + reflectedLight.indirectSpecular;\n\t#include <transmission_fragment>\n\tvec3 outgoingLight = totalDiffuse + totalSpecular + totalEmissiveRadiance;\n\t#ifdef USE_SHEEN\n\t\tfloat sheenEnergyComp = 1.0 - 0.157 * max3( material.sheenColor );\n\t\toutgoingLight = outgoingLight * sheenEnergyComp + sheenSpecular;\n\t#endif\n\t#ifdef USE_CLEARCOAT\n\t\tfloat dotNVcc = saturate( dot( geometry.clearcoatNormal, geometry.viewDir ) );\n\t\tvec3 Fcc = F_Schlick( material.clearcoatF0, material.clearcoatF90, dotNVcc );\n\t\toutgoingLight = outgoingLight * ( 1.0 - material.clearcoat * Fcc ) + clearcoatSpecular * material.clearcoat;\n\t#endif\n\t#include <output_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";
  7786. const vertex$4 = "#define TOON\nvarying vec3 vViewPosition;\n#include <common>\n#include <uv_pars_vertex>\n#include <uv2_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <normal_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <uv2_vertex>\n\t#include <color_vertex>\n\t#include <morphcolor_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#include <normal_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\tvViewPosition = - mvPosition.xyz;\n\t#include <worldpos_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n}";
  7787. const fragment$4 = "#define TOON\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float opacity;\n#include <common>\n#include <packing>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <uv2_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <gradientmap_pars_fragment>\n#include <fog_pars_fragment>\n#include <bsdfs>\n#include <lights_pars_begin>\n#include <normal_pars_fragment>\n#include <lights_toon_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\t#include <emissivemap_fragment>\n\t#include <lights_toon_fragment>\n\t#include <lights_fragment_begin>\n\t#include <lights_fragment_maps>\n\t#include <lights_fragment_end>\n\t#include <aomap_fragment>\n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance;\n\t#include <output_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";
  7788. const vertex$3 = "uniform float size;\nuniform float scale;\n#include <common>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <color_vertex>\n\t#include <morphcolor_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <project_vertex>\n\tgl_PointSize = size;\n\t#ifdef USE_SIZEATTENUATION\n\t\tbool isPerspective = isPerspectiveMatrix( projectionMatrix );\n\t\tif ( isPerspective ) gl_PointSize *= ( scale / - mvPosition.z );\n\t#endif\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <worldpos_vertex>\n\t#include <fog_vertex>\n}";
  7789. const fragment$3 = "uniform vec3 diffuse;\nuniform float opacity;\n#include <common>\n#include <color_pars_fragment>\n#include <map_particle_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <fog_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec3 outgoingLight = vec3( 0.0 );\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <logdepthbuf_fragment>\n\t#include <map_particle_fragment>\n\t#include <color_fragment>\n\t#include <alphatest_fragment>\n\toutgoingLight = diffuseColor.rgb;\n\t#include <output_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n}";
  7790. const vertex$2 = "#include <common>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\nvoid main() {\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <project_vertex>\n\t#include <worldpos_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n}";
  7791. const fragment$2 = "uniform vec3 color;\nuniform float opacity;\n#include <common>\n#include <packing>\n#include <fog_pars_fragment>\n#include <bsdfs>\n#include <lights_pars_begin>\n#include <shadowmap_pars_fragment>\n#include <shadowmask_pars_fragment>\nvoid main() {\n\tgl_FragColor = vec4( color, opacity * ( 1.0 - getShadowMask() ) );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n}";
  7792. const vertex$1 = "uniform float rotation;\nuniform vec2 center;\n#include <common>\n#include <uv_pars_vertex>\n#include <fog_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\tvec4 mvPosition = modelViewMatrix * vec4( 0.0, 0.0, 0.0, 1.0 );\n\tvec2 scale;\n\tscale.x = length( vec3( modelMatrix[ 0 ].x, modelMatrix[ 0 ].y, modelMatrix[ 0 ].z ) );\n\tscale.y = length( vec3( modelMatrix[ 1 ].x, modelMatrix[ 1 ].y, modelMatrix[ 1 ].z ) );\n\t#ifndef USE_SIZEATTENUATION\n\t\tbool isPerspective = isPerspectiveMatrix( projectionMatrix );\n\t\tif ( isPerspective ) scale *= - mvPosition.z;\n\t#endif\n\tvec2 alignedPosition = ( position.xy - ( center - vec2( 0.5 ) ) ) * scale;\n\tvec2 rotatedPosition;\n\trotatedPosition.x = cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y;\n\trotatedPosition.y = sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y;\n\tmvPosition.xy += rotatedPosition;\n\tgl_Position = projectionMatrix * mvPosition;\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <fog_vertex>\n}";
  7793. const fragment$1 = "uniform vec3 diffuse;\nuniform float opacity;\n#include <common>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <fog_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec3 outgoingLight = vec3( 0.0 );\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\toutgoingLight = diffuseColor.rgb;\n\t#include <output_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n}";
  7794. const ShaderChunk = {
  7795. alphamap_fragment: alphamap_fragment,
  7796. alphamap_pars_fragment: alphamap_pars_fragment,
  7797. alphatest_fragment: alphatest_fragment,
  7798. alphatest_pars_fragment: alphatest_pars_fragment,
  7799. aomap_fragment: aomap_fragment,
  7800. aomap_pars_fragment: aomap_pars_fragment,
  7801. begin_vertex: begin_vertex,
  7802. beginnormal_vertex: beginnormal_vertex,
  7803. bsdfs: bsdfs,
  7804. iridescence_fragment: iridescence_fragment,
  7805. bumpmap_pars_fragment: bumpmap_pars_fragment,
  7806. clipping_planes_fragment: clipping_planes_fragment,
  7807. clipping_planes_pars_fragment: clipping_planes_pars_fragment,
  7808. clipping_planes_pars_vertex: clipping_planes_pars_vertex,
  7809. clipping_planes_vertex: clipping_planes_vertex,
  7810. color_fragment: color_fragment,
  7811. color_pars_fragment: color_pars_fragment,
  7812. color_pars_vertex: color_pars_vertex,
  7813. color_vertex: color_vertex,
  7814. common: common,
  7815. cube_uv_reflection_fragment: cube_uv_reflection_fragment,
  7816. defaultnormal_vertex: defaultnormal_vertex,
  7817. displacementmap_pars_vertex: displacementmap_pars_vertex,
  7818. displacementmap_vertex: displacementmap_vertex,
  7819. emissivemap_fragment: emissivemap_fragment,
  7820. emissivemap_pars_fragment: emissivemap_pars_fragment,
  7821. encodings_fragment: encodings_fragment,
  7822. encodings_pars_fragment: encodings_pars_fragment,
  7823. envmap_fragment: envmap_fragment,
  7824. envmap_common_pars_fragment: envmap_common_pars_fragment,
  7825. envmap_pars_fragment: envmap_pars_fragment,
  7826. envmap_pars_vertex: envmap_pars_vertex,
  7827. envmap_physical_pars_fragment: envmap_physical_pars_fragment,
  7828. envmap_vertex: envmap_vertex,
  7829. fog_vertex: fog_vertex,
  7830. fog_pars_vertex: fog_pars_vertex,
  7831. fog_fragment: fog_fragment,
  7832. fog_pars_fragment: fog_pars_fragment,
  7833. gradientmap_pars_fragment: gradientmap_pars_fragment,
  7834. lightmap_fragment: lightmap_fragment,
  7835. lightmap_pars_fragment: lightmap_pars_fragment,
  7836. lights_lambert_fragment: lights_lambert_fragment,
  7837. lights_lambert_pars_fragment: lights_lambert_pars_fragment,
  7838. lights_pars_begin: lights_pars_begin,
  7839. lights_toon_fragment: lights_toon_fragment,
  7840. lights_toon_pars_fragment: lights_toon_pars_fragment,
  7841. lights_phong_fragment: lights_phong_fragment,
  7842. lights_phong_pars_fragment: lights_phong_pars_fragment,
  7843. lights_physical_fragment: lights_physical_fragment,
  7844. lights_physical_pars_fragment: lights_physical_pars_fragment,
  7845. lights_fragment_begin: lights_fragment_begin,
  7846. lights_fragment_maps: lights_fragment_maps,
  7847. lights_fragment_end: lights_fragment_end,
  7848. logdepthbuf_fragment: logdepthbuf_fragment,
  7849. logdepthbuf_pars_fragment: logdepthbuf_pars_fragment,
  7850. logdepthbuf_pars_vertex: logdepthbuf_pars_vertex,
  7851. logdepthbuf_vertex: logdepthbuf_vertex,
  7852. map_fragment: map_fragment,
  7853. map_pars_fragment: map_pars_fragment,
  7854. map_particle_fragment: map_particle_fragment,
  7855. map_particle_pars_fragment: map_particle_pars_fragment,
  7856. metalnessmap_fragment: metalnessmap_fragment,
  7857. metalnessmap_pars_fragment: metalnessmap_pars_fragment,
  7858. morphcolor_vertex: morphcolor_vertex,
  7859. morphnormal_vertex: morphnormal_vertex,
  7860. morphtarget_pars_vertex: morphtarget_pars_vertex,
  7861. morphtarget_vertex: morphtarget_vertex,
  7862. normal_fragment_begin: normal_fragment_begin,
  7863. normal_fragment_maps: normal_fragment_maps,
  7864. normal_pars_fragment: normal_pars_fragment,
  7865. normal_pars_vertex: normal_pars_vertex,
  7866. normal_vertex: normal_vertex,
  7867. normalmap_pars_fragment: normalmap_pars_fragment,
  7868. clearcoat_normal_fragment_begin: clearcoat_normal_fragment_begin,
  7869. clearcoat_normal_fragment_maps: clearcoat_normal_fragment_maps,
  7870. clearcoat_pars_fragment: clearcoat_pars_fragment,
  7871. iridescence_pars_fragment: iridescence_pars_fragment,
  7872. output_fragment: output_fragment,
  7873. packing: packing,
  7874. premultiplied_alpha_fragment: premultiplied_alpha_fragment,
  7875. project_vertex: project_vertex,
  7876. dithering_fragment: dithering_fragment,
  7877. dithering_pars_fragment: dithering_pars_fragment,
  7878. roughnessmap_fragment: roughnessmap_fragment,
  7879. roughnessmap_pars_fragment: roughnessmap_pars_fragment,
  7880. shadowmap_pars_fragment: shadowmap_pars_fragment,
  7881. shadowmap_pars_vertex: shadowmap_pars_vertex,
  7882. shadowmap_vertex: shadowmap_vertex,
  7883. shadowmask_pars_fragment: shadowmask_pars_fragment,
  7884. skinbase_vertex: skinbase_vertex,
  7885. skinning_pars_vertex: skinning_pars_vertex,
  7886. skinning_vertex: skinning_vertex,
  7887. skinnormal_vertex: skinnormal_vertex,
  7888. specularmap_fragment: specularmap_fragment,
  7889. specularmap_pars_fragment: specularmap_pars_fragment,
  7890. tonemapping_fragment: tonemapping_fragment,
  7891. tonemapping_pars_fragment: tonemapping_pars_fragment,
  7892. transmission_fragment: transmission_fragment,
  7893. transmission_pars_fragment: transmission_pars_fragment,
  7894. uv_pars_fragment: uv_pars_fragment,
  7895. uv_pars_vertex: uv_pars_vertex,
  7896. uv_vertex: uv_vertex,
  7897. uv2_pars_fragment: uv2_pars_fragment,
  7898. uv2_pars_vertex: uv2_pars_vertex,
  7899. uv2_vertex: uv2_vertex,
  7900. worldpos_vertex: worldpos_vertex,
  7901. background_vert: vertex$h,
  7902. background_frag: fragment$h,
  7903. backgroundCube_vert: vertex$g,
  7904. backgroundCube_frag: fragment$g,
  7905. cube_vert: vertex$f,
  7906. cube_frag: fragment$f,
  7907. depth_vert: vertex$e,
  7908. depth_frag: fragment$e,
  7909. distanceRGBA_vert: vertex$d,
  7910. distanceRGBA_frag: fragment$d,
  7911. equirect_vert: vertex$c,
  7912. equirect_frag: fragment$c,
  7913. linedashed_vert: vertex$b,
  7914. linedashed_frag: fragment$b,
  7915. meshbasic_vert: vertex$a,
  7916. meshbasic_frag: fragment$a,
  7917. meshlambert_vert: vertex$9,
  7918. meshlambert_frag: fragment$9,
  7919. meshmatcap_vert: vertex$8,
  7920. meshmatcap_frag: fragment$8,
  7921. meshnormal_vert: vertex$7,
  7922. meshnormal_frag: fragment$7,
  7923. meshphong_vert: vertex$6,
  7924. meshphong_frag: fragment$6,
  7925. meshphysical_vert: vertex$5,
  7926. meshphysical_frag: fragment$5,
  7927. meshtoon_vert: vertex$4,
  7928. meshtoon_frag: fragment$4,
  7929. points_vert: vertex$3,
  7930. points_frag: fragment$3,
  7931. shadow_vert: vertex$2,
  7932. shadow_frag: fragment$2,
  7933. sprite_vert: vertex$1,
  7934. sprite_frag: fragment$1
  7935. };
  7936. /**
  7937. * Uniforms library for shared webgl shaders
  7938. */
  7939. const UniformsLib = {
  7940. common: {
  7941. diffuse: { value: /*@__PURE__*/ new Color( 0xffffff ) },
  7942. opacity: { value: 1.0 },
  7943. map: { value: null },
  7944. uvTransform: { value: /*@__PURE__*/ new Matrix3() },
  7945. uv2Transform: { value: /*@__PURE__*/ new Matrix3() },
  7946. alphaMap: { value: null },
  7947. alphaTest: { value: 0 }
  7948. },
  7949. specularmap: {
  7950. specularMap: { value: null },
  7951. },
  7952. envmap: {
  7953. envMap: { value: null },
  7954. flipEnvMap: { value: - 1 },
  7955. reflectivity: { value: 1.0 }, // basic, lambert, phong
  7956. ior: { value: 1.5 }, // physical
  7957. refractionRatio: { value: 0.98 }, // basic, lambert, phong
  7958. },
  7959. aomap: {
  7960. aoMap: { value: null },
  7961. aoMapIntensity: { value: 1 }
  7962. },
  7963. lightmap: {
  7964. lightMap: { value: null },
  7965. lightMapIntensity: { value: 1 }
  7966. },
  7967. emissivemap: {
  7968. emissiveMap: { value: null }
  7969. },
  7970. bumpmap: {
  7971. bumpMap: { value: null },
  7972. bumpScale: { value: 1 }
  7973. },
  7974. normalmap: {
  7975. normalMap: { value: null },
  7976. normalScale: { value: /*@__PURE__*/ new Vector2( 1, 1 ) }
  7977. },
  7978. displacementmap: {
  7979. displacementMap: { value: null },
  7980. displacementScale: { value: 1 },
  7981. displacementBias: { value: 0 }
  7982. },
  7983. roughnessmap: {
  7984. roughnessMap: { value: null }
  7985. },
  7986. metalnessmap: {
  7987. metalnessMap: { value: null }
  7988. },
  7989. gradientmap: {
  7990. gradientMap: { value: null }
  7991. },
  7992. fog: {
  7993. fogDensity: { value: 0.00025 },
  7994. fogNear: { value: 1 },
  7995. fogFar: { value: 2000 },
  7996. fogColor: { value: /*@__PURE__*/ new Color( 0xffffff ) }
  7997. },
  7998. lights: {
  7999. ambientLightColor: { value: [] },
  8000. lightProbe: { value: [] },
  8001. directionalLights: { value: [], properties: {
  8002. direction: {},
  8003. color: {}
  8004. } },
  8005. directionalLightShadows: { value: [], properties: {
  8006. shadowBias: {},
  8007. shadowNormalBias: {},
  8008. shadowRadius: {},
  8009. shadowMapSize: {}
  8010. } },
  8011. directionalShadowMap: { value: [] },
  8012. directionalShadowMatrix: { value: [] },
  8013. spotLights: { value: [], properties: {
  8014. color: {},
  8015. position: {},
  8016. direction: {},
  8017. distance: {},
  8018. coneCos: {},
  8019. penumbraCos: {},
  8020. decay: {}
  8021. } },
  8022. spotLightShadows: { value: [], properties: {
  8023. shadowBias: {},
  8024. shadowNormalBias: {},
  8025. shadowRadius: {},
  8026. shadowMapSize: {}
  8027. } },
  8028. spotLightMap: { value: [] },
  8029. spotShadowMap: { value: [] },
  8030. spotLightMatrix: { value: [] },
  8031. pointLights: { value: [], properties: {
  8032. color: {},
  8033. position: {},
  8034. decay: {},
  8035. distance: {}
  8036. } },
  8037. pointLightShadows: { value: [], properties: {
  8038. shadowBias: {},
  8039. shadowNormalBias: {},
  8040. shadowRadius: {},
  8041. shadowMapSize: {},
  8042. shadowCameraNear: {},
  8043. shadowCameraFar: {}
  8044. } },
  8045. pointShadowMap: { value: [] },
  8046. pointShadowMatrix: { value: [] },
  8047. hemisphereLights: { value: [], properties: {
  8048. direction: {},
  8049. skyColor: {},
  8050. groundColor: {}
  8051. } },
  8052. // TODO (abelnation): RectAreaLight BRDF data needs to be moved from example to main src
  8053. rectAreaLights: { value: [], properties: {
  8054. color: {},
  8055. position: {},
  8056. width: {},
  8057. height: {}
  8058. } },
  8059. ltc_1: { value: null },
  8060. ltc_2: { value: null }
  8061. },
  8062. points: {
  8063. diffuse: { value: /*@__PURE__*/ new Color( 0xffffff ) },
  8064. opacity: { value: 1.0 },
  8065. size: { value: 1.0 },
  8066. scale: { value: 1.0 },
  8067. map: { value: null },
  8068. alphaMap: { value: null },
  8069. alphaTest: { value: 0 },
  8070. uvTransform: { value: /*@__PURE__*/ new Matrix3() }
  8071. },
  8072. sprite: {
  8073. diffuse: { value: /*@__PURE__*/ new Color( 0xffffff ) },
  8074. opacity: { value: 1.0 },
  8075. center: { value: /*@__PURE__*/ new Vector2( 0.5, 0.5 ) },
  8076. rotation: { value: 0.0 },
  8077. map: { value: null },
  8078. alphaMap: { value: null },
  8079. alphaTest: { value: 0 },
  8080. uvTransform: { value: /*@__PURE__*/ new Matrix3() }
  8081. }
  8082. };
  8083. const ShaderLib = {
  8084. basic: {
  8085. uniforms: /*@__PURE__*/ mergeUniforms( [
  8086. UniformsLib.common,
  8087. UniformsLib.specularmap,
  8088. UniformsLib.envmap,
  8089. UniformsLib.aomap,
  8090. UniformsLib.lightmap,
  8091. UniformsLib.fog
  8092. ] ),
  8093. vertexShader: ShaderChunk.meshbasic_vert,
  8094. fragmentShader: ShaderChunk.meshbasic_frag
  8095. },
  8096. lambert: {
  8097. uniforms: /*@__PURE__*/ mergeUniforms( [
  8098. UniformsLib.common,
  8099. UniformsLib.specularmap,
  8100. UniformsLib.envmap,
  8101. UniformsLib.aomap,
  8102. UniformsLib.lightmap,
  8103. UniformsLib.emissivemap,
  8104. UniformsLib.bumpmap,
  8105. UniformsLib.normalmap,
  8106. UniformsLib.displacementmap,
  8107. UniformsLib.fog,
  8108. UniformsLib.lights,
  8109. {
  8110. emissive: { value: /*@__PURE__*/ new Color( 0x000000 ) }
  8111. }
  8112. ] ),
  8113. vertexShader: ShaderChunk.meshlambert_vert,
  8114. fragmentShader: ShaderChunk.meshlambert_frag
  8115. },
  8116. phong: {
  8117. uniforms: /*@__PURE__*/ mergeUniforms( [
  8118. UniformsLib.common,
  8119. UniformsLib.specularmap,
  8120. UniformsLib.envmap,
  8121. UniformsLib.aomap,
  8122. UniformsLib.lightmap,
  8123. UniformsLib.emissivemap,
  8124. UniformsLib.bumpmap,
  8125. UniformsLib.normalmap,
  8126. UniformsLib.displacementmap,
  8127. UniformsLib.fog,
  8128. UniformsLib.lights,
  8129. {
  8130. emissive: { value: /*@__PURE__*/ new Color( 0x000000 ) },
  8131. specular: { value: /*@__PURE__*/ new Color( 0x111111 ) },
  8132. shininess: { value: 30 }
  8133. }
  8134. ] ),
  8135. vertexShader: ShaderChunk.meshphong_vert,
  8136. fragmentShader: ShaderChunk.meshphong_frag
  8137. },
  8138. standard: {
  8139. uniforms: /*@__PURE__*/ mergeUniforms( [
  8140. UniformsLib.common,
  8141. UniformsLib.envmap,
  8142. UniformsLib.aomap,
  8143. UniformsLib.lightmap,
  8144. UniformsLib.emissivemap,
  8145. UniformsLib.bumpmap,
  8146. UniformsLib.normalmap,
  8147. UniformsLib.displacementmap,
  8148. UniformsLib.roughnessmap,
  8149. UniformsLib.metalnessmap,
  8150. UniformsLib.fog,
  8151. UniformsLib.lights,
  8152. {
  8153. emissive: { value: /*@__PURE__*/ new Color( 0x000000 ) },
  8154. roughness: { value: 1.0 },
  8155. metalness: { value: 0.0 },
  8156. envMapIntensity: { value: 1 } // temporary
  8157. }
  8158. ] ),
  8159. vertexShader: ShaderChunk.meshphysical_vert,
  8160. fragmentShader: ShaderChunk.meshphysical_frag
  8161. },
  8162. toon: {
  8163. uniforms: /*@__PURE__*/ mergeUniforms( [
  8164. UniformsLib.common,
  8165. UniformsLib.aomap,
  8166. UniformsLib.lightmap,
  8167. UniformsLib.emissivemap,
  8168. UniformsLib.bumpmap,
  8169. UniformsLib.normalmap,
  8170. UniformsLib.displacementmap,
  8171. UniformsLib.gradientmap,
  8172. UniformsLib.fog,
  8173. UniformsLib.lights,
  8174. {
  8175. emissive: { value: /*@__PURE__*/ new Color( 0x000000 ) }
  8176. }
  8177. ] ),
  8178. vertexShader: ShaderChunk.meshtoon_vert,
  8179. fragmentShader: ShaderChunk.meshtoon_frag
  8180. },
  8181. matcap: {
  8182. uniforms: /*@__PURE__*/ mergeUniforms( [
  8183. UniformsLib.common,
  8184. UniformsLib.bumpmap,
  8185. UniformsLib.normalmap,
  8186. UniformsLib.displacementmap,
  8187. UniformsLib.fog,
  8188. {
  8189. matcap: { value: null }
  8190. }
  8191. ] ),
  8192. vertexShader: ShaderChunk.meshmatcap_vert,
  8193. fragmentShader: ShaderChunk.meshmatcap_frag
  8194. },
  8195. points: {
  8196. uniforms: /*@__PURE__*/ mergeUniforms( [
  8197. UniformsLib.points,
  8198. UniformsLib.fog
  8199. ] ),
  8200. vertexShader: ShaderChunk.points_vert,
  8201. fragmentShader: ShaderChunk.points_frag
  8202. },
  8203. dashed: {
  8204. uniforms: /*@__PURE__*/ mergeUniforms( [
  8205. UniformsLib.common,
  8206. UniformsLib.fog,
  8207. {
  8208. scale: { value: 1 },
  8209. dashSize: { value: 1 },
  8210. totalSize: { value: 2 }
  8211. }
  8212. ] ),
  8213. vertexShader: ShaderChunk.linedashed_vert,
  8214. fragmentShader: ShaderChunk.linedashed_frag
  8215. },
  8216. depth: {
  8217. uniforms: /*@__PURE__*/ mergeUniforms( [
  8218. UniformsLib.common,
  8219. UniformsLib.displacementmap
  8220. ] ),
  8221. vertexShader: ShaderChunk.depth_vert,
  8222. fragmentShader: ShaderChunk.depth_frag
  8223. },
  8224. normal: {
  8225. uniforms: /*@__PURE__*/ mergeUniforms( [
  8226. UniformsLib.common,
  8227. UniformsLib.bumpmap,
  8228. UniformsLib.normalmap,
  8229. UniformsLib.displacementmap,
  8230. {
  8231. opacity: { value: 1.0 }
  8232. }
  8233. ] ),
  8234. vertexShader: ShaderChunk.meshnormal_vert,
  8235. fragmentShader: ShaderChunk.meshnormal_frag
  8236. },
  8237. sprite: {
  8238. uniforms: /*@__PURE__*/ mergeUniforms( [
  8239. UniformsLib.sprite,
  8240. UniformsLib.fog
  8241. ] ),
  8242. vertexShader: ShaderChunk.sprite_vert,
  8243. fragmentShader: ShaderChunk.sprite_frag
  8244. },
  8245. background: {
  8246. uniforms: {
  8247. uvTransform: { value: /*@__PURE__*/ new Matrix3() },
  8248. t2D: { value: null },
  8249. backgroundIntensity: { value: 1 }
  8250. },
  8251. vertexShader: ShaderChunk.background_vert,
  8252. fragmentShader: ShaderChunk.background_frag
  8253. },
  8254. backgroundCube: {
  8255. uniforms: {
  8256. envMap: { value: null },
  8257. flipEnvMap: { value: - 1 },
  8258. backgroundBlurriness: { value: 0 },
  8259. backgroundIntensity: { value: 1 }
  8260. },
  8261. vertexShader: ShaderChunk.backgroundCube_vert,
  8262. fragmentShader: ShaderChunk.backgroundCube_frag
  8263. },
  8264. cube: {
  8265. uniforms: {
  8266. tCube: { value: null },
  8267. tFlip: { value: - 1 },
  8268. opacity: { value: 1.0 }
  8269. },
  8270. vertexShader: ShaderChunk.cube_vert,
  8271. fragmentShader: ShaderChunk.cube_frag
  8272. },
  8273. equirect: {
  8274. uniforms: {
  8275. tEquirect: { value: null },
  8276. },
  8277. vertexShader: ShaderChunk.equirect_vert,
  8278. fragmentShader: ShaderChunk.equirect_frag
  8279. },
  8280. distanceRGBA: {
  8281. uniforms: /*@__PURE__*/ mergeUniforms( [
  8282. UniformsLib.common,
  8283. UniformsLib.displacementmap,
  8284. {
  8285. referencePosition: { value: /*@__PURE__*/ new Vector3() },
  8286. nearDistance: { value: 1 },
  8287. farDistance: { value: 1000 }
  8288. }
  8289. ] ),
  8290. vertexShader: ShaderChunk.distanceRGBA_vert,
  8291. fragmentShader: ShaderChunk.distanceRGBA_frag
  8292. },
  8293. shadow: {
  8294. uniforms: /*@__PURE__*/ mergeUniforms( [
  8295. UniformsLib.lights,
  8296. UniformsLib.fog,
  8297. {
  8298. color: { value: /*@__PURE__*/ new Color( 0x00000 ) },
  8299. opacity: { value: 1.0 }
  8300. },
  8301. ] ),
  8302. vertexShader: ShaderChunk.shadow_vert,
  8303. fragmentShader: ShaderChunk.shadow_frag
  8304. }
  8305. };
  8306. ShaderLib.physical = {
  8307. uniforms: /*@__PURE__*/ mergeUniforms( [
  8308. ShaderLib.standard.uniforms,
  8309. {
  8310. clearcoat: { value: 0 },
  8311. clearcoatMap: { value: null },
  8312. clearcoatRoughness: { value: 0 },
  8313. clearcoatRoughnessMap: { value: null },
  8314. clearcoatNormalScale: { value: /*@__PURE__*/ new Vector2( 1, 1 ) },
  8315. clearcoatNormalMap: { value: null },
  8316. iridescence: { value: 0 },
  8317. iridescenceMap: { value: null },
  8318. iridescenceIOR: { value: 1.3 },
  8319. iridescenceThicknessMinimum: { value: 100 },
  8320. iridescenceThicknessMaximum: { value: 400 },
  8321. iridescenceThicknessMap: { value: null },
  8322. sheen: { value: 0 },
  8323. sheenColor: { value: /*@__PURE__*/ new Color( 0x000000 ) },
  8324. sheenColorMap: { value: null },
  8325. sheenRoughness: { value: 1 },
  8326. sheenRoughnessMap: { value: null },
  8327. transmission: { value: 0 },
  8328. transmissionMap: { value: null },
  8329. transmissionSamplerSize: { value: /*@__PURE__*/ new Vector2() },
  8330. transmissionSamplerMap: { value: null },
  8331. thickness: { value: 0 },
  8332. thicknessMap: { value: null },
  8333. attenuationDistance: { value: 0 },
  8334. attenuationColor: { value: /*@__PURE__*/ new Color( 0x000000 ) },
  8335. specularIntensity: { value: 1 },
  8336. specularIntensityMap: { value: null },
  8337. specularColor: { value: /*@__PURE__*/ new Color( 1, 1, 1 ) },
  8338. specularColorMap: { value: null },
  8339. }
  8340. ] ),
  8341. vertexShader: ShaderChunk.meshphysical_vert,
  8342. fragmentShader: ShaderChunk.meshphysical_frag
  8343. };
  8344. const _rgb = { r: 0, b: 0, g: 0 };
  8345. function WebGLBackground( renderer, cubemaps, cubeuvmaps, state, objects, alpha, premultipliedAlpha ) {
  8346. const clearColor = new Color( 0x000000 );
  8347. let clearAlpha = alpha === true ? 0 : 1;
  8348. let planeMesh;
  8349. let boxMesh;
  8350. let currentBackground = null;
  8351. let currentBackgroundVersion = 0;
  8352. let currentTonemapping = null;
  8353. function render( renderList, scene ) {
  8354. let forceClear = false;
  8355. let background = scene.isScene === true ? scene.background : null;
  8356. if ( background && background.isTexture ) {
  8357. const usePMREM = scene.backgroundBlurriness > 0; // use PMREM if the user wants to blur the background
  8358. background = ( usePMREM ? cubeuvmaps : cubemaps ).get( background );
  8359. }
  8360. // Ignore background in AR
  8361. // TODO: Reconsider this.
  8362. const xr = renderer.xr;
  8363. const session = xr.getSession && xr.getSession();
  8364. if ( session && session.environmentBlendMode === 'additive' ) {
  8365. background = null;
  8366. }
  8367. if ( background === null ) {
  8368. setClear( clearColor, clearAlpha );
  8369. } else if ( background && background.isColor ) {
  8370. setClear( background, 1 );
  8371. forceClear = true;
  8372. }
  8373. if ( renderer.autoClear || forceClear ) {
  8374. renderer.clear( renderer.autoClearColor, renderer.autoClearDepth, renderer.autoClearStencil );
  8375. }
  8376. if ( background && ( background.isCubeTexture || background.mapping === CubeUVReflectionMapping ) ) {
  8377. if ( boxMesh === undefined ) {
  8378. boxMesh = new Mesh(
  8379. new BoxGeometry( 1, 1, 1 ),
  8380. new ShaderMaterial( {
  8381. name: 'BackgroundCubeMaterial',
  8382. uniforms: cloneUniforms( ShaderLib.backgroundCube.uniforms ),
  8383. vertexShader: ShaderLib.backgroundCube.vertexShader,
  8384. fragmentShader: ShaderLib.backgroundCube.fragmentShader,
  8385. side: BackSide,
  8386. depthTest: false,
  8387. depthWrite: false,
  8388. fog: false
  8389. } )
  8390. );
  8391. boxMesh.geometry.deleteAttribute( 'normal' );
  8392. boxMesh.geometry.deleteAttribute( 'uv' );
  8393. boxMesh.onBeforeRender = function ( renderer, scene, camera ) {
  8394. this.matrixWorld.copyPosition( camera.matrixWorld );
  8395. };
  8396. // add "envMap" material property so the renderer can evaluate it like for built-in materials
  8397. Object.defineProperty( boxMesh.material, 'envMap', {
  8398. get: function () {
  8399. return this.uniforms.envMap.value;
  8400. }
  8401. } );
  8402. objects.update( boxMesh );
  8403. }
  8404. boxMesh.material.uniforms.envMap.value = background;
  8405. boxMesh.material.uniforms.flipEnvMap.value = ( background.isCubeTexture && background.isRenderTargetTexture === false ) ? - 1 : 1;
  8406. boxMesh.material.uniforms.backgroundBlurriness.value = scene.backgroundBlurriness;
  8407. boxMesh.material.uniforms.backgroundIntensity.value = scene.backgroundIntensity;
  8408. boxMesh.material.toneMapped = ( background.encoding === sRGBEncoding ) ? false : true;
  8409. if ( currentBackground !== background ||
  8410. currentBackgroundVersion !== background.version ||
  8411. currentTonemapping !== renderer.toneMapping ) {
  8412. boxMesh.material.needsUpdate = true;
  8413. currentBackground = background;
  8414. currentBackgroundVersion = background.version;
  8415. currentTonemapping = renderer.toneMapping;
  8416. }
  8417. boxMesh.layers.enableAll();
  8418. // push to the pre-sorted opaque render list
  8419. renderList.unshift( boxMesh, boxMesh.geometry, boxMesh.material, 0, 0, null );
  8420. } else if ( background && background.isTexture ) {
  8421. if ( planeMesh === undefined ) {
  8422. planeMesh = new Mesh(
  8423. new PlaneGeometry( 2, 2 ),
  8424. new ShaderMaterial( {
  8425. name: 'BackgroundMaterial',
  8426. uniforms: cloneUniforms( ShaderLib.background.uniforms ),
  8427. vertexShader: ShaderLib.background.vertexShader,
  8428. fragmentShader: ShaderLib.background.fragmentShader,
  8429. side: FrontSide,
  8430. depthTest: false,
  8431. depthWrite: false,
  8432. fog: false
  8433. } )
  8434. );
  8435. planeMesh.geometry.deleteAttribute( 'normal' );
  8436. // add "map" material property so the renderer can evaluate it like for built-in materials
  8437. Object.defineProperty( planeMesh.material, 'map', {
  8438. get: function () {
  8439. return this.uniforms.t2D.value;
  8440. }
  8441. } );
  8442. objects.update( planeMesh );
  8443. }
  8444. planeMesh.material.uniforms.t2D.value = background;
  8445. planeMesh.material.uniforms.backgroundIntensity.value = scene.backgroundIntensity;
  8446. planeMesh.material.toneMapped = ( background.encoding === sRGBEncoding ) ? false : true;
  8447. if ( background.matrixAutoUpdate === true ) {
  8448. background.updateMatrix();
  8449. }
  8450. planeMesh.material.uniforms.uvTransform.value.copy( background.matrix );
  8451. if ( currentBackground !== background ||
  8452. currentBackgroundVersion !== background.version ||
  8453. currentTonemapping !== renderer.toneMapping ) {
  8454. planeMesh.material.needsUpdate = true;
  8455. currentBackground = background;
  8456. currentBackgroundVersion = background.version;
  8457. currentTonemapping = renderer.toneMapping;
  8458. }
  8459. planeMesh.layers.enableAll();
  8460. // push to the pre-sorted opaque render list
  8461. renderList.unshift( planeMesh, planeMesh.geometry, planeMesh.material, 0, 0, null );
  8462. }
  8463. }
  8464. function setClear( color, alpha ) {
  8465. color.getRGB( _rgb, getUnlitUniformColorSpace( renderer ) );
  8466. state.buffers.color.setClear( _rgb.r, _rgb.g, _rgb.b, alpha, premultipliedAlpha );
  8467. }
  8468. return {
  8469. getClearColor: function () {
  8470. return clearColor;
  8471. },
  8472. setClearColor: function ( color, alpha = 1 ) {
  8473. clearColor.set( color );
  8474. clearAlpha = alpha;
  8475. setClear( clearColor, clearAlpha );
  8476. },
  8477. getClearAlpha: function () {
  8478. return clearAlpha;
  8479. },
  8480. setClearAlpha: function ( alpha ) {
  8481. clearAlpha = alpha;
  8482. setClear( clearColor, clearAlpha );
  8483. },
  8484. render: render
  8485. };
  8486. }
  8487. function WebGLBindingStates( gl, extensions, attributes, capabilities ) {
  8488. const maxVertexAttributes = gl.getParameter( gl.MAX_VERTEX_ATTRIBS );
  8489. const extension = capabilities.isWebGL2 ? null : extensions.get( 'OES_vertex_array_object' );
  8490. const vaoAvailable = capabilities.isWebGL2 || extension !== null;
  8491. const bindingStates = {};
  8492. const defaultState = createBindingState( null );
  8493. let currentState = defaultState;
  8494. let forceUpdate = false;
  8495. function setup( object, material, program, geometry, index ) {
  8496. let updateBuffers = false;
  8497. if ( vaoAvailable ) {
  8498. const state = getBindingState( geometry, program, material );
  8499. if ( currentState !== state ) {
  8500. currentState = state;
  8501. bindVertexArrayObject( currentState.object );
  8502. }
  8503. updateBuffers = needsUpdate( object, geometry, program, index );
  8504. if ( updateBuffers ) saveCache( object, geometry, program, index );
  8505. } else {
  8506. const wireframe = ( material.wireframe === true );
  8507. if ( currentState.geometry !== geometry.id ||
  8508. currentState.program !== program.id ||
  8509. currentState.wireframe !== wireframe ) {
  8510. currentState.geometry = geometry.id;
  8511. currentState.program = program.id;
  8512. currentState.wireframe = wireframe;
  8513. updateBuffers = true;
  8514. }
  8515. }
  8516. if ( index !== null ) {
  8517. attributes.update( index, gl.ELEMENT_ARRAY_BUFFER );
  8518. }
  8519. if ( updateBuffers || forceUpdate ) {
  8520. forceUpdate = false;
  8521. setupVertexAttributes( object, material, program, geometry );
  8522. if ( index !== null ) {
  8523. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, attributes.get( index ).buffer );
  8524. }
  8525. }
  8526. }
  8527. function createVertexArrayObject() {
  8528. if ( capabilities.isWebGL2 ) return gl.createVertexArray();
  8529. return extension.createVertexArrayOES();
  8530. }
  8531. function bindVertexArrayObject( vao ) {
  8532. if ( capabilities.isWebGL2 ) return gl.bindVertexArray( vao );
  8533. return extension.bindVertexArrayOES( vao );
  8534. }
  8535. function deleteVertexArrayObject( vao ) {
  8536. if ( capabilities.isWebGL2 ) return gl.deleteVertexArray( vao );
  8537. return extension.deleteVertexArrayOES( vao );
  8538. }
  8539. function getBindingState( geometry, program, material ) {
  8540. const wireframe = ( material.wireframe === true );
  8541. let programMap = bindingStates[ geometry.id ];
  8542. if ( programMap === undefined ) {
  8543. programMap = {};
  8544. bindingStates[ geometry.id ] = programMap;
  8545. }
  8546. let stateMap = programMap[ program.id ];
  8547. if ( stateMap === undefined ) {
  8548. stateMap = {};
  8549. programMap[ program.id ] = stateMap;
  8550. }
  8551. let state = stateMap[ wireframe ];
  8552. if ( state === undefined ) {
  8553. state = createBindingState( createVertexArrayObject() );
  8554. stateMap[ wireframe ] = state;
  8555. }
  8556. return state;
  8557. }
  8558. function createBindingState( vao ) {
  8559. const newAttributes = [];
  8560. const enabledAttributes = [];
  8561. const attributeDivisors = [];
  8562. for ( let i = 0; i < maxVertexAttributes; i ++ ) {
  8563. newAttributes[ i ] = 0;
  8564. enabledAttributes[ i ] = 0;
  8565. attributeDivisors[ i ] = 0;
  8566. }
  8567. return {
  8568. // for backward compatibility on non-VAO support browser
  8569. geometry: null,
  8570. program: null,
  8571. wireframe: false,
  8572. newAttributes: newAttributes,
  8573. enabledAttributes: enabledAttributes,
  8574. attributeDivisors: attributeDivisors,
  8575. object: vao,
  8576. attributes: {},
  8577. index: null
  8578. };
  8579. }
  8580. function needsUpdate( object, geometry, program, index ) {
  8581. const cachedAttributes = currentState.attributes;
  8582. const geometryAttributes = geometry.attributes;
  8583. let attributesNum = 0;
  8584. const programAttributes = program.getAttributes();
  8585. for ( const name in programAttributes ) {
  8586. const programAttribute = programAttributes[ name ];
  8587. if ( programAttribute.location >= 0 ) {
  8588. const cachedAttribute = cachedAttributes[ name ];
  8589. let geometryAttribute = geometryAttributes[ name ];
  8590. if ( geometryAttribute === undefined ) {
  8591. if ( name === 'instanceMatrix' && object.instanceMatrix ) geometryAttribute = object.instanceMatrix;
  8592. if ( name === 'instanceColor' && object.instanceColor ) geometryAttribute = object.instanceColor;
  8593. }
  8594. if ( cachedAttribute === undefined ) return true;
  8595. if ( cachedAttribute.attribute !== geometryAttribute ) return true;
  8596. if ( geometryAttribute && cachedAttribute.data !== geometryAttribute.data ) return true;
  8597. attributesNum ++;
  8598. }
  8599. }
  8600. if ( currentState.attributesNum !== attributesNum ) return true;
  8601. if ( currentState.index !== index ) return true;
  8602. return false;
  8603. }
  8604. function saveCache( object, geometry, program, index ) {
  8605. const cache = {};
  8606. const attributes = geometry.attributes;
  8607. let attributesNum = 0;
  8608. const programAttributes = program.getAttributes();
  8609. for ( const name in programAttributes ) {
  8610. const programAttribute = programAttributes[ name ];
  8611. if ( programAttribute.location >= 0 ) {
  8612. let attribute = attributes[ name ];
  8613. if ( attribute === undefined ) {
  8614. if ( name === 'instanceMatrix' && object.instanceMatrix ) attribute = object.instanceMatrix;
  8615. if ( name === 'instanceColor' && object.instanceColor ) attribute = object.instanceColor;
  8616. }
  8617. const data = {};
  8618. data.attribute = attribute;
  8619. if ( attribute && attribute.data ) {
  8620. data.data = attribute.data;
  8621. }
  8622. cache[ name ] = data;
  8623. attributesNum ++;
  8624. }
  8625. }
  8626. currentState.attributes = cache;
  8627. currentState.attributesNum = attributesNum;
  8628. currentState.index = index;
  8629. }
  8630. function initAttributes() {
  8631. const newAttributes = currentState.newAttributes;
  8632. for ( let i = 0, il = newAttributes.length; i < il; i ++ ) {
  8633. newAttributes[ i ] = 0;
  8634. }
  8635. }
  8636. function enableAttribute( attribute ) {
  8637. enableAttributeAndDivisor( attribute, 0 );
  8638. }
  8639. function enableAttributeAndDivisor( attribute, meshPerAttribute ) {
  8640. const newAttributes = currentState.newAttributes;
  8641. const enabledAttributes = currentState.enabledAttributes;
  8642. const attributeDivisors = currentState.attributeDivisors;
  8643. newAttributes[ attribute ] = 1;
  8644. if ( enabledAttributes[ attribute ] === 0 ) {
  8645. gl.enableVertexAttribArray( attribute );
  8646. enabledAttributes[ attribute ] = 1;
  8647. }
  8648. if ( attributeDivisors[ attribute ] !== meshPerAttribute ) {
  8649. const extension = capabilities.isWebGL2 ? gl : extensions.get( 'ANGLE_instanced_arrays' );
  8650. extension[ capabilities.isWebGL2 ? 'vertexAttribDivisor' : 'vertexAttribDivisorANGLE' ]( attribute, meshPerAttribute );
  8651. attributeDivisors[ attribute ] = meshPerAttribute;
  8652. }
  8653. }
  8654. function disableUnusedAttributes() {
  8655. const newAttributes = currentState.newAttributes;
  8656. const enabledAttributes = currentState.enabledAttributes;
  8657. for ( let i = 0, il = enabledAttributes.length; i < il; i ++ ) {
  8658. if ( enabledAttributes[ i ] !== newAttributes[ i ] ) {
  8659. gl.disableVertexAttribArray( i );
  8660. enabledAttributes[ i ] = 0;
  8661. }
  8662. }
  8663. }
  8664. function vertexAttribPointer( index, size, type, normalized, stride, offset ) {
  8665. if ( capabilities.isWebGL2 === true && ( type === gl.INT || type === gl.UNSIGNED_INT ) ) {
  8666. gl.vertexAttribIPointer( index, size, type, stride, offset );
  8667. } else {
  8668. gl.vertexAttribPointer( index, size, type, normalized, stride, offset );
  8669. }
  8670. }
  8671. function setupVertexAttributes( object, material, program, geometry ) {
  8672. if ( capabilities.isWebGL2 === false && ( object.isInstancedMesh || geometry.isInstancedBufferGeometry ) ) {
  8673. if ( extensions.get( 'ANGLE_instanced_arrays' ) === null ) return;
  8674. }
  8675. initAttributes();
  8676. const geometryAttributes = geometry.attributes;
  8677. const programAttributes = program.getAttributes();
  8678. const materialDefaultAttributeValues = material.defaultAttributeValues;
  8679. for ( const name in programAttributes ) {
  8680. const programAttribute = programAttributes[ name ];
  8681. if ( programAttribute.location >= 0 ) {
  8682. let geometryAttribute = geometryAttributes[ name ];
  8683. if ( geometryAttribute === undefined ) {
  8684. if ( name === 'instanceMatrix' && object.instanceMatrix ) geometryAttribute = object.instanceMatrix;
  8685. if ( name === 'instanceColor' && object.instanceColor ) geometryAttribute = object.instanceColor;
  8686. }
  8687. if ( geometryAttribute !== undefined ) {
  8688. const normalized = geometryAttribute.normalized;
  8689. const size = geometryAttribute.itemSize;
  8690. const attribute = attributes.get( geometryAttribute );
  8691. // TODO Attribute may not be available on context restore
  8692. if ( attribute === undefined ) continue;
  8693. const buffer = attribute.buffer;
  8694. const type = attribute.type;
  8695. const bytesPerElement = attribute.bytesPerElement;
  8696. if ( geometryAttribute.isInterleavedBufferAttribute ) {
  8697. const data = geometryAttribute.data;
  8698. const stride = data.stride;
  8699. const offset = geometryAttribute.offset;
  8700. if ( data.isInstancedInterleavedBuffer ) {
  8701. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  8702. enableAttributeAndDivisor( programAttribute.location + i, data.meshPerAttribute );
  8703. }
  8704. if ( object.isInstancedMesh !== true && geometry._maxInstanceCount === undefined ) {
  8705. geometry._maxInstanceCount = data.meshPerAttribute * data.count;
  8706. }
  8707. } else {
  8708. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  8709. enableAttribute( programAttribute.location + i );
  8710. }
  8711. }
  8712. gl.bindBuffer( gl.ARRAY_BUFFER, buffer );
  8713. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  8714. vertexAttribPointer(
  8715. programAttribute.location + i,
  8716. size / programAttribute.locationSize,
  8717. type,
  8718. normalized,
  8719. stride * bytesPerElement,
  8720. ( offset + ( size / programAttribute.locationSize ) * i ) * bytesPerElement
  8721. );
  8722. }
  8723. } else {
  8724. if ( geometryAttribute.isInstancedBufferAttribute ) {
  8725. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  8726. enableAttributeAndDivisor( programAttribute.location + i, geometryAttribute.meshPerAttribute );
  8727. }
  8728. if ( object.isInstancedMesh !== true && geometry._maxInstanceCount === undefined ) {
  8729. geometry._maxInstanceCount = geometryAttribute.meshPerAttribute * geometryAttribute.count;
  8730. }
  8731. } else {
  8732. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  8733. enableAttribute( programAttribute.location + i );
  8734. }
  8735. }
  8736. gl.bindBuffer( gl.ARRAY_BUFFER, buffer );
  8737. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  8738. vertexAttribPointer(
  8739. programAttribute.location + i,
  8740. size / programAttribute.locationSize,
  8741. type,
  8742. normalized,
  8743. size * bytesPerElement,
  8744. ( size / programAttribute.locationSize ) * i * bytesPerElement
  8745. );
  8746. }
  8747. }
  8748. } else if ( materialDefaultAttributeValues !== undefined ) {
  8749. const value = materialDefaultAttributeValues[ name ];
  8750. if ( value !== undefined ) {
  8751. switch ( value.length ) {
  8752. case 2:
  8753. gl.vertexAttrib2fv( programAttribute.location, value );
  8754. break;
  8755. case 3:
  8756. gl.vertexAttrib3fv( programAttribute.location, value );
  8757. break;
  8758. case 4:
  8759. gl.vertexAttrib4fv( programAttribute.location, value );
  8760. break;
  8761. default:
  8762. gl.vertexAttrib1fv( programAttribute.location, value );
  8763. }
  8764. }
  8765. }
  8766. }
  8767. }
  8768. disableUnusedAttributes();
  8769. }
  8770. function dispose() {
  8771. reset();
  8772. for ( const geometryId in bindingStates ) {
  8773. const programMap = bindingStates[ geometryId ];
  8774. for ( const programId in programMap ) {
  8775. const stateMap = programMap[ programId ];
  8776. for ( const wireframe in stateMap ) {
  8777. deleteVertexArrayObject( stateMap[ wireframe ].object );
  8778. delete stateMap[ wireframe ];
  8779. }
  8780. delete programMap[ programId ];
  8781. }
  8782. delete bindingStates[ geometryId ];
  8783. }
  8784. }
  8785. function releaseStatesOfGeometry( geometry ) {
  8786. if ( bindingStates[ geometry.id ] === undefined ) return;
  8787. const programMap = bindingStates[ geometry.id ];
  8788. for ( const programId in programMap ) {
  8789. const stateMap = programMap[ programId ];
  8790. for ( const wireframe in stateMap ) {
  8791. deleteVertexArrayObject( stateMap[ wireframe ].object );
  8792. delete stateMap[ wireframe ];
  8793. }
  8794. delete programMap[ programId ];
  8795. }
  8796. delete bindingStates[ geometry.id ];
  8797. }
  8798. function releaseStatesOfProgram( program ) {
  8799. for ( const geometryId in bindingStates ) {
  8800. const programMap = bindingStates[ geometryId ];
  8801. if ( programMap[ program.id ] === undefined ) continue;
  8802. const stateMap = programMap[ program.id ];
  8803. for ( const wireframe in stateMap ) {
  8804. deleteVertexArrayObject( stateMap[ wireframe ].object );
  8805. delete stateMap[ wireframe ];
  8806. }
  8807. delete programMap[ program.id ];
  8808. }
  8809. }
  8810. function reset() {
  8811. resetDefaultState();
  8812. forceUpdate = true;
  8813. if ( currentState === defaultState ) return;
  8814. currentState = defaultState;
  8815. bindVertexArrayObject( currentState.object );
  8816. }
  8817. // for backward-compatibility
  8818. function resetDefaultState() {
  8819. defaultState.geometry = null;
  8820. defaultState.program = null;
  8821. defaultState.wireframe = false;
  8822. }
  8823. return {
  8824. setup: setup,
  8825. reset: reset,
  8826. resetDefaultState: resetDefaultState,
  8827. dispose: dispose,
  8828. releaseStatesOfGeometry: releaseStatesOfGeometry,
  8829. releaseStatesOfProgram: releaseStatesOfProgram,
  8830. initAttributes: initAttributes,
  8831. enableAttribute: enableAttribute,
  8832. disableUnusedAttributes: disableUnusedAttributes
  8833. };
  8834. }
  8835. function WebGLBufferRenderer( gl, extensions, info, capabilities ) {
  8836. const isWebGL2 = capabilities.isWebGL2;
  8837. let mode;
  8838. function setMode( value ) {
  8839. mode = value;
  8840. }
  8841. function render( start, count ) {
  8842. gl.drawArrays( mode, start, count );
  8843. info.update( count, mode, 1 );
  8844. }
  8845. function renderInstances( start, count, primcount ) {
  8846. if ( primcount === 0 ) return;
  8847. let extension, methodName;
  8848. if ( isWebGL2 ) {
  8849. extension = gl;
  8850. methodName = 'drawArraysInstanced';
  8851. } else {
  8852. extension = extensions.get( 'ANGLE_instanced_arrays' );
  8853. methodName = 'drawArraysInstancedANGLE';
  8854. if ( extension === null ) {
  8855. console.error( 'THREE.WebGLBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.' );
  8856. return;
  8857. }
  8858. }
  8859. extension[ methodName ]( mode, start, count, primcount );
  8860. info.update( count, mode, primcount );
  8861. }
  8862. //
  8863. this.setMode = setMode;
  8864. this.render = render;
  8865. this.renderInstances = renderInstances;
  8866. }
  8867. function WebGLCapabilities( gl, extensions, parameters ) {
  8868. let maxAnisotropy;
  8869. function getMaxAnisotropy() {
  8870. if ( maxAnisotropy !== undefined ) return maxAnisotropy;
  8871. if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) {
  8872. const extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  8873. maxAnisotropy = gl.getParameter( extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT );
  8874. } else {
  8875. maxAnisotropy = 0;
  8876. }
  8877. return maxAnisotropy;
  8878. }
  8879. function getMaxPrecision( precision ) {
  8880. if ( precision === 'highp' ) {
  8881. if ( gl.getShaderPrecisionFormat( gl.VERTEX_SHADER, gl.HIGH_FLOAT ).precision > 0 &&
  8882. gl.getShaderPrecisionFormat( gl.FRAGMENT_SHADER, gl.HIGH_FLOAT ).precision > 0 ) {
  8883. return 'highp';
  8884. }
  8885. precision = 'mediump';
  8886. }
  8887. if ( precision === 'mediump' ) {
  8888. if ( gl.getShaderPrecisionFormat( gl.VERTEX_SHADER, gl.MEDIUM_FLOAT ).precision > 0 &&
  8889. gl.getShaderPrecisionFormat( gl.FRAGMENT_SHADER, gl.MEDIUM_FLOAT ).precision > 0 ) {
  8890. return 'mediump';
  8891. }
  8892. }
  8893. return 'lowp';
  8894. }
  8895. const isWebGL2 = typeof WebGL2RenderingContext !== 'undefined' && gl instanceof WebGL2RenderingContext;
  8896. let precision = parameters.precision !== undefined ? parameters.precision : 'highp';
  8897. const maxPrecision = getMaxPrecision( precision );
  8898. if ( maxPrecision !== precision ) {
  8899. console.warn( 'THREE.WebGLRenderer:', precision, 'not supported, using', maxPrecision, 'instead.' );
  8900. precision = maxPrecision;
  8901. }
  8902. const drawBuffers = isWebGL2 || extensions.has( 'WEBGL_draw_buffers' );
  8903. const logarithmicDepthBuffer = parameters.logarithmicDepthBuffer === true;
  8904. const maxTextures = gl.getParameter( gl.MAX_TEXTURE_IMAGE_UNITS );
  8905. const maxVertexTextures = gl.getParameter( gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS );
  8906. const maxTextureSize = gl.getParameter( gl.MAX_TEXTURE_SIZE );
  8907. const maxCubemapSize = gl.getParameter( gl.MAX_CUBE_MAP_TEXTURE_SIZE );
  8908. const maxAttributes = gl.getParameter( gl.MAX_VERTEX_ATTRIBS );
  8909. const maxVertexUniforms = gl.getParameter( gl.MAX_VERTEX_UNIFORM_VECTORS );
  8910. const maxVaryings = gl.getParameter( gl.MAX_VARYING_VECTORS );
  8911. const maxFragmentUniforms = gl.getParameter( gl.MAX_FRAGMENT_UNIFORM_VECTORS );
  8912. const vertexTextures = maxVertexTextures > 0;
  8913. const floatFragmentTextures = isWebGL2 || extensions.has( 'OES_texture_float' );
  8914. const floatVertexTextures = vertexTextures && floatFragmentTextures;
  8915. const maxSamples = isWebGL2 ? gl.getParameter( gl.MAX_SAMPLES ) : 0;
  8916. return {
  8917. isWebGL2: isWebGL2,
  8918. drawBuffers: drawBuffers,
  8919. getMaxAnisotropy: getMaxAnisotropy,
  8920. getMaxPrecision: getMaxPrecision,
  8921. precision: precision,
  8922. logarithmicDepthBuffer: logarithmicDepthBuffer,
  8923. maxTextures: maxTextures,
  8924. maxVertexTextures: maxVertexTextures,
  8925. maxTextureSize: maxTextureSize,
  8926. maxCubemapSize: maxCubemapSize,
  8927. maxAttributes: maxAttributes,
  8928. maxVertexUniforms: maxVertexUniforms,
  8929. maxVaryings: maxVaryings,
  8930. maxFragmentUniforms: maxFragmentUniforms,
  8931. vertexTextures: vertexTextures,
  8932. floatFragmentTextures: floatFragmentTextures,
  8933. floatVertexTextures: floatVertexTextures,
  8934. maxSamples: maxSamples
  8935. };
  8936. }
  8937. function WebGLClipping( properties ) {
  8938. const scope = this;
  8939. let globalState = null,
  8940. numGlobalPlanes = 0,
  8941. localClippingEnabled = false,
  8942. renderingShadows = false;
  8943. const plane = new Plane(),
  8944. viewNormalMatrix = new Matrix3(),
  8945. uniform = { value: null, needsUpdate: false };
  8946. this.uniform = uniform;
  8947. this.numPlanes = 0;
  8948. this.numIntersection = 0;
  8949. this.init = function ( planes, enableLocalClipping ) {
  8950. const enabled =
  8951. planes.length !== 0 ||
  8952. enableLocalClipping ||
  8953. // enable state of previous frame - the clipping code has to
  8954. // run another frame in order to reset the state:
  8955. numGlobalPlanes !== 0 ||
  8956. localClippingEnabled;
  8957. localClippingEnabled = enableLocalClipping;
  8958. numGlobalPlanes = planes.length;
  8959. return enabled;
  8960. };
  8961. this.beginShadows = function () {
  8962. renderingShadows = true;
  8963. projectPlanes( null );
  8964. };
  8965. this.endShadows = function () {
  8966. renderingShadows = false;
  8967. };
  8968. this.setGlobalState = function ( planes, camera ) {
  8969. globalState = projectPlanes( planes, camera, 0 );
  8970. };
  8971. this.setState = function ( material, camera, useCache ) {
  8972. const planes = material.clippingPlanes,
  8973. clipIntersection = material.clipIntersection,
  8974. clipShadows = material.clipShadows;
  8975. const materialProperties = properties.get( material );
  8976. if ( ! localClippingEnabled || planes === null || planes.length === 0 || renderingShadows && ! clipShadows ) {
  8977. // there's no local clipping
  8978. if ( renderingShadows ) {
  8979. // there's no global clipping
  8980. projectPlanes( null );
  8981. } else {
  8982. resetGlobalState();
  8983. }
  8984. } else {
  8985. const nGlobal = renderingShadows ? 0 : numGlobalPlanes,
  8986. lGlobal = nGlobal * 4;
  8987. let dstArray = materialProperties.clippingState || null;
  8988. uniform.value = dstArray; // ensure unique state
  8989. dstArray = projectPlanes( planes, camera, lGlobal, useCache );
  8990. for ( let i = 0; i !== lGlobal; ++ i ) {
  8991. dstArray[ i ] = globalState[ i ];
  8992. }
  8993. materialProperties.clippingState = dstArray;
  8994. this.numIntersection = clipIntersection ? this.numPlanes : 0;
  8995. this.numPlanes += nGlobal;
  8996. }
  8997. };
  8998. function resetGlobalState() {
  8999. if ( uniform.value !== globalState ) {
  9000. uniform.value = globalState;
  9001. uniform.needsUpdate = numGlobalPlanes > 0;
  9002. }
  9003. scope.numPlanes = numGlobalPlanes;
  9004. scope.numIntersection = 0;
  9005. }
  9006. function projectPlanes( planes, camera, dstOffset, skipTransform ) {
  9007. const nPlanes = planes !== null ? planes.length : 0;
  9008. let dstArray = null;
  9009. if ( nPlanes !== 0 ) {
  9010. dstArray = uniform.value;
  9011. if ( skipTransform !== true || dstArray === null ) {
  9012. const flatSize = dstOffset + nPlanes * 4,
  9013. viewMatrix = camera.matrixWorldInverse;
  9014. viewNormalMatrix.getNormalMatrix( viewMatrix );
  9015. if ( dstArray === null || dstArray.length < flatSize ) {
  9016. dstArray = new Float32Array( flatSize );
  9017. }
  9018. for ( let i = 0, i4 = dstOffset; i !== nPlanes; ++ i, i4 += 4 ) {
  9019. plane.copy( planes[ i ] ).applyMatrix4( viewMatrix, viewNormalMatrix );
  9020. plane.normal.toArray( dstArray, i4 );
  9021. dstArray[ i4 + 3 ] = plane.constant;
  9022. }
  9023. }
  9024. uniform.value = dstArray;
  9025. uniform.needsUpdate = true;
  9026. }
  9027. scope.numPlanes = nPlanes;
  9028. scope.numIntersection = 0;
  9029. return dstArray;
  9030. }
  9031. }
  9032. function WebGLCubeMaps( renderer ) {
  9033. let cubemaps = new WeakMap();
  9034. function mapTextureMapping( texture, mapping ) {
  9035. if ( mapping === EquirectangularReflectionMapping ) {
  9036. texture.mapping = CubeReflectionMapping;
  9037. } else if ( mapping === EquirectangularRefractionMapping ) {
  9038. texture.mapping = CubeRefractionMapping;
  9039. }
  9040. return texture;
  9041. }
  9042. function get( texture ) {
  9043. if ( texture && texture.isTexture && texture.isRenderTargetTexture === false ) {
  9044. const mapping = texture.mapping;
  9045. if ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping ) {
  9046. if ( cubemaps.has( texture ) ) {
  9047. const cubemap = cubemaps.get( texture ).texture;
  9048. return mapTextureMapping( cubemap, texture.mapping );
  9049. } else {
  9050. const image = texture.image;
  9051. if ( image && image.height > 0 ) {
  9052. const renderTarget = new WebGLCubeRenderTarget( image.height / 2 );
  9053. renderTarget.fromEquirectangularTexture( renderer, texture );
  9054. cubemaps.set( texture, renderTarget );
  9055. texture.addEventListener( 'dispose', onTextureDispose );
  9056. return mapTextureMapping( renderTarget.texture, texture.mapping );
  9057. } else {
  9058. // image not yet ready. try the conversion next frame
  9059. return null;
  9060. }
  9061. }
  9062. }
  9063. }
  9064. return texture;
  9065. }
  9066. function onTextureDispose( event ) {
  9067. const texture = event.target;
  9068. texture.removeEventListener( 'dispose', onTextureDispose );
  9069. const cubemap = cubemaps.get( texture );
  9070. if ( cubemap !== undefined ) {
  9071. cubemaps.delete( texture );
  9072. cubemap.dispose();
  9073. }
  9074. }
  9075. function dispose() {
  9076. cubemaps = new WeakMap();
  9077. }
  9078. return {
  9079. get: get,
  9080. dispose: dispose
  9081. };
  9082. }
  9083. class OrthographicCamera extends Camera {
  9084. constructor( left = - 1, right = 1, top = 1, bottom = - 1, near = 0.1, far = 2000 ) {
  9085. super();
  9086. this.isOrthographicCamera = true;
  9087. this.type = 'OrthographicCamera';
  9088. this.zoom = 1;
  9089. this.view = null;
  9090. this.left = left;
  9091. this.right = right;
  9092. this.top = top;
  9093. this.bottom = bottom;
  9094. this.near = near;
  9095. this.far = far;
  9096. this.updateProjectionMatrix();
  9097. }
  9098. copy( source, recursive ) {
  9099. super.copy( source, recursive );
  9100. this.left = source.left;
  9101. this.right = source.right;
  9102. this.top = source.top;
  9103. this.bottom = source.bottom;
  9104. this.near = source.near;
  9105. this.far = source.far;
  9106. this.zoom = source.zoom;
  9107. this.view = source.view === null ? null : Object.assign( {}, source.view );
  9108. return this;
  9109. }
  9110. setViewOffset( fullWidth, fullHeight, x, y, width, height ) {
  9111. if ( this.view === null ) {
  9112. this.view = {
  9113. enabled: true,
  9114. fullWidth: 1,
  9115. fullHeight: 1,
  9116. offsetX: 0,
  9117. offsetY: 0,
  9118. width: 1,
  9119. height: 1
  9120. };
  9121. }
  9122. this.view.enabled = true;
  9123. this.view.fullWidth = fullWidth;
  9124. this.view.fullHeight = fullHeight;
  9125. this.view.offsetX = x;
  9126. this.view.offsetY = y;
  9127. this.view.width = width;
  9128. this.view.height = height;
  9129. this.updateProjectionMatrix();
  9130. }
  9131. clearViewOffset() {
  9132. if ( this.view !== null ) {
  9133. this.view.enabled = false;
  9134. }
  9135. this.updateProjectionMatrix();
  9136. }
  9137. updateProjectionMatrix() {
  9138. const dx = ( this.right - this.left ) / ( 2 * this.zoom );
  9139. const dy = ( this.top - this.bottom ) / ( 2 * this.zoom );
  9140. const cx = ( this.right + this.left ) / 2;
  9141. const cy = ( this.top + this.bottom ) / 2;
  9142. let left = cx - dx;
  9143. let right = cx + dx;
  9144. let top = cy + dy;
  9145. let bottom = cy - dy;
  9146. if ( this.view !== null && this.view.enabled ) {
  9147. const scaleW = ( this.right - this.left ) / this.view.fullWidth / this.zoom;
  9148. const scaleH = ( this.top - this.bottom ) / this.view.fullHeight / this.zoom;
  9149. left += scaleW * this.view.offsetX;
  9150. right = left + scaleW * this.view.width;
  9151. top -= scaleH * this.view.offsetY;
  9152. bottom = top - scaleH * this.view.height;
  9153. }
  9154. this.projectionMatrix.makeOrthographic( left, right, top, bottom, this.near, this.far );
  9155. this.projectionMatrixInverse.copy( this.projectionMatrix ).invert();
  9156. }
  9157. toJSON( meta ) {
  9158. const data = super.toJSON( meta );
  9159. data.object.zoom = this.zoom;
  9160. data.object.left = this.left;
  9161. data.object.right = this.right;
  9162. data.object.top = this.top;
  9163. data.object.bottom = this.bottom;
  9164. data.object.near = this.near;
  9165. data.object.far = this.far;
  9166. if ( this.view !== null ) data.object.view = Object.assign( {}, this.view );
  9167. return data;
  9168. }
  9169. }
  9170. const LOD_MIN = 4;
  9171. // The standard deviations (radians) associated with the extra mips. These are
  9172. // chosen to approximate a Trowbridge-Reitz distribution function times the
  9173. // geometric shadowing function. These sigma values squared must match the
  9174. // variance #defines in cube_uv_reflection_fragment.glsl.js.
  9175. const EXTRA_LOD_SIGMA = [ 0.125, 0.215, 0.35, 0.446, 0.526, 0.582 ];
  9176. // The maximum length of the blur for loop. Smaller sigmas will use fewer
  9177. // samples and exit early, but not recompile the shader.
  9178. const MAX_SAMPLES = 20;
  9179. const _flatCamera = /*@__PURE__*/ new OrthographicCamera();
  9180. const _clearColor = /*@__PURE__*/ new Color();
  9181. let _oldTarget = null;
  9182. // Golden Ratio
  9183. const PHI = ( 1 + Math.sqrt( 5 ) ) / 2;
  9184. const INV_PHI = 1 / PHI;
  9185. // Vertices of a dodecahedron (except the opposites, which represent the
  9186. // same axis), used as axis directions evenly spread on a sphere.
  9187. const _axisDirections = [
  9188. /*@__PURE__*/ new Vector3( 1, 1, 1 ),
  9189. /*@__PURE__*/ new Vector3( - 1, 1, 1 ),
  9190. /*@__PURE__*/ new Vector3( 1, 1, - 1 ),
  9191. /*@__PURE__*/ new Vector3( - 1, 1, - 1 ),
  9192. /*@__PURE__*/ new Vector3( 0, PHI, INV_PHI ),
  9193. /*@__PURE__*/ new Vector3( 0, PHI, - INV_PHI ),
  9194. /*@__PURE__*/ new Vector3( INV_PHI, 0, PHI ),
  9195. /*@__PURE__*/ new Vector3( - INV_PHI, 0, PHI ),
  9196. /*@__PURE__*/ new Vector3( PHI, INV_PHI, 0 ),
  9197. /*@__PURE__*/ new Vector3( - PHI, INV_PHI, 0 ) ];
  9198. /**
  9199. * This class generates a Prefiltered, Mipmapped Radiance Environment Map
  9200. * (PMREM) from a cubeMap environment texture. This allows different levels of
  9201. * blur to be quickly accessed based on material roughness. It is packed into a
  9202. * special CubeUV format that allows us to perform custom interpolation so that
  9203. * we can support nonlinear formats such as RGBE. Unlike a traditional mipmap
  9204. * chain, it only goes down to the LOD_MIN level (above), and then creates extra
  9205. * even more filtered 'mips' at the same LOD_MIN resolution, associated with
  9206. * higher roughness levels. In this way we maintain resolution to smoothly
  9207. * interpolate diffuse lighting while limiting sampling computation.
  9208. *
  9209. * Paper: Fast, Accurate Image-Based Lighting
  9210. * https://drive.google.com/file/d/15y8r_UpKlU9SvV4ILb0C3qCPecS8pvLz/view
  9211. */
  9212. class PMREMGenerator {
  9213. constructor( renderer ) {
  9214. this._renderer = renderer;
  9215. this._pingPongRenderTarget = null;
  9216. this._lodMax = 0;
  9217. this._cubeSize = 0;
  9218. this._lodPlanes = [];
  9219. this._sizeLods = [];
  9220. this._sigmas = [];
  9221. this._blurMaterial = null;
  9222. this._cubemapMaterial = null;
  9223. this._equirectMaterial = null;
  9224. this._compileMaterial( this._blurMaterial );
  9225. }
  9226. /**
  9227. * Generates a PMREM from a supplied Scene, which can be faster than using an
  9228. * image if networking bandwidth is low. Optional sigma specifies a blur radius
  9229. * in radians to be applied to the scene before PMREM generation. Optional near
  9230. * and far planes ensure the scene is rendered in its entirety (the cubeCamera
  9231. * is placed at the origin).
  9232. */
  9233. fromScene( scene, sigma = 0, near = 0.1, far = 100 ) {
  9234. _oldTarget = this._renderer.getRenderTarget();
  9235. this._setSize( 256 );
  9236. const cubeUVRenderTarget = this._allocateTargets();
  9237. cubeUVRenderTarget.depthBuffer = true;
  9238. this._sceneToCubeUV( scene, near, far, cubeUVRenderTarget );
  9239. if ( sigma > 0 ) {
  9240. this._blur( cubeUVRenderTarget, 0, 0, sigma );
  9241. }
  9242. this._applyPMREM( cubeUVRenderTarget );
  9243. this._cleanup( cubeUVRenderTarget );
  9244. return cubeUVRenderTarget;
  9245. }
  9246. /**
  9247. * Generates a PMREM from an equirectangular texture, which can be either LDR
  9248. * or HDR. The ideal input image size is 1k (1024 x 512),
  9249. * as this matches best with the 256 x 256 cubemap output.
  9250. */
  9251. fromEquirectangular( equirectangular, renderTarget = null ) {
  9252. return this._fromTexture( equirectangular, renderTarget );
  9253. }
  9254. /**
  9255. * Generates a PMREM from an cubemap texture, which can be either LDR
  9256. * or HDR. The ideal input cube size is 256 x 256,
  9257. * as this matches best with the 256 x 256 cubemap output.
  9258. */
  9259. fromCubemap( cubemap, renderTarget = null ) {
  9260. return this._fromTexture( cubemap, renderTarget );
  9261. }
  9262. /**
  9263. * Pre-compiles the cubemap shader. You can get faster start-up by invoking this method during
  9264. * your texture's network fetch for increased concurrency.
  9265. */
  9266. compileCubemapShader() {
  9267. if ( this._cubemapMaterial === null ) {
  9268. this._cubemapMaterial = _getCubemapMaterial();
  9269. this._compileMaterial( this._cubemapMaterial );
  9270. }
  9271. }
  9272. /**
  9273. * Pre-compiles the equirectangular shader. You can get faster start-up by invoking this method during
  9274. * your texture's network fetch for increased concurrency.
  9275. */
  9276. compileEquirectangularShader() {
  9277. if ( this._equirectMaterial === null ) {
  9278. this._equirectMaterial = _getEquirectMaterial();
  9279. this._compileMaterial( this._equirectMaterial );
  9280. }
  9281. }
  9282. /**
  9283. * Disposes of the PMREMGenerator's internal memory. Note that PMREMGenerator is a static class,
  9284. * so you should not need more than one PMREMGenerator object. If you do, calling dispose() on
  9285. * one of them will cause any others to also become unusable.
  9286. */
  9287. dispose() {
  9288. this._dispose();
  9289. if ( this._cubemapMaterial !== null ) this._cubemapMaterial.dispose();
  9290. if ( this._equirectMaterial !== null ) this._equirectMaterial.dispose();
  9291. }
  9292. // private interface
  9293. _setSize( cubeSize ) {
  9294. this._lodMax = Math.floor( Math.log2( cubeSize ) );
  9295. this._cubeSize = Math.pow( 2, this._lodMax );
  9296. }
  9297. _dispose() {
  9298. if ( this._blurMaterial !== null ) this._blurMaterial.dispose();
  9299. if ( this._pingPongRenderTarget !== null ) this._pingPongRenderTarget.dispose();
  9300. for ( let i = 0; i < this._lodPlanes.length; i ++ ) {
  9301. this._lodPlanes[ i ].dispose();
  9302. }
  9303. }
  9304. _cleanup( outputTarget ) {
  9305. this._renderer.setRenderTarget( _oldTarget );
  9306. outputTarget.scissorTest = false;
  9307. _setViewport( outputTarget, 0, 0, outputTarget.width, outputTarget.height );
  9308. }
  9309. _fromTexture( texture, renderTarget ) {
  9310. if ( texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping ) {
  9311. this._setSize( texture.image.length === 0 ? 16 : ( texture.image[ 0 ].width || texture.image[ 0 ].image.width ) );
  9312. } else { // Equirectangular
  9313. this._setSize( texture.image.width / 4 );
  9314. }
  9315. _oldTarget = this._renderer.getRenderTarget();
  9316. const cubeUVRenderTarget = renderTarget || this._allocateTargets();
  9317. this._textureToCubeUV( texture, cubeUVRenderTarget );
  9318. this._applyPMREM( cubeUVRenderTarget );
  9319. this._cleanup( cubeUVRenderTarget );
  9320. return cubeUVRenderTarget;
  9321. }
  9322. _allocateTargets() {
  9323. const width = 3 * Math.max( this._cubeSize, 16 * 7 );
  9324. const height = 4 * this._cubeSize;
  9325. const params = {
  9326. magFilter: LinearFilter,
  9327. minFilter: LinearFilter,
  9328. generateMipmaps: false,
  9329. type: HalfFloatType,
  9330. format: RGBAFormat,
  9331. encoding: LinearEncoding,
  9332. depthBuffer: false
  9333. };
  9334. const cubeUVRenderTarget = _createRenderTarget( width, height, params );
  9335. if ( this._pingPongRenderTarget === null || this._pingPongRenderTarget.width !== width || this._pingPongRenderTarget.height !== height ) {
  9336. if ( this._pingPongRenderTarget !== null ) {
  9337. this._dispose();
  9338. }
  9339. this._pingPongRenderTarget = _createRenderTarget( width, height, params );
  9340. const { _lodMax } = this;
  9341. ( { sizeLods: this._sizeLods, lodPlanes: this._lodPlanes, sigmas: this._sigmas } = _createPlanes( _lodMax ) );
  9342. this._blurMaterial = _getBlurShader( _lodMax, width, height );
  9343. }
  9344. return cubeUVRenderTarget;
  9345. }
  9346. _compileMaterial( material ) {
  9347. const tmpMesh = new Mesh( this._lodPlanes[ 0 ], material );
  9348. this._renderer.compile( tmpMesh, _flatCamera );
  9349. }
  9350. _sceneToCubeUV( scene, near, far, cubeUVRenderTarget ) {
  9351. const fov = 90;
  9352. const aspect = 1;
  9353. const cubeCamera = new PerspectiveCamera( fov, aspect, near, far );
  9354. const upSign = [ 1, - 1, 1, 1, 1, 1 ];
  9355. const forwardSign = [ 1, 1, 1, - 1, - 1, - 1 ];
  9356. const renderer = this._renderer;
  9357. const originalAutoClear = renderer.autoClear;
  9358. const toneMapping = renderer.toneMapping;
  9359. renderer.getClearColor( _clearColor );
  9360. renderer.toneMapping = NoToneMapping;
  9361. renderer.autoClear = false;
  9362. const backgroundMaterial = new MeshBasicMaterial( {
  9363. name: 'PMREM.Background',
  9364. side: BackSide,
  9365. depthWrite: false,
  9366. depthTest: false,
  9367. } );
  9368. const backgroundBox = new Mesh( new BoxGeometry(), backgroundMaterial );
  9369. let useSolidColor = false;
  9370. const background = scene.background;
  9371. if ( background ) {
  9372. if ( background.isColor ) {
  9373. backgroundMaterial.color.copy( background );
  9374. scene.background = null;
  9375. useSolidColor = true;
  9376. }
  9377. } else {
  9378. backgroundMaterial.color.copy( _clearColor );
  9379. useSolidColor = true;
  9380. }
  9381. for ( let i = 0; i < 6; i ++ ) {
  9382. const col = i % 3;
  9383. if ( col === 0 ) {
  9384. cubeCamera.up.set( 0, upSign[ i ], 0 );
  9385. cubeCamera.lookAt( forwardSign[ i ], 0, 0 );
  9386. } else if ( col === 1 ) {
  9387. cubeCamera.up.set( 0, 0, upSign[ i ] );
  9388. cubeCamera.lookAt( 0, forwardSign[ i ], 0 );
  9389. } else {
  9390. cubeCamera.up.set( 0, upSign[ i ], 0 );
  9391. cubeCamera.lookAt( 0, 0, forwardSign[ i ] );
  9392. }
  9393. const size = this._cubeSize;
  9394. _setViewport( cubeUVRenderTarget, col * size, i > 2 ? size : 0, size, size );
  9395. renderer.setRenderTarget( cubeUVRenderTarget );
  9396. if ( useSolidColor ) {
  9397. renderer.render( backgroundBox, cubeCamera );
  9398. }
  9399. renderer.render( scene, cubeCamera );
  9400. }
  9401. backgroundBox.geometry.dispose();
  9402. backgroundBox.material.dispose();
  9403. renderer.toneMapping = toneMapping;
  9404. renderer.autoClear = originalAutoClear;
  9405. scene.background = background;
  9406. }
  9407. _textureToCubeUV( texture, cubeUVRenderTarget ) {
  9408. const renderer = this._renderer;
  9409. const isCubeTexture = ( texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping );
  9410. if ( isCubeTexture ) {
  9411. if ( this._cubemapMaterial === null ) {
  9412. this._cubemapMaterial = _getCubemapMaterial();
  9413. }
  9414. this._cubemapMaterial.uniforms.flipEnvMap.value = ( texture.isRenderTargetTexture === false ) ? - 1 : 1;
  9415. } else {
  9416. if ( this._equirectMaterial === null ) {
  9417. this._equirectMaterial = _getEquirectMaterial();
  9418. }
  9419. }
  9420. const material = isCubeTexture ? this._cubemapMaterial : this._equirectMaterial;
  9421. const mesh = new Mesh( this._lodPlanes[ 0 ], material );
  9422. const uniforms = material.uniforms;
  9423. uniforms[ 'envMap' ].value = texture;
  9424. const size = this._cubeSize;
  9425. _setViewport( cubeUVRenderTarget, 0, 0, 3 * size, 2 * size );
  9426. renderer.setRenderTarget( cubeUVRenderTarget );
  9427. renderer.render( mesh, _flatCamera );
  9428. }
  9429. _applyPMREM( cubeUVRenderTarget ) {
  9430. const renderer = this._renderer;
  9431. const autoClear = renderer.autoClear;
  9432. renderer.autoClear = false;
  9433. for ( let i = 1; i < this._lodPlanes.length; i ++ ) {
  9434. const sigma = Math.sqrt( this._sigmas[ i ] * this._sigmas[ i ] - this._sigmas[ i - 1 ] * this._sigmas[ i - 1 ] );
  9435. const poleAxis = _axisDirections[ ( i - 1 ) % _axisDirections.length ];
  9436. this._blur( cubeUVRenderTarget, i - 1, i, sigma, poleAxis );
  9437. }
  9438. renderer.autoClear = autoClear;
  9439. }
  9440. /**
  9441. * This is a two-pass Gaussian blur for a cubemap. Normally this is done
  9442. * vertically and horizontally, but this breaks down on a cube. Here we apply
  9443. * the blur latitudinally (around the poles), and then longitudinally (towards
  9444. * the poles) to approximate the orthogonally-separable blur. It is least
  9445. * accurate at the poles, but still does a decent job.
  9446. */
  9447. _blur( cubeUVRenderTarget, lodIn, lodOut, sigma, poleAxis ) {
  9448. const pingPongRenderTarget = this._pingPongRenderTarget;
  9449. this._halfBlur(
  9450. cubeUVRenderTarget,
  9451. pingPongRenderTarget,
  9452. lodIn,
  9453. lodOut,
  9454. sigma,
  9455. 'latitudinal',
  9456. poleAxis );
  9457. this._halfBlur(
  9458. pingPongRenderTarget,
  9459. cubeUVRenderTarget,
  9460. lodOut,
  9461. lodOut,
  9462. sigma,
  9463. 'longitudinal',
  9464. poleAxis );
  9465. }
  9466. _halfBlur( targetIn, targetOut, lodIn, lodOut, sigmaRadians, direction, poleAxis ) {
  9467. const renderer = this._renderer;
  9468. const blurMaterial = this._blurMaterial;
  9469. if ( direction !== 'latitudinal' && direction !== 'longitudinal' ) {
  9470. console.error(
  9471. 'blur direction must be either latitudinal or longitudinal!' );
  9472. }
  9473. // Number of standard deviations at which to cut off the discrete approximation.
  9474. const STANDARD_DEVIATIONS = 3;
  9475. const blurMesh = new Mesh( this._lodPlanes[ lodOut ], blurMaterial );
  9476. const blurUniforms = blurMaterial.uniforms;
  9477. const pixels = this._sizeLods[ lodIn ] - 1;
  9478. const radiansPerPixel = isFinite( sigmaRadians ) ? Math.PI / ( 2 * pixels ) : 2 * Math.PI / ( 2 * MAX_SAMPLES - 1 );
  9479. const sigmaPixels = sigmaRadians / radiansPerPixel;
  9480. const samples = isFinite( sigmaRadians ) ? 1 + Math.floor( STANDARD_DEVIATIONS * sigmaPixels ) : MAX_SAMPLES;
  9481. if ( samples > MAX_SAMPLES ) {
  9482. console.warn( `sigmaRadians, ${
  9483. sigmaRadians}, is too large and will clip, as it requested ${
  9484. samples} samples when the maximum is set to ${MAX_SAMPLES}` );
  9485. }
  9486. const weights = [];
  9487. let sum = 0;
  9488. for ( let i = 0; i < MAX_SAMPLES; ++ i ) {
  9489. const x = i / sigmaPixels;
  9490. const weight = Math.exp( - x * x / 2 );
  9491. weights.push( weight );
  9492. if ( i === 0 ) {
  9493. sum += weight;
  9494. } else if ( i < samples ) {
  9495. sum += 2 * weight;
  9496. }
  9497. }
  9498. for ( let i = 0; i < weights.length; i ++ ) {
  9499. weights[ i ] = weights[ i ] / sum;
  9500. }
  9501. blurUniforms[ 'envMap' ].value = targetIn.texture;
  9502. blurUniforms[ 'samples' ].value = samples;
  9503. blurUniforms[ 'weights' ].value = weights;
  9504. blurUniforms[ 'latitudinal' ].value = direction === 'latitudinal';
  9505. if ( poleAxis ) {
  9506. blurUniforms[ 'poleAxis' ].value = poleAxis;
  9507. }
  9508. const { _lodMax } = this;
  9509. blurUniforms[ 'dTheta' ].value = radiansPerPixel;
  9510. blurUniforms[ 'mipInt' ].value = _lodMax - lodIn;
  9511. const outputSize = this._sizeLods[ lodOut ];
  9512. const x = 3 * outputSize * ( lodOut > _lodMax - LOD_MIN ? lodOut - _lodMax + LOD_MIN : 0 );
  9513. const y = 4 * ( this._cubeSize - outputSize );
  9514. _setViewport( targetOut, x, y, 3 * outputSize, 2 * outputSize );
  9515. renderer.setRenderTarget( targetOut );
  9516. renderer.render( blurMesh, _flatCamera );
  9517. }
  9518. }
  9519. function _createPlanes( lodMax ) {
  9520. const lodPlanes = [];
  9521. const sizeLods = [];
  9522. const sigmas = [];
  9523. let lod = lodMax;
  9524. const totalLods = lodMax - LOD_MIN + 1 + EXTRA_LOD_SIGMA.length;
  9525. for ( let i = 0; i < totalLods; i ++ ) {
  9526. const sizeLod = Math.pow( 2, lod );
  9527. sizeLods.push( sizeLod );
  9528. let sigma = 1.0 / sizeLod;
  9529. if ( i > lodMax - LOD_MIN ) {
  9530. sigma = EXTRA_LOD_SIGMA[ i - lodMax + LOD_MIN - 1 ];
  9531. } else if ( i === 0 ) {
  9532. sigma = 0;
  9533. }
  9534. sigmas.push( sigma );
  9535. const texelSize = 1.0 / ( sizeLod - 2 );
  9536. const min = - texelSize;
  9537. const max = 1 + texelSize;
  9538. const uv1 = [ min, min, max, min, max, max, min, min, max, max, min, max ];
  9539. const cubeFaces = 6;
  9540. const vertices = 6;
  9541. const positionSize = 3;
  9542. const uvSize = 2;
  9543. const faceIndexSize = 1;
  9544. const position = new Float32Array( positionSize * vertices * cubeFaces );
  9545. const uv = new Float32Array( uvSize * vertices * cubeFaces );
  9546. const faceIndex = new Float32Array( faceIndexSize * vertices * cubeFaces );
  9547. for ( let face = 0; face < cubeFaces; face ++ ) {
  9548. const x = ( face % 3 ) * 2 / 3 - 1;
  9549. const y = face > 2 ? 0 : - 1;
  9550. const coordinates = [
  9551. x, y, 0,
  9552. x + 2 / 3, y, 0,
  9553. x + 2 / 3, y + 1, 0,
  9554. x, y, 0,
  9555. x + 2 / 3, y + 1, 0,
  9556. x, y + 1, 0
  9557. ];
  9558. position.set( coordinates, positionSize * vertices * face );
  9559. uv.set( uv1, uvSize * vertices * face );
  9560. const fill = [ face, face, face, face, face, face ];
  9561. faceIndex.set( fill, faceIndexSize * vertices * face );
  9562. }
  9563. const planes = new BufferGeometry();
  9564. planes.setAttribute( 'position', new BufferAttribute( position, positionSize ) );
  9565. planes.setAttribute( 'uv', new BufferAttribute( uv, uvSize ) );
  9566. planes.setAttribute( 'faceIndex', new BufferAttribute( faceIndex, faceIndexSize ) );
  9567. lodPlanes.push( planes );
  9568. if ( lod > LOD_MIN ) {
  9569. lod --;
  9570. }
  9571. }
  9572. return { lodPlanes, sizeLods, sigmas };
  9573. }
  9574. function _createRenderTarget( width, height, params ) {
  9575. const cubeUVRenderTarget = new WebGLRenderTarget( width, height, params );
  9576. cubeUVRenderTarget.texture.mapping = CubeUVReflectionMapping;
  9577. cubeUVRenderTarget.texture.name = 'PMREM.cubeUv';
  9578. cubeUVRenderTarget.scissorTest = true;
  9579. return cubeUVRenderTarget;
  9580. }
  9581. function _setViewport( target, x, y, width, height ) {
  9582. target.viewport.set( x, y, width, height );
  9583. target.scissor.set( x, y, width, height );
  9584. }
  9585. function _getBlurShader( lodMax, width, height ) {
  9586. const weights = new Float32Array( MAX_SAMPLES );
  9587. const poleAxis = new Vector3( 0, 1, 0 );
  9588. const shaderMaterial = new ShaderMaterial( {
  9589. name: 'SphericalGaussianBlur',
  9590. defines: {
  9591. 'n': MAX_SAMPLES,
  9592. 'CUBEUV_TEXEL_WIDTH': 1.0 / width,
  9593. 'CUBEUV_TEXEL_HEIGHT': 1.0 / height,
  9594. 'CUBEUV_MAX_MIP': `${lodMax}.0`,
  9595. },
  9596. uniforms: {
  9597. 'envMap': { value: null },
  9598. 'samples': { value: 1 },
  9599. 'weights': { value: weights },
  9600. 'latitudinal': { value: false },
  9601. 'dTheta': { value: 0 },
  9602. 'mipInt': { value: 0 },
  9603. 'poleAxis': { value: poleAxis }
  9604. },
  9605. vertexShader: _getCommonVertexShader(),
  9606. fragmentShader: /* glsl */`
  9607. precision mediump float;
  9608. precision mediump int;
  9609. varying vec3 vOutputDirection;
  9610. uniform sampler2D envMap;
  9611. uniform int samples;
  9612. uniform float weights[ n ];
  9613. uniform bool latitudinal;
  9614. uniform float dTheta;
  9615. uniform float mipInt;
  9616. uniform vec3 poleAxis;
  9617. #define ENVMAP_TYPE_CUBE_UV
  9618. #include <cube_uv_reflection_fragment>
  9619. vec3 getSample( float theta, vec3 axis ) {
  9620. float cosTheta = cos( theta );
  9621. // Rodrigues' axis-angle rotation
  9622. vec3 sampleDirection = vOutputDirection * cosTheta
  9623. + cross( axis, vOutputDirection ) * sin( theta )
  9624. + axis * dot( axis, vOutputDirection ) * ( 1.0 - cosTheta );
  9625. return bilinearCubeUV( envMap, sampleDirection, mipInt );
  9626. }
  9627. void main() {
  9628. vec3 axis = latitudinal ? poleAxis : cross( poleAxis, vOutputDirection );
  9629. if ( all( equal( axis, vec3( 0.0 ) ) ) ) {
  9630. axis = vec3( vOutputDirection.z, 0.0, - vOutputDirection.x );
  9631. }
  9632. axis = normalize( axis );
  9633. gl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 );
  9634. gl_FragColor.rgb += weights[ 0 ] * getSample( 0.0, axis );
  9635. for ( int i = 1; i < n; i++ ) {
  9636. if ( i >= samples ) {
  9637. break;
  9638. }
  9639. float theta = dTheta * float( i );
  9640. gl_FragColor.rgb += weights[ i ] * getSample( -1.0 * theta, axis );
  9641. gl_FragColor.rgb += weights[ i ] * getSample( theta, axis );
  9642. }
  9643. }
  9644. `,
  9645. blending: NoBlending,
  9646. depthTest: false,
  9647. depthWrite: false
  9648. } );
  9649. return shaderMaterial;
  9650. }
  9651. function _getEquirectMaterial() {
  9652. return new ShaderMaterial( {
  9653. name: 'EquirectangularToCubeUV',
  9654. uniforms: {
  9655. 'envMap': { value: null }
  9656. },
  9657. vertexShader: _getCommonVertexShader(),
  9658. fragmentShader: /* glsl */`
  9659. precision mediump float;
  9660. precision mediump int;
  9661. varying vec3 vOutputDirection;
  9662. uniform sampler2D envMap;
  9663. #include <common>
  9664. void main() {
  9665. vec3 outputDirection = normalize( vOutputDirection );
  9666. vec2 uv = equirectUv( outputDirection );
  9667. gl_FragColor = vec4( texture2D ( envMap, uv ).rgb, 1.0 );
  9668. }
  9669. `,
  9670. blending: NoBlending,
  9671. depthTest: false,
  9672. depthWrite: false
  9673. } );
  9674. }
  9675. function _getCubemapMaterial() {
  9676. return new ShaderMaterial( {
  9677. name: 'CubemapToCubeUV',
  9678. uniforms: {
  9679. 'envMap': { value: null },
  9680. 'flipEnvMap': { value: - 1 }
  9681. },
  9682. vertexShader: _getCommonVertexShader(),
  9683. fragmentShader: /* glsl */`
  9684. precision mediump float;
  9685. precision mediump int;
  9686. uniform float flipEnvMap;
  9687. varying vec3 vOutputDirection;
  9688. uniform samplerCube envMap;
  9689. void main() {
  9690. gl_FragColor = textureCube( envMap, vec3( flipEnvMap * vOutputDirection.x, vOutputDirection.yz ) );
  9691. }
  9692. `,
  9693. blending: NoBlending,
  9694. depthTest: false,
  9695. depthWrite: false
  9696. } );
  9697. }
  9698. function _getCommonVertexShader() {
  9699. return /* glsl */`
  9700. precision mediump float;
  9701. precision mediump int;
  9702. attribute float faceIndex;
  9703. varying vec3 vOutputDirection;
  9704. // RH coordinate system; PMREM face-indexing convention
  9705. vec3 getDirection( vec2 uv, float face ) {
  9706. uv = 2.0 * uv - 1.0;
  9707. vec3 direction = vec3( uv, 1.0 );
  9708. if ( face == 0.0 ) {
  9709. direction = direction.zyx; // ( 1, v, u ) pos x
  9710. } else if ( face == 1.0 ) {
  9711. direction = direction.xzy;
  9712. direction.xz *= -1.0; // ( -u, 1, -v ) pos y
  9713. } else if ( face == 2.0 ) {
  9714. direction.x *= -1.0; // ( -u, v, 1 ) pos z
  9715. } else if ( face == 3.0 ) {
  9716. direction = direction.zyx;
  9717. direction.xz *= -1.0; // ( -1, v, -u ) neg x
  9718. } else if ( face == 4.0 ) {
  9719. direction = direction.xzy;
  9720. direction.xy *= -1.0; // ( -u, -1, v ) neg y
  9721. } else if ( face == 5.0 ) {
  9722. direction.z *= -1.0; // ( u, v, -1 ) neg z
  9723. }
  9724. return direction;
  9725. }
  9726. void main() {
  9727. vOutputDirection = getDirection( uv, faceIndex );
  9728. gl_Position = vec4( position, 1.0 );
  9729. }
  9730. `;
  9731. }
  9732. function WebGLCubeUVMaps( renderer ) {
  9733. let cubeUVmaps = new WeakMap();
  9734. let pmremGenerator = null;
  9735. function get( texture ) {
  9736. if ( texture && texture.isTexture ) {
  9737. const mapping = texture.mapping;
  9738. const isEquirectMap = ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping );
  9739. const isCubeMap = ( mapping === CubeReflectionMapping || mapping === CubeRefractionMapping );
  9740. // equirect/cube map to cubeUV conversion
  9741. if ( isEquirectMap || isCubeMap ) {
  9742. if ( texture.isRenderTargetTexture && texture.needsPMREMUpdate === true ) {
  9743. texture.needsPMREMUpdate = false;
  9744. let renderTarget = cubeUVmaps.get( texture );
  9745. if ( pmremGenerator === null ) pmremGenerator = new PMREMGenerator( renderer );
  9746. renderTarget = isEquirectMap ? pmremGenerator.fromEquirectangular( texture, renderTarget ) : pmremGenerator.fromCubemap( texture, renderTarget );
  9747. cubeUVmaps.set( texture, renderTarget );
  9748. return renderTarget.texture;
  9749. } else {
  9750. if ( cubeUVmaps.has( texture ) ) {
  9751. return cubeUVmaps.get( texture ).texture;
  9752. } else {
  9753. const image = texture.image;
  9754. if ( ( isEquirectMap && image && image.height > 0 ) || ( isCubeMap && image && isCubeTextureComplete( image ) ) ) {
  9755. if ( pmremGenerator === null ) pmremGenerator = new PMREMGenerator( renderer );
  9756. const renderTarget = isEquirectMap ? pmremGenerator.fromEquirectangular( texture ) : pmremGenerator.fromCubemap( texture );
  9757. cubeUVmaps.set( texture, renderTarget );
  9758. texture.addEventListener( 'dispose', onTextureDispose );
  9759. return renderTarget.texture;
  9760. } else {
  9761. // image not yet ready. try the conversion next frame
  9762. return null;
  9763. }
  9764. }
  9765. }
  9766. }
  9767. }
  9768. return texture;
  9769. }
  9770. function isCubeTextureComplete( image ) {
  9771. let count = 0;
  9772. const length = 6;
  9773. for ( let i = 0; i < length; i ++ ) {
  9774. if ( image[ i ] !== undefined ) count ++;
  9775. }
  9776. return count === length;
  9777. }
  9778. function onTextureDispose( event ) {
  9779. const texture = event.target;
  9780. texture.removeEventListener( 'dispose', onTextureDispose );
  9781. const cubemapUV = cubeUVmaps.get( texture );
  9782. if ( cubemapUV !== undefined ) {
  9783. cubeUVmaps.delete( texture );
  9784. cubemapUV.dispose();
  9785. }
  9786. }
  9787. function dispose() {
  9788. cubeUVmaps = new WeakMap();
  9789. if ( pmremGenerator !== null ) {
  9790. pmremGenerator.dispose();
  9791. pmremGenerator = null;
  9792. }
  9793. }
  9794. return {
  9795. get: get,
  9796. dispose: dispose
  9797. };
  9798. }
  9799. function WebGLExtensions( gl ) {
  9800. const extensions = {};
  9801. function getExtension( name ) {
  9802. if ( extensions[ name ] !== undefined ) {
  9803. return extensions[ name ];
  9804. }
  9805. let extension;
  9806. switch ( name ) {
  9807. case 'WEBGL_depth_texture':
  9808. extension = gl.getExtension( 'WEBGL_depth_texture' ) || gl.getExtension( 'MOZ_WEBGL_depth_texture' ) || gl.getExtension( 'WEBKIT_WEBGL_depth_texture' );
  9809. break;
  9810. case 'EXT_texture_filter_anisotropic':
  9811. extension = gl.getExtension( 'EXT_texture_filter_anisotropic' ) || gl.getExtension( 'MOZ_EXT_texture_filter_anisotropic' ) || gl.getExtension( 'WEBKIT_EXT_texture_filter_anisotropic' );
  9812. break;
  9813. case 'WEBGL_compressed_texture_s3tc':
  9814. extension = gl.getExtension( 'WEBGL_compressed_texture_s3tc' ) || gl.getExtension( 'MOZ_WEBGL_compressed_texture_s3tc' ) || gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_s3tc' );
  9815. break;
  9816. case 'WEBGL_compressed_texture_pvrtc':
  9817. extension = gl.getExtension( 'WEBGL_compressed_texture_pvrtc' ) || gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_pvrtc' );
  9818. break;
  9819. default:
  9820. extension = gl.getExtension( name );
  9821. }
  9822. extensions[ name ] = extension;
  9823. return extension;
  9824. }
  9825. return {
  9826. has: function ( name ) {
  9827. return getExtension( name ) !== null;
  9828. },
  9829. init: function ( capabilities ) {
  9830. if ( capabilities.isWebGL2 ) {
  9831. getExtension( 'EXT_color_buffer_float' );
  9832. } else {
  9833. getExtension( 'WEBGL_depth_texture' );
  9834. getExtension( 'OES_texture_float' );
  9835. getExtension( 'OES_texture_half_float' );
  9836. getExtension( 'OES_texture_half_float_linear' );
  9837. getExtension( 'OES_standard_derivatives' );
  9838. getExtension( 'OES_element_index_uint' );
  9839. getExtension( 'OES_vertex_array_object' );
  9840. getExtension( 'ANGLE_instanced_arrays' );
  9841. }
  9842. getExtension( 'OES_texture_float_linear' );
  9843. getExtension( 'EXT_color_buffer_half_float' );
  9844. getExtension( 'WEBGL_multisampled_render_to_texture' );
  9845. },
  9846. get: function ( name ) {
  9847. const extension = getExtension( name );
  9848. if ( extension === null ) {
  9849. console.warn( 'THREE.WebGLRenderer: ' + name + ' extension not supported.' );
  9850. }
  9851. return extension;
  9852. }
  9853. };
  9854. }
  9855. function WebGLGeometries( gl, attributes, info, bindingStates ) {
  9856. const geometries = {};
  9857. const wireframeAttributes = new WeakMap();
  9858. function onGeometryDispose( event ) {
  9859. const geometry = event.target;
  9860. if ( geometry.index !== null ) {
  9861. attributes.remove( geometry.index );
  9862. }
  9863. for ( const name in geometry.attributes ) {
  9864. attributes.remove( geometry.attributes[ name ] );
  9865. }
  9866. geometry.removeEventListener( 'dispose', onGeometryDispose );
  9867. delete geometries[ geometry.id ];
  9868. const attribute = wireframeAttributes.get( geometry );
  9869. if ( attribute ) {
  9870. attributes.remove( attribute );
  9871. wireframeAttributes.delete( geometry );
  9872. }
  9873. bindingStates.releaseStatesOfGeometry( geometry );
  9874. if ( geometry.isInstancedBufferGeometry === true ) {
  9875. delete geometry._maxInstanceCount;
  9876. }
  9877. //
  9878. info.memory.geometries --;
  9879. }
  9880. function get( object, geometry ) {
  9881. if ( geometries[ geometry.id ] === true ) return geometry;
  9882. geometry.addEventListener( 'dispose', onGeometryDispose );
  9883. geometries[ geometry.id ] = true;
  9884. info.memory.geometries ++;
  9885. return geometry;
  9886. }
  9887. function update( geometry ) {
  9888. const geometryAttributes = geometry.attributes;
  9889. // Updating index buffer in VAO now. See WebGLBindingStates.
  9890. for ( const name in geometryAttributes ) {
  9891. attributes.update( geometryAttributes[ name ], gl.ARRAY_BUFFER );
  9892. }
  9893. // morph targets
  9894. const morphAttributes = geometry.morphAttributes;
  9895. for ( const name in morphAttributes ) {
  9896. const array = morphAttributes[ name ];
  9897. for ( let i = 0, l = array.length; i < l; i ++ ) {
  9898. attributes.update( array[ i ], gl.ARRAY_BUFFER );
  9899. }
  9900. }
  9901. }
  9902. function updateWireframeAttribute( geometry ) {
  9903. const indices = [];
  9904. const geometryIndex = geometry.index;
  9905. const geometryPosition = geometry.attributes.position;
  9906. let version = 0;
  9907. if ( geometryIndex !== null ) {
  9908. const array = geometryIndex.array;
  9909. version = geometryIndex.version;
  9910. for ( let i = 0, l = array.length; i < l; i += 3 ) {
  9911. const a = array[ i + 0 ];
  9912. const b = array[ i + 1 ];
  9913. const c = array[ i + 2 ];
  9914. indices.push( a, b, b, c, c, a );
  9915. }
  9916. } else {
  9917. const array = geometryPosition.array;
  9918. version = geometryPosition.version;
  9919. for ( let i = 0, l = ( array.length / 3 ) - 1; i < l; i += 3 ) {
  9920. const a = i + 0;
  9921. const b = i + 1;
  9922. const c = i + 2;
  9923. indices.push( a, b, b, c, c, a );
  9924. }
  9925. }
  9926. const attribute = new ( arrayNeedsUint32( indices ) ? Uint32BufferAttribute : Uint16BufferAttribute )( indices, 1 );
  9927. attribute.version = version;
  9928. // Updating index buffer in VAO now. See WebGLBindingStates
  9929. //
  9930. const previousAttribute = wireframeAttributes.get( geometry );
  9931. if ( previousAttribute ) attributes.remove( previousAttribute );
  9932. //
  9933. wireframeAttributes.set( geometry, attribute );
  9934. }
  9935. function getWireframeAttribute( geometry ) {
  9936. const currentAttribute = wireframeAttributes.get( geometry );
  9937. if ( currentAttribute ) {
  9938. const geometryIndex = geometry.index;
  9939. if ( geometryIndex !== null ) {
  9940. // if the attribute is obsolete, create a new one
  9941. if ( currentAttribute.version < geometryIndex.version ) {
  9942. updateWireframeAttribute( geometry );
  9943. }
  9944. }
  9945. } else {
  9946. updateWireframeAttribute( geometry );
  9947. }
  9948. return wireframeAttributes.get( geometry );
  9949. }
  9950. return {
  9951. get: get,
  9952. update: update,
  9953. getWireframeAttribute: getWireframeAttribute
  9954. };
  9955. }
  9956. function WebGLIndexedBufferRenderer( gl, extensions, info, capabilities ) {
  9957. const isWebGL2 = capabilities.isWebGL2;
  9958. let mode;
  9959. function setMode( value ) {
  9960. mode = value;
  9961. }
  9962. let type, bytesPerElement;
  9963. function setIndex( value ) {
  9964. type = value.type;
  9965. bytesPerElement = value.bytesPerElement;
  9966. }
  9967. function render( start, count ) {
  9968. gl.drawElements( mode, count, type, start * bytesPerElement );
  9969. info.update( count, mode, 1 );
  9970. }
  9971. function renderInstances( start, count, primcount ) {
  9972. if ( primcount === 0 ) return;
  9973. let extension, methodName;
  9974. if ( isWebGL2 ) {
  9975. extension = gl;
  9976. methodName = 'drawElementsInstanced';
  9977. } else {
  9978. extension = extensions.get( 'ANGLE_instanced_arrays' );
  9979. methodName = 'drawElementsInstancedANGLE';
  9980. if ( extension === null ) {
  9981. console.error( 'THREE.WebGLIndexedBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.' );
  9982. return;
  9983. }
  9984. }
  9985. extension[ methodName ]( mode, count, type, start * bytesPerElement, primcount );
  9986. info.update( count, mode, primcount );
  9987. }
  9988. //
  9989. this.setMode = setMode;
  9990. this.setIndex = setIndex;
  9991. this.render = render;
  9992. this.renderInstances = renderInstances;
  9993. }
  9994. function WebGLInfo( gl ) {
  9995. const memory = {
  9996. geometries: 0,
  9997. textures: 0
  9998. };
  9999. const render = {
  10000. frame: 0,
  10001. calls: 0,
  10002. triangles: 0,
  10003. points: 0,
  10004. lines: 0
  10005. };
  10006. function update( count, mode, instanceCount ) {
  10007. render.calls ++;
  10008. switch ( mode ) {
  10009. case gl.TRIANGLES:
  10010. render.triangles += instanceCount * ( count / 3 );
  10011. break;
  10012. case gl.LINES:
  10013. render.lines += instanceCount * ( count / 2 );
  10014. break;
  10015. case gl.LINE_STRIP:
  10016. render.lines += instanceCount * ( count - 1 );
  10017. break;
  10018. case gl.LINE_LOOP:
  10019. render.lines += instanceCount * count;
  10020. break;
  10021. case gl.POINTS:
  10022. render.points += instanceCount * count;
  10023. break;
  10024. default:
  10025. console.error( 'THREE.WebGLInfo: Unknown draw mode:', mode );
  10026. break;
  10027. }
  10028. }
  10029. function reset() {
  10030. render.frame ++;
  10031. render.calls = 0;
  10032. render.triangles = 0;
  10033. render.points = 0;
  10034. render.lines = 0;
  10035. }
  10036. return {
  10037. memory: memory,
  10038. render: render,
  10039. programs: null,
  10040. autoReset: true,
  10041. reset: reset,
  10042. update: update
  10043. };
  10044. }
  10045. function numericalSort( a, b ) {
  10046. return a[ 0 ] - b[ 0 ];
  10047. }
  10048. function absNumericalSort( a, b ) {
  10049. return Math.abs( b[ 1 ] ) - Math.abs( a[ 1 ] );
  10050. }
  10051. function WebGLMorphtargets( gl, capabilities, textures ) {
  10052. const influencesList = {};
  10053. const morphInfluences = new Float32Array( 8 );
  10054. const morphTextures = new WeakMap();
  10055. const morph = new Vector4();
  10056. const workInfluences = [];
  10057. for ( let i = 0; i < 8; i ++ ) {
  10058. workInfluences[ i ] = [ i, 0 ];
  10059. }
  10060. function update( object, geometry, material, program ) {
  10061. const objectInfluences = object.morphTargetInfluences;
  10062. if ( capabilities.isWebGL2 === true ) {
  10063. // instead of using attributes, the WebGL 2 code path encodes morph targets
  10064. // into an array of data textures. Each layer represents a single morph target.
  10065. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  10066. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  10067. let entry = morphTextures.get( geometry );
  10068. if ( entry === undefined || entry.count !== morphTargetsCount ) {
  10069. if ( entry !== undefined ) entry.texture.dispose();
  10070. const hasMorphPosition = geometry.morphAttributes.position !== undefined;
  10071. const hasMorphNormals = geometry.morphAttributes.normal !== undefined;
  10072. const hasMorphColors = geometry.morphAttributes.color !== undefined;
  10073. const morphTargets = geometry.morphAttributes.position || [];
  10074. const morphNormals = geometry.morphAttributes.normal || [];
  10075. const morphColors = geometry.morphAttributes.color || [];
  10076. let vertexDataCount = 0;
  10077. if ( hasMorphPosition === true ) vertexDataCount = 1;
  10078. if ( hasMorphNormals === true ) vertexDataCount = 2;
  10079. if ( hasMorphColors === true ) vertexDataCount = 3;
  10080. let width = geometry.attributes.position.count * vertexDataCount;
  10081. let height = 1;
  10082. if ( width > capabilities.maxTextureSize ) {
  10083. height = Math.ceil( width / capabilities.maxTextureSize );
  10084. width = capabilities.maxTextureSize;
  10085. }
  10086. const buffer = new Float32Array( width * height * 4 * morphTargetsCount );
  10087. const texture = new DataArrayTexture( buffer, width, height, morphTargetsCount );
  10088. texture.type = FloatType;
  10089. texture.needsUpdate = true;
  10090. // fill buffer
  10091. const vertexDataStride = vertexDataCount * 4;
  10092. for ( let i = 0; i < morphTargetsCount; i ++ ) {
  10093. const morphTarget = morphTargets[ i ];
  10094. const morphNormal = morphNormals[ i ];
  10095. const morphColor = morphColors[ i ];
  10096. const offset = width * height * 4 * i;
  10097. for ( let j = 0; j < morphTarget.count; j ++ ) {
  10098. const stride = j * vertexDataStride;
  10099. if ( hasMorphPosition === true ) {
  10100. morph.fromBufferAttribute( morphTarget, j );
  10101. buffer[ offset + stride + 0 ] = morph.x;
  10102. buffer[ offset + stride + 1 ] = morph.y;
  10103. buffer[ offset + stride + 2 ] = morph.z;
  10104. buffer[ offset + stride + 3 ] = 0;
  10105. }
  10106. if ( hasMorphNormals === true ) {
  10107. morph.fromBufferAttribute( morphNormal, j );
  10108. buffer[ offset + stride + 4 ] = morph.x;
  10109. buffer[ offset + stride + 5 ] = morph.y;
  10110. buffer[ offset + stride + 6 ] = morph.z;
  10111. buffer[ offset + stride + 7 ] = 0;
  10112. }
  10113. if ( hasMorphColors === true ) {
  10114. morph.fromBufferAttribute( morphColor, j );
  10115. buffer[ offset + stride + 8 ] = morph.x;
  10116. buffer[ offset + stride + 9 ] = morph.y;
  10117. buffer[ offset + stride + 10 ] = morph.z;
  10118. buffer[ offset + stride + 11 ] = ( morphColor.itemSize === 4 ) ? morph.w : 1;
  10119. }
  10120. }
  10121. }
  10122. entry = {
  10123. count: morphTargetsCount,
  10124. texture: texture,
  10125. size: new Vector2( width, height )
  10126. };
  10127. morphTextures.set( geometry, entry );
  10128. function disposeTexture() {
  10129. texture.dispose();
  10130. morphTextures.delete( geometry );
  10131. geometry.removeEventListener( 'dispose', disposeTexture );
  10132. }
  10133. geometry.addEventListener( 'dispose', disposeTexture );
  10134. }
  10135. //
  10136. let morphInfluencesSum = 0;
  10137. for ( let i = 0; i < objectInfluences.length; i ++ ) {
  10138. morphInfluencesSum += objectInfluences[ i ];
  10139. }
  10140. const morphBaseInfluence = geometry.morphTargetsRelative ? 1 : 1 - morphInfluencesSum;
  10141. program.getUniforms().setValue( gl, 'morphTargetBaseInfluence', morphBaseInfluence );
  10142. program.getUniforms().setValue( gl, 'morphTargetInfluences', objectInfluences );
  10143. program.getUniforms().setValue( gl, 'morphTargetsTexture', entry.texture, textures );
  10144. program.getUniforms().setValue( gl, 'morphTargetsTextureSize', entry.size );
  10145. } else {
  10146. // When object doesn't have morph target influences defined, we treat it as a 0-length array
  10147. // This is important to make sure we set up morphTargetBaseInfluence / morphTargetInfluences
  10148. const length = objectInfluences === undefined ? 0 : objectInfluences.length;
  10149. let influences = influencesList[ geometry.id ];
  10150. if ( influences === undefined || influences.length !== length ) {
  10151. // initialise list
  10152. influences = [];
  10153. for ( let i = 0; i < length; i ++ ) {
  10154. influences[ i ] = [ i, 0 ];
  10155. }
  10156. influencesList[ geometry.id ] = influences;
  10157. }
  10158. // Collect influences
  10159. for ( let i = 0; i < length; i ++ ) {
  10160. const influence = influences[ i ];
  10161. influence[ 0 ] = i;
  10162. influence[ 1 ] = objectInfluences[ i ];
  10163. }
  10164. influences.sort( absNumericalSort );
  10165. for ( let i = 0; i < 8; i ++ ) {
  10166. if ( i < length && influences[ i ][ 1 ] ) {
  10167. workInfluences[ i ][ 0 ] = influences[ i ][ 0 ];
  10168. workInfluences[ i ][ 1 ] = influences[ i ][ 1 ];
  10169. } else {
  10170. workInfluences[ i ][ 0 ] = Number.MAX_SAFE_INTEGER;
  10171. workInfluences[ i ][ 1 ] = 0;
  10172. }
  10173. }
  10174. workInfluences.sort( numericalSort );
  10175. const morphTargets = geometry.morphAttributes.position;
  10176. const morphNormals = geometry.morphAttributes.normal;
  10177. let morphInfluencesSum = 0;
  10178. for ( let i = 0; i < 8; i ++ ) {
  10179. const influence = workInfluences[ i ];
  10180. const index = influence[ 0 ];
  10181. const value = influence[ 1 ];
  10182. if ( index !== Number.MAX_SAFE_INTEGER && value ) {
  10183. if ( morphTargets && geometry.getAttribute( 'morphTarget' + i ) !== morphTargets[ index ] ) {
  10184. geometry.setAttribute( 'morphTarget' + i, morphTargets[ index ] );
  10185. }
  10186. if ( morphNormals && geometry.getAttribute( 'morphNormal' + i ) !== morphNormals[ index ] ) {
  10187. geometry.setAttribute( 'morphNormal' + i, morphNormals[ index ] );
  10188. }
  10189. morphInfluences[ i ] = value;
  10190. morphInfluencesSum += value;
  10191. } else {
  10192. if ( morphTargets && geometry.hasAttribute( 'morphTarget' + i ) === true ) {
  10193. geometry.deleteAttribute( 'morphTarget' + i );
  10194. }
  10195. if ( morphNormals && geometry.hasAttribute( 'morphNormal' + i ) === true ) {
  10196. geometry.deleteAttribute( 'morphNormal' + i );
  10197. }
  10198. morphInfluences[ i ] = 0;
  10199. }
  10200. }
  10201. // GLSL shader uses formula baseinfluence * base + sum(target * influence)
  10202. // This allows us to switch between absolute morphs and relative morphs without changing shader code
  10203. // When baseinfluence = 1 - sum(influence), the above is equivalent to sum((target - base) * influence)
  10204. const morphBaseInfluence = geometry.morphTargetsRelative ? 1 : 1 - morphInfluencesSum;
  10205. program.getUniforms().setValue( gl, 'morphTargetBaseInfluence', morphBaseInfluence );
  10206. program.getUniforms().setValue( gl, 'morphTargetInfluences', morphInfluences );
  10207. }
  10208. }
  10209. return {
  10210. update: update
  10211. };
  10212. }
  10213. function WebGLObjects( gl, geometries, attributes, info ) {
  10214. let updateMap = new WeakMap();
  10215. function update( object ) {
  10216. const frame = info.render.frame;
  10217. const geometry = object.geometry;
  10218. const buffergeometry = geometries.get( object, geometry );
  10219. // Update once per frame
  10220. if ( updateMap.get( buffergeometry ) !== frame ) {
  10221. geometries.update( buffergeometry );
  10222. updateMap.set( buffergeometry, frame );
  10223. }
  10224. if ( object.isInstancedMesh ) {
  10225. if ( object.hasEventListener( 'dispose', onInstancedMeshDispose ) === false ) {
  10226. object.addEventListener( 'dispose', onInstancedMeshDispose );
  10227. }
  10228. attributes.update( object.instanceMatrix, gl.ARRAY_BUFFER );
  10229. if ( object.instanceColor !== null ) {
  10230. attributes.update( object.instanceColor, gl.ARRAY_BUFFER );
  10231. }
  10232. }
  10233. return buffergeometry;
  10234. }
  10235. function dispose() {
  10236. updateMap = new WeakMap();
  10237. }
  10238. function onInstancedMeshDispose( event ) {
  10239. const instancedMesh = event.target;
  10240. instancedMesh.removeEventListener( 'dispose', onInstancedMeshDispose );
  10241. attributes.remove( instancedMesh.instanceMatrix );
  10242. if ( instancedMesh.instanceColor !== null ) attributes.remove( instancedMesh.instanceColor );
  10243. }
  10244. return {
  10245. update: update,
  10246. dispose: dispose
  10247. };
  10248. }
  10249. /**
  10250. * Uniforms of a program.
  10251. * Those form a tree structure with a special top-level container for the root,
  10252. * which you get by calling 'new WebGLUniforms( gl, program )'.
  10253. *
  10254. *
  10255. * Properties of inner nodes including the top-level container:
  10256. *
  10257. * .seq - array of nested uniforms
  10258. * .map - nested uniforms by name
  10259. *
  10260. *
  10261. * Methods of all nodes except the top-level container:
  10262. *
  10263. * .setValue( gl, value, [textures] )
  10264. *
  10265. * uploads a uniform value(s)
  10266. * the 'textures' parameter is needed for sampler uniforms
  10267. *
  10268. *
  10269. * Static methods of the top-level container (textures factorizations):
  10270. *
  10271. * .upload( gl, seq, values, textures )
  10272. *
  10273. * sets uniforms in 'seq' to 'values[id].value'
  10274. *
  10275. * .seqWithValue( seq, values ) : filteredSeq
  10276. *
  10277. * filters 'seq' entries with corresponding entry in values
  10278. *
  10279. *
  10280. * Methods of the top-level container (textures factorizations):
  10281. *
  10282. * .setValue( gl, name, value, textures )
  10283. *
  10284. * sets uniform with name 'name' to 'value'
  10285. *
  10286. * .setOptional( gl, obj, prop )
  10287. *
  10288. * like .set for an optional property of the object
  10289. *
  10290. */
  10291. const emptyTexture = /*@__PURE__*/ new Texture();
  10292. const emptyArrayTexture = /*@__PURE__*/ new DataArrayTexture();
  10293. const empty3dTexture = /*@__PURE__*/ new Data3DTexture();
  10294. const emptyCubeTexture = /*@__PURE__*/ new CubeTexture();
  10295. // --- Utilities ---
  10296. // Array Caches (provide typed arrays for temporary by size)
  10297. const arrayCacheF32 = [];
  10298. const arrayCacheI32 = [];
  10299. // Float32Array caches used for uploading Matrix uniforms
  10300. const mat4array = new Float32Array( 16 );
  10301. const mat3array = new Float32Array( 9 );
  10302. const mat2array = new Float32Array( 4 );
  10303. // Flattening for arrays of vectors and matrices
  10304. function flatten( array, nBlocks, blockSize ) {
  10305. const firstElem = array[ 0 ];
  10306. if ( firstElem <= 0 || firstElem > 0 ) return array;
  10307. // unoptimized: ! isNaN( firstElem )
  10308. // see http://jacksondunstan.com/articles/983
  10309. const n = nBlocks * blockSize;
  10310. let r = arrayCacheF32[ n ];
  10311. if ( r === undefined ) {
  10312. r = new Float32Array( n );
  10313. arrayCacheF32[ n ] = r;
  10314. }
  10315. if ( nBlocks !== 0 ) {
  10316. firstElem.toArray( r, 0 );
  10317. for ( let i = 1, offset = 0; i !== nBlocks; ++ i ) {
  10318. offset += blockSize;
  10319. array[ i ].toArray( r, offset );
  10320. }
  10321. }
  10322. return r;
  10323. }
  10324. function arraysEqual( a, b ) {
  10325. if ( a.length !== b.length ) return false;
  10326. for ( let i = 0, l = a.length; i < l; i ++ ) {
  10327. if ( a[ i ] !== b[ i ] ) return false;
  10328. }
  10329. return true;
  10330. }
  10331. function copyArray( a, b ) {
  10332. for ( let i = 0, l = b.length; i < l; i ++ ) {
  10333. a[ i ] = b[ i ];
  10334. }
  10335. }
  10336. // Texture unit allocation
  10337. function allocTexUnits( textures, n ) {
  10338. let r = arrayCacheI32[ n ];
  10339. if ( r === undefined ) {
  10340. r = new Int32Array( n );
  10341. arrayCacheI32[ n ] = r;
  10342. }
  10343. for ( let i = 0; i !== n; ++ i ) {
  10344. r[ i ] = textures.allocateTextureUnit();
  10345. }
  10346. return r;
  10347. }
  10348. // --- Setters ---
  10349. // Note: Defining these methods externally, because they come in a bunch
  10350. // and this way their names minify.
  10351. // Single scalar
  10352. function setValueV1f( gl, v ) {
  10353. const cache = this.cache;
  10354. if ( cache[ 0 ] === v ) return;
  10355. gl.uniform1f( this.addr, v );
  10356. cache[ 0 ] = v;
  10357. }
  10358. // Single float vector (from flat array or THREE.VectorN)
  10359. function setValueV2f( gl, v ) {
  10360. const cache = this.cache;
  10361. if ( v.x !== undefined ) {
  10362. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y ) {
  10363. gl.uniform2f( this.addr, v.x, v.y );
  10364. cache[ 0 ] = v.x;
  10365. cache[ 1 ] = v.y;
  10366. }
  10367. } else {
  10368. if ( arraysEqual( cache, v ) ) return;
  10369. gl.uniform2fv( this.addr, v );
  10370. copyArray( cache, v );
  10371. }
  10372. }
  10373. function setValueV3f( gl, v ) {
  10374. const cache = this.cache;
  10375. if ( v.x !== undefined ) {
  10376. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z ) {
  10377. gl.uniform3f( this.addr, v.x, v.y, v.z );
  10378. cache[ 0 ] = v.x;
  10379. cache[ 1 ] = v.y;
  10380. cache[ 2 ] = v.z;
  10381. }
  10382. } else if ( v.r !== undefined ) {
  10383. if ( cache[ 0 ] !== v.r || cache[ 1 ] !== v.g || cache[ 2 ] !== v.b ) {
  10384. gl.uniform3f( this.addr, v.r, v.g, v.b );
  10385. cache[ 0 ] = v.r;
  10386. cache[ 1 ] = v.g;
  10387. cache[ 2 ] = v.b;
  10388. }
  10389. } else {
  10390. if ( arraysEqual( cache, v ) ) return;
  10391. gl.uniform3fv( this.addr, v );
  10392. copyArray( cache, v );
  10393. }
  10394. }
  10395. function setValueV4f( gl, v ) {
  10396. const cache = this.cache;
  10397. if ( v.x !== undefined ) {
  10398. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z || cache[ 3 ] !== v.w ) {
  10399. gl.uniform4f( this.addr, v.x, v.y, v.z, v.w );
  10400. cache[ 0 ] = v.x;
  10401. cache[ 1 ] = v.y;
  10402. cache[ 2 ] = v.z;
  10403. cache[ 3 ] = v.w;
  10404. }
  10405. } else {
  10406. if ( arraysEqual( cache, v ) ) return;
  10407. gl.uniform4fv( this.addr, v );
  10408. copyArray( cache, v );
  10409. }
  10410. }
  10411. // Single matrix (from flat array or THREE.MatrixN)
  10412. function setValueM2( gl, v ) {
  10413. const cache = this.cache;
  10414. const elements = v.elements;
  10415. if ( elements === undefined ) {
  10416. if ( arraysEqual( cache, v ) ) return;
  10417. gl.uniformMatrix2fv( this.addr, false, v );
  10418. copyArray( cache, v );
  10419. } else {
  10420. if ( arraysEqual( cache, elements ) ) return;
  10421. mat2array.set( elements );
  10422. gl.uniformMatrix2fv( this.addr, false, mat2array );
  10423. copyArray( cache, elements );
  10424. }
  10425. }
  10426. function setValueM3( gl, v ) {
  10427. const cache = this.cache;
  10428. const elements = v.elements;
  10429. if ( elements === undefined ) {
  10430. if ( arraysEqual( cache, v ) ) return;
  10431. gl.uniformMatrix3fv( this.addr, false, v );
  10432. copyArray( cache, v );
  10433. } else {
  10434. if ( arraysEqual( cache, elements ) ) return;
  10435. mat3array.set( elements );
  10436. gl.uniformMatrix3fv( this.addr, false, mat3array );
  10437. copyArray( cache, elements );
  10438. }
  10439. }
  10440. function setValueM4( gl, v ) {
  10441. const cache = this.cache;
  10442. const elements = v.elements;
  10443. if ( elements === undefined ) {
  10444. if ( arraysEqual( cache, v ) ) return;
  10445. gl.uniformMatrix4fv( this.addr, false, v );
  10446. copyArray( cache, v );
  10447. } else {
  10448. if ( arraysEqual( cache, elements ) ) return;
  10449. mat4array.set( elements );
  10450. gl.uniformMatrix4fv( this.addr, false, mat4array );
  10451. copyArray( cache, elements );
  10452. }
  10453. }
  10454. // Single integer / boolean
  10455. function setValueV1i( gl, v ) {
  10456. const cache = this.cache;
  10457. if ( cache[ 0 ] === v ) return;
  10458. gl.uniform1i( this.addr, v );
  10459. cache[ 0 ] = v;
  10460. }
  10461. // Single integer / boolean vector (from flat array or THREE.VectorN)
  10462. function setValueV2i( gl, v ) {
  10463. const cache = this.cache;
  10464. if ( v.x !== undefined ) {
  10465. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y ) {
  10466. gl.uniform2i( this.addr, v.x, v.y );
  10467. cache[ 0 ] = v.x;
  10468. cache[ 1 ] = v.y;
  10469. }
  10470. } else {
  10471. if ( arraysEqual( cache, v ) ) return;
  10472. gl.uniform2iv( this.addr, v );
  10473. copyArray( cache, v );
  10474. }
  10475. }
  10476. function setValueV3i( gl, v ) {
  10477. const cache = this.cache;
  10478. if ( v.x !== undefined ) {
  10479. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z ) {
  10480. gl.uniform3i( this.addr, v.x, v.y, v.z );
  10481. cache[ 0 ] = v.x;
  10482. cache[ 1 ] = v.y;
  10483. cache[ 2 ] = v.z;
  10484. }
  10485. } else {
  10486. if ( arraysEqual( cache, v ) ) return;
  10487. gl.uniform3iv( this.addr, v );
  10488. copyArray( cache, v );
  10489. }
  10490. }
  10491. function setValueV4i( gl, v ) {
  10492. const cache = this.cache;
  10493. if ( v.x !== undefined ) {
  10494. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z || cache[ 3 ] !== v.w ) {
  10495. gl.uniform4i( this.addr, v.x, v.y, v.z, v.w );
  10496. cache[ 0 ] = v.x;
  10497. cache[ 1 ] = v.y;
  10498. cache[ 2 ] = v.z;
  10499. cache[ 3 ] = v.w;
  10500. }
  10501. } else {
  10502. if ( arraysEqual( cache, v ) ) return;
  10503. gl.uniform4iv( this.addr, v );
  10504. copyArray( cache, v );
  10505. }
  10506. }
  10507. // Single unsigned integer
  10508. function setValueV1ui( gl, v ) {
  10509. const cache = this.cache;
  10510. if ( cache[ 0 ] === v ) return;
  10511. gl.uniform1ui( this.addr, v );
  10512. cache[ 0 ] = v;
  10513. }
  10514. // Single unsigned integer vector (from flat array or THREE.VectorN)
  10515. function setValueV2ui( gl, v ) {
  10516. const cache = this.cache;
  10517. if ( v.x !== undefined ) {
  10518. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y ) {
  10519. gl.uniform2ui( this.addr, v.x, v.y );
  10520. cache[ 0 ] = v.x;
  10521. cache[ 1 ] = v.y;
  10522. }
  10523. } else {
  10524. if ( arraysEqual( cache, v ) ) return;
  10525. gl.uniform2uiv( this.addr, v );
  10526. copyArray( cache, v );
  10527. }
  10528. }
  10529. function setValueV3ui( gl, v ) {
  10530. const cache = this.cache;
  10531. if ( v.x !== undefined ) {
  10532. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z ) {
  10533. gl.uniform3ui( this.addr, v.x, v.y, v.z );
  10534. cache[ 0 ] = v.x;
  10535. cache[ 1 ] = v.y;
  10536. cache[ 2 ] = v.z;
  10537. }
  10538. } else {
  10539. if ( arraysEqual( cache, v ) ) return;
  10540. gl.uniform3uiv( this.addr, v );
  10541. copyArray( cache, v );
  10542. }
  10543. }
  10544. function setValueV4ui( gl, v ) {
  10545. const cache = this.cache;
  10546. if ( v.x !== undefined ) {
  10547. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z || cache[ 3 ] !== v.w ) {
  10548. gl.uniform4ui( this.addr, v.x, v.y, v.z, v.w );
  10549. cache[ 0 ] = v.x;
  10550. cache[ 1 ] = v.y;
  10551. cache[ 2 ] = v.z;
  10552. cache[ 3 ] = v.w;
  10553. }
  10554. } else {
  10555. if ( arraysEqual( cache, v ) ) return;
  10556. gl.uniform4uiv( this.addr, v );
  10557. copyArray( cache, v );
  10558. }
  10559. }
  10560. // Single texture (2D / Cube)
  10561. function setValueT1( gl, v, textures ) {
  10562. const cache = this.cache;
  10563. const unit = textures.allocateTextureUnit();
  10564. if ( cache[ 0 ] !== unit ) {
  10565. gl.uniform1i( this.addr, unit );
  10566. cache[ 0 ] = unit;
  10567. }
  10568. textures.setTexture2D( v || emptyTexture, unit );
  10569. }
  10570. function setValueT3D1( gl, v, textures ) {
  10571. const cache = this.cache;
  10572. const unit = textures.allocateTextureUnit();
  10573. if ( cache[ 0 ] !== unit ) {
  10574. gl.uniform1i( this.addr, unit );
  10575. cache[ 0 ] = unit;
  10576. }
  10577. textures.setTexture3D( v || empty3dTexture, unit );
  10578. }
  10579. function setValueT6( gl, v, textures ) {
  10580. const cache = this.cache;
  10581. const unit = textures.allocateTextureUnit();
  10582. if ( cache[ 0 ] !== unit ) {
  10583. gl.uniform1i( this.addr, unit );
  10584. cache[ 0 ] = unit;
  10585. }
  10586. textures.setTextureCube( v || emptyCubeTexture, unit );
  10587. }
  10588. function setValueT2DArray1( gl, v, textures ) {
  10589. const cache = this.cache;
  10590. const unit = textures.allocateTextureUnit();
  10591. if ( cache[ 0 ] !== unit ) {
  10592. gl.uniform1i( this.addr, unit );
  10593. cache[ 0 ] = unit;
  10594. }
  10595. textures.setTexture2DArray( v || emptyArrayTexture, unit );
  10596. }
  10597. // Helper to pick the right setter for the singular case
  10598. function getSingularSetter( type ) {
  10599. switch ( type ) {
  10600. case 0x1406: return setValueV1f; // FLOAT
  10601. case 0x8b50: return setValueV2f; // _VEC2
  10602. case 0x8b51: return setValueV3f; // _VEC3
  10603. case 0x8b52: return setValueV4f; // _VEC4
  10604. case 0x8b5a: return setValueM2; // _MAT2
  10605. case 0x8b5b: return setValueM3; // _MAT3
  10606. case 0x8b5c: return setValueM4; // _MAT4
  10607. case 0x1404: case 0x8b56: return setValueV1i; // INT, BOOL
  10608. case 0x8b53: case 0x8b57: return setValueV2i; // _VEC2
  10609. case 0x8b54: case 0x8b58: return setValueV3i; // _VEC3
  10610. case 0x8b55: case 0x8b59: return setValueV4i; // _VEC4
  10611. case 0x1405: return setValueV1ui; // UINT
  10612. case 0x8dc6: return setValueV2ui; // _VEC2
  10613. case 0x8dc7: return setValueV3ui; // _VEC3
  10614. case 0x8dc8: return setValueV4ui; // _VEC4
  10615. case 0x8b5e: // SAMPLER_2D
  10616. case 0x8d66: // SAMPLER_EXTERNAL_OES
  10617. case 0x8dca: // INT_SAMPLER_2D
  10618. case 0x8dd2: // UNSIGNED_INT_SAMPLER_2D
  10619. case 0x8b62: // SAMPLER_2D_SHADOW
  10620. return setValueT1;
  10621. case 0x8b5f: // SAMPLER_3D
  10622. case 0x8dcb: // INT_SAMPLER_3D
  10623. case 0x8dd3: // UNSIGNED_INT_SAMPLER_3D
  10624. return setValueT3D1;
  10625. case 0x8b60: // SAMPLER_CUBE
  10626. case 0x8dcc: // INT_SAMPLER_CUBE
  10627. case 0x8dd4: // UNSIGNED_INT_SAMPLER_CUBE
  10628. case 0x8dc5: // SAMPLER_CUBE_SHADOW
  10629. return setValueT6;
  10630. case 0x8dc1: // SAMPLER_2D_ARRAY
  10631. case 0x8dcf: // INT_SAMPLER_2D_ARRAY
  10632. case 0x8dd7: // UNSIGNED_INT_SAMPLER_2D_ARRAY
  10633. case 0x8dc4: // SAMPLER_2D_ARRAY_SHADOW
  10634. return setValueT2DArray1;
  10635. }
  10636. }
  10637. // Array of scalars
  10638. function setValueV1fArray( gl, v ) {
  10639. gl.uniform1fv( this.addr, v );
  10640. }
  10641. // Array of vectors (from flat array or array of THREE.VectorN)
  10642. function setValueV2fArray( gl, v ) {
  10643. const data = flatten( v, this.size, 2 );
  10644. gl.uniform2fv( this.addr, data );
  10645. }
  10646. function setValueV3fArray( gl, v ) {
  10647. const data = flatten( v, this.size, 3 );
  10648. gl.uniform3fv( this.addr, data );
  10649. }
  10650. function setValueV4fArray( gl, v ) {
  10651. const data = flatten( v, this.size, 4 );
  10652. gl.uniform4fv( this.addr, data );
  10653. }
  10654. // Array of matrices (from flat array or array of THREE.MatrixN)
  10655. function setValueM2Array( gl, v ) {
  10656. const data = flatten( v, this.size, 4 );
  10657. gl.uniformMatrix2fv( this.addr, false, data );
  10658. }
  10659. function setValueM3Array( gl, v ) {
  10660. const data = flatten( v, this.size, 9 );
  10661. gl.uniformMatrix3fv( this.addr, false, data );
  10662. }
  10663. function setValueM4Array( gl, v ) {
  10664. const data = flatten( v, this.size, 16 );
  10665. gl.uniformMatrix4fv( this.addr, false, data );
  10666. }
  10667. // Array of integer / boolean
  10668. function setValueV1iArray( gl, v ) {
  10669. gl.uniform1iv( this.addr, v );
  10670. }
  10671. // Array of integer / boolean vectors (from flat array)
  10672. function setValueV2iArray( gl, v ) {
  10673. gl.uniform2iv( this.addr, v );
  10674. }
  10675. function setValueV3iArray( gl, v ) {
  10676. gl.uniform3iv( this.addr, v );
  10677. }
  10678. function setValueV4iArray( gl, v ) {
  10679. gl.uniform4iv( this.addr, v );
  10680. }
  10681. // Array of unsigned integer
  10682. function setValueV1uiArray( gl, v ) {
  10683. gl.uniform1uiv( this.addr, v );
  10684. }
  10685. // Array of unsigned integer vectors (from flat array)
  10686. function setValueV2uiArray( gl, v ) {
  10687. gl.uniform2uiv( this.addr, v );
  10688. }
  10689. function setValueV3uiArray( gl, v ) {
  10690. gl.uniform3uiv( this.addr, v );
  10691. }
  10692. function setValueV4uiArray( gl, v ) {
  10693. gl.uniform4uiv( this.addr, v );
  10694. }
  10695. // Array of textures (2D / 3D / Cube / 2DArray)
  10696. function setValueT1Array( gl, v, textures ) {
  10697. const cache = this.cache;
  10698. const n = v.length;
  10699. const units = allocTexUnits( textures, n );
  10700. if ( ! arraysEqual( cache, units ) ) {
  10701. gl.uniform1iv( this.addr, units );
  10702. copyArray( cache, units );
  10703. }
  10704. for ( let i = 0; i !== n; ++ i ) {
  10705. textures.setTexture2D( v[ i ] || emptyTexture, units[ i ] );
  10706. }
  10707. }
  10708. function setValueT3DArray( gl, v, textures ) {
  10709. const cache = this.cache;
  10710. const n = v.length;
  10711. const units = allocTexUnits( textures, n );
  10712. if ( ! arraysEqual( cache, units ) ) {
  10713. gl.uniform1iv( this.addr, units );
  10714. copyArray( cache, units );
  10715. }
  10716. for ( let i = 0; i !== n; ++ i ) {
  10717. textures.setTexture3D( v[ i ] || empty3dTexture, units[ i ] );
  10718. }
  10719. }
  10720. function setValueT6Array( gl, v, textures ) {
  10721. const cache = this.cache;
  10722. const n = v.length;
  10723. const units = allocTexUnits( textures, n );
  10724. if ( ! arraysEqual( cache, units ) ) {
  10725. gl.uniform1iv( this.addr, units );
  10726. copyArray( cache, units );
  10727. }
  10728. for ( let i = 0; i !== n; ++ i ) {
  10729. textures.setTextureCube( v[ i ] || emptyCubeTexture, units[ i ] );
  10730. }
  10731. }
  10732. function setValueT2DArrayArray( gl, v, textures ) {
  10733. const cache = this.cache;
  10734. const n = v.length;
  10735. const units = allocTexUnits( textures, n );
  10736. if ( ! arraysEqual( cache, units ) ) {
  10737. gl.uniform1iv( this.addr, units );
  10738. copyArray( cache, units );
  10739. }
  10740. for ( let i = 0; i !== n; ++ i ) {
  10741. textures.setTexture2DArray( v[ i ] || emptyArrayTexture, units[ i ] );
  10742. }
  10743. }
  10744. // Helper to pick the right setter for a pure (bottom-level) array
  10745. function getPureArraySetter( type ) {
  10746. switch ( type ) {
  10747. case 0x1406: return setValueV1fArray; // FLOAT
  10748. case 0x8b50: return setValueV2fArray; // _VEC2
  10749. case 0x8b51: return setValueV3fArray; // _VEC3
  10750. case 0x8b52: return setValueV4fArray; // _VEC4
  10751. case 0x8b5a: return setValueM2Array; // _MAT2
  10752. case 0x8b5b: return setValueM3Array; // _MAT3
  10753. case 0x8b5c: return setValueM4Array; // _MAT4
  10754. case 0x1404: case 0x8b56: return setValueV1iArray; // INT, BOOL
  10755. case 0x8b53: case 0x8b57: return setValueV2iArray; // _VEC2
  10756. case 0x8b54: case 0x8b58: return setValueV3iArray; // _VEC3
  10757. case 0x8b55: case 0x8b59: return setValueV4iArray; // _VEC4
  10758. case 0x1405: return setValueV1uiArray; // UINT
  10759. case 0x8dc6: return setValueV2uiArray; // _VEC2
  10760. case 0x8dc7: return setValueV3uiArray; // _VEC3
  10761. case 0x8dc8: return setValueV4uiArray; // _VEC4
  10762. case 0x8b5e: // SAMPLER_2D
  10763. case 0x8d66: // SAMPLER_EXTERNAL_OES
  10764. case 0x8dca: // INT_SAMPLER_2D
  10765. case 0x8dd2: // UNSIGNED_INT_SAMPLER_2D
  10766. case 0x8b62: // SAMPLER_2D_SHADOW
  10767. return setValueT1Array;
  10768. case 0x8b5f: // SAMPLER_3D
  10769. case 0x8dcb: // INT_SAMPLER_3D
  10770. case 0x8dd3: // UNSIGNED_INT_SAMPLER_3D
  10771. return setValueT3DArray;
  10772. case 0x8b60: // SAMPLER_CUBE
  10773. case 0x8dcc: // INT_SAMPLER_CUBE
  10774. case 0x8dd4: // UNSIGNED_INT_SAMPLER_CUBE
  10775. case 0x8dc5: // SAMPLER_CUBE_SHADOW
  10776. return setValueT6Array;
  10777. case 0x8dc1: // SAMPLER_2D_ARRAY
  10778. case 0x8dcf: // INT_SAMPLER_2D_ARRAY
  10779. case 0x8dd7: // UNSIGNED_INT_SAMPLER_2D_ARRAY
  10780. case 0x8dc4: // SAMPLER_2D_ARRAY_SHADOW
  10781. return setValueT2DArrayArray;
  10782. }
  10783. }
  10784. // --- Uniform Classes ---
  10785. class SingleUniform {
  10786. constructor( id, activeInfo, addr ) {
  10787. this.id = id;
  10788. this.addr = addr;
  10789. this.cache = [];
  10790. this.setValue = getSingularSetter( activeInfo.type );
  10791. // this.path = activeInfo.name; // DEBUG
  10792. }
  10793. }
  10794. class PureArrayUniform {
  10795. constructor( id, activeInfo, addr ) {
  10796. this.id = id;
  10797. this.addr = addr;
  10798. this.cache = [];
  10799. this.size = activeInfo.size;
  10800. this.setValue = getPureArraySetter( activeInfo.type );
  10801. // this.path = activeInfo.name; // DEBUG
  10802. }
  10803. }
  10804. class StructuredUniform {
  10805. constructor( id ) {
  10806. this.id = id;
  10807. this.seq = [];
  10808. this.map = {};
  10809. }
  10810. setValue( gl, value, textures ) {
  10811. const seq = this.seq;
  10812. for ( let i = 0, n = seq.length; i !== n; ++ i ) {
  10813. const u = seq[ i ];
  10814. u.setValue( gl, value[ u.id ], textures );
  10815. }
  10816. }
  10817. }
  10818. // --- Top-level ---
  10819. // Parser - builds up the property tree from the path strings
  10820. const RePathPart = /(\w+)(\])?(\[|\.)?/g;
  10821. // extracts
  10822. // - the identifier (member name or array index)
  10823. // - followed by an optional right bracket (found when array index)
  10824. // - followed by an optional left bracket or dot (type of subscript)
  10825. //
  10826. // Note: These portions can be read in a non-overlapping fashion and
  10827. // allow straightforward parsing of the hierarchy that WebGL encodes
  10828. // in the uniform names.
  10829. function addUniform( container, uniformObject ) {
  10830. container.seq.push( uniformObject );
  10831. container.map[ uniformObject.id ] = uniformObject;
  10832. }
  10833. function parseUniform( activeInfo, addr, container ) {
  10834. const path = activeInfo.name,
  10835. pathLength = path.length;
  10836. // reset RegExp object, because of the early exit of a previous run
  10837. RePathPart.lastIndex = 0;
  10838. while ( true ) {
  10839. const match = RePathPart.exec( path ),
  10840. matchEnd = RePathPart.lastIndex;
  10841. let id = match[ 1 ];
  10842. const idIsIndex = match[ 2 ] === ']',
  10843. subscript = match[ 3 ];
  10844. if ( idIsIndex ) id = id | 0; // convert to integer
  10845. if ( subscript === undefined || subscript === '[' && matchEnd + 2 === pathLength ) {
  10846. // bare name or "pure" bottom-level array "[0]" suffix
  10847. addUniform( container, subscript === undefined ?
  10848. new SingleUniform( id, activeInfo, addr ) :
  10849. new PureArrayUniform( id, activeInfo, addr ) );
  10850. break;
  10851. } else {
  10852. // step into inner node / create it in case it doesn't exist
  10853. const map = container.map;
  10854. let next = map[ id ];
  10855. if ( next === undefined ) {
  10856. next = new StructuredUniform( id );
  10857. addUniform( container, next );
  10858. }
  10859. container = next;
  10860. }
  10861. }
  10862. }
  10863. // Root Container
  10864. class WebGLUniforms {
  10865. constructor( gl, program ) {
  10866. this.seq = [];
  10867. this.map = {};
  10868. const n = gl.getProgramParameter( program, gl.ACTIVE_UNIFORMS );
  10869. for ( let i = 0; i < n; ++ i ) {
  10870. const info = gl.getActiveUniform( program, i ),
  10871. addr = gl.getUniformLocation( program, info.name );
  10872. parseUniform( info, addr, this );
  10873. }
  10874. }
  10875. setValue( gl, name, value, textures ) {
  10876. const u = this.map[ name ];
  10877. if ( u !== undefined ) u.setValue( gl, value, textures );
  10878. }
  10879. setOptional( gl, object, name ) {
  10880. const v = object[ name ];
  10881. if ( v !== undefined ) this.setValue( gl, name, v );
  10882. }
  10883. static upload( gl, seq, values, textures ) {
  10884. for ( let i = 0, n = seq.length; i !== n; ++ i ) {
  10885. const u = seq[ i ],
  10886. v = values[ u.id ];
  10887. if ( v.needsUpdate !== false ) {
  10888. // note: always updating when .needsUpdate is undefined
  10889. u.setValue( gl, v.value, textures );
  10890. }
  10891. }
  10892. }
  10893. static seqWithValue( seq, values ) {
  10894. const r = [];
  10895. for ( let i = 0, n = seq.length; i !== n; ++ i ) {
  10896. const u = seq[ i ];
  10897. if ( u.id in values ) r.push( u );
  10898. }
  10899. return r;
  10900. }
  10901. }
  10902. function WebGLShader( gl, type, string ) {
  10903. const shader = gl.createShader( type );
  10904. gl.shaderSource( shader, string );
  10905. gl.compileShader( shader );
  10906. return shader;
  10907. }
  10908. let programIdCount = 0;
  10909. function handleSource( string, errorLine ) {
  10910. const lines = string.split( '\n' );
  10911. const lines2 = [];
  10912. const from = Math.max( errorLine - 6, 0 );
  10913. const to = Math.min( errorLine + 6, lines.length );
  10914. for ( let i = from; i < to; i ++ ) {
  10915. const line = i + 1;
  10916. lines2.push( `${line === errorLine ? '>' : ' '} ${line}: ${lines[ i ]}` );
  10917. }
  10918. return lines2.join( '\n' );
  10919. }
  10920. function getEncodingComponents( encoding ) {
  10921. switch ( encoding ) {
  10922. case LinearEncoding:
  10923. return [ 'Linear', '( value )' ];
  10924. case sRGBEncoding:
  10925. return [ 'sRGB', '( value )' ];
  10926. default:
  10927. console.warn( 'THREE.WebGLProgram: Unsupported encoding:', encoding );
  10928. return [ 'Linear', '( value )' ];
  10929. }
  10930. }
  10931. function getShaderErrors( gl, shader, type ) {
  10932. const status = gl.getShaderParameter( shader, gl.COMPILE_STATUS );
  10933. const errors = gl.getShaderInfoLog( shader ).trim();
  10934. if ( status && errors === '' ) return '';
  10935. const errorMatches = /ERROR: 0:(\d+)/.exec( errors );
  10936. if ( errorMatches ) {
  10937. // --enable-privileged-webgl-extension
  10938. // console.log( '**' + type + '**', gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( shader ) );
  10939. const errorLine = parseInt( errorMatches[ 1 ] );
  10940. return type.toUpperCase() + '\n\n' + errors + '\n\n' + handleSource( gl.getShaderSource( shader ), errorLine );
  10941. } else {
  10942. return errors;
  10943. }
  10944. }
  10945. function getTexelEncodingFunction( functionName, encoding ) {
  10946. const components = getEncodingComponents( encoding );
  10947. return 'vec4 ' + functionName + '( vec4 value ) { return LinearTo' + components[ 0 ] + components[ 1 ] + '; }';
  10948. }
  10949. function getToneMappingFunction( functionName, toneMapping ) {
  10950. let toneMappingName;
  10951. switch ( toneMapping ) {
  10952. case LinearToneMapping:
  10953. toneMappingName = 'Linear';
  10954. break;
  10955. case ReinhardToneMapping:
  10956. toneMappingName = 'Reinhard';
  10957. break;
  10958. case CineonToneMapping:
  10959. toneMappingName = 'OptimizedCineon';
  10960. break;
  10961. case ACESFilmicToneMapping:
  10962. toneMappingName = 'ACESFilmic';
  10963. break;
  10964. case CustomToneMapping:
  10965. toneMappingName = 'Custom';
  10966. break;
  10967. default:
  10968. console.warn( 'THREE.WebGLProgram: Unsupported toneMapping:', toneMapping );
  10969. toneMappingName = 'Linear';
  10970. }
  10971. return 'vec3 ' + functionName + '( vec3 color ) { return ' + toneMappingName + 'ToneMapping( color ); }';
  10972. }
  10973. function generateExtensions( parameters ) {
  10974. const chunks = [
  10975. ( parameters.extensionDerivatives || !! parameters.envMapCubeUVHeight || parameters.bumpMap || parameters.tangentSpaceNormalMap || parameters.clearcoatNormalMap || parameters.flatShading || parameters.shaderID === 'physical' ) ? '#extension GL_OES_standard_derivatives : enable' : '',
  10976. ( parameters.extensionFragDepth || parameters.logarithmicDepthBuffer ) && parameters.rendererExtensionFragDepth ? '#extension GL_EXT_frag_depth : enable' : '',
  10977. ( parameters.extensionDrawBuffers && parameters.rendererExtensionDrawBuffers ) ? '#extension GL_EXT_draw_buffers : require' : '',
  10978. ( parameters.extensionShaderTextureLOD || parameters.envMap || parameters.transmission ) && parameters.rendererExtensionShaderTextureLod ? '#extension GL_EXT_shader_texture_lod : enable' : ''
  10979. ];
  10980. return chunks.filter( filterEmptyLine ).join( '\n' );
  10981. }
  10982. function generateDefines( defines ) {
  10983. const chunks = [];
  10984. for ( const name in defines ) {
  10985. const value = defines[ name ];
  10986. if ( value === false ) continue;
  10987. chunks.push( '#define ' + name + ' ' + value );
  10988. }
  10989. return chunks.join( '\n' );
  10990. }
  10991. function fetchAttributeLocations( gl, program ) {
  10992. const attributes = {};
  10993. const n = gl.getProgramParameter( program, gl.ACTIVE_ATTRIBUTES );
  10994. for ( let i = 0; i < n; i ++ ) {
  10995. const info = gl.getActiveAttrib( program, i );
  10996. const name = info.name;
  10997. let locationSize = 1;
  10998. if ( info.type === gl.FLOAT_MAT2 ) locationSize = 2;
  10999. if ( info.type === gl.FLOAT_MAT3 ) locationSize = 3;
  11000. if ( info.type === gl.FLOAT_MAT4 ) locationSize = 4;
  11001. // console.log( 'THREE.WebGLProgram: ACTIVE VERTEX ATTRIBUTE:', name, i );
  11002. attributes[ name ] = {
  11003. type: info.type,
  11004. location: gl.getAttribLocation( program, name ),
  11005. locationSize: locationSize
  11006. };
  11007. }
  11008. return attributes;
  11009. }
  11010. function filterEmptyLine( string ) {
  11011. return string !== '';
  11012. }
  11013. function replaceLightNums( string, parameters ) {
  11014. const numSpotLightCoords = parameters.numSpotLightShadows + parameters.numSpotLightMaps - parameters.numSpotLightShadowsWithMaps;
  11015. return string
  11016. .replace( /NUM_DIR_LIGHTS/g, parameters.numDirLights )
  11017. .replace( /NUM_SPOT_LIGHTS/g, parameters.numSpotLights )
  11018. .replace( /NUM_SPOT_LIGHT_MAPS/g, parameters.numSpotLightMaps )
  11019. .replace( /NUM_SPOT_LIGHT_COORDS/g, numSpotLightCoords )
  11020. .replace( /NUM_RECT_AREA_LIGHTS/g, parameters.numRectAreaLights )
  11021. .replace( /NUM_POINT_LIGHTS/g, parameters.numPointLights )
  11022. .replace( /NUM_HEMI_LIGHTS/g, parameters.numHemiLights )
  11023. .replace( /NUM_DIR_LIGHT_SHADOWS/g, parameters.numDirLightShadows )
  11024. .replace( /NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS/g, parameters.numSpotLightShadowsWithMaps )
  11025. .replace( /NUM_SPOT_LIGHT_SHADOWS/g, parameters.numSpotLightShadows )
  11026. .replace( /NUM_POINT_LIGHT_SHADOWS/g, parameters.numPointLightShadows );
  11027. }
  11028. function replaceClippingPlaneNums( string, parameters ) {
  11029. return string
  11030. .replace( /NUM_CLIPPING_PLANES/g, parameters.numClippingPlanes )
  11031. .replace( /UNION_CLIPPING_PLANES/g, ( parameters.numClippingPlanes - parameters.numClipIntersection ) );
  11032. }
  11033. // Resolve Includes
  11034. const includePattern = /^[ \t]*#include +<([\w\d./]+)>/gm;
  11035. function resolveIncludes( string ) {
  11036. return string.replace( includePattern, includeReplacer );
  11037. }
  11038. function includeReplacer( match, include ) {
  11039. const string = ShaderChunk[ include ];
  11040. if ( string === undefined ) {
  11041. throw new Error( 'Can not resolve #include <' + include + '>' );
  11042. }
  11043. return resolveIncludes( string );
  11044. }
  11045. // Unroll Loops
  11046. const unrollLoopPattern = /#pragma unroll_loop_start\s+for\s*\(\s*int\s+i\s*=\s*(\d+)\s*;\s*i\s*<\s*(\d+)\s*;\s*i\s*\+\+\s*\)\s*{([\s\S]+?)}\s+#pragma unroll_loop_end/g;
  11047. function unrollLoops( string ) {
  11048. return string.replace( unrollLoopPattern, loopReplacer );
  11049. }
  11050. function loopReplacer( match, start, end, snippet ) {
  11051. let string = '';
  11052. for ( let i = parseInt( start ); i < parseInt( end ); i ++ ) {
  11053. string += snippet
  11054. .replace( /\[\s*i\s*\]/g, '[ ' + i + ' ]' )
  11055. .replace( /UNROLLED_LOOP_INDEX/g, i );
  11056. }
  11057. return string;
  11058. }
  11059. //
  11060. function generatePrecision( parameters ) {
  11061. let precisionstring = 'precision ' + parameters.precision + ' float;\nprecision ' + parameters.precision + ' int;';
  11062. if ( parameters.precision === 'highp' ) {
  11063. precisionstring += '\n#define HIGH_PRECISION';
  11064. } else if ( parameters.precision === 'mediump' ) {
  11065. precisionstring += '\n#define MEDIUM_PRECISION';
  11066. } else if ( parameters.precision === 'lowp' ) {
  11067. precisionstring += '\n#define LOW_PRECISION';
  11068. }
  11069. return precisionstring;
  11070. }
  11071. function generateShadowMapTypeDefine( parameters ) {
  11072. let shadowMapTypeDefine = 'SHADOWMAP_TYPE_BASIC';
  11073. if ( parameters.shadowMapType === PCFShadowMap ) {
  11074. shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF';
  11075. } else if ( parameters.shadowMapType === PCFSoftShadowMap ) {
  11076. shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF_SOFT';
  11077. } else if ( parameters.shadowMapType === VSMShadowMap ) {
  11078. shadowMapTypeDefine = 'SHADOWMAP_TYPE_VSM';
  11079. }
  11080. return shadowMapTypeDefine;
  11081. }
  11082. function generateEnvMapTypeDefine( parameters ) {
  11083. let envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
  11084. if ( parameters.envMap ) {
  11085. switch ( parameters.envMapMode ) {
  11086. case CubeReflectionMapping:
  11087. case CubeRefractionMapping:
  11088. envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
  11089. break;
  11090. case CubeUVReflectionMapping:
  11091. envMapTypeDefine = 'ENVMAP_TYPE_CUBE_UV';
  11092. break;
  11093. }
  11094. }
  11095. return envMapTypeDefine;
  11096. }
  11097. function generateEnvMapModeDefine( parameters ) {
  11098. let envMapModeDefine = 'ENVMAP_MODE_REFLECTION';
  11099. if ( parameters.envMap ) {
  11100. switch ( parameters.envMapMode ) {
  11101. case CubeRefractionMapping:
  11102. envMapModeDefine = 'ENVMAP_MODE_REFRACTION';
  11103. break;
  11104. }
  11105. }
  11106. return envMapModeDefine;
  11107. }
  11108. function generateEnvMapBlendingDefine( parameters ) {
  11109. let envMapBlendingDefine = 'ENVMAP_BLENDING_NONE';
  11110. if ( parameters.envMap ) {
  11111. switch ( parameters.combine ) {
  11112. case MultiplyOperation:
  11113. envMapBlendingDefine = 'ENVMAP_BLENDING_MULTIPLY';
  11114. break;
  11115. case MixOperation:
  11116. envMapBlendingDefine = 'ENVMAP_BLENDING_MIX';
  11117. break;
  11118. case AddOperation:
  11119. envMapBlendingDefine = 'ENVMAP_BLENDING_ADD';
  11120. break;
  11121. }
  11122. }
  11123. return envMapBlendingDefine;
  11124. }
  11125. function generateCubeUVSize( parameters ) {
  11126. const imageHeight = parameters.envMapCubeUVHeight;
  11127. if ( imageHeight === null ) return null;
  11128. const maxMip = Math.log2( imageHeight ) - 2;
  11129. const texelHeight = 1.0 / imageHeight;
  11130. const texelWidth = 1.0 / ( 3 * Math.max( Math.pow( 2, maxMip ), 7 * 16 ) );
  11131. return { texelWidth, texelHeight, maxMip };
  11132. }
  11133. function WebGLProgram( renderer, cacheKey, parameters, bindingStates ) {
  11134. // TODO Send this event to Three.js DevTools
  11135. // console.log( 'WebGLProgram', cacheKey );
  11136. const gl = renderer.getContext();
  11137. const defines = parameters.defines;
  11138. let vertexShader = parameters.vertexShader;
  11139. let fragmentShader = parameters.fragmentShader;
  11140. const shadowMapTypeDefine = generateShadowMapTypeDefine( parameters );
  11141. const envMapTypeDefine = generateEnvMapTypeDefine( parameters );
  11142. const envMapModeDefine = generateEnvMapModeDefine( parameters );
  11143. const envMapBlendingDefine = generateEnvMapBlendingDefine( parameters );
  11144. const envMapCubeUVSize = generateCubeUVSize( parameters );
  11145. const customExtensions = parameters.isWebGL2 ? '' : generateExtensions( parameters );
  11146. const customDefines = generateDefines( defines );
  11147. const program = gl.createProgram();
  11148. let prefixVertex, prefixFragment;
  11149. let versionString = parameters.glslVersion ? '#version ' + parameters.glslVersion + '\n' : '';
  11150. if ( parameters.isRawShaderMaterial ) {
  11151. prefixVertex = [
  11152. customDefines
  11153. ].filter( filterEmptyLine ).join( '\n' );
  11154. if ( prefixVertex.length > 0 ) {
  11155. prefixVertex += '\n';
  11156. }
  11157. prefixFragment = [
  11158. customExtensions,
  11159. customDefines
  11160. ].filter( filterEmptyLine ).join( '\n' );
  11161. if ( prefixFragment.length > 0 ) {
  11162. prefixFragment += '\n';
  11163. }
  11164. } else {
  11165. prefixVertex = [
  11166. generatePrecision( parameters ),
  11167. '#define SHADER_NAME ' + parameters.shaderName,
  11168. customDefines,
  11169. parameters.instancing ? '#define USE_INSTANCING' : '',
  11170. parameters.instancingColor ? '#define USE_INSTANCING_COLOR' : '',
  11171. parameters.supportsVertexTextures ? '#define VERTEX_TEXTURES' : '',
  11172. ( parameters.useFog && parameters.fog ) ? '#define USE_FOG' : '',
  11173. ( parameters.useFog && parameters.fogExp2 ) ? '#define FOG_EXP2' : '',
  11174. parameters.map ? '#define USE_MAP' : '',
  11175. parameters.envMap ? '#define USE_ENVMAP' : '',
  11176. parameters.envMap ? '#define ' + envMapModeDefine : '',
  11177. parameters.lightMap ? '#define USE_LIGHTMAP' : '',
  11178. parameters.aoMap ? '#define USE_AOMAP' : '',
  11179. parameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '',
  11180. parameters.bumpMap ? '#define USE_BUMPMAP' : '',
  11181. parameters.normalMap ? '#define USE_NORMALMAP' : '',
  11182. ( parameters.normalMap && parameters.objectSpaceNormalMap ) ? '#define OBJECTSPACE_NORMALMAP' : '',
  11183. ( parameters.normalMap && parameters.tangentSpaceNormalMap ) ? '#define TANGENTSPACE_NORMALMAP' : '',
  11184. parameters.clearcoatMap ? '#define USE_CLEARCOATMAP' : '',
  11185. parameters.clearcoatRoughnessMap ? '#define USE_CLEARCOAT_ROUGHNESSMAP' : '',
  11186. parameters.clearcoatNormalMap ? '#define USE_CLEARCOAT_NORMALMAP' : '',
  11187. parameters.iridescenceMap ? '#define USE_IRIDESCENCEMAP' : '',
  11188. parameters.iridescenceThicknessMap ? '#define USE_IRIDESCENCE_THICKNESSMAP' : '',
  11189. parameters.displacementMap && parameters.supportsVertexTextures ? '#define USE_DISPLACEMENTMAP' : '',
  11190. parameters.specularMap ? '#define USE_SPECULARMAP' : '',
  11191. parameters.specularIntensityMap ? '#define USE_SPECULARINTENSITYMAP' : '',
  11192. parameters.specularColorMap ? '#define USE_SPECULARCOLORMAP' : '',
  11193. parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '',
  11194. parameters.metalnessMap ? '#define USE_METALNESSMAP' : '',
  11195. parameters.alphaMap ? '#define USE_ALPHAMAP' : '',
  11196. parameters.transmission ? '#define USE_TRANSMISSION' : '',
  11197. parameters.transmissionMap ? '#define USE_TRANSMISSIONMAP' : '',
  11198. parameters.thicknessMap ? '#define USE_THICKNESSMAP' : '',
  11199. parameters.sheenColorMap ? '#define USE_SHEENCOLORMAP' : '',
  11200. parameters.sheenRoughnessMap ? '#define USE_SHEENROUGHNESSMAP' : '',
  11201. parameters.vertexTangents ? '#define USE_TANGENT' : '',
  11202. parameters.vertexColors ? '#define USE_COLOR' : '',
  11203. parameters.vertexAlphas ? '#define USE_COLOR_ALPHA' : '',
  11204. parameters.vertexUvs ? '#define USE_UV' : '',
  11205. parameters.uvsVertexOnly ? '#define UVS_VERTEX_ONLY' : '',
  11206. parameters.flatShading ? '#define FLAT_SHADED' : '',
  11207. parameters.skinning ? '#define USE_SKINNING' : '',
  11208. parameters.morphTargets ? '#define USE_MORPHTARGETS' : '',
  11209. parameters.morphNormals && parameters.flatShading === false ? '#define USE_MORPHNORMALS' : '',
  11210. ( parameters.morphColors && parameters.isWebGL2 ) ? '#define USE_MORPHCOLORS' : '',
  11211. ( parameters.morphTargetsCount > 0 && parameters.isWebGL2 ) ? '#define MORPHTARGETS_TEXTURE' : '',
  11212. ( parameters.morphTargetsCount > 0 && parameters.isWebGL2 ) ? '#define MORPHTARGETS_TEXTURE_STRIDE ' + parameters.morphTextureStride : '',
  11213. ( parameters.morphTargetsCount > 0 && parameters.isWebGL2 ) ? '#define MORPHTARGETS_COUNT ' + parameters.morphTargetsCount : '',
  11214. parameters.doubleSided ? '#define DOUBLE_SIDED' : '',
  11215. parameters.flipSided ? '#define FLIP_SIDED' : '',
  11216. parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '',
  11217. parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '',
  11218. parameters.sizeAttenuation ? '#define USE_SIZEATTENUATION' : '',
  11219. parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '',
  11220. ( parameters.logarithmicDepthBuffer && parameters.rendererExtensionFragDepth ) ? '#define USE_LOGDEPTHBUF_EXT' : '',
  11221. 'uniform mat4 modelMatrix;',
  11222. 'uniform mat4 modelViewMatrix;',
  11223. 'uniform mat4 projectionMatrix;',
  11224. 'uniform mat4 viewMatrix;',
  11225. 'uniform mat3 normalMatrix;',
  11226. 'uniform vec3 cameraPosition;',
  11227. 'uniform bool isOrthographic;',
  11228. '#ifdef USE_INSTANCING',
  11229. ' attribute mat4 instanceMatrix;',
  11230. '#endif',
  11231. '#ifdef USE_INSTANCING_COLOR',
  11232. ' attribute vec3 instanceColor;',
  11233. '#endif',
  11234. 'attribute vec3 position;',
  11235. 'attribute vec3 normal;',
  11236. 'attribute vec2 uv;',
  11237. '#ifdef USE_TANGENT',
  11238. ' attribute vec4 tangent;',
  11239. '#endif',
  11240. '#if defined( USE_COLOR_ALPHA )',
  11241. ' attribute vec4 color;',
  11242. '#elif defined( USE_COLOR )',
  11243. ' attribute vec3 color;',
  11244. '#endif',
  11245. '#if ( defined( USE_MORPHTARGETS ) && ! defined( MORPHTARGETS_TEXTURE ) )',
  11246. ' attribute vec3 morphTarget0;',
  11247. ' attribute vec3 morphTarget1;',
  11248. ' attribute vec3 morphTarget2;',
  11249. ' attribute vec3 morphTarget3;',
  11250. ' #ifdef USE_MORPHNORMALS',
  11251. ' attribute vec3 morphNormal0;',
  11252. ' attribute vec3 morphNormal1;',
  11253. ' attribute vec3 morphNormal2;',
  11254. ' attribute vec3 morphNormal3;',
  11255. ' #else',
  11256. ' attribute vec3 morphTarget4;',
  11257. ' attribute vec3 morphTarget5;',
  11258. ' attribute vec3 morphTarget6;',
  11259. ' attribute vec3 morphTarget7;',
  11260. ' #endif',
  11261. '#endif',
  11262. '#ifdef USE_SKINNING',
  11263. ' attribute vec4 skinIndex;',
  11264. ' attribute vec4 skinWeight;',
  11265. '#endif',
  11266. '\n'
  11267. ].filter( filterEmptyLine ).join( '\n' );
  11268. prefixFragment = [
  11269. customExtensions,
  11270. generatePrecision( parameters ),
  11271. '#define SHADER_NAME ' + parameters.shaderName,
  11272. customDefines,
  11273. ( parameters.useFog && parameters.fog ) ? '#define USE_FOG' : '',
  11274. ( parameters.useFog && parameters.fogExp2 ) ? '#define FOG_EXP2' : '',
  11275. parameters.map ? '#define USE_MAP' : '',
  11276. parameters.matcap ? '#define USE_MATCAP' : '',
  11277. parameters.envMap ? '#define USE_ENVMAP' : '',
  11278. parameters.envMap ? '#define ' + envMapTypeDefine : '',
  11279. parameters.envMap ? '#define ' + envMapModeDefine : '',
  11280. parameters.envMap ? '#define ' + envMapBlendingDefine : '',
  11281. envMapCubeUVSize ? '#define CUBEUV_TEXEL_WIDTH ' + envMapCubeUVSize.texelWidth : '',
  11282. envMapCubeUVSize ? '#define CUBEUV_TEXEL_HEIGHT ' + envMapCubeUVSize.texelHeight : '',
  11283. envMapCubeUVSize ? '#define CUBEUV_MAX_MIP ' + envMapCubeUVSize.maxMip + '.0' : '',
  11284. parameters.lightMap ? '#define USE_LIGHTMAP' : '',
  11285. parameters.aoMap ? '#define USE_AOMAP' : '',
  11286. parameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '',
  11287. parameters.bumpMap ? '#define USE_BUMPMAP' : '',
  11288. parameters.normalMap ? '#define USE_NORMALMAP' : '',
  11289. ( parameters.normalMap && parameters.objectSpaceNormalMap ) ? '#define OBJECTSPACE_NORMALMAP' : '',
  11290. ( parameters.normalMap && parameters.tangentSpaceNormalMap ) ? '#define TANGENTSPACE_NORMALMAP' : '',
  11291. parameters.clearcoat ? '#define USE_CLEARCOAT' : '',
  11292. parameters.clearcoatMap ? '#define USE_CLEARCOATMAP' : '',
  11293. parameters.clearcoatRoughnessMap ? '#define USE_CLEARCOAT_ROUGHNESSMAP' : '',
  11294. parameters.clearcoatNormalMap ? '#define USE_CLEARCOAT_NORMALMAP' : '',
  11295. parameters.iridescence ? '#define USE_IRIDESCENCE' : '',
  11296. parameters.iridescenceMap ? '#define USE_IRIDESCENCEMAP' : '',
  11297. parameters.iridescenceThicknessMap ? '#define USE_IRIDESCENCE_THICKNESSMAP' : '',
  11298. parameters.specularMap ? '#define USE_SPECULARMAP' : '',
  11299. parameters.specularIntensityMap ? '#define USE_SPECULARINTENSITYMAP' : '',
  11300. parameters.specularColorMap ? '#define USE_SPECULARCOLORMAP' : '',
  11301. parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '',
  11302. parameters.metalnessMap ? '#define USE_METALNESSMAP' : '',
  11303. parameters.alphaMap ? '#define USE_ALPHAMAP' : '',
  11304. parameters.alphaTest ? '#define USE_ALPHATEST' : '',
  11305. parameters.sheen ? '#define USE_SHEEN' : '',
  11306. parameters.sheenColorMap ? '#define USE_SHEENCOLORMAP' : '',
  11307. parameters.sheenRoughnessMap ? '#define USE_SHEENROUGHNESSMAP' : '',
  11308. parameters.transmission ? '#define USE_TRANSMISSION' : '',
  11309. parameters.transmissionMap ? '#define USE_TRANSMISSIONMAP' : '',
  11310. parameters.thicknessMap ? '#define USE_THICKNESSMAP' : '',
  11311. parameters.decodeVideoTexture ? '#define DECODE_VIDEO_TEXTURE' : '',
  11312. parameters.vertexTangents ? '#define USE_TANGENT' : '',
  11313. parameters.vertexColors || parameters.instancingColor ? '#define USE_COLOR' : '',
  11314. parameters.vertexAlphas ? '#define USE_COLOR_ALPHA' : '',
  11315. parameters.vertexUvs ? '#define USE_UV' : '',
  11316. parameters.uvsVertexOnly ? '#define UVS_VERTEX_ONLY' : '',
  11317. parameters.gradientMap ? '#define USE_GRADIENTMAP' : '',
  11318. parameters.flatShading ? '#define FLAT_SHADED' : '',
  11319. parameters.doubleSided ? '#define DOUBLE_SIDED' : '',
  11320. parameters.flipSided ? '#define FLIP_SIDED' : '',
  11321. parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '',
  11322. parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '',
  11323. parameters.premultipliedAlpha ? '#define PREMULTIPLIED_ALPHA' : '',
  11324. parameters.physicallyCorrectLights ? '#define PHYSICALLY_CORRECT_LIGHTS' : '',
  11325. parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '',
  11326. ( parameters.logarithmicDepthBuffer && parameters.rendererExtensionFragDepth ) ? '#define USE_LOGDEPTHBUF_EXT' : '',
  11327. 'uniform mat4 viewMatrix;',
  11328. 'uniform vec3 cameraPosition;',
  11329. 'uniform bool isOrthographic;',
  11330. ( parameters.toneMapping !== NoToneMapping ) ? '#define TONE_MAPPING' : '',
  11331. ( parameters.toneMapping !== NoToneMapping ) ? ShaderChunk[ 'tonemapping_pars_fragment' ] : '', // this code is required here because it is used by the toneMapping() function defined below
  11332. ( parameters.toneMapping !== NoToneMapping ) ? getToneMappingFunction( 'toneMapping', parameters.toneMapping ) : '',
  11333. parameters.dithering ? '#define DITHERING' : '',
  11334. parameters.opaque ? '#define OPAQUE' : '',
  11335. ShaderChunk[ 'encodings_pars_fragment' ], // this code is required here because it is used by the various encoding/decoding function defined below
  11336. getTexelEncodingFunction( 'linearToOutputTexel', parameters.outputEncoding ),
  11337. parameters.useDepthPacking ? '#define DEPTH_PACKING ' + parameters.depthPacking : '',
  11338. '\n'
  11339. ].filter( filterEmptyLine ).join( '\n' );
  11340. }
  11341. vertexShader = resolveIncludes( vertexShader );
  11342. vertexShader = replaceLightNums( vertexShader, parameters );
  11343. vertexShader = replaceClippingPlaneNums( vertexShader, parameters );
  11344. fragmentShader = resolveIncludes( fragmentShader );
  11345. fragmentShader = replaceLightNums( fragmentShader, parameters );
  11346. fragmentShader = replaceClippingPlaneNums( fragmentShader, parameters );
  11347. vertexShader = unrollLoops( vertexShader );
  11348. fragmentShader = unrollLoops( fragmentShader );
  11349. if ( parameters.isWebGL2 && parameters.isRawShaderMaterial !== true ) {
  11350. // GLSL 3.0 conversion for built-in materials and ShaderMaterial
  11351. versionString = '#version 300 es\n';
  11352. prefixVertex = [
  11353. 'precision mediump sampler2DArray;',
  11354. '#define attribute in',
  11355. '#define varying out',
  11356. '#define texture2D texture'
  11357. ].join( '\n' ) + '\n' + prefixVertex;
  11358. prefixFragment = [
  11359. '#define varying in',
  11360. ( parameters.glslVersion === GLSL3 ) ? '' : 'layout(location = 0) out highp vec4 pc_fragColor;',
  11361. ( parameters.glslVersion === GLSL3 ) ? '' : '#define gl_FragColor pc_fragColor',
  11362. '#define gl_FragDepthEXT gl_FragDepth',
  11363. '#define texture2D texture',
  11364. '#define textureCube texture',
  11365. '#define texture2DProj textureProj',
  11366. '#define texture2DLodEXT textureLod',
  11367. '#define texture2DProjLodEXT textureProjLod',
  11368. '#define textureCubeLodEXT textureLod',
  11369. '#define texture2DGradEXT textureGrad',
  11370. '#define texture2DProjGradEXT textureProjGrad',
  11371. '#define textureCubeGradEXT textureGrad'
  11372. ].join( '\n' ) + '\n' + prefixFragment;
  11373. }
  11374. const vertexGlsl = versionString + prefixVertex + vertexShader;
  11375. const fragmentGlsl = versionString + prefixFragment + fragmentShader;
  11376. // console.log( '*VERTEX*', vertexGlsl );
  11377. // console.log( '*FRAGMENT*', fragmentGlsl );
  11378. const glVertexShader = WebGLShader( gl, gl.VERTEX_SHADER, vertexGlsl );
  11379. const glFragmentShader = WebGLShader( gl, gl.FRAGMENT_SHADER, fragmentGlsl );
  11380. gl.attachShader( program, glVertexShader );
  11381. gl.attachShader( program, glFragmentShader );
  11382. // Force a particular attribute to index 0.
  11383. if ( parameters.index0AttributeName !== undefined ) {
  11384. gl.bindAttribLocation( program, 0, parameters.index0AttributeName );
  11385. } else if ( parameters.morphTargets === true ) {
  11386. // programs with morphTargets displace position out of attribute 0
  11387. gl.bindAttribLocation( program, 0, 'position' );
  11388. }
  11389. gl.linkProgram( program );
  11390. // check for link errors
  11391. if ( renderer.debug.checkShaderErrors ) {
  11392. const programLog = gl.getProgramInfoLog( program ).trim();
  11393. const vertexLog = gl.getShaderInfoLog( glVertexShader ).trim();
  11394. const fragmentLog = gl.getShaderInfoLog( glFragmentShader ).trim();
  11395. let runnable = true;
  11396. let haveDiagnostics = true;
  11397. if ( gl.getProgramParameter( program, gl.LINK_STATUS ) === false ) {
  11398. runnable = false;
  11399. const vertexErrors = getShaderErrors( gl, glVertexShader, 'vertex' );
  11400. const fragmentErrors = getShaderErrors( gl, glFragmentShader, 'fragment' );
  11401. console.error(
  11402. 'THREE.WebGLProgram: Shader Error ' + gl.getError() + ' - ' +
  11403. 'VALIDATE_STATUS ' + gl.getProgramParameter( program, gl.VALIDATE_STATUS ) + '\n\n' +
  11404. 'Program Info Log: ' + programLog + '\n' +
  11405. vertexErrors + '\n' +
  11406. fragmentErrors
  11407. );
  11408. } else if ( programLog !== '' ) {
  11409. console.warn( 'THREE.WebGLProgram: Program Info Log:', programLog );
  11410. } else if ( vertexLog === '' || fragmentLog === '' ) {
  11411. haveDiagnostics = false;
  11412. }
  11413. if ( haveDiagnostics ) {
  11414. this.diagnostics = {
  11415. runnable: runnable,
  11416. programLog: programLog,
  11417. vertexShader: {
  11418. log: vertexLog,
  11419. prefix: prefixVertex
  11420. },
  11421. fragmentShader: {
  11422. log: fragmentLog,
  11423. prefix: prefixFragment
  11424. }
  11425. };
  11426. }
  11427. }
  11428. // Clean up
  11429. // Crashes in iOS9 and iOS10. #18402
  11430. // gl.detachShader( program, glVertexShader );
  11431. // gl.detachShader( program, glFragmentShader );
  11432. gl.deleteShader( glVertexShader );
  11433. gl.deleteShader( glFragmentShader );
  11434. // set up caching for uniform locations
  11435. let cachedUniforms;
  11436. this.getUniforms = function () {
  11437. if ( cachedUniforms === undefined ) {
  11438. cachedUniforms = new WebGLUniforms( gl, program );
  11439. }
  11440. return cachedUniforms;
  11441. };
  11442. // set up caching for attribute locations
  11443. let cachedAttributes;
  11444. this.getAttributes = function () {
  11445. if ( cachedAttributes === undefined ) {
  11446. cachedAttributes = fetchAttributeLocations( gl, program );
  11447. }
  11448. return cachedAttributes;
  11449. };
  11450. // free resource
  11451. this.destroy = function () {
  11452. bindingStates.releaseStatesOfProgram( this );
  11453. gl.deleteProgram( program );
  11454. this.program = undefined;
  11455. };
  11456. //
  11457. this.name = parameters.shaderName;
  11458. this.id = programIdCount ++;
  11459. this.cacheKey = cacheKey;
  11460. this.usedTimes = 1;
  11461. this.program = program;
  11462. this.vertexShader = glVertexShader;
  11463. this.fragmentShader = glFragmentShader;
  11464. return this;
  11465. }
  11466. let _id = 0;
  11467. class WebGLShaderCache {
  11468. constructor() {
  11469. this.shaderCache = new Map();
  11470. this.materialCache = new Map();
  11471. }
  11472. update( material ) {
  11473. const vertexShader = material.vertexShader;
  11474. const fragmentShader = material.fragmentShader;
  11475. const vertexShaderStage = this._getShaderStage( vertexShader );
  11476. const fragmentShaderStage = this._getShaderStage( fragmentShader );
  11477. const materialShaders = this._getShaderCacheForMaterial( material );
  11478. if ( materialShaders.has( vertexShaderStage ) === false ) {
  11479. materialShaders.add( vertexShaderStage );
  11480. vertexShaderStage.usedTimes ++;
  11481. }
  11482. if ( materialShaders.has( fragmentShaderStage ) === false ) {
  11483. materialShaders.add( fragmentShaderStage );
  11484. fragmentShaderStage.usedTimes ++;
  11485. }
  11486. return this;
  11487. }
  11488. remove( material ) {
  11489. const materialShaders = this.materialCache.get( material );
  11490. for ( const shaderStage of materialShaders ) {
  11491. shaderStage.usedTimes --;
  11492. if ( shaderStage.usedTimes === 0 ) this.shaderCache.delete( shaderStage.code );
  11493. }
  11494. this.materialCache.delete( material );
  11495. return this;
  11496. }
  11497. getVertexShaderID( material ) {
  11498. return this._getShaderStage( material.vertexShader ).id;
  11499. }
  11500. getFragmentShaderID( material ) {
  11501. return this._getShaderStage( material.fragmentShader ).id;
  11502. }
  11503. dispose() {
  11504. this.shaderCache.clear();
  11505. this.materialCache.clear();
  11506. }
  11507. _getShaderCacheForMaterial( material ) {
  11508. const cache = this.materialCache;
  11509. let set = cache.get( material );
  11510. if ( set === undefined ) {
  11511. set = new Set();
  11512. cache.set( material, set );
  11513. }
  11514. return set;
  11515. }
  11516. _getShaderStage( code ) {
  11517. const cache = this.shaderCache;
  11518. let stage = cache.get( code );
  11519. if ( stage === undefined ) {
  11520. stage = new WebGLShaderStage( code );
  11521. cache.set( code, stage );
  11522. }
  11523. return stage;
  11524. }
  11525. }
  11526. class WebGLShaderStage {
  11527. constructor( code ) {
  11528. this.id = _id ++;
  11529. this.code = code;
  11530. this.usedTimes = 0;
  11531. }
  11532. }
  11533. function WebGLPrograms( renderer, cubemaps, cubeuvmaps, extensions, capabilities, bindingStates, clipping ) {
  11534. const _programLayers = new Layers();
  11535. const _customShaders = new WebGLShaderCache();
  11536. const programs = [];
  11537. const isWebGL2 = capabilities.isWebGL2;
  11538. const logarithmicDepthBuffer = capabilities.logarithmicDepthBuffer;
  11539. const vertexTextures = capabilities.vertexTextures;
  11540. let precision = capabilities.precision;
  11541. const shaderIDs = {
  11542. MeshDepthMaterial: 'depth',
  11543. MeshDistanceMaterial: 'distanceRGBA',
  11544. MeshNormalMaterial: 'normal',
  11545. MeshBasicMaterial: 'basic',
  11546. MeshLambertMaterial: 'lambert',
  11547. MeshPhongMaterial: 'phong',
  11548. MeshToonMaterial: 'toon',
  11549. MeshStandardMaterial: 'physical',
  11550. MeshPhysicalMaterial: 'physical',
  11551. MeshMatcapMaterial: 'matcap',
  11552. LineBasicMaterial: 'basic',
  11553. LineDashedMaterial: 'dashed',
  11554. PointsMaterial: 'points',
  11555. ShadowMaterial: 'shadow',
  11556. SpriteMaterial: 'sprite'
  11557. };
  11558. function getParameters( material, lights, shadows, scene, object ) {
  11559. const fog = scene.fog;
  11560. const geometry = object.geometry;
  11561. const environment = material.isMeshStandardMaterial ? scene.environment : null;
  11562. const envMap = ( material.isMeshStandardMaterial ? cubeuvmaps : cubemaps ).get( material.envMap || environment );
  11563. const envMapCubeUVHeight = ( !! envMap ) && ( envMap.mapping === CubeUVReflectionMapping ) ? envMap.image.height : null;
  11564. const shaderID = shaderIDs[ material.type ];
  11565. // heuristics to create shader parameters according to lights in the scene
  11566. // (not to blow over maxLights budget)
  11567. if ( material.precision !== null ) {
  11568. precision = capabilities.getMaxPrecision( material.precision );
  11569. if ( precision !== material.precision ) {
  11570. console.warn( 'THREE.WebGLProgram.getParameters:', material.precision, 'not supported, using', precision, 'instead.' );
  11571. }
  11572. }
  11573. //
  11574. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  11575. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  11576. let morphTextureStride = 0;
  11577. if ( geometry.morphAttributes.position !== undefined ) morphTextureStride = 1;
  11578. if ( geometry.morphAttributes.normal !== undefined ) morphTextureStride = 2;
  11579. if ( geometry.morphAttributes.color !== undefined ) morphTextureStride = 3;
  11580. //
  11581. let vertexShader, fragmentShader;
  11582. let customVertexShaderID, customFragmentShaderID;
  11583. if ( shaderID ) {
  11584. const shader = ShaderLib[ shaderID ];
  11585. vertexShader = shader.vertexShader;
  11586. fragmentShader = shader.fragmentShader;
  11587. } else {
  11588. vertexShader = material.vertexShader;
  11589. fragmentShader = material.fragmentShader;
  11590. _customShaders.update( material );
  11591. customVertexShaderID = _customShaders.getVertexShaderID( material );
  11592. customFragmentShaderID = _customShaders.getFragmentShaderID( material );
  11593. }
  11594. const currentRenderTarget = renderer.getRenderTarget();
  11595. const useAlphaTest = material.alphaTest > 0;
  11596. const useClearcoat = material.clearcoat > 0;
  11597. const useIridescence = material.iridescence > 0;
  11598. const parameters = {
  11599. isWebGL2: isWebGL2,
  11600. shaderID: shaderID,
  11601. shaderName: material.type,
  11602. vertexShader: vertexShader,
  11603. fragmentShader: fragmentShader,
  11604. defines: material.defines,
  11605. customVertexShaderID: customVertexShaderID,
  11606. customFragmentShaderID: customFragmentShaderID,
  11607. isRawShaderMaterial: material.isRawShaderMaterial === true,
  11608. glslVersion: material.glslVersion,
  11609. precision: precision,
  11610. instancing: object.isInstancedMesh === true,
  11611. instancingColor: object.isInstancedMesh === true && object.instanceColor !== null,
  11612. supportsVertexTextures: vertexTextures,
  11613. outputEncoding: ( currentRenderTarget === null ) ? renderer.outputEncoding : ( currentRenderTarget.isXRRenderTarget === true ? currentRenderTarget.texture.encoding : LinearEncoding ),
  11614. map: !! material.map,
  11615. matcap: !! material.matcap,
  11616. envMap: !! envMap,
  11617. envMapMode: envMap && envMap.mapping,
  11618. envMapCubeUVHeight: envMapCubeUVHeight,
  11619. lightMap: !! material.lightMap,
  11620. aoMap: !! material.aoMap,
  11621. emissiveMap: !! material.emissiveMap,
  11622. bumpMap: !! material.bumpMap,
  11623. normalMap: !! material.normalMap,
  11624. objectSpaceNormalMap: material.normalMapType === ObjectSpaceNormalMap,
  11625. tangentSpaceNormalMap: material.normalMapType === TangentSpaceNormalMap,
  11626. decodeVideoTexture: !! material.map && ( material.map.isVideoTexture === true ) && ( material.map.encoding === sRGBEncoding ),
  11627. clearcoat: useClearcoat,
  11628. clearcoatMap: useClearcoat && !! material.clearcoatMap,
  11629. clearcoatRoughnessMap: useClearcoat && !! material.clearcoatRoughnessMap,
  11630. clearcoatNormalMap: useClearcoat && !! material.clearcoatNormalMap,
  11631. iridescence: useIridescence,
  11632. iridescenceMap: useIridescence && !! material.iridescenceMap,
  11633. iridescenceThicknessMap: useIridescence && !! material.iridescenceThicknessMap,
  11634. displacementMap: !! material.displacementMap,
  11635. roughnessMap: !! material.roughnessMap,
  11636. metalnessMap: !! material.metalnessMap,
  11637. specularMap: !! material.specularMap,
  11638. specularIntensityMap: !! material.specularIntensityMap,
  11639. specularColorMap: !! material.specularColorMap,
  11640. opaque: material.transparent === false && material.blending === NormalBlending,
  11641. alphaMap: !! material.alphaMap,
  11642. alphaTest: useAlphaTest,
  11643. gradientMap: !! material.gradientMap,
  11644. sheen: material.sheen > 0,
  11645. sheenColorMap: !! material.sheenColorMap,
  11646. sheenRoughnessMap: !! material.sheenRoughnessMap,
  11647. transmission: material.transmission > 0,
  11648. transmissionMap: !! material.transmissionMap,
  11649. thicknessMap: !! material.thicknessMap,
  11650. combine: material.combine,
  11651. vertexTangents: ( !! material.normalMap && !! geometry.attributes.tangent ),
  11652. vertexColors: material.vertexColors,
  11653. vertexAlphas: material.vertexColors === true && !! geometry.attributes.color && geometry.attributes.color.itemSize === 4,
  11654. vertexUvs: !! material.map || !! material.bumpMap || !! material.normalMap || !! material.specularMap || !! material.alphaMap || !! material.emissiveMap || !! material.roughnessMap || !! material.metalnessMap || !! material.clearcoatMap || !! material.clearcoatRoughnessMap || !! material.clearcoatNormalMap || !! material.iridescenceMap || !! material.iridescenceThicknessMap || !! material.displacementMap || !! material.transmissionMap || !! material.thicknessMap || !! material.specularIntensityMap || !! material.specularColorMap || !! material.sheenColorMap || !! material.sheenRoughnessMap,
  11655. uvsVertexOnly: ! ( !! material.map || !! material.bumpMap || !! material.normalMap || !! material.specularMap || !! material.alphaMap || !! material.emissiveMap || !! material.roughnessMap || !! material.metalnessMap || !! material.clearcoatNormalMap || !! material.iridescenceMap || !! material.iridescenceThicknessMap || material.transmission > 0 || !! material.transmissionMap || !! material.thicknessMap || !! material.specularIntensityMap || !! material.specularColorMap || material.sheen > 0 || !! material.sheenColorMap || !! material.sheenRoughnessMap ) && !! material.displacementMap,
  11656. fog: !! fog,
  11657. useFog: material.fog === true,
  11658. fogExp2: ( fog && fog.isFogExp2 ),
  11659. flatShading: !! material.flatShading,
  11660. sizeAttenuation: material.sizeAttenuation,
  11661. logarithmicDepthBuffer: logarithmicDepthBuffer,
  11662. skinning: object.isSkinnedMesh === true,
  11663. morphTargets: geometry.morphAttributes.position !== undefined,
  11664. morphNormals: geometry.morphAttributes.normal !== undefined,
  11665. morphColors: geometry.morphAttributes.color !== undefined,
  11666. morphTargetsCount: morphTargetsCount,
  11667. morphTextureStride: morphTextureStride,
  11668. numDirLights: lights.directional.length,
  11669. numPointLights: lights.point.length,
  11670. numSpotLights: lights.spot.length,
  11671. numSpotLightMaps: lights.spotLightMap.length,
  11672. numRectAreaLights: lights.rectArea.length,
  11673. numHemiLights: lights.hemi.length,
  11674. numDirLightShadows: lights.directionalShadowMap.length,
  11675. numPointLightShadows: lights.pointShadowMap.length,
  11676. numSpotLightShadows: lights.spotShadowMap.length,
  11677. numSpotLightShadowsWithMaps: lights.numSpotLightShadowsWithMaps,
  11678. numClippingPlanes: clipping.numPlanes,
  11679. numClipIntersection: clipping.numIntersection,
  11680. dithering: material.dithering,
  11681. shadowMapEnabled: renderer.shadowMap.enabled && shadows.length > 0,
  11682. shadowMapType: renderer.shadowMap.type,
  11683. toneMapping: material.toneMapped ? renderer.toneMapping : NoToneMapping,
  11684. physicallyCorrectLights: renderer.physicallyCorrectLights,
  11685. premultipliedAlpha: material.premultipliedAlpha,
  11686. doubleSided: material.side === DoubleSide,
  11687. flipSided: material.side === BackSide,
  11688. useDepthPacking: !! material.depthPacking,
  11689. depthPacking: material.depthPacking || 0,
  11690. index0AttributeName: material.index0AttributeName,
  11691. extensionDerivatives: material.extensions && material.extensions.derivatives,
  11692. extensionFragDepth: material.extensions && material.extensions.fragDepth,
  11693. extensionDrawBuffers: material.extensions && material.extensions.drawBuffers,
  11694. extensionShaderTextureLOD: material.extensions && material.extensions.shaderTextureLOD,
  11695. rendererExtensionFragDepth: isWebGL2 || extensions.has( 'EXT_frag_depth' ),
  11696. rendererExtensionDrawBuffers: isWebGL2 || extensions.has( 'WEBGL_draw_buffers' ),
  11697. rendererExtensionShaderTextureLod: isWebGL2 || extensions.has( 'EXT_shader_texture_lod' ),
  11698. customProgramCacheKey: material.customProgramCacheKey()
  11699. };
  11700. return parameters;
  11701. }
  11702. function getProgramCacheKey( parameters ) {
  11703. const array = [];
  11704. if ( parameters.shaderID ) {
  11705. array.push( parameters.shaderID );
  11706. } else {
  11707. array.push( parameters.customVertexShaderID );
  11708. array.push( parameters.customFragmentShaderID );
  11709. }
  11710. if ( parameters.defines !== undefined ) {
  11711. for ( const name in parameters.defines ) {
  11712. array.push( name );
  11713. array.push( parameters.defines[ name ] );
  11714. }
  11715. }
  11716. if ( parameters.isRawShaderMaterial === false ) {
  11717. getProgramCacheKeyParameters( array, parameters );
  11718. getProgramCacheKeyBooleans( array, parameters );
  11719. array.push( renderer.outputEncoding );
  11720. }
  11721. array.push( parameters.customProgramCacheKey );
  11722. return array.join();
  11723. }
  11724. function getProgramCacheKeyParameters( array, parameters ) {
  11725. array.push( parameters.precision );
  11726. array.push( parameters.outputEncoding );
  11727. array.push( parameters.envMapMode );
  11728. array.push( parameters.envMapCubeUVHeight );
  11729. array.push( parameters.combine );
  11730. array.push( parameters.vertexUvs );
  11731. array.push( parameters.fogExp2 );
  11732. array.push( parameters.sizeAttenuation );
  11733. array.push( parameters.morphTargetsCount );
  11734. array.push( parameters.morphAttributeCount );
  11735. array.push( parameters.numDirLights );
  11736. array.push( parameters.numPointLights );
  11737. array.push( parameters.numSpotLights );
  11738. array.push( parameters.numSpotLightMaps );
  11739. array.push( parameters.numHemiLights );
  11740. array.push( parameters.numRectAreaLights );
  11741. array.push( parameters.numDirLightShadows );
  11742. array.push( parameters.numPointLightShadows );
  11743. array.push( parameters.numSpotLightShadows );
  11744. array.push( parameters.numSpotLightShadowsWithMaps );
  11745. array.push( parameters.shadowMapType );
  11746. array.push( parameters.toneMapping );
  11747. array.push( parameters.numClippingPlanes );
  11748. array.push( parameters.numClipIntersection );
  11749. array.push( parameters.depthPacking );
  11750. }
  11751. function getProgramCacheKeyBooleans( array, parameters ) {
  11752. _programLayers.disableAll();
  11753. if ( parameters.isWebGL2 )
  11754. _programLayers.enable( 0 );
  11755. if ( parameters.supportsVertexTextures )
  11756. _programLayers.enable( 1 );
  11757. if ( parameters.instancing )
  11758. _programLayers.enable( 2 );
  11759. if ( parameters.instancingColor )
  11760. _programLayers.enable( 3 );
  11761. if ( parameters.map )
  11762. _programLayers.enable( 4 );
  11763. if ( parameters.matcap )
  11764. _programLayers.enable( 5 );
  11765. if ( parameters.envMap )
  11766. _programLayers.enable( 6 );
  11767. if ( parameters.lightMap )
  11768. _programLayers.enable( 7 );
  11769. if ( parameters.aoMap )
  11770. _programLayers.enable( 8 );
  11771. if ( parameters.emissiveMap )
  11772. _programLayers.enable( 9 );
  11773. if ( parameters.bumpMap )
  11774. _programLayers.enable( 10 );
  11775. if ( parameters.normalMap )
  11776. _programLayers.enable( 11 );
  11777. if ( parameters.objectSpaceNormalMap )
  11778. _programLayers.enable( 12 );
  11779. if ( parameters.tangentSpaceNormalMap )
  11780. _programLayers.enable( 13 );
  11781. if ( parameters.clearcoat )
  11782. _programLayers.enable( 14 );
  11783. if ( parameters.clearcoatMap )
  11784. _programLayers.enable( 15 );
  11785. if ( parameters.clearcoatRoughnessMap )
  11786. _programLayers.enable( 16 );
  11787. if ( parameters.clearcoatNormalMap )
  11788. _programLayers.enable( 17 );
  11789. if ( parameters.iridescence )
  11790. _programLayers.enable( 18 );
  11791. if ( parameters.iridescenceMap )
  11792. _programLayers.enable( 19 );
  11793. if ( parameters.iridescenceThicknessMap )
  11794. _programLayers.enable( 20 );
  11795. if ( parameters.displacementMap )
  11796. _programLayers.enable( 21 );
  11797. if ( parameters.specularMap )
  11798. _programLayers.enable( 22 );
  11799. if ( parameters.roughnessMap )
  11800. _programLayers.enable( 23 );
  11801. if ( parameters.metalnessMap )
  11802. _programLayers.enable( 24 );
  11803. if ( parameters.gradientMap )
  11804. _programLayers.enable( 25 );
  11805. if ( parameters.alphaMap )
  11806. _programLayers.enable( 26 );
  11807. if ( parameters.alphaTest )
  11808. _programLayers.enable( 27 );
  11809. if ( parameters.vertexColors )
  11810. _programLayers.enable( 28 );
  11811. if ( parameters.vertexAlphas )
  11812. _programLayers.enable( 29 );
  11813. if ( parameters.vertexUvs )
  11814. _programLayers.enable( 30 );
  11815. if ( parameters.vertexTangents )
  11816. _programLayers.enable( 31 );
  11817. if ( parameters.uvsVertexOnly )
  11818. _programLayers.enable( 32 );
  11819. array.push( _programLayers.mask );
  11820. _programLayers.disableAll();
  11821. if ( parameters.fog )
  11822. _programLayers.enable( 0 );
  11823. if ( parameters.useFog )
  11824. _programLayers.enable( 1 );
  11825. if ( parameters.flatShading )
  11826. _programLayers.enable( 2 );
  11827. if ( parameters.logarithmicDepthBuffer )
  11828. _programLayers.enable( 3 );
  11829. if ( parameters.skinning )
  11830. _programLayers.enable( 4 );
  11831. if ( parameters.morphTargets )
  11832. _programLayers.enable( 5 );
  11833. if ( parameters.morphNormals )
  11834. _programLayers.enable( 6 );
  11835. if ( parameters.morphColors )
  11836. _programLayers.enable( 7 );
  11837. if ( parameters.premultipliedAlpha )
  11838. _programLayers.enable( 8 );
  11839. if ( parameters.shadowMapEnabled )
  11840. _programLayers.enable( 9 );
  11841. if ( parameters.physicallyCorrectLights )
  11842. _programLayers.enable( 10 );
  11843. if ( parameters.doubleSided )
  11844. _programLayers.enable( 11 );
  11845. if ( parameters.flipSided )
  11846. _programLayers.enable( 12 );
  11847. if ( parameters.useDepthPacking )
  11848. _programLayers.enable( 13 );
  11849. if ( parameters.dithering )
  11850. _programLayers.enable( 14 );
  11851. if ( parameters.specularIntensityMap )
  11852. _programLayers.enable( 15 );
  11853. if ( parameters.specularColorMap )
  11854. _programLayers.enable( 16 );
  11855. if ( parameters.transmission )
  11856. _programLayers.enable( 17 );
  11857. if ( parameters.transmissionMap )
  11858. _programLayers.enable( 18 );
  11859. if ( parameters.thicknessMap )
  11860. _programLayers.enable( 19 );
  11861. if ( parameters.sheen )
  11862. _programLayers.enable( 20 );
  11863. if ( parameters.sheenColorMap )
  11864. _programLayers.enable( 21 );
  11865. if ( parameters.sheenRoughnessMap )
  11866. _programLayers.enable( 22 );
  11867. if ( parameters.decodeVideoTexture )
  11868. _programLayers.enable( 23 );
  11869. if ( parameters.opaque )
  11870. _programLayers.enable( 24 );
  11871. array.push( _programLayers.mask );
  11872. }
  11873. function getUniforms( material ) {
  11874. const shaderID = shaderIDs[ material.type ];
  11875. let uniforms;
  11876. if ( shaderID ) {
  11877. const shader = ShaderLib[ shaderID ];
  11878. uniforms = UniformsUtils.clone( shader.uniforms );
  11879. } else {
  11880. uniforms = material.uniforms;
  11881. }
  11882. return uniforms;
  11883. }
  11884. function acquireProgram( parameters, cacheKey ) {
  11885. let program;
  11886. // Check if code has been already compiled
  11887. for ( let p = 0, pl = programs.length; p < pl; p ++ ) {
  11888. const preexistingProgram = programs[ p ];
  11889. if ( preexistingProgram.cacheKey === cacheKey ) {
  11890. program = preexistingProgram;
  11891. ++ program.usedTimes;
  11892. break;
  11893. }
  11894. }
  11895. if ( program === undefined ) {
  11896. program = new WebGLProgram( renderer, cacheKey, parameters, bindingStates );
  11897. programs.push( program );
  11898. }
  11899. return program;
  11900. }
  11901. function releaseProgram( program ) {
  11902. if ( -- program.usedTimes === 0 ) {
  11903. // Remove from unordered set
  11904. const i = programs.indexOf( program );
  11905. programs[ i ] = programs[ programs.length - 1 ];
  11906. programs.pop();
  11907. // Free WebGL resources
  11908. program.destroy();
  11909. }
  11910. }
  11911. function releaseShaderCache( material ) {
  11912. _customShaders.remove( material );
  11913. }
  11914. function dispose() {
  11915. _customShaders.dispose();
  11916. }
  11917. return {
  11918. getParameters: getParameters,
  11919. getProgramCacheKey: getProgramCacheKey,
  11920. getUniforms: getUniforms,
  11921. acquireProgram: acquireProgram,
  11922. releaseProgram: releaseProgram,
  11923. releaseShaderCache: releaseShaderCache,
  11924. // Exposed for resource monitoring & error feedback via renderer.info:
  11925. programs: programs,
  11926. dispose: dispose
  11927. };
  11928. }
  11929. function WebGLProperties() {
  11930. let properties = new WeakMap();
  11931. function get( object ) {
  11932. let map = properties.get( object );
  11933. if ( map === undefined ) {
  11934. map = {};
  11935. properties.set( object, map );
  11936. }
  11937. return map;
  11938. }
  11939. function remove( object ) {
  11940. properties.delete( object );
  11941. }
  11942. function update( object, key, value ) {
  11943. properties.get( object )[ key ] = value;
  11944. }
  11945. function dispose() {
  11946. properties = new WeakMap();
  11947. }
  11948. return {
  11949. get: get,
  11950. remove: remove,
  11951. update: update,
  11952. dispose: dispose
  11953. };
  11954. }
  11955. function painterSortStable( a, b ) {
  11956. if ( a.groupOrder !== b.groupOrder ) {
  11957. return a.groupOrder - b.groupOrder;
  11958. } else if ( a.renderOrder !== b.renderOrder ) {
  11959. return a.renderOrder - b.renderOrder;
  11960. } else if ( a.material.id !== b.material.id ) {
  11961. return a.material.id - b.material.id;
  11962. } else if ( a.z !== b.z ) {
  11963. return a.z - b.z;
  11964. } else {
  11965. return a.id - b.id;
  11966. }
  11967. }
  11968. function reversePainterSortStable( a, b ) {
  11969. if ( a.groupOrder !== b.groupOrder ) {
  11970. return a.groupOrder - b.groupOrder;
  11971. } else if ( a.renderOrder !== b.renderOrder ) {
  11972. return a.renderOrder - b.renderOrder;
  11973. } else if ( a.z !== b.z ) {
  11974. return b.z - a.z;
  11975. } else {
  11976. return a.id - b.id;
  11977. }
  11978. }
  11979. function WebGLRenderList() {
  11980. const renderItems = [];
  11981. let renderItemsIndex = 0;
  11982. const opaque = [];
  11983. const transmissive = [];
  11984. const transparent = [];
  11985. function init() {
  11986. renderItemsIndex = 0;
  11987. opaque.length = 0;
  11988. transmissive.length = 0;
  11989. transparent.length = 0;
  11990. }
  11991. function getNextRenderItem( object, geometry, material, groupOrder, z, group ) {
  11992. let renderItem = renderItems[ renderItemsIndex ];
  11993. if ( renderItem === undefined ) {
  11994. renderItem = {
  11995. id: object.id,
  11996. object: object,
  11997. geometry: geometry,
  11998. material: material,
  11999. groupOrder: groupOrder,
  12000. renderOrder: object.renderOrder,
  12001. z: z,
  12002. group: group
  12003. };
  12004. renderItems[ renderItemsIndex ] = renderItem;
  12005. } else {
  12006. renderItem.id = object.id;
  12007. renderItem.object = object;
  12008. renderItem.geometry = geometry;
  12009. renderItem.material = material;
  12010. renderItem.groupOrder = groupOrder;
  12011. renderItem.renderOrder = object.renderOrder;
  12012. renderItem.z = z;
  12013. renderItem.group = group;
  12014. }
  12015. renderItemsIndex ++;
  12016. return renderItem;
  12017. }
  12018. function push( object, geometry, material, groupOrder, z, group ) {
  12019. const renderItem = getNextRenderItem( object, geometry, material, groupOrder, z, group );
  12020. if ( material.transmission > 0.0 ) {
  12021. transmissive.push( renderItem );
  12022. } else if ( material.transparent === true ) {
  12023. transparent.push( renderItem );
  12024. } else {
  12025. opaque.push( renderItem );
  12026. }
  12027. }
  12028. function unshift( object, geometry, material, groupOrder, z, group ) {
  12029. const renderItem = getNextRenderItem( object, geometry, material, groupOrder, z, group );
  12030. if ( material.transmission > 0.0 ) {
  12031. transmissive.unshift( renderItem );
  12032. } else if ( material.transparent === true ) {
  12033. transparent.unshift( renderItem );
  12034. } else {
  12035. opaque.unshift( renderItem );
  12036. }
  12037. }
  12038. function sort( customOpaqueSort, customTransparentSort ) {
  12039. if ( opaque.length > 1 ) opaque.sort( customOpaqueSort || painterSortStable );
  12040. if ( transmissive.length > 1 ) transmissive.sort( customTransparentSort || reversePainterSortStable );
  12041. if ( transparent.length > 1 ) transparent.sort( customTransparentSort || reversePainterSortStable );
  12042. }
  12043. function finish() {
  12044. // Clear references from inactive renderItems in the list
  12045. for ( let i = renderItemsIndex, il = renderItems.length; i < il; i ++ ) {
  12046. const renderItem = renderItems[ i ];
  12047. if ( renderItem.id === null ) break;
  12048. renderItem.id = null;
  12049. renderItem.object = null;
  12050. renderItem.geometry = null;
  12051. renderItem.material = null;
  12052. renderItem.group = null;
  12053. }
  12054. }
  12055. return {
  12056. opaque: opaque,
  12057. transmissive: transmissive,
  12058. transparent: transparent,
  12059. init: init,
  12060. push: push,
  12061. unshift: unshift,
  12062. finish: finish,
  12063. sort: sort
  12064. };
  12065. }
  12066. function WebGLRenderLists() {
  12067. let lists = new WeakMap();
  12068. function get( scene, renderCallDepth ) {
  12069. const listArray = lists.get( scene );
  12070. let list;
  12071. if ( listArray === undefined ) {
  12072. list = new WebGLRenderList();
  12073. lists.set( scene, [ list ] );
  12074. } else {
  12075. if ( renderCallDepth >= listArray.length ) {
  12076. list = new WebGLRenderList();
  12077. listArray.push( list );
  12078. } else {
  12079. list = listArray[ renderCallDepth ];
  12080. }
  12081. }
  12082. return list;
  12083. }
  12084. function dispose() {
  12085. lists = new WeakMap();
  12086. }
  12087. return {
  12088. get: get,
  12089. dispose: dispose
  12090. };
  12091. }
  12092. function UniformsCache() {
  12093. const lights = {};
  12094. return {
  12095. get: function ( light ) {
  12096. if ( lights[ light.id ] !== undefined ) {
  12097. return lights[ light.id ];
  12098. }
  12099. let uniforms;
  12100. switch ( light.type ) {
  12101. case 'DirectionalLight':
  12102. uniforms = {
  12103. direction: new Vector3(),
  12104. color: new Color()
  12105. };
  12106. break;
  12107. case 'SpotLight':
  12108. uniforms = {
  12109. position: new Vector3(),
  12110. direction: new Vector3(),
  12111. color: new Color(),
  12112. distance: 0,
  12113. coneCos: 0,
  12114. penumbraCos: 0,
  12115. decay: 0
  12116. };
  12117. break;
  12118. case 'PointLight':
  12119. uniforms = {
  12120. position: new Vector3(),
  12121. color: new Color(),
  12122. distance: 0,
  12123. decay: 0
  12124. };
  12125. break;
  12126. case 'HemisphereLight':
  12127. uniforms = {
  12128. direction: new Vector3(),
  12129. skyColor: new Color(),
  12130. groundColor: new Color()
  12131. };
  12132. break;
  12133. case 'RectAreaLight':
  12134. uniforms = {
  12135. color: new Color(),
  12136. position: new Vector3(),
  12137. halfWidth: new Vector3(),
  12138. halfHeight: new Vector3()
  12139. };
  12140. break;
  12141. }
  12142. lights[ light.id ] = uniforms;
  12143. return uniforms;
  12144. }
  12145. };
  12146. }
  12147. function ShadowUniformsCache() {
  12148. const lights = {};
  12149. return {
  12150. get: function ( light ) {
  12151. if ( lights[ light.id ] !== undefined ) {
  12152. return lights[ light.id ];
  12153. }
  12154. let uniforms;
  12155. switch ( light.type ) {
  12156. case 'DirectionalLight':
  12157. uniforms = {
  12158. shadowBias: 0,
  12159. shadowNormalBias: 0,
  12160. shadowRadius: 1,
  12161. shadowMapSize: new Vector2()
  12162. };
  12163. break;
  12164. case 'SpotLight':
  12165. uniforms = {
  12166. shadowBias: 0,
  12167. shadowNormalBias: 0,
  12168. shadowRadius: 1,
  12169. shadowMapSize: new Vector2()
  12170. };
  12171. break;
  12172. case 'PointLight':
  12173. uniforms = {
  12174. shadowBias: 0,
  12175. shadowNormalBias: 0,
  12176. shadowRadius: 1,
  12177. shadowMapSize: new Vector2(),
  12178. shadowCameraNear: 1,
  12179. shadowCameraFar: 1000
  12180. };
  12181. break;
  12182. // TODO (abelnation): set RectAreaLight shadow uniforms
  12183. }
  12184. lights[ light.id ] = uniforms;
  12185. return uniforms;
  12186. }
  12187. };
  12188. }
  12189. let nextVersion = 0;
  12190. function shadowCastingAndTexturingLightsFirst( lightA, lightB ) {
  12191. return ( lightB.castShadow ? 2 : 0 ) - ( lightA.castShadow ? 2 : 0 ) + ( lightB.map ? 1 : 0 ) - ( lightA.map ? 1 : 0 );
  12192. }
  12193. function WebGLLights( extensions, capabilities ) {
  12194. const cache = new UniformsCache();
  12195. const shadowCache = ShadowUniformsCache();
  12196. const state = {
  12197. version: 0,
  12198. hash: {
  12199. directionalLength: - 1,
  12200. pointLength: - 1,
  12201. spotLength: - 1,
  12202. rectAreaLength: - 1,
  12203. hemiLength: - 1,
  12204. numDirectionalShadows: - 1,
  12205. numPointShadows: - 1,
  12206. numSpotShadows: - 1,
  12207. numSpotMaps: - 1
  12208. },
  12209. ambient: [ 0, 0, 0 ],
  12210. probe: [],
  12211. directional: [],
  12212. directionalShadow: [],
  12213. directionalShadowMap: [],
  12214. directionalShadowMatrix: [],
  12215. spot: [],
  12216. spotLightMap: [],
  12217. spotShadow: [],
  12218. spotShadowMap: [],
  12219. spotLightMatrix: [],
  12220. rectArea: [],
  12221. rectAreaLTC1: null,
  12222. rectAreaLTC2: null,
  12223. point: [],
  12224. pointShadow: [],
  12225. pointShadowMap: [],
  12226. pointShadowMatrix: [],
  12227. hemi: [],
  12228. numSpotLightShadowsWithMaps: 0
  12229. };
  12230. for ( let i = 0; i < 9; i ++ ) state.probe.push( new Vector3() );
  12231. const vector3 = new Vector3();
  12232. const matrix4 = new Matrix4();
  12233. const matrix42 = new Matrix4();
  12234. function setup( lights, physicallyCorrectLights ) {
  12235. let r = 0, g = 0, b = 0;
  12236. for ( let i = 0; i < 9; i ++ ) state.probe[ i ].set( 0, 0, 0 );
  12237. let directionalLength = 0;
  12238. let pointLength = 0;
  12239. let spotLength = 0;
  12240. let rectAreaLength = 0;
  12241. let hemiLength = 0;
  12242. let numDirectionalShadows = 0;
  12243. let numPointShadows = 0;
  12244. let numSpotShadows = 0;
  12245. let numSpotMaps = 0;
  12246. let numSpotShadowsWithMaps = 0;
  12247. // ordering : [shadow casting + map texturing, map texturing, shadow casting, none ]
  12248. lights.sort( shadowCastingAndTexturingLightsFirst );
  12249. // artist-friendly light intensity scaling factor
  12250. const scaleFactor = ( physicallyCorrectLights !== true ) ? Math.PI : 1;
  12251. for ( let i = 0, l = lights.length; i < l; i ++ ) {
  12252. const light = lights[ i ];
  12253. const color = light.color;
  12254. const intensity = light.intensity;
  12255. const distance = light.distance;
  12256. const shadowMap = ( light.shadow && light.shadow.map ) ? light.shadow.map.texture : null;
  12257. if ( light.isAmbientLight ) {
  12258. r += color.r * intensity * scaleFactor;
  12259. g += color.g * intensity * scaleFactor;
  12260. b += color.b * intensity * scaleFactor;
  12261. } else if ( light.isLightProbe ) {
  12262. for ( let j = 0; j < 9; j ++ ) {
  12263. state.probe[ j ].addScaledVector( light.sh.coefficients[ j ], intensity );
  12264. }
  12265. } else if ( light.isDirectionalLight ) {
  12266. const uniforms = cache.get( light );
  12267. uniforms.color.copy( light.color ).multiplyScalar( light.intensity * scaleFactor );
  12268. if ( light.castShadow ) {
  12269. const shadow = light.shadow;
  12270. const shadowUniforms = shadowCache.get( light );
  12271. shadowUniforms.shadowBias = shadow.bias;
  12272. shadowUniforms.shadowNormalBias = shadow.normalBias;
  12273. shadowUniforms.shadowRadius = shadow.radius;
  12274. shadowUniforms.shadowMapSize = shadow.mapSize;
  12275. state.directionalShadow[ directionalLength ] = shadowUniforms;
  12276. state.directionalShadowMap[ directionalLength ] = shadowMap;
  12277. state.directionalShadowMatrix[ directionalLength ] = light.shadow.matrix;
  12278. numDirectionalShadows ++;
  12279. }
  12280. state.directional[ directionalLength ] = uniforms;
  12281. directionalLength ++;
  12282. } else if ( light.isSpotLight ) {
  12283. const uniforms = cache.get( light );
  12284. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  12285. uniforms.color.copy( color ).multiplyScalar( intensity * scaleFactor );
  12286. uniforms.distance = distance;
  12287. uniforms.coneCos = Math.cos( light.angle );
  12288. uniforms.penumbraCos = Math.cos( light.angle * ( 1 - light.penumbra ) );
  12289. uniforms.decay = light.decay;
  12290. state.spot[ spotLength ] = uniforms;
  12291. const shadow = light.shadow;
  12292. if ( light.map ) {
  12293. state.spotLightMap[ numSpotMaps ] = light.map;
  12294. numSpotMaps ++;
  12295. // make sure the lightMatrix is up to date
  12296. // TODO : do it if required only
  12297. shadow.updateMatrices( light );
  12298. if ( light.castShadow ) numSpotShadowsWithMaps ++;
  12299. }
  12300. state.spotLightMatrix[ spotLength ] = shadow.matrix;
  12301. if ( light.castShadow ) {
  12302. const shadowUniforms = shadowCache.get( light );
  12303. shadowUniforms.shadowBias = shadow.bias;
  12304. shadowUniforms.shadowNormalBias = shadow.normalBias;
  12305. shadowUniforms.shadowRadius = shadow.radius;
  12306. shadowUniforms.shadowMapSize = shadow.mapSize;
  12307. state.spotShadow[ spotLength ] = shadowUniforms;
  12308. state.spotShadowMap[ spotLength ] = shadowMap;
  12309. numSpotShadows ++;
  12310. }
  12311. spotLength ++;
  12312. } else if ( light.isRectAreaLight ) {
  12313. const uniforms = cache.get( light );
  12314. uniforms.color.copy( color ).multiplyScalar( intensity );
  12315. uniforms.halfWidth.set( light.width * 0.5, 0.0, 0.0 );
  12316. uniforms.halfHeight.set( 0.0, light.height * 0.5, 0.0 );
  12317. state.rectArea[ rectAreaLength ] = uniforms;
  12318. rectAreaLength ++;
  12319. } else if ( light.isPointLight ) {
  12320. const uniforms = cache.get( light );
  12321. uniforms.color.copy( light.color ).multiplyScalar( light.intensity * scaleFactor );
  12322. uniforms.distance = light.distance;
  12323. uniforms.decay = light.decay;
  12324. if ( light.castShadow ) {
  12325. const shadow = light.shadow;
  12326. const shadowUniforms = shadowCache.get( light );
  12327. shadowUniforms.shadowBias = shadow.bias;
  12328. shadowUniforms.shadowNormalBias = shadow.normalBias;
  12329. shadowUniforms.shadowRadius = shadow.radius;
  12330. shadowUniforms.shadowMapSize = shadow.mapSize;
  12331. shadowUniforms.shadowCameraNear = shadow.camera.near;
  12332. shadowUniforms.shadowCameraFar = shadow.camera.far;
  12333. state.pointShadow[ pointLength ] = shadowUniforms;
  12334. state.pointShadowMap[ pointLength ] = shadowMap;
  12335. state.pointShadowMatrix[ pointLength ] = light.shadow.matrix;
  12336. numPointShadows ++;
  12337. }
  12338. state.point[ pointLength ] = uniforms;
  12339. pointLength ++;
  12340. } else if ( light.isHemisphereLight ) {
  12341. const uniforms = cache.get( light );
  12342. uniforms.skyColor.copy( light.color ).multiplyScalar( intensity * scaleFactor );
  12343. uniforms.groundColor.copy( light.groundColor ).multiplyScalar( intensity * scaleFactor );
  12344. state.hemi[ hemiLength ] = uniforms;
  12345. hemiLength ++;
  12346. }
  12347. }
  12348. if ( rectAreaLength > 0 ) {
  12349. if ( capabilities.isWebGL2 ) {
  12350. // WebGL 2
  12351. state.rectAreaLTC1 = UniformsLib.LTC_FLOAT_1;
  12352. state.rectAreaLTC2 = UniformsLib.LTC_FLOAT_2;
  12353. } else {
  12354. // WebGL 1
  12355. if ( extensions.has( 'OES_texture_float_linear' ) === true ) {
  12356. state.rectAreaLTC1 = UniformsLib.LTC_FLOAT_1;
  12357. state.rectAreaLTC2 = UniformsLib.LTC_FLOAT_2;
  12358. } else if ( extensions.has( 'OES_texture_half_float_linear' ) === true ) {
  12359. state.rectAreaLTC1 = UniformsLib.LTC_HALF_1;
  12360. state.rectAreaLTC2 = UniformsLib.LTC_HALF_2;
  12361. } else {
  12362. console.error( 'THREE.WebGLRenderer: Unable to use RectAreaLight. Missing WebGL extensions.' );
  12363. }
  12364. }
  12365. }
  12366. state.ambient[ 0 ] = r;
  12367. state.ambient[ 1 ] = g;
  12368. state.ambient[ 2 ] = b;
  12369. const hash = state.hash;
  12370. if ( hash.directionalLength !== directionalLength ||
  12371. hash.pointLength !== pointLength ||
  12372. hash.spotLength !== spotLength ||
  12373. hash.rectAreaLength !== rectAreaLength ||
  12374. hash.hemiLength !== hemiLength ||
  12375. hash.numDirectionalShadows !== numDirectionalShadows ||
  12376. hash.numPointShadows !== numPointShadows ||
  12377. hash.numSpotShadows !== numSpotShadows ||
  12378. hash.numSpotMaps !== numSpotMaps ) {
  12379. state.directional.length = directionalLength;
  12380. state.spot.length = spotLength;
  12381. state.rectArea.length = rectAreaLength;
  12382. state.point.length = pointLength;
  12383. state.hemi.length = hemiLength;
  12384. state.directionalShadow.length = numDirectionalShadows;
  12385. state.directionalShadowMap.length = numDirectionalShadows;
  12386. state.pointShadow.length = numPointShadows;
  12387. state.pointShadowMap.length = numPointShadows;
  12388. state.spotShadow.length = numSpotShadows;
  12389. state.spotShadowMap.length = numSpotShadows;
  12390. state.directionalShadowMatrix.length = numDirectionalShadows;
  12391. state.pointShadowMatrix.length = numPointShadows;
  12392. state.spotLightMatrix.length = numSpotShadows + numSpotMaps - numSpotShadowsWithMaps;
  12393. state.spotLightMap.length = numSpotMaps;
  12394. state.numSpotLightShadowsWithMaps = numSpotShadowsWithMaps;
  12395. hash.directionalLength = directionalLength;
  12396. hash.pointLength = pointLength;
  12397. hash.spotLength = spotLength;
  12398. hash.rectAreaLength = rectAreaLength;
  12399. hash.hemiLength = hemiLength;
  12400. hash.numDirectionalShadows = numDirectionalShadows;
  12401. hash.numPointShadows = numPointShadows;
  12402. hash.numSpotShadows = numSpotShadows;
  12403. hash.numSpotMaps = numSpotMaps;
  12404. state.version = nextVersion ++;
  12405. }
  12406. }
  12407. function setupView( lights, camera ) {
  12408. let directionalLength = 0;
  12409. let pointLength = 0;
  12410. let spotLength = 0;
  12411. let rectAreaLength = 0;
  12412. let hemiLength = 0;
  12413. const viewMatrix = camera.matrixWorldInverse;
  12414. for ( let i = 0, l = lights.length; i < l; i ++ ) {
  12415. const light = lights[ i ];
  12416. if ( light.isDirectionalLight ) {
  12417. const uniforms = state.directional[ directionalLength ];
  12418. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  12419. vector3.setFromMatrixPosition( light.target.matrixWorld );
  12420. uniforms.direction.sub( vector3 );
  12421. uniforms.direction.transformDirection( viewMatrix );
  12422. directionalLength ++;
  12423. } else if ( light.isSpotLight ) {
  12424. const uniforms = state.spot[ spotLength ];
  12425. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  12426. uniforms.position.applyMatrix4( viewMatrix );
  12427. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  12428. vector3.setFromMatrixPosition( light.target.matrixWorld );
  12429. uniforms.direction.sub( vector3 );
  12430. uniforms.direction.transformDirection( viewMatrix );
  12431. spotLength ++;
  12432. } else if ( light.isRectAreaLight ) {
  12433. const uniforms = state.rectArea[ rectAreaLength ];
  12434. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  12435. uniforms.position.applyMatrix4( viewMatrix );
  12436. // extract local rotation of light to derive width/height half vectors
  12437. matrix42.identity();
  12438. matrix4.copy( light.matrixWorld );
  12439. matrix4.premultiply( viewMatrix );
  12440. matrix42.extractRotation( matrix4 );
  12441. uniforms.halfWidth.set( light.width * 0.5, 0.0, 0.0 );
  12442. uniforms.halfHeight.set( 0.0, light.height * 0.5, 0.0 );
  12443. uniforms.halfWidth.applyMatrix4( matrix42 );
  12444. uniforms.halfHeight.applyMatrix4( matrix42 );
  12445. rectAreaLength ++;
  12446. } else if ( light.isPointLight ) {
  12447. const uniforms = state.point[ pointLength ];
  12448. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  12449. uniforms.position.applyMatrix4( viewMatrix );
  12450. pointLength ++;
  12451. } else if ( light.isHemisphereLight ) {
  12452. const uniforms = state.hemi[ hemiLength ];
  12453. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  12454. uniforms.direction.transformDirection( viewMatrix );
  12455. hemiLength ++;
  12456. }
  12457. }
  12458. }
  12459. return {
  12460. setup: setup,
  12461. setupView: setupView,
  12462. state: state
  12463. };
  12464. }
  12465. function WebGLRenderState( extensions, capabilities ) {
  12466. const lights = new WebGLLights( extensions, capabilities );
  12467. const lightsArray = [];
  12468. const shadowsArray = [];
  12469. function init() {
  12470. lightsArray.length = 0;
  12471. shadowsArray.length = 0;
  12472. }
  12473. function pushLight( light ) {
  12474. lightsArray.push( light );
  12475. }
  12476. function pushShadow( shadowLight ) {
  12477. shadowsArray.push( shadowLight );
  12478. }
  12479. function setupLights( physicallyCorrectLights ) {
  12480. lights.setup( lightsArray, physicallyCorrectLights );
  12481. }
  12482. function setupLightsView( camera ) {
  12483. lights.setupView( lightsArray, camera );
  12484. }
  12485. const state = {
  12486. lightsArray: lightsArray,
  12487. shadowsArray: shadowsArray,
  12488. lights: lights
  12489. };
  12490. return {
  12491. init: init,
  12492. state: state,
  12493. setupLights: setupLights,
  12494. setupLightsView: setupLightsView,
  12495. pushLight: pushLight,
  12496. pushShadow: pushShadow
  12497. };
  12498. }
  12499. function WebGLRenderStates( extensions, capabilities ) {
  12500. let renderStates = new WeakMap();
  12501. function get( scene, renderCallDepth = 0 ) {
  12502. const renderStateArray = renderStates.get( scene );
  12503. let renderState;
  12504. if ( renderStateArray === undefined ) {
  12505. renderState = new WebGLRenderState( extensions, capabilities );
  12506. renderStates.set( scene, [ renderState ] );
  12507. } else {
  12508. if ( renderCallDepth >= renderStateArray.length ) {
  12509. renderState = new WebGLRenderState( extensions, capabilities );
  12510. renderStateArray.push( renderState );
  12511. } else {
  12512. renderState = renderStateArray[ renderCallDepth ];
  12513. }
  12514. }
  12515. return renderState;
  12516. }
  12517. function dispose() {
  12518. renderStates = new WeakMap();
  12519. }
  12520. return {
  12521. get: get,
  12522. dispose: dispose
  12523. };
  12524. }
  12525. class MeshDepthMaterial extends Material {
  12526. constructor( parameters ) {
  12527. super();
  12528. this.isMeshDepthMaterial = true;
  12529. this.type = 'MeshDepthMaterial';
  12530. this.depthPacking = BasicDepthPacking;
  12531. this.map = null;
  12532. this.alphaMap = null;
  12533. this.displacementMap = null;
  12534. this.displacementScale = 1;
  12535. this.displacementBias = 0;
  12536. this.wireframe = false;
  12537. this.wireframeLinewidth = 1;
  12538. this.setValues( parameters );
  12539. }
  12540. copy( source ) {
  12541. super.copy( source );
  12542. this.depthPacking = source.depthPacking;
  12543. this.map = source.map;
  12544. this.alphaMap = source.alphaMap;
  12545. this.displacementMap = source.displacementMap;
  12546. this.displacementScale = source.displacementScale;
  12547. this.displacementBias = source.displacementBias;
  12548. this.wireframe = source.wireframe;
  12549. this.wireframeLinewidth = source.wireframeLinewidth;
  12550. return this;
  12551. }
  12552. }
  12553. class MeshDistanceMaterial extends Material {
  12554. constructor( parameters ) {
  12555. super();
  12556. this.isMeshDistanceMaterial = true;
  12557. this.type = 'MeshDistanceMaterial';
  12558. this.referencePosition = new Vector3();
  12559. this.nearDistance = 1;
  12560. this.farDistance = 1000;
  12561. this.map = null;
  12562. this.alphaMap = null;
  12563. this.displacementMap = null;
  12564. this.displacementScale = 1;
  12565. this.displacementBias = 0;
  12566. this.setValues( parameters );
  12567. }
  12568. copy( source ) {
  12569. super.copy( source );
  12570. this.referencePosition.copy( source.referencePosition );
  12571. this.nearDistance = source.nearDistance;
  12572. this.farDistance = source.farDistance;
  12573. this.map = source.map;
  12574. this.alphaMap = source.alphaMap;
  12575. this.displacementMap = source.displacementMap;
  12576. this.displacementScale = source.displacementScale;
  12577. this.displacementBias = source.displacementBias;
  12578. return this;
  12579. }
  12580. }
  12581. const vertex = "void main() {\n\tgl_Position = vec4( position, 1.0 );\n}";
  12582. const fragment = "uniform sampler2D shadow_pass;\nuniform vec2 resolution;\nuniform float radius;\n#include <packing>\nvoid main() {\n\tconst float samples = float( VSM_SAMPLES );\n\tfloat mean = 0.0;\n\tfloat squared_mean = 0.0;\n\tfloat uvStride = samples <= 1.0 ? 0.0 : 2.0 / ( samples - 1.0 );\n\tfloat uvStart = samples <= 1.0 ? 0.0 : - 1.0;\n\tfor ( float i = 0.0; i < samples; i ++ ) {\n\t\tfloat uvOffset = uvStart + i * uvStride;\n\t\t#ifdef HORIZONTAL_PASS\n\t\t\tvec2 distribution = unpackRGBATo2Half( texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( uvOffset, 0.0 ) * radius ) / resolution ) );\n\t\t\tmean += distribution.x;\n\t\t\tsquared_mean += distribution.y * distribution.y + distribution.x * distribution.x;\n\t\t#else\n\t\t\tfloat depth = unpackRGBAToDepth( texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( 0.0, uvOffset ) * radius ) / resolution ) );\n\t\t\tmean += depth;\n\t\t\tsquared_mean += depth * depth;\n\t\t#endif\n\t}\n\tmean = mean / samples;\n\tsquared_mean = squared_mean / samples;\n\tfloat std_dev = sqrt( squared_mean - mean * mean );\n\tgl_FragColor = pack2HalfToRGBA( vec2( mean, std_dev ) );\n}";
  12583. function WebGLShadowMap( _renderer, _objects, _capabilities ) {
  12584. let _frustum = new Frustum();
  12585. const _shadowMapSize = new Vector2(),
  12586. _viewportSize = new Vector2(),
  12587. _viewport = new Vector4(),
  12588. _depthMaterial = new MeshDepthMaterial( { depthPacking: RGBADepthPacking } ),
  12589. _distanceMaterial = new MeshDistanceMaterial(),
  12590. _materialCache = {},
  12591. _maxTextureSize = _capabilities.maxTextureSize;
  12592. const shadowSide = { [ FrontSide ]: BackSide, [ BackSide ]: FrontSide, [ DoubleSide ]: DoubleSide };
  12593. const shadowMaterialVertical = new ShaderMaterial( {
  12594. defines: {
  12595. VSM_SAMPLES: 8
  12596. },
  12597. uniforms: {
  12598. shadow_pass: { value: null },
  12599. resolution: { value: new Vector2() },
  12600. radius: { value: 4.0 }
  12601. },
  12602. vertexShader: vertex,
  12603. fragmentShader: fragment
  12604. } );
  12605. const shadowMaterialHorizontal = shadowMaterialVertical.clone();
  12606. shadowMaterialHorizontal.defines.HORIZONTAL_PASS = 1;
  12607. const fullScreenTri = new BufferGeometry();
  12608. fullScreenTri.setAttribute(
  12609. 'position',
  12610. new BufferAttribute(
  12611. new Float32Array( [ - 1, - 1, 0.5, 3, - 1, 0.5, - 1, 3, 0.5 ] ),
  12612. 3
  12613. )
  12614. );
  12615. const fullScreenMesh = new Mesh( fullScreenTri, shadowMaterialVertical );
  12616. const scope = this;
  12617. this.enabled = false;
  12618. this.autoUpdate = true;
  12619. this.needsUpdate = false;
  12620. this.type = PCFShadowMap;
  12621. this.render = function ( lights, scene, camera ) {
  12622. if ( scope.enabled === false ) return;
  12623. if ( scope.autoUpdate === false && scope.needsUpdate === false ) return;
  12624. if ( lights.length === 0 ) return;
  12625. const currentRenderTarget = _renderer.getRenderTarget();
  12626. const activeCubeFace = _renderer.getActiveCubeFace();
  12627. const activeMipmapLevel = _renderer.getActiveMipmapLevel();
  12628. const _state = _renderer.state;
  12629. // Set GL state for depth map.
  12630. _state.setBlending( NoBlending );
  12631. _state.buffers.color.setClear( 1, 1, 1, 1 );
  12632. _state.buffers.depth.setTest( true );
  12633. _state.setScissorTest( false );
  12634. // render depth map
  12635. for ( let i = 0, il = lights.length; i < il; i ++ ) {
  12636. const light = lights[ i ];
  12637. const shadow = light.shadow;
  12638. if ( shadow === undefined ) {
  12639. console.warn( 'THREE.WebGLShadowMap:', light, 'has no shadow.' );
  12640. continue;
  12641. }
  12642. if ( shadow.autoUpdate === false && shadow.needsUpdate === false ) continue;
  12643. _shadowMapSize.copy( shadow.mapSize );
  12644. const shadowFrameExtents = shadow.getFrameExtents();
  12645. _shadowMapSize.multiply( shadowFrameExtents );
  12646. _viewportSize.copy( shadow.mapSize );
  12647. if ( _shadowMapSize.x > _maxTextureSize || _shadowMapSize.y > _maxTextureSize ) {
  12648. if ( _shadowMapSize.x > _maxTextureSize ) {
  12649. _viewportSize.x = Math.floor( _maxTextureSize / shadowFrameExtents.x );
  12650. _shadowMapSize.x = _viewportSize.x * shadowFrameExtents.x;
  12651. shadow.mapSize.x = _viewportSize.x;
  12652. }
  12653. if ( _shadowMapSize.y > _maxTextureSize ) {
  12654. _viewportSize.y = Math.floor( _maxTextureSize / shadowFrameExtents.y );
  12655. _shadowMapSize.y = _viewportSize.y * shadowFrameExtents.y;
  12656. shadow.mapSize.y = _viewportSize.y;
  12657. }
  12658. }
  12659. if ( shadow.map === null ) {
  12660. const pars = ( this.type !== VSMShadowMap ) ? { minFilter: NearestFilter, magFilter: NearestFilter } : {};
  12661. shadow.map = new WebGLRenderTarget( _shadowMapSize.x, _shadowMapSize.y, pars );
  12662. shadow.map.texture.name = light.name + '.shadowMap';
  12663. shadow.camera.updateProjectionMatrix();
  12664. }
  12665. _renderer.setRenderTarget( shadow.map );
  12666. _renderer.clear();
  12667. const viewportCount = shadow.getViewportCount();
  12668. for ( let vp = 0; vp < viewportCount; vp ++ ) {
  12669. const viewport = shadow.getViewport( vp );
  12670. _viewport.set(
  12671. _viewportSize.x * viewport.x,
  12672. _viewportSize.y * viewport.y,
  12673. _viewportSize.x * viewport.z,
  12674. _viewportSize.y * viewport.w
  12675. );
  12676. _state.viewport( _viewport );
  12677. shadow.updateMatrices( light, vp );
  12678. _frustum = shadow.getFrustum();
  12679. renderObject( scene, camera, shadow.camera, light, this.type );
  12680. }
  12681. // do blur pass for VSM
  12682. if ( shadow.isPointLightShadow !== true && this.type === VSMShadowMap ) {
  12683. VSMPass( shadow, camera );
  12684. }
  12685. shadow.needsUpdate = false;
  12686. }
  12687. scope.needsUpdate = false;
  12688. _renderer.setRenderTarget( currentRenderTarget, activeCubeFace, activeMipmapLevel );
  12689. };
  12690. function VSMPass( shadow, camera ) {
  12691. const geometry = _objects.update( fullScreenMesh );
  12692. if ( shadowMaterialVertical.defines.VSM_SAMPLES !== shadow.blurSamples ) {
  12693. shadowMaterialVertical.defines.VSM_SAMPLES = shadow.blurSamples;
  12694. shadowMaterialHorizontal.defines.VSM_SAMPLES = shadow.blurSamples;
  12695. shadowMaterialVertical.needsUpdate = true;
  12696. shadowMaterialHorizontal.needsUpdate = true;
  12697. }
  12698. if ( shadow.mapPass === null ) {
  12699. shadow.mapPass = new WebGLRenderTarget( _shadowMapSize.x, _shadowMapSize.y );
  12700. }
  12701. // vertical pass
  12702. shadowMaterialVertical.uniforms.shadow_pass.value = shadow.map.texture;
  12703. shadowMaterialVertical.uniforms.resolution.value = shadow.mapSize;
  12704. shadowMaterialVertical.uniforms.radius.value = shadow.radius;
  12705. _renderer.setRenderTarget( shadow.mapPass );
  12706. _renderer.clear();
  12707. _renderer.renderBufferDirect( camera, null, geometry, shadowMaterialVertical, fullScreenMesh, null );
  12708. // horizontal pass
  12709. shadowMaterialHorizontal.uniforms.shadow_pass.value = shadow.mapPass.texture;
  12710. shadowMaterialHorizontal.uniforms.resolution.value = shadow.mapSize;
  12711. shadowMaterialHorizontal.uniforms.radius.value = shadow.radius;
  12712. _renderer.setRenderTarget( shadow.map );
  12713. _renderer.clear();
  12714. _renderer.renderBufferDirect( camera, null, geometry, shadowMaterialHorizontal, fullScreenMesh, null );
  12715. }
  12716. function getDepthMaterial( object, material, light, shadowCameraNear, shadowCameraFar, type ) {
  12717. let result = null;
  12718. const customMaterial = ( light.isPointLight === true ) ? object.customDistanceMaterial : object.customDepthMaterial;
  12719. if ( customMaterial !== undefined ) {
  12720. result = customMaterial;
  12721. } else {
  12722. result = ( light.isPointLight === true ) ? _distanceMaterial : _depthMaterial;
  12723. if ( ( _renderer.localClippingEnabled && material.clipShadows === true && Array.isArray( material.clippingPlanes ) && material.clippingPlanes.length !== 0 ) ||
  12724. ( material.displacementMap && material.displacementScale !== 0 ) ||
  12725. ( material.alphaMap && material.alphaTest > 0 ) ||
  12726. ( material.map && material.alphaTest > 0 ) ) {
  12727. // in this case we need a unique material instance reflecting the
  12728. // appropriate state
  12729. const keyA = result.uuid, keyB = material.uuid;
  12730. let materialsForVariant = _materialCache[ keyA ];
  12731. if ( materialsForVariant === undefined ) {
  12732. materialsForVariant = {};
  12733. _materialCache[ keyA ] = materialsForVariant;
  12734. }
  12735. let cachedMaterial = materialsForVariant[ keyB ];
  12736. if ( cachedMaterial === undefined ) {
  12737. cachedMaterial = result.clone();
  12738. materialsForVariant[ keyB ] = cachedMaterial;
  12739. }
  12740. result = cachedMaterial;
  12741. }
  12742. }
  12743. result.visible = material.visible;
  12744. result.wireframe = material.wireframe;
  12745. if ( type === VSMShadowMap ) {
  12746. result.side = ( material.shadowSide !== null ) ? material.shadowSide : material.side;
  12747. } else {
  12748. result.side = ( material.shadowSide !== null ) ? material.shadowSide : shadowSide[ material.side ];
  12749. }
  12750. result.alphaMap = material.alphaMap;
  12751. result.alphaTest = material.alphaTest;
  12752. result.map = material.map;
  12753. result.clipShadows = material.clipShadows;
  12754. result.clippingPlanes = material.clippingPlanes;
  12755. result.clipIntersection = material.clipIntersection;
  12756. result.displacementMap = material.displacementMap;
  12757. result.displacementScale = material.displacementScale;
  12758. result.displacementBias = material.displacementBias;
  12759. result.wireframeLinewidth = material.wireframeLinewidth;
  12760. result.linewidth = material.linewidth;
  12761. if ( light.isPointLight === true && result.isMeshDistanceMaterial === true ) {
  12762. result.referencePosition.setFromMatrixPosition( light.matrixWorld );
  12763. result.nearDistance = shadowCameraNear;
  12764. result.farDistance = shadowCameraFar;
  12765. }
  12766. return result;
  12767. }
  12768. function renderObject( object, camera, shadowCamera, light, type ) {
  12769. if ( object.visible === false ) return;
  12770. const visible = object.layers.test( camera.layers );
  12771. if ( visible && ( object.isMesh || object.isLine || object.isPoints ) ) {
  12772. if ( ( object.castShadow || ( object.receiveShadow && type === VSMShadowMap ) ) && ( ! object.frustumCulled || _frustum.intersectsObject( object ) ) ) {
  12773. object.modelViewMatrix.multiplyMatrices( shadowCamera.matrixWorldInverse, object.matrixWorld );
  12774. const geometry = _objects.update( object );
  12775. const material = object.material;
  12776. if ( Array.isArray( material ) ) {
  12777. const groups = geometry.groups;
  12778. for ( let k = 0, kl = groups.length; k < kl; k ++ ) {
  12779. const group = groups[ k ];
  12780. const groupMaterial = material[ group.materialIndex ];
  12781. if ( groupMaterial && groupMaterial.visible ) {
  12782. const depthMaterial = getDepthMaterial( object, groupMaterial, light, shadowCamera.near, shadowCamera.far, type );
  12783. _renderer.renderBufferDirect( shadowCamera, null, geometry, depthMaterial, object, group );
  12784. }
  12785. }
  12786. } else if ( material.visible ) {
  12787. const depthMaterial = getDepthMaterial( object, material, light, shadowCamera.near, shadowCamera.far, type );
  12788. _renderer.renderBufferDirect( shadowCamera, null, geometry, depthMaterial, object, null );
  12789. }
  12790. }
  12791. }
  12792. const children = object.children;
  12793. for ( let i = 0, l = children.length; i < l; i ++ ) {
  12794. renderObject( children[ i ], camera, shadowCamera, light, type );
  12795. }
  12796. }
  12797. }
  12798. function WebGLState( gl, extensions, capabilities ) {
  12799. const isWebGL2 = capabilities.isWebGL2;
  12800. function ColorBuffer() {
  12801. let locked = false;
  12802. const color = new Vector4();
  12803. let currentColorMask = null;
  12804. const currentColorClear = new Vector4( 0, 0, 0, 0 );
  12805. return {
  12806. setMask: function ( colorMask ) {
  12807. if ( currentColorMask !== colorMask && ! locked ) {
  12808. gl.colorMask( colorMask, colorMask, colorMask, colorMask );
  12809. currentColorMask = colorMask;
  12810. }
  12811. },
  12812. setLocked: function ( lock ) {
  12813. locked = lock;
  12814. },
  12815. setClear: function ( r, g, b, a, premultipliedAlpha ) {
  12816. if ( premultipliedAlpha === true ) {
  12817. r *= a; g *= a; b *= a;
  12818. }
  12819. color.set( r, g, b, a );
  12820. if ( currentColorClear.equals( color ) === false ) {
  12821. gl.clearColor( r, g, b, a );
  12822. currentColorClear.copy( color );
  12823. }
  12824. },
  12825. reset: function () {
  12826. locked = false;
  12827. currentColorMask = null;
  12828. currentColorClear.set( - 1, 0, 0, 0 ); // set to invalid state
  12829. }
  12830. };
  12831. }
  12832. function DepthBuffer() {
  12833. let locked = false;
  12834. let currentDepthMask = null;
  12835. let currentDepthFunc = null;
  12836. let currentDepthClear = null;
  12837. return {
  12838. setTest: function ( depthTest ) {
  12839. if ( depthTest ) {
  12840. enable( gl.DEPTH_TEST );
  12841. } else {
  12842. disable( gl.DEPTH_TEST );
  12843. }
  12844. },
  12845. setMask: function ( depthMask ) {
  12846. if ( currentDepthMask !== depthMask && ! locked ) {
  12847. gl.depthMask( depthMask );
  12848. currentDepthMask = depthMask;
  12849. }
  12850. },
  12851. setFunc: function ( depthFunc ) {
  12852. if ( currentDepthFunc !== depthFunc ) {
  12853. switch ( depthFunc ) {
  12854. case NeverDepth:
  12855. gl.depthFunc( gl.NEVER );
  12856. break;
  12857. case AlwaysDepth:
  12858. gl.depthFunc( gl.ALWAYS );
  12859. break;
  12860. case LessDepth:
  12861. gl.depthFunc( gl.LESS );
  12862. break;
  12863. case LessEqualDepth:
  12864. gl.depthFunc( gl.LEQUAL );
  12865. break;
  12866. case EqualDepth:
  12867. gl.depthFunc( gl.EQUAL );
  12868. break;
  12869. case GreaterEqualDepth:
  12870. gl.depthFunc( gl.GEQUAL );
  12871. break;
  12872. case GreaterDepth:
  12873. gl.depthFunc( gl.GREATER );
  12874. break;
  12875. case NotEqualDepth:
  12876. gl.depthFunc( gl.NOTEQUAL );
  12877. break;
  12878. default:
  12879. gl.depthFunc( gl.LEQUAL );
  12880. }
  12881. currentDepthFunc = depthFunc;
  12882. }
  12883. },
  12884. setLocked: function ( lock ) {
  12885. locked = lock;
  12886. },
  12887. setClear: function ( depth ) {
  12888. if ( currentDepthClear !== depth ) {
  12889. gl.clearDepth( depth );
  12890. currentDepthClear = depth;
  12891. }
  12892. },
  12893. reset: function () {
  12894. locked = false;
  12895. currentDepthMask = null;
  12896. currentDepthFunc = null;
  12897. currentDepthClear = null;
  12898. }
  12899. };
  12900. }
  12901. function StencilBuffer() {
  12902. let locked = false;
  12903. let currentStencilMask = null;
  12904. let currentStencilFunc = null;
  12905. let currentStencilRef = null;
  12906. let currentStencilFuncMask = null;
  12907. let currentStencilFail = null;
  12908. let currentStencilZFail = null;
  12909. let currentStencilZPass = null;
  12910. let currentStencilClear = null;
  12911. return {
  12912. setTest: function ( stencilTest ) {
  12913. if ( ! locked ) {
  12914. if ( stencilTest ) {
  12915. enable( gl.STENCIL_TEST );
  12916. } else {
  12917. disable( gl.STENCIL_TEST );
  12918. }
  12919. }
  12920. },
  12921. setMask: function ( stencilMask ) {
  12922. if ( currentStencilMask !== stencilMask && ! locked ) {
  12923. gl.stencilMask( stencilMask );
  12924. currentStencilMask = stencilMask;
  12925. }
  12926. },
  12927. setFunc: function ( stencilFunc, stencilRef, stencilMask ) {
  12928. if ( currentStencilFunc !== stencilFunc ||
  12929. currentStencilRef !== stencilRef ||
  12930. currentStencilFuncMask !== stencilMask ) {
  12931. gl.stencilFunc( stencilFunc, stencilRef, stencilMask );
  12932. currentStencilFunc = stencilFunc;
  12933. currentStencilRef = stencilRef;
  12934. currentStencilFuncMask = stencilMask;
  12935. }
  12936. },
  12937. setOp: function ( stencilFail, stencilZFail, stencilZPass ) {
  12938. if ( currentStencilFail !== stencilFail ||
  12939. currentStencilZFail !== stencilZFail ||
  12940. currentStencilZPass !== stencilZPass ) {
  12941. gl.stencilOp( stencilFail, stencilZFail, stencilZPass );
  12942. currentStencilFail = stencilFail;
  12943. currentStencilZFail = stencilZFail;
  12944. currentStencilZPass = stencilZPass;
  12945. }
  12946. },
  12947. setLocked: function ( lock ) {
  12948. locked = lock;
  12949. },
  12950. setClear: function ( stencil ) {
  12951. if ( currentStencilClear !== stencil ) {
  12952. gl.clearStencil( stencil );
  12953. currentStencilClear = stencil;
  12954. }
  12955. },
  12956. reset: function () {
  12957. locked = false;
  12958. currentStencilMask = null;
  12959. currentStencilFunc = null;
  12960. currentStencilRef = null;
  12961. currentStencilFuncMask = null;
  12962. currentStencilFail = null;
  12963. currentStencilZFail = null;
  12964. currentStencilZPass = null;
  12965. currentStencilClear = null;
  12966. }
  12967. };
  12968. }
  12969. //
  12970. const colorBuffer = new ColorBuffer();
  12971. const depthBuffer = new DepthBuffer();
  12972. const stencilBuffer = new StencilBuffer();
  12973. const uboBindings = new WeakMap();
  12974. const uboProgramMap = new WeakMap();
  12975. let enabledCapabilities = {};
  12976. let currentBoundFramebuffers = {};
  12977. let currentDrawbuffers = new WeakMap();
  12978. let defaultDrawbuffers = [];
  12979. let currentProgram = null;
  12980. let currentBlendingEnabled = false;
  12981. let currentBlending = null;
  12982. let currentBlendEquation = null;
  12983. let currentBlendSrc = null;
  12984. let currentBlendDst = null;
  12985. let currentBlendEquationAlpha = null;
  12986. let currentBlendSrcAlpha = null;
  12987. let currentBlendDstAlpha = null;
  12988. let currentPremultipledAlpha = false;
  12989. let currentFlipSided = null;
  12990. let currentCullFace = null;
  12991. let currentLineWidth = null;
  12992. let currentPolygonOffsetFactor = null;
  12993. let currentPolygonOffsetUnits = null;
  12994. const maxTextures = gl.getParameter( gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS );
  12995. let lineWidthAvailable = false;
  12996. let version = 0;
  12997. const glVersion = gl.getParameter( gl.VERSION );
  12998. if ( glVersion.indexOf( 'WebGL' ) !== - 1 ) {
  12999. version = parseFloat( /^WebGL (\d)/.exec( glVersion )[ 1 ] );
  13000. lineWidthAvailable = ( version >= 1.0 );
  13001. } else if ( glVersion.indexOf( 'OpenGL ES' ) !== - 1 ) {
  13002. version = parseFloat( /^OpenGL ES (\d)/.exec( glVersion )[ 1 ] );
  13003. lineWidthAvailable = ( version >= 2.0 );
  13004. }
  13005. let currentTextureSlot = null;
  13006. let currentBoundTextures = {};
  13007. const scissorParam = gl.getParameter( gl.SCISSOR_BOX );
  13008. const viewportParam = gl.getParameter( gl.VIEWPORT );
  13009. const currentScissor = new Vector4().fromArray( scissorParam );
  13010. const currentViewport = new Vector4().fromArray( viewportParam );
  13011. function createTexture( type, target, count ) {
  13012. const data = new Uint8Array( 4 ); // 4 is required to match default unpack alignment of 4.
  13013. const texture = gl.createTexture();
  13014. gl.bindTexture( type, texture );
  13015. gl.texParameteri( type, gl.TEXTURE_MIN_FILTER, gl.NEAREST );
  13016. gl.texParameteri( type, gl.TEXTURE_MAG_FILTER, gl.NEAREST );
  13017. for ( let i = 0; i < count; i ++ ) {
  13018. gl.texImage2D( target + i, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, data );
  13019. }
  13020. return texture;
  13021. }
  13022. const emptyTextures = {};
  13023. emptyTextures[ gl.TEXTURE_2D ] = createTexture( gl.TEXTURE_2D, gl.TEXTURE_2D, 1 );
  13024. emptyTextures[ gl.TEXTURE_CUBE_MAP ] = createTexture( gl.TEXTURE_CUBE_MAP, gl.TEXTURE_CUBE_MAP_POSITIVE_X, 6 );
  13025. // init
  13026. colorBuffer.setClear( 0, 0, 0, 1 );
  13027. depthBuffer.setClear( 1 );
  13028. stencilBuffer.setClear( 0 );
  13029. enable( gl.DEPTH_TEST );
  13030. depthBuffer.setFunc( LessEqualDepth );
  13031. setFlipSided( false );
  13032. setCullFace( CullFaceBack );
  13033. enable( gl.CULL_FACE );
  13034. setBlending( NoBlending );
  13035. //
  13036. function enable( id ) {
  13037. if ( enabledCapabilities[ id ] !== true ) {
  13038. gl.enable( id );
  13039. enabledCapabilities[ id ] = true;
  13040. }
  13041. }
  13042. function disable( id ) {
  13043. if ( enabledCapabilities[ id ] !== false ) {
  13044. gl.disable( id );
  13045. enabledCapabilities[ id ] = false;
  13046. }
  13047. }
  13048. function bindFramebuffer( target, framebuffer ) {
  13049. if ( currentBoundFramebuffers[ target ] !== framebuffer ) {
  13050. gl.bindFramebuffer( target, framebuffer );
  13051. currentBoundFramebuffers[ target ] = framebuffer;
  13052. if ( isWebGL2 ) {
  13053. // gl.DRAW_FRAMEBUFFER is equivalent to gl.FRAMEBUFFER
  13054. if ( target === gl.DRAW_FRAMEBUFFER ) {
  13055. currentBoundFramebuffers[ gl.FRAMEBUFFER ] = framebuffer;
  13056. }
  13057. if ( target === gl.FRAMEBUFFER ) {
  13058. currentBoundFramebuffers[ gl.DRAW_FRAMEBUFFER ] = framebuffer;
  13059. }
  13060. }
  13061. return true;
  13062. }
  13063. return false;
  13064. }
  13065. function drawBuffers( renderTarget, framebuffer ) {
  13066. let drawBuffers = defaultDrawbuffers;
  13067. let needsUpdate = false;
  13068. if ( renderTarget ) {
  13069. drawBuffers = currentDrawbuffers.get( framebuffer );
  13070. if ( drawBuffers === undefined ) {
  13071. drawBuffers = [];
  13072. currentDrawbuffers.set( framebuffer, drawBuffers );
  13073. }
  13074. if ( renderTarget.isWebGLMultipleRenderTargets ) {
  13075. const textures = renderTarget.texture;
  13076. if ( drawBuffers.length !== textures.length || drawBuffers[ 0 ] !== gl.COLOR_ATTACHMENT0 ) {
  13077. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  13078. drawBuffers[ i ] = gl.COLOR_ATTACHMENT0 + i;
  13079. }
  13080. drawBuffers.length = textures.length;
  13081. needsUpdate = true;
  13082. }
  13083. } else {
  13084. if ( drawBuffers[ 0 ] !== gl.COLOR_ATTACHMENT0 ) {
  13085. drawBuffers[ 0 ] = gl.COLOR_ATTACHMENT0;
  13086. needsUpdate = true;
  13087. }
  13088. }
  13089. } else {
  13090. if ( drawBuffers[ 0 ] !== gl.BACK ) {
  13091. drawBuffers[ 0 ] = gl.BACK;
  13092. needsUpdate = true;
  13093. }
  13094. }
  13095. if ( needsUpdate ) {
  13096. if ( capabilities.isWebGL2 ) {
  13097. gl.drawBuffers( drawBuffers );
  13098. } else {
  13099. extensions.get( 'WEBGL_draw_buffers' ).drawBuffersWEBGL( drawBuffers );
  13100. }
  13101. }
  13102. }
  13103. function useProgram( program ) {
  13104. if ( currentProgram !== program ) {
  13105. gl.useProgram( program );
  13106. currentProgram = program;
  13107. return true;
  13108. }
  13109. return false;
  13110. }
  13111. const equationToGL = {
  13112. [ AddEquation ]: gl.FUNC_ADD,
  13113. [ SubtractEquation ]: gl.FUNC_SUBTRACT,
  13114. [ ReverseSubtractEquation ]: gl.FUNC_REVERSE_SUBTRACT
  13115. };
  13116. if ( isWebGL2 ) {
  13117. equationToGL[ MinEquation ] = gl.MIN;
  13118. equationToGL[ MaxEquation ] = gl.MAX;
  13119. } else {
  13120. const extension = extensions.get( 'EXT_blend_minmax' );
  13121. if ( extension !== null ) {
  13122. equationToGL[ MinEquation ] = extension.MIN_EXT;
  13123. equationToGL[ MaxEquation ] = extension.MAX_EXT;
  13124. }
  13125. }
  13126. const factorToGL = {
  13127. [ ZeroFactor ]: gl.ZERO,
  13128. [ OneFactor ]: gl.ONE,
  13129. [ SrcColorFactor ]: gl.SRC_COLOR,
  13130. [ SrcAlphaFactor ]: gl.SRC_ALPHA,
  13131. [ SrcAlphaSaturateFactor ]: gl.SRC_ALPHA_SATURATE,
  13132. [ DstColorFactor ]: gl.DST_COLOR,
  13133. [ DstAlphaFactor ]: gl.DST_ALPHA,
  13134. [ OneMinusSrcColorFactor ]: gl.ONE_MINUS_SRC_COLOR,
  13135. [ OneMinusSrcAlphaFactor ]: gl.ONE_MINUS_SRC_ALPHA,
  13136. [ OneMinusDstColorFactor ]: gl.ONE_MINUS_DST_COLOR,
  13137. [ OneMinusDstAlphaFactor ]: gl.ONE_MINUS_DST_ALPHA
  13138. };
  13139. function setBlending( blending, blendEquation, blendSrc, blendDst, blendEquationAlpha, blendSrcAlpha, blendDstAlpha, premultipliedAlpha ) {
  13140. if ( blending === NoBlending ) {
  13141. if ( currentBlendingEnabled === true ) {
  13142. disable( gl.BLEND );
  13143. currentBlendingEnabled = false;
  13144. }
  13145. return;
  13146. }
  13147. if ( currentBlendingEnabled === false ) {
  13148. enable( gl.BLEND );
  13149. currentBlendingEnabled = true;
  13150. }
  13151. if ( blending !== CustomBlending ) {
  13152. if ( blending !== currentBlending || premultipliedAlpha !== currentPremultipledAlpha ) {
  13153. if ( currentBlendEquation !== AddEquation || currentBlendEquationAlpha !== AddEquation ) {
  13154. gl.blendEquation( gl.FUNC_ADD );
  13155. currentBlendEquation = AddEquation;
  13156. currentBlendEquationAlpha = AddEquation;
  13157. }
  13158. if ( premultipliedAlpha ) {
  13159. switch ( blending ) {
  13160. case NormalBlending:
  13161. gl.blendFuncSeparate( gl.ONE, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  13162. break;
  13163. case AdditiveBlending:
  13164. gl.blendFunc( gl.ONE, gl.ONE );
  13165. break;
  13166. case SubtractiveBlending:
  13167. gl.blendFuncSeparate( gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ZERO, gl.ONE );
  13168. break;
  13169. case MultiplyBlending:
  13170. gl.blendFuncSeparate( gl.ZERO, gl.SRC_COLOR, gl.ZERO, gl.SRC_ALPHA );
  13171. break;
  13172. default:
  13173. console.error( 'THREE.WebGLState: Invalid blending: ', blending );
  13174. break;
  13175. }
  13176. } else {
  13177. switch ( blending ) {
  13178. case NormalBlending:
  13179. gl.blendFuncSeparate( gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  13180. break;
  13181. case AdditiveBlending:
  13182. gl.blendFunc( gl.SRC_ALPHA, gl.ONE );
  13183. break;
  13184. case SubtractiveBlending:
  13185. gl.blendFuncSeparate( gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ZERO, gl.ONE );
  13186. break;
  13187. case MultiplyBlending:
  13188. gl.blendFunc( gl.ZERO, gl.SRC_COLOR );
  13189. break;
  13190. default:
  13191. console.error( 'THREE.WebGLState: Invalid blending: ', blending );
  13192. break;
  13193. }
  13194. }
  13195. currentBlendSrc = null;
  13196. currentBlendDst = null;
  13197. currentBlendSrcAlpha = null;
  13198. currentBlendDstAlpha = null;
  13199. currentBlending = blending;
  13200. currentPremultipledAlpha = premultipliedAlpha;
  13201. }
  13202. return;
  13203. }
  13204. // custom blending
  13205. blendEquationAlpha = blendEquationAlpha || blendEquation;
  13206. blendSrcAlpha = blendSrcAlpha || blendSrc;
  13207. blendDstAlpha = blendDstAlpha || blendDst;
  13208. if ( blendEquation !== currentBlendEquation || blendEquationAlpha !== currentBlendEquationAlpha ) {
  13209. gl.blendEquationSeparate( equationToGL[ blendEquation ], equationToGL[ blendEquationAlpha ] );
  13210. currentBlendEquation = blendEquation;
  13211. currentBlendEquationAlpha = blendEquationAlpha;
  13212. }
  13213. if ( blendSrc !== currentBlendSrc || blendDst !== currentBlendDst || blendSrcAlpha !== currentBlendSrcAlpha || blendDstAlpha !== currentBlendDstAlpha ) {
  13214. gl.blendFuncSeparate( factorToGL[ blendSrc ], factorToGL[ blendDst ], factorToGL[ blendSrcAlpha ], factorToGL[ blendDstAlpha ] );
  13215. currentBlendSrc = blendSrc;
  13216. currentBlendDst = blendDst;
  13217. currentBlendSrcAlpha = blendSrcAlpha;
  13218. currentBlendDstAlpha = blendDstAlpha;
  13219. }
  13220. currentBlending = blending;
  13221. currentPremultipledAlpha = false;
  13222. }
  13223. function setMaterial( material, frontFaceCW ) {
  13224. material.side === DoubleSide
  13225. ? disable( gl.CULL_FACE )
  13226. : enable( gl.CULL_FACE );
  13227. let flipSided = ( material.side === BackSide );
  13228. if ( frontFaceCW ) flipSided = ! flipSided;
  13229. setFlipSided( flipSided );
  13230. ( material.blending === NormalBlending && material.transparent === false )
  13231. ? setBlending( NoBlending )
  13232. : setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst, material.blendEquationAlpha, material.blendSrcAlpha, material.blendDstAlpha, material.premultipliedAlpha );
  13233. depthBuffer.setFunc( material.depthFunc );
  13234. depthBuffer.setTest( material.depthTest );
  13235. depthBuffer.setMask( material.depthWrite );
  13236. colorBuffer.setMask( material.colorWrite );
  13237. const stencilWrite = material.stencilWrite;
  13238. stencilBuffer.setTest( stencilWrite );
  13239. if ( stencilWrite ) {
  13240. stencilBuffer.setMask( material.stencilWriteMask );
  13241. stencilBuffer.setFunc( material.stencilFunc, material.stencilRef, material.stencilFuncMask );
  13242. stencilBuffer.setOp( material.stencilFail, material.stencilZFail, material.stencilZPass );
  13243. }
  13244. setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  13245. material.alphaToCoverage === true
  13246. ? enable( gl.SAMPLE_ALPHA_TO_COVERAGE )
  13247. : disable( gl.SAMPLE_ALPHA_TO_COVERAGE );
  13248. }
  13249. //
  13250. function setFlipSided( flipSided ) {
  13251. if ( currentFlipSided !== flipSided ) {
  13252. if ( flipSided ) {
  13253. gl.frontFace( gl.CW );
  13254. } else {
  13255. gl.frontFace( gl.CCW );
  13256. }
  13257. currentFlipSided = flipSided;
  13258. }
  13259. }
  13260. function setCullFace( cullFace ) {
  13261. if ( cullFace !== CullFaceNone ) {
  13262. enable( gl.CULL_FACE );
  13263. if ( cullFace !== currentCullFace ) {
  13264. if ( cullFace === CullFaceBack ) {
  13265. gl.cullFace( gl.BACK );
  13266. } else if ( cullFace === CullFaceFront ) {
  13267. gl.cullFace( gl.FRONT );
  13268. } else {
  13269. gl.cullFace( gl.FRONT_AND_BACK );
  13270. }
  13271. }
  13272. } else {
  13273. disable( gl.CULL_FACE );
  13274. }
  13275. currentCullFace = cullFace;
  13276. }
  13277. function setLineWidth( width ) {
  13278. if ( width !== currentLineWidth ) {
  13279. if ( lineWidthAvailable ) gl.lineWidth( width );
  13280. currentLineWidth = width;
  13281. }
  13282. }
  13283. function setPolygonOffset( polygonOffset, factor, units ) {
  13284. if ( polygonOffset ) {
  13285. enable( gl.POLYGON_OFFSET_FILL );
  13286. if ( currentPolygonOffsetFactor !== factor || currentPolygonOffsetUnits !== units ) {
  13287. gl.polygonOffset( factor, units );
  13288. currentPolygonOffsetFactor = factor;
  13289. currentPolygonOffsetUnits = units;
  13290. }
  13291. } else {
  13292. disable( gl.POLYGON_OFFSET_FILL );
  13293. }
  13294. }
  13295. function setScissorTest( scissorTest ) {
  13296. if ( scissorTest ) {
  13297. enable( gl.SCISSOR_TEST );
  13298. } else {
  13299. disable( gl.SCISSOR_TEST );
  13300. }
  13301. }
  13302. // texture
  13303. function activeTexture( webglSlot ) {
  13304. if ( webglSlot === undefined ) webglSlot = gl.TEXTURE0 + maxTextures - 1;
  13305. if ( currentTextureSlot !== webglSlot ) {
  13306. gl.activeTexture( webglSlot );
  13307. currentTextureSlot = webglSlot;
  13308. }
  13309. }
  13310. function bindTexture( webglType, webglTexture, webglSlot ) {
  13311. if ( webglSlot === undefined ) {
  13312. if ( currentTextureSlot === null ) {
  13313. webglSlot = gl.TEXTURE0 + maxTextures - 1;
  13314. } else {
  13315. webglSlot = currentTextureSlot;
  13316. }
  13317. }
  13318. let boundTexture = currentBoundTextures[ webglSlot ];
  13319. if ( boundTexture === undefined ) {
  13320. boundTexture = { type: undefined, texture: undefined };
  13321. currentBoundTextures[ webglSlot ] = boundTexture;
  13322. }
  13323. if ( boundTexture.type !== webglType || boundTexture.texture !== webglTexture ) {
  13324. if ( currentTextureSlot !== webglSlot ) {
  13325. gl.activeTexture( webglSlot );
  13326. currentTextureSlot = webglSlot;
  13327. }
  13328. gl.bindTexture( webglType, webglTexture || emptyTextures[ webglType ] );
  13329. boundTexture.type = webglType;
  13330. boundTexture.texture = webglTexture;
  13331. }
  13332. }
  13333. function unbindTexture() {
  13334. const boundTexture = currentBoundTextures[ currentTextureSlot ];
  13335. if ( boundTexture !== undefined && boundTexture.type !== undefined ) {
  13336. gl.bindTexture( boundTexture.type, null );
  13337. boundTexture.type = undefined;
  13338. boundTexture.texture = undefined;
  13339. }
  13340. }
  13341. function compressedTexImage2D() {
  13342. try {
  13343. gl.compressedTexImage2D.apply( gl, arguments );
  13344. } catch ( error ) {
  13345. console.error( 'THREE.WebGLState:', error );
  13346. }
  13347. }
  13348. function compressedTexImage3D() {
  13349. try {
  13350. gl.compressedTexImage3D.apply( gl, arguments );
  13351. } catch ( error ) {
  13352. console.error( 'THREE.WebGLState:', error );
  13353. }
  13354. }
  13355. function texSubImage2D() {
  13356. try {
  13357. gl.texSubImage2D.apply( gl, arguments );
  13358. } catch ( error ) {
  13359. console.error( 'THREE.WebGLState:', error );
  13360. }
  13361. }
  13362. function texSubImage3D() {
  13363. try {
  13364. gl.texSubImage3D.apply( gl, arguments );
  13365. } catch ( error ) {
  13366. console.error( 'THREE.WebGLState:', error );
  13367. }
  13368. }
  13369. function compressedTexSubImage2D() {
  13370. try {
  13371. gl.compressedTexSubImage2D.apply( gl, arguments );
  13372. } catch ( error ) {
  13373. console.error( 'THREE.WebGLState:', error );
  13374. }
  13375. }
  13376. function compressedTexSubImage3D() {
  13377. try {
  13378. gl.compressedTexSubImage3D.apply( gl, arguments );
  13379. } catch ( error ) {
  13380. console.error( 'THREE.WebGLState:', error );
  13381. }
  13382. }
  13383. function texStorage2D() {
  13384. try {
  13385. gl.texStorage2D.apply( gl, arguments );
  13386. } catch ( error ) {
  13387. console.error( 'THREE.WebGLState:', error );
  13388. }
  13389. }
  13390. function texStorage3D() {
  13391. try {
  13392. gl.texStorage3D.apply( gl, arguments );
  13393. } catch ( error ) {
  13394. console.error( 'THREE.WebGLState:', error );
  13395. }
  13396. }
  13397. function texImage2D() {
  13398. try {
  13399. gl.texImage2D.apply( gl, arguments );
  13400. } catch ( error ) {
  13401. console.error( 'THREE.WebGLState:', error );
  13402. }
  13403. }
  13404. function texImage3D() {
  13405. try {
  13406. gl.texImage3D.apply( gl, arguments );
  13407. } catch ( error ) {
  13408. console.error( 'THREE.WebGLState:', error );
  13409. }
  13410. }
  13411. //
  13412. function scissor( scissor ) {
  13413. if ( currentScissor.equals( scissor ) === false ) {
  13414. gl.scissor( scissor.x, scissor.y, scissor.z, scissor.w );
  13415. currentScissor.copy( scissor );
  13416. }
  13417. }
  13418. function viewport( viewport ) {
  13419. if ( currentViewport.equals( viewport ) === false ) {
  13420. gl.viewport( viewport.x, viewport.y, viewport.z, viewport.w );
  13421. currentViewport.copy( viewport );
  13422. }
  13423. }
  13424. function updateUBOMapping( uniformsGroup, program ) {
  13425. let mapping = uboProgramMap.get( program );
  13426. if ( mapping === undefined ) {
  13427. mapping = new WeakMap();
  13428. uboProgramMap.set( program, mapping );
  13429. }
  13430. let blockIndex = mapping.get( uniformsGroup );
  13431. if ( blockIndex === undefined ) {
  13432. blockIndex = gl.getUniformBlockIndex( program, uniformsGroup.name );
  13433. mapping.set( uniformsGroup, blockIndex );
  13434. }
  13435. }
  13436. function uniformBlockBinding( uniformsGroup, program ) {
  13437. const mapping = uboProgramMap.get( program );
  13438. const blockIndex = mapping.get( uniformsGroup );
  13439. if ( uboBindings.get( program ) !== blockIndex ) {
  13440. // bind shader specific block index to global block point
  13441. gl.uniformBlockBinding( program, blockIndex, uniformsGroup.__bindingPointIndex );
  13442. uboBindings.set( program, blockIndex );
  13443. }
  13444. }
  13445. //
  13446. function reset() {
  13447. // reset state
  13448. gl.disable( gl.BLEND );
  13449. gl.disable( gl.CULL_FACE );
  13450. gl.disable( gl.DEPTH_TEST );
  13451. gl.disable( gl.POLYGON_OFFSET_FILL );
  13452. gl.disable( gl.SCISSOR_TEST );
  13453. gl.disable( gl.STENCIL_TEST );
  13454. gl.disable( gl.SAMPLE_ALPHA_TO_COVERAGE );
  13455. gl.blendEquation( gl.FUNC_ADD );
  13456. gl.blendFunc( gl.ONE, gl.ZERO );
  13457. gl.blendFuncSeparate( gl.ONE, gl.ZERO, gl.ONE, gl.ZERO );
  13458. gl.colorMask( true, true, true, true );
  13459. gl.clearColor( 0, 0, 0, 0 );
  13460. gl.depthMask( true );
  13461. gl.depthFunc( gl.LESS );
  13462. gl.clearDepth( 1 );
  13463. gl.stencilMask( 0xffffffff );
  13464. gl.stencilFunc( gl.ALWAYS, 0, 0xffffffff );
  13465. gl.stencilOp( gl.KEEP, gl.KEEP, gl.KEEP );
  13466. gl.clearStencil( 0 );
  13467. gl.cullFace( gl.BACK );
  13468. gl.frontFace( gl.CCW );
  13469. gl.polygonOffset( 0, 0 );
  13470. gl.activeTexture( gl.TEXTURE0 );
  13471. gl.bindFramebuffer( gl.FRAMEBUFFER, null );
  13472. if ( isWebGL2 === true ) {
  13473. gl.bindFramebuffer( gl.DRAW_FRAMEBUFFER, null );
  13474. gl.bindFramebuffer( gl.READ_FRAMEBUFFER, null );
  13475. }
  13476. gl.useProgram( null );
  13477. gl.lineWidth( 1 );
  13478. gl.scissor( 0, 0, gl.canvas.width, gl.canvas.height );
  13479. gl.viewport( 0, 0, gl.canvas.width, gl.canvas.height );
  13480. // reset internals
  13481. enabledCapabilities = {};
  13482. currentTextureSlot = null;
  13483. currentBoundTextures = {};
  13484. currentBoundFramebuffers = {};
  13485. currentDrawbuffers = new WeakMap();
  13486. defaultDrawbuffers = [];
  13487. currentProgram = null;
  13488. currentBlendingEnabled = false;
  13489. currentBlending = null;
  13490. currentBlendEquation = null;
  13491. currentBlendSrc = null;
  13492. currentBlendDst = null;
  13493. currentBlendEquationAlpha = null;
  13494. currentBlendSrcAlpha = null;
  13495. currentBlendDstAlpha = null;
  13496. currentPremultipledAlpha = false;
  13497. currentFlipSided = null;
  13498. currentCullFace = null;
  13499. currentLineWidth = null;
  13500. currentPolygonOffsetFactor = null;
  13501. currentPolygonOffsetUnits = null;
  13502. currentScissor.set( 0, 0, gl.canvas.width, gl.canvas.height );
  13503. currentViewport.set( 0, 0, gl.canvas.width, gl.canvas.height );
  13504. colorBuffer.reset();
  13505. depthBuffer.reset();
  13506. stencilBuffer.reset();
  13507. }
  13508. return {
  13509. buffers: {
  13510. color: colorBuffer,
  13511. depth: depthBuffer,
  13512. stencil: stencilBuffer
  13513. },
  13514. enable: enable,
  13515. disable: disable,
  13516. bindFramebuffer: bindFramebuffer,
  13517. drawBuffers: drawBuffers,
  13518. useProgram: useProgram,
  13519. setBlending: setBlending,
  13520. setMaterial: setMaterial,
  13521. setFlipSided: setFlipSided,
  13522. setCullFace: setCullFace,
  13523. setLineWidth: setLineWidth,
  13524. setPolygonOffset: setPolygonOffset,
  13525. setScissorTest: setScissorTest,
  13526. activeTexture: activeTexture,
  13527. bindTexture: bindTexture,
  13528. unbindTexture: unbindTexture,
  13529. compressedTexImage2D: compressedTexImage2D,
  13530. compressedTexImage3D: compressedTexImage3D,
  13531. texImage2D: texImage2D,
  13532. texImage3D: texImage3D,
  13533. updateUBOMapping: updateUBOMapping,
  13534. uniformBlockBinding: uniformBlockBinding,
  13535. texStorage2D: texStorage2D,
  13536. texStorage3D: texStorage3D,
  13537. texSubImage2D: texSubImage2D,
  13538. texSubImage3D: texSubImage3D,
  13539. compressedTexSubImage2D: compressedTexSubImage2D,
  13540. compressedTexSubImage3D: compressedTexSubImage3D,
  13541. scissor: scissor,
  13542. viewport: viewport,
  13543. reset: reset
  13544. };
  13545. }
  13546. function WebGLTextures( _gl, extensions, state, properties, capabilities, utils, info ) {
  13547. const isWebGL2 = capabilities.isWebGL2;
  13548. const maxTextures = capabilities.maxTextures;
  13549. const maxCubemapSize = capabilities.maxCubemapSize;
  13550. const maxTextureSize = capabilities.maxTextureSize;
  13551. const maxSamples = capabilities.maxSamples;
  13552. const multisampledRTTExt = extensions.has( 'WEBGL_multisampled_render_to_texture' ) ? extensions.get( 'WEBGL_multisampled_render_to_texture' ) : null;
  13553. const supportsInvalidateFramebuffer = typeof navigator === 'undefined' ? false : /OculusBrowser/g.test( navigator.userAgent );
  13554. const _videoTextures = new WeakMap();
  13555. let _canvas;
  13556. const _sources = new WeakMap(); // maps WebglTexture objects to instances of Source
  13557. // cordova iOS (as of 5.0) still uses UIWebView, which provides OffscreenCanvas,
  13558. // also OffscreenCanvas.getContext("webgl"), but not OffscreenCanvas.getContext("2d")!
  13559. // Some implementations may only implement OffscreenCanvas partially (e.g. lacking 2d).
  13560. let useOffscreenCanvas = false;
  13561. try {
  13562. useOffscreenCanvas = typeof OffscreenCanvas !== 'undefined'
  13563. // eslint-disable-next-line compat/compat
  13564. && ( new OffscreenCanvas( 1, 1 ).getContext( '2d' ) ) !== null;
  13565. } catch ( err ) {
  13566. // Ignore any errors
  13567. }
  13568. function createCanvas( width, height ) {
  13569. // Use OffscreenCanvas when available. Specially needed in web workers
  13570. return useOffscreenCanvas ?
  13571. // eslint-disable-next-line compat/compat
  13572. new OffscreenCanvas( width, height ) : createElementNS( 'canvas' );
  13573. }
  13574. function resizeImage( image, needsPowerOfTwo, needsNewCanvas, maxSize ) {
  13575. let scale = 1;
  13576. // handle case if texture exceeds max size
  13577. if ( image.width > maxSize || image.height > maxSize ) {
  13578. scale = maxSize / Math.max( image.width, image.height );
  13579. }
  13580. // only perform resize if necessary
  13581. if ( scale < 1 || needsPowerOfTwo === true ) {
  13582. // only perform resize for certain image types
  13583. if ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) ||
  13584. ( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) ||
  13585. ( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) ) {
  13586. const floor = needsPowerOfTwo ? floorPowerOfTwo : Math.floor;
  13587. const width = floor( scale * image.width );
  13588. const height = floor( scale * image.height );
  13589. if ( _canvas === undefined ) _canvas = createCanvas( width, height );
  13590. // cube textures can't reuse the same canvas
  13591. const canvas = needsNewCanvas ? createCanvas( width, height ) : _canvas;
  13592. canvas.width = width;
  13593. canvas.height = height;
  13594. const context = canvas.getContext( '2d' );
  13595. context.drawImage( image, 0, 0, width, height );
  13596. console.warn( 'THREE.WebGLRenderer: Texture has been resized from (' + image.width + 'x' + image.height + ') to (' + width + 'x' + height + ').' );
  13597. return canvas;
  13598. } else {
  13599. if ( 'data' in image ) {
  13600. console.warn( 'THREE.WebGLRenderer: Image in DataTexture is too big (' + image.width + 'x' + image.height + ').' );
  13601. }
  13602. return image;
  13603. }
  13604. }
  13605. return image;
  13606. }
  13607. function isPowerOfTwo$1( image ) {
  13608. return isPowerOfTwo( image.width ) && isPowerOfTwo( image.height );
  13609. }
  13610. function textureNeedsPowerOfTwo( texture ) {
  13611. if ( isWebGL2 ) return false;
  13612. return ( texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping ) ||
  13613. ( texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter );
  13614. }
  13615. function textureNeedsGenerateMipmaps( texture, supportsMips ) {
  13616. return texture.generateMipmaps && supportsMips &&
  13617. texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter;
  13618. }
  13619. function generateMipmap( target ) {
  13620. _gl.generateMipmap( target );
  13621. }
  13622. function getInternalFormat( internalFormatName, glFormat, glType, encoding, forceLinearEncoding = false ) {
  13623. if ( isWebGL2 === false ) return glFormat;
  13624. if ( internalFormatName !== null ) {
  13625. if ( _gl[ internalFormatName ] !== undefined ) return _gl[ internalFormatName ];
  13626. console.warn( 'THREE.WebGLRenderer: Attempt to use non-existing WebGL internal format \'' + internalFormatName + '\'' );
  13627. }
  13628. let internalFormat = glFormat;
  13629. if ( glFormat === _gl.RED ) {
  13630. if ( glType === _gl.FLOAT ) internalFormat = _gl.R32F;
  13631. if ( glType === _gl.HALF_FLOAT ) internalFormat = _gl.R16F;
  13632. if ( glType === _gl.UNSIGNED_BYTE ) internalFormat = _gl.R8;
  13633. }
  13634. if ( glFormat === _gl.RG ) {
  13635. if ( glType === _gl.FLOAT ) internalFormat = _gl.RG32F;
  13636. if ( glType === _gl.HALF_FLOAT ) internalFormat = _gl.RG16F;
  13637. if ( glType === _gl.UNSIGNED_BYTE ) internalFormat = _gl.RG8;
  13638. }
  13639. if ( glFormat === _gl.RGBA ) {
  13640. if ( glType === _gl.FLOAT ) internalFormat = _gl.RGBA32F;
  13641. if ( glType === _gl.HALF_FLOAT ) internalFormat = _gl.RGBA16F;
  13642. if ( glType === _gl.UNSIGNED_BYTE ) internalFormat = ( encoding === sRGBEncoding && forceLinearEncoding === false ) ? _gl.SRGB8_ALPHA8 : _gl.RGBA8;
  13643. if ( glType === _gl.UNSIGNED_SHORT_4_4_4_4 ) internalFormat = _gl.RGBA4;
  13644. if ( glType === _gl.UNSIGNED_SHORT_5_5_5_1 ) internalFormat = _gl.RGB5_A1;
  13645. }
  13646. if ( internalFormat === _gl.R16F || internalFormat === _gl.R32F ||
  13647. internalFormat === _gl.RG16F || internalFormat === _gl.RG32F ||
  13648. internalFormat === _gl.RGBA16F || internalFormat === _gl.RGBA32F ) {
  13649. extensions.get( 'EXT_color_buffer_float' );
  13650. }
  13651. return internalFormat;
  13652. }
  13653. function getMipLevels( texture, image, supportsMips ) {
  13654. if ( textureNeedsGenerateMipmaps( texture, supportsMips ) === true || ( texture.isFramebufferTexture && texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter ) ) {
  13655. return Math.log2( Math.max( image.width, image.height ) ) + 1;
  13656. } else if ( texture.mipmaps !== undefined && texture.mipmaps.length > 0 ) {
  13657. // user-defined mipmaps
  13658. return texture.mipmaps.length;
  13659. } else if ( texture.isCompressedTexture && Array.isArray( texture.image ) ) {
  13660. return image.mipmaps.length;
  13661. } else {
  13662. // texture without mipmaps (only base level)
  13663. return 1;
  13664. }
  13665. }
  13666. // Fallback filters for non-power-of-2 textures
  13667. function filterFallback( f ) {
  13668. if ( f === NearestFilter || f === NearestMipmapNearestFilter || f === NearestMipmapLinearFilter ) {
  13669. return _gl.NEAREST;
  13670. }
  13671. return _gl.LINEAR;
  13672. }
  13673. //
  13674. function onTextureDispose( event ) {
  13675. const texture = event.target;
  13676. texture.removeEventListener( 'dispose', onTextureDispose );
  13677. deallocateTexture( texture );
  13678. if ( texture.isVideoTexture ) {
  13679. _videoTextures.delete( texture );
  13680. }
  13681. }
  13682. function onRenderTargetDispose( event ) {
  13683. const renderTarget = event.target;
  13684. renderTarget.removeEventListener( 'dispose', onRenderTargetDispose );
  13685. deallocateRenderTarget( renderTarget );
  13686. }
  13687. //
  13688. function deallocateTexture( texture ) {
  13689. const textureProperties = properties.get( texture );
  13690. if ( textureProperties.__webglInit === undefined ) return;
  13691. // check if it's necessary to remove the WebGLTexture object
  13692. const source = texture.source;
  13693. const webglTextures = _sources.get( source );
  13694. if ( webglTextures ) {
  13695. const webglTexture = webglTextures[ textureProperties.__cacheKey ];
  13696. webglTexture.usedTimes --;
  13697. // the WebGLTexture object is not used anymore, remove it
  13698. if ( webglTexture.usedTimes === 0 ) {
  13699. deleteTexture( texture );
  13700. }
  13701. // remove the weak map entry if no WebGLTexture uses the source anymore
  13702. if ( Object.keys( webglTextures ).length === 0 ) {
  13703. _sources.delete( source );
  13704. }
  13705. }
  13706. properties.remove( texture );
  13707. }
  13708. function deleteTexture( texture ) {
  13709. const textureProperties = properties.get( texture );
  13710. _gl.deleteTexture( textureProperties.__webglTexture );
  13711. const source = texture.source;
  13712. const webglTextures = _sources.get( source );
  13713. delete webglTextures[ textureProperties.__cacheKey ];
  13714. info.memory.textures --;
  13715. }
  13716. function deallocateRenderTarget( renderTarget ) {
  13717. const texture = renderTarget.texture;
  13718. const renderTargetProperties = properties.get( renderTarget );
  13719. const textureProperties = properties.get( texture );
  13720. if ( textureProperties.__webglTexture !== undefined ) {
  13721. _gl.deleteTexture( textureProperties.__webglTexture );
  13722. info.memory.textures --;
  13723. }
  13724. if ( renderTarget.depthTexture ) {
  13725. renderTarget.depthTexture.dispose();
  13726. }
  13727. if ( renderTarget.isWebGLCubeRenderTarget ) {
  13728. for ( let i = 0; i < 6; i ++ ) {
  13729. _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer[ i ] );
  13730. if ( renderTargetProperties.__webglDepthbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthbuffer[ i ] );
  13731. }
  13732. } else {
  13733. _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer );
  13734. if ( renderTargetProperties.__webglDepthbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthbuffer );
  13735. if ( renderTargetProperties.__webglMultisampledFramebuffer ) _gl.deleteFramebuffer( renderTargetProperties.__webglMultisampledFramebuffer );
  13736. if ( renderTargetProperties.__webglColorRenderbuffer ) {
  13737. for ( let i = 0; i < renderTargetProperties.__webglColorRenderbuffer.length; i ++ ) {
  13738. if ( renderTargetProperties.__webglColorRenderbuffer[ i ] ) _gl.deleteRenderbuffer( renderTargetProperties.__webglColorRenderbuffer[ i ] );
  13739. }
  13740. }
  13741. if ( renderTargetProperties.__webglDepthRenderbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthRenderbuffer );
  13742. }
  13743. if ( renderTarget.isWebGLMultipleRenderTargets ) {
  13744. for ( let i = 0, il = texture.length; i < il; i ++ ) {
  13745. const attachmentProperties = properties.get( texture[ i ] );
  13746. if ( attachmentProperties.__webglTexture ) {
  13747. _gl.deleteTexture( attachmentProperties.__webglTexture );
  13748. info.memory.textures --;
  13749. }
  13750. properties.remove( texture[ i ] );
  13751. }
  13752. }
  13753. properties.remove( texture );
  13754. properties.remove( renderTarget );
  13755. }
  13756. //
  13757. let textureUnits = 0;
  13758. function resetTextureUnits() {
  13759. textureUnits = 0;
  13760. }
  13761. function allocateTextureUnit() {
  13762. const textureUnit = textureUnits;
  13763. if ( textureUnit >= maxTextures ) {
  13764. console.warn( 'THREE.WebGLTextures: Trying to use ' + textureUnit + ' texture units while this GPU supports only ' + maxTextures );
  13765. }
  13766. textureUnits += 1;
  13767. return textureUnit;
  13768. }
  13769. function getTextureCacheKey( texture ) {
  13770. const array = [];
  13771. array.push( texture.wrapS );
  13772. array.push( texture.wrapT );
  13773. array.push( texture.wrapR || 0 );
  13774. array.push( texture.magFilter );
  13775. array.push( texture.minFilter );
  13776. array.push( texture.anisotropy );
  13777. array.push( texture.internalFormat );
  13778. array.push( texture.format );
  13779. array.push( texture.type );
  13780. array.push( texture.generateMipmaps );
  13781. array.push( texture.premultiplyAlpha );
  13782. array.push( texture.flipY );
  13783. array.push( texture.unpackAlignment );
  13784. array.push( texture.encoding );
  13785. return array.join();
  13786. }
  13787. //
  13788. function setTexture2D( texture, slot ) {
  13789. const textureProperties = properties.get( texture );
  13790. if ( texture.isVideoTexture ) updateVideoTexture( texture );
  13791. if ( texture.isRenderTargetTexture === false && texture.version > 0 && textureProperties.__version !== texture.version ) {
  13792. const image = texture.image;
  13793. if ( image === null ) {
  13794. console.warn( 'THREE.WebGLRenderer: Texture marked for update but no image data found.' );
  13795. } else if ( image.complete === false ) {
  13796. console.warn( 'THREE.WebGLRenderer: Texture marked for update but image is incomplete' );
  13797. } else {
  13798. uploadTexture( textureProperties, texture, slot );
  13799. return;
  13800. }
  13801. }
  13802. state.bindTexture( _gl.TEXTURE_2D, textureProperties.__webglTexture, _gl.TEXTURE0 + slot );
  13803. }
  13804. function setTexture2DArray( texture, slot ) {
  13805. const textureProperties = properties.get( texture );
  13806. if ( texture.version > 0 && textureProperties.__version !== texture.version ) {
  13807. uploadTexture( textureProperties, texture, slot );
  13808. return;
  13809. }
  13810. state.bindTexture( _gl.TEXTURE_2D_ARRAY, textureProperties.__webglTexture, _gl.TEXTURE0 + slot );
  13811. }
  13812. function setTexture3D( texture, slot ) {
  13813. const textureProperties = properties.get( texture );
  13814. if ( texture.version > 0 && textureProperties.__version !== texture.version ) {
  13815. uploadTexture( textureProperties, texture, slot );
  13816. return;
  13817. }
  13818. state.bindTexture( _gl.TEXTURE_3D, textureProperties.__webglTexture, _gl.TEXTURE0 + slot );
  13819. }
  13820. function setTextureCube( texture, slot ) {
  13821. const textureProperties = properties.get( texture );
  13822. if ( texture.version > 0 && textureProperties.__version !== texture.version ) {
  13823. uploadCubeTexture( textureProperties, texture, slot );
  13824. return;
  13825. }
  13826. state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture, _gl.TEXTURE0 + slot );
  13827. }
  13828. const wrappingToGL = {
  13829. [ RepeatWrapping ]: _gl.REPEAT,
  13830. [ ClampToEdgeWrapping ]: _gl.CLAMP_TO_EDGE,
  13831. [ MirroredRepeatWrapping ]: _gl.MIRRORED_REPEAT
  13832. };
  13833. const filterToGL = {
  13834. [ NearestFilter ]: _gl.NEAREST,
  13835. [ NearestMipmapNearestFilter ]: _gl.NEAREST_MIPMAP_NEAREST,
  13836. [ NearestMipmapLinearFilter ]: _gl.NEAREST_MIPMAP_LINEAR,
  13837. [ LinearFilter ]: _gl.LINEAR,
  13838. [ LinearMipmapNearestFilter ]: _gl.LINEAR_MIPMAP_NEAREST,
  13839. [ LinearMipmapLinearFilter ]: _gl.LINEAR_MIPMAP_LINEAR
  13840. };
  13841. function setTextureParameters( textureType, texture, supportsMips ) {
  13842. if ( supportsMips ) {
  13843. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, wrappingToGL[ texture.wrapS ] );
  13844. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, wrappingToGL[ texture.wrapT ] );
  13845. if ( textureType === _gl.TEXTURE_3D || textureType === _gl.TEXTURE_2D_ARRAY ) {
  13846. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_R, wrappingToGL[ texture.wrapR ] );
  13847. }
  13848. _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, filterToGL[ texture.magFilter ] );
  13849. _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, filterToGL[ texture.minFilter ] );
  13850. } else {
  13851. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE );
  13852. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE );
  13853. if ( textureType === _gl.TEXTURE_3D || textureType === _gl.TEXTURE_2D_ARRAY ) {
  13854. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_R, _gl.CLAMP_TO_EDGE );
  13855. }
  13856. if ( texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping ) {
  13857. console.warn( 'THREE.WebGLRenderer: Texture is not power of two. Texture.wrapS and Texture.wrapT should be set to THREE.ClampToEdgeWrapping.' );
  13858. }
  13859. _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, filterFallback( texture.magFilter ) );
  13860. _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, filterFallback( texture.minFilter ) );
  13861. if ( texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter ) {
  13862. console.warn( 'THREE.WebGLRenderer: Texture is not power of two. Texture.minFilter should be set to THREE.NearestFilter or THREE.LinearFilter.' );
  13863. }
  13864. }
  13865. if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) {
  13866. const extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  13867. if ( texture.magFilter === NearestFilter ) return;
  13868. if ( texture.minFilter !== NearestMipmapLinearFilter && texture.minFilter !== LinearMipmapLinearFilter ) return;
  13869. if ( texture.type === FloatType && extensions.has( 'OES_texture_float_linear' ) === false ) return; // verify extension for WebGL 1 and WebGL 2
  13870. if ( isWebGL2 === false && ( texture.type === HalfFloatType && extensions.has( 'OES_texture_half_float_linear' ) === false ) ) return; // verify extension for WebGL 1 only
  13871. if ( texture.anisotropy > 1 || properties.get( texture ).__currentAnisotropy ) {
  13872. _gl.texParameterf( textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, capabilities.getMaxAnisotropy() ) );
  13873. properties.get( texture ).__currentAnisotropy = texture.anisotropy;
  13874. }
  13875. }
  13876. }
  13877. function initTexture( textureProperties, texture ) {
  13878. let forceUpload = false;
  13879. if ( textureProperties.__webglInit === undefined ) {
  13880. textureProperties.__webglInit = true;
  13881. texture.addEventListener( 'dispose', onTextureDispose );
  13882. }
  13883. // create Source <-> WebGLTextures mapping if necessary
  13884. const source = texture.source;
  13885. let webglTextures = _sources.get( source );
  13886. if ( webglTextures === undefined ) {
  13887. webglTextures = {};
  13888. _sources.set( source, webglTextures );
  13889. }
  13890. // check if there is already a WebGLTexture object for the given texture parameters
  13891. const textureCacheKey = getTextureCacheKey( texture );
  13892. if ( textureCacheKey !== textureProperties.__cacheKey ) {
  13893. // if not, create a new instance of WebGLTexture
  13894. if ( webglTextures[ textureCacheKey ] === undefined ) {
  13895. // create new entry
  13896. webglTextures[ textureCacheKey ] = {
  13897. texture: _gl.createTexture(),
  13898. usedTimes: 0
  13899. };
  13900. info.memory.textures ++;
  13901. // when a new instance of WebGLTexture was created, a texture upload is required
  13902. // even if the image contents are identical
  13903. forceUpload = true;
  13904. }
  13905. webglTextures[ textureCacheKey ].usedTimes ++;
  13906. // every time the texture cache key changes, it's necessary to check if an instance of
  13907. // WebGLTexture can be deleted in order to avoid a memory leak.
  13908. const webglTexture = webglTextures[ textureProperties.__cacheKey ];
  13909. if ( webglTexture !== undefined ) {
  13910. webglTextures[ textureProperties.__cacheKey ].usedTimes --;
  13911. if ( webglTexture.usedTimes === 0 ) {
  13912. deleteTexture( texture );
  13913. }
  13914. }
  13915. // store references to cache key and WebGLTexture object
  13916. textureProperties.__cacheKey = textureCacheKey;
  13917. textureProperties.__webglTexture = webglTextures[ textureCacheKey ].texture;
  13918. }
  13919. return forceUpload;
  13920. }
  13921. function uploadTexture( textureProperties, texture, slot ) {
  13922. let textureType = _gl.TEXTURE_2D;
  13923. if ( texture.isDataArrayTexture || texture.isCompressedArrayTexture ) textureType = _gl.TEXTURE_2D_ARRAY;
  13924. if ( texture.isData3DTexture ) textureType = _gl.TEXTURE_3D;
  13925. const forceUpload = initTexture( textureProperties, texture );
  13926. const source = texture.source;
  13927. state.bindTexture( textureType, textureProperties.__webglTexture, _gl.TEXTURE0 + slot );
  13928. const sourceProperties = properties.get( source );
  13929. if ( source.version !== sourceProperties.__version || forceUpload === true ) {
  13930. state.activeTexture( _gl.TEXTURE0 + slot );
  13931. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  13932. _gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha );
  13933. _gl.pixelStorei( _gl.UNPACK_ALIGNMENT, texture.unpackAlignment );
  13934. _gl.pixelStorei( _gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, _gl.NONE );
  13935. const needsPowerOfTwo = textureNeedsPowerOfTwo( texture ) && isPowerOfTwo$1( texture.image ) === false;
  13936. let image = resizeImage( texture.image, needsPowerOfTwo, false, maxTextureSize );
  13937. image = verifyColorSpace( texture, image );
  13938. const supportsMips = isPowerOfTwo$1( image ) || isWebGL2,
  13939. glFormat = utils.convert( texture.format, texture.encoding );
  13940. let glType = utils.convert( texture.type ),
  13941. glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.encoding, texture.isVideoTexture );
  13942. setTextureParameters( textureType, texture, supportsMips );
  13943. let mipmap;
  13944. const mipmaps = texture.mipmaps;
  13945. const useTexStorage = ( isWebGL2 && texture.isVideoTexture !== true );
  13946. const allocateMemory = ( sourceProperties.__version === undefined ) || ( forceUpload === true );
  13947. const levels = getMipLevels( texture, image, supportsMips );
  13948. if ( texture.isDepthTexture ) {
  13949. // populate depth texture with dummy data
  13950. glInternalFormat = _gl.DEPTH_COMPONENT;
  13951. if ( isWebGL2 ) {
  13952. if ( texture.type === FloatType ) {
  13953. glInternalFormat = _gl.DEPTH_COMPONENT32F;
  13954. } else if ( texture.type === UnsignedIntType ) {
  13955. glInternalFormat = _gl.DEPTH_COMPONENT24;
  13956. } else if ( texture.type === UnsignedInt248Type ) {
  13957. glInternalFormat = _gl.DEPTH24_STENCIL8;
  13958. } else {
  13959. glInternalFormat = _gl.DEPTH_COMPONENT16; // WebGL2 requires sized internalformat for glTexImage2D
  13960. }
  13961. } else {
  13962. if ( texture.type === FloatType ) {
  13963. console.error( 'WebGLRenderer: Floating point depth texture requires WebGL2.' );
  13964. }
  13965. }
  13966. // validation checks for WebGL 1
  13967. if ( texture.format === DepthFormat && glInternalFormat === _gl.DEPTH_COMPONENT ) {
  13968. // The error INVALID_OPERATION is generated by texImage2D if format and internalformat are
  13969. // DEPTH_COMPONENT and type is not UNSIGNED_SHORT or UNSIGNED_INT
  13970. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  13971. if ( texture.type !== UnsignedShortType && texture.type !== UnsignedIntType ) {
  13972. console.warn( 'THREE.WebGLRenderer: Use UnsignedShortType or UnsignedIntType for DepthFormat DepthTexture.' );
  13973. texture.type = UnsignedIntType;
  13974. glType = utils.convert( texture.type );
  13975. }
  13976. }
  13977. if ( texture.format === DepthStencilFormat && glInternalFormat === _gl.DEPTH_COMPONENT ) {
  13978. // Depth stencil textures need the DEPTH_STENCIL internal format
  13979. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  13980. glInternalFormat = _gl.DEPTH_STENCIL;
  13981. // The error INVALID_OPERATION is generated by texImage2D if format and internalformat are
  13982. // DEPTH_STENCIL and type is not UNSIGNED_INT_24_8_WEBGL.
  13983. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  13984. if ( texture.type !== UnsignedInt248Type ) {
  13985. console.warn( 'THREE.WebGLRenderer: Use UnsignedInt248Type for DepthStencilFormat DepthTexture.' );
  13986. texture.type = UnsignedInt248Type;
  13987. glType = utils.convert( texture.type );
  13988. }
  13989. }
  13990. //
  13991. if ( allocateMemory ) {
  13992. if ( useTexStorage ) {
  13993. state.texStorage2D( _gl.TEXTURE_2D, 1, glInternalFormat, image.width, image.height );
  13994. } else {
  13995. state.texImage2D( _gl.TEXTURE_2D, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, null );
  13996. }
  13997. }
  13998. } else if ( texture.isDataTexture ) {
  13999. // use manually created mipmaps if available
  14000. // if there are no manual mipmaps
  14001. // set 0 level mipmap and then use GL to generate other mipmap levels
  14002. if ( mipmaps.length > 0 && supportsMips ) {
  14003. if ( useTexStorage && allocateMemory ) {
  14004. state.texStorage2D( _gl.TEXTURE_2D, levels, glInternalFormat, mipmaps[ 0 ].width, mipmaps[ 0 ].height );
  14005. }
  14006. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  14007. mipmap = mipmaps[ i ];
  14008. if ( useTexStorage ) {
  14009. state.texSubImage2D( _gl.TEXTURE_2D, i, 0, 0, mipmap.width, mipmap.height, glFormat, glType, mipmap.data );
  14010. } else {
  14011. state.texImage2D( _gl.TEXTURE_2D, i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  14012. }
  14013. }
  14014. texture.generateMipmaps = false;
  14015. } else {
  14016. if ( useTexStorage ) {
  14017. if ( allocateMemory ) {
  14018. state.texStorage2D( _gl.TEXTURE_2D, levels, glInternalFormat, image.width, image.height );
  14019. }
  14020. state.texSubImage2D( _gl.TEXTURE_2D, 0, 0, 0, image.width, image.height, glFormat, glType, image.data );
  14021. } else {
  14022. state.texImage2D( _gl.TEXTURE_2D, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, image.data );
  14023. }
  14024. }
  14025. } else if ( texture.isCompressedTexture ) {
  14026. if ( texture.isCompressedArrayTexture ) {
  14027. if ( useTexStorage && allocateMemory ) {
  14028. state.texStorage3D( _gl.TEXTURE_2D_ARRAY, levels, glInternalFormat, mipmaps[ 0 ].width, mipmaps[ 0 ].height, image.depth );
  14029. }
  14030. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  14031. mipmap = mipmaps[ i ];
  14032. if ( texture.format !== RGBAFormat ) {
  14033. if ( glFormat !== null ) {
  14034. if ( useTexStorage ) {
  14035. state.compressedTexSubImage3D( _gl.TEXTURE_2D_ARRAY, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, mipmap.data, 0, 0 );
  14036. } else {
  14037. state.compressedTexImage3D( _gl.TEXTURE_2D_ARRAY, i, glInternalFormat, mipmap.width, mipmap.height, image.depth, 0, mipmap.data, 0, 0 );
  14038. }
  14039. } else {
  14040. console.warn( 'THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()' );
  14041. }
  14042. } else {
  14043. if ( useTexStorage ) {
  14044. state.texSubImage3D( _gl.TEXTURE_2D_ARRAY, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, glType, mipmap.data );
  14045. } else {
  14046. state.texImage3D( _gl.TEXTURE_2D_ARRAY, i, glInternalFormat, mipmap.width, mipmap.height, image.depth, 0, glFormat, glType, mipmap.data );
  14047. }
  14048. }
  14049. }
  14050. } else {
  14051. if ( useTexStorage && allocateMemory ) {
  14052. state.texStorage2D( _gl.TEXTURE_2D, levels, glInternalFormat, mipmaps[ 0 ].width, mipmaps[ 0 ].height );
  14053. }
  14054. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  14055. mipmap = mipmaps[ i ];
  14056. if ( texture.format !== RGBAFormat ) {
  14057. if ( glFormat !== null ) {
  14058. if ( useTexStorage ) {
  14059. state.compressedTexSubImage2D( _gl.TEXTURE_2D, i, 0, 0, mipmap.width, mipmap.height, glFormat, mipmap.data );
  14060. } else {
  14061. state.compressedTexImage2D( _gl.TEXTURE_2D, i, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  14062. }
  14063. } else {
  14064. console.warn( 'THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()' );
  14065. }
  14066. } else {
  14067. if ( useTexStorage ) {
  14068. state.texSubImage2D( _gl.TEXTURE_2D, i, 0, 0, mipmap.width, mipmap.height, glFormat, glType, mipmap.data );
  14069. } else {
  14070. state.texImage2D( _gl.TEXTURE_2D, i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  14071. }
  14072. }
  14073. }
  14074. }
  14075. } else if ( texture.isDataArrayTexture ) {
  14076. if ( useTexStorage ) {
  14077. if ( allocateMemory ) {
  14078. state.texStorage3D( _gl.TEXTURE_2D_ARRAY, levels, glInternalFormat, image.width, image.height, image.depth );
  14079. }
  14080. state.texSubImage3D( _gl.TEXTURE_2D_ARRAY, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data );
  14081. } else {
  14082. state.texImage3D( _gl.TEXTURE_2D_ARRAY, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data );
  14083. }
  14084. } else if ( texture.isData3DTexture ) {
  14085. if ( useTexStorage ) {
  14086. if ( allocateMemory ) {
  14087. state.texStorage3D( _gl.TEXTURE_3D, levels, glInternalFormat, image.width, image.height, image.depth );
  14088. }
  14089. state.texSubImage3D( _gl.TEXTURE_3D, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data );
  14090. } else {
  14091. state.texImage3D( _gl.TEXTURE_3D, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data );
  14092. }
  14093. } else if ( texture.isFramebufferTexture ) {
  14094. if ( allocateMemory ) {
  14095. if ( useTexStorage ) {
  14096. state.texStorage2D( _gl.TEXTURE_2D, levels, glInternalFormat, image.width, image.height );
  14097. } else {
  14098. let width = image.width, height = image.height;
  14099. for ( let i = 0; i < levels; i ++ ) {
  14100. state.texImage2D( _gl.TEXTURE_2D, i, glInternalFormat, width, height, 0, glFormat, glType, null );
  14101. width >>= 1;
  14102. height >>= 1;
  14103. }
  14104. }
  14105. }
  14106. } else {
  14107. // regular Texture (image, video, canvas)
  14108. // use manually created mipmaps if available
  14109. // if there are no manual mipmaps
  14110. // set 0 level mipmap and then use GL to generate other mipmap levels
  14111. if ( mipmaps.length > 0 && supportsMips ) {
  14112. if ( useTexStorage && allocateMemory ) {
  14113. state.texStorage2D( _gl.TEXTURE_2D, levels, glInternalFormat, mipmaps[ 0 ].width, mipmaps[ 0 ].height );
  14114. }
  14115. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  14116. mipmap = mipmaps[ i ];
  14117. if ( useTexStorage ) {
  14118. state.texSubImage2D( _gl.TEXTURE_2D, i, 0, 0, glFormat, glType, mipmap );
  14119. } else {
  14120. state.texImage2D( _gl.TEXTURE_2D, i, glInternalFormat, glFormat, glType, mipmap );
  14121. }
  14122. }
  14123. texture.generateMipmaps = false;
  14124. } else {
  14125. if ( useTexStorage ) {
  14126. if ( allocateMemory ) {
  14127. state.texStorage2D( _gl.TEXTURE_2D, levels, glInternalFormat, image.width, image.height );
  14128. }
  14129. state.texSubImage2D( _gl.TEXTURE_2D, 0, 0, 0, glFormat, glType, image );
  14130. } else {
  14131. state.texImage2D( _gl.TEXTURE_2D, 0, glInternalFormat, glFormat, glType, image );
  14132. }
  14133. }
  14134. }
  14135. if ( textureNeedsGenerateMipmaps( texture, supportsMips ) ) {
  14136. generateMipmap( textureType );
  14137. }
  14138. sourceProperties.__version = source.version;
  14139. if ( texture.onUpdate ) texture.onUpdate( texture );
  14140. }
  14141. textureProperties.__version = texture.version;
  14142. }
  14143. function uploadCubeTexture( textureProperties, texture, slot ) {
  14144. if ( texture.image.length !== 6 ) return;
  14145. const forceUpload = initTexture( textureProperties, texture );
  14146. const source = texture.source;
  14147. state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture, _gl.TEXTURE0 + slot );
  14148. const sourceProperties = properties.get( source );
  14149. if ( source.version !== sourceProperties.__version || forceUpload === true ) {
  14150. state.activeTexture( _gl.TEXTURE0 + slot );
  14151. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  14152. _gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha );
  14153. _gl.pixelStorei( _gl.UNPACK_ALIGNMENT, texture.unpackAlignment );
  14154. _gl.pixelStorei( _gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, _gl.NONE );
  14155. const isCompressed = ( texture.isCompressedTexture || texture.image[ 0 ].isCompressedTexture );
  14156. const isDataTexture = ( texture.image[ 0 ] && texture.image[ 0 ].isDataTexture );
  14157. const cubeImage = [];
  14158. for ( let i = 0; i < 6; i ++ ) {
  14159. if ( ! isCompressed && ! isDataTexture ) {
  14160. cubeImage[ i ] = resizeImage( texture.image[ i ], false, true, maxCubemapSize );
  14161. } else {
  14162. cubeImage[ i ] = isDataTexture ? texture.image[ i ].image : texture.image[ i ];
  14163. }
  14164. cubeImage[ i ] = verifyColorSpace( texture, cubeImage[ i ] );
  14165. }
  14166. const image = cubeImage[ 0 ],
  14167. supportsMips = isPowerOfTwo$1( image ) || isWebGL2,
  14168. glFormat = utils.convert( texture.format, texture.encoding ),
  14169. glType = utils.convert( texture.type ),
  14170. glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.encoding );
  14171. const useTexStorage = ( isWebGL2 && texture.isVideoTexture !== true );
  14172. const allocateMemory = ( sourceProperties.__version === undefined ) || ( forceUpload === true );
  14173. let levels = getMipLevels( texture, image, supportsMips );
  14174. setTextureParameters( _gl.TEXTURE_CUBE_MAP, texture, supportsMips );
  14175. let mipmaps;
  14176. if ( isCompressed ) {
  14177. if ( useTexStorage && allocateMemory ) {
  14178. state.texStorage2D( _gl.TEXTURE_CUBE_MAP, levels, glInternalFormat, image.width, image.height );
  14179. }
  14180. for ( let i = 0; i < 6; i ++ ) {
  14181. mipmaps = cubeImage[ i ].mipmaps;
  14182. for ( let j = 0; j < mipmaps.length; j ++ ) {
  14183. const mipmap = mipmaps[ j ];
  14184. if ( texture.format !== RGBAFormat ) {
  14185. if ( glFormat !== null ) {
  14186. if ( useTexStorage ) {
  14187. state.compressedTexSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, 0, 0, mipmap.width, mipmap.height, glFormat, mipmap.data );
  14188. } else {
  14189. state.compressedTexImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  14190. }
  14191. } else {
  14192. console.warn( 'THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()' );
  14193. }
  14194. } else {
  14195. if ( useTexStorage ) {
  14196. state.texSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, 0, 0, mipmap.width, mipmap.height, glFormat, glType, mipmap.data );
  14197. } else {
  14198. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  14199. }
  14200. }
  14201. }
  14202. }
  14203. } else {
  14204. mipmaps = texture.mipmaps;
  14205. if ( useTexStorage && allocateMemory ) {
  14206. // TODO: Uniformly handle mipmap definitions
  14207. // Normal textures and compressed cube textures define base level + mips with their mipmap array
  14208. // Uncompressed cube textures use their mipmap array only for mips (no base level)
  14209. if ( mipmaps.length > 0 ) levels ++;
  14210. state.texStorage2D( _gl.TEXTURE_CUBE_MAP, levels, glInternalFormat, cubeImage[ 0 ].width, cubeImage[ 0 ].height );
  14211. }
  14212. for ( let i = 0; i < 6; i ++ ) {
  14213. if ( isDataTexture ) {
  14214. if ( useTexStorage ) {
  14215. state.texSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, 0, 0, cubeImage[ i ].width, cubeImage[ i ].height, glFormat, glType, cubeImage[ i ].data );
  14216. } else {
  14217. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glInternalFormat, cubeImage[ i ].width, cubeImage[ i ].height, 0, glFormat, glType, cubeImage[ i ].data );
  14218. }
  14219. for ( let j = 0; j < mipmaps.length; j ++ ) {
  14220. const mipmap = mipmaps[ j ];
  14221. const mipmapImage = mipmap.image[ i ].image;
  14222. if ( useTexStorage ) {
  14223. state.texSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, 0, 0, mipmapImage.width, mipmapImage.height, glFormat, glType, mipmapImage.data );
  14224. } else {
  14225. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, glInternalFormat, mipmapImage.width, mipmapImage.height, 0, glFormat, glType, mipmapImage.data );
  14226. }
  14227. }
  14228. } else {
  14229. if ( useTexStorage ) {
  14230. state.texSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, 0, 0, glFormat, glType, cubeImage[ i ] );
  14231. } else {
  14232. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glInternalFormat, glFormat, glType, cubeImage[ i ] );
  14233. }
  14234. for ( let j = 0; j < mipmaps.length; j ++ ) {
  14235. const mipmap = mipmaps[ j ];
  14236. if ( useTexStorage ) {
  14237. state.texSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, 0, 0, glFormat, glType, mipmap.image[ i ] );
  14238. } else {
  14239. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, glInternalFormat, glFormat, glType, mipmap.image[ i ] );
  14240. }
  14241. }
  14242. }
  14243. }
  14244. }
  14245. if ( textureNeedsGenerateMipmaps( texture, supportsMips ) ) {
  14246. // We assume images for cube map have the same size.
  14247. generateMipmap( _gl.TEXTURE_CUBE_MAP );
  14248. }
  14249. sourceProperties.__version = source.version;
  14250. if ( texture.onUpdate ) texture.onUpdate( texture );
  14251. }
  14252. textureProperties.__version = texture.version;
  14253. }
  14254. // Render targets
  14255. // Setup storage for target texture and bind it to correct framebuffer
  14256. function setupFrameBufferTexture( framebuffer, renderTarget, texture, attachment, textureTarget ) {
  14257. const glFormat = utils.convert( texture.format, texture.encoding );
  14258. const glType = utils.convert( texture.type );
  14259. const glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.encoding );
  14260. const renderTargetProperties = properties.get( renderTarget );
  14261. if ( ! renderTargetProperties.__hasExternalTextures ) {
  14262. if ( textureTarget === _gl.TEXTURE_3D || textureTarget === _gl.TEXTURE_2D_ARRAY ) {
  14263. state.texImage3D( textureTarget, 0, glInternalFormat, renderTarget.width, renderTarget.height, renderTarget.depth, 0, glFormat, glType, null );
  14264. } else {
  14265. state.texImage2D( textureTarget, 0, glInternalFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null );
  14266. }
  14267. }
  14268. state.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  14269. if ( useMultisampledRTT( renderTarget ) ) {
  14270. multisampledRTTExt.framebufferTexture2DMultisampleEXT( _gl.FRAMEBUFFER, attachment, textureTarget, properties.get( texture ).__webglTexture, 0, getRenderTargetSamples( renderTarget ) );
  14271. } else if ( textureTarget === _gl.TEXTURE_2D || ( textureTarget >= _gl.TEXTURE_CUBE_MAP_POSITIVE_X && textureTarget <= _gl.TEXTURE_CUBE_MAP_NEGATIVE_Z ) ) { // see #24753
  14272. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, attachment, textureTarget, properties.get( texture ).__webglTexture, 0 );
  14273. }
  14274. state.bindFramebuffer( _gl.FRAMEBUFFER, null );
  14275. }
  14276. // Setup storage for internal depth/stencil buffers and bind to correct framebuffer
  14277. function setupRenderBufferStorage( renderbuffer, renderTarget, isMultisample ) {
  14278. _gl.bindRenderbuffer( _gl.RENDERBUFFER, renderbuffer );
  14279. if ( renderTarget.depthBuffer && ! renderTarget.stencilBuffer ) {
  14280. let glInternalFormat = _gl.DEPTH_COMPONENT16;
  14281. if ( isMultisample || useMultisampledRTT( renderTarget ) ) {
  14282. const depthTexture = renderTarget.depthTexture;
  14283. if ( depthTexture && depthTexture.isDepthTexture ) {
  14284. if ( depthTexture.type === FloatType ) {
  14285. glInternalFormat = _gl.DEPTH_COMPONENT32F;
  14286. } else if ( depthTexture.type === UnsignedIntType ) {
  14287. glInternalFormat = _gl.DEPTH_COMPONENT24;
  14288. }
  14289. }
  14290. const samples = getRenderTargetSamples( renderTarget );
  14291. if ( useMultisampledRTT( renderTarget ) ) {
  14292. multisampledRTTExt.renderbufferStorageMultisampleEXT( _gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height );
  14293. } else {
  14294. _gl.renderbufferStorageMultisample( _gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height );
  14295. }
  14296. } else {
  14297. _gl.renderbufferStorage( _gl.RENDERBUFFER, glInternalFormat, renderTarget.width, renderTarget.height );
  14298. }
  14299. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  14300. } else if ( renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  14301. const samples = getRenderTargetSamples( renderTarget );
  14302. if ( isMultisample && useMultisampledRTT( renderTarget ) === false ) {
  14303. _gl.renderbufferStorageMultisample( _gl.RENDERBUFFER, samples, _gl.DEPTH24_STENCIL8, renderTarget.width, renderTarget.height );
  14304. } else if ( useMultisampledRTT( renderTarget ) ) {
  14305. multisampledRTTExt.renderbufferStorageMultisampleEXT( _gl.RENDERBUFFER, samples, _gl.DEPTH24_STENCIL8, renderTarget.width, renderTarget.height );
  14306. } else {
  14307. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_STENCIL, renderTarget.width, renderTarget.height );
  14308. }
  14309. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  14310. } else {
  14311. const textures = renderTarget.isWebGLMultipleRenderTargets === true ? renderTarget.texture : [ renderTarget.texture ];
  14312. for ( let i = 0; i < textures.length; i ++ ) {
  14313. const texture = textures[ i ];
  14314. const glFormat = utils.convert( texture.format, texture.encoding );
  14315. const glType = utils.convert( texture.type );
  14316. const glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.encoding );
  14317. const samples = getRenderTargetSamples( renderTarget );
  14318. if ( isMultisample && useMultisampledRTT( renderTarget ) === false ) {
  14319. _gl.renderbufferStorageMultisample( _gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height );
  14320. } else if ( useMultisampledRTT( renderTarget ) ) {
  14321. multisampledRTTExt.renderbufferStorageMultisampleEXT( _gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height );
  14322. } else {
  14323. _gl.renderbufferStorage( _gl.RENDERBUFFER, glInternalFormat, renderTarget.width, renderTarget.height );
  14324. }
  14325. }
  14326. }
  14327. _gl.bindRenderbuffer( _gl.RENDERBUFFER, null );
  14328. }
  14329. // Setup resources for a Depth Texture for a FBO (needs an extension)
  14330. function setupDepthTexture( framebuffer, renderTarget ) {
  14331. const isCube = ( renderTarget && renderTarget.isWebGLCubeRenderTarget );
  14332. if ( isCube ) throw new Error( 'Depth Texture with cube render targets is not supported' );
  14333. state.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  14334. if ( ! ( renderTarget.depthTexture && renderTarget.depthTexture.isDepthTexture ) ) {
  14335. throw new Error( 'renderTarget.depthTexture must be an instance of THREE.DepthTexture' );
  14336. }
  14337. // upload an empty depth texture with framebuffer size
  14338. if ( ! properties.get( renderTarget.depthTexture ).__webglTexture ||
  14339. renderTarget.depthTexture.image.width !== renderTarget.width ||
  14340. renderTarget.depthTexture.image.height !== renderTarget.height ) {
  14341. renderTarget.depthTexture.image.width = renderTarget.width;
  14342. renderTarget.depthTexture.image.height = renderTarget.height;
  14343. renderTarget.depthTexture.needsUpdate = true;
  14344. }
  14345. setTexture2D( renderTarget.depthTexture, 0 );
  14346. const webglDepthTexture = properties.get( renderTarget.depthTexture ).__webglTexture;
  14347. const samples = getRenderTargetSamples( renderTarget );
  14348. if ( renderTarget.depthTexture.format === DepthFormat ) {
  14349. if ( useMultisampledRTT( renderTarget ) ) {
  14350. multisampledRTTExt.framebufferTexture2DMultisampleEXT( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0, samples );
  14351. } else {
  14352. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0 );
  14353. }
  14354. } else if ( renderTarget.depthTexture.format === DepthStencilFormat ) {
  14355. if ( useMultisampledRTT( renderTarget ) ) {
  14356. multisampledRTTExt.framebufferTexture2DMultisampleEXT( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0, samples );
  14357. } else {
  14358. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0 );
  14359. }
  14360. } else {
  14361. throw new Error( 'Unknown depthTexture format' );
  14362. }
  14363. }
  14364. // Setup GL resources for a non-texture depth buffer
  14365. function setupDepthRenderbuffer( renderTarget ) {
  14366. const renderTargetProperties = properties.get( renderTarget );
  14367. const isCube = ( renderTarget.isWebGLCubeRenderTarget === true );
  14368. if ( renderTarget.depthTexture && ! renderTargetProperties.__autoAllocateDepthBuffer ) {
  14369. if ( isCube ) throw new Error( 'target.depthTexture not supported in Cube render targets' );
  14370. setupDepthTexture( renderTargetProperties.__webglFramebuffer, renderTarget );
  14371. } else {
  14372. if ( isCube ) {
  14373. renderTargetProperties.__webglDepthbuffer = [];
  14374. for ( let i = 0; i < 6; i ++ ) {
  14375. state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer[ i ] );
  14376. renderTargetProperties.__webglDepthbuffer[ i ] = _gl.createRenderbuffer();
  14377. setupRenderBufferStorage( renderTargetProperties.__webglDepthbuffer[ i ], renderTarget, false );
  14378. }
  14379. } else {
  14380. state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer );
  14381. renderTargetProperties.__webglDepthbuffer = _gl.createRenderbuffer();
  14382. setupRenderBufferStorage( renderTargetProperties.__webglDepthbuffer, renderTarget, false );
  14383. }
  14384. }
  14385. state.bindFramebuffer( _gl.FRAMEBUFFER, null );
  14386. }
  14387. // rebind framebuffer with external textures
  14388. function rebindTextures( renderTarget, colorTexture, depthTexture ) {
  14389. const renderTargetProperties = properties.get( renderTarget );
  14390. if ( colorTexture !== undefined ) {
  14391. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer, renderTarget, renderTarget.texture, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_2D );
  14392. }
  14393. if ( depthTexture !== undefined ) {
  14394. setupDepthRenderbuffer( renderTarget );
  14395. }
  14396. }
  14397. // Set up GL resources for the render target
  14398. function setupRenderTarget( renderTarget ) {
  14399. const texture = renderTarget.texture;
  14400. const renderTargetProperties = properties.get( renderTarget );
  14401. const textureProperties = properties.get( texture );
  14402. renderTarget.addEventListener( 'dispose', onRenderTargetDispose );
  14403. if ( renderTarget.isWebGLMultipleRenderTargets !== true ) {
  14404. if ( textureProperties.__webglTexture === undefined ) {
  14405. textureProperties.__webglTexture = _gl.createTexture();
  14406. }
  14407. textureProperties.__version = texture.version;
  14408. info.memory.textures ++;
  14409. }
  14410. const isCube = ( renderTarget.isWebGLCubeRenderTarget === true );
  14411. const isMultipleRenderTargets = ( renderTarget.isWebGLMultipleRenderTargets === true );
  14412. const supportsMips = isPowerOfTwo$1( renderTarget ) || isWebGL2;
  14413. // Setup framebuffer
  14414. if ( isCube ) {
  14415. renderTargetProperties.__webglFramebuffer = [];
  14416. for ( let i = 0; i < 6; i ++ ) {
  14417. renderTargetProperties.__webglFramebuffer[ i ] = _gl.createFramebuffer();
  14418. }
  14419. } else {
  14420. renderTargetProperties.__webglFramebuffer = _gl.createFramebuffer();
  14421. if ( isMultipleRenderTargets ) {
  14422. if ( capabilities.drawBuffers ) {
  14423. const textures = renderTarget.texture;
  14424. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  14425. const attachmentProperties = properties.get( textures[ i ] );
  14426. if ( attachmentProperties.__webglTexture === undefined ) {
  14427. attachmentProperties.__webglTexture = _gl.createTexture();
  14428. info.memory.textures ++;
  14429. }
  14430. }
  14431. } else {
  14432. console.warn( 'THREE.WebGLRenderer: WebGLMultipleRenderTargets can only be used with WebGL2 or WEBGL_draw_buffers extension.' );
  14433. }
  14434. }
  14435. if ( ( isWebGL2 && renderTarget.samples > 0 ) && useMultisampledRTT( renderTarget ) === false ) {
  14436. const textures = isMultipleRenderTargets ? texture : [ texture ];
  14437. renderTargetProperties.__webglMultisampledFramebuffer = _gl.createFramebuffer();
  14438. renderTargetProperties.__webglColorRenderbuffer = [];
  14439. state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer );
  14440. for ( let i = 0; i < textures.length; i ++ ) {
  14441. const texture = textures[ i ];
  14442. renderTargetProperties.__webglColorRenderbuffer[ i ] = _gl.createRenderbuffer();
  14443. _gl.bindRenderbuffer( _gl.RENDERBUFFER, renderTargetProperties.__webglColorRenderbuffer[ i ] );
  14444. const glFormat = utils.convert( texture.format, texture.encoding );
  14445. const glType = utils.convert( texture.type );
  14446. const glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.encoding, renderTarget.isXRRenderTarget === true );
  14447. const samples = getRenderTargetSamples( renderTarget );
  14448. _gl.renderbufferStorageMultisample( _gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height );
  14449. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.RENDERBUFFER, renderTargetProperties.__webglColorRenderbuffer[ i ] );
  14450. }
  14451. _gl.bindRenderbuffer( _gl.RENDERBUFFER, null );
  14452. if ( renderTarget.depthBuffer ) {
  14453. renderTargetProperties.__webglDepthRenderbuffer = _gl.createRenderbuffer();
  14454. setupRenderBufferStorage( renderTargetProperties.__webglDepthRenderbuffer, renderTarget, true );
  14455. }
  14456. state.bindFramebuffer( _gl.FRAMEBUFFER, null );
  14457. }
  14458. }
  14459. // Setup color buffer
  14460. if ( isCube ) {
  14461. state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture );
  14462. setTextureParameters( _gl.TEXTURE_CUBE_MAP, texture, supportsMips );
  14463. for ( let i = 0; i < 6; i ++ ) {
  14464. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer[ i ], renderTarget, texture, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i );
  14465. }
  14466. if ( textureNeedsGenerateMipmaps( texture, supportsMips ) ) {
  14467. generateMipmap( _gl.TEXTURE_CUBE_MAP );
  14468. }
  14469. state.unbindTexture();
  14470. } else if ( isMultipleRenderTargets ) {
  14471. const textures = renderTarget.texture;
  14472. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  14473. const attachment = textures[ i ];
  14474. const attachmentProperties = properties.get( attachment );
  14475. state.bindTexture( _gl.TEXTURE_2D, attachmentProperties.__webglTexture );
  14476. setTextureParameters( _gl.TEXTURE_2D, attachment, supportsMips );
  14477. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer, renderTarget, attachment, _gl.COLOR_ATTACHMENT0 + i, _gl.TEXTURE_2D );
  14478. if ( textureNeedsGenerateMipmaps( attachment, supportsMips ) ) {
  14479. generateMipmap( _gl.TEXTURE_2D );
  14480. }
  14481. }
  14482. state.unbindTexture();
  14483. } else {
  14484. let glTextureType = _gl.TEXTURE_2D;
  14485. if ( renderTarget.isWebGL3DRenderTarget || renderTarget.isWebGLArrayRenderTarget ) {
  14486. if ( isWebGL2 ) {
  14487. glTextureType = renderTarget.isWebGL3DRenderTarget ? _gl.TEXTURE_3D : _gl.TEXTURE_2D_ARRAY;
  14488. } else {
  14489. console.error( 'THREE.WebGLTextures: THREE.Data3DTexture and THREE.DataArrayTexture only supported with WebGL2.' );
  14490. }
  14491. }
  14492. state.bindTexture( glTextureType, textureProperties.__webglTexture );
  14493. setTextureParameters( glTextureType, texture, supportsMips );
  14494. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer, renderTarget, texture, _gl.COLOR_ATTACHMENT0, glTextureType );
  14495. if ( textureNeedsGenerateMipmaps( texture, supportsMips ) ) {
  14496. generateMipmap( glTextureType );
  14497. }
  14498. state.unbindTexture();
  14499. }
  14500. // Setup depth and stencil buffers
  14501. if ( renderTarget.depthBuffer ) {
  14502. setupDepthRenderbuffer( renderTarget );
  14503. }
  14504. }
  14505. function updateRenderTargetMipmap( renderTarget ) {
  14506. const supportsMips = isPowerOfTwo$1( renderTarget ) || isWebGL2;
  14507. const textures = renderTarget.isWebGLMultipleRenderTargets === true ? renderTarget.texture : [ renderTarget.texture ];
  14508. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  14509. const texture = textures[ i ];
  14510. if ( textureNeedsGenerateMipmaps( texture, supportsMips ) ) {
  14511. const target = renderTarget.isWebGLCubeRenderTarget ? _gl.TEXTURE_CUBE_MAP : _gl.TEXTURE_2D;
  14512. const webglTexture = properties.get( texture ).__webglTexture;
  14513. state.bindTexture( target, webglTexture );
  14514. generateMipmap( target );
  14515. state.unbindTexture();
  14516. }
  14517. }
  14518. }
  14519. function updateMultisampleRenderTarget( renderTarget ) {
  14520. if ( ( isWebGL2 && renderTarget.samples > 0 ) && useMultisampledRTT( renderTarget ) === false ) {
  14521. const textures = renderTarget.isWebGLMultipleRenderTargets ? renderTarget.texture : [ renderTarget.texture ];
  14522. const width = renderTarget.width;
  14523. const height = renderTarget.height;
  14524. let mask = _gl.COLOR_BUFFER_BIT;
  14525. const invalidationArray = [];
  14526. const depthStyle = renderTarget.stencilBuffer ? _gl.DEPTH_STENCIL_ATTACHMENT : _gl.DEPTH_ATTACHMENT;
  14527. const renderTargetProperties = properties.get( renderTarget );
  14528. const isMultipleRenderTargets = ( renderTarget.isWebGLMultipleRenderTargets === true );
  14529. // If MRT we need to remove FBO attachments
  14530. if ( isMultipleRenderTargets ) {
  14531. for ( let i = 0; i < textures.length; i ++ ) {
  14532. state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer );
  14533. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.RENDERBUFFER, null );
  14534. state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer );
  14535. _gl.framebufferTexture2D( _gl.DRAW_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.TEXTURE_2D, null, 0 );
  14536. }
  14537. }
  14538. state.bindFramebuffer( _gl.READ_FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer );
  14539. state.bindFramebuffer( _gl.DRAW_FRAMEBUFFER, renderTargetProperties.__webglFramebuffer );
  14540. for ( let i = 0; i < textures.length; i ++ ) {
  14541. invalidationArray.push( _gl.COLOR_ATTACHMENT0 + i );
  14542. if ( renderTarget.depthBuffer ) {
  14543. invalidationArray.push( depthStyle );
  14544. }
  14545. const ignoreDepthValues = ( renderTargetProperties.__ignoreDepthValues !== undefined ) ? renderTargetProperties.__ignoreDepthValues : false;
  14546. if ( ignoreDepthValues === false ) {
  14547. if ( renderTarget.depthBuffer ) mask |= _gl.DEPTH_BUFFER_BIT;
  14548. if ( renderTarget.stencilBuffer ) mask |= _gl.STENCIL_BUFFER_BIT;
  14549. }
  14550. if ( isMultipleRenderTargets ) {
  14551. _gl.framebufferRenderbuffer( _gl.READ_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.RENDERBUFFER, renderTargetProperties.__webglColorRenderbuffer[ i ] );
  14552. }
  14553. if ( ignoreDepthValues === true ) {
  14554. _gl.invalidateFramebuffer( _gl.READ_FRAMEBUFFER, [ depthStyle ] );
  14555. _gl.invalidateFramebuffer( _gl.DRAW_FRAMEBUFFER, [ depthStyle ] );
  14556. }
  14557. if ( isMultipleRenderTargets ) {
  14558. const webglTexture = properties.get( textures[ i ] ).__webglTexture;
  14559. _gl.framebufferTexture2D( _gl.DRAW_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_2D, webglTexture, 0 );
  14560. }
  14561. _gl.blitFramebuffer( 0, 0, width, height, 0, 0, width, height, mask, _gl.NEAREST );
  14562. if ( supportsInvalidateFramebuffer ) {
  14563. _gl.invalidateFramebuffer( _gl.READ_FRAMEBUFFER, invalidationArray );
  14564. }
  14565. }
  14566. state.bindFramebuffer( _gl.READ_FRAMEBUFFER, null );
  14567. state.bindFramebuffer( _gl.DRAW_FRAMEBUFFER, null );
  14568. // If MRT since pre-blit we removed the FBO we need to reconstruct the attachments
  14569. if ( isMultipleRenderTargets ) {
  14570. for ( let i = 0; i < textures.length; i ++ ) {
  14571. state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer );
  14572. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.RENDERBUFFER, renderTargetProperties.__webglColorRenderbuffer[ i ] );
  14573. const webglTexture = properties.get( textures[ i ] ).__webglTexture;
  14574. state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer );
  14575. _gl.framebufferTexture2D( _gl.DRAW_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.TEXTURE_2D, webglTexture, 0 );
  14576. }
  14577. }
  14578. state.bindFramebuffer( _gl.DRAW_FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer );
  14579. }
  14580. }
  14581. function getRenderTargetSamples( renderTarget ) {
  14582. return Math.min( maxSamples, renderTarget.samples );
  14583. }
  14584. function useMultisampledRTT( renderTarget ) {
  14585. const renderTargetProperties = properties.get( renderTarget );
  14586. return isWebGL2 && renderTarget.samples > 0 && extensions.has( 'WEBGL_multisampled_render_to_texture' ) === true && renderTargetProperties.__useRenderToTexture !== false;
  14587. }
  14588. function updateVideoTexture( texture ) {
  14589. const frame = info.render.frame;
  14590. // Check the last frame we updated the VideoTexture
  14591. if ( _videoTextures.get( texture ) !== frame ) {
  14592. _videoTextures.set( texture, frame );
  14593. texture.update();
  14594. }
  14595. }
  14596. function verifyColorSpace( texture, image ) {
  14597. const encoding = texture.encoding;
  14598. const format = texture.format;
  14599. const type = texture.type;
  14600. if ( texture.isCompressedTexture === true || texture.isVideoTexture === true || texture.format === _SRGBAFormat ) return image;
  14601. if ( encoding !== LinearEncoding ) {
  14602. // sRGB
  14603. if ( encoding === sRGBEncoding ) {
  14604. if ( isWebGL2 === false ) {
  14605. // in WebGL 1, try to use EXT_sRGB extension and unsized formats
  14606. if ( extensions.has( 'EXT_sRGB' ) === true && format === RGBAFormat ) {
  14607. texture.format = _SRGBAFormat;
  14608. // it's not possible to generate mips in WebGL 1 with this extension
  14609. texture.minFilter = LinearFilter;
  14610. texture.generateMipmaps = false;
  14611. } else {
  14612. // slow fallback (CPU decode)
  14613. image = ImageUtils.sRGBToLinear( image );
  14614. }
  14615. } else {
  14616. // in WebGL 2 uncompressed textures can only be sRGB encoded if they have the RGBA8 format
  14617. if ( format !== RGBAFormat || type !== UnsignedByteType ) {
  14618. console.warn( 'THREE.WebGLTextures: sRGB encoded textures have to use RGBAFormat and UnsignedByteType.' );
  14619. }
  14620. }
  14621. } else {
  14622. console.error( 'THREE.WebGLTextures: Unsupported texture encoding:', encoding );
  14623. }
  14624. }
  14625. return image;
  14626. }
  14627. //
  14628. this.allocateTextureUnit = allocateTextureUnit;
  14629. this.resetTextureUnits = resetTextureUnits;
  14630. this.setTexture2D = setTexture2D;
  14631. this.setTexture2DArray = setTexture2DArray;
  14632. this.setTexture3D = setTexture3D;
  14633. this.setTextureCube = setTextureCube;
  14634. this.rebindTextures = rebindTextures;
  14635. this.setupRenderTarget = setupRenderTarget;
  14636. this.updateRenderTargetMipmap = updateRenderTargetMipmap;
  14637. this.updateMultisampleRenderTarget = updateMultisampleRenderTarget;
  14638. this.setupDepthRenderbuffer = setupDepthRenderbuffer;
  14639. this.setupFrameBufferTexture = setupFrameBufferTexture;
  14640. this.useMultisampledRTT = useMultisampledRTT;
  14641. }
  14642. function WebGLUtils( gl, extensions, capabilities ) {
  14643. const isWebGL2 = capabilities.isWebGL2;
  14644. function convert( p, encoding = null ) {
  14645. let extension;
  14646. if ( p === UnsignedByteType ) return gl.UNSIGNED_BYTE;
  14647. if ( p === UnsignedShort4444Type ) return gl.UNSIGNED_SHORT_4_4_4_4;
  14648. if ( p === UnsignedShort5551Type ) return gl.UNSIGNED_SHORT_5_5_5_1;
  14649. if ( p === ByteType ) return gl.BYTE;
  14650. if ( p === ShortType ) return gl.SHORT;
  14651. if ( p === UnsignedShortType ) return gl.UNSIGNED_SHORT;
  14652. if ( p === IntType ) return gl.INT;
  14653. if ( p === UnsignedIntType ) return gl.UNSIGNED_INT;
  14654. if ( p === FloatType ) return gl.FLOAT;
  14655. if ( p === HalfFloatType ) {
  14656. if ( isWebGL2 ) return gl.HALF_FLOAT;
  14657. extension = extensions.get( 'OES_texture_half_float' );
  14658. if ( extension !== null ) {
  14659. return extension.HALF_FLOAT_OES;
  14660. } else {
  14661. return null;
  14662. }
  14663. }
  14664. if ( p === AlphaFormat ) return gl.ALPHA;
  14665. if ( p === RGBAFormat ) return gl.RGBA;
  14666. if ( p === LuminanceFormat ) return gl.LUMINANCE;
  14667. if ( p === LuminanceAlphaFormat ) return gl.LUMINANCE_ALPHA;
  14668. if ( p === DepthFormat ) return gl.DEPTH_COMPONENT;
  14669. if ( p === DepthStencilFormat ) return gl.DEPTH_STENCIL;
  14670. // WebGL 1 sRGB fallback
  14671. if ( p === _SRGBAFormat ) {
  14672. extension = extensions.get( 'EXT_sRGB' );
  14673. if ( extension !== null ) {
  14674. return extension.SRGB_ALPHA_EXT;
  14675. } else {
  14676. return null;
  14677. }
  14678. }
  14679. // WebGL2 formats.
  14680. if ( p === RedFormat ) return gl.RED;
  14681. if ( p === RedIntegerFormat ) return gl.RED_INTEGER;
  14682. if ( p === RGFormat ) return gl.RG;
  14683. if ( p === RGIntegerFormat ) return gl.RG_INTEGER;
  14684. if ( p === RGBAIntegerFormat ) return gl.RGBA_INTEGER;
  14685. // S3TC
  14686. if ( p === RGB_S3TC_DXT1_Format || p === RGBA_S3TC_DXT1_Format || p === RGBA_S3TC_DXT3_Format || p === RGBA_S3TC_DXT5_Format ) {
  14687. if ( encoding === sRGBEncoding ) {
  14688. extension = extensions.get( 'WEBGL_compressed_texture_s3tc_srgb' );
  14689. if ( extension !== null ) {
  14690. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_SRGB_S3TC_DXT1_EXT;
  14691. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;
  14692. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;
  14693. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT;
  14694. } else {
  14695. return null;
  14696. }
  14697. } else {
  14698. extension = extensions.get( 'WEBGL_compressed_texture_s3tc' );
  14699. if ( extension !== null ) {
  14700. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_RGB_S3TC_DXT1_EXT;
  14701. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  14702. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  14703. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  14704. } else {
  14705. return null;
  14706. }
  14707. }
  14708. }
  14709. // PVRTC
  14710. if ( p === RGB_PVRTC_4BPPV1_Format || p === RGB_PVRTC_2BPPV1_Format || p === RGBA_PVRTC_4BPPV1_Format || p === RGBA_PVRTC_2BPPV1_Format ) {
  14711. extension = extensions.get( 'WEBGL_compressed_texture_pvrtc' );
  14712. if ( extension !== null ) {
  14713. if ( p === RGB_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
  14714. if ( p === RGB_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
  14715. if ( p === RGBA_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
  14716. if ( p === RGBA_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
  14717. } else {
  14718. return null;
  14719. }
  14720. }
  14721. // ETC1
  14722. if ( p === RGB_ETC1_Format ) {
  14723. extension = extensions.get( 'WEBGL_compressed_texture_etc1' );
  14724. if ( extension !== null ) {
  14725. return extension.COMPRESSED_RGB_ETC1_WEBGL;
  14726. } else {
  14727. return null;
  14728. }
  14729. }
  14730. // ETC2
  14731. if ( p === RGB_ETC2_Format || p === RGBA_ETC2_EAC_Format ) {
  14732. extension = extensions.get( 'WEBGL_compressed_texture_etc' );
  14733. if ( extension !== null ) {
  14734. if ( p === RGB_ETC2_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ETC2 : extension.COMPRESSED_RGB8_ETC2;
  14735. if ( p === RGBA_ETC2_EAC_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC : extension.COMPRESSED_RGBA8_ETC2_EAC;
  14736. } else {
  14737. return null;
  14738. }
  14739. }
  14740. // ASTC
  14741. if ( p === RGBA_ASTC_4x4_Format || p === RGBA_ASTC_5x4_Format || p === RGBA_ASTC_5x5_Format ||
  14742. p === RGBA_ASTC_6x5_Format || p === RGBA_ASTC_6x6_Format || p === RGBA_ASTC_8x5_Format ||
  14743. p === RGBA_ASTC_8x6_Format || p === RGBA_ASTC_8x8_Format || p === RGBA_ASTC_10x5_Format ||
  14744. p === RGBA_ASTC_10x6_Format || p === RGBA_ASTC_10x8_Format || p === RGBA_ASTC_10x10_Format ||
  14745. p === RGBA_ASTC_12x10_Format || p === RGBA_ASTC_12x12_Format ) {
  14746. extension = extensions.get( 'WEBGL_compressed_texture_astc' );
  14747. if ( extension !== null ) {
  14748. if ( p === RGBA_ASTC_4x4_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR : extension.COMPRESSED_RGBA_ASTC_4x4_KHR;
  14749. if ( p === RGBA_ASTC_5x4_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR : extension.COMPRESSED_RGBA_ASTC_5x4_KHR;
  14750. if ( p === RGBA_ASTC_5x5_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR : extension.COMPRESSED_RGBA_ASTC_5x5_KHR;
  14751. if ( p === RGBA_ASTC_6x5_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR : extension.COMPRESSED_RGBA_ASTC_6x5_KHR;
  14752. if ( p === RGBA_ASTC_6x6_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR : extension.COMPRESSED_RGBA_ASTC_6x6_KHR;
  14753. if ( p === RGBA_ASTC_8x5_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR : extension.COMPRESSED_RGBA_ASTC_8x5_KHR;
  14754. if ( p === RGBA_ASTC_8x6_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR : extension.COMPRESSED_RGBA_ASTC_8x6_KHR;
  14755. if ( p === RGBA_ASTC_8x8_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR : extension.COMPRESSED_RGBA_ASTC_8x8_KHR;
  14756. if ( p === RGBA_ASTC_10x5_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR : extension.COMPRESSED_RGBA_ASTC_10x5_KHR;
  14757. if ( p === RGBA_ASTC_10x6_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR : extension.COMPRESSED_RGBA_ASTC_10x6_KHR;
  14758. if ( p === RGBA_ASTC_10x8_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR : extension.COMPRESSED_RGBA_ASTC_10x8_KHR;
  14759. if ( p === RGBA_ASTC_10x10_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR : extension.COMPRESSED_RGBA_ASTC_10x10_KHR;
  14760. if ( p === RGBA_ASTC_12x10_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR : extension.COMPRESSED_RGBA_ASTC_12x10_KHR;
  14761. if ( p === RGBA_ASTC_12x12_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR : extension.COMPRESSED_RGBA_ASTC_12x12_KHR;
  14762. } else {
  14763. return null;
  14764. }
  14765. }
  14766. // BPTC
  14767. if ( p === RGBA_BPTC_Format ) {
  14768. extension = extensions.get( 'EXT_texture_compression_bptc' );
  14769. if ( extension !== null ) {
  14770. if ( p === RGBA_BPTC_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT : extension.COMPRESSED_RGBA_BPTC_UNORM_EXT;
  14771. } else {
  14772. return null;
  14773. }
  14774. }
  14775. // RGTC
  14776. if ( p === RED_RGTC1_Format || p === SIGNED_RED_RGTC1_Format || p === RED_GREEN_RGTC2_Format || p === SIGNED_RED_GREEN_RGTC2_Format ) {
  14777. extension = extensions.get( 'EXT_texture_compression_rgtc' );
  14778. if ( extension !== null ) {
  14779. if ( p === RGBA_BPTC_Format ) return extension.COMPRESSED_RED_RGTC1_EXT;
  14780. if ( p === SIGNED_RED_RGTC1_Format ) return extension.COMPRESSED_SIGNED_RED_RGTC1_EXT;
  14781. if ( p === RED_GREEN_RGTC2_Format ) return extension.COMPRESSED_RED_GREEN_RGTC2_EXT;
  14782. if ( p === SIGNED_RED_GREEN_RGTC2_Format ) return extension.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT;
  14783. } else {
  14784. return null;
  14785. }
  14786. }
  14787. //
  14788. if ( p === UnsignedInt248Type ) {
  14789. if ( isWebGL2 ) return gl.UNSIGNED_INT_24_8;
  14790. extension = extensions.get( 'WEBGL_depth_texture' );
  14791. if ( extension !== null ) {
  14792. return extension.UNSIGNED_INT_24_8_WEBGL;
  14793. } else {
  14794. return null;
  14795. }
  14796. }
  14797. // if "p" can't be resolved, assume the user defines a WebGL constant as a string (fallback/workaround for packed RGB formats)
  14798. return ( gl[ p ] !== undefined ) ? gl[ p ] : null;
  14799. }
  14800. return { convert: convert };
  14801. }
  14802. class ArrayCamera extends PerspectiveCamera {
  14803. constructor( array = [] ) {
  14804. super();
  14805. this.isArrayCamera = true;
  14806. this.cameras = array;
  14807. }
  14808. }
  14809. class Group extends Object3D {
  14810. constructor() {
  14811. super();
  14812. this.isGroup = true;
  14813. this.type = 'Group';
  14814. }
  14815. }
  14816. const _moveEvent = { type: 'move' };
  14817. class WebXRController {
  14818. constructor() {
  14819. this._targetRay = null;
  14820. this._grip = null;
  14821. this._hand = null;
  14822. }
  14823. getHandSpace() {
  14824. if ( this._hand === null ) {
  14825. this._hand = new Group();
  14826. this._hand.matrixAutoUpdate = false;
  14827. this._hand.visible = false;
  14828. this._hand.joints = {};
  14829. this._hand.inputState = { pinching: false };
  14830. }
  14831. return this._hand;
  14832. }
  14833. getTargetRaySpace() {
  14834. if ( this._targetRay === null ) {
  14835. this._targetRay = new Group();
  14836. this._targetRay.matrixAutoUpdate = false;
  14837. this._targetRay.visible = false;
  14838. this._targetRay.hasLinearVelocity = false;
  14839. this._targetRay.linearVelocity = new Vector3();
  14840. this._targetRay.hasAngularVelocity = false;
  14841. this._targetRay.angularVelocity = new Vector3();
  14842. }
  14843. return this._targetRay;
  14844. }
  14845. getGripSpace() {
  14846. if ( this._grip === null ) {
  14847. this._grip = new Group();
  14848. this._grip.matrixAutoUpdate = false;
  14849. this._grip.visible = false;
  14850. this._grip.hasLinearVelocity = false;
  14851. this._grip.linearVelocity = new Vector3();
  14852. this._grip.hasAngularVelocity = false;
  14853. this._grip.angularVelocity = new Vector3();
  14854. }
  14855. return this._grip;
  14856. }
  14857. dispatchEvent( event ) {
  14858. if ( this._targetRay !== null ) {
  14859. this._targetRay.dispatchEvent( event );
  14860. }
  14861. if ( this._grip !== null ) {
  14862. this._grip.dispatchEvent( event );
  14863. }
  14864. if ( this._hand !== null ) {
  14865. this._hand.dispatchEvent( event );
  14866. }
  14867. return this;
  14868. }
  14869. connect( inputSource ) {
  14870. if ( inputSource && inputSource.hand ) {
  14871. const hand = this._hand;
  14872. if ( hand ) {
  14873. for ( const inputjoint of inputSource.hand.values() ) {
  14874. // Initialize hand with joints when connected
  14875. this._getHandJoint( hand, inputjoint );
  14876. }
  14877. }
  14878. }
  14879. this.dispatchEvent( { type: 'connected', data: inputSource } );
  14880. return this;
  14881. }
  14882. disconnect( inputSource ) {
  14883. this.dispatchEvent( { type: 'disconnected', data: inputSource } );
  14884. if ( this._targetRay !== null ) {
  14885. this._targetRay.visible = false;
  14886. }
  14887. if ( this._grip !== null ) {
  14888. this._grip.visible = false;
  14889. }
  14890. if ( this._hand !== null ) {
  14891. this._hand.visible = false;
  14892. }
  14893. return this;
  14894. }
  14895. update( inputSource, frame, referenceSpace ) {
  14896. let inputPose = null;
  14897. let gripPose = null;
  14898. let handPose = null;
  14899. const targetRay = this._targetRay;
  14900. const grip = this._grip;
  14901. const hand = this._hand;
  14902. if ( inputSource && frame.session.visibilityState !== 'visible-blurred' ) {
  14903. if ( hand && inputSource.hand ) {
  14904. handPose = true;
  14905. for ( const inputjoint of inputSource.hand.values() ) {
  14906. // Update the joints groups with the XRJoint poses
  14907. const jointPose = frame.getJointPose( inputjoint, referenceSpace );
  14908. // The transform of this joint will be updated with the joint pose on each frame
  14909. const joint = this._getHandJoint( hand, inputjoint );
  14910. if ( jointPose !== null ) {
  14911. joint.matrix.fromArray( jointPose.transform.matrix );
  14912. joint.matrix.decompose( joint.position, joint.rotation, joint.scale );
  14913. joint.jointRadius = jointPose.radius;
  14914. }
  14915. joint.visible = jointPose !== null;
  14916. }
  14917. // Custom events
  14918. // Check pinchz
  14919. const indexTip = hand.joints[ 'index-finger-tip' ];
  14920. const thumbTip = hand.joints[ 'thumb-tip' ];
  14921. const distance = indexTip.position.distanceTo( thumbTip.position );
  14922. const distanceToPinch = 0.02;
  14923. const threshold = 0.005;
  14924. if ( hand.inputState.pinching && distance > distanceToPinch + threshold ) {
  14925. hand.inputState.pinching = false;
  14926. this.dispatchEvent( {
  14927. type: 'pinchend',
  14928. handedness: inputSource.handedness,
  14929. target: this
  14930. } );
  14931. } else if ( ! hand.inputState.pinching && distance <= distanceToPinch - threshold ) {
  14932. hand.inputState.pinching = true;
  14933. this.dispatchEvent( {
  14934. type: 'pinchstart',
  14935. handedness: inputSource.handedness,
  14936. target: this
  14937. } );
  14938. }
  14939. } else {
  14940. if ( grip !== null && inputSource.gripSpace ) {
  14941. gripPose = frame.getPose( inputSource.gripSpace, referenceSpace );
  14942. if ( gripPose !== null ) {
  14943. grip.matrix.fromArray( gripPose.transform.matrix );
  14944. grip.matrix.decompose( grip.position, grip.rotation, grip.scale );
  14945. if ( gripPose.linearVelocity ) {
  14946. grip.hasLinearVelocity = true;
  14947. grip.linearVelocity.copy( gripPose.linearVelocity );
  14948. } else {
  14949. grip.hasLinearVelocity = false;
  14950. }
  14951. if ( gripPose.angularVelocity ) {
  14952. grip.hasAngularVelocity = true;
  14953. grip.angularVelocity.copy( gripPose.angularVelocity );
  14954. } else {
  14955. grip.hasAngularVelocity = false;
  14956. }
  14957. }
  14958. }
  14959. }
  14960. if ( targetRay !== null ) {
  14961. inputPose = frame.getPose( inputSource.targetRaySpace, referenceSpace );
  14962. // Some runtimes (namely Vive Cosmos with Vive OpenXR Runtime) have only grip space and ray space is equal to it
  14963. if ( inputPose === null && gripPose !== null ) {
  14964. inputPose = gripPose;
  14965. }
  14966. if ( inputPose !== null ) {
  14967. targetRay.matrix.fromArray( inputPose.transform.matrix );
  14968. targetRay.matrix.decompose( targetRay.position, targetRay.rotation, targetRay.scale );
  14969. if ( inputPose.linearVelocity ) {
  14970. targetRay.hasLinearVelocity = true;
  14971. targetRay.linearVelocity.copy( inputPose.linearVelocity );
  14972. } else {
  14973. targetRay.hasLinearVelocity = false;
  14974. }
  14975. if ( inputPose.angularVelocity ) {
  14976. targetRay.hasAngularVelocity = true;
  14977. targetRay.angularVelocity.copy( inputPose.angularVelocity );
  14978. } else {
  14979. targetRay.hasAngularVelocity = false;
  14980. }
  14981. this.dispatchEvent( _moveEvent );
  14982. }
  14983. }
  14984. }
  14985. if ( targetRay !== null ) {
  14986. targetRay.visible = ( inputPose !== null );
  14987. }
  14988. if ( grip !== null ) {
  14989. grip.visible = ( gripPose !== null );
  14990. }
  14991. if ( hand !== null ) {
  14992. hand.visible = ( handPose !== null );
  14993. }
  14994. return this;
  14995. }
  14996. // private method
  14997. _getHandJoint( hand, inputjoint ) {
  14998. if ( hand.joints[ inputjoint.jointName ] === undefined ) {
  14999. const joint = new Group();
  15000. joint.matrixAutoUpdate = false;
  15001. joint.visible = false;
  15002. hand.joints[ inputjoint.jointName ] = joint;
  15003. hand.add( joint );
  15004. }
  15005. return hand.joints[ inputjoint.jointName ];
  15006. }
  15007. }
  15008. class DepthTexture extends Texture {
  15009. constructor( width, height, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, format ) {
  15010. format = format !== undefined ? format : DepthFormat;
  15011. if ( format !== DepthFormat && format !== DepthStencilFormat ) {
  15012. throw new Error( 'DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat' );
  15013. }
  15014. if ( type === undefined && format === DepthFormat ) type = UnsignedIntType;
  15015. if ( type === undefined && format === DepthStencilFormat ) type = UnsignedInt248Type;
  15016. super( null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  15017. this.isDepthTexture = true;
  15018. this.image = { width: width, height: height };
  15019. this.magFilter = magFilter !== undefined ? magFilter : NearestFilter;
  15020. this.minFilter = minFilter !== undefined ? minFilter : NearestFilter;
  15021. this.flipY = false;
  15022. this.generateMipmaps = false;
  15023. }
  15024. }
  15025. class WebXRManager extends EventDispatcher {
  15026. constructor( renderer, gl ) {
  15027. super();
  15028. const scope = this;
  15029. let session = null;
  15030. let framebufferScaleFactor = 1.0;
  15031. let referenceSpace = null;
  15032. let referenceSpaceType = 'local-floor';
  15033. // Set default foveation to maximum.
  15034. let foveation = 1.0;
  15035. let customReferenceSpace = null;
  15036. let pose = null;
  15037. let glBinding = null;
  15038. let glProjLayer = null;
  15039. let glBaseLayer = null;
  15040. let xrFrame = null;
  15041. const attributes = gl.getContextAttributes();
  15042. let initialRenderTarget = null;
  15043. let newRenderTarget = null;
  15044. const controllers = [];
  15045. const controllerInputSources = [];
  15046. const planes = new Set();
  15047. const planesLastChangedTimes = new Map();
  15048. //
  15049. const cameraL = new PerspectiveCamera();
  15050. cameraL.layers.enable( 1 );
  15051. cameraL.viewport = new Vector4();
  15052. const cameraR = new PerspectiveCamera();
  15053. cameraR.layers.enable( 2 );
  15054. cameraR.viewport = new Vector4();
  15055. const cameras = [ cameraL, cameraR ];
  15056. const cameraVR = new ArrayCamera();
  15057. cameraVR.layers.enable( 1 );
  15058. cameraVR.layers.enable( 2 );
  15059. let _currentDepthNear = null;
  15060. let _currentDepthFar = null;
  15061. //
  15062. this.cameraAutoUpdate = true;
  15063. this.enabled = false;
  15064. this.isPresenting = false;
  15065. this.getController = function ( index ) {
  15066. let controller = controllers[ index ];
  15067. if ( controller === undefined ) {
  15068. controller = new WebXRController();
  15069. controllers[ index ] = controller;
  15070. }
  15071. return controller.getTargetRaySpace();
  15072. };
  15073. this.getControllerGrip = function ( index ) {
  15074. let controller = controllers[ index ];
  15075. if ( controller === undefined ) {
  15076. controller = new WebXRController();
  15077. controllers[ index ] = controller;
  15078. }
  15079. return controller.getGripSpace();
  15080. };
  15081. this.getHand = function ( index ) {
  15082. let controller = controllers[ index ];
  15083. if ( controller === undefined ) {
  15084. controller = new WebXRController();
  15085. controllers[ index ] = controller;
  15086. }
  15087. return controller.getHandSpace();
  15088. };
  15089. //
  15090. function onSessionEvent( event ) {
  15091. const controllerIndex = controllerInputSources.indexOf( event.inputSource );
  15092. if ( controllerIndex === - 1 ) {
  15093. return;
  15094. }
  15095. const controller = controllers[ controllerIndex ];
  15096. if ( controller !== undefined ) {
  15097. controller.dispatchEvent( { type: event.type, data: event.inputSource } );
  15098. }
  15099. }
  15100. function onSessionEnd() {
  15101. session.removeEventListener( 'select', onSessionEvent );
  15102. session.removeEventListener( 'selectstart', onSessionEvent );
  15103. session.removeEventListener( 'selectend', onSessionEvent );
  15104. session.removeEventListener( 'squeeze', onSessionEvent );
  15105. session.removeEventListener( 'squeezestart', onSessionEvent );
  15106. session.removeEventListener( 'squeezeend', onSessionEvent );
  15107. session.removeEventListener( 'end', onSessionEnd );
  15108. session.removeEventListener( 'inputsourceschange', onInputSourcesChange );
  15109. for ( let i = 0; i < controllers.length; i ++ ) {
  15110. const inputSource = controllerInputSources[ i ];
  15111. if ( inputSource === null ) continue;
  15112. controllerInputSources[ i ] = null;
  15113. controllers[ i ].disconnect( inputSource );
  15114. }
  15115. _currentDepthNear = null;
  15116. _currentDepthFar = null;
  15117. // restore framebuffer/rendering state
  15118. renderer.setRenderTarget( initialRenderTarget );
  15119. glBaseLayer = null;
  15120. glProjLayer = null;
  15121. glBinding = null;
  15122. session = null;
  15123. newRenderTarget = null;
  15124. //
  15125. animation.stop();
  15126. scope.isPresenting = false;
  15127. scope.dispatchEvent( { type: 'sessionend' } );
  15128. }
  15129. this.setFramebufferScaleFactor = function ( value ) {
  15130. framebufferScaleFactor = value;
  15131. if ( scope.isPresenting === true ) {
  15132. console.warn( 'THREE.WebXRManager: Cannot change framebuffer scale while presenting.' );
  15133. }
  15134. };
  15135. this.setReferenceSpaceType = function ( value ) {
  15136. referenceSpaceType = value;
  15137. if ( scope.isPresenting === true ) {
  15138. console.warn( 'THREE.WebXRManager: Cannot change reference space type while presenting.' );
  15139. }
  15140. };
  15141. this.getReferenceSpace = function () {
  15142. return customReferenceSpace || referenceSpace;
  15143. };
  15144. this.setReferenceSpace = function ( space ) {
  15145. customReferenceSpace = space;
  15146. };
  15147. this.getBaseLayer = function () {
  15148. return glProjLayer !== null ? glProjLayer : glBaseLayer;
  15149. };
  15150. this.getBinding = function () {
  15151. return glBinding;
  15152. };
  15153. this.getFrame = function () {
  15154. return xrFrame;
  15155. };
  15156. this.getSession = function () {
  15157. return session;
  15158. };
  15159. this.setSession = async function ( value ) {
  15160. session = value;
  15161. if ( session !== null ) {
  15162. initialRenderTarget = renderer.getRenderTarget();
  15163. session.addEventListener( 'select', onSessionEvent );
  15164. session.addEventListener( 'selectstart', onSessionEvent );
  15165. session.addEventListener( 'selectend', onSessionEvent );
  15166. session.addEventListener( 'squeeze', onSessionEvent );
  15167. session.addEventListener( 'squeezestart', onSessionEvent );
  15168. session.addEventListener( 'squeezeend', onSessionEvent );
  15169. session.addEventListener( 'end', onSessionEnd );
  15170. session.addEventListener( 'inputsourceschange', onInputSourcesChange );
  15171. if ( attributes.xrCompatible !== true ) {
  15172. await gl.makeXRCompatible();
  15173. }
  15174. if ( ( session.renderState.layers === undefined ) || ( renderer.capabilities.isWebGL2 === false ) ) {
  15175. const layerInit = {
  15176. antialias: ( session.renderState.layers === undefined ) ? attributes.antialias : true,
  15177. alpha: attributes.alpha,
  15178. depth: attributes.depth,
  15179. stencil: attributes.stencil,
  15180. framebufferScaleFactor: framebufferScaleFactor
  15181. };
  15182. glBaseLayer = new XRWebGLLayer( session, gl, layerInit );
  15183. session.updateRenderState( { baseLayer: glBaseLayer } );
  15184. newRenderTarget = new WebGLRenderTarget(
  15185. glBaseLayer.framebufferWidth,
  15186. glBaseLayer.framebufferHeight,
  15187. {
  15188. format: RGBAFormat,
  15189. type: UnsignedByteType,
  15190. encoding: renderer.outputEncoding,
  15191. stencilBuffer: attributes.stencil
  15192. }
  15193. );
  15194. } else {
  15195. let depthFormat = null;
  15196. let depthType = null;
  15197. let glDepthFormat = null;
  15198. if ( attributes.depth ) {
  15199. glDepthFormat = attributes.stencil ? gl.DEPTH24_STENCIL8 : gl.DEPTH_COMPONENT24;
  15200. depthFormat = attributes.stencil ? DepthStencilFormat : DepthFormat;
  15201. depthType = attributes.stencil ? UnsignedInt248Type : UnsignedIntType;
  15202. }
  15203. const projectionlayerInit = {
  15204. colorFormat: gl.RGBA8,
  15205. depthFormat: glDepthFormat,
  15206. scaleFactor: framebufferScaleFactor
  15207. };
  15208. glBinding = new XRWebGLBinding( session, gl );
  15209. glProjLayer = glBinding.createProjectionLayer( projectionlayerInit );
  15210. session.updateRenderState( { layers: [ glProjLayer ] } );
  15211. newRenderTarget = new WebGLRenderTarget(
  15212. glProjLayer.textureWidth,
  15213. glProjLayer.textureHeight,
  15214. {
  15215. format: RGBAFormat,
  15216. type: UnsignedByteType,
  15217. depthTexture: new DepthTexture( glProjLayer.textureWidth, glProjLayer.textureHeight, depthType, undefined, undefined, undefined, undefined, undefined, undefined, depthFormat ),
  15218. stencilBuffer: attributes.stencil,
  15219. encoding: renderer.outputEncoding,
  15220. samples: attributes.antialias ? 4 : 0
  15221. } );
  15222. const renderTargetProperties = renderer.properties.get( newRenderTarget );
  15223. renderTargetProperties.__ignoreDepthValues = glProjLayer.ignoreDepthValues;
  15224. }
  15225. newRenderTarget.isXRRenderTarget = true; // TODO Remove this when possible, see #23278
  15226. this.setFoveation( foveation );
  15227. customReferenceSpace = null;
  15228. referenceSpace = await session.requestReferenceSpace( referenceSpaceType );
  15229. animation.setContext( session );
  15230. animation.start();
  15231. scope.isPresenting = true;
  15232. scope.dispatchEvent( { type: 'sessionstart' } );
  15233. }
  15234. };
  15235. function onInputSourcesChange( event ) {
  15236. // Notify disconnected
  15237. for ( let i = 0; i < event.removed.length; i ++ ) {
  15238. const inputSource = event.removed[ i ];
  15239. const index = controllerInputSources.indexOf( inputSource );
  15240. if ( index >= 0 ) {
  15241. controllerInputSources[ index ] = null;
  15242. controllers[ index ].disconnect( inputSource );
  15243. }
  15244. }
  15245. // Notify connected
  15246. for ( let i = 0; i < event.added.length; i ++ ) {
  15247. const inputSource = event.added[ i ];
  15248. let controllerIndex = controllerInputSources.indexOf( inputSource );
  15249. if ( controllerIndex === - 1 ) {
  15250. // Assign input source a controller that currently has no input source
  15251. for ( let i = 0; i < controllers.length; i ++ ) {
  15252. if ( i >= controllerInputSources.length ) {
  15253. controllerInputSources.push( inputSource );
  15254. controllerIndex = i;
  15255. break;
  15256. } else if ( controllerInputSources[ i ] === null ) {
  15257. controllerInputSources[ i ] = inputSource;
  15258. controllerIndex = i;
  15259. break;
  15260. }
  15261. }
  15262. // If all controllers do currently receive input we ignore new ones
  15263. if ( controllerIndex === - 1 ) break;
  15264. }
  15265. const controller = controllers[ controllerIndex ];
  15266. if ( controller ) {
  15267. controller.connect( inputSource );
  15268. }
  15269. }
  15270. }
  15271. //
  15272. const cameraLPos = new Vector3();
  15273. const cameraRPos = new Vector3();
  15274. /**
  15275. * Assumes 2 cameras that are parallel and share an X-axis, and that
  15276. * the cameras' projection and world matrices have already been set.
  15277. * And that near and far planes are identical for both cameras.
  15278. * Visualization of this technique: https://computergraphics.stackexchange.com/a/4765
  15279. */
  15280. function setProjectionFromUnion( camera, cameraL, cameraR ) {
  15281. cameraLPos.setFromMatrixPosition( cameraL.matrixWorld );
  15282. cameraRPos.setFromMatrixPosition( cameraR.matrixWorld );
  15283. const ipd = cameraLPos.distanceTo( cameraRPos );
  15284. const projL = cameraL.projectionMatrix.elements;
  15285. const projR = cameraR.projectionMatrix.elements;
  15286. // VR systems will have identical far and near planes, and
  15287. // most likely identical top and bottom frustum extents.
  15288. // Use the left camera for these values.
  15289. const near = projL[ 14 ] / ( projL[ 10 ] - 1 );
  15290. const far = projL[ 14 ] / ( projL[ 10 ] + 1 );
  15291. const topFov = ( projL[ 9 ] + 1 ) / projL[ 5 ];
  15292. const bottomFov = ( projL[ 9 ] - 1 ) / projL[ 5 ];
  15293. const leftFov = ( projL[ 8 ] - 1 ) / projL[ 0 ];
  15294. const rightFov = ( projR[ 8 ] + 1 ) / projR[ 0 ];
  15295. const left = near * leftFov;
  15296. const right = near * rightFov;
  15297. // Calculate the new camera's position offset from the
  15298. // left camera. xOffset should be roughly half `ipd`.
  15299. const zOffset = ipd / ( - leftFov + rightFov );
  15300. const xOffset = zOffset * - leftFov;
  15301. // TODO: Better way to apply this offset?
  15302. cameraL.matrixWorld.decompose( camera.position, camera.quaternion, camera.scale );
  15303. camera.translateX( xOffset );
  15304. camera.translateZ( zOffset );
  15305. camera.matrixWorld.compose( camera.position, camera.quaternion, camera.scale );
  15306. camera.matrixWorldInverse.copy( camera.matrixWorld ).invert();
  15307. // Find the union of the frustum values of the cameras and scale
  15308. // the values so that the near plane's position does not change in world space,
  15309. // although must now be relative to the new union camera.
  15310. const near2 = near + zOffset;
  15311. const far2 = far + zOffset;
  15312. const left2 = left - xOffset;
  15313. const right2 = right + ( ipd - xOffset );
  15314. const top2 = topFov * far / far2 * near2;
  15315. const bottom2 = bottomFov * far / far2 * near2;
  15316. camera.projectionMatrix.makePerspective( left2, right2, top2, bottom2, near2, far2 );
  15317. }
  15318. function updateCamera( camera, parent ) {
  15319. if ( parent === null ) {
  15320. camera.matrixWorld.copy( camera.matrix );
  15321. } else {
  15322. camera.matrixWorld.multiplyMatrices( parent.matrixWorld, camera.matrix );
  15323. }
  15324. camera.matrixWorldInverse.copy( camera.matrixWorld ).invert();
  15325. }
  15326. this.updateCamera = function ( camera ) {
  15327. if ( session === null ) return;
  15328. cameraVR.near = cameraR.near = cameraL.near = camera.near;
  15329. cameraVR.far = cameraR.far = cameraL.far = camera.far;
  15330. if ( _currentDepthNear !== cameraVR.near || _currentDepthFar !== cameraVR.far ) {
  15331. // Note that the new renderState won't apply until the next frame. See #18320
  15332. session.updateRenderState( {
  15333. depthNear: cameraVR.near,
  15334. depthFar: cameraVR.far
  15335. } );
  15336. _currentDepthNear = cameraVR.near;
  15337. _currentDepthFar = cameraVR.far;
  15338. }
  15339. const parent = camera.parent;
  15340. const cameras = cameraVR.cameras;
  15341. updateCamera( cameraVR, parent );
  15342. for ( let i = 0; i < cameras.length; i ++ ) {
  15343. updateCamera( cameras[ i ], parent );
  15344. }
  15345. cameraVR.matrixWorld.decompose( cameraVR.position, cameraVR.quaternion, cameraVR.scale );
  15346. // update user camera and its children
  15347. camera.matrix.copy( cameraVR.matrix );
  15348. camera.matrix.decompose( camera.position, camera.quaternion, camera.scale );
  15349. const children = camera.children;
  15350. for ( let i = 0, l = children.length; i < l; i ++ ) {
  15351. children[ i ].updateMatrixWorld( true );
  15352. }
  15353. // update projection matrix for proper view frustum culling
  15354. if ( cameras.length === 2 ) {
  15355. setProjectionFromUnion( cameraVR, cameraL, cameraR );
  15356. } else {
  15357. // assume single camera setup (AR)
  15358. cameraVR.projectionMatrix.copy( cameraL.projectionMatrix );
  15359. }
  15360. };
  15361. this.getCamera = function () {
  15362. return cameraVR;
  15363. };
  15364. this.getFoveation = function () {
  15365. if ( glProjLayer === null && glBaseLayer === null ) {
  15366. return undefined;
  15367. }
  15368. return foveation;
  15369. };
  15370. this.setFoveation = function ( value ) {
  15371. // 0 = no foveation = full resolution
  15372. // 1 = maximum foveation = the edges render at lower resolution
  15373. foveation = value;
  15374. if ( glProjLayer !== null ) {
  15375. glProjLayer.fixedFoveation = value;
  15376. }
  15377. if ( glBaseLayer !== null && glBaseLayer.fixedFoveation !== undefined ) {
  15378. glBaseLayer.fixedFoveation = value;
  15379. }
  15380. };
  15381. this.getPlanes = function () {
  15382. return planes;
  15383. };
  15384. // Animation Loop
  15385. let onAnimationFrameCallback = null;
  15386. function onAnimationFrame( time, frame ) {
  15387. pose = frame.getViewerPose( customReferenceSpace || referenceSpace );
  15388. xrFrame = frame;
  15389. if ( pose !== null ) {
  15390. const views = pose.views;
  15391. if ( glBaseLayer !== null ) {
  15392. renderer.setRenderTargetFramebuffer( newRenderTarget, glBaseLayer.framebuffer );
  15393. renderer.setRenderTarget( newRenderTarget );
  15394. }
  15395. let cameraVRNeedsUpdate = false;
  15396. // check if it's necessary to rebuild cameraVR's camera list
  15397. if ( views.length !== cameraVR.cameras.length ) {
  15398. cameraVR.cameras.length = 0;
  15399. cameraVRNeedsUpdate = true;
  15400. }
  15401. for ( let i = 0; i < views.length; i ++ ) {
  15402. const view = views[ i ];
  15403. let viewport = null;
  15404. if ( glBaseLayer !== null ) {
  15405. viewport = glBaseLayer.getViewport( view );
  15406. } else {
  15407. const glSubImage = glBinding.getViewSubImage( glProjLayer, view );
  15408. viewport = glSubImage.viewport;
  15409. // For side-by-side projection, we only produce a single texture for both eyes.
  15410. if ( i === 0 ) {
  15411. renderer.setRenderTargetTextures(
  15412. newRenderTarget,
  15413. glSubImage.colorTexture,
  15414. glProjLayer.ignoreDepthValues ? undefined : glSubImage.depthStencilTexture );
  15415. renderer.setRenderTarget( newRenderTarget );
  15416. }
  15417. }
  15418. let camera = cameras[ i ];
  15419. if ( camera === undefined ) {
  15420. camera = new PerspectiveCamera();
  15421. camera.layers.enable( i );
  15422. camera.viewport = new Vector4();
  15423. cameras[ i ] = camera;
  15424. }
  15425. camera.matrix.fromArray( view.transform.matrix );
  15426. camera.projectionMatrix.fromArray( view.projectionMatrix );
  15427. camera.viewport.set( viewport.x, viewport.y, viewport.width, viewport.height );
  15428. if ( i === 0 ) {
  15429. cameraVR.matrix.copy( camera.matrix );
  15430. }
  15431. if ( cameraVRNeedsUpdate === true ) {
  15432. cameraVR.cameras.push( camera );
  15433. }
  15434. }
  15435. }
  15436. //
  15437. for ( let i = 0; i < controllers.length; i ++ ) {
  15438. const inputSource = controllerInputSources[ i ];
  15439. const controller = controllers[ i ];
  15440. if ( inputSource !== null && controller !== undefined ) {
  15441. controller.update( inputSource, frame, customReferenceSpace || referenceSpace );
  15442. }
  15443. }
  15444. if ( onAnimationFrameCallback ) onAnimationFrameCallback( time, frame );
  15445. if ( frame.detectedPlanes ) {
  15446. scope.dispatchEvent( { type: 'planesdetected', data: frame.detectedPlanes } );
  15447. let planesToRemove = null;
  15448. for ( const plane of planes ) {
  15449. if ( ! frame.detectedPlanes.has( plane ) ) {
  15450. if ( planesToRemove === null ) {
  15451. planesToRemove = [];
  15452. }
  15453. planesToRemove.push( plane );
  15454. }
  15455. }
  15456. if ( planesToRemove !== null ) {
  15457. for ( const plane of planesToRemove ) {
  15458. planes.delete( plane );
  15459. planesLastChangedTimes.delete( plane );
  15460. scope.dispatchEvent( { type: 'planeremoved', data: plane } );
  15461. }
  15462. }
  15463. for ( const plane of frame.detectedPlanes ) {
  15464. if ( ! planes.has( plane ) ) {
  15465. planes.add( plane );
  15466. planesLastChangedTimes.set( plane, frame.lastChangedTime );
  15467. scope.dispatchEvent( { type: 'planeadded', data: plane } );
  15468. } else {
  15469. const lastKnownTime = planesLastChangedTimes.get( plane );
  15470. if ( plane.lastChangedTime > lastKnownTime ) {
  15471. planesLastChangedTimes.set( plane, plane.lastChangedTime );
  15472. scope.dispatchEvent( { type: 'planechanged', data: plane } );
  15473. }
  15474. }
  15475. }
  15476. }
  15477. xrFrame = null;
  15478. }
  15479. const animation = new WebGLAnimation();
  15480. animation.setAnimationLoop( onAnimationFrame );
  15481. this.setAnimationLoop = function ( callback ) {
  15482. onAnimationFrameCallback = callback;
  15483. };
  15484. this.dispose = function () {};
  15485. }
  15486. }
  15487. function WebGLMaterials( renderer, properties ) {
  15488. function refreshFogUniforms( uniforms, fog ) {
  15489. fog.color.getRGB( uniforms.fogColor.value, getUnlitUniformColorSpace( renderer ) );
  15490. if ( fog.isFog ) {
  15491. uniforms.fogNear.value = fog.near;
  15492. uniforms.fogFar.value = fog.far;
  15493. } else if ( fog.isFogExp2 ) {
  15494. uniforms.fogDensity.value = fog.density;
  15495. }
  15496. }
  15497. function refreshMaterialUniforms( uniforms, material, pixelRatio, height, transmissionRenderTarget ) {
  15498. if ( material.isMeshBasicMaterial ) {
  15499. refreshUniformsCommon( uniforms, material );
  15500. } else if ( material.isMeshLambertMaterial ) {
  15501. refreshUniformsCommon( uniforms, material );
  15502. } else if ( material.isMeshToonMaterial ) {
  15503. refreshUniformsCommon( uniforms, material );
  15504. refreshUniformsToon( uniforms, material );
  15505. } else if ( material.isMeshPhongMaterial ) {
  15506. refreshUniformsCommon( uniforms, material );
  15507. refreshUniformsPhong( uniforms, material );
  15508. } else if ( material.isMeshStandardMaterial ) {
  15509. refreshUniformsCommon( uniforms, material );
  15510. refreshUniformsStandard( uniforms, material );
  15511. if ( material.isMeshPhysicalMaterial ) {
  15512. refreshUniformsPhysical( uniforms, material, transmissionRenderTarget );
  15513. }
  15514. } else if ( material.isMeshMatcapMaterial ) {
  15515. refreshUniformsCommon( uniforms, material );
  15516. refreshUniformsMatcap( uniforms, material );
  15517. } else if ( material.isMeshDepthMaterial ) {
  15518. refreshUniformsCommon( uniforms, material );
  15519. } else if ( material.isMeshDistanceMaterial ) {
  15520. refreshUniformsCommon( uniforms, material );
  15521. refreshUniformsDistance( uniforms, material );
  15522. } else if ( material.isMeshNormalMaterial ) {
  15523. refreshUniformsCommon( uniforms, material );
  15524. } else if ( material.isLineBasicMaterial ) {
  15525. refreshUniformsLine( uniforms, material );
  15526. if ( material.isLineDashedMaterial ) {
  15527. refreshUniformsDash( uniforms, material );
  15528. }
  15529. } else if ( material.isPointsMaterial ) {
  15530. refreshUniformsPoints( uniforms, material, pixelRatio, height );
  15531. } else if ( material.isSpriteMaterial ) {
  15532. refreshUniformsSprites( uniforms, material );
  15533. } else if ( material.isShadowMaterial ) {
  15534. uniforms.color.value.copy( material.color );
  15535. uniforms.opacity.value = material.opacity;
  15536. } else if ( material.isShaderMaterial ) {
  15537. material.uniformsNeedUpdate = false; // #15581
  15538. }
  15539. }
  15540. function refreshUniformsCommon( uniforms, material ) {
  15541. uniforms.opacity.value = material.opacity;
  15542. if ( material.color ) {
  15543. uniforms.diffuse.value.copy( material.color );
  15544. }
  15545. if ( material.emissive ) {
  15546. uniforms.emissive.value.copy( material.emissive ).multiplyScalar( material.emissiveIntensity );
  15547. }
  15548. if ( material.map ) {
  15549. uniforms.map.value = material.map;
  15550. }
  15551. if ( material.alphaMap ) {
  15552. uniforms.alphaMap.value = material.alphaMap;
  15553. }
  15554. if ( material.bumpMap ) {
  15555. uniforms.bumpMap.value = material.bumpMap;
  15556. uniforms.bumpScale.value = material.bumpScale;
  15557. if ( material.side === BackSide ) uniforms.bumpScale.value *= - 1;
  15558. }
  15559. if ( material.displacementMap ) {
  15560. uniforms.displacementMap.value = material.displacementMap;
  15561. uniforms.displacementScale.value = material.displacementScale;
  15562. uniforms.displacementBias.value = material.displacementBias;
  15563. }
  15564. if ( material.emissiveMap ) {
  15565. uniforms.emissiveMap.value = material.emissiveMap;
  15566. }
  15567. if ( material.normalMap ) {
  15568. uniforms.normalMap.value = material.normalMap;
  15569. uniforms.normalScale.value.copy( material.normalScale );
  15570. if ( material.side === BackSide ) uniforms.normalScale.value.negate();
  15571. }
  15572. if ( material.specularMap ) {
  15573. uniforms.specularMap.value = material.specularMap;
  15574. }
  15575. if ( material.alphaTest > 0 ) {
  15576. uniforms.alphaTest.value = material.alphaTest;
  15577. }
  15578. const envMap = properties.get( material ).envMap;
  15579. if ( envMap ) {
  15580. uniforms.envMap.value = envMap;
  15581. uniforms.flipEnvMap.value = ( envMap.isCubeTexture && envMap.isRenderTargetTexture === false ) ? - 1 : 1;
  15582. uniforms.reflectivity.value = material.reflectivity;
  15583. uniforms.ior.value = material.ior;
  15584. uniforms.refractionRatio.value = material.refractionRatio;
  15585. }
  15586. if ( material.lightMap ) {
  15587. uniforms.lightMap.value = material.lightMap;
  15588. // artist-friendly light intensity scaling factor
  15589. const scaleFactor = ( renderer.physicallyCorrectLights !== true ) ? Math.PI : 1;
  15590. uniforms.lightMapIntensity.value = material.lightMapIntensity * scaleFactor;
  15591. }
  15592. if ( material.aoMap ) {
  15593. uniforms.aoMap.value = material.aoMap;
  15594. uniforms.aoMapIntensity.value = material.aoMapIntensity;
  15595. }
  15596. // uv repeat and offset setting priorities
  15597. // 1. color map
  15598. // 2. specular map
  15599. // 3. displacementMap map
  15600. // 4. normal map
  15601. // 5. bump map
  15602. // 6. roughnessMap map
  15603. // 7. metalnessMap map
  15604. // 8. alphaMap map
  15605. // 9. emissiveMap map
  15606. // 10. clearcoat map
  15607. // 11. clearcoat normal map
  15608. // 12. clearcoat roughnessMap map
  15609. // 13. iridescence map
  15610. // 14. iridescence thickness map
  15611. // 15. specular intensity map
  15612. // 16. specular tint map
  15613. // 17. transmission map
  15614. // 18. thickness map
  15615. let uvScaleMap;
  15616. if ( material.map ) {
  15617. uvScaleMap = material.map;
  15618. } else if ( material.specularMap ) {
  15619. uvScaleMap = material.specularMap;
  15620. } else if ( material.displacementMap ) {
  15621. uvScaleMap = material.displacementMap;
  15622. } else if ( material.normalMap ) {
  15623. uvScaleMap = material.normalMap;
  15624. } else if ( material.bumpMap ) {
  15625. uvScaleMap = material.bumpMap;
  15626. } else if ( material.roughnessMap ) {
  15627. uvScaleMap = material.roughnessMap;
  15628. } else if ( material.metalnessMap ) {
  15629. uvScaleMap = material.metalnessMap;
  15630. } else if ( material.alphaMap ) {
  15631. uvScaleMap = material.alphaMap;
  15632. } else if ( material.emissiveMap ) {
  15633. uvScaleMap = material.emissiveMap;
  15634. } else if ( material.clearcoatMap ) {
  15635. uvScaleMap = material.clearcoatMap;
  15636. } else if ( material.clearcoatNormalMap ) {
  15637. uvScaleMap = material.clearcoatNormalMap;
  15638. } else if ( material.clearcoatRoughnessMap ) {
  15639. uvScaleMap = material.clearcoatRoughnessMap;
  15640. } else if ( material.iridescenceMap ) {
  15641. uvScaleMap = material.iridescenceMap;
  15642. } else if ( material.iridescenceThicknessMap ) {
  15643. uvScaleMap = material.iridescenceThicknessMap;
  15644. } else if ( material.specularIntensityMap ) {
  15645. uvScaleMap = material.specularIntensityMap;
  15646. } else if ( material.specularColorMap ) {
  15647. uvScaleMap = material.specularColorMap;
  15648. } else if ( material.transmissionMap ) {
  15649. uvScaleMap = material.transmissionMap;
  15650. } else if ( material.thicknessMap ) {
  15651. uvScaleMap = material.thicknessMap;
  15652. } else if ( material.sheenColorMap ) {
  15653. uvScaleMap = material.sheenColorMap;
  15654. } else if ( material.sheenRoughnessMap ) {
  15655. uvScaleMap = material.sheenRoughnessMap;
  15656. }
  15657. if ( uvScaleMap !== undefined ) {
  15658. // backwards compatibility
  15659. if ( uvScaleMap.isWebGLRenderTarget ) {
  15660. uvScaleMap = uvScaleMap.texture;
  15661. }
  15662. if ( uvScaleMap.matrixAutoUpdate === true ) {
  15663. uvScaleMap.updateMatrix();
  15664. }
  15665. uniforms.uvTransform.value.copy( uvScaleMap.matrix );
  15666. }
  15667. // uv repeat and offset setting priorities for uv2
  15668. // 1. ao map
  15669. // 2. light map
  15670. let uv2ScaleMap;
  15671. if ( material.aoMap ) {
  15672. uv2ScaleMap = material.aoMap;
  15673. } else if ( material.lightMap ) {
  15674. uv2ScaleMap = material.lightMap;
  15675. }
  15676. if ( uv2ScaleMap !== undefined ) {
  15677. // backwards compatibility
  15678. if ( uv2ScaleMap.isWebGLRenderTarget ) {
  15679. uv2ScaleMap = uv2ScaleMap.texture;
  15680. }
  15681. if ( uv2ScaleMap.matrixAutoUpdate === true ) {
  15682. uv2ScaleMap.updateMatrix();
  15683. }
  15684. uniforms.uv2Transform.value.copy( uv2ScaleMap.matrix );
  15685. }
  15686. }
  15687. function refreshUniformsLine( uniforms, material ) {
  15688. uniforms.diffuse.value.copy( material.color );
  15689. uniforms.opacity.value = material.opacity;
  15690. }
  15691. function refreshUniformsDash( uniforms, material ) {
  15692. uniforms.dashSize.value = material.dashSize;
  15693. uniforms.totalSize.value = material.dashSize + material.gapSize;
  15694. uniforms.scale.value = material.scale;
  15695. }
  15696. function refreshUniformsPoints( uniforms, material, pixelRatio, height ) {
  15697. uniforms.diffuse.value.copy( material.color );
  15698. uniforms.opacity.value = material.opacity;
  15699. uniforms.size.value = material.size * pixelRatio;
  15700. uniforms.scale.value = height * 0.5;
  15701. if ( material.map ) {
  15702. uniforms.map.value = material.map;
  15703. }
  15704. if ( material.alphaMap ) {
  15705. uniforms.alphaMap.value = material.alphaMap;
  15706. }
  15707. if ( material.alphaTest > 0 ) {
  15708. uniforms.alphaTest.value = material.alphaTest;
  15709. }
  15710. // uv repeat and offset setting priorities
  15711. // 1. color map
  15712. // 2. alpha map
  15713. let uvScaleMap;
  15714. if ( material.map ) {
  15715. uvScaleMap = material.map;
  15716. } else if ( material.alphaMap ) {
  15717. uvScaleMap = material.alphaMap;
  15718. }
  15719. if ( uvScaleMap !== undefined ) {
  15720. if ( uvScaleMap.matrixAutoUpdate === true ) {
  15721. uvScaleMap.updateMatrix();
  15722. }
  15723. uniforms.uvTransform.value.copy( uvScaleMap.matrix );
  15724. }
  15725. }
  15726. function refreshUniformsSprites( uniforms, material ) {
  15727. uniforms.diffuse.value.copy( material.color );
  15728. uniforms.opacity.value = material.opacity;
  15729. uniforms.rotation.value = material.rotation;
  15730. if ( material.map ) {
  15731. uniforms.map.value = material.map;
  15732. }
  15733. if ( material.alphaMap ) {
  15734. uniforms.alphaMap.value = material.alphaMap;
  15735. }
  15736. if ( material.alphaTest > 0 ) {
  15737. uniforms.alphaTest.value = material.alphaTest;
  15738. }
  15739. // uv repeat and offset setting priorities
  15740. // 1. color map
  15741. // 2. alpha map
  15742. let uvScaleMap;
  15743. if ( material.map ) {
  15744. uvScaleMap = material.map;
  15745. } else if ( material.alphaMap ) {
  15746. uvScaleMap = material.alphaMap;
  15747. }
  15748. if ( uvScaleMap !== undefined ) {
  15749. if ( uvScaleMap.matrixAutoUpdate === true ) {
  15750. uvScaleMap.updateMatrix();
  15751. }
  15752. uniforms.uvTransform.value.copy( uvScaleMap.matrix );
  15753. }
  15754. }
  15755. function refreshUniformsPhong( uniforms, material ) {
  15756. uniforms.specular.value.copy( material.specular );
  15757. uniforms.shininess.value = Math.max( material.shininess, 1e-4 ); // to prevent pow( 0.0, 0.0 )
  15758. }
  15759. function refreshUniformsToon( uniforms, material ) {
  15760. if ( material.gradientMap ) {
  15761. uniforms.gradientMap.value = material.gradientMap;
  15762. }
  15763. }
  15764. function refreshUniformsStandard( uniforms, material ) {
  15765. uniforms.roughness.value = material.roughness;
  15766. uniforms.metalness.value = material.metalness;
  15767. if ( material.roughnessMap ) {
  15768. uniforms.roughnessMap.value = material.roughnessMap;
  15769. }
  15770. if ( material.metalnessMap ) {
  15771. uniforms.metalnessMap.value = material.metalnessMap;
  15772. }
  15773. const envMap = properties.get( material ).envMap;
  15774. if ( envMap ) {
  15775. //uniforms.envMap.value = material.envMap; // part of uniforms common
  15776. uniforms.envMapIntensity.value = material.envMapIntensity;
  15777. }
  15778. }
  15779. function refreshUniformsPhysical( uniforms, material, transmissionRenderTarget ) {
  15780. uniforms.ior.value = material.ior; // also part of uniforms common
  15781. if ( material.sheen > 0 ) {
  15782. uniforms.sheenColor.value.copy( material.sheenColor ).multiplyScalar( material.sheen );
  15783. uniforms.sheenRoughness.value = material.sheenRoughness;
  15784. if ( material.sheenColorMap ) {
  15785. uniforms.sheenColorMap.value = material.sheenColorMap;
  15786. }
  15787. if ( material.sheenRoughnessMap ) {
  15788. uniforms.sheenRoughnessMap.value = material.sheenRoughnessMap;
  15789. }
  15790. }
  15791. if ( material.clearcoat > 0 ) {
  15792. uniforms.clearcoat.value = material.clearcoat;
  15793. uniforms.clearcoatRoughness.value = material.clearcoatRoughness;
  15794. if ( material.clearcoatMap ) {
  15795. uniforms.clearcoatMap.value = material.clearcoatMap;
  15796. }
  15797. if ( material.clearcoatRoughnessMap ) {
  15798. uniforms.clearcoatRoughnessMap.value = material.clearcoatRoughnessMap;
  15799. }
  15800. if ( material.clearcoatNormalMap ) {
  15801. uniforms.clearcoatNormalScale.value.copy( material.clearcoatNormalScale );
  15802. uniforms.clearcoatNormalMap.value = material.clearcoatNormalMap;
  15803. if ( material.side === BackSide ) {
  15804. uniforms.clearcoatNormalScale.value.negate();
  15805. }
  15806. }
  15807. }
  15808. if ( material.iridescence > 0 ) {
  15809. uniforms.iridescence.value = material.iridescence;
  15810. uniforms.iridescenceIOR.value = material.iridescenceIOR;
  15811. uniforms.iridescenceThicknessMinimum.value = material.iridescenceThicknessRange[ 0 ];
  15812. uniforms.iridescenceThicknessMaximum.value = material.iridescenceThicknessRange[ 1 ];
  15813. if ( material.iridescenceMap ) {
  15814. uniforms.iridescenceMap.value = material.iridescenceMap;
  15815. }
  15816. if ( material.iridescenceThicknessMap ) {
  15817. uniforms.iridescenceThicknessMap.value = material.iridescenceThicknessMap;
  15818. }
  15819. }
  15820. if ( material.transmission > 0 ) {
  15821. uniforms.transmission.value = material.transmission;
  15822. uniforms.transmissionSamplerMap.value = transmissionRenderTarget.texture;
  15823. uniforms.transmissionSamplerSize.value.set( transmissionRenderTarget.width, transmissionRenderTarget.height );
  15824. if ( material.transmissionMap ) {
  15825. uniforms.transmissionMap.value = material.transmissionMap;
  15826. }
  15827. uniforms.thickness.value = material.thickness;
  15828. if ( material.thicknessMap ) {
  15829. uniforms.thicknessMap.value = material.thicknessMap;
  15830. }
  15831. uniforms.attenuationDistance.value = material.attenuationDistance;
  15832. uniforms.attenuationColor.value.copy( material.attenuationColor );
  15833. }
  15834. uniforms.specularIntensity.value = material.specularIntensity;
  15835. uniforms.specularColor.value.copy( material.specularColor );
  15836. if ( material.specularIntensityMap ) {
  15837. uniforms.specularIntensityMap.value = material.specularIntensityMap;
  15838. }
  15839. if ( material.specularColorMap ) {
  15840. uniforms.specularColorMap.value = material.specularColorMap;
  15841. }
  15842. }
  15843. function refreshUniformsMatcap( uniforms, material ) {
  15844. if ( material.matcap ) {
  15845. uniforms.matcap.value = material.matcap;
  15846. }
  15847. }
  15848. function refreshUniformsDistance( uniforms, material ) {
  15849. uniforms.referencePosition.value.copy( material.referencePosition );
  15850. uniforms.nearDistance.value = material.nearDistance;
  15851. uniforms.farDistance.value = material.farDistance;
  15852. }
  15853. return {
  15854. refreshFogUniforms: refreshFogUniforms,
  15855. refreshMaterialUniforms: refreshMaterialUniforms
  15856. };
  15857. }
  15858. function WebGLUniformsGroups( gl, info, capabilities, state ) {
  15859. let buffers = {};
  15860. let updateList = {};
  15861. let allocatedBindingPoints = [];
  15862. const maxBindingPoints = ( capabilities.isWebGL2 ) ? gl.getParameter( gl.MAX_UNIFORM_BUFFER_BINDINGS ) : 0; // binding points are global whereas block indices are per shader program
  15863. function bind( uniformsGroup, program ) {
  15864. const webglProgram = program.program;
  15865. state.uniformBlockBinding( uniformsGroup, webglProgram );
  15866. }
  15867. function update( uniformsGroup, program ) {
  15868. let buffer = buffers[ uniformsGroup.id ];
  15869. if ( buffer === undefined ) {
  15870. prepareUniformsGroup( uniformsGroup );
  15871. buffer = createBuffer( uniformsGroup );
  15872. buffers[ uniformsGroup.id ] = buffer;
  15873. uniformsGroup.addEventListener( 'dispose', onUniformsGroupsDispose );
  15874. }
  15875. // ensure to update the binding points/block indices mapping for this program
  15876. const webglProgram = program.program;
  15877. state.updateUBOMapping( uniformsGroup, webglProgram );
  15878. // update UBO once per frame
  15879. const frame = info.render.frame;
  15880. if ( updateList[ uniformsGroup.id ] !== frame ) {
  15881. updateBufferData( uniformsGroup );
  15882. updateList[ uniformsGroup.id ] = frame;
  15883. }
  15884. }
  15885. function createBuffer( uniformsGroup ) {
  15886. // the setup of an UBO is independent of a particular shader program but global
  15887. const bindingPointIndex = allocateBindingPointIndex();
  15888. uniformsGroup.__bindingPointIndex = bindingPointIndex;
  15889. const buffer = gl.createBuffer();
  15890. const size = uniformsGroup.__size;
  15891. const usage = uniformsGroup.usage;
  15892. gl.bindBuffer( gl.UNIFORM_BUFFER, buffer );
  15893. gl.bufferData( gl.UNIFORM_BUFFER, size, usage );
  15894. gl.bindBuffer( gl.UNIFORM_BUFFER, null );
  15895. gl.bindBufferBase( gl.UNIFORM_BUFFER, bindingPointIndex, buffer );
  15896. return buffer;
  15897. }
  15898. function allocateBindingPointIndex() {
  15899. for ( let i = 0; i < maxBindingPoints; i ++ ) {
  15900. if ( allocatedBindingPoints.indexOf( i ) === - 1 ) {
  15901. allocatedBindingPoints.push( i );
  15902. return i;
  15903. }
  15904. }
  15905. console.error( 'THREE.WebGLRenderer: Maximum number of simultaneously usable uniforms groups reached.' );
  15906. return 0;
  15907. }
  15908. function updateBufferData( uniformsGroup ) {
  15909. const buffer = buffers[ uniformsGroup.id ];
  15910. const uniforms = uniformsGroup.uniforms;
  15911. const cache = uniformsGroup.__cache;
  15912. gl.bindBuffer( gl.UNIFORM_BUFFER, buffer );
  15913. for ( let i = 0, il = uniforms.length; i < il; i ++ ) {
  15914. const uniform = uniforms[ i ];
  15915. // partly update the buffer if necessary
  15916. if ( hasUniformChanged( uniform, i, cache ) === true ) {
  15917. const offset = uniform.__offset;
  15918. const values = Array.isArray( uniform.value ) ? uniform.value : [ uniform.value ];
  15919. let arrayOffset = 0;
  15920. for ( let i = 0; i < values.length; i ++ ) {
  15921. const value = values[ i ];
  15922. const info = getUniformSize( value );
  15923. if ( typeof value === 'number' ) {
  15924. uniform.__data[ 0 ] = value;
  15925. gl.bufferSubData( gl.UNIFORM_BUFFER, offset + arrayOffset, uniform.__data );
  15926. } else if ( value.isMatrix3 ) {
  15927. // manually converting 3x3 to 3x4
  15928. uniform.__data[ 0 ] = value.elements[ 0 ];
  15929. uniform.__data[ 1 ] = value.elements[ 1 ];
  15930. uniform.__data[ 2 ] = value.elements[ 2 ];
  15931. uniform.__data[ 3 ] = value.elements[ 0 ];
  15932. uniform.__data[ 4 ] = value.elements[ 3 ];
  15933. uniform.__data[ 5 ] = value.elements[ 4 ];
  15934. uniform.__data[ 6 ] = value.elements[ 5 ];
  15935. uniform.__data[ 7 ] = value.elements[ 0 ];
  15936. uniform.__data[ 8 ] = value.elements[ 6 ];
  15937. uniform.__data[ 9 ] = value.elements[ 7 ];
  15938. uniform.__data[ 10 ] = value.elements[ 8 ];
  15939. uniform.__data[ 11 ] = value.elements[ 0 ];
  15940. } else {
  15941. value.toArray( uniform.__data, arrayOffset );
  15942. arrayOffset += info.storage / Float32Array.BYTES_PER_ELEMENT;
  15943. }
  15944. }
  15945. gl.bufferSubData( gl.UNIFORM_BUFFER, offset, uniform.__data );
  15946. }
  15947. }
  15948. gl.bindBuffer( gl.UNIFORM_BUFFER, null );
  15949. }
  15950. function hasUniformChanged( uniform, index, cache ) {
  15951. const value = uniform.value;
  15952. if ( cache[ index ] === undefined ) {
  15953. // cache entry does not exist so far
  15954. if ( typeof value === 'number' ) {
  15955. cache[ index ] = value;
  15956. } else {
  15957. const values = Array.isArray( value ) ? value : [ value ];
  15958. const tempValues = [];
  15959. for ( let i = 0; i < values.length; i ++ ) {
  15960. tempValues.push( values[ i ].clone() );
  15961. }
  15962. cache[ index ] = tempValues;
  15963. }
  15964. return true;
  15965. } else {
  15966. // compare current value with cached entry
  15967. if ( typeof value === 'number' ) {
  15968. if ( cache[ index ] !== value ) {
  15969. cache[ index ] = value;
  15970. return true;
  15971. }
  15972. } else {
  15973. const cachedObjects = Array.isArray( cache[ index ] ) ? cache[ index ] : [ cache[ index ] ];
  15974. const values = Array.isArray( value ) ? value : [ value ];
  15975. for ( let i = 0; i < cachedObjects.length; i ++ ) {
  15976. const cachedObject = cachedObjects[ i ];
  15977. if ( cachedObject.equals( values[ i ] ) === false ) {
  15978. cachedObject.copy( values[ i ] );
  15979. return true;
  15980. }
  15981. }
  15982. }
  15983. }
  15984. return false;
  15985. }
  15986. function prepareUniformsGroup( uniformsGroup ) {
  15987. // determine total buffer size according to the STD140 layout
  15988. // Hint: STD140 is the only supported layout in WebGL 2
  15989. const uniforms = uniformsGroup.uniforms;
  15990. let offset = 0; // global buffer offset in bytes
  15991. const chunkSize = 16; // size of a chunk in bytes
  15992. let chunkOffset = 0; // offset within a single chunk in bytes
  15993. for ( let i = 0, l = uniforms.length; i < l; i ++ ) {
  15994. const uniform = uniforms[ i ];
  15995. const infos = {
  15996. boundary: 0, // bytes
  15997. storage: 0 // bytes
  15998. };
  15999. const values = Array.isArray( uniform.value ) ? uniform.value : [ uniform.value ];
  16000. for ( let j = 0, jl = values.length; j < jl; j ++ ) {
  16001. const value = values[ j ];
  16002. const info = getUniformSize( value );
  16003. infos.boundary += info.boundary;
  16004. infos.storage += info.storage;
  16005. }
  16006. // the following two properties will be used for partial buffer updates
  16007. uniform.__data = new Float32Array( infos.storage / Float32Array.BYTES_PER_ELEMENT );
  16008. uniform.__offset = offset;
  16009. //
  16010. if ( i > 0 ) {
  16011. chunkOffset = offset % chunkSize;
  16012. const remainingSizeInChunk = chunkSize - chunkOffset;
  16013. // check for chunk overflow
  16014. if ( chunkOffset !== 0 && ( remainingSizeInChunk - infos.boundary ) < 0 ) {
  16015. // add padding and adjust offset
  16016. offset += ( chunkSize - chunkOffset );
  16017. uniform.__offset = offset;
  16018. }
  16019. }
  16020. offset += infos.storage;
  16021. }
  16022. // ensure correct final padding
  16023. chunkOffset = offset % chunkSize;
  16024. if ( chunkOffset > 0 ) offset += ( chunkSize - chunkOffset );
  16025. //
  16026. uniformsGroup.__size = offset;
  16027. uniformsGroup.__cache = {};
  16028. return this;
  16029. }
  16030. function getUniformSize( value ) {
  16031. const info = {
  16032. boundary: 0, // bytes
  16033. storage: 0 // bytes
  16034. };
  16035. // determine sizes according to STD140
  16036. if ( typeof value === 'number' ) {
  16037. // float/int
  16038. info.boundary = 4;
  16039. info.storage = 4;
  16040. } else if ( value.isVector2 ) {
  16041. // vec2
  16042. info.boundary = 8;
  16043. info.storage = 8;
  16044. } else if ( value.isVector3 || value.isColor ) {
  16045. // vec3
  16046. info.boundary = 16;
  16047. info.storage = 12; // evil: vec3 must start on a 16-byte boundary but it only consumes 12 bytes
  16048. } else if ( value.isVector4 ) {
  16049. // vec4
  16050. info.boundary = 16;
  16051. info.storage = 16;
  16052. } else if ( value.isMatrix3 ) {
  16053. // mat3 (in STD140 a 3x3 matrix is represented as 3x4)
  16054. info.boundary = 48;
  16055. info.storage = 48;
  16056. } else if ( value.isMatrix4 ) {
  16057. // mat4
  16058. info.boundary = 64;
  16059. info.storage = 64;
  16060. } else if ( value.isTexture ) {
  16061. console.warn( 'THREE.WebGLRenderer: Texture samplers can not be part of an uniforms group.' );
  16062. } else {
  16063. console.warn( 'THREE.WebGLRenderer: Unsupported uniform value type.', value );
  16064. }
  16065. return info;
  16066. }
  16067. function onUniformsGroupsDispose( event ) {
  16068. const uniformsGroup = event.target;
  16069. uniformsGroup.removeEventListener( 'dispose', onUniformsGroupsDispose );
  16070. const index = allocatedBindingPoints.indexOf( uniformsGroup.__bindingPointIndex );
  16071. allocatedBindingPoints.splice( index, 1 );
  16072. gl.deleteBuffer( buffers[ uniformsGroup.id ] );
  16073. delete buffers[ uniformsGroup.id ];
  16074. delete updateList[ uniformsGroup.id ];
  16075. }
  16076. function dispose() {
  16077. for ( const id in buffers ) {
  16078. gl.deleteBuffer( buffers[ id ] );
  16079. }
  16080. allocatedBindingPoints = [];
  16081. buffers = {};
  16082. updateList = {};
  16083. }
  16084. return {
  16085. bind: bind,
  16086. update: update,
  16087. dispose: dispose
  16088. };
  16089. }
  16090. function createCanvasElement() {
  16091. const canvas = createElementNS( 'canvas' );
  16092. canvas.style.display = 'block';
  16093. return canvas;
  16094. }
  16095. function WebGLRenderer( parameters = {} ) {
  16096. this.isWebGLRenderer = true;
  16097. const _canvas = parameters.canvas !== undefined ? parameters.canvas : createCanvasElement(),
  16098. _context = parameters.context !== undefined ? parameters.context : null,
  16099. _depth = parameters.depth !== undefined ? parameters.depth : true,
  16100. _stencil = parameters.stencil !== undefined ? parameters.stencil : true,
  16101. _antialias = parameters.antialias !== undefined ? parameters.antialias : false,
  16102. _premultipliedAlpha = parameters.premultipliedAlpha !== undefined ? parameters.premultipliedAlpha : true,
  16103. _preserveDrawingBuffer = parameters.preserveDrawingBuffer !== undefined ? parameters.preserveDrawingBuffer : false,
  16104. _powerPreference = parameters.powerPreference !== undefined ? parameters.powerPreference : 'default',
  16105. _failIfMajorPerformanceCaveat = parameters.failIfMajorPerformanceCaveat !== undefined ? parameters.failIfMajorPerformanceCaveat : false;
  16106. let _alpha;
  16107. if ( _context !== null ) {
  16108. _alpha = _context.getContextAttributes().alpha;
  16109. } else {
  16110. _alpha = parameters.alpha !== undefined ? parameters.alpha : false;
  16111. }
  16112. let currentRenderList = null;
  16113. let currentRenderState = null;
  16114. // render() can be called from within a callback triggered by another render.
  16115. // We track this so that the nested render call gets its list and state isolated from the parent render call.
  16116. const renderListStack = [];
  16117. const renderStateStack = [];
  16118. // public properties
  16119. this.domElement = _canvas;
  16120. // Debug configuration container
  16121. this.debug = {
  16122. /**
  16123. * Enables error checking and reporting when shader programs are being compiled
  16124. * @type {boolean}
  16125. */
  16126. checkShaderErrors: true
  16127. };
  16128. // clearing
  16129. this.autoClear = true;
  16130. this.autoClearColor = true;
  16131. this.autoClearDepth = true;
  16132. this.autoClearStencil = true;
  16133. // scene graph
  16134. this.sortObjects = true;
  16135. // user-defined clipping
  16136. this.clippingPlanes = [];
  16137. this.localClippingEnabled = false;
  16138. // physically based shading
  16139. this.outputEncoding = LinearEncoding;
  16140. // physical lights
  16141. this.physicallyCorrectLights = false;
  16142. // tone mapping
  16143. this.toneMapping = NoToneMapping;
  16144. this.toneMappingExposure = 1.0;
  16145. // internal properties
  16146. const _this = this;
  16147. let _isContextLost = false;
  16148. // internal state cache
  16149. let _currentActiveCubeFace = 0;
  16150. let _currentActiveMipmapLevel = 0;
  16151. let _currentRenderTarget = null;
  16152. let _currentMaterialId = - 1;
  16153. let _currentCamera = null;
  16154. const _currentViewport = new Vector4();
  16155. const _currentScissor = new Vector4();
  16156. let _currentScissorTest = null;
  16157. //
  16158. let _width = _canvas.width;
  16159. let _height = _canvas.height;
  16160. let _pixelRatio = 1;
  16161. let _opaqueSort = null;
  16162. let _transparentSort = null;
  16163. const _viewport = new Vector4( 0, 0, _width, _height );
  16164. const _scissor = new Vector4( 0, 0, _width, _height );
  16165. let _scissorTest = false;
  16166. // frustum
  16167. const _frustum = new Frustum();
  16168. // clipping
  16169. let _clippingEnabled = false;
  16170. let _localClippingEnabled = false;
  16171. // transmission
  16172. let _transmissionRenderTarget = null;
  16173. // camera matrices cache
  16174. const _projScreenMatrix = new Matrix4();
  16175. const _vector2 = new Vector2();
  16176. const _vector3 = new Vector3();
  16177. const _emptyScene = { background: null, fog: null, environment: null, overrideMaterial: null, isScene: true };
  16178. function getTargetPixelRatio() {
  16179. return _currentRenderTarget === null ? _pixelRatio : 1;
  16180. }
  16181. // initialize
  16182. let _gl = _context;
  16183. function getContext( contextNames, contextAttributes ) {
  16184. for ( let i = 0; i < contextNames.length; i ++ ) {
  16185. const contextName = contextNames[ i ];
  16186. const context = _canvas.getContext( contextName, contextAttributes );
  16187. if ( context !== null ) return context;
  16188. }
  16189. return null;
  16190. }
  16191. try {
  16192. const contextAttributes = {
  16193. alpha: true,
  16194. depth: _depth,
  16195. stencil: _stencil,
  16196. antialias: _antialias,
  16197. premultipliedAlpha: _premultipliedAlpha,
  16198. preserveDrawingBuffer: _preserveDrawingBuffer,
  16199. powerPreference: _powerPreference,
  16200. failIfMajorPerformanceCaveat: _failIfMajorPerformanceCaveat
  16201. };
  16202. // OffscreenCanvas does not have setAttribute, see #22811
  16203. if ( 'setAttribute' in _canvas ) _canvas.setAttribute( 'data-engine', `three.js r${REVISION}` );
  16204. // event listeners must be registered before WebGL context is created, see #12753
  16205. _canvas.addEventListener( 'webglcontextlost', onContextLost, false );
  16206. _canvas.addEventListener( 'webglcontextrestored', onContextRestore, false );
  16207. _canvas.addEventListener( 'webglcontextcreationerror', onContextCreationError, false );
  16208. if ( _gl === null ) {
  16209. const contextNames = [ 'webgl2', 'webgl', 'experimental-webgl' ];
  16210. if ( _this.isWebGL1Renderer === true ) {
  16211. contextNames.shift();
  16212. }
  16213. _gl = getContext( contextNames, contextAttributes );
  16214. if ( _gl === null ) {
  16215. if ( getContext( contextNames ) ) {
  16216. throw new Error( 'Error creating WebGL context with your selected attributes.' );
  16217. } else {
  16218. throw new Error( 'Error creating WebGL context.' );
  16219. }
  16220. }
  16221. }
  16222. // Some experimental-webgl implementations do not have getShaderPrecisionFormat
  16223. if ( _gl.getShaderPrecisionFormat === undefined ) {
  16224. _gl.getShaderPrecisionFormat = function () {
  16225. return { 'rangeMin': 1, 'rangeMax': 1, 'precision': 1 };
  16226. };
  16227. }
  16228. } catch ( error ) {
  16229. console.error( 'THREE.WebGLRenderer: ' + error.message );
  16230. throw error;
  16231. }
  16232. let extensions, capabilities, state, info;
  16233. let properties, textures, cubemaps, cubeuvmaps, attributes, geometries, objects;
  16234. let programCache, materials, renderLists, renderStates, clipping, shadowMap;
  16235. let background, morphtargets, bufferRenderer, indexedBufferRenderer;
  16236. let utils, bindingStates, uniformsGroups;
  16237. function initGLContext() {
  16238. extensions = new WebGLExtensions( _gl );
  16239. capabilities = new WebGLCapabilities( _gl, extensions, parameters );
  16240. extensions.init( capabilities );
  16241. utils = new WebGLUtils( _gl, extensions, capabilities );
  16242. state = new WebGLState( _gl, extensions, capabilities );
  16243. info = new WebGLInfo( _gl );
  16244. properties = new WebGLProperties();
  16245. textures = new WebGLTextures( _gl, extensions, state, properties, capabilities, utils, info );
  16246. cubemaps = new WebGLCubeMaps( _this );
  16247. cubeuvmaps = new WebGLCubeUVMaps( _this );
  16248. attributes = new WebGLAttributes( _gl, capabilities );
  16249. bindingStates = new WebGLBindingStates( _gl, extensions, attributes, capabilities );
  16250. geometries = new WebGLGeometries( _gl, attributes, info, bindingStates );
  16251. objects = new WebGLObjects( _gl, geometries, attributes, info );
  16252. morphtargets = new WebGLMorphtargets( _gl, capabilities, textures );
  16253. clipping = new WebGLClipping( properties );
  16254. programCache = new WebGLPrograms( _this, cubemaps, cubeuvmaps, extensions, capabilities, bindingStates, clipping );
  16255. materials = new WebGLMaterials( _this, properties );
  16256. renderLists = new WebGLRenderLists();
  16257. renderStates = new WebGLRenderStates( extensions, capabilities );
  16258. background = new WebGLBackground( _this, cubemaps, cubeuvmaps, state, objects, _alpha, _premultipliedAlpha );
  16259. shadowMap = new WebGLShadowMap( _this, objects, capabilities );
  16260. uniformsGroups = new WebGLUniformsGroups( _gl, info, capabilities, state );
  16261. bufferRenderer = new WebGLBufferRenderer( _gl, extensions, info, capabilities );
  16262. indexedBufferRenderer = new WebGLIndexedBufferRenderer( _gl, extensions, info, capabilities );
  16263. info.programs = programCache.programs;
  16264. _this.capabilities = capabilities;
  16265. _this.extensions = extensions;
  16266. _this.properties = properties;
  16267. _this.renderLists = renderLists;
  16268. _this.shadowMap = shadowMap;
  16269. _this.state = state;
  16270. _this.info = info;
  16271. }
  16272. initGLContext();
  16273. // xr
  16274. const xr = new WebXRManager( _this, _gl );
  16275. this.xr = xr;
  16276. // API
  16277. this.getContext = function () {
  16278. return _gl;
  16279. };
  16280. this.getContextAttributes = function () {
  16281. return _gl.getContextAttributes();
  16282. };
  16283. this.forceContextLoss = function () {
  16284. const extension = extensions.get( 'WEBGL_lose_context' );
  16285. if ( extension ) extension.loseContext();
  16286. };
  16287. this.forceContextRestore = function () {
  16288. const extension = extensions.get( 'WEBGL_lose_context' );
  16289. if ( extension ) extension.restoreContext();
  16290. };
  16291. this.getPixelRatio = function () {
  16292. return _pixelRatio;
  16293. };
  16294. this.setPixelRatio = function ( value ) {
  16295. if ( value === undefined ) return;
  16296. _pixelRatio = value;
  16297. this.setSize( _width, _height, false );
  16298. };
  16299. this.getSize = function ( target ) {
  16300. return target.set( _width, _height );
  16301. };
  16302. this.setSize = function ( width, height, updateStyle ) {
  16303. if ( xr.isPresenting ) {
  16304. console.warn( 'THREE.WebGLRenderer: Can\'t change size while VR device is presenting.' );
  16305. return;
  16306. }
  16307. _width = width;
  16308. _height = height;
  16309. _canvas.width = Math.floor( width * _pixelRatio );
  16310. _canvas.height = Math.floor( height * _pixelRatio );
  16311. if ( updateStyle !== false ) {
  16312. _canvas.style.width = width + 'px';
  16313. _canvas.style.height = height + 'px';
  16314. }
  16315. this.setViewport( 0, 0, width, height );
  16316. };
  16317. this.getDrawingBufferSize = function ( target ) {
  16318. return target.set( _width * _pixelRatio, _height * _pixelRatio ).floor();
  16319. };
  16320. this.setDrawingBufferSize = function ( width, height, pixelRatio ) {
  16321. _width = width;
  16322. _height = height;
  16323. _pixelRatio = pixelRatio;
  16324. _canvas.width = Math.floor( width * pixelRatio );
  16325. _canvas.height = Math.floor( height * pixelRatio );
  16326. this.setViewport( 0, 0, width, height );
  16327. };
  16328. this.getCurrentViewport = function ( target ) {
  16329. return target.copy( _currentViewport );
  16330. };
  16331. this.getViewport = function ( target ) {
  16332. return target.copy( _viewport );
  16333. };
  16334. this.setViewport = function ( x, y, width, height ) {
  16335. if ( x.isVector4 ) {
  16336. _viewport.set( x.x, x.y, x.z, x.w );
  16337. } else {
  16338. _viewport.set( x, y, width, height );
  16339. }
  16340. state.viewport( _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ).floor() );
  16341. };
  16342. this.getScissor = function ( target ) {
  16343. return target.copy( _scissor );
  16344. };
  16345. this.setScissor = function ( x, y, width, height ) {
  16346. if ( x.isVector4 ) {
  16347. _scissor.set( x.x, x.y, x.z, x.w );
  16348. } else {
  16349. _scissor.set( x, y, width, height );
  16350. }
  16351. state.scissor( _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ).floor() );
  16352. };
  16353. this.getScissorTest = function () {
  16354. return _scissorTest;
  16355. };
  16356. this.setScissorTest = function ( boolean ) {
  16357. state.setScissorTest( _scissorTest = boolean );
  16358. };
  16359. this.setOpaqueSort = function ( method ) {
  16360. _opaqueSort = method;
  16361. };
  16362. this.setTransparentSort = function ( method ) {
  16363. _transparentSort = method;
  16364. };
  16365. // Clearing
  16366. this.getClearColor = function ( target ) {
  16367. return target.copy( background.getClearColor() );
  16368. };
  16369. this.setClearColor = function () {
  16370. background.setClearColor.apply( background, arguments );
  16371. };
  16372. this.getClearAlpha = function () {
  16373. return background.getClearAlpha();
  16374. };
  16375. this.setClearAlpha = function () {
  16376. background.setClearAlpha.apply( background, arguments );
  16377. };
  16378. this.clear = function ( color = true, depth = true, stencil = true ) {
  16379. let bits = 0;
  16380. if ( color ) bits |= _gl.COLOR_BUFFER_BIT;
  16381. if ( depth ) bits |= _gl.DEPTH_BUFFER_BIT;
  16382. if ( stencil ) bits |= _gl.STENCIL_BUFFER_BIT;
  16383. _gl.clear( bits );
  16384. };
  16385. this.clearColor = function () {
  16386. this.clear( true, false, false );
  16387. };
  16388. this.clearDepth = function () {
  16389. this.clear( false, true, false );
  16390. };
  16391. this.clearStencil = function () {
  16392. this.clear( false, false, true );
  16393. };
  16394. //
  16395. this.dispose = function () {
  16396. _canvas.removeEventListener( 'webglcontextlost', onContextLost, false );
  16397. _canvas.removeEventListener( 'webglcontextrestored', onContextRestore, false );
  16398. _canvas.removeEventListener( 'webglcontextcreationerror', onContextCreationError, false );
  16399. renderLists.dispose();
  16400. renderStates.dispose();
  16401. properties.dispose();
  16402. cubemaps.dispose();
  16403. cubeuvmaps.dispose();
  16404. objects.dispose();
  16405. bindingStates.dispose();
  16406. uniformsGroups.dispose();
  16407. programCache.dispose();
  16408. xr.dispose();
  16409. xr.removeEventListener( 'sessionstart', onXRSessionStart );
  16410. xr.removeEventListener( 'sessionend', onXRSessionEnd );
  16411. if ( _transmissionRenderTarget ) {
  16412. _transmissionRenderTarget.dispose();
  16413. _transmissionRenderTarget = null;
  16414. }
  16415. animation.stop();
  16416. };
  16417. // Events
  16418. function onContextLost( event ) {
  16419. event.preventDefault();
  16420. console.log( 'THREE.WebGLRenderer: Context Lost.' );
  16421. _isContextLost = true;
  16422. }
  16423. function onContextRestore( /* event */ ) {
  16424. console.log( 'THREE.WebGLRenderer: Context Restored.' );
  16425. _isContextLost = false;
  16426. const infoAutoReset = info.autoReset;
  16427. const shadowMapEnabled = shadowMap.enabled;
  16428. const shadowMapAutoUpdate = shadowMap.autoUpdate;
  16429. const shadowMapNeedsUpdate = shadowMap.needsUpdate;
  16430. const shadowMapType = shadowMap.type;
  16431. initGLContext();
  16432. info.autoReset = infoAutoReset;
  16433. shadowMap.enabled = shadowMapEnabled;
  16434. shadowMap.autoUpdate = shadowMapAutoUpdate;
  16435. shadowMap.needsUpdate = shadowMapNeedsUpdate;
  16436. shadowMap.type = shadowMapType;
  16437. }
  16438. function onContextCreationError( event ) {
  16439. console.error( 'THREE.WebGLRenderer: A WebGL context could not be created. Reason: ', event.statusMessage );
  16440. }
  16441. function onMaterialDispose( event ) {
  16442. const material = event.target;
  16443. material.removeEventListener( 'dispose', onMaterialDispose );
  16444. deallocateMaterial( material );
  16445. }
  16446. // Buffer deallocation
  16447. function deallocateMaterial( material ) {
  16448. releaseMaterialProgramReferences( material );
  16449. properties.remove( material );
  16450. }
  16451. function releaseMaterialProgramReferences( material ) {
  16452. const programs = properties.get( material ).programs;
  16453. if ( programs !== undefined ) {
  16454. programs.forEach( function ( program ) {
  16455. programCache.releaseProgram( program );
  16456. } );
  16457. if ( material.isShaderMaterial ) {
  16458. programCache.releaseShaderCache( material );
  16459. }
  16460. }
  16461. }
  16462. // Buffer rendering
  16463. this.renderBufferDirect = function ( camera, scene, geometry, material, object, group ) {
  16464. if ( scene === null ) scene = _emptyScene; // renderBufferDirect second parameter used to be fog (could be null)
  16465. const frontFaceCW = ( object.isMesh && object.matrixWorld.determinant() < 0 );
  16466. const program = setProgram( camera, scene, geometry, material, object );
  16467. state.setMaterial( material, frontFaceCW );
  16468. //
  16469. let index = geometry.index;
  16470. let rangeFactor = 1;
  16471. if ( material.wireframe === true ) {
  16472. index = geometries.getWireframeAttribute( geometry );
  16473. rangeFactor = 2;
  16474. }
  16475. //
  16476. const drawRange = geometry.drawRange;
  16477. const position = geometry.attributes.position;
  16478. let drawStart = drawRange.start * rangeFactor;
  16479. let drawEnd = ( drawRange.start + drawRange.count ) * rangeFactor;
  16480. if ( group !== null ) {
  16481. drawStart = Math.max( drawStart, group.start * rangeFactor );
  16482. drawEnd = Math.min( drawEnd, ( group.start + group.count ) * rangeFactor );
  16483. }
  16484. if ( index !== null ) {
  16485. drawStart = Math.max( drawStart, 0 );
  16486. drawEnd = Math.min( drawEnd, index.count );
  16487. } else if ( position !== undefined && position !== null ) {
  16488. drawStart = Math.max( drawStart, 0 );
  16489. drawEnd = Math.min( drawEnd, position.count );
  16490. }
  16491. const drawCount = drawEnd - drawStart;
  16492. if ( drawCount < 0 || drawCount === Infinity ) return;
  16493. //
  16494. bindingStates.setup( object, material, program, geometry, index );
  16495. let attribute;
  16496. let renderer = bufferRenderer;
  16497. if ( index !== null ) {
  16498. attribute = attributes.get( index );
  16499. renderer = indexedBufferRenderer;
  16500. renderer.setIndex( attribute );
  16501. }
  16502. //
  16503. if ( object.isMesh ) {
  16504. if ( material.wireframe === true ) {
  16505. state.setLineWidth( material.wireframeLinewidth * getTargetPixelRatio() );
  16506. renderer.setMode( _gl.LINES );
  16507. } else {
  16508. renderer.setMode( _gl.TRIANGLES );
  16509. }
  16510. } else if ( object.isLine ) {
  16511. let lineWidth = material.linewidth;
  16512. if ( lineWidth === undefined ) lineWidth = 1; // Not using Line*Material
  16513. state.setLineWidth( lineWidth * getTargetPixelRatio() );
  16514. if ( object.isLineSegments ) {
  16515. renderer.setMode( _gl.LINES );
  16516. } else if ( object.isLineLoop ) {
  16517. renderer.setMode( _gl.LINE_LOOP );
  16518. } else {
  16519. renderer.setMode( _gl.LINE_STRIP );
  16520. }
  16521. } else if ( object.isPoints ) {
  16522. renderer.setMode( _gl.POINTS );
  16523. } else if ( object.isSprite ) {
  16524. renderer.setMode( _gl.TRIANGLES );
  16525. }
  16526. if ( object.isInstancedMesh ) {
  16527. renderer.renderInstances( drawStart, drawCount, object.count );
  16528. } else if ( geometry.isInstancedBufferGeometry ) {
  16529. const maxInstanceCount = geometry._maxInstanceCount !== undefined ? geometry._maxInstanceCount : Infinity;
  16530. const instanceCount = Math.min( geometry.instanceCount, maxInstanceCount );
  16531. renderer.renderInstances( drawStart, drawCount, instanceCount );
  16532. } else {
  16533. renderer.render( drawStart, drawCount );
  16534. }
  16535. };
  16536. // Compile
  16537. this.compile = function ( scene, camera ) {
  16538. function prepare( material, scene, object ) {
  16539. if ( material.transparent === true && material.side === DoubleSide && material.forceSinglePass === false ) {
  16540. material.side = BackSide;
  16541. material.needsUpdate = true;
  16542. getProgram( material, scene, object );
  16543. material.side = FrontSide;
  16544. material.needsUpdate = true;
  16545. getProgram( material, scene, object );
  16546. material.side = DoubleSide;
  16547. } else {
  16548. getProgram( material, scene, object );
  16549. }
  16550. }
  16551. currentRenderState = renderStates.get( scene );
  16552. currentRenderState.init();
  16553. renderStateStack.push( currentRenderState );
  16554. scene.traverseVisible( function ( object ) {
  16555. if ( object.isLight && object.layers.test( camera.layers ) ) {
  16556. currentRenderState.pushLight( object );
  16557. if ( object.castShadow ) {
  16558. currentRenderState.pushShadow( object );
  16559. }
  16560. }
  16561. } );
  16562. currentRenderState.setupLights( _this.physicallyCorrectLights );
  16563. scene.traverse( function ( object ) {
  16564. const material = object.material;
  16565. if ( material ) {
  16566. if ( Array.isArray( material ) ) {
  16567. for ( let i = 0; i < material.length; i ++ ) {
  16568. const material2 = material[ i ];
  16569. prepare( material2, scene, object );
  16570. }
  16571. } else {
  16572. prepare( material, scene, object );
  16573. }
  16574. }
  16575. } );
  16576. renderStateStack.pop();
  16577. currentRenderState = null;
  16578. };
  16579. // Animation Loop
  16580. let onAnimationFrameCallback = null;
  16581. function onAnimationFrame( time ) {
  16582. if ( onAnimationFrameCallback ) onAnimationFrameCallback( time );
  16583. }
  16584. function onXRSessionStart() {
  16585. animation.stop();
  16586. }
  16587. function onXRSessionEnd() {
  16588. animation.start();
  16589. }
  16590. const animation = new WebGLAnimation();
  16591. animation.setAnimationLoop( onAnimationFrame );
  16592. if ( typeof self !== 'undefined' ) animation.setContext( self );
  16593. this.setAnimationLoop = function ( callback ) {
  16594. onAnimationFrameCallback = callback;
  16595. xr.setAnimationLoop( callback );
  16596. ( callback === null ) ? animation.stop() : animation.start();
  16597. };
  16598. xr.addEventListener( 'sessionstart', onXRSessionStart );
  16599. xr.addEventListener( 'sessionend', onXRSessionEnd );
  16600. // Rendering
  16601. this.render = function ( scene, camera ) {
  16602. if ( camera !== undefined && camera.isCamera !== true ) {
  16603. console.error( 'THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.' );
  16604. return;
  16605. }
  16606. if ( _isContextLost === true ) return;
  16607. // update scene graph
  16608. if ( scene.matrixWorldAutoUpdate === true ) scene.updateMatrixWorld();
  16609. // update camera matrices and frustum
  16610. if ( camera.parent === null && camera.matrixWorldAutoUpdate === true ) camera.updateMatrixWorld();
  16611. if ( xr.enabled === true && xr.isPresenting === true ) {
  16612. if ( xr.cameraAutoUpdate === true ) xr.updateCamera( camera );
  16613. camera = xr.getCamera(); // use XR camera for rendering
  16614. }
  16615. //
  16616. if ( scene.isScene === true ) scene.onBeforeRender( _this, scene, camera, _currentRenderTarget );
  16617. currentRenderState = renderStates.get( scene, renderStateStack.length );
  16618. currentRenderState.init();
  16619. renderStateStack.push( currentRenderState );
  16620. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  16621. _frustum.setFromProjectionMatrix( _projScreenMatrix );
  16622. _localClippingEnabled = this.localClippingEnabled;
  16623. _clippingEnabled = clipping.init( this.clippingPlanes, _localClippingEnabled );
  16624. currentRenderList = renderLists.get( scene, renderListStack.length );
  16625. currentRenderList.init();
  16626. renderListStack.push( currentRenderList );
  16627. projectObject( scene, camera, 0, _this.sortObjects );
  16628. currentRenderList.finish();
  16629. if ( _this.sortObjects === true ) {
  16630. currentRenderList.sort( _opaqueSort, _transparentSort );
  16631. }
  16632. //
  16633. if ( _clippingEnabled === true ) clipping.beginShadows();
  16634. const shadowsArray = currentRenderState.state.shadowsArray;
  16635. shadowMap.render( shadowsArray, scene, camera );
  16636. if ( _clippingEnabled === true ) clipping.endShadows();
  16637. //
  16638. if ( this.info.autoReset === true ) this.info.reset();
  16639. //
  16640. background.render( currentRenderList, scene );
  16641. // render scene
  16642. currentRenderState.setupLights( _this.physicallyCorrectLights );
  16643. if ( camera.isArrayCamera ) {
  16644. const cameras = camera.cameras;
  16645. for ( let i = 0, l = cameras.length; i < l; i ++ ) {
  16646. const camera2 = cameras[ i ];
  16647. renderScene( currentRenderList, scene, camera2, camera2.viewport );
  16648. }
  16649. } else {
  16650. renderScene( currentRenderList, scene, camera );
  16651. }
  16652. //
  16653. if ( _currentRenderTarget !== null ) {
  16654. // resolve multisample renderbuffers to a single-sample texture if necessary
  16655. textures.updateMultisampleRenderTarget( _currentRenderTarget );
  16656. // Generate mipmap if we're using any kind of mipmap filtering
  16657. textures.updateRenderTargetMipmap( _currentRenderTarget );
  16658. }
  16659. //
  16660. if ( scene.isScene === true ) scene.onAfterRender( _this, scene, camera );
  16661. // _gl.finish();
  16662. bindingStates.resetDefaultState();
  16663. _currentMaterialId = - 1;
  16664. _currentCamera = null;
  16665. renderStateStack.pop();
  16666. if ( renderStateStack.length > 0 ) {
  16667. currentRenderState = renderStateStack[ renderStateStack.length - 1 ];
  16668. } else {
  16669. currentRenderState = null;
  16670. }
  16671. renderListStack.pop();
  16672. if ( renderListStack.length > 0 ) {
  16673. currentRenderList = renderListStack[ renderListStack.length - 1 ];
  16674. } else {
  16675. currentRenderList = null;
  16676. }
  16677. };
  16678. function projectObject( object, camera, groupOrder, sortObjects ) {
  16679. if ( object.visible === false ) return;
  16680. const visible = object.layers.test( camera.layers );
  16681. if ( visible ) {
  16682. if ( object.isGroup ) {
  16683. groupOrder = object.renderOrder;
  16684. } else if ( object.isLOD ) {
  16685. if ( object.autoUpdate === true ) object.update( camera );
  16686. } else if ( object.isLight ) {
  16687. currentRenderState.pushLight( object );
  16688. if ( object.castShadow ) {
  16689. currentRenderState.pushShadow( object );
  16690. }
  16691. } else if ( object.isSprite ) {
  16692. if ( ! object.frustumCulled || _frustum.intersectsSprite( object ) ) {
  16693. if ( sortObjects ) {
  16694. _vector3.setFromMatrixPosition( object.matrixWorld )
  16695. .applyMatrix4( _projScreenMatrix );
  16696. }
  16697. const geometry = objects.update( object );
  16698. const material = object.material;
  16699. if ( material.visible ) {
  16700. currentRenderList.push( object, geometry, material, groupOrder, _vector3.z, null );
  16701. }
  16702. }
  16703. } else if ( object.isMesh || object.isLine || object.isPoints ) {
  16704. if ( object.isSkinnedMesh ) {
  16705. // update skeleton only once in a frame
  16706. if ( object.skeleton.frame !== info.render.frame ) {
  16707. object.skeleton.update();
  16708. object.skeleton.frame = info.render.frame;
  16709. }
  16710. }
  16711. if ( ! object.frustumCulled || _frustum.intersectsObject( object ) ) {
  16712. if ( sortObjects ) {
  16713. _vector3.setFromMatrixPosition( object.matrixWorld )
  16714. .applyMatrix4( _projScreenMatrix );
  16715. }
  16716. const geometry = objects.update( object );
  16717. const material = object.material;
  16718. if ( Array.isArray( material ) ) {
  16719. const groups = geometry.groups;
  16720. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  16721. const group = groups[ i ];
  16722. const groupMaterial = material[ group.materialIndex ];
  16723. if ( groupMaterial && groupMaterial.visible ) {
  16724. currentRenderList.push( object, geometry, groupMaterial, groupOrder, _vector3.z, group );
  16725. }
  16726. }
  16727. } else if ( material.visible ) {
  16728. currentRenderList.push( object, geometry, material, groupOrder, _vector3.z, null );
  16729. }
  16730. }
  16731. }
  16732. }
  16733. const children = object.children;
  16734. for ( let i = 0, l = children.length; i < l; i ++ ) {
  16735. projectObject( children[ i ], camera, groupOrder, sortObjects );
  16736. }
  16737. }
  16738. function renderScene( currentRenderList, scene, camera, viewport ) {
  16739. const opaqueObjects = currentRenderList.opaque;
  16740. const transmissiveObjects = currentRenderList.transmissive;
  16741. const transparentObjects = currentRenderList.transparent;
  16742. currentRenderState.setupLightsView( camera );
  16743. if ( _clippingEnabled === true ) clipping.setGlobalState( _this.clippingPlanes, camera );
  16744. if ( transmissiveObjects.length > 0 ) renderTransmissionPass( opaqueObjects, scene, camera );
  16745. if ( viewport ) state.viewport( _currentViewport.copy( viewport ) );
  16746. if ( opaqueObjects.length > 0 ) renderObjects( opaqueObjects, scene, camera );
  16747. if ( transmissiveObjects.length > 0 ) renderObjects( transmissiveObjects, scene, camera );
  16748. if ( transparentObjects.length > 0 ) renderObjects( transparentObjects, scene, camera );
  16749. // Ensure depth buffer writing is enabled so it can be cleared on next render
  16750. state.buffers.depth.setTest( true );
  16751. state.buffers.depth.setMask( true );
  16752. state.buffers.color.setMask( true );
  16753. state.setPolygonOffset( false );
  16754. }
  16755. function renderTransmissionPass( opaqueObjects, scene, camera ) {
  16756. const isWebGL2 = capabilities.isWebGL2;
  16757. if ( _transmissionRenderTarget === null ) {
  16758. _transmissionRenderTarget = new WebGLRenderTarget( 1, 1, {
  16759. generateMipmaps: true,
  16760. type: extensions.has( 'EXT_color_buffer_half_float' ) ? HalfFloatType : UnsignedByteType,
  16761. minFilter: LinearMipmapLinearFilter,
  16762. samples: ( isWebGL2 && _antialias === true ) ? 4 : 0
  16763. } );
  16764. }
  16765. _this.getDrawingBufferSize( _vector2 );
  16766. if ( isWebGL2 ) {
  16767. _transmissionRenderTarget.setSize( _vector2.x, _vector2.y );
  16768. } else {
  16769. _transmissionRenderTarget.setSize( floorPowerOfTwo( _vector2.x ), floorPowerOfTwo( _vector2.y ) );
  16770. }
  16771. //
  16772. const currentRenderTarget = _this.getRenderTarget();
  16773. _this.setRenderTarget( _transmissionRenderTarget );
  16774. _this.clear();
  16775. // Turn off the features which can affect the frag color for opaque objects pass.
  16776. // Otherwise they are applied twice in opaque objects pass and transmission objects pass.
  16777. const currentToneMapping = _this.toneMapping;
  16778. _this.toneMapping = NoToneMapping;
  16779. renderObjects( opaqueObjects, scene, camera );
  16780. _this.toneMapping = currentToneMapping;
  16781. textures.updateMultisampleRenderTarget( _transmissionRenderTarget );
  16782. textures.updateRenderTargetMipmap( _transmissionRenderTarget );
  16783. _this.setRenderTarget( currentRenderTarget );
  16784. }
  16785. function renderObjects( renderList, scene, camera ) {
  16786. const overrideMaterial = scene.isScene === true ? scene.overrideMaterial : null;
  16787. for ( let i = 0, l = renderList.length; i < l; i ++ ) {
  16788. const renderItem = renderList[ i ];
  16789. const object = renderItem.object;
  16790. const geometry = renderItem.geometry;
  16791. const material = overrideMaterial === null ? renderItem.material : overrideMaterial;
  16792. const group = renderItem.group;
  16793. if ( object.layers.test( camera.layers ) ) {
  16794. renderObject( object, scene, camera, geometry, material, group );
  16795. }
  16796. }
  16797. }
  16798. function renderObject( object, scene, camera, geometry, material, group ) {
  16799. object.onBeforeRender( _this, scene, camera, geometry, material, group );
  16800. object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  16801. object.normalMatrix.getNormalMatrix( object.modelViewMatrix );
  16802. material.onBeforeRender( _this, scene, camera, geometry, object, group );
  16803. if ( material.transparent === true && material.side === DoubleSide && material.forceSinglePass === false ) {
  16804. material.side = BackSide;
  16805. material.needsUpdate = true;
  16806. _this.renderBufferDirect( camera, scene, geometry, material, object, group );
  16807. material.side = FrontSide;
  16808. material.needsUpdate = true;
  16809. _this.renderBufferDirect( camera, scene, geometry, material, object, group );
  16810. material.side = DoubleSide;
  16811. } else {
  16812. _this.renderBufferDirect( camera, scene, geometry, material, object, group );
  16813. }
  16814. object.onAfterRender( _this, scene, camera, geometry, material, group );
  16815. }
  16816. function getProgram( material, scene, object ) {
  16817. if ( scene.isScene !== true ) scene = _emptyScene; // scene could be a Mesh, Line, Points, ...
  16818. const materialProperties = properties.get( material );
  16819. const lights = currentRenderState.state.lights;
  16820. const shadowsArray = currentRenderState.state.shadowsArray;
  16821. const lightsStateVersion = lights.state.version;
  16822. const parameters = programCache.getParameters( material, lights.state, shadowsArray, scene, object );
  16823. const programCacheKey = programCache.getProgramCacheKey( parameters );
  16824. let programs = materialProperties.programs;
  16825. // always update environment and fog - changing these trigger an getProgram call, but it's possible that the program doesn't change
  16826. materialProperties.environment = material.isMeshStandardMaterial ? scene.environment : null;
  16827. materialProperties.fog = scene.fog;
  16828. materialProperties.envMap = ( material.isMeshStandardMaterial ? cubeuvmaps : cubemaps ).get( material.envMap || materialProperties.environment );
  16829. if ( programs === undefined ) {
  16830. // new material
  16831. material.addEventListener( 'dispose', onMaterialDispose );
  16832. programs = new Map();
  16833. materialProperties.programs = programs;
  16834. }
  16835. let program = programs.get( programCacheKey );
  16836. if ( program !== undefined ) {
  16837. // early out if program and light state is identical
  16838. if ( materialProperties.currentProgram === program && materialProperties.lightsStateVersion === lightsStateVersion ) {
  16839. updateCommonMaterialProperties( material, parameters );
  16840. return program;
  16841. }
  16842. } else {
  16843. parameters.uniforms = programCache.getUniforms( material );
  16844. material.onBuild( object, parameters, _this );
  16845. material.onBeforeCompile( parameters, _this );
  16846. program = programCache.acquireProgram( parameters, programCacheKey );
  16847. programs.set( programCacheKey, program );
  16848. materialProperties.uniforms = parameters.uniforms;
  16849. }
  16850. const uniforms = materialProperties.uniforms;
  16851. if ( ( ! material.isShaderMaterial && ! material.isRawShaderMaterial ) || material.clipping === true ) {
  16852. uniforms.clippingPlanes = clipping.uniform;
  16853. }
  16854. updateCommonMaterialProperties( material, parameters );
  16855. // store the light setup it was created for
  16856. materialProperties.needsLights = materialNeedsLights( material );
  16857. materialProperties.lightsStateVersion = lightsStateVersion;
  16858. if ( materialProperties.needsLights ) {
  16859. // wire up the material to this renderer's lighting state
  16860. uniforms.ambientLightColor.value = lights.state.ambient;
  16861. uniforms.lightProbe.value = lights.state.probe;
  16862. uniforms.directionalLights.value = lights.state.directional;
  16863. uniforms.directionalLightShadows.value = lights.state.directionalShadow;
  16864. uniforms.spotLights.value = lights.state.spot;
  16865. uniforms.spotLightShadows.value = lights.state.spotShadow;
  16866. uniforms.rectAreaLights.value = lights.state.rectArea;
  16867. uniforms.ltc_1.value = lights.state.rectAreaLTC1;
  16868. uniforms.ltc_2.value = lights.state.rectAreaLTC2;
  16869. uniforms.pointLights.value = lights.state.point;
  16870. uniforms.pointLightShadows.value = lights.state.pointShadow;
  16871. uniforms.hemisphereLights.value = lights.state.hemi;
  16872. uniforms.directionalShadowMap.value = lights.state.directionalShadowMap;
  16873. uniforms.directionalShadowMatrix.value = lights.state.directionalShadowMatrix;
  16874. uniforms.spotShadowMap.value = lights.state.spotShadowMap;
  16875. uniforms.spotLightMatrix.value = lights.state.spotLightMatrix;
  16876. uniforms.spotLightMap.value = lights.state.spotLightMap;
  16877. uniforms.pointShadowMap.value = lights.state.pointShadowMap;
  16878. uniforms.pointShadowMatrix.value = lights.state.pointShadowMatrix;
  16879. // TODO (abelnation): add area lights shadow info to uniforms
  16880. }
  16881. const progUniforms = program.getUniforms();
  16882. const uniformsList = WebGLUniforms.seqWithValue( progUniforms.seq, uniforms );
  16883. materialProperties.currentProgram = program;
  16884. materialProperties.uniformsList = uniformsList;
  16885. return program;
  16886. }
  16887. function updateCommonMaterialProperties( material, parameters ) {
  16888. const materialProperties = properties.get( material );
  16889. materialProperties.outputEncoding = parameters.outputEncoding;
  16890. materialProperties.instancing = parameters.instancing;
  16891. materialProperties.skinning = parameters.skinning;
  16892. materialProperties.morphTargets = parameters.morphTargets;
  16893. materialProperties.morphNormals = parameters.morphNormals;
  16894. materialProperties.morphColors = parameters.morphColors;
  16895. materialProperties.morphTargetsCount = parameters.morphTargetsCount;
  16896. materialProperties.numClippingPlanes = parameters.numClippingPlanes;
  16897. materialProperties.numIntersection = parameters.numClipIntersection;
  16898. materialProperties.vertexAlphas = parameters.vertexAlphas;
  16899. materialProperties.vertexTangents = parameters.vertexTangents;
  16900. materialProperties.toneMapping = parameters.toneMapping;
  16901. }
  16902. function setProgram( camera, scene, geometry, material, object ) {
  16903. if ( scene.isScene !== true ) scene = _emptyScene; // scene could be a Mesh, Line, Points, ...
  16904. textures.resetTextureUnits();
  16905. const fog = scene.fog;
  16906. const environment = material.isMeshStandardMaterial ? scene.environment : null;
  16907. const encoding = ( _currentRenderTarget === null ) ? _this.outputEncoding : ( _currentRenderTarget.isXRRenderTarget === true ? _currentRenderTarget.texture.encoding : LinearEncoding );
  16908. const envMap = ( material.isMeshStandardMaterial ? cubeuvmaps : cubemaps ).get( material.envMap || environment );
  16909. const vertexAlphas = material.vertexColors === true && !! geometry.attributes.color && geometry.attributes.color.itemSize === 4;
  16910. const vertexTangents = !! material.normalMap && !! geometry.attributes.tangent;
  16911. const morphTargets = !! geometry.morphAttributes.position;
  16912. const morphNormals = !! geometry.morphAttributes.normal;
  16913. const morphColors = !! geometry.morphAttributes.color;
  16914. const toneMapping = material.toneMapped ? _this.toneMapping : NoToneMapping;
  16915. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  16916. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  16917. const materialProperties = properties.get( material );
  16918. const lights = currentRenderState.state.lights;
  16919. if ( _clippingEnabled === true ) {
  16920. if ( _localClippingEnabled === true || camera !== _currentCamera ) {
  16921. const useCache =
  16922. camera === _currentCamera &&
  16923. material.id === _currentMaterialId;
  16924. // we might want to call this function with some ClippingGroup
  16925. // object instead of the material, once it becomes feasible
  16926. // (#8465, #8379)
  16927. clipping.setState( material, camera, useCache );
  16928. }
  16929. }
  16930. //
  16931. let needsProgramChange = false;
  16932. if ( material.version === materialProperties.__version ) {
  16933. if ( materialProperties.needsLights && ( materialProperties.lightsStateVersion !== lights.state.version ) ) {
  16934. needsProgramChange = true;
  16935. } else if ( materialProperties.outputEncoding !== encoding ) {
  16936. needsProgramChange = true;
  16937. } else if ( object.isInstancedMesh && materialProperties.instancing === false ) {
  16938. needsProgramChange = true;
  16939. } else if ( ! object.isInstancedMesh && materialProperties.instancing === true ) {
  16940. needsProgramChange = true;
  16941. } else if ( object.isSkinnedMesh && materialProperties.skinning === false ) {
  16942. needsProgramChange = true;
  16943. } else if ( ! object.isSkinnedMesh && materialProperties.skinning === true ) {
  16944. needsProgramChange = true;
  16945. } else if ( materialProperties.envMap !== envMap ) {
  16946. needsProgramChange = true;
  16947. } else if ( material.fog === true && materialProperties.fog !== fog ) {
  16948. needsProgramChange = true;
  16949. } else if ( materialProperties.numClippingPlanes !== undefined &&
  16950. ( materialProperties.numClippingPlanes !== clipping.numPlanes ||
  16951. materialProperties.numIntersection !== clipping.numIntersection ) ) {
  16952. needsProgramChange = true;
  16953. } else if ( materialProperties.vertexAlphas !== vertexAlphas ) {
  16954. needsProgramChange = true;
  16955. } else if ( materialProperties.vertexTangents !== vertexTangents ) {
  16956. needsProgramChange = true;
  16957. } else if ( materialProperties.morphTargets !== morphTargets ) {
  16958. needsProgramChange = true;
  16959. } else if ( materialProperties.morphNormals !== morphNormals ) {
  16960. needsProgramChange = true;
  16961. } else if ( materialProperties.morphColors !== morphColors ) {
  16962. needsProgramChange = true;
  16963. } else if ( materialProperties.toneMapping !== toneMapping ) {
  16964. needsProgramChange = true;
  16965. } else if ( capabilities.isWebGL2 === true && materialProperties.morphTargetsCount !== morphTargetsCount ) {
  16966. needsProgramChange = true;
  16967. }
  16968. } else {
  16969. needsProgramChange = true;
  16970. materialProperties.__version = material.version;
  16971. }
  16972. //
  16973. let program = materialProperties.currentProgram;
  16974. if ( needsProgramChange === true ) {
  16975. program = getProgram( material, scene, object );
  16976. }
  16977. let refreshProgram = false;
  16978. let refreshMaterial = false;
  16979. let refreshLights = false;
  16980. const p_uniforms = program.getUniforms(),
  16981. m_uniforms = materialProperties.uniforms;
  16982. if ( state.useProgram( program.program ) ) {
  16983. refreshProgram = true;
  16984. refreshMaterial = true;
  16985. refreshLights = true;
  16986. }
  16987. if ( material.id !== _currentMaterialId ) {
  16988. _currentMaterialId = material.id;
  16989. refreshMaterial = true;
  16990. }
  16991. if ( refreshProgram || _currentCamera !== camera ) {
  16992. p_uniforms.setValue( _gl, 'projectionMatrix', camera.projectionMatrix );
  16993. if ( capabilities.logarithmicDepthBuffer ) {
  16994. p_uniforms.setValue( _gl, 'logDepthBufFC',
  16995. 2.0 / ( Math.log( camera.far + 1.0 ) / Math.LN2 ) );
  16996. }
  16997. if ( _currentCamera !== camera ) {
  16998. _currentCamera = camera;
  16999. // lighting uniforms depend on the camera so enforce an update
  17000. // now, in case this material supports lights - or later, when
  17001. // the next material that does gets activated:
  17002. refreshMaterial = true; // set to true on material change
  17003. refreshLights = true; // remains set until update done
  17004. }
  17005. // load material specific uniforms
  17006. // (shader material also gets them for the sake of genericity)
  17007. if ( material.isShaderMaterial ||
  17008. material.isMeshPhongMaterial ||
  17009. material.isMeshToonMaterial ||
  17010. material.isMeshStandardMaterial ||
  17011. material.envMap ) {
  17012. const uCamPos = p_uniforms.map.cameraPosition;
  17013. if ( uCamPos !== undefined ) {
  17014. uCamPos.setValue( _gl,
  17015. _vector3.setFromMatrixPosition( camera.matrixWorld ) );
  17016. }
  17017. }
  17018. if ( material.isMeshPhongMaterial ||
  17019. material.isMeshToonMaterial ||
  17020. material.isMeshLambertMaterial ||
  17021. material.isMeshBasicMaterial ||
  17022. material.isMeshStandardMaterial ||
  17023. material.isShaderMaterial ) {
  17024. p_uniforms.setValue( _gl, 'isOrthographic', camera.isOrthographicCamera === true );
  17025. }
  17026. if ( material.isMeshPhongMaterial ||
  17027. material.isMeshToonMaterial ||
  17028. material.isMeshLambertMaterial ||
  17029. material.isMeshBasicMaterial ||
  17030. material.isMeshStandardMaterial ||
  17031. material.isShaderMaterial ||
  17032. material.isShadowMaterial ||
  17033. object.isSkinnedMesh ) {
  17034. p_uniforms.setValue( _gl, 'viewMatrix', camera.matrixWorldInverse );
  17035. }
  17036. }
  17037. // skinning and morph target uniforms must be set even if material didn't change
  17038. // auto-setting of texture unit for bone and morph texture must go before other textures
  17039. // otherwise textures used for skinning and morphing can take over texture units reserved for other material textures
  17040. if ( object.isSkinnedMesh ) {
  17041. p_uniforms.setOptional( _gl, object, 'bindMatrix' );
  17042. p_uniforms.setOptional( _gl, object, 'bindMatrixInverse' );
  17043. const skeleton = object.skeleton;
  17044. if ( skeleton ) {
  17045. if ( capabilities.floatVertexTextures ) {
  17046. if ( skeleton.boneTexture === null ) skeleton.computeBoneTexture();
  17047. p_uniforms.setValue( _gl, 'boneTexture', skeleton.boneTexture, textures );
  17048. p_uniforms.setValue( _gl, 'boneTextureSize', skeleton.boneTextureSize );
  17049. } else {
  17050. console.warn( 'THREE.WebGLRenderer: SkinnedMesh can only be used with WebGL 2. With WebGL 1 OES_texture_float and vertex textures support is required.' );
  17051. }
  17052. }
  17053. }
  17054. const morphAttributes = geometry.morphAttributes;
  17055. if ( morphAttributes.position !== undefined || morphAttributes.normal !== undefined || ( morphAttributes.color !== undefined && capabilities.isWebGL2 === true ) ) {
  17056. morphtargets.update( object, geometry, material, program );
  17057. }
  17058. if ( refreshMaterial || materialProperties.receiveShadow !== object.receiveShadow ) {
  17059. materialProperties.receiveShadow = object.receiveShadow;
  17060. p_uniforms.setValue( _gl, 'receiveShadow', object.receiveShadow );
  17061. }
  17062. // https://github.com/mrdoob/three.js/pull/24467#issuecomment-1209031512
  17063. if ( material.isMeshGouraudMaterial && material.envMap !== null ) {
  17064. m_uniforms.envMap.value = envMap;
  17065. m_uniforms.flipEnvMap.value = ( envMap.isCubeTexture && envMap.isRenderTargetTexture === false ) ? - 1 : 1;
  17066. }
  17067. if ( refreshMaterial ) {
  17068. p_uniforms.setValue( _gl, 'toneMappingExposure', _this.toneMappingExposure );
  17069. if ( materialProperties.needsLights ) {
  17070. // the current material requires lighting info
  17071. // note: all lighting uniforms are always set correctly
  17072. // they simply reference the renderer's state for their
  17073. // values
  17074. //
  17075. // use the current material's .needsUpdate flags to set
  17076. // the GL state when required
  17077. markUniformsLightsNeedsUpdate( m_uniforms, refreshLights );
  17078. }
  17079. // refresh uniforms common to several materials
  17080. if ( fog && material.fog === true ) {
  17081. materials.refreshFogUniforms( m_uniforms, fog );
  17082. }
  17083. materials.refreshMaterialUniforms( m_uniforms, material, _pixelRatio, _height, _transmissionRenderTarget );
  17084. WebGLUniforms.upload( _gl, materialProperties.uniformsList, m_uniforms, textures );
  17085. }
  17086. if ( material.isShaderMaterial && material.uniformsNeedUpdate === true ) {
  17087. WebGLUniforms.upload( _gl, materialProperties.uniformsList, m_uniforms, textures );
  17088. material.uniformsNeedUpdate = false;
  17089. }
  17090. if ( material.isSpriteMaterial ) {
  17091. p_uniforms.setValue( _gl, 'center', object.center );
  17092. }
  17093. // common matrices
  17094. p_uniforms.setValue( _gl, 'modelViewMatrix', object.modelViewMatrix );
  17095. p_uniforms.setValue( _gl, 'normalMatrix', object.normalMatrix );
  17096. p_uniforms.setValue( _gl, 'modelMatrix', object.matrixWorld );
  17097. // UBOs
  17098. if ( material.isShaderMaterial || material.isRawShaderMaterial ) {
  17099. const groups = material.uniformsGroups;
  17100. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  17101. if ( capabilities.isWebGL2 ) {
  17102. const group = groups[ i ];
  17103. uniformsGroups.update( group, program );
  17104. uniformsGroups.bind( group, program );
  17105. } else {
  17106. console.warn( 'THREE.WebGLRenderer: Uniform Buffer Objects can only be used with WebGL 2.' );
  17107. }
  17108. }
  17109. }
  17110. return program;
  17111. }
  17112. // If uniforms are marked as clean, they don't need to be loaded to the GPU.
  17113. function markUniformsLightsNeedsUpdate( uniforms, value ) {
  17114. uniforms.ambientLightColor.needsUpdate = value;
  17115. uniforms.lightProbe.needsUpdate = value;
  17116. uniforms.directionalLights.needsUpdate = value;
  17117. uniforms.directionalLightShadows.needsUpdate = value;
  17118. uniforms.pointLights.needsUpdate = value;
  17119. uniforms.pointLightShadows.needsUpdate = value;
  17120. uniforms.spotLights.needsUpdate = value;
  17121. uniforms.spotLightShadows.needsUpdate = value;
  17122. uniforms.rectAreaLights.needsUpdate = value;
  17123. uniforms.hemisphereLights.needsUpdate = value;
  17124. }
  17125. function materialNeedsLights( material ) {
  17126. return material.isMeshLambertMaterial || material.isMeshToonMaterial || material.isMeshPhongMaterial ||
  17127. material.isMeshStandardMaterial || material.isShadowMaterial ||
  17128. ( material.isShaderMaterial && material.lights === true );
  17129. }
  17130. this.getActiveCubeFace = function () {
  17131. return _currentActiveCubeFace;
  17132. };
  17133. this.getActiveMipmapLevel = function () {
  17134. return _currentActiveMipmapLevel;
  17135. };
  17136. this.getRenderTarget = function () {
  17137. return _currentRenderTarget;
  17138. };
  17139. this.setRenderTargetTextures = function ( renderTarget, colorTexture, depthTexture ) {
  17140. properties.get( renderTarget.texture ).__webglTexture = colorTexture;
  17141. properties.get( renderTarget.depthTexture ).__webglTexture = depthTexture;
  17142. const renderTargetProperties = properties.get( renderTarget );
  17143. renderTargetProperties.__hasExternalTextures = true;
  17144. if ( renderTargetProperties.__hasExternalTextures ) {
  17145. renderTargetProperties.__autoAllocateDepthBuffer = depthTexture === undefined;
  17146. if ( ! renderTargetProperties.__autoAllocateDepthBuffer ) {
  17147. // The multisample_render_to_texture extension doesn't work properly if there
  17148. // are midframe flushes and an external depth buffer. Disable use of the extension.
  17149. if ( extensions.has( 'WEBGL_multisampled_render_to_texture' ) === true ) {
  17150. console.warn( 'THREE.WebGLRenderer: Render-to-texture extension was disabled because an external texture was provided' );
  17151. renderTargetProperties.__useRenderToTexture = false;
  17152. }
  17153. }
  17154. }
  17155. };
  17156. this.setRenderTargetFramebuffer = function ( renderTarget, defaultFramebuffer ) {
  17157. const renderTargetProperties = properties.get( renderTarget );
  17158. renderTargetProperties.__webglFramebuffer = defaultFramebuffer;
  17159. renderTargetProperties.__useDefaultFramebuffer = defaultFramebuffer === undefined;
  17160. };
  17161. this.setRenderTarget = function ( renderTarget, activeCubeFace = 0, activeMipmapLevel = 0 ) {
  17162. _currentRenderTarget = renderTarget;
  17163. _currentActiveCubeFace = activeCubeFace;
  17164. _currentActiveMipmapLevel = activeMipmapLevel;
  17165. let useDefaultFramebuffer = true;
  17166. let framebuffer = null;
  17167. let isCube = false;
  17168. let isRenderTarget3D = false;
  17169. if ( renderTarget ) {
  17170. const renderTargetProperties = properties.get( renderTarget );
  17171. if ( renderTargetProperties.__useDefaultFramebuffer !== undefined ) {
  17172. // We need to make sure to rebind the framebuffer.
  17173. state.bindFramebuffer( _gl.FRAMEBUFFER, null );
  17174. useDefaultFramebuffer = false;
  17175. } else if ( renderTargetProperties.__webglFramebuffer === undefined ) {
  17176. textures.setupRenderTarget( renderTarget );
  17177. } else if ( renderTargetProperties.__hasExternalTextures ) {
  17178. // Color and depth texture must be rebound in order for the swapchain to update.
  17179. textures.rebindTextures( renderTarget, properties.get( renderTarget.texture ).__webglTexture, properties.get( renderTarget.depthTexture ).__webglTexture );
  17180. }
  17181. const texture = renderTarget.texture;
  17182. if ( texture.isData3DTexture || texture.isDataArrayTexture || texture.isCompressedArrayTexture ) {
  17183. isRenderTarget3D = true;
  17184. }
  17185. const __webglFramebuffer = properties.get( renderTarget ).__webglFramebuffer;
  17186. if ( renderTarget.isWebGLCubeRenderTarget ) {
  17187. framebuffer = __webglFramebuffer[ activeCubeFace ];
  17188. isCube = true;
  17189. } else if ( ( capabilities.isWebGL2 && renderTarget.samples > 0 ) && textures.useMultisampledRTT( renderTarget ) === false ) {
  17190. framebuffer = properties.get( renderTarget ).__webglMultisampledFramebuffer;
  17191. } else {
  17192. framebuffer = __webglFramebuffer;
  17193. }
  17194. _currentViewport.copy( renderTarget.viewport );
  17195. _currentScissor.copy( renderTarget.scissor );
  17196. _currentScissorTest = renderTarget.scissorTest;
  17197. } else {
  17198. _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ).floor();
  17199. _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ).floor();
  17200. _currentScissorTest = _scissorTest;
  17201. }
  17202. const framebufferBound = state.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  17203. if ( framebufferBound && capabilities.drawBuffers && useDefaultFramebuffer ) {
  17204. state.drawBuffers( renderTarget, framebuffer );
  17205. }
  17206. state.viewport( _currentViewport );
  17207. state.scissor( _currentScissor );
  17208. state.setScissorTest( _currentScissorTest );
  17209. if ( isCube ) {
  17210. const textureProperties = properties.get( renderTarget.texture );
  17211. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + activeCubeFace, textureProperties.__webglTexture, activeMipmapLevel );
  17212. } else if ( isRenderTarget3D ) {
  17213. const textureProperties = properties.get( renderTarget.texture );
  17214. const layer = activeCubeFace || 0;
  17215. _gl.framebufferTextureLayer( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, textureProperties.__webglTexture, activeMipmapLevel || 0, layer );
  17216. }
  17217. _currentMaterialId = - 1; // reset current material to ensure correct uniform bindings
  17218. };
  17219. this.readRenderTargetPixels = function ( renderTarget, x, y, width, height, buffer, activeCubeFaceIndex ) {
  17220. if ( ! ( renderTarget && renderTarget.isWebGLRenderTarget ) ) {
  17221. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.' );
  17222. return;
  17223. }
  17224. let framebuffer = properties.get( renderTarget ).__webglFramebuffer;
  17225. if ( renderTarget.isWebGLCubeRenderTarget && activeCubeFaceIndex !== undefined ) {
  17226. framebuffer = framebuffer[ activeCubeFaceIndex ];
  17227. }
  17228. if ( framebuffer ) {
  17229. state.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  17230. try {
  17231. const texture = renderTarget.texture;
  17232. const textureFormat = texture.format;
  17233. const textureType = texture.type;
  17234. if ( textureFormat !== RGBAFormat && utils.convert( textureFormat ) !== _gl.getParameter( _gl.IMPLEMENTATION_COLOR_READ_FORMAT ) ) {
  17235. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.' );
  17236. return;
  17237. }
  17238. const halfFloatSupportedByExt = ( textureType === HalfFloatType ) && ( extensions.has( 'EXT_color_buffer_half_float' ) || ( capabilities.isWebGL2 && extensions.has( 'EXT_color_buffer_float' ) ) );
  17239. if ( textureType !== UnsignedByteType && utils.convert( textureType ) !== _gl.getParameter( _gl.IMPLEMENTATION_COLOR_READ_TYPE ) && // Edge and Chrome Mac < 52 (#9513)
  17240. ! ( textureType === FloatType && ( capabilities.isWebGL2 || extensions.has( 'OES_texture_float' ) || extensions.has( 'WEBGL_color_buffer_float' ) ) ) && // Chrome Mac >= 52 and Firefox
  17241. ! halfFloatSupportedByExt ) {
  17242. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.' );
  17243. return;
  17244. }
  17245. // the following if statement ensures valid read requests (no out-of-bounds pixels, see #8604)
  17246. if ( ( x >= 0 && x <= ( renderTarget.width - width ) ) && ( y >= 0 && y <= ( renderTarget.height - height ) ) ) {
  17247. _gl.readPixels( x, y, width, height, utils.convert( textureFormat ), utils.convert( textureType ), buffer );
  17248. }
  17249. } finally {
  17250. // restore framebuffer of current render target if necessary
  17251. const framebuffer = ( _currentRenderTarget !== null ) ? properties.get( _currentRenderTarget ).__webglFramebuffer : null;
  17252. state.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  17253. }
  17254. }
  17255. };
  17256. this.copyFramebufferToTexture = function ( position, texture, level = 0 ) {
  17257. const levelScale = Math.pow( 2, - level );
  17258. const width = Math.floor( texture.image.width * levelScale );
  17259. const height = Math.floor( texture.image.height * levelScale );
  17260. textures.setTexture2D( texture, 0 );
  17261. _gl.copyTexSubImage2D( _gl.TEXTURE_2D, level, 0, 0, position.x, position.y, width, height );
  17262. state.unbindTexture();
  17263. };
  17264. this.copyTextureToTexture = function ( position, srcTexture, dstTexture, level = 0 ) {
  17265. const width = srcTexture.image.width;
  17266. const height = srcTexture.image.height;
  17267. const glFormat = utils.convert( dstTexture.format );
  17268. const glType = utils.convert( dstTexture.type );
  17269. textures.setTexture2D( dstTexture, 0 );
  17270. // As another texture upload may have changed pixelStorei
  17271. // parameters, make sure they are correct for the dstTexture
  17272. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, dstTexture.flipY );
  17273. _gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, dstTexture.premultiplyAlpha );
  17274. _gl.pixelStorei( _gl.UNPACK_ALIGNMENT, dstTexture.unpackAlignment );
  17275. if ( srcTexture.isDataTexture ) {
  17276. _gl.texSubImage2D( _gl.TEXTURE_2D, level, position.x, position.y, width, height, glFormat, glType, srcTexture.image.data );
  17277. } else {
  17278. if ( srcTexture.isCompressedTexture ) {
  17279. _gl.compressedTexSubImage2D( _gl.TEXTURE_2D, level, position.x, position.y, srcTexture.mipmaps[ 0 ].width, srcTexture.mipmaps[ 0 ].height, glFormat, srcTexture.mipmaps[ 0 ].data );
  17280. } else {
  17281. _gl.texSubImage2D( _gl.TEXTURE_2D, level, position.x, position.y, glFormat, glType, srcTexture.image );
  17282. }
  17283. }
  17284. // Generate mipmaps only when copying level 0
  17285. if ( level === 0 && dstTexture.generateMipmaps ) _gl.generateMipmap( _gl.TEXTURE_2D );
  17286. state.unbindTexture();
  17287. };
  17288. this.copyTextureToTexture3D = function ( sourceBox, position, srcTexture, dstTexture, level = 0 ) {
  17289. if ( _this.isWebGL1Renderer ) {
  17290. console.warn( 'THREE.WebGLRenderer.copyTextureToTexture3D: can only be used with WebGL2.' );
  17291. return;
  17292. }
  17293. const width = sourceBox.max.x - sourceBox.min.x + 1;
  17294. const height = sourceBox.max.y - sourceBox.min.y + 1;
  17295. const depth = sourceBox.max.z - sourceBox.min.z + 1;
  17296. const glFormat = utils.convert( dstTexture.format );
  17297. const glType = utils.convert( dstTexture.type );
  17298. let glTarget;
  17299. if ( dstTexture.isData3DTexture ) {
  17300. textures.setTexture3D( dstTexture, 0 );
  17301. glTarget = _gl.TEXTURE_3D;
  17302. } else if ( dstTexture.isDataArrayTexture ) {
  17303. textures.setTexture2DArray( dstTexture, 0 );
  17304. glTarget = _gl.TEXTURE_2D_ARRAY;
  17305. } else {
  17306. console.warn( 'THREE.WebGLRenderer.copyTextureToTexture3D: only supports THREE.DataTexture3D and THREE.DataTexture2DArray.' );
  17307. return;
  17308. }
  17309. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, dstTexture.flipY );
  17310. _gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, dstTexture.premultiplyAlpha );
  17311. _gl.pixelStorei( _gl.UNPACK_ALIGNMENT, dstTexture.unpackAlignment );
  17312. const unpackRowLen = _gl.getParameter( _gl.UNPACK_ROW_LENGTH );
  17313. const unpackImageHeight = _gl.getParameter( _gl.UNPACK_IMAGE_HEIGHT );
  17314. const unpackSkipPixels = _gl.getParameter( _gl.UNPACK_SKIP_PIXELS );
  17315. const unpackSkipRows = _gl.getParameter( _gl.UNPACK_SKIP_ROWS );
  17316. const unpackSkipImages = _gl.getParameter( _gl.UNPACK_SKIP_IMAGES );
  17317. const image = srcTexture.isCompressedTexture ? srcTexture.mipmaps[ 0 ] : srcTexture.image;
  17318. _gl.pixelStorei( _gl.UNPACK_ROW_LENGTH, image.width );
  17319. _gl.pixelStorei( _gl.UNPACK_IMAGE_HEIGHT, image.height );
  17320. _gl.pixelStorei( _gl.UNPACK_SKIP_PIXELS, sourceBox.min.x );
  17321. _gl.pixelStorei( _gl.UNPACK_SKIP_ROWS, sourceBox.min.y );
  17322. _gl.pixelStorei( _gl.UNPACK_SKIP_IMAGES, sourceBox.min.z );
  17323. if ( srcTexture.isDataTexture || srcTexture.isData3DTexture ) {
  17324. _gl.texSubImage3D( glTarget, level, position.x, position.y, position.z, width, height, depth, glFormat, glType, image.data );
  17325. } else {
  17326. if ( srcTexture.isCompressedArrayTexture ) {
  17327. console.warn( 'THREE.WebGLRenderer.copyTextureToTexture3D: untested support for compressed srcTexture.' );
  17328. _gl.compressedTexSubImage3D( glTarget, level, position.x, position.y, position.z, width, height, depth, glFormat, image.data );
  17329. } else {
  17330. _gl.texSubImage3D( glTarget, level, position.x, position.y, position.z, width, height, depth, glFormat, glType, image );
  17331. }
  17332. }
  17333. _gl.pixelStorei( _gl.UNPACK_ROW_LENGTH, unpackRowLen );
  17334. _gl.pixelStorei( _gl.UNPACK_IMAGE_HEIGHT, unpackImageHeight );
  17335. _gl.pixelStorei( _gl.UNPACK_SKIP_PIXELS, unpackSkipPixels );
  17336. _gl.pixelStorei( _gl.UNPACK_SKIP_ROWS, unpackSkipRows );
  17337. _gl.pixelStorei( _gl.UNPACK_SKIP_IMAGES, unpackSkipImages );
  17338. // Generate mipmaps only when copying level 0
  17339. if ( level === 0 && dstTexture.generateMipmaps ) _gl.generateMipmap( glTarget );
  17340. state.unbindTexture();
  17341. };
  17342. this.initTexture = function ( texture ) {
  17343. if ( texture.isCubeTexture ) {
  17344. textures.setTextureCube( texture, 0 );
  17345. } else if ( texture.isData3DTexture ) {
  17346. textures.setTexture3D( texture, 0 );
  17347. } else if ( texture.isDataArrayTexture || texture.isCompressedArrayTexture ) {
  17348. textures.setTexture2DArray( texture, 0 );
  17349. } else {
  17350. textures.setTexture2D( texture, 0 );
  17351. }
  17352. state.unbindTexture();
  17353. };
  17354. this.resetState = function () {
  17355. _currentActiveCubeFace = 0;
  17356. _currentActiveMipmapLevel = 0;
  17357. _currentRenderTarget = null;
  17358. state.reset();
  17359. bindingStates.reset();
  17360. };
  17361. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  17362. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'observe', { detail: this } ) );
  17363. }
  17364. }
  17365. class WebGL1Renderer extends WebGLRenderer {}
  17366. WebGL1Renderer.prototype.isWebGL1Renderer = true;
  17367. class FogExp2 {
  17368. constructor( color, density = 0.00025 ) {
  17369. this.isFogExp2 = true;
  17370. this.name = '';
  17371. this.color = new Color( color );
  17372. this.density = density;
  17373. }
  17374. clone() {
  17375. return new FogExp2( this.color, this.density );
  17376. }
  17377. toJSON( /* meta */ ) {
  17378. return {
  17379. type: 'FogExp2',
  17380. color: this.color.getHex(),
  17381. density: this.density
  17382. };
  17383. }
  17384. }
  17385. class Fog {
  17386. constructor( color, near = 1, far = 1000 ) {
  17387. this.isFog = true;
  17388. this.name = '';
  17389. this.color = new Color( color );
  17390. this.near = near;
  17391. this.far = far;
  17392. }
  17393. clone() {
  17394. return new Fog( this.color, this.near, this.far );
  17395. }
  17396. toJSON( /* meta */ ) {
  17397. return {
  17398. type: 'Fog',
  17399. color: this.color.getHex(),
  17400. near: this.near,
  17401. far: this.far
  17402. };
  17403. }
  17404. }
  17405. class Scene extends Object3D {
  17406. constructor() {
  17407. super();
  17408. this.isScene = true;
  17409. this.type = 'Scene';
  17410. this.background = null;
  17411. this.environment = null;
  17412. this.fog = null;
  17413. this.backgroundBlurriness = 0;
  17414. this.backgroundIntensity = 1;
  17415. this.overrideMaterial = null;
  17416. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  17417. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'observe', { detail: this } ) );
  17418. }
  17419. }
  17420. copy( source, recursive ) {
  17421. super.copy( source, recursive );
  17422. if ( source.background !== null ) this.background = source.background.clone();
  17423. if ( source.environment !== null ) this.environment = source.environment.clone();
  17424. if ( source.fog !== null ) this.fog = source.fog.clone();
  17425. this.backgroundBlurriness = source.backgroundBlurriness;
  17426. this.backgroundIntensity = source.backgroundIntensity;
  17427. if ( source.overrideMaterial !== null ) this.overrideMaterial = source.overrideMaterial.clone();
  17428. this.matrixAutoUpdate = source.matrixAutoUpdate;
  17429. return this;
  17430. }
  17431. toJSON( meta ) {
  17432. const data = super.toJSON( meta );
  17433. if ( this.fog !== null ) data.object.fog = this.fog.toJSON();
  17434. if ( this.backgroundBlurriness > 0 ) data.object.backgroundBlurriness = this.backgroundBlurriness;
  17435. if ( this.backgroundIntensity !== 1 ) data.object.backgroundIntensity = this.backgroundIntensity;
  17436. return data;
  17437. }
  17438. // @deprecated
  17439. get autoUpdate() {
  17440. console.warn( 'THREE.Scene: autoUpdate was renamed to matrixWorldAutoUpdate in r144.' );
  17441. return this.matrixWorldAutoUpdate;
  17442. }
  17443. set autoUpdate( value ) {
  17444. console.warn( 'THREE.Scene: autoUpdate was renamed to matrixWorldAutoUpdate in r144.' );
  17445. this.matrixWorldAutoUpdate = value;
  17446. }
  17447. }
  17448. class InterleavedBuffer {
  17449. constructor( array, stride ) {
  17450. this.isInterleavedBuffer = true;
  17451. this.array = array;
  17452. this.stride = stride;
  17453. this.count = array !== undefined ? array.length / stride : 0;
  17454. this.usage = StaticDrawUsage;
  17455. this.updateRange = { offset: 0, count: - 1 };
  17456. this.version = 0;
  17457. this.uuid = generateUUID();
  17458. }
  17459. onUploadCallback() {}
  17460. set needsUpdate( value ) {
  17461. if ( value === true ) this.version ++;
  17462. }
  17463. setUsage( value ) {
  17464. this.usage = value;
  17465. return this;
  17466. }
  17467. copy( source ) {
  17468. this.array = new source.array.constructor( source.array );
  17469. this.count = source.count;
  17470. this.stride = source.stride;
  17471. this.usage = source.usage;
  17472. return this;
  17473. }
  17474. copyAt( index1, attribute, index2 ) {
  17475. index1 *= this.stride;
  17476. index2 *= attribute.stride;
  17477. for ( let i = 0, l = this.stride; i < l; i ++ ) {
  17478. this.array[ index1 + i ] = attribute.array[ index2 + i ];
  17479. }
  17480. return this;
  17481. }
  17482. set( value, offset = 0 ) {
  17483. this.array.set( value, offset );
  17484. return this;
  17485. }
  17486. clone( data ) {
  17487. if ( data.arrayBuffers === undefined ) {
  17488. data.arrayBuffers = {};
  17489. }
  17490. if ( this.array.buffer._uuid === undefined ) {
  17491. this.array.buffer._uuid = generateUUID();
  17492. }
  17493. if ( data.arrayBuffers[ this.array.buffer._uuid ] === undefined ) {
  17494. data.arrayBuffers[ this.array.buffer._uuid ] = this.array.slice( 0 ).buffer;
  17495. }
  17496. const array = new this.array.constructor( data.arrayBuffers[ this.array.buffer._uuid ] );
  17497. const ib = new this.constructor( array, this.stride );
  17498. ib.setUsage( this.usage );
  17499. return ib;
  17500. }
  17501. onUpload( callback ) {
  17502. this.onUploadCallback = callback;
  17503. return this;
  17504. }
  17505. toJSON( data ) {
  17506. if ( data.arrayBuffers === undefined ) {
  17507. data.arrayBuffers = {};
  17508. }
  17509. // generate UUID for array buffer if necessary
  17510. if ( this.array.buffer._uuid === undefined ) {
  17511. this.array.buffer._uuid = generateUUID();
  17512. }
  17513. if ( data.arrayBuffers[ this.array.buffer._uuid ] === undefined ) {
  17514. data.arrayBuffers[ this.array.buffer._uuid ] = Array.from( new Uint32Array( this.array.buffer ) );
  17515. }
  17516. //
  17517. return {
  17518. uuid: this.uuid,
  17519. buffer: this.array.buffer._uuid,
  17520. type: this.array.constructor.name,
  17521. stride: this.stride
  17522. };
  17523. }
  17524. }
  17525. const _vector$6 = /*@__PURE__*/ new Vector3();
  17526. class InterleavedBufferAttribute {
  17527. constructor( interleavedBuffer, itemSize, offset, normalized = false ) {
  17528. this.isInterleavedBufferAttribute = true;
  17529. this.name = '';
  17530. this.data = interleavedBuffer;
  17531. this.itemSize = itemSize;
  17532. this.offset = offset;
  17533. this.normalized = normalized;
  17534. }
  17535. get count() {
  17536. return this.data.count;
  17537. }
  17538. get array() {
  17539. return this.data.array;
  17540. }
  17541. set needsUpdate( value ) {
  17542. this.data.needsUpdate = value;
  17543. }
  17544. applyMatrix4( m ) {
  17545. for ( let i = 0, l = this.data.count; i < l; i ++ ) {
  17546. _vector$6.fromBufferAttribute( this, i );
  17547. _vector$6.applyMatrix4( m );
  17548. this.setXYZ( i, _vector$6.x, _vector$6.y, _vector$6.z );
  17549. }
  17550. return this;
  17551. }
  17552. applyNormalMatrix( m ) {
  17553. for ( let i = 0, l = this.count; i < l; i ++ ) {
  17554. _vector$6.fromBufferAttribute( this, i );
  17555. _vector$6.applyNormalMatrix( m );
  17556. this.setXYZ( i, _vector$6.x, _vector$6.y, _vector$6.z );
  17557. }
  17558. return this;
  17559. }
  17560. transformDirection( m ) {
  17561. for ( let i = 0, l = this.count; i < l; i ++ ) {
  17562. _vector$6.fromBufferAttribute( this, i );
  17563. _vector$6.transformDirection( m );
  17564. this.setXYZ( i, _vector$6.x, _vector$6.y, _vector$6.z );
  17565. }
  17566. return this;
  17567. }
  17568. setX( index, x ) {
  17569. if ( this.normalized ) x = normalize( x, this.array );
  17570. this.data.array[ index * this.data.stride + this.offset ] = x;
  17571. return this;
  17572. }
  17573. setY( index, y ) {
  17574. if ( this.normalized ) y = normalize( y, this.array );
  17575. this.data.array[ index * this.data.stride + this.offset + 1 ] = y;
  17576. return this;
  17577. }
  17578. setZ( index, z ) {
  17579. if ( this.normalized ) z = normalize( z, this.array );
  17580. this.data.array[ index * this.data.stride + this.offset + 2 ] = z;
  17581. return this;
  17582. }
  17583. setW( index, w ) {
  17584. if ( this.normalized ) w = normalize( w, this.array );
  17585. this.data.array[ index * this.data.stride + this.offset + 3 ] = w;
  17586. return this;
  17587. }
  17588. getX( index ) {
  17589. let x = this.data.array[ index * this.data.stride + this.offset ];
  17590. if ( this.normalized ) x = denormalize( x, this.array );
  17591. return x;
  17592. }
  17593. getY( index ) {
  17594. let y = this.data.array[ index * this.data.stride + this.offset + 1 ];
  17595. if ( this.normalized ) y = denormalize( y, this.array );
  17596. return y;
  17597. }
  17598. getZ( index ) {
  17599. let z = this.data.array[ index * this.data.stride + this.offset + 2 ];
  17600. if ( this.normalized ) z = denormalize( z, this.array );
  17601. return z;
  17602. }
  17603. getW( index ) {
  17604. let w = this.data.array[ index * this.data.stride + this.offset + 3 ];
  17605. if ( this.normalized ) w = denormalize( w, this.array );
  17606. return w;
  17607. }
  17608. setXY( index, x, y ) {
  17609. index = index * this.data.stride + this.offset;
  17610. if ( this.normalized ) {
  17611. x = normalize( x, this.array );
  17612. y = normalize( y, this.array );
  17613. }
  17614. this.data.array[ index + 0 ] = x;
  17615. this.data.array[ index + 1 ] = y;
  17616. return this;
  17617. }
  17618. setXYZ( index, x, y, z ) {
  17619. index = index * this.data.stride + this.offset;
  17620. if ( this.normalized ) {
  17621. x = normalize( x, this.array );
  17622. y = normalize( y, this.array );
  17623. z = normalize( z, this.array );
  17624. }
  17625. this.data.array[ index + 0 ] = x;
  17626. this.data.array[ index + 1 ] = y;
  17627. this.data.array[ index + 2 ] = z;
  17628. return this;
  17629. }
  17630. setXYZW( index, x, y, z, w ) {
  17631. index = index * this.data.stride + this.offset;
  17632. if ( this.normalized ) {
  17633. x = normalize( x, this.array );
  17634. y = normalize( y, this.array );
  17635. z = normalize( z, this.array );
  17636. w = normalize( w, this.array );
  17637. }
  17638. this.data.array[ index + 0 ] = x;
  17639. this.data.array[ index + 1 ] = y;
  17640. this.data.array[ index + 2 ] = z;
  17641. this.data.array[ index + 3 ] = w;
  17642. return this;
  17643. }
  17644. clone( data ) {
  17645. if ( data === undefined ) {
  17646. console.log( 'THREE.InterleavedBufferAttribute.clone(): Cloning an interleaved buffer attribute will de-interleave buffer data.' );
  17647. const array = [];
  17648. for ( let i = 0; i < this.count; i ++ ) {
  17649. const index = i * this.data.stride + this.offset;
  17650. for ( let j = 0; j < this.itemSize; j ++ ) {
  17651. array.push( this.data.array[ index + j ] );
  17652. }
  17653. }
  17654. return new BufferAttribute( new this.array.constructor( array ), this.itemSize, this.normalized );
  17655. } else {
  17656. if ( data.interleavedBuffers === undefined ) {
  17657. data.interleavedBuffers = {};
  17658. }
  17659. if ( data.interleavedBuffers[ this.data.uuid ] === undefined ) {
  17660. data.interleavedBuffers[ this.data.uuid ] = this.data.clone( data );
  17661. }
  17662. return new InterleavedBufferAttribute( data.interleavedBuffers[ this.data.uuid ], this.itemSize, this.offset, this.normalized );
  17663. }
  17664. }
  17665. toJSON( data ) {
  17666. if ( data === undefined ) {
  17667. console.log( 'THREE.InterleavedBufferAttribute.toJSON(): Serializing an interleaved buffer attribute will de-interleave buffer data.' );
  17668. const array = [];
  17669. for ( let i = 0; i < this.count; i ++ ) {
  17670. const index = i * this.data.stride + this.offset;
  17671. for ( let j = 0; j < this.itemSize; j ++ ) {
  17672. array.push( this.data.array[ index + j ] );
  17673. }
  17674. }
  17675. // de-interleave data and save it as an ordinary buffer attribute for now
  17676. return {
  17677. itemSize: this.itemSize,
  17678. type: this.array.constructor.name,
  17679. array: array,
  17680. normalized: this.normalized
  17681. };
  17682. } else {
  17683. // save as true interleaved attribute
  17684. if ( data.interleavedBuffers === undefined ) {
  17685. data.interleavedBuffers = {};
  17686. }
  17687. if ( data.interleavedBuffers[ this.data.uuid ] === undefined ) {
  17688. data.interleavedBuffers[ this.data.uuid ] = this.data.toJSON( data );
  17689. }
  17690. return {
  17691. isInterleavedBufferAttribute: true,
  17692. itemSize: this.itemSize,
  17693. data: this.data.uuid,
  17694. offset: this.offset,
  17695. normalized: this.normalized
  17696. };
  17697. }
  17698. }
  17699. }
  17700. class SpriteMaterial extends Material {
  17701. constructor( parameters ) {
  17702. super();
  17703. this.isSpriteMaterial = true;
  17704. this.type = 'SpriteMaterial';
  17705. this.color = new Color( 0xffffff );
  17706. this.map = null;
  17707. this.alphaMap = null;
  17708. this.rotation = 0;
  17709. this.sizeAttenuation = true;
  17710. this.transparent = true;
  17711. this.fog = true;
  17712. this.setValues( parameters );
  17713. }
  17714. copy( source ) {
  17715. super.copy( source );
  17716. this.color.copy( source.color );
  17717. this.map = source.map;
  17718. this.alphaMap = source.alphaMap;
  17719. this.rotation = source.rotation;
  17720. this.sizeAttenuation = source.sizeAttenuation;
  17721. this.fog = source.fog;
  17722. return this;
  17723. }
  17724. }
  17725. let _geometry;
  17726. const _intersectPoint = /*@__PURE__*/ new Vector3();
  17727. const _worldScale = /*@__PURE__*/ new Vector3();
  17728. const _mvPosition = /*@__PURE__*/ new Vector3();
  17729. const _alignedPosition = /*@__PURE__*/ new Vector2();
  17730. const _rotatedPosition = /*@__PURE__*/ new Vector2();
  17731. const _viewWorldMatrix = /*@__PURE__*/ new Matrix4();
  17732. const _vA = /*@__PURE__*/ new Vector3();
  17733. const _vB = /*@__PURE__*/ new Vector3();
  17734. const _vC = /*@__PURE__*/ new Vector3();
  17735. const _uvA = /*@__PURE__*/ new Vector2();
  17736. const _uvB = /*@__PURE__*/ new Vector2();
  17737. const _uvC = /*@__PURE__*/ new Vector2();
  17738. class Sprite extends Object3D {
  17739. constructor( material ) {
  17740. super();
  17741. this.isSprite = true;
  17742. this.type = 'Sprite';
  17743. if ( _geometry === undefined ) {
  17744. _geometry = new BufferGeometry();
  17745. const float32Array = new Float32Array( [
  17746. - 0.5, - 0.5, 0, 0, 0,
  17747. 0.5, - 0.5, 0, 1, 0,
  17748. 0.5, 0.5, 0, 1, 1,
  17749. - 0.5, 0.5, 0, 0, 1
  17750. ] );
  17751. const interleavedBuffer = new InterleavedBuffer( float32Array, 5 );
  17752. _geometry.setIndex( [ 0, 1, 2, 0, 2, 3 ] );
  17753. _geometry.setAttribute( 'position', new InterleavedBufferAttribute( interleavedBuffer, 3, 0, false ) );
  17754. _geometry.setAttribute( 'uv', new InterleavedBufferAttribute( interleavedBuffer, 2, 3, false ) );
  17755. }
  17756. this.geometry = _geometry;
  17757. this.material = ( material !== undefined ) ? material : new SpriteMaterial();
  17758. this.center = new Vector2( 0.5, 0.5 );
  17759. }
  17760. raycast( raycaster, intersects ) {
  17761. if ( raycaster.camera === null ) {
  17762. console.error( 'THREE.Sprite: "Raycaster.camera" needs to be set in order to raycast against sprites.' );
  17763. }
  17764. _worldScale.setFromMatrixScale( this.matrixWorld );
  17765. _viewWorldMatrix.copy( raycaster.camera.matrixWorld );
  17766. this.modelViewMatrix.multiplyMatrices( raycaster.camera.matrixWorldInverse, this.matrixWorld );
  17767. _mvPosition.setFromMatrixPosition( this.modelViewMatrix );
  17768. if ( raycaster.camera.isPerspectiveCamera && this.material.sizeAttenuation === false ) {
  17769. _worldScale.multiplyScalar( - _mvPosition.z );
  17770. }
  17771. const rotation = this.material.rotation;
  17772. let sin, cos;
  17773. if ( rotation !== 0 ) {
  17774. cos = Math.cos( rotation );
  17775. sin = Math.sin( rotation );
  17776. }
  17777. const center = this.center;
  17778. transformVertex( _vA.set( - 0.5, - 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  17779. transformVertex( _vB.set( 0.5, - 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  17780. transformVertex( _vC.set( 0.5, 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  17781. _uvA.set( 0, 0 );
  17782. _uvB.set( 1, 0 );
  17783. _uvC.set( 1, 1 );
  17784. // check first triangle
  17785. let intersect = raycaster.ray.intersectTriangle( _vA, _vB, _vC, false, _intersectPoint );
  17786. if ( intersect === null ) {
  17787. // check second triangle
  17788. transformVertex( _vB.set( - 0.5, 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  17789. _uvB.set( 0, 1 );
  17790. intersect = raycaster.ray.intersectTriangle( _vA, _vC, _vB, false, _intersectPoint );
  17791. if ( intersect === null ) {
  17792. return;
  17793. }
  17794. }
  17795. const distance = raycaster.ray.origin.distanceTo( _intersectPoint );
  17796. if ( distance < raycaster.near || distance > raycaster.far ) return;
  17797. intersects.push( {
  17798. distance: distance,
  17799. point: _intersectPoint.clone(),
  17800. uv: Triangle.getUV( _intersectPoint, _vA, _vB, _vC, _uvA, _uvB, _uvC, new Vector2() ),
  17801. face: null,
  17802. object: this
  17803. } );
  17804. }
  17805. copy( source, recursive ) {
  17806. super.copy( source, recursive );
  17807. if ( source.center !== undefined ) this.center.copy( source.center );
  17808. this.material = source.material;
  17809. return this;
  17810. }
  17811. }
  17812. function transformVertex( vertexPosition, mvPosition, center, scale, sin, cos ) {
  17813. // compute position in camera space
  17814. _alignedPosition.subVectors( vertexPosition, center ).addScalar( 0.5 ).multiply( scale );
  17815. // to check if rotation is not zero
  17816. if ( sin !== undefined ) {
  17817. _rotatedPosition.x = ( cos * _alignedPosition.x ) - ( sin * _alignedPosition.y );
  17818. _rotatedPosition.y = ( sin * _alignedPosition.x ) + ( cos * _alignedPosition.y );
  17819. } else {
  17820. _rotatedPosition.copy( _alignedPosition );
  17821. }
  17822. vertexPosition.copy( mvPosition );
  17823. vertexPosition.x += _rotatedPosition.x;
  17824. vertexPosition.y += _rotatedPosition.y;
  17825. // transform to world space
  17826. vertexPosition.applyMatrix4( _viewWorldMatrix );
  17827. }
  17828. const _v1$2 = /*@__PURE__*/ new Vector3();
  17829. const _v2$1 = /*@__PURE__*/ new Vector3();
  17830. class LOD extends Object3D {
  17831. constructor() {
  17832. super();
  17833. this._currentLevel = 0;
  17834. this.type = 'LOD';
  17835. Object.defineProperties( this, {
  17836. levels: {
  17837. enumerable: true,
  17838. value: []
  17839. },
  17840. isLOD: {
  17841. value: true,
  17842. }
  17843. } );
  17844. this.autoUpdate = true;
  17845. }
  17846. copy( source ) {
  17847. super.copy( source, false );
  17848. const levels = source.levels;
  17849. for ( let i = 0, l = levels.length; i < l; i ++ ) {
  17850. const level = levels[ i ];
  17851. this.addLevel( level.object.clone(), level.distance, level.hysteresis );
  17852. }
  17853. this.autoUpdate = source.autoUpdate;
  17854. return this;
  17855. }
  17856. addLevel( object, distance = 0, hysteresis = 0 ) {
  17857. distance = Math.abs( distance );
  17858. const levels = this.levels;
  17859. let l;
  17860. for ( l = 0; l < levels.length; l ++ ) {
  17861. if ( distance < levels[ l ].distance ) {
  17862. break;
  17863. }
  17864. }
  17865. levels.splice( l, 0, { distance: distance, hysteresis: hysteresis, object: object } );
  17866. this.add( object );
  17867. return this;
  17868. }
  17869. getCurrentLevel() {
  17870. return this._currentLevel;
  17871. }
  17872. getObjectForDistance( distance ) {
  17873. const levels = this.levels;
  17874. if ( levels.length > 0 ) {
  17875. let i, l;
  17876. for ( i = 1, l = levels.length; i < l; i ++ ) {
  17877. let levelDistance = levels[ i ].distance;
  17878. if ( levels[ i ].object.visible ) {
  17879. levelDistance -= levelDistance * levels[ i ].hysteresis;
  17880. }
  17881. if ( distance < levelDistance ) {
  17882. break;
  17883. }
  17884. }
  17885. return levels[ i - 1 ].object;
  17886. }
  17887. return null;
  17888. }
  17889. raycast( raycaster, intersects ) {
  17890. const levels = this.levels;
  17891. if ( levels.length > 0 ) {
  17892. _v1$2.setFromMatrixPosition( this.matrixWorld );
  17893. const distance = raycaster.ray.origin.distanceTo( _v1$2 );
  17894. this.getObjectForDistance( distance ).raycast( raycaster, intersects );
  17895. }
  17896. }
  17897. update( camera ) {
  17898. const levels = this.levels;
  17899. if ( levels.length > 1 ) {
  17900. _v1$2.setFromMatrixPosition( camera.matrixWorld );
  17901. _v2$1.setFromMatrixPosition( this.matrixWorld );
  17902. const distance = _v1$2.distanceTo( _v2$1 ) / camera.zoom;
  17903. levels[ 0 ].object.visible = true;
  17904. let i, l;
  17905. for ( i = 1, l = levels.length; i < l; i ++ ) {
  17906. let levelDistance = levels[ i ].distance;
  17907. if ( levels[ i ].object.visible ) {
  17908. levelDistance -= levelDistance * levels[ i ].hysteresis;
  17909. }
  17910. if ( distance >= levelDistance ) {
  17911. levels[ i - 1 ].object.visible = false;
  17912. levels[ i ].object.visible = true;
  17913. } else {
  17914. break;
  17915. }
  17916. }
  17917. this._currentLevel = i - 1;
  17918. for ( ; i < l; i ++ ) {
  17919. levels[ i ].object.visible = false;
  17920. }
  17921. }
  17922. }
  17923. toJSON( meta ) {
  17924. const data = super.toJSON( meta );
  17925. if ( this.autoUpdate === false ) data.object.autoUpdate = false;
  17926. data.object.levels = [];
  17927. const levels = this.levels;
  17928. for ( let i = 0, l = levels.length; i < l; i ++ ) {
  17929. const level = levels[ i ];
  17930. data.object.levels.push( {
  17931. object: level.object.uuid,
  17932. distance: level.distance,
  17933. hysteresis: level.hysteresis
  17934. } );
  17935. }
  17936. return data;
  17937. }
  17938. }
  17939. const _basePosition = /*@__PURE__*/ new Vector3();
  17940. const _skinIndex = /*@__PURE__*/ new Vector4();
  17941. const _skinWeight = /*@__PURE__*/ new Vector4();
  17942. const _vector$5 = /*@__PURE__*/ new Vector3();
  17943. const _matrix = /*@__PURE__*/ new Matrix4();
  17944. class SkinnedMesh extends Mesh {
  17945. constructor( geometry, material ) {
  17946. super( geometry, material );
  17947. this.isSkinnedMesh = true;
  17948. this.type = 'SkinnedMesh';
  17949. this.bindMode = 'attached';
  17950. this.bindMatrix = new Matrix4();
  17951. this.bindMatrixInverse = new Matrix4();
  17952. }
  17953. copy( source, recursive ) {
  17954. super.copy( source, recursive );
  17955. this.bindMode = source.bindMode;
  17956. this.bindMatrix.copy( source.bindMatrix );
  17957. this.bindMatrixInverse.copy( source.bindMatrixInverse );
  17958. this.skeleton = source.skeleton;
  17959. return this;
  17960. }
  17961. bind( skeleton, bindMatrix ) {
  17962. this.skeleton = skeleton;
  17963. if ( bindMatrix === undefined ) {
  17964. this.updateMatrixWorld( true );
  17965. this.skeleton.calculateInverses();
  17966. bindMatrix = this.matrixWorld;
  17967. }
  17968. this.bindMatrix.copy( bindMatrix );
  17969. this.bindMatrixInverse.copy( bindMatrix ).invert();
  17970. }
  17971. pose() {
  17972. this.skeleton.pose();
  17973. }
  17974. normalizeSkinWeights() {
  17975. const vector = new Vector4();
  17976. const skinWeight = this.geometry.attributes.skinWeight;
  17977. for ( let i = 0, l = skinWeight.count; i < l; i ++ ) {
  17978. vector.fromBufferAttribute( skinWeight, i );
  17979. const scale = 1.0 / vector.manhattanLength();
  17980. if ( scale !== Infinity ) {
  17981. vector.multiplyScalar( scale );
  17982. } else {
  17983. vector.set( 1, 0, 0, 0 ); // do something reasonable
  17984. }
  17985. skinWeight.setXYZW( i, vector.x, vector.y, vector.z, vector.w );
  17986. }
  17987. }
  17988. updateMatrixWorld( force ) {
  17989. super.updateMatrixWorld( force );
  17990. if ( this.bindMode === 'attached' ) {
  17991. this.bindMatrixInverse.copy( this.matrixWorld ).invert();
  17992. } else if ( this.bindMode === 'detached' ) {
  17993. this.bindMatrixInverse.copy( this.bindMatrix ).invert();
  17994. } else {
  17995. console.warn( 'THREE.SkinnedMesh: Unrecognized bindMode: ' + this.bindMode );
  17996. }
  17997. }
  17998. boneTransform( index, target ) {
  17999. const skeleton = this.skeleton;
  18000. const geometry = this.geometry;
  18001. _skinIndex.fromBufferAttribute( geometry.attributes.skinIndex, index );
  18002. _skinWeight.fromBufferAttribute( geometry.attributes.skinWeight, index );
  18003. _basePosition.copy( target ).applyMatrix4( this.bindMatrix );
  18004. target.set( 0, 0, 0 );
  18005. for ( let i = 0; i < 4; i ++ ) {
  18006. const weight = _skinWeight.getComponent( i );
  18007. if ( weight !== 0 ) {
  18008. const boneIndex = _skinIndex.getComponent( i );
  18009. _matrix.multiplyMatrices( skeleton.bones[ boneIndex ].matrixWorld, skeleton.boneInverses[ boneIndex ] );
  18010. target.addScaledVector( _vector$5.copy( _basePosition ).applyMatrix4( _matrix ), weight );
  18011. }
  18012. }
  18013. return target.applyMatrix4( this.bindMatrixInverse );
  18014. }
  18015. }
  18016. class Bone extends Object3D {
  18017. constructor() {
  18018. super();
  18019. this.isBone = true;
  18020. this.type = 'Bone';
  18021. }
  18022. }
  18023. class DataTexture extends Texture {
  18024. constructor( data = null, width = 1, height = 1, format, type, mapping, wrapS, wrapT, magFilter = NearestFilter, minFilter = NearestFilter, anisotropy, encoding ) {
  18025. super( null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding );
  18026. this.isDataTexture = true;
  18027. this.image = { data: data, width: width, height: height };
  18028. this.generateMipmaps = false;
  18029. this.flipY = false;
  18030. this.unpackAlignment = 1;
  18031. }
  18032. }
  18033. const _offsetMatrix = /*@__PURE__*/ new Matrix4();
  18034. const _identityMatrix = /*@__PURE__*/ new Matrix4();
  18035. class Skeleton {
  18036. constructor( bones = [], boneInverses = [] ) {
  18037. this.uuid = generateUUID();
  18038. this.bones = bones.slice( 0 );
  18039. this.boneInverses = boneInverses;
  18040. this.boneMatrices = null;
  18041. this.boneTexture = null;
  18042. this.boneTextureSize = 0;
  18043. this.frame = - 1;
  18044. this.init();
  18045. }
  18046. init() {
  18047. const bones = this.bones;
  18048. const boneInverses = this.boneInverses;
  18049. this.boneMatrices = new Float32Array( bones.length * 16 );
  18050. // calculate inverse bone matrices if necessary
  18051. if ( boneInverses.length === 0 ) {
  18052. this.calculateInverses();
  18053. } else {
  18054. // handle special case
  18055. if ( bones.length !== boneInverses.length ) {
  18056. console.warn( 'THREE.Skeleton: Number of inverse bone matrices does not match amount of bones.' );
  18057. this.boneInverses = [];
  18058. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  18059. this.boneInverses.push( new Matrix4() );
  18060. }
  18061. }
  18062. }
  18063. }
  18064. calculateInverses() {
  18065. this.boneInverses.length = 0;
  18066. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  18067. const inverse = new Matrix4();
  18068. if ( this.bones[ i ] ) {
  18069. inverse.copy( this.bones[ i ].matrixWorld ).invert();
  18070. }
  18071. this.boneInverses.push( inverse );
  18072. }
  18073. }
  18074. pose() {
  18075. // recover the bind-time world matrices
  18076. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  18077. const bone = this.bones[ i ];
  18078. if ( bone ) {
  18079. bone.matrixWorld.copy( this.boneInverses[ i ] ).invert();
  18080. }
  18081. }
  18082. // compute the local matrices, positions, rotations and scales
  18083. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  18084. const bone = this.bones[ i ];
  18085. if ( bone ) {
  18086. if ( bone.parent && bone.parent.isBone ) {
  18087. bone.matrix.copy( bone.parent.matrixWorld ).invert();
  18088. bone.matrix.multiply( bone.matrixWorld );
  18089. } else {
  18090. bone.matrix.copy( bone.matrixWorld );
  18091. }
  18092. bone.matrix.decompose( bone.position, bone.quaternion, bone.scale );
  18093. }
  18094. }
  18095. }
  18096. update() {
  18097. const bones = this.bones;
  18098. const boneInverses = this.boneInverses;
  18099. const boneMatrices = this.boneMatrices;
  18100. const boneTexture = this.boneTexture;
  18101. // flatten bone matrices to array
  18102. for ( let i = 0, il = bones.length; i < il; i ++ ) {
  18103. // compute the offset between the current and the original transform
  18104. const matrix = bones[ i ] ? bones[ i ].matrixWorld : _identityMatrix;
  18105. _offsetMatrix.multiplyMatrices( matrix, boneInverses[ i ] );
  18106. _offsetMatrix.toArray( boneMatrices, i * 16 );
  18107. }
  18108. if ( boneTexture !== null ) {
  18109. boneTexture.needsUpdate = true;
  18110. }
  18111. }
  18112. clone() {
  18113. return new Skeleton( this.bones, this.boneInverses );
  18114. }
  18115. computeBoneTexture() {
  18116. // layout (1 matrix = 4 pixels)
  18117. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  18118. // with 8x8 pixel texture max 16 bones * 4 pixels = (8 * 8)
  18119. // 16x16 pixel texture max 64 bones * 4 pixels = (16 * 16)
  18120. // 32x32 pixel texture max 256 bones * 4 pixels = (32 * 32)
  18121. // 64x64 pixel texture max 1024 bones * 4 pixels = (64 * 64)
  18122. let size = Math.sqrt( this.bones.length * 4 ); // 4 pixels needed for 1 matrix
  18123. size = ceilPowerOfTwo( size );
  18124. size = Math.max( size, 4 );
  18125. const boneMatrices = new Float32Array( size * size * 4 ); // 4 floats per RGBA pixel
  18126. boneMatrices.set( this.boneMatrices ); // copy current values
  18127. const boneTexture = new DataTexture( boneMatrices, size, size, RGBAFormat, FloatType );
  18128. boneTexture.needsUpdate = true;
  18129. this.boneMatrices = boneMatrices;
  18130. this.boneTexture = boneTexture;
  18131. this.boneTextureSize = size;
  18132. return this;
  18133. }
  18134. getBoneByName( name ) {
  18135. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  18136. const bone = this.bones[ i ];
  18137. if ( bone.name === name ) {
  18138. return bone;
  18139. }
  18140. }
  18141. return undefined;
  18142. }
  18143. dispose( ) {
  18144. if ( this.boneTexture !== null ) {
  18145. this.boneTexture.dispose();
  18146. this.boneTexture = null;
  18147. }
  18148. }
  18149. fromJSON( json, bones ) {
  18150. this.uuid = json.uuid;
  18151. for ( let i = 0, l = json.bones.length; i < l; i ++ ) {
  18152. const uuid = json.bones[ i ];
  18153. let bone = bones[ uuid ];
  18154. if ( bone === undefined ) {
  18155. console.warn( 'THREE.Skeleton: No bone found with UUID:', uuid );
  18156. bone = new Bone();
  18157. }
  18158. this.bones.push( bone );
  18159. this.boneInverses.push( new Matrix4().fromArray( json.boneInverses[ i ] ) );
  18160. }
  18161. this.init();
  18162. return this;
  18163. }
  18164. toJSON() {
  18165. const data = {
  18166. metadata: {
  18167. version: 4.5,
  18168. type: 'Skeleton',
  18169. generator: 'Skeleton.toJSON'
  18170. },
  18171. bones: [],
  18172. boneInverses: []
  18173. };
  18174. data.uuid = this.uuid;
  18175. const bones = this.bones;
  18176. const boneInverses = this.boneInverses;
  18177. for ( let i = 0, l = bones.length; i < l; i ++ ) {
  18178. const bone = bones[ i ];
  18179. data.bones.push( bone.uuid );
  18180. const boneInverse = boneInverses[ i ];
  18181. data.boneInverses.push( boneInverse.toArray() );
  18182. }
  18183. return data;
  18184. }
  18185. }
  18186. class InstancedBufferAttribute extends BufferAttribute {
  18187. constructor( array, itemSize, normalized, meshPerAttribute = 1 ) {
  18188. super( array, itemSize, normalized );
  18189. this.isInstancedBufferAttribute = true;
  18190. this.meshPerAttribute = meshPerAttribute;
  18191. }
  18192. copy( source ) {
  18193. super.copy( source );
  18194. this.meshPerAttribute = source.meshPerAttribute;
  18195. return this;
  18196. }
  18197. toJSON() {
  18198. const data = super.toJSON();
  18199. data.meshPerAttribute = this.meshPerAttribute;
  18200. data.isInstancedBufferAttribute = true;
  18201. return data;
  18202. }
  18203. }
  18204. const _instanceLocalMatrix = /*@__PURE__*/ new Matrix4();
  18205. const _instanceWorldMatrix = /*@__PURE__*/ new Matrix4();
  18206. const _instanceIntersects = [];
  18207. const _identity = /*@__PURE__*/ new Matrix4();
  18208. const _mesh = /*@__PURE__*/ new Mesh();
  18209. class InstancedMesh extends Mesh {
  18210. constructor( geometry, material, count ) {
  18211. super( geometry, material );
  18212. this.isInstancedMesh = true;
  18213. this.instanceMatrix = new InstancedBufferAttribute( new Float32Array( count * 16 ), 16 );
  18214. this.instanceColor = null;
  18215. this.count = count;
  18216. this.frustumCulled = false;
  18217. for ( let i = 0; i < count; i ++ ) {
  18218. this.setMatrixAt( i, _identity );
  18219. }
  18220. }
  18221. copy( source, recursive ) {
  18222. super.copy( source, recursive );
  18223. this.instanceMatrix.copy( source.instanceMatrix );
  18224. if ( source.instanceColor !== null ) this.instanceColor = source.instanceColor.clone();
  18225. this.count = source.count;
  18226. return this;
  18227. }
  18228. getColorAt( index, color ) {
  18229. color.fromArray( this.instanceColor.array, index * 3 );
  18230. }
  18231. getMatrixAt( index, matrix ) {
  18232. matrix.fromArray( this.instanceMatrix.array, index * 16 );
  18233. }
  18234. raycast( raycaster, intersects ) {
  18235. const matrixWorld = this.matrixWorld;
  18236. const raycastTimes = this.count;
  18237. _mesh.geometry = this.geometry;
  18238. _mesh.material = this.material;
  18239. if ( _mesh.material === undefined ) return;
  18240. for ( let instanceId = 0; instanceId < raycastTimes; instanceId ++ ) {
  18241. // calculate the world matrix for each instance
  18242. this.getMatrixAt( instanceId, _instanceLocalMatrix );
  18243. _instanceWorldMatrix.multiplyMatrices( matrixWorld, _instanceLocalMatrix );
  18244. // the mesh represents this single instance
  18245. _mesh.matrixWorld = _instanceWorldMatrix;
  18246. _mesh.raycast( raycaster, _instanceIntersects );
  18247. // process the result of raycast
  18248. for ( let i = 0, l = _instanceIntersects.length; i < l; i ++ ) {
  18249. const intersect = _instanceIntersects[ i ];
  18250. intersect.instanceId = instanceId;
  18251. intersect.object = this;
  18252. intersects.push( intersect );
  18253. }
  18254. _instanceIntersects.length = 0;
  18255. }
  18256. }
  18257. setColorAt( index, color ) {
  18258. if ( this.instanceColor === null ) {
  18259. this.instanceColor = new InstancedBufferAttribute( new Float32Array( this.instanceMatrix.count * 3 ), 3 );
  18260. }
  18261. color.toArray( this.instanceColor.array, index * 3 );
  18262. }
  18263. setMatrixAt( index, matrix ) {
  18264. matrix.toArray( this.instanceMatrix.array, index * 16 );
  18265. }
  18266. updateMorphTargets() {
  18267. }
  18268. dispose() {
  18269. this.dispatchEvent( { type: 'dispose' } );
  18270. }
  18271. }
  18272. class LineBasicMaterial extends Material {
  18273. constructor( parameters ) {
  18274. super();
  18275. this.isLineBasicMaterial = true;
  18276. this.type = 'LineBasicMaterial';
  18277. this.color = new Color( 0xffffff );
  18278. this.linewidth = 1;
  18279. this.linecap = 'round';
  18280. this.linejoin = 'round';
  18281. this.fog = true;
  18282. this.setValues( parameters );
  18283. }
  18284. copy( source ) {
  18285. super.copy( source );
  18286. this.color.copy( source.color );
  18287. this.linewidth = source.linewidth;
  18288. this.linecap = source.linecap;
  18289. this.linejoin = source.linejoin;
  18290. this.fog = source.fog;
  18291. return this;
  18292. }
  18293. }
  18294. const _start$1 = /*@__PURE__*/ new Vector3();
  18295. const _end$1 = /*@__PURE__*/ new Vector3();
  18296. const _inverseMatrix$1 = /*@__PURE__*/ new Matrix4();
  18297. const _ray$1 = /*@__PURE__*/ new Ray();
  18298. const _sphere$1 = /*@__PURE__*/ new Sphere();
  18299. class Line extends Object3D {
  18300. constructor( geometry = new BufferGeometry(), material = new LineBasicMaterial() ) {
  18301. super();
  18302. this.isLine = true;
  18303. this.type = 'Line';
  18304. this.geometry = geometry;
  18305. this.material = material;
  18306. this.updateMorphTargets();
  18307. }
  18308. copy( source, recursive ) {
  18309. super.copy( source, recursive );
  18310. this.material = source.material;
  18311. this.geometry = source.geometry;
  18312. return this;
  18313. }
  18314. computeLineDistances() {
  18315. const geometry = this.geometry;
  18316. // we assume non-indexed geometry
  18317. if ( geometry.index === null ) {
  18318. const positionAttribute = geometry.attributes.position;
  18319. const lineDistances = [ 0 ];
  18320. for ( let i = 1, l = positionAttribute.count; i < l; i ++ ) {
  18321. _start$1.fromBufferAttribute( positionAttribute, i - 1 );
  18322. _end$1.fromBufferAttribute( positionAttribute, i );
  18323. lineDistances[ i ] = lineDistances[ i - 1 ];
  18324. lineDistances[ i ] += _start$1.distanceTo( _end$1 );
  18325. }
  18326. geometry.setAttribute( 'lineDistance', new Float32BufferAttribute( lineDistances, 1 ) );
  18327. } else {
  18328. console.warn( 'THREE.Line.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.' );
  18329. }
  18330. return this;
  18331. }
  18332. raycast( raycaster, intersects ) {
  18333. const geometry = this.geometry;
  18334. const matrixWorld = this.matrixWorld;
  18335. const threshold = raycaster.params.Line.threshold;
  18336. const drawRange = geometry.drawRange;
  18337. // Checking boundingSphere distance to ray
  18338. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  18339. _sphere$1.copy( geometry.boundingSphere );
  18340. _sphere$1.applyMatrix4( matrixWorld );
  18341. _sphere$1.radius += threshold;
  18342. if ( raycaster.ray.intersectsSphere( _sphere$1 ) === false ) return;
  18343. //
  18344. _inverseMatrix$1.copy( matrixWorld ).invert();
  18345. _ray$1.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$1 );
  18346. const localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 );
  18347. const localThresholdSq = localThreshold * localThreshold;
  18348. const vStart = new Vector3();
  18349. const vEnd = new Vector3();
  18350. const interSegment = new Vector3();
  18351. const interRay = new Vector3();
  18352. const step = this.isLineSegments ? 2 : 1;
  18353. const index = geometry.index;
  18354. const attributes = geometry.attributes;
  18355. const positionAttribute = attributes.position;
  18356. if ( index !== null ) {
  18357. const start = Math.max( 0, drawRange.start );
  18358. const end = Math.min( index.count, ( drawRange.start + drawRange.count ) );
  18359. for ( let i = start, l = end - 1; i < l; i += step ) {
  18360. const a = index.getX( i );
  18361. const b = index.getX( i + 1 );
  18362. vStart.fromBufferAttribute( positionAttribute, a );
  18363. vEnd.fromBufferAttribute( positionAttribute, b );
  18364. const distSq = _ray$1.distanceSqToSegment( vStart, vEnd, interRay, interSegment );
  18365. if ( distSq > localThresholdSq ) continue;
  18366. interRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation
  18367. const distance = raycaster.ray.origin.distanceTo( interRay );
  18368. if ( distance < raycaster.near || distance > raycaster.far ) continue;
  18369. intersects.push( {
  18370. distance: distance,
  18371. // What do we want? intersection point on the ray or on the segment??
  18372. // point: raycaster.ray.at( distance ),
  18373. point: interSegment.clone().applyMatrix4( this.matrixWorld ),
  18374. index: i,
  18375. face: null,
  18376. faceIndex: null,
  18377. object: this
  18378. } );
  18379. }
  18380. } else {
  18381. const start = Math.max( 0, drawRange.start );
  18382. const end = Math.min( positionAttribute.count, ( drawRange.start + drawRange.count ) );
  18383. for ( let i = start, l = end - 1; i < l; i += step ) {
  18384. vStart.fromBufferAttribute( positionAttribute, i );
  18385. vEnd.fromBufferAttribute( positionAttribute, i + 1 );
  18386. const distSq = _ray$1.distanceSqToSegment( vStart, vEnd, interRay, interSegment );
  18387. if ( distSq > localThresholdSq ) continue;
  18388. interRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation
  18389. const distance = raycaster.ray.origin.distanceTo( interRay );
  18390. if ( distance < raycaster.near || distance > raycaster.far ) continue;
  18391. intersects.push( {
  18392. distance: distance,
  18393. // What do we want? intersection point on the ray or on the segment??
  18394. // point: raycaster.ray.at( distance ),
  18395. point: interSegment.clone().applyMatrix4( this.matrixWorld ),
  18396. index: i,
  18397. face: null,
  18398. faceIndex: null,
  18399. object: this
  18400. } );
  18401. }
  18402. }
  18403. }
  18404. updateMorphTargets() {
  18405. const geometry = this.geometry;
  18406. const morphAttributes = geometry.morphAttributes;
  18407. const keys = Object.keys( morphAttributes );
  18408. if ( keys.length > 0 ) {
  18409. const morphAttribute = morphAttributes[ keys[ 0 ] ];
  18410. if ( morphAttribute !== undefined ) {
  18411. this.morphTargetInfluences = [];
  18412. this.morphTargetDictionary = {};
  18413. for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  18414. const name = morphAttribute[ m ].name || String( m );
  18415. this.morphTargetInfluences.push( 0 );
  18416. this.morphTargetDictionary[ name ] = m;
  18417. }
  18418. }
  18419. }
  18420. }
  18421. }
  18422. const _start = /*@__PURE__*/ new Vector3();
  18423. const _end = /*@__PURE__*/ new Vector3();
  18424. class LineSegments extends Line {
  18425. constructor( geometry, material ) {
  18426. super( geometry, material );
  18427. this.isLineSegments = true;
  18428. this.type = 'LineSegments';
  18429. }
  18430. computeLineDistances() {
  18431. const geometry = this.geometry;
  18432. // we assume non-indexed geometry
  18433. if ( geometry.index === null ) {
  18434. const positionAttribute = geometry.attributes.position;
  18435. const lineDistances = [];
  18436. for ( let i = 0, l = positionAttribute.count; i < l; i += 2 ) {
  18437. _start.fromBufferAttribute( positionAttribute, i );
  18438. _end.fromBufferAttribute( positionAttribute, i + 1 );
  18439. lineDistances[ i ] = ( i === 0 ) ? 0 : lineDistances[ i - 1 ];
  18440. lineDistances[ i + 1 ] = lineDistances[ i ] + _start.distanceTo( _end );
  18441. }
  18442. geometry.setAttribute( 'lineDistance', new Float32BufferAttribute( lineDistances, 1 ) );
  18443. } else {
  18444. console.warn( 'THREE.LineSegments.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.' );
  18445. }
  18446. return this;
  18447. }
  18448. }
  18449. class LineLoop extends Line {
  18450. constructor( geometry, material ) {
  18451. super( geometry, material );
  18452. this.isLineLoop = true;
  18453. this.type = 'LineLoop';
  18454. }
  18455. }
  18456. class PointsMaterial extends Material {
  18457. constructor( parameters ) {
  18458. super();
  18459. this.isPointsMaterial = true;
  18460. this.type = 'PointsMaterial';
  18461. this.color = new Color( 0xffffff );
  18462. this.map = null;
  18463. this.alphaMap = null;
  18464. this.size = 1;
  18465. this.sizeAttenuation = true;
  18466. this.fog = true;
  18467. this.setValues( parameters );
  18468. }
  18469. copy( source ) {
  18470. super.copy( source );
  18471. this.color.copy( source.color );
  18472. this.map = source.map;
  18473. this.alphaMap = source.alphaMap;
  18474. this.size = source.size;
  18475. this.sizeAttenuation = source.sizeAttenuation;
  18476. this.fog = source.fog;
  18477. return this;
  18478. }
  18479. }
  18480. const _inverseMatrix = /*@__PURE__*/ new Matrix4();
  18481. const _ray = /*@__PURE__*/ new Ray();
  18482. const _sphere = /*@__PURE__*/ new Sphere();
  18483. const _position$2 = /*@__PURE__*/ new Vector3();
  18484. class Points extends Object3D {
  18485. constructor( geometry = new BufferGeometry(), material = new PointsMaterial() ) {
  18486. super();
  18487. this.isPoints = true;
  18488. this.type = 'Points';
  18489. this.geometry = geometry;
  18490. this.material = material;
  18491. this.updateMorphTargets();
  18492. }
  18493. copy( source, recursive ) {
  18494. super.copy( source, recursive );
  18495. this.material = source.material;
  18496. this.geometry = source.geometry;
  18497. return this;
  18498. }
  18499. raycast( raycaster, intersects ) {
  18500. const geometry = this.geometry;
  18501. const matrixWorld = this.matrixWorld;
  18502. const threshold = raycaster.params.Points.threshold;
  18503. const drawRange = geometry.drawRange;
  18504. // Checking boundingSphere distance to ray
  18505. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  18506. _sphere.copy( geometry.boundingSphere );
  18507. _sphere.applyMatrix4( matrixWorld );
  18508. _sphere.radius += threshold;
  18509. if ( raycaster.ray.intersectsSphere( _sphere ) === false ) return;
  18510. //
  18511. _inverseMatrix.copy( matrixWorld ).invert();
  18512. _ray.copy( raycaster.ray ).applyMatrix4( _inverseMatrix );
  18513. const localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 );
  18514. const localThresholdSq = localThreshold * localThreshold;
  18515. const index = geometry.index;
  18516. const attributes = geometry.attributes;
  18517. const positionAttribute = attributes.position;
  18518. if ( index !== null ) {
  18519. const start = Math.max( 0, drawRange.start );
  18520. const end = Math.min( index.count, ( drawRange.start + drawRange.count ) );
  18521. for ( let i = start, il = end; i < il; i ++ ) {
  18522. const a = index.getX( i );
  18523. _position$2.fromBufferAttribute( positionAttribute, a );
  18524. testPoint( _position$2, a, localThresholdSq, matrixWorld, raycaster, intersects, this );
  18525. }
  18526. } else {
  18527. const start = Math.max( 0, drawRange.start );
  18528. const end = Math.min( positionAttribute.count, ( drawRange.start + drawRange.count ) );
  18529. for ( let i = start, l = end; i < l; i ++ ) {
  18530. _position$2.fromBufferAttribute( positionAttribute, i );
  18531. testPoint( _position$2, i, localThresholdSq, matrixWorld, raycaster, intersects, this );
  18532. }
  18533. }
  18534. }
  18535. updateMorphTargets() {
  18536. const geometry = this.geometry;
  18537. const morphAttributes = geometry.morphAttributes;
  18538. const keys = Object.keys( morphAttributes );
  18539. if ( keys.length > 0 ) {
  18540. const morphAttribute = morphAttributes[ keys[ 0 ] ];
  18541. if ( morphAttribute !== undefined ) {
  18542. this.morphTargetInfluences = [];
  18543. this.morphTargetDictionary = {};
  18544. for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  18545. const name = morphAttribute[ m ].name || String( m );
  18546. this.morphTargetInfluences.push( 0 );
  18547. this.morphTargetDictionary[ name ] = m;
  18548. }
  18549. }
  18550. }
  18551. }
  18552. }
  18553. function testPoint( point, index, localThresholdSq, matrixWorld, raycaster, intersects, object ) {
  18554. const rayPointDistanceSq = _ray.distanceSqToPoint( point );
  18555. if ( rayPointDistanceSq < localThresholdSq ) {
  18556. const intersectPoint = new Vector3();
  18557. _ray.closestPointToPoint( point, intersectPoint );
  18558. intersectPoint.applyMatrix4( matrixWorld );
  18559. const distance = raycaster.ray.origin.distanceTo( intersectPoint );
  18560. if ( distance < raycaster.near || distance > raycaster.far ) return;
  18561. intersects.push( {
  18562. distance: distance,
  18563. distanceToRay: Math.sqrt( rayPointDistanceSq ),
  18564. point: intersectPoint,
  18565. index: index,
  18566. face: null,
  18567. object: object
  18568. } );
  18569. }
  18570. }
  18571. class VideoTexture extends Texture {
  18572. constructor( video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  18573. super( video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  18574. this.isVideoTexture = true;
  18575. this.minFilter = minFilter !== undefined ? minFilter : LinearFilter;
  18576. this.magFilter = magFilter !== undefined ? magFilter : LinearFilter;
  18577. this.generateMipmaps = false;
  18578. const scope = this;
  18579. function updateVideo() {
  18580. scope.needsUpdate = true;
  18581. video.requestVideoFrameCallback( updateVideo );
  18582. }
  18583. if ( 'requestVideoFrameCallback' in video ) {
  18584. video.requestVideoFrameCallback( updateVideo );
  18585. }
  18586. }
  18587. clone() {
  18588. return new this.constructor( this.image ).copy( this );
  18589. }
  18590. update() {
  18591. const video = this.image;
  18592. const hasVideoFrameCallback = 'requestVideoFrameCallback' in video;
  18593. if ( hasVideoFrameCallback === false && video.readyState >= video.HAVE_CURRENT_DATA ) {
  18594. this.needsUpdate = true;
  18595. }
  18596. }
  18597. }
  18598. class FramebufferTexture extends Texture {
  18599. constructor( width, height, format ) {
  18600. super( { width, height } );
  18601. this.isFramebufferTexture = true;
  18602. this.format = format;
  18603. this.magFilter = NearestFilter;
  18604. this.minFilter = NearestFilter;
  18605. this.generateMipmaps = false;
  18606. this.needsUpdate = true;
  18607. }
  18608. }
  18609. class CompressedTexture extends Texture {
  18610. constructor( mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, encoding ) {
  18611. super( null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding );
  18612. this.isCompressedTexture = true;
  18613. this.image = { width: width, height: height };
  18614. this.mipmaps = mipmaps;
  18615. // no flipping for cube textures
  18616. // (also flipping doesn't work for compressed textures )
  18617. this.flipY = false;
  18618. // can't generate mipmaps for compressed textures
  18619. // mips must be embedded in DDS files
  18620. this.generateMipmaps = false;
  18621. }
  18622. }
  18623. class CompressedArrayTexture extends CompressedTexture {
  18624. constructor( mipmaps, width, height, depth, format, type ) {
  18625. super( mipmaps, width, height, format, type );
  18626. this.isCompressedArrayTexture = true;
  18627. this.image.depth = depth;
  18628. this.wrapR = ClampToEdgeWrapping;
  18629. }
  18630. }
  18631. class CanvasTexture extends Texture {
  18632. constructor( canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  18633. super( canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  18634. this.isCanvasTexture = true;
  18635. this.needsUpdate = true;
  18636. }
  18637. }
  18638. /**
  18639. * Extensible curve object.
  18640. *
  18641. * Some common of curve methods:
  18642. * .getPoint( t, optionalTarget ), .getTangent( t, optionalTarget )
  18643. * .getPointAt( u, optionalTarget ), .getTangentAt( u, optionalTarget )
  18644. * .getPoints(), .getSpacedPoints()
  18645. * .getLength()
  18646. * .updateArcLengths()
  18647. *
  18648. * This following curves inherit from THREE.Curve:
  18649. *
  18650. * -- 2D curves --
  18651. * THREE.ArcCurve
  18652. * THREE.CubicBezierCurve
  18653. * THREE.EllipseCurve
  18654. * THREE.LineCurve
  18655. * THREE.QuadraticBezierCurve
  18656. * THREE.SplineCurve
  18657. *
  18658. * -- 3D curves --
  18659. * THREE.CatmullRomCurve3
  18660. * THREE.CubicBezierCurve3
  18661. * THREE.LineCurve3
  18662. * THREE.QuadraticBezierCurve3
  18663. *
  18664. * A series of curves can be represented as a THREE.CurvePath.
  18665. *
  18666. **/
  18667. class Curve {
  18668. constructor() {
  18669. this.type = 'Curve';
  18670. this.arcLengthDivisions = 200;
  18671. }
  18672. // Virtual base class method to overwrite and implement in subclasses
  18673. // - t [0 .. 1]
  18674. getPoint( /* t, optionalTarget */ ) {
  18675. console.warn( 'THREE.Curve: .getPoint() not implemented.' );
  18676. return null;
  18677. }
  18678. // Get point at relative position in curve according to arc length
  18679. // - u [0 .. 1]
  18680. getPointAt( u, optionalTarget ) {
  18681. const t = this.getUtoTmapping( u );
  18682. return this.getPoint( t, optionalTarget );
  18683. }
  18684. // Get sequence of points using getPoint( t )
  18685. getPoints( divisions = 5 ) {
  18686. const points = [];
  18687. for ( let d = 0; d <= divisions; d ++ ) {
  18688. points.push( this.getPoint( d / divisions ) );
  18689. }
  18690. return points;
  18691. }
  18692. // Get sequence of points using getPointAt( u )
  18693. getSpacedPoints( divisions = 5 ) {
  18694. const points = [];
  18695. for ( let d = 0; d <= divisions; d ++ ) {
  18696. points.push( this.getPointAt( d / divisions ) );
  18697. }
  18698. return points;
  18699. }
  18700. // Get total curve arc length
  18701. getLength() {
  18702. const lengths = this.getLengths();
  18703. return lengths[ lengths.length - 1 ];
  18704. }
  18705. // Get list of cumulative segment lengths
  18706. getLengths( divisions = this.arcLengthDivisions ) {
  18707. if ( this.cacheArcLengths &&
  18708. ( this.cacheArcLengths.length === divisions + 1 ) &&
  18709. ! this.needsUpdate ) {
  18710. return this.cacheArcLengths;
  18711. }
  18712. this.needsUpdate = false;
  18713. const cache = [];
  18714. let current, last = this.getPoint( 0 );
  18715. let sum = 0;
  18716. cache.push( 0 );
  18717. for ( let p = 1; p <= divisions; p ++ ) {
  18718. current = this.getPoint( p / divisions );
  18719. sum += current.distanceTo( last );
  18720. cache.push( sum );
  18721. last = current;
  18722. }
  18723. this.cacheArcLengths = cache;
  18724. return cache; // { sums: cache, sum: sum }; Sum is in the last element.
  18725. }
  18726. updateArcLengths() {
  18727. this.needsUpdate = true;
  18728. this.getLengths();
  18729. }
  18730. // Given u ( 0 .. 1 ), get a t to find p. This gives you points which are equidistant
  18731. getUtoTmapping( u, distance ) {
  18732. const arcLengths = this.getLengths();
  18733. let i = 0;
  18734. const il = arcLengths.length;
  18735. let targetArcLength; // The targeted u distance value to get
  18736. if ( distance ) {
  18737. targetArcLength = distance;
  18738. } else {
  18739. targetArcLength = u * arcLengths[ il - 1 ];
  18740. }
  18741. // binary search for the index with largest value smaller than target u distance
  18742. let low = 0, high = il - 1, comparison;
  18743. while ( low <= high ) {
  18744. 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
  18745. comparison = arcLengths[ i ] - targetArcLength;
  18746. if ( comparison < 0 ) {
  18747. low = i + 1;
  18748. } else if ( comparison > 0 ) {
  18749. high = i - 1;
  18750. } else {
  18751. high = i;
  18752. break;
  18753. // DONE
  18754. }
  18755. }
  18756. i = high;
  18757. if ( arcLengths[ i ] === targetArcLength ) {
  18758. return i / ( il - 1 );
  18759. }
  18760. // we could get finer grain at lengths, or use simple interpolation between two points
  18761. const lengthBefore = arcLengths[ i ];
  18762. const lengthAfter = arcLengths[ i + 1 ];
  18763. const segmentLength = lengthAfter - lengthBefore;
  18764. // determine where we are between the 'before' and 'after' points
  18765. const segmentFraction = ( targetArcLength - lengthBefore ) / segmentLength;
  18766. // add that fractional amount to t
  18767. const t = ( i + segmentFraction ) / ( il - 1 );
  18768. return t;
  18769. }
  18770. // Returns a unit vector tangent at t
  18771. // In case any sub curve does not implement its tangent derivation,
  18772. // 2 points a small delta apart will be used to find its gradient
  18773. // which seems to give a reasonable approximation
  18774. getTangent( t, optionalTarget ) {
  18775. const delta = 0.0001;
  18776. let t1 = t - delta;
  18777. let t2 = t + delta;
  18778. // Capping in case of danger
  18779. if ( t1 < 0 ) t1 = 0;
  18780. if ( t2 > 1 ) t2 = 1;
  18781. const pt1 = this.getPoint( t1 );
  18782. const pt2 = this.getPoint( t2 );
  18783. const tangent = optionalTarget || ( ( pt1.isVector2 ) ? new Vector2() : new Vector3() );
  18784. tangent.copy( pt2 ).sub( pt1 ).normalize();
  18785. return tangent;
  18786. }
  18787. getTangentAt( u, optionalTarget ) {
  18788. const t = this.getUtoTmapping( u );
  18789. return this.getTangent( t, optionalTarget );
  18790. }
  18791. computeFrenetFrames( segments, closed ) {
  18792. // see http://www.cs.indiana.edu/pub/techreports/TR425.pdf
  18793. const normal = new Vector3();
  18794. const tangents = [];
  18795. const normals = [];
  18796. const binormals = [];
  18797. const vec = new Vector3();
  18798. const mat = new Matrix4();
  18799. // compute the tangent vectors for each segment on the curve
  18800. for ( let i = 0; i <= segments; i ++ ) {
  18801. const u = i / segments;
  18802. tangents[ i ] = this.getTangentAt( u, new Vector3() );
  18803. }
  18804. // select an initial normal vector perpendicular to the first tangent vector,
  18805. // and in the direction of the minimum tangent xyz component
  18806. normals[ 0 ] = new Vector3();
  18807. binormals[ 0 ] = new Vector3();
  18808. let min = Number.MAX_VALUE;
  18809. const tx = Math.abs( tangents[ 0 ].x );
  18810. const ty = Math.abs( tangents[ 0 ].y );
  18811. const tz = Math.abs( tangents[ 0 ].z );
  18812. if ( tx <= min ) {
  18813. min = tx;
  18814. normal.set( 1, 0, 0 );
  18815. }
  18816. if ( ty <= min ) {
  18817. min = ty;
  18818. normal.set( 0, 1, 0 );
  18819. }
  18820. if ( tz <= min ) {
  18821. normal.set( 0, 0, 1 );
  18822. }
  18823. vec.crossVectors( tangents[ 0 ], normal ).normalize();
  18824. normals[ 0 ].crossVectors( tangents[ 0 ], vec );
  18825. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] );
  18826. // compute the slowly-varying normal and binormal vectors for each segment on the curve
  18827. for ( let i = 1; i <= segments; i ++ ) {
  18828. normals[ i ] = normals[ i - 1 ].clone();
  18829. binormals[ i ] = binormals[ i - 1 ].clone();
  18830. vec.crossVectors( tangents[ i - 1 ], tangents[ i ] );
  18831. if ( vec.length() > Number.EPSILON ) {
  18832. vec.normalize();
  18833. const theta = Math.acos( clamp( tangents[ i - 1 ].dot( tangents[ i ] ), - 1, 1 ) ); // clamp for floating pt errors
  18834. normals[ i ].applyMatrix4( mat.makeRotationAxis( vec, theta ) );
  18835. }
  18836. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  18837. }
  18838. // if the curve is closed, postprocess the vectors so the first and last normal vectors are the same
  18839. if ( closed === true ) {
  18840. let theta = Math.acos( clamp( normals[ 0 ].dot( normals[ segments ] ), - 1, 1 ) );
  18841. theta /= segments;
  18842. if ( tangents[ 0 ].dot( vec.crossVectors( normals[ 0 ], normals[ segments ] ) ) > 0 ) {
  18843. theta = - theta;
  18844. }
  18845. for ( let i = 1; i <= segments; i ++ ) {
  18846. // twist a little...
  18847. normals[ i ].applyMatrix4( mat.makeRotationAxis( tangents[ i ], theta * i ) );
  18848. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  18849. }
  18850. }
  18851. return {
  18852. tangents: tangents,
  18853. normals: normals,
  18854. binormals: binormals
  18855. };
  18856. }
  18857. clone() {
  18858. return new this.constructor().copy( this );
  18859. }
  18860. copy( source ) {
  18861. this.arcLengthDivisions = source.arcLengthDivisions;
  18862. return this;
  18863. }
  18864. toJSON() {
  18865. const data = {
  18866. metadata: {
  18867. version: 4.5,
  18868. type: 'Curve',
  18869. generator: 'Curve.toJSON'
  18870. }
  18871. };
  18872. data.arcLengthDivisions = this.arcLengthDivisions;
  18873. data.type = this.type;
  18874. return data;
  18875. }
  18876. fromJSON( json ) {
  18877. this.arcLengthDivisions = json.arcLengthDivisions;
  18878. return this;
  18879. }
  18880. }
  18881. class EllipseCurve extends Curve {
  18882. constructor( aX = 0, aY = 0, xRadius = 1, yRadius = 1, aStartAngle = 0, aEndAngle = Math.PI * 2, aClockwise = false, aRotation = 0 ) {
  18883. super();
  18884. this.isEllipseCurve = true;
  18885. this.type = 'EllipseCurve';
  18886. this.aX = aX;
  18887. this.aY = aY;
  18888. this.xRadius = xRadius;
  18889. this.yRadius = yRadius;
  18890. this.aStartAngle = aStartAngle;
  18891. this.aEndAngle = aEndAngle;
  18892. this.aClockwise = aClockwise;
  18893. this.aRotation = aRotation;
  18894. }
  18895. getPoint( t, optionalTarget ) {
  18896. const point = optionalTarget || new Vector2();
  18897. const twoPi = Math.PI * 2;
  18898. let deltaAngle = this.aEndAngle - this.aStartAngle;
  18899. const samePoints = Math.abs( deltaAngle ) < Number.EPSILON;
  18900. // ensures that deltaAngle is 0 .. 2 PI
  18901. while ( deltaAngle < 0 ) deltaAngle += twoPi;
  18902. while ( deltaAngle > twoPi ) deltaAngle -= twoPi;
  18903. if ( deltaAngle < Number.EPSILON ) {
  18904. if ( samePoints ) {
  18905. deltaAngle = 0;
  18906. } else {
  18907. deltaAngle = twoPi;
  18908. }
  18909. }
  18910. if ( this.aClockwise === true && ! samePoints ) {
  18911. if ( deltaAngle === twoPi ) {
  18912. deltaAngle = - twoPi;
  18913. } else {
  18914. deltaAngle = deltaAngle - twoPi;
  18915. }
  18916. }
  18917. const angle = this.aStartAngle + t * deltaAngle;
  18918. let x = this.aX + this.xRadius * Math.cos( angle );
  18919. let y = this.aY + this.yRadius * Math.sin( angle );
  18920. if ( this.aRotation !== 0 ) {
  18921. const cos = Math.cos( this.aRotation );
  18922. const sin = Math.sin( this.aRotation );
  18923. const tx = x - this.aX;
  18924. const ty = y - this.aY;
  18925. // Rotate the point about the center of the ellipse.
  18926. x = tx * cos - ty * sin + this.aX;
  18927. y = tx * sin + ty * cos + this.aY;
  18928. }
  18929. return point.set( x, y );
  18930. }
  18931. copy( source ) {
  18932. super.copy( source );
  18933. this.aX = source.aX;
  18934. this.aY = source.aY;
  18935. this.xRadius = source.xRadius;
  18936. this.yRadius = source.yRadius;
  18937. this.aStartAngle = source.aStartAngle;
  18938. this.aEndAngle = source.aEndAngle;
  18939. this.aClockwise = source.aClockwise;
  18940. this.aRotation = source.aRotation;
  18941. return this;
  18942. }
  18943. toJSON() {
  18944. const data = super.toJSON();
  18945. data.aX = this.aX;
  18946. data.aY = this.aY;
  18947. data.xRadius = this.xRadius;
  18948. data.yRadius = this.yRadius;
  18949. data.aStartAngle = this.aStartAngle;
  18950. data.aEndAngle = this.aEndAngle;
  18951. data.aClockwise = this.aClockwise;
  18952. data.aRotation = this.aRotation;
  18953. return data;
  18954. }
  18955. fromJSON( json ) {
  18956. super.fromJSON( json );
  18957. this.aX = json.aX;
  18958. this.aY = json.aY;
  18959. this.xRadius = json.xRadius;
  18960. this.yRadius = json.yRadius;
  18961. this.aStartAngle = json.aStartAngle;
  18962. this.aEndAngle = json.aEndAngle;
  18963. this.aClockwise = json.aClockwise;
  18964. this.aRotation = json.aRotation;
  18965. return this;
  18966. }
  18967. }
  18968. class ArcCurve extends EllipseCurve {
  18969. constructor( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  18970. super( aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  18971. this.isArcCurve = true;
  18972. this.type = 'ArcCurve';
  18973. }
  18974. }
  18975. /**
  18976. * Centripetal CatmullRom Curve - which is useful for avoiding
  18977. * cusps and self-intersections in non-uniform catmull rom curves.
  18978. * http://www.cemyuksel.com/research/catmullrom_param/catmullrom.pdf
  18979. *
  18980. * curve.type accepts centripetal(default), chordal and catmullrom
  18981. * curve.tension is used for catmullrom which defaults to 0.5
  18982. */
  18983. /*
  18984. Based on an optimized c++ solution in
  18985. - http://stackoverflow.com/questions/9489736/catmull-rom-curve-with-no-cusps-and-no-self-intersections/
  18986. - http://ideone.com/NoEbVM
  18987. This CubicPoly class could be used for reusing some variables and calculations,
  18988. but for three.js curve use, it could be possible inlined and flatten into a single function call
  18989. which can be placed in CurveUtils.
  18990. */
  18991. function CubicPoly() {
  18992. let c0 = 0, c1 = 0, c2 = 0, c3 = 0;
  18993. /*
  18994. * Compute coefficients for a cubic polynomial
  18995. * p(s) = c0 + c1*s + c2*s^2 + c3*s^3
  18996. * such that
  18997. * p(0) = x0, p(1) = x1
  18998. * and
  18999. * p'(0) = t0, p'(1) = t1.
  19000. */
  19001. function init( x0, x1, t0, t1 ) {
  19002. c0 = x0;
  19003. c1 = t0;
  19004. c2 = - 3 * x0 + 3 * x1 - 2 * t0 - t1;
  19005. c3 = 2 * x0 - 2 * x1 + t0 + t1;
  19006. }
  19007. return {
  19008. initCatmullRom: function ( x0, x1, x2, x3, tension ) {
  19009. init( x1, x2, tension * ( x2 - x0 ), tension * ( x3 - x1 ) );
  19010. },
  19011. initNonuniformCatmullRom: function ( x0, x1, x2, x3, dt0, dt1, dt2 ) {
  19012. // compute tangents when parameterized in [t1,t2]
  19013. let t1 = ( x1 - x0 ) / dt0 - ( x2 - x0 ) / ( dt0 + dt1 ) + ( x2 - x1 ) / dt1;
  19014. let t2 = ( x2 - x1 ) / dt1 - ( x3 - x1 ) / ( dt1 + dt2 ) + ( x3 - x2 ) / dt2;
  19015. // rescale tangents for parametrization in [0,1]
  19016. t1 *= dt1;
  19017. t2 *= dt1;
  19018. init( x1, x2, t1, t2 );
  19019. },
  19020. calc: function ( t ) {
  19021. const t2 = t * t;
  19022. const t3 = t2 * t;
  19023. return c0 + c1 * t + c2 * t2 + c3 * t3;
  19024. }
  19025. };
  19026. }
  19027. //
  19028. const tmp = /*@__PURE__*/ new Vector3();
  19029. const px = /*@__PURE__*/ new CubicPoly();
  19030. const py = /*@__PURE__*/ new CubicPoly();
  19031. const pz = /*@__PURE__*/ new CubicPoly();
  19032. class CatmullRomCurve3 extends Curve {
  19033. constructor( points = [], closed = false, curveType = 'centripetal', tension = 0.5 ) {
  19034. super();
  19035. this.isCatmullRomCurve3 = true;
  19036. this.type = 'CatmullRomCurve3';
  19037. this.points = points;
  19038. this.closed = closed;
  19039. this.curveType = curveType;
  19040. this.tension = tension;
  19041. }
  19042. getPoint( t, optionalTarget = new Vector3() ) {
  19043. const point = optionalTarget;
  19044. const points = this.points;
  19045. const l = points.length;
  19046. const p = ( l - ( this.closed ? 0 : 1 ) ) * t;
  19047. let intPoint = Math.floor( p );
  19048. let weight = p - intPoint;
  19049. if ( this.closed ) {
  19050. intPoint += intPoint > 0 ? 0 : ( Math.floor( Math.abs( intPoint ) / l ) + 1 ) * l;
  19051. } else if ( weight === 0 && intPoint === l - 1 ) {
  19052. intPoint = l - 2;
  19053. weight = 1;
  19054. }
  19055. let p0, p3; // 4 points (p1 & p2 defined below)
  19056. if ( this.closed || intPoint > 0 ) {
  19057. p0 = points[ ( intPoint - 1 ) % l ];
  19058. } else {
  19059. // extrapolate first point
  19060. tmp.subVectors( points[ 0 ], points[ 1 ] ).add( points[ 0 ] );
  19061. p0 = tmp;
  19062. }
  19063. const p1 = points[ intPoint % l ];
  19064. const p2 = points[ ( intPoint + 1 ) % l ];
  19065. if ( this.closed || intPoint + 2 < l ) {
  19066. p3 = points[ ( intPoint + 2 ) % l ];
  19067. } else {
  19068. // extrapolate last point
  19069. tmp.subVectors( points[ l - 1 ], points[ l - 2 ] ).add( points[ l - 1 ] );
  19070. p3 = tmp;
  19071. }
  19072. if ( this.curveType === 'centripetal' || this.curveType === 'chordal' ) {
  19073. // init Centripetal / Chordal Catmull-Rom
  19074. const pow = this.curveType === 'chordal' ? 0.5 : 0.25;
  19075. let dt0 = Math.pow( p0.distanceToSquared( p1 ), pow );
  19076. let dt1 = Math.pow( p1.distanceToSquared( p2 ), pow );
  19077. let dt2 = Math.pow( p2.distanceToSquared( p3 ), pow );
  19078. // safety check for repeated points
  19079. if ( dt1 < 1e-4 ) dt1 = 1.0;
  19080. if ( dt0 < 1e-4 ) dt0 = dt1;
  19081. if ( dt2 < 1e-4 ) dt2 = dt1;
  19082. px.initNonuniformCatmullRom( p0.x, p1.x, p2.x, p3.x, dt0, dt1, dt2 );
  19083. py.initNonuniformCatmullRom( p0.y, p1.y, p2.y, p3.y, dt0, dt1, dt2 );
  19084. pz.initNonuniformCatmullRom( p0.z, p1.z, p2.z, p3.z, dt0, dt1, dt2 );
  19085. } else if ( this.curveType === 'catmullrom' ) {
  19086. px.initCatmullRom( p0.x, p1.x, p2.x, p3.x, this.tension );
  19087. py.initCatmullRom( p0.y, p1.y, p2.y, p3.y, this.tension );
  19088. pz.initCatmullRom( p0.z, p1.z, p2.z, p3.z, this.tension );
  19089. }
  19090. point.set(
  19091. px.calc( weight ),
  19092. py.calc( weight ),
  19093. pz.calc( weight )
  19094. );
  19095. return point;
  19096. }
  19097. copy( source ) {
  19098. super.copy( source );
  19099. this.points = [];
  19100. for ( let i = 0, l = source.points.length; i < l; i ++ ) {
  19101. const point = source.points[ i ];
  19102. this.points.push( point.clone() );
  19103. }
  19104. this.closed = source.closed;
  19105. this.curveType = source.curveType;
  19106. this.tension = source.tension;
  19107. return this;
  19108. }
  19109. toJSON() {
  19110. const data = super.toJSON();
  19111. data.points = [];
  19112. for ( let i = 0, l = this.points.length; i < l; i ++ ) {
  19113. const point = this.points[ i ];
  19114. data.points.push( point.toArray() );
  19115. }
  19116. data.closed = this.closed;
  19117. data.curveType = this.curveType;
  19118. data.tension = this.tension;
  19119. return data;
  19120. }
  19121. fromJSON( json ) {
  19122. super.fromJSON( json );
  19123. this.points = [];
  19124. for ( let i = 0, l = json.points.length; i < l; i ++ ) {
  19125. const point = json.points[ i ];
  19126. this.points.push( new Vector3().fromArray( point ) );
  19127. }
  19128. this.closed = json.closed;
  19129. this.curveType = json.curveType;
  19130. this.tension = json.tension;
  19131. return this;
  19132. }
  19133. }
  19134. /**
  19135. * Bezier Curves formulas obtained from
  19136. * https://en.wikipedia.org/wiki/B%C3%A9zier_curve
  19137. */
  19138. function CatmullRom( t, p0, p1, p2, p3 ) {
  19139. const v0 = ( p2 - p0 ) * 0.5;
  19140. const v1 = ( p3 - p1 ) * 0.5;
  19141. const t2 = t * t;
  19142. const t3 = t * t2;
  19143. return ( 2 * p1 - 2 * p2 + v0 + v1 ) * t3 + ( - 3 * p1 + 3 * p2 - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  19144. }
  19145. //
  19146. function QuadraticBezierP0( t, p ) {
  19147. const k = 1 - t;
  19148. return k * k * p;
  19149. }
  19150. function QuadraticBezierP1( t, p ) {
  19151. return 2 * ( 1 - t ) * t * p;
  19152. }
  19153. function QuadraticBezierP2( t, p ) {
  19154. return t * t * p;
  19155. }
  19156. function QuadraticBezier( t, p0, p1, p2 ) {
  19157. return QuadraticBezierP0( t, p0 ) + QuadraticBezierP1( t, p1 ) +
  19158. QuadraticBezierP2( t, p2 );
  19159. }
  19160. //
  19161. function CubicBezierP0( t, p ) {
  19162. const k = 1 - t;
  19163. return k * k * k * p;
  19164. }
  19165. function CubicBezierP1( t, p ) {
  19166. const k = 1 - t;
  19167. return 3 * k * k * t * p;
  19168. }
  19169. function CubicBezierP2( t, p ) {
  19170. return 3 * ( 1 - t ) * t * t * p;
  19171. }
  19172. function CubicBezierP3( t, p ) {
  19173. return t * t * t * p;
  19174. }
  19175. function CubicBezier( t, p0, p1, p2, p3 ) {
  19176. return CubicBezierP0( t, p0 ) + CubicBezierP1( t, p1 ) + CubicBezierP2( t, p2 ) +
  19177. CubicBezierP3( t, p3 );
  19178. }
  19179. class CubicBezierCurve extends Curve {
  19180. constructor( v0 = new Vector2(), v1 = new Vector2(), v2 = new Vector2(), v3 = new Vector2() ) {
  19181. super();
  19182. this.isCubicBezierCurve = true;
  19183. this.type = 'CubicBezierCurve';
  19184. this.v0 = v0;
  19185. this.v1 = v1;
  19186. this.v2 = v2;
  19187. this.v3 = v3;
  19188. }
  19189. getPoint( t, optionalTarget = new Vector2() ) {
  19190. const point = optionalTarget;
  19191. const v0 = this.v0, v1 = this.v1, v2 = this.v2, v3 = this.v3;
  19192. point.set(
  19193. CubicBezier( t, v0.x, v1.x, v2.x, v3.x ),
  19194. CubicBezier( t, v0.y, v1.y, v2.y, v3.y )
  19195. );
  19196. return point;
  19197. }
  19198. copy( source ) {
  19199. super.copy( source );
  19200. this.v0.copy( source.v0 );
  19201. this.v1.copy( source.v1 );
  19202. this.v2.copy( source.v2 );
  19203. this.v3.copy( source.v3 );
  19204. return this;
  19205. }
  19206. toJSON() {
  19207. const data = super.toJSON();
  19208. data.v0 = this.v0.toArray();
  19209. data.v1 = this.v1.toArray();
  19210. data.v2 = this.v2.toArray();
  19211. data.v3 = this.v3.toArray();
  19212. return data;
  19213. }
  19214. fromJSON( json ) {
  19215. super.fromJSON( json );
  19216. this.v0.fromArray( json.v0 );
  19217. this.v1.fromArray( json.v1 );
  19218. this.v2.fromArray( json.v2 );
  19219. this.v3.fromArray( json.v3 );
  19220. return this;
  19221. }
  19222. }
  19223. class CubicBezierCurve3 extends Curve {
  19224. constructor( v0 = new Vector3(), v1 = new Vector3(), v2 = new Vector3(), v3 = new Vector3() ) {
  19225. super();
  19226. this.isCubicBezierCurve3 = true;
  19227. this.type = 'CubicBezierCurve3';
  19228. this.v0 = v0;
  19229. this.v1 = v1;
  19230. this.v2 = v2;
  19231. this.v3 = v3;
  19232. }
  19233. getPoint( t, optionalTarget = new Vector3() ) {
  19234. const point = optionalTarget;
  19235. const v0 = this.v0, v1 = this.v1, v2 = this.v2, v3 = this.v3;
  19236. point.set(
  19237. CubicBezier( t, v0.x, v1.x, v2.x, v3.x ),
  19238. CubicBezier( t, v0.y, v1.y, v2.y, v3.y ),
  19239. CubicBezier( t, v0.z, v1.z, v2.z, v3.z )
  19240. );
  19241. return point;
  19242. }
  19243. copy( source ) {
  19244. super.copy( source );
  19245. this.v0.copy( source.v0 );
  19246. this.v1.copy( source.v1 );
  19247. this.v2.copy( source.v2 );
  19248. this.v3.copy( source.v3 );
  19249. return this;
  19250. }
  19251. toJSON() {
  19252. const data = super.toJSON();
  19253. data.v0 = this.v0.toArray();
  19254. data.v1 = this.v1.toArray();
  19255. data.v2 = this.v2.toArray();
  19256. data.v3 = this.v3.toArray();
  19257. return data;
  19258. }
  19259. fromJSON( json ) {
  19260. super.fromJSON( json );
  19261. this.v0.fromArray( json.v0 );
  19262. this.v1.fromArray( json.v1 );
  19263. this.v2.fromArray( json.v2 );
  19264. this.v3.fromArray( json.v3 );
  19265. return this;
  19266. }
  19267. }
  19268. class LineCurve extends Curve {
  19269. constructor( v1 = new Vector2(), v2 = new Vector2() ) {
  19270. super();
  19271. this.isLineCurve = true;
  19272. this.type = 'LineCurve';
  19273. this.v1 = v1;
  19274. this.v2 = v2;
  19275. }
  19276. getPoint( t, optionalTarget = new Vector2() ) {
  19277. const point = optionalTarget;
  19278. if ( t === 1 ) {
  19279. point.copy( this.v2 );
  19280. } else {
  19281. point.copy( this.v2 ).sub( this.v1 );
  19282. point.multiplyScalar( t ).add( this.v1 );
  19283. }
  19284. return point;
  19285. }
  19286. // Line curve is linear, so we can overwrite default getPointAt
  19287. getPointAt( u, optionalTarget ) {
  19288. return this.getPoint( u, optionalTarget );
  19289. }
  19290. getTangent( t, optionalTarget ) {
  19291. const tangent = optionalTarget || new Vector2();
  19292. tangent.copy( this.v2 ).sub( this.v1 ).normalize();
  19293. return tangent;
  19294. }
  19295. copy( source ) {
  19296. super.copy( source );
  19297. this.v1.copy( source.v1 );
  19298. this.v2.copy( source.v2 );
  19299. return this;
  19300. }
  19301. toJSON() {
  19302. const data = super.toJSON();
  19303. data.v1 = this.v1.toArray();
  19304. data.v2 = this.v2.toArray();
  19305. return data;
  19306. }
  19307. fromJSON( json ) {
  19308. super.fromJSON( json );
  19309. this.v1.fromArray( json.v1 );
  19310. this.v2.fromArray( json.v2 );
  19311. return this;
  19312. }
  19313. }
  19314. class LineCurve3 extends Curve {
  19315. constructor( v1 = new Vector3(), v2 = new Vector3() ) {
  19316. super();
  19317. this.isLineCurve3 = true;
  19318. this.type = 'LineCurve3';
  19319. this.v1 = v1;
  19320. this.v2 = v2;
  19321. }
  19322. getPoint( t, optionalTarget = new Vector3() ) {
  19323. const point = optionalTarget;
  19324. if ( t === 1 ) {
  19325. point.copy( this.v2 );
  19326. } else {
  19327. point.copy( this.v2 ).sub( this.v1 );
  19328. point.multiplyScalar( t ).add( this.v1 );
  19329. }
  19330. return point;
  19331. }
  19332. // Line curve is linear, so we can overwrite default getPointAt
  19333. getPointAt( u, optionalTarget ) {
  19334. return this.getPoint( u, optionalTarget );
  19335. }
  19336. copy( source ) {
  19337. super.copy( source );
  19338. this.v1.copy( source.v1 );
  19339. this.v2.copy( source.v2 );
  19340. return this;
  19341. }
  19342. toJSON() {
  19343. const data = super.toJSON();
  19344. data.v1 = this.v1.toArray();
  19345. data.v2 = this.v2.toArray();
  19346. return data;
  19347. }
  19348. fromJSON( json ) {
  19349. super.fromJSON( json );
  19350. this.v1.fromArray( json.v1 );
  19351. this.v2.fromArray( json.v2 );
  19352. return this;
  19353. }
  19354. }
  19355. class QuadraticBezierCurve extends Curve {
  19356. constructor( v0 = new Vector2(), v1 = new Vector2(), v2 = new Vector2() ) {
  19357. super();
  19358. this.isQuadraticBezierCurve = true;
  19359. this.type = 'QuadraticBezierCurve';
  19360. this.v0 = v0;
  19361. this.v1 = v1;
  19362. this.v2 = v2;
  19363. }
  19364. getPoint( t, optionalTarget = new Vector2() ) {
  19365. const point = optionalTarget;
  19366. const v0 = this.v0, v1 = this.v1, v2 = this.v2;
  19367. point.set(
  19368. QuadraticBezier( t, v0.x, v1.x, v2.x ),
  19369. QuadraticBezier( t, v0.y, v1.y, v2.y )
  19370. );
  19371. return point;
  19372. }
  19373. copy( source ) {
  19374. super.copy( source );
  19375. this.v0.copy( source.v0 );
  19376. this.v1.copy( source.v1 );
  19377. this.v2.copy( source.v2 );
  19378. return this;
  19379. }
  19380. toJSON() {
  19381. const data = super.toJSON();
  19382. data.v0 = this.v0.toArray();
  19383. data.v1 = this.v1.toArray();
  19384. data.v2 = this.v2.toArray();
  19385. return data;
  19386. }
  19387. fromJSON( json ) {
  19388. super.fromJSON( json );
  19389. this.v0.fromArray( json.v0 );
  19390. this.v1.fromArray( json.v1 );
  19391. this.v2.fromArray( json.v2 );
  19392. return this;
  19393. }
  19394. }
  19395. class QuadraticBezierCurve3 extends Curve {
  19396. constructor( v0 = new Vector3(), v1 = new Vector3(), v2 = new Vector3() ) {
  19397. super();
  19398. this.isQuadraticBezierCurve3 = true;
  19399. this.type = 'QuadraticBezierCurve3';
  19400. this.v0 = v0;
  19401. this.v1 = v1;
  19402. this.v2 = v2;
  19403. }
  19404. getPoint( t, optionalTarget = new Vector3() ) {
  19405. const point = optionalTarget;
  19406. const v0 = this.v0, v1 = this.v1, v2 = this.v2;
  19407. point.set(
  19408. QuadraticBezier( t, v0.x, v1.x, v2.x ),
  19409. QuadraticBezier( t, v0.y, v1.y, v2.y ),
  19410. QuadraticBezier( t, v0.z, v1.z, v2.z )
  19411. );
  19412. return point;
  19413. }
  19414. copy( source ) {
  19415. super.copy( source );
  19416. this.v0.copy( source.v0 );
  19417. this.v1.copy( source.v1 );
  19418. this.v2.copy( source.v2 );
  19419. return this;
  19420. }
  19421. toJSON() {
  19422. const data = super.toJSON();
  19423. data.v0 = this.v0.toArray();
  19424. data.v1 = this.v1.toArray();
  19425. data.v2 = this.v2.toArray();
  19426. return data;
  19427. }
  19428. fromJSON( json ) {
  19429. super.fromJSON( json );
  19430. this.v0.fromArray( json.v0 );
  19431. this.v1.fromArray( json.v1 );
  19432. this.v2.fromArray( json.v2 );
  19433. return this;
  19434. }
  19435. }
  19436. class SplineCurve extends Curve {
  19437. constructor( points = [] ) {
  19438. super();
  19439. this.isSplineCurve = true;
  19440. this.type = 'SplineCurve';
  19441. this.points = points;
  19442. }
  19443. getPoint( t, optionalTarget = new Vector2() ) {
  19444. const point = optionalTarget;
  19445. const points = this.points;
  19446. const p = ( points.length - 1 ) * t;
  19447. const intPoint = Math.floor( p );
  19448. const weight = p - intPoint;
  19449. const p0 = points[ intPoint === 0 ? intPoint : intPoint - 1 ];
  19450. const p1 = points[ intPoint ];
  19451. const p2 = points[ intPoint > points.length - 2 ? points.length - 1 : intPoint + 1 ];
  19452. const p3 = points[ intPoint > points.length - 3 ? points.length - 1 : intPoint + 2 ];
  19453. point.set(
  19454. CatmullRom( weight, p0.x, p1.x, p2.x, p3.x ),
  19455. CatmullRom( weight, p0.y, p1.y, p2.y, p3.y )
  19456. );
  19457. return point;
  19458. }
  19459. copy( source ) {
  19460. super.copy( source );
  19461. this.points = [];
  19462. for ( let i = 0, l = source.points.length; i < l; i ++ ) {
  19463. const point = source.points[ i ];
  19464. this.points.push( point.clone() );
  19465. }
  19466. return this;
  19467. }
  19468. toJSON() {
  19469. const data = super.toJSON();
  19470. data.points = [];
  19471. for ( let i = 0, l = this.points.length; i < l; i ++ ) {
  19472. const point = this.points[ i ];
  19473. data.points.push( point.toArray() );
  19474. }
  19475. return data;
  19476. }
  19477. fromJSON( json ) {
  19478. super.fromJSON( json );
  19479. this.points = [];
  19480. for ( let i = 0, l = json.points.length; i < l; i ++ ) {
  19481. const point = json.points[ i ];
  19482. this.points.push( new Vector2().fromArray( point ) );
  19483. }
  19484. return this;
  19485. }
  19486. }
  19487. var Curves = /*#__PURE__*/Object.freeze({
  19488. __proto__: null,
  19489. ArcCurve: ArcCurve,
  19490. CatmullRomCurve3: CatmullRomCurve3,
  19491. CubicBezierCurve: CubicBezierCurve,
  19492. CubicBezierCurve3: CubicBezierCurve3,
  19493. EllipseCurve: EllipseCurve,
  19494. LineCurve: LineCurve,
  19495. LineCurve3: LineCurve3,
  19496. QuadraticBezierCurve: QuadraticBezierCurve,
  19497. QuadraticBezierCurve3: QuadraticBezierCurve3,
  19498. SplineCurve: SplineCurve
  19499. });
  19500. /**************************************************************
  19501. * Curved Path - a curve path is simply a array of connected
  19502. * curves, but retains the api of a curve
  19503. **************************************************************/
  19504. class CurvePath extends Curve {
  19505. constructor() {
  19506. super();
  19507. this.type = 'CurvePath';
  19508. this.curves = [];
  19509. this.autoClose = false; // Automatically closes the path
  19510. }
  19511. add( curve ) {
  19512. this.curves.push( curve );
  19513. }
  19514. closePath() {
  19515. // Add a line curve if start and end of lines are not connected
  19516. const startPoint = this.curves[ 0 ].getPoint( 0 );
  19517. const endPoint = this.curves[ this.curves.length - 1 ].getPoint( 1 );
  19518. if ( ! startPoint.equals( endPoint ) ) {
  19519. this.curves.push( new LineCurve( endPoint, startPoint ) );
  19520. }
  19521. }
  19522. // To get accurate point with reference to
  19523. // entire path distance at time t,
  19524. // following has to be done:
  19525. // 1. Length of each sub path have to be known
  19526. // 2. Locate and identify type of curve
  19527. // 3. Get t for the curve
  19528. // 4. Return curve.getPointAt(t')
  19529. getPoint( t, optionalTarget ) {
  19530. const d = t * this.getLength();
  19531. const curveLengths = this.getCurveLengths();
  19532. let i = 0;
  19533. // To think about boundaries points.
  19534. while ( i < curveLengths.length ) {
  19535. if ( curveLengths[ i ] >= d ) {
  19536. const diff = curveLengths[ i ] - d;
  19537. const curve = this.curves[ i ];
  19538. const segmentLength = curve.getLength();
  19539. const u = segmentLength === 0 ? 0 : 1 - diff / segmentLength;
  19540. return curve.getPointAt( u, optionalTarget );
  19541. }
  19542. i ++;
  19543. }
  19544. return null;
  19545. // loop where sum != 0, sum > d , sum+1 <d
  19546. }
  19547. // We cannot use the default THREE.Curve getPoint() with getLength() because in
  19548. // THREE.Curve, getLength() depends on getPoint() but in THREE.CurvePath
  19549. // getPoint() depends on getLength
  19550. getLength() {
  19551. const lens = this.getCurveLengths();
  19552. return lens[ lens.length - 1 ];
  19553. }
  19554. // cacheLengths must be recalculated.
  19555. updateArcLengths() {
  19556. this.needsUpdate = true;
  19557. this.cacheLengths = null;
  19558. this.getCurveLengths();
  19559. }
  19560. // Compute lengths and cache them
  19561. // We cannot overwrite getLengths() because UtoT mapping uses it.
  19562. getCurveLengths() {
  19563. // We use cache values if curves and cache array are same length
  19564. if ( this.cacheLengths && this.cacheLengths.length === this.curves.length ) {
  19565. return this.cacheLengths;
  19566. }
  19567. // Get length of sub-curve
  19568. // Push sums into cached array
  19569. const lengths = [];
  19570. let sums = 0;
  19571. for ( let i = 0, l = this.curves.length; i < l; i ++ ) {
  19572. sums += this.curves[ i ].getLength();
  19573. lengths.push( sums );
  19574. }
  19575. this.cacheLengths = lengths;
  19576. return lengths;
  19577. }
  19578. getSpacedPoints( divisions = 40 ) {
  19579. const points = [];
  19580. for ( let i = 0; i <= divisions; i ++ ) {
  19581. points.push( this.getPoint( i / divisions ) );
  19582. }
  19583. if ( this.autoClose ) {
  19584. points.push( points[ 0 ] );
  19585. }
  19586. return points;
  19587. }
  19588. getPoints( divisions = 12 ) {
  19589. const points = [];
  19590. let last;
  19591. for ( let i = 0, curves = this.curves; i < curves.length; i ++ ) {
  19592. const curve = curves[ i ];
  19593. const resolution = curve.isEllipseCurve ? divisions * 2
  19594. : ( curve.isLineCurve || curve.isLineCurve3 ) ? 1
  19595. : curve.isSplineCurve ? divisions * curve.points.length
  19596. : divisions;
  19597. const pts = curve.getPoints( resolution );
  19598. for ( let j = 0; j < pts.length; j ++ ) {
  19599. const point = pts[ j ];
  19600. if ( last && last.equals( point ) ) continue; // ensures no consecutive points are duplicates
  19601. points.push( point );
  19602. last = point;
  19603. }
  19604. }
  19605. if ( this.autoClose && points.length > 1 && ! points[ points.length - 1 ].equals( points[ 0 ] ) ) {
  19606. points.push( points[ 0 ] );
  19607. }
  19608. return points;
  19609. }
  19610. copy( source ) {
  19611. super.copy( source );
  19612. this.curves = [];
  19613. for ( let i = 0, l = source.curves.length; i < l; i ++ ) {
  19614. const curve = source.curves[ i ];
  19615. this.curves.push( curve.clone() );
  19616. }
  19617. this.autoClose = source.autoClose;
  19618. return this;
  19619. }
  19620. toJSON() {
  19621. const data = super.toJSON();
  19622. data.autoClose = this.autoClose;
  19623. data.curves = [];
  19624. for ( let i = 0, l = this.curves.length; i < l; i ++ ) {
  19625. const curve = this.curves[ i ];
  19626. data.curves.push( curve.toJSON() );
  19627. }
  19628. return data;
  19629. }
  19630. fromJSON( json ) {
  19631. super.fromJSON( json );
  19632. this.autoClose = json.autoClose;
  19633. this.curves = [];
  19634. for ( let i = 0, l = json.curves.length; i < l; i ++ ) {
  19635. const curve = json.curves[ i ];
  19636. this.curves.push( new Curves[ curve.type ]().fromJSON( curve ) );
  19637. }
  19638. return this;
  19639. }
  19640. }
  19641. class Path extends CurvePath {
  19642. constructor( points ) {
  19643. super();
  19644. this.type = 'Path';
  19645. this.currentPoint = new Vector2();
  19646. if ( points ) {
  19647. this.setFromPoints( points );
  19648. }
  19649. }
  19650. setFromPoints( points ) {
  19651. this.moveTo( points[ 0 ].x, points[ 0 ].y );
  19652. for ( let i = 1, l = points.length; i < l; i ++ ) {
  19653. this.lineTo( points[ i ].x, points[ i ].y );
  19654. }
  19655. return this;
  19656. }
  19657. moveTo( x, y ) {
  19658. this.currentPoint.set( x, y ); // TODO consider referencing vectors instead of copying?
  19659. return this;
  19660. }
  19661. lineTo( x, y ) {
  19662. const curve = new LineCurve( this.currentPoint.clone(), new Vector2( x, y ) );
  19663. this.curves.push( curve );
  19664. this.currentPoint.set( x, y );
  19665. return this;
  19666. }
  19667. quadraticCurveTo( aCPx, aCPy, aX, aY ) {
  19668. const curve = new QuadraticBezierCurve(
  19669. this.currentPoint.clone(),
  19670. new Vector2( aCPx, aCPy ),
  19671. new Vector2( aX, aY )
  19672. );
  19673. this.curves.push( curve );
  19674. this.currentPoint.set( aX, aY );
  19675. return this;
  19676. }
  19677. bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) {
  19678. const curve = new CubicBezierCurve(
  19679. this.currentPoint.clone(),
  19680. new Vector2( aCP1x, aCP1y ),
  19681. new Vector2( aCP2x, aCP2y ),
  19682. new Vector2( aX, aY )
  19683. );
  19684. this.curves.push( curve );
  19685. this.currentPoint.set( aX, aY );
  19686. return this;
  19687. }
  19688. splineThru( pts /*Array of Vector*/ ) {
  19689. const npts = [ this.currentPoint.clone() ].concat( pts );
  19690. const curve = new SplineCurve( npts );
  19691. this.curves.push( curve );
  19692. this.currentPoint.copy( pts[ pts.length - 1 ] );
  19693. return this;
  19694. }
  19695. arc( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  19696. const x0 = this.currentPoint.x;
  19697. const y0 = this.currentPoint.y;
  19698. this.absarc( aX + x0, aY + y0, aRadius,
  19699. aStartAngle, aEndAngle, aClockwise );
  19700. return this;
  19701. }
  19702. absarc( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  19703. this.absellipse( aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  19704. return this;
  19705. }
  19706. ellipse( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  19707. const x0 = this.currentPoint.x;
  19708. const y0 = this.currentPoint.y;
  19709. this.absellipse( aX + x0, aY + y0, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation );
  19710. return this;
  19711. }
  19712. absellipse( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  19713. const curve = new EllipseCurve( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation );
  19714. if ( this.curves.length > 0 ) {
  19715. // if a previous curve is present, attempt to join
  19716. const firstPoint = curve.getPoint( 0 );
  19717. if ( ! firstPoint.equals( this.currentPoint ) ) {
  19718. this.lineTo( firstPoint.x, firstPoint.y );
  19719. }
  19720. }
  19721. this.curves.push( curve );
  19722. const lastPoint = curve.getPoint( 1 );
  19723. this.currentPoint.copy( lastPoint );
  19724. return this;
  19725. }
  19726. copy( source ) {
  19727. super.copy( source );
  19728. this.currentPoint.copy( source.currentPoint );
  19729. return this;
  19730. }
  19731. toJSON() {
  19732. const data = super.toJSON();
  19733. data.currentPoint = this.currentPoint.toArray();
  19734. return data;
  19735. }
  19736. fromJSON( json ) {
  19737. super.fromJSON( json );
  19738. this.currentPoint.fromArray( json.currentPoint );
  19739. return this;
  19740. }
  19741. }
  19742. class LatheGeometry extends BufferGeometry {
  19743. 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 ) {
  19744. super();
  19745. this.type = 'LatheGeometry';
  19746. this.parameters = {
  19747. points: points,
  19748. segments: segments,
  19749. phiStart: phiStart,
  19750. phiLength: phiLength
  19751. };
  19752. segments = Math.floor( segments );
  19753. // clamp phiLength so it's in range of [ 0, 2PI ]
  19754. phiLength = clamp( phiLength, 0, Math.PI * 2 );
  19755. // buffers
  19756. const indices = [];
  19757. const vertices = [];
  19758. const uvs = [];
  19759. const initNormals = [];
  19760. const normals = [];
  19761. // helper variables
  19762. const inverseSegments = 1.0 / segments;
  19763. const vertex = new Vector3();
  19764. const uv = new Vector2();
  19765. const normal = new Vector3();
  19766. const curNormal = new Vector3();
  19767. const prevNormal = new Vector3();
  19768. let dx = 0;
  19769. let dy = 0;
  19770. // pre-compute normals for initial "meridian"
  19771. for ( let j = 0; j <= ( points.length - 1 ); j ++ ) {
  19772. switch ( j ) {
  19773. case 0: // special handling for 1st vertex on path
  19774. dx = points[ j + 1 ].x - points[ j ].x;
  19775. dy = points[ j + 1 ].y - points[ j ].y;
  19776. normal.x = dy * 1.0;
  19777. normal.y = - dx;
  19778. normal.z = dy * 0.0;
  19779. prevNormal.copy( normal );
  19780. normal.normalize();
  19781. initNormals.push( normal.x, normal.y, normal.z );
  19782. break;
  19783. case ( points.length - 1 ): // special handling for last Vertex on path
  19784. initNormals.push( prevNormal.x, prevNormal.y, prevNormal.z );
  19785. break;
  19786. default: // default handling for all vertices in between
  19787. dx = points[ j + 1 ].x - points[ j ].x;
  19788. dy = points[ j + 1 ].y - points[ j ].y;
  19789. normal.x = dy * 1.0;
  19790. normal.y = - dx;
  19791. normal.z = dy * 0.0;
  19792. curNormal.copy( normal );
  19793. normal.x += prevNormal.x;
  19794. normal.y += prevNormal.y;
  19795. normal.z += prevNormal.z;
  19796. normal.normalize();
  19797. initNormals.push( normal.x, normal.y, normal.z );
  19798. prevNormal.copy( curNormal );
  19799. }
  19800. }
  19801. // generate vertices, uvs and normals
  19802. for ( let i = 0; i <= segments; i ++ ) {
  19803. const phi = phiStart + i * inverseSegments * phiLength;
  19804. const sin = Math.sin( phi );
  19805. const cos = Math.cos( phi );
  19806. for ( let j = 0; j <= ( points.length - 1 ); j ++ ) {
  19807. // vertex
  19808. vertex.x = points[ j ].x * sin;
  19809. vertex.y = points[ j ].y;
  19810. vertex.z = points[ j ].x * cos;
  19811. vertices.push( vertex.x, vertex.y, vertex.z );
  19812. // uv
  19813. uv.x = i / segments;
  19814. uv.y = j / ( points.length - 1 );
  19815. uvs.push( uv.x, uv.y );
  19816. // normal
  19817. const x = initNormals[ 3 * j + 0 ] * sin;
  19818. const y = initNormals[ 3 * j + 1 ];
  19819. const z = initNormals[ 3 * j + 0 ] * cos;
  19820. normals.push( x, y, z );
  19821. }
  19822. }
  19823. // indices
  19824. for ( let i = 0; i < segments; i ++ ) {
  19825. for ( let j = 0; j < ( points.length - 1 ); j ++ ) {
  19826. const base = j + i * points.length;
  19827. const a = base;
  19828. const b = base + points.length;
  19829. const c = base + points.length + 1;
  19830. const d = base + 1;
  19831. // faces
  19832. indices.push( a, b, d );
  19833. indices.push( c, d, b );
  19834. }
  19835. }
  19836. // build geometry
  19837. this.setIndex( indices );
  19838. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  19839. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  19840. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  19841. }
  19842. static fromJSON( data ) {
  19843. return new LatheGeometry( data.points, data.segments, data.phiStart, data.phiLength );
  19844. }
  19845. }
  19846. class CapsuleGeometry extends LatheGeometry {
  19847. constructor( radius = 1, length = 1, capSegments = 4, radialSegments = 8 ) {
  19848. const path = new Path();
  19849. path.absarc( 0, - length / 2, radius, Math.PI * 1.5, 0 );
  19850. path.absarc( 0, length / 2, radius, 0, Math.PI * 0.5 );
  19851. super( path.getPoints( capSegments ), radialSegments );
  19852. this.type = 'CapsuleGeometry';
  19853. this.parameters = {
  19854. radius: radius,
  19855. height: length,
  19856. capSegments: capSegments,
  19857. radialSegments: radialSegments,
  19858. };
  19859. }
  19860. static fromJSON( data ) {
  19861. return new CapsuleGeometry( data.radius, data.length, data.capSegments, data.radialSegments );
  19862. }
  19863. }
  19864. class CircleGeometry extends BufferGeometry {
  19865. constructor( radius = 1, segments = 32, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  19866. super();
  19867. this.type = 'CircleGeometry';
  19868. this.parameters = {
  19869. radius: radius,
  19870. segments: segments,
  19871. thetaStart: thetaStart,
  19872. thetaLength: thetaLength
  19873. };
  19874. segments = Math.max( 3, segments );
  19875. // buffers
  19876. const indices = [];
  19877. const vertices = [];
  19878. const normals = [];
  19879. const uvs = [];
  19880. // helper variables
  19881. const vertex = new Vector3();
  19882. const uv = new Vector2();
  19883. // center point
  19884. vertices.push( 0, 0, 0 );
  19885. normals.push( 0, 0, 1 );
  19886. uvs.push( 0.5, 0.5 );
  19887. for ( let s = 0, i = 3; s <= segments; s ++, i += 3 ) {
  19888. const segment = thetaStart + s / segments * thetaLength;
  19889. // vertex
  19890. vertex.x = radius * Math.cos( segment );
  19891. vertex.y = radius * Math.sin( segment );
  19892. vertices.push( vertex.x, vertex.y, vertex.z );
  19893. // normal
  19894. normals.push( 0, 0, 1 );
  19895. // uvs
  19896. uv.x = ( vertices[ i ] / radius + 1 ) / 2;
  19897. uv.y = ( vertices[ i + 1 ] / radius + 1 ) / 2;
  19898. uvs.push( uv.x, uv.y );
  19899. }
  19900. // indices
  19901. for ( let i = 1; i <= segments; i ++ ) {
  19902. indices.push( i, i + 1, 0 );
  19903. }
  19904. // build geometry
  19905. this.setIndex( indices );
  19906. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  19907. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  19908. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  19909. }
  19910. static fromJSON( data ) {
  19911. return new CircleGeometry( data.radius, data.segments, data.thetaStart, data.thetaLength );
  19912. }
  19913. }
  19914. class CylinderGeometry extends BufferGeometry {
  19915. constructor( radiusTop = 1, radiusBottom = 1, height = 1, radialSegments = 32, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  19916. super();
  19917. this.type = 'CylinderGeometry';
  19918. this.parameters = {
  19919. radiusTop: radiusTop,
  19920. radiusBottom: radiusBottom,
  19921. height: height,
  19922. radialSegments: radialSegments,
  19923. heightSegments: heightSegments,
  19924. openEnded: openEnded,
  19925. thetaStart: thetaStart,
  19926. thetaLength: thetaLength
  19927. };
  19928. const scope = this;
  19929. radialSegments = Math.floor( radialSegments );
  19930. heightSegments = Math.floor( heightSegments );
  19931. // buffers
  19932. const indices = [];
  19933. const vertices = [];
  19934. const normals = [];
  19935. const uvs = [];
  19936. // helper variables
  19937. let index = 0;
  19938. const indexArray = [];
  19939. const halfHeight = height / 2;
  19940. let groupStart = 0;
  19941. // generate geometry
  19942. generateTorso();
  19943. if ( openEnded === false ) {
  19944. if ( radiusTop > 0 ) generateCap( true );
  19945. if ( radiusBottom > 0 ) generateCap( false );
  19946. }
  19947. // build geometry
  19948. this.setIndex( indices );
  19949. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  19950. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  19951. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  19952. function generateTorso() {
  19953. const normal = new Vector3();
  19954. const vertex = new Vector3();
  19955. let groupCount = 0;
  19956. // this will be used to calculate the normal
  19957. const slope = ( radiusBottom - radiusTop ) / height;
  19958. // generate vertices, normals and uvs
  19959. for ( let y = 0; y <= heightSegments; y ++ ) {
  19960. const indexRow = [];
  19961. const v = y / heightSegments;
  19962. // calculate the radius of the current row
  19963. const radius = v * ( radiusBottom - radiusTop ) + radiusTop;
  19964. for ( let x = 0; x <= radialSegments; x ++ ) {
  19965. const u = x / radialSegments;
  19966. const theta = u * thetaLength + thetaStart;
  19967. const sinTheta = Math.sin( theta );
  19968. const cosTheta = Math.cos( theta );
  19969. // vertex
  19970. vertex.x = radius * sinTheta;
  19971. vertex.y = - v * height + halfHeight;
  19972. vertex.z = radius * cosTheta;
  19973. vertices.push( vertex.x, vertex.y, vertex.z );
  19974. // normal
  19975. normal.set( sinTheta, slope, cosTheta ).normalize();
  19976. normals.push( normal.x, normal.y, normal.z );
  19977. // uv
  19978. uvs.push( u, 1 - v );
  19979. // save index of vertex in respective row
  19980. indexRow.push( index ++ );
  19981. }
  19982. // now save vertices of the row in our index array
  19983. indexArray.push( indexRow );
  19984. }
  19985. // generate indices
  19986. for ( let x = 0; x < radialSegments; x ++ ) {
  19987. for ( let y = 0; y < heightSegments; y ++ ) {
  19988. // we use the index array to access the correct indices
  19989. const a = indexArray[ y ][ x ];
  19990. const b = indexArray[ y + 1 ][ x ];
  19991. const c = indexArray[ y + 1 ][ x + 1 ];
  19992. const d = indexArray[ y ][ x + 1 ];
  19993. // faces
  19994. indices.push( a, b, d );
  19995. indices.push( b, c, d );
  19996. // update group counter
  19997. groupCount += 6;
  19998. }
  19999. }
  20000. // add a group to the geometry. this will ensure multi material support
  20001. scope.addGroup( groupStart, groupCount, 0 );
  20002. // calculate new start value for groups
  20003. groupStart += groupCount;
  20004. }
  20005. function generateCap( top ) {
  20006. // save the index of the first center vertex
  20007. const centerIndexStart = index;
  20008. const uv = new Vector2();
  20009. const vertex = new Vector3();
  20010. let groupCount = 0;
  20011. const radius = ( top === true ) ? radiusTop : radiusBottom;
  20012. const sign = ( top === true ) ? 1 : - 1;
  20013. // first we generate the center vertex data of the cap.
  20014. // because the geometry needs one set of uvs per face,
  20015. // we must generate a center vertex per face/segment
  20016. for ( let x = 1; x <= radialSegments; x ++ ) {
  20017. // vertex
  20018. vertices.push( 0, halfHeight * sign, 0 );
  20019. // normal
  20020. normals.push( 0, sign, 0 );
  20021. // uv
  20022. uvs.push( 0.5, 0.5 );
  20023. // increase index
  20024. index ++;
  20025. }
  20026. // save the index of the last center vertex
  20027. const centerIndexEnd = index;
  20028. // now we generate the surrounding vertices, normals and uvs
  20029. for ( let x = 0; x <= radialSegments; x ++ ) {
  20030. const u = x / radialSegments;
  20031. const theta = u * thetaLength + thetaStart;
  20032. const cosTheta = Math.cos( theta );
  20033. const sinTheta = Math.sin( theta );
  20034. // vertex
  20035. vertex.x = radius * sinTheta;
  20036. vertex.y = halfHeight * sign;
  20037. vertex.z = radius * cosTheta;
  20038. vertices.push( vertex.x, vertex.y, vertex.z );
  20039. // normal
  20040. normals.push( 0, sign, 0 );
  20041. // uv
  20042. uv.x = ( cosTheta * 0.5 ) + 0.5;
  20043. uv.y = ( sinTheta * 0.5 * sign ) + 0.5;
  20044. uvs.push( uv.x, uv.y );
  20045. // increase index
  20046. index ++;
  20047. }
  20048. // generate indices
  20049. for ( let x = 0; x < radialSegments; x ++ ) {
  20050. const c = centerIndexStart + x;
  20051. const i = centerIndexEnd + x;
  20052. if ( top === true ) {
  20053. // face top
  20054. indices.push( i, i + 1, c );
  20055. } else {
  20056. // face bottom
  20057. indices.push( i + 1, i, c );
  20058. }
  20059. groupCount += 3;
  20060. }
  20061. // add a group to the geometry. this will ensure multi material support
  20062. scope.addGroup( groupStart, groupCount, top === true ? 1 : 2 );
  20063. // calculate new start value for groups
  20064. groupStart += groupCount;
  20065. }
  20066. }
  20067. static fromJSON( data ) {
  20068. return new CylinderGeometry( data.radiusTop, data.radiusBottom, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength );
  20069. }
  20070. }
  20071. class ConeGeometry extends CylinderGeometry {
  20072. constructor( radius = 1, height = 1, radialSegments = 32, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  20073. super( 0, radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength );
  20074. this.type = 'ConeGeometry';
  20075. this.parameters = {
  20076. radius: radius,
  20077. height: height,
  20078. radialSegments: radialSegments,
  20079. heightSegments: heightSegments,
  20080. openEnded: openEnded,
  20081. thetaStart: thetaStart,
  20082. thetaLength: thetaLength
  20083. };
  20084. }
  20085. static fromJSON( data ) {
  20086. return new ConeGeometry( data.radius, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength );
  20087. }
  20088. }
  20089. class PolyhedronGeometry extends BufferGeometry {
  20090. constructor( vertices = [], indices = [], radius = 1, detail = 0 ) {
  20091. super();
  20092. this.type = 'PolyhedronGeometry';
  20093. this.parameters = {
  20094. vertices: vertices,
  20095. indices: indices,
  20096. radius: radius,
  20097. detail: detail
  20098. };
  20099. // default buffer data
  20100. const vertexBuffer = [];
  20101. const uvBuffer = [];
  20102. // the subdivision creates the vertex buffer data
  20103. subdivide( detail );
  20104. // all vertices should lie on a conceptual sphere with a given radius
  20105. applyRadius( radius );
  20106. // finally, create the uv data
  20107. generateUVs();
  20108. // build non-indexed geometry
  20109. this.setAttribute( 'position', new Float32BufferAttribute( vertexBuffer, 3 ) );
  20110. this.setAttribute( 'normal', new Float32BufferAttribute( vertexBuffer.slice(), 3 ) );
  20111. this.setAttribute( 'uv', new Float32BufferAttribute( uvBuffer, 2 ) );
  20112. if ( detail === 0 ) {
  20113. this.computeVertexNormals(); // flat normals
  20114. } else {
  20115. this.normalizeNormals(); // smooth normals
  20116. }
  20117. // helper functions
  20118. function subdivide( detail ) {
  20119. const a = new Vector3();
  20120. const b = new Vector3();
  20121. const c = new Vector3();
  20122. // iterate over all faces and apply a subdivision with the given detail value
  20123. for ( let i = 0; i < indices.length; i += 3 ) {
  20124. // get the vertices of the face
  20125. getVertexByIndex( indices[ i + 0 ], a );
  20126. getVertexByIndex( indices[ i + 1 ], b );
  20127. getVertexByIndex( indices[ i + 2 ], c );
  20128. // perform subdivision
  20129. subdivideFace( a, b, c, detail );
  20130. }
  20131. }
  20132. function subdivideFace( a, b, c, detail ) {
  20133. const cols = detail + 1;
  20134. // we use this multidimensional array as a data structure for creating the subdivision
  20135. const v = [];
  20136. // construct all of the vertices for this subdivision
  20137. for ( let i = 0; i <= cols; i ++ ) {
  20138. v[ i ] = [];
  20139. const aj = a.clone().lerp( c, i / cols );
  20140. const bj = b.clone().lerp( c, i / cols );
  20141. const rows = cols - i;
  20142. for ( let j = 0; j <= rows; j ++ ) {
  20143. if ( j === 0 && i === cols ) {
  20144. v[ i ][ j ] = aj;
  20145. } else {
  20146. v[ i ][ j ] = aj.clone().lerp( bj, j / rows );
  20147. }
  20148. }
  20149. }
  20150. // construct all of the faces
  20151. for ( let i = 0; i < cols; i ++ ) {
  20152. for ( let j = 0; j < 2 * ( cols - i ) - 1; j ++ ) {
  20153. const k = Math.floor( j / 2 );
  20154. if ( j % 2 === 0 ) {
  20155. pushVertex( v[ i ][ k + 1 ] );
  20156. pushVertex( v[ i + 1 ][ k ] );
  20157. pushVertex( v[ i ][ k ] );
  20158. } else {
  20159. pushVertex( v[ i ][ k + 1 ] );
  20160. pushVertex( v[ i + 1 ][ k + 1 ] );
  20161. pushVertex( v[ i + 1 ][ k ] );
  20162. }
  20163. }
  20164. }
  20165. }
  20166. function applyRadius( radius ) {
  20167. const vertex = new Vector3();
  20168. // iterate over the entire buffer and apply the radius to each vertex
  20169. for ( let i = 0; i < vertexBuffer.length; i += 3 ) {
  20170. vertex.x = vertexBuffer[ i + 0 ];
  20171. vertex.y = vertexBuffer[ i + 1 ];
  20172. vertex.z = vertexBuffer[ i + 2 ];
  20173. vertex.normalize().multiplyScalar( radius );
  20174. vertexBuffer[ i + 0 ] = vertex.x;
  20175. vertexBuffer[ i + 1 ] = vertex.y;
  20176. vertexBuffer[ i + 2 ] = vertex.z;
  20177. }
  20178. }
  20179. function generateUVs() {
  20180. const vertex = new Vector3();
  20181. for ( let i = 0; i < vertexBuffer.length; i += 3 ) {
  20182. vertex.x = vertexBuffer[ i + 0 ];
  20183. vertex.y = vertexBuffer[ i + 1 ];
  20184. vertex.z = vertexBuffer[ i + 2 ];
  20185. const u = azimuth( vertex ) / 2 / Math.PI + 0.5;
  20186. const v = inclination( vertex ) / Math.PI + 0.5;
  20187. uvBuffer.push( u, 1 - v );
  20188. }
  20189. correctUVs();
  20190. correctSeam();
  20191. }
  20192. function correctSeam() {
  20193. // handle case when face straddles the seam, see #3269
  20194. for ( let i = 0; i < uvBuffer.length; i += 6 ) {
  20195. // uv data of a single face
  20196. const x0 = uvBuffer[ i + 0 ];
  20197. const x1 = uvBuffer[ i + 2 ];
  20198. const x2 = uvBuffer[ i + 4 ];
  20199. const max = Math.max( x0, x1, x2 );
  20200. const min = Math.min( x0, x1, x2 );
  20201. // 0.9 is somewhat arbitrary
  20202. if ( max > 0.9 && min < 0.1 ) {
  20203. if ( x0 < 0.2 ) uvBuffer[ i + 0 ] += 1;
  20204. if ( x1 < 0.2 ) uvBuffer[ i + 2 ] += 1;
  20205. if ( x2 < 0.2 ) uvBuffer[ i + 4 ] += 1;
  20206. }
  20207. }
  20208. }
  20209. function pushVertex( vertex ) {
  20210. vertexBuffer.push( vertex.x, vertex.y, vertex.z );
  20211. }
  20212. function getVertexByIndex( index, vertex ) {
  20213. const stride = index * 3;
  20214. vertex.x = vertices[ stride + 0 ];
  20215. vertex.y = vertices[ stride + 1 ];
  20216. vertex.z = vertices[ stride + 2 ];
  20217. }
  20218. function correctUVs() {
  20219. const a = new Vector3();
  20220. const b = new Vector3();
  20221. const c = new Vector3();
  20222. const centroid = new Vector3();
  20223. const uvA = new Vector2();
  20224. const uvB = new Vector2();
  20225. const uvC = new Vector2();
  20226. for ( let i = 0, j = 0; i < vertexBuffer.length; i += 9, j += 6 ) {
  20227. a.set( vertexBuffer[ i + 0 ], vertexBuffer[ i + 1 ], vertexBuffer[ i + 2 ] );
  20228. b.set( vertexBuffer[ i + 3 ], vertexBuffer[ i + 4 ], vertexBuffer[ i + 5 ] );
  20229. c.set( vertexBuffer[ i + 6 ], vertexBuffer[ i + 7 ], vertexBuffer[ i + 8 ] );
  20230. uvA.set( uvBuffer[ j + 0 ], uvBuffer[ j + 1 ] );
  20231. uvB.set( uvBuffer[ j + 2 ], uvBuffer[ j + 3 ] );
  20232. uvC.set( uvBuffer[ j + 4 ], uvBuffer[ j + 5 ] );
  20233. centroid.copy( a ).add( b ).add( c ).divideScalar( 3 );
  20234. const azi = azimuth( centroid );
  20235. correctUV( uvA, j + 0, a, azi );
  20236. correctUV( uvB, j + 2, b, azi );
  20237. correctUV( uvC, j + 4, c, azi );
  20238. }
  20239. }
  20240. function correctUV( uv, stride, vector, azimuth ) {
  20241. if ( ( azimuth < 0 ) && ( uv.x === 1 ) ) {
  20242. uvBuffer[ stride ] = uv.x - 1;
  20243. }
  20244. if ( ( vector.x === 0 ) && ( vector.z === 0 ) ) {
  20245. uvBuffer[ stride ] = azimuth / 2 / Math.PI + 0.5;
  20246. }
  20247. }
  20248. // Angle around the Y axis, counter-clockwise when looking from above.
  20249. function azimuth( vector ) {
  20250. return Math.atan2( vector.z, - vector.x );
  20251. }
  20252. // Angle above the XZ plane.
  20253. function inclination( vector ) {
  20254. return Math.atan2( - vector.y, Math.sqrt( ( vector.x * vector.x ) + ( vector.z * vector.z ) ) );
  20255. }
  20256. }
  20257. static fromJSON( data ) {
  20258. return new PolyhedronGeometry( data.vertices, data.indices, data.radius, data.details );
  20259. }
  20260. }
  20261. class DodecahedronGeometry extends PolyhedronGeometry {
  20262. constructor( radius = 1, detail = 0 ) {
  20263. const t = ( 1 + Math.sqrt( 5 ) ) / 2;
  20264. const r = 1 / t;
  20265. const vertices = [
  20266. // (±1, ±1, ±1)
  20267. - 1, - 1, - 1, - 1, - 1, 1,
  20268. - 1, 1, - 1, - 1, 1, 1,
  20269. 1, - 1, - 1, 1, - 1, 1,
  20270. 1, 1, - 1, 1, 1, 1,
  20271. // (0, ±1/φ, ±φ)
  20272. 0, - r, - t, 0, - r, t,
  20273. 0, r, - t, 0, r, t,
  20274. // (±1/φ, ±φ, 0)
  20275. - r, - t, 0, - r, t, 0,
  20276. r, - t, 0, r, t, 0,
  20277. // (±φ, 0, ±1/φ)
  20278. - t, 0, - r, t, 0, - r,
  20279. - t, 0, r, t, 0, r
  20280. ];
  20281. const indices = [
  20282. 3, 11, 7, 3, 7, 15, 3, 15, 13,
  20283. 7, 19, 17, 7, 17, 6, 7, 6, 15,
  20284. 17, 4, 8, 17, 8, 10, 17, 10, 6,
  20285. 8, 0, 16, 8, 16, 2, 8, 2, 10,
  20286. 0, 12, 1, 0, 1, 18, 0, 18, 16,
  20287. 6, 10, 2, 6, 2, 13, 6, 13, 15,
  20288. 2, 16, 18, 2, 18, 3, 2, 3, 13,
  20289. 18, 1, 9, 18, 9, 11, 18, 11, 3,
  20290. 4, 14, 12, 4, 12, 0, 4, 0, 8,
  20291. 11, 9, 5, 11, 5, 19, 11, 19, 7,
  20292. 19, 5, 14, 19, 14, 4, 19, 4, 17,
  20293. 1, 12, 14, 1, 14, 5, 1, 5, 9
  20294. ];
  20295. super( vertices, indices, radius, detail );
  20296. this.type = 'DodecahedronGeometry';
  20297. this.parameters = {
  20298. radius: radius,
  20299. detail: detail
  20300. };
  20301. }
  20302. static fromJSON( data ) {
  20303. return new DodecahedronGeometry( data.radius, data.detail );
  20304. }
  20305. }
  20306. const _v0 = /*@__PURE__*/ new Vector3();
  20307. const _v1$1 = /*@__PURE__*/ new Vector3();
  20308. const _normal = /*@__PURE__*/ new Vector3();
  20309. const _triangle = /*@__PURE__*/ new Triangle();
  20310. class EdgesGeometry extends BufferGeometry {
  20311. constructor( geometry = null, thresholdAngle = 1 ) {
  20312. super();
  20313. this.type = 'EdgesGeometry';
  20314. this.parameters = {
  20315. geometry: geometry,
  20316. thresholdAngle: thresholdAngle
  20317. };
  20318. if ( geometry !== null ) {
  20319. const precisionPoints = 4;
  20320. const precision = Math.pow( 10, precisionPoints );
  20321. const thresholdDot = Math.cos( DEG2RAD * thresholdAngle );
  20322. const indexAttr = geometry.getIndex();
  20323. const positionAttr = geometry.getAttribute( 'position' );
  20324. const indexCount = indexAttr ? indexAttr.count : positionAttr.count;
  20325. const indexArr = [ 0, 0, 0 ];
  20326. const vertKeys = [ 'a', 'b', 'c' ];
  20327. const hashes = new Array( 3 );
  20328. const edgeData = {};
  20329. const vertices = [];
  20330. for ( let i = 0; i < indexCount; i += 3 ) {
  20331. if ( indexAttr ) {
  20332. indexArr[ 0 ] = indexAttr.getX( i );
  20333. indexArr[ 1 ] = indexAttr.getX( i + 1 );
  20334. indexArr[ 2 ] = indexAttr.getX( i + 2 );
  20335. } else {
  20336. indexArr[ 0 ] = i;
  20337. indexArr[ 1 ] = i + 1;
  20338. indexArr[ 2 ] = i + 2;
  20339. }
  20340. const { a, b, c } = _triangle;
  20341. a.fromBufferAttribute( positionAttr, indexArr[ 0 ] );
  20342. b.fromBufferAttribute( positionAttr, indexArr[ 1 ] );
  20343. c.fromBufferAttribute( positionAttr, indexArr[ 2 ] );
  20344. _triangle.getNormal( _normal );
  20345. // create hashes for the edge from the vertices
  20346. hashes[ 0 ] = `${ Math.round( a.x * precision ) },${ Math.round( a.y * precision ) },${ Math.round( a.z * precision ) }`;
  20347. hashes[ 1 ] = `${ Math.round( b.x * precision ) },${ Math.round( b.y * precision ) },${ Math.round( b.z * precision ) }`;
  20348. hashes[ 2 ] = `${ Math.round( c.x * precision ) },${ Math.round( c.y * precision ) },${ Math.round( c.z * precision ) }`;
  20349. // skip degenerate triangles
  20350. if ( hashes[ 0 ] === hashes[ 1 ] || hashes[ 1 ] === hashes[ 2 ] || hashes[ 2 ] === hashes[ 0 ] ) {
  20351. continue;
  20352. }
  20353. // iterate over every edge
  20354. for ( let j = 0; j < 3; j ++ ) {
  20355. // get the first and next vertex making up the edge
  20356. const jNext = ( j + 1 ) % 3;
  20357. const vecHash0 = hashes[ j ];
  20358. const vecHash1 = hashes[ jNext ];
  20359. const v0 = _triangle[ vertKeys[ j ] ];
  20360. const v1 = _triangle[ vertKeys[ jNext ] ];
  20361. const hash = `${ vecHash0 }_${ vecHash1 }`;
  20362. const reverseHash = `${ vecHash1 }_${ vecHash0 }`;
  20363. if ( reverseHash in edgeData && edgeData[ reverseHash ] ) {
  20364. // if we found a sibling edge add it into the vertex array if
  20365. // it meets the angle threshold and delete the edge from the map.
  20366. if ( _normal.dot( edgeData[ reverseHash ].normal ) <= thresholdDot ) {
  20367. vertices.push( v0.x, v0.y, v0.z );
  20368. vertices.push( v1.x, v1.y, v1.z );
  20369. }
  20370. edgeData[ reverseHash ] = null;
  20371. } else if ( ! ( hash in edgeData ) ) {
  20372. // if we've already got an edge here then skip adding a new one
  20373. edgeData[ hash ] = {
  20374. index0: indexArr[ j ],
  20375. index1: indexArr[ jNext ],
  20376. normal: _normal.clone(),
  20377. };
  20378. }
  20379. }
  20380. }
  20381. // iterate over all remaining, unmatched edges and add them to the vertex array
  20382. for ( const key in edgeData ) {
  20383. if ( edgeData[ key ] ) {
  20384. const { index0, index1 } = edgeData[ key ];
  20385. _v0.fromBufferAttribute( positionAttr, index0 );
  20386. _v1$1.fromBufferAttribute( positionAttr, index1 );
  20387. vertices.push( _v0.x, _v0.y, _v0.z );
  20388. vertices.push( _v1$1.x, _v1$1.y, _v1$1.z );
  20389. }
  20390. }
  20391. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  20392. }
  20393. }
  20394. }
  20395. class Shape extends Path {
  20396. constructor( points ) {
  20397. super( points );
  20398. this.uuid = generateUUID();
  20399. this.type = 'Shape';
  20400. this.holes = [];
  20401. }
  20402. getPointsHoles( divisions ) {
  20403. const holesPts = [];
  20404. for ( let i = 0, l = this.holes.length; i < l; i ++ ) {
  20405. holesPts[ i ] = this.holes[ i ].getPoints( divisions );
  20406. }
  20407. return holesPts;
  20408. }
  20409. // get points of shape and holes (keypoints based on segments parameter)
  20410. extractPoints( divisions ) {
  20411. return {
  20412. shape: this.getPoints( divisions ),
  20413. holes: this.getPointsHoles( divisions )
  20414. };
  20415. }
  20416. copy( source ) {
  20417. super.copy( source );
  20418. this.holes = [];
  20419. for ( let i = 0, l = source.holes.length; i < l; i ++ ) {
  20420. const hole = source.holes[ i ];
  20421. this.holes.push( hole.clone() );
  20422. }
  20423. return this;
  20424. }
  20425. toJSON() {
  20426. const data = super.toJSON();
  20427. data.uuid = this.uuid;
  20428. data.holes = [];
  20429. for ( let i = 0, l = this.holes.length; i < l; i ++ ) {
  20430. const hole = this.holes[ i ];
  20431. data.holes.push( hole.toJSON() );
  20432. }
  20433. return data;
  20434. }
  20435. fromJSON( json ) {
  20436. super.fromJSON( json );
  20437. this.uuid = json.uuid;
  20438. this.holes = [];
  20439. for ( let i = 0, l = json.holes.length; i < l; i ++ ) {
  20440. const hole = json.holes[ i ];
  20441. this.holes.push( new Path().fromJSON( hole ) );
  20442. }
  20443. return this;
  20444. }
  20445. }
  20446. /**
  20447. * Port from https://github.com/mapbox/earcut (v2.2.4)
  20448. */
  20449. const Earcut = {
  20450. triangulate: function ( data, holeIndices, dim = 2 ) {
  20451. const hasHoles = holeIndices && holeIndices.length;
  20452. const outerLen = hasHoles ? holeIndices[ 0 ] * dim : data.length;
  20453. let outerNode = linkedList( data, 0, outerLen, dim, true );
  20454. const triangles = [];
  20455. if ( ! outerNode || outerNode.next === outerNode.prev ) return triangles;
  20456. let minX, minY, maxX, maxY, x, y, invSize;
  20457. if ( hasHoles ) outerNode = eliminateHoles( data, holeIndices, outerNode, dim );
  20458. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  20459. if ( data.length > 80 * dim ) {
  20460. minX = maxX = data[ 0 ];
  20461. minY = maxY = data[ 1 ];
  20462. for ( let i = dim; i < outerLen; i += dim ) {
  20463. x = data[ i ];
  20464. y = data[ i + 1 ];
  20465. if ( x < minX ) minX = x;
  20466. if ( y < minY ) minY = y;
  20467. if ( x > maxX ) maxX = x;
  20468. if ( y > maxY ) maxY = y;
  20469. }
  20470. // minX, minY and invSize are later used to transform coords into integers for z-order calculation
  20471. invSize = Math.max( maxX - minX, maxY - minY );
  20472. invSize = invSize !== 0 ? 32767 / invSize : 0;
  20473. }
  20474. earcutLinked( outerNode, triangles, dim, minX, minY, invSize, 0 );
  20475. return triangles;
  20476. }
  20477. };
  20478. // create a circular doubly linked list from polygon points in the specified winding order
  20479. function linkedList( data, start, end, dim, clockwise ) {
  20480. let i, last;
  20481. if ( clockwise === ( signedArea( data, start, end, dim ) > 0 ) ) {
  20482. for ( i = start; i < end; i += dim ) last = insertNode( i, data[ i ], data[ i + 1 ], last );
  20483. } else {
  20484. for ( i = end - dim; i >= start; i -= dim ) last = insertNode( i, data[ i ], data[ i + 1 ], last );
  20485. }
  20486. if ( last && equals( last, last.next ) ) {
  20487. removeNode( last );
  20488. last = last.next;
  20489. }
  20490. return last;
  20491. }
  20492. // eliminate colinear or duplicate points
  20493. function filterPoints( start, end ) {
  20494. if ( ! start ) return start;
  20495. if ( ! end ) end = start;
  20496. let p = start,
  20497. again;
  20498. do {
  20499. again = false;
  20500. if ( ! p.steiner && ( equals( p, p.next ) || area( p.prev, p, p.next ) === 0 ) ) {
  20501. removeNode( p );
  20502. p = end = p.prev;
  20503. if ( p === p.next ) break;
  20504. again = true;
  20505. } else {
  20506. p = p.next;
  20507. }
  20508. } while ( again || p !== end );
  20509. return end;
  20510. }
  20511. // main ear slicing loop which triangulates a polygon (given as a linked list)
  20512. function earcutLinked( ear, triangles, dim, minX, minY, invSize, pass ) {
  20513. if ( ! ear ) return;
  20514. // interlink polygon nodes in z-order
  20515. if ( ! pass && invSize ) indexCurve( ear, minX, minY, invSize );
  20516. let stop = ear,
  20517. prev, next;
  20518. // iterate through ears, slicing them one by one
  20519. while ( ear.prev !== ear.next ) {
  20520. prev = ear.prev;
  20521. next = ear.next;
  20522. if ( invSize ? isEarHashed( ear, minX, minY, invSize ) : isEar( ear ) ) {
  20523. // cut off the triangle
  20524. triangles.push( prev.i / dim | 0 );
  20525. triangles.push( ear.i / dim | 0 );
  20526. triangles.push( next.i / dim | 0 );
  20527. removeNode( ear );
  20528. // skipping the next vertex leads to less sliver triangles
  20529. ear = next.next;
  20530. stop = next.next;
  20531. continue;
  20532. }
  20533. ear = next;
  20534. // if we looped through the whole remaining polygon and can't find any more ears
  20535. if ( ear === stop ) {
  20536. // try filtering points and slicing again
  20537. if ( ! pass ) {
  20538. earcutLinked( filterPoints( ear ), triangles, dim, minX, minY, invSize, 1 );
  20539. // if this didn't work, try curing all small self-intersections locally
  20540. } else if ( pass === 1 ) {
  20541. ear = cureLocalIntersections( filterPoints( ear ), triangles, dim );
  20542. earcutLinked( ear, triangles, dim, minX, minY, invSize, 2 );
  20543. // as a last resort, try splitting the remaining polygon into two
  20544. } else if ( pass === 2 ) {
  20545. splitEarcut( ear, triangles, dim, minX, minY, invSize );
  20546. }
  20547. break;
  20548. }
  20549. }
  20550. }
  20551. // check whether a polygon node forms a valid ear with adjacent nodes
  20552. function isEar( ear ) {
  20553. const a = ear.prev,
  20554. b = ear,
  20555. c = ear.next;
  20556. if ( area( a, b, c ) >= 0 ) return false; // reflex, can't be an ear
  20557. // now make sure we don't have other points inside the potential ear
  20558. const ax = a.x, bx = b.x, cx = c.x, ay = a.y, by = b.y, cy = c.y;
  20559. // triangle bbox; min & max are calculated like this for speed
  20560. const x0 = ax < bx ? ( ax < cx ? ax : cx ) : ( bx < cx ? bx : cx ),
  20561. y0 = ay < by ? ( ay < cy ? ay : cy ) : ( by < cy ? by : cy ),
  20562. x1 = ax > bx ? ( ax > cx ? ax : cx ) : ( bx > cx ? bx : cx ),
  20563. y1 = ay > by ? ( ay > cy ? ay : cy ) : ( by > cy ? by : cy );
  20564. let p = c.next;
  20565. while ( p !== a ) {
  20566. if ( p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 &&
  20567. pointInTriangle( ax, ay, bx, by, cx, cy, p.x, p.y ) &&
  20568. area( p.prev, p, p.next ) >= 0 ) return false;
  20569. p = p.next;
  20570. }
  20571. return true;
  20572. }
  20573. function isEarHashed( ear, minX, minY, invSize ) {
  20574. const a = ear.prev,
  20575. b = ear,
  20576. c = ear.next;
  20577. if ( area( a, b, c ) >= 0 ) return false; // reflex, can't be an ear
  20578. const ax = a.x, bx = b.x, cx = c.x, ay = a.y, by = b.y, cy = c.y;
  20579. // triangle bbox; min & max are calculated like this for speed
  20580. const x0 = ax < bx ? ( ax < cx ? ax : cx ) : ( bx < cx ? bx : cx ),
  20581. y0 = ay < by ? ( ay < cy ? ay : cy ) : ( by < cy ? by : cy ),
  20582. x1 = ax > bx ? ( ax > cx ? ax : cx ) : ( bx > cx ? bx : cx ),
  20583. y1 = ay > by ? ( ay > cy ? ay : cy ) : ( by > cy ? by : cy );
  20584. // z-order range for the current triangle bbox;
  20585. const minZ = zOrder( x0, y0, minX, minY, invSize ),
  20586. maxZ = zOrder( x1, y1, minX, minY, invSize );
  20587. let p = ear.prevZ,
  20588. n = ear.nextZ;
  20589. // look for points inside the triangle in both directions
  20590. while ( p && p.z >= minZ && n && n.z <= maxZ ) {
  20591. if ( p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 && p !== a && p !== c &&
  20592. pointInTriangle( ax, ay, bx, by, cx, cy, p.x, p.y ) && area( p.prev, p, p.next ) >= 0 ) return false;
  20593. p = p.prevZ;
  20594. if ( n.x >= x0 && n.x <= x1 && n.y >= y0 && n.y <= y1 && n !== a && n !== c &&
  20595. pointInTriangle( ax, ay, bx, by, cx, cy, n.x, n.y ) && area( n.prev, n, n.next ) >= 0 ) return false;
  20596. n = n.nextZ;
  20597. }
  20598. // look for remaining points in decreasing z-order
  20599. while ( p && p.z >= minZ ) {
  20600. if ( p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 && p !== a && p !== c &&
  20601. pointInTriangle( ax, ay, bx, by, cx, cy, p.x, p.y ) && area( p.prev, p, p.next ) >= 0 ) return false;
  20602. p = p.prevZ;
  20603. }
  20604. // look for remaining points in increasing z-order
  20605. while ( n && n.z <= maxZ ) {
  20606. if ( n.x >= x0 && n.x <= x1 && n.y >= y0 && n.y <= y1 && n !== a && n !== c &&
  20607. pointInTriangle( ax, ay, bx, by, cx, cy, n.x, n.y ) && area( n.prev, n, n.next ) >= 0 ) return false;
  20608. n = n.nextZ;
  20609. }
  20610. return true;
  20611. }
  20612. // go through all polygon nodes and cure small local self-intersections
  20613. function cureLocalIntersections( start, triangles, dim ) {
  20614. let p = start;
  20615. do {
  20616. const a = p.prev,
  20617. b = p.next.next;
  20618. if ( ! equals( a, b ) && intersects( a, p, p.next, b ) && locallyInside( a, b ) && locallyInside( b, a ) ) {
  20619. triangles.push( a.i / dim | 0 );
  20620. triangles.push( p.i / dim | 0 );
  20621. triangles.push( b.i / dim | 0 );
  20622. // remove two nodes involved
  20623. removeNode( p );
  20624. removeNode( p.next );
  20625. p = start = b;
  20626. }
  20627. p = p.next;
  20628. } while ( p !== start );
  20629. return filterPoints( p );
  20630. }
  20631. // try splitting polygon into two and triangulate them independently
  20632. function splitEarcut( start, triangles, dim, minX, minY, invSize ) {
  20633. // look for a valid diagonal that divides the polygon into two
  20634. let a = start;
  20635. do {
  20636. let b = a.next.next;
  20637. while ( b !== a.prev ) {
  20638. if ( a.i !== b.i && isValidDiagonal( a, b ) ) {
  20639. // split the polygon in two by the diagonal
  20640. let c = splitPolygon( a, b );
  20641. // filter colinear points around the cuts
  20642. a = filterPoints( a, a.next );
  20643. c = filterPoints( c, c.next );
  20644. // run earcut on each half
  20645. earcutLinked( a, triangles, dim, minX, minY, invSize, 0 );
  20646. earcutLinked( c, triangles, dim, minX, minY, invSize, 0 );
  20647. return;
  20648. }
  20649. b = b.next;
  20650. }
  20651. a = a.next;
  20652. } while ( a !== start );
  20653. }
  20654. // link every hole into the outer loop, producing a single-ring polygon without holes
  20655. function eliminateHoles( data, holeIndices, outerNode, dim ) {
  20656. const queue = [];
  20657. let i, len, start, end, list;
  20658. for ( i = 0, len = holeIndices.length; i < len; i ++ ) {
  20659. start = holeIndices[ i ] * dim;
  20660. end = i < len - 1 ? holeIndices[ i + 1 ] * dim : data.length;
  20661. list = linkedList( data, start, end, dim, false );
  20662. if ( list === list.next ) list.steiner = true;
  20663. queue.push( getLeftmost( list ) );
  20664. }
  20665. queue.sort( compareX );
  20666. // process holes from left to right
  20667. for ( i = 0; i < queue.length; i ++ ) {
  20668. outerNode = eliminateHole( queue[ i ], outerNode );
  20669. }
  20670. return outerNode;
  20671. }
  20672. function compareX( a, b ) {
  20673. return a.x - b.x;
  20674. }
  20675. // find a bridge between vertices that connects hole with an outer ring and link it
  20676. function eliminateHole( hole, outerNode ) {
  20677. const bridge = findHoleBridge( hole, outerNode );
  20678. if ( ! bridge ) {
  20679. return outerNode;
  20680. }
  20681. const bridgeReverse = splitPolygon( bridge, hole );
  20682. // filter collinear points around the cuts
  20683. filterPoints( bridgeReverse, bridgeReverse.next );
  20684. return filterPoints( bridge, bridge.next );
  20685. }
  20686. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  20687. function findHoleBridge( hole, outerNode ) {
  20688. let p = outerNode,
  20689. qx = - Infinity,
  20690. m;
  20691. const hx = hole.x, hy = hole.y;
  20692. // find a segment intersected by a ray from the hole's leftmost point to the left;
  20693. // segment's endpoint with lesser x will be potential connection point
  20694. do {
  20695. if ( hy <= p.y && hy >= p.next.y && p.next.y !== p.y ) {
  20696. const x = p.x + ( hy - p.y ) * ( p.next.x - p.x ) / ( p.next.y - p.y );
  20697. if ( x <= hx && x > qx ) {
  20698. qx = x;
  20699. m = p.x < p.next.x ? p : p.next;
  20700. if ( x === hx ) return m; // hole touches outer segment; pick leftmost endpoint
  20701. }
  20702. }
  20703. p = p.next;
  20704. } while ( p !== outerNode );
  20705. if ( ! m ) return null;
  20706. // look for points inside the triangle of hole point, segment intersection and endpoint;
  20707. // if there are no points found, we have a valid connection;
  20708. // otherwise choose the point of the minimum angle with the ray as connection point
  20709. const stop = m,
  20710. mx = m.x,
  20711. my = m.y;
  20712. let tanMin = Infinity, tan;
  20713. p = m;
  20714. do {
  20715. if ( hx >= p.x && p.x >= mx && hx !== p.x &&
  20716. pointInTriangle( hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y ) ) {
  20717. tan = Math.abs( hy - p.y ) / ( hx - p.x ); // tangential
  20718. if ( locallyInside( p, hole ) && ( tan < tanMin || ( tan === tanMin && ( p.x > m.x || ( p.x === m.x && sectorContainsSector( m, p ) ) ) ) ) ) {
  20719. m = p;
  20720. tanMin = tan;
  20721. }
  20722. }
  20723. p = p.next;
  20724. } while ( p !== stop );
  20725. return m;
  20726. }
  20727. // whether sector in vertex m contains sector in vertex p in the same coordinates
  20728. function sectorContainsSector( m, p ) {
  20729. return area( m.prev, m, p.prev ) < 0 && area( p.next, m, m.next ) < 0;
  20730. }
  20731. // interlink polygon nodes in z-order
  20732. function indexCurve( start, minX, minY, invSize ) {
  20733. let p = start;
  20734. do {
  20735. if ( p.z === 0 ) p.z = zOrder( p.x, p.y, minX, minY, invSize );
  20736. p.prevZ = p.prev;
  20737. p.nextZ = p.next;
  20738. p = p.next;
  20739. } while ( p !== start );
  20740. p.prevZ.nextZ = null;
  20741. p.prevZ = null;
  20742. sortLinked( p );
  20743. }
  20744. // Simon Tatham's linked list merge sort algorithm
  20745. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  20746. function sortLinked( list ) {
  20747. let i, p, q, e, tail, numMerges, pSize, qSize,
  20748. inSize = 1;
  20749. do {
  20750. p = list;
  20751. list = null;
  20752. tail = null;
  20753. numMerges = 0;
  20754. while ( p ) {
  20755. numMerges ++;
  20756. q = p;
  20757. pSize = 0;
  20758. for ( i = 0; i < inSize; i ++ ) {
  20759. pSize ++;
  20760. q = q.nextZ;
  20761. if ( ! q ) break;
  20762. }
  20763. qSize = inSize;
  20764. while ( pSize > 0 || ( qSize > 0 && q ) ) {
  20765. if ( pSize !== 0 && ( qSize === 0 || ! q || p.z <= q.z ) ) {
  20766. e = p;
  20767. p = p.nextZ;
  20768. pSize --;
  20769. } else {
  20770. e = q;
  20771. q = q.nextZ;
  20772. qSize --;
  20773. }
  20774. if ( tail ) tail.nextZ = e;
  20775. else list = e;
  20776. e.prevZ = tail;
  20777. tail = e;
  20778. }
  20779. p = q;
  20780. }
  20781. tail.nextZ = null;
  20782. inSize *= 2;
  20783. } while ( numMerges > 1 );
  20784. return list;
  20785. }
  20786. // z-order of a point given coords and inverse of the longer side of data bbox
  20787. function zOrder( x, y, minX, minY, invSize ) {
  20788. // coords are transformed into non-negative 15-bit integer range
  20789. x = ( x - minX ) * invSize | 0;
  20790. y = ( y - minY ) * invSize | 0;
  20791. x = ( x | ( x << 8 ) ) & 0x00FF00FF;
  20792. x = ( x | ( x << 4 ) ) & 0x0F0F0F0F;
  20793. x = ( x | ( x << 2 ) ) & 0x33333333;
  20794. x = ( x | ( x << 1 ) ) & 0x55555555;
  20795. y = ( y | ( y << 8 ) ) & 0x00FF00FF;
  20796. y = ( y | ( y << 4 ) ) & 0x0F0F0F0F;
  20797. y = ( y | ( y << 2 ) ) & 0x33333333;
  20798. y = ( y | ( y << 1 ) ) & 0x55555555;
  20799. return x | ( y << 1 );
  20800. }
  20801. // find the leftmost node of a polygon ring
  20802. function getLeftmost( start ) {
  20803. let p = start,
  20804. leftmost = start;
  20805. do {
  20806. if ( p.x < leftmost.x || ( p.x === leftmost.x && p.y < leftmost.y ) ) leftmost = p;
  20807. p = p.next;
  20808. } while ( p !== start );
  20809. return leftmost;
  20810. }
  20811. // check if a point lies within a convex triangle
  20812. function pointInTriangle( ax, ay, bx, by, cx, cy, px, py ) {
  20813. return ( cx - px ) * ( ay - py ) >= ( ax - px ) * ( cy - py ) &&
  20814. ( ax - px ) * ( by - py ) >= ( bx - px ) * ( ay - py ) &&
  20815. ( bx - px ) * ( cy - py ) >= ( cx - px ) * ( by - py );
  20816. }
  20817. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  20818. function isValidDiagonal( a, b ) {
  20819. return a.next.i !== b.i && a.prev.i !== b.i && ! intersectsPolygon( a, b ) && // dones't intersect other edges
  20820. ( locallyInside( a, b ) && locallyInside( b, a ) && middleInside( a, b ) && // locally visible
  20821. ( area( a.prev, a, b.prev ) || area( a, b.prev, b ) ) || // does not create opposite-facing sectors
  20822. equals( a, b ) && area( a.prev, a, a.next ) > 0 && area( b.prev, b, b.next ) > 0 ); // special zero-length case
  20823. }
  20824. // signed area of a triangle
  20825. function area( p, q, r ) {
  20826. return ( q.y - p.y ) * ( r.x - q.x ) - ( q.x - p.x ) * ( r.y - q.y );
  20827. }
  20828. // check if two points are equal
  20829. function equals( p1, p2 ) {
  20830. return p1.x === p2.x && p1.y === p2.y;
  20831. }
  20832. // check if two segments intersect
  20833. function intersects( p1, q1, p2, q2 ) {
  20834. const o1 = sign( area( p1, q1, p2 ) );
  20835. const o2 = sign( area( p1, q1, q2 ) );
  20836. const o3 = sign( area( p2, q2, p1 ) );
  20837. const o4 = sign( area( p2, q2, q1 ) );
  20838. if ( o1 !== o2 && o3 !== o4 ) return true; // general case
  20839. if ( o1 === 0 && onSegment( p1, p2, q1 ) ) return true; // p1, q1 and p2 are collinear and p2 lies on p1q1
  20840. if ( o2 === 0 && onSegment( p1, q2, q1 ) ) return true; // p1, q1 and q2 are collinear and q2 lies on p1q1
  20841. if ( o3 === 0 && onSegment( p2, p1, q2 ) ) return true; // p2, q2 and p1 are collinear and p1 lies on p2q2
  20842. if ( o4 === 0 && onSegment( p2, q1, q2 ) ) return true; // p2, q2 and q1 are collinear and q1 lies on p2q2
  20843. return false;
  20844. }
  20845. // for collinear points p, q, r, check if point q lies on segment pr
  20846. function onSegment( p, q, r ) {
  20847. 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 );
  20848. }
  20849. function sign( num ) {
  20850. return num > 0 ? 1 : num < 0 ? - 1 : 0;
  20851. }
  20852. // check if a polygon diagonal intersects any polygon segments
  20853. function intersectsPolygon( a, b ) {
  20854. let p = a;
  20855. do {
  20856. if ( p.i !== a.i && p.next.i !== a.i && p.i !== b.i && p.next.i !== b.i &&
  20857. intersects( p, p.next, a, b ) ) return true;
  20858. p = p.next;
  20859. } while ( p !== a );
  20860. return false;
  20861. }
  20862. // check if a polygon diagonal is locally inside the polygon
  20863. function locallyInside( a, b ) {
  20864. return area( a.prev, a, a.next ) < 0 ?
  20865. area( a, b, a.next ) >= 0 && area( a, a.prev, b ) >= 0 :
  20866. area( a, b, a.prev ) < 0 || area( a, a.next, b ) < 0;
  20867. }
  20868. // check if the middle point of a polygon diagonal is inside the polygon
  20869. function middleInside( a, b ) {
  20870. let p = a,
  20871. inside = false;
  20872. const px = ( a.x + b.x ) / 2,
  20873. py = ( a.y + b.y ) / 2;
  20874. do {
  20875. if ( ( ( p.y > py ) !== ( p.next.y > py ) ) && p.next.y !== p.y &&
  20876. ( px < ( p.next.x - p.x ) * ( py - p.y ) / ( p.next.y - p.y ) + p.x ) )
  20877. inside = ! inside;
  20878. p = p.next;
  20879. } while ( p !== a );
  20880. return inside;
  20881. }
  20882. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  20883. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  20884. function splitPolygon( a, b ) {
  20885. const a2 = new Node( a.i, a.x, a.y ),
  20886. b2 = new Node( b.i, b.x, b.y ),
  20887. an = a.next,
  20888. bp = b.prev;
  20889. a.next = b;
  20890. b.prev = a;
  20891. a2.next = an;
  20892. an.prev = a2;
  20893. b2.next = a2;
  20894. a2.prev = b2;
  20895. bp.next = b2;
  20896. b2.prev = bp;
  20897. return b2;
  20898. }
  20899. // create a node and optionally link it with previous one (in a circular doubly linked list)
  20900. function insertNode( i, x, y, last ) {
  20901. const p = new Node( i, x, y );
  20902. if ( ! last ) {
  20903. p.prev = p;
  20904. p.next = p;
  20905. } else {
  20906. p.next = last.next;
  20907. p.prev = last;
  20908. last.next.prev = p;
  20909. last.next = p;
  20910. }
  20911. return p;
  20912. }
  20913. function removeNode( p ) {
  20914. p.next.prev = p.prev;
  20915. p.prev.next = p.next;
  20916. if ( p.prevZ ) p.prevZ.nextZ = p.nextZ;
  20917. if ( p.nextZ ) p.nextZ.prevZ = p.prevZ;
  20918. }
  20919. function Node( i, x, y ) {
  20920. // vertex index in coordinates array
  20921. this.i = i;
  20922. // vertex coordinates
  20923. this.x = x;
  20924. this.y = y;
  20925. // previous and next vertex nodes in a polygon ring
  20926. this.prev = null;
  20927. this.next = null;
  20928. // z-order curve value
  20929. this.z = 0;
  20930. // previous and next nodes in z-order
  20931. this.prevZ = null;
  20932. this.nextZ = null;
  20933. // indicates whether this is a steiner point
  20934. this.steiner = false;
  20935. }
  20936. function signedArea( data, start, end, dim ) {
  20937. let sum = 0;
  20938. for ( let i = start, j = end - dim; i < end; i += dim ) {
  20939. sum += ( data[ j ] - data[ i ] ) * ( data[ i + 1 ] + data[ j + 1 ] );
  20940. j = i;
  20941. }
  20942. return sum;
  20943. }
  20944. class ShapeUtils {
  20945. // calculate area of the contour polygon
  20946. static area( contour ) {
  20947. const n = contour.length;
  20948. let a = 0.0;
  20949. for ( let p = n - 1, q = 0; q < n; p = q ++ ) {
  20950. a += contour[ p ].x * contour[ q ].y - contour[ q ].x * contour[ p ].y;
  20951. }
  20952. return a * 0.5;
  20953. }
  20954. static isClockWise( pts ) {
  20955. return ShapeUtils.area( pts ) < 0;
  20956. }
  20957. static triangulateShape( contour, holes ) {
  20958. const vertices = []; // flat array of vertices like [ x0,y0, x1,y1, x2,y2, ... ]
  20959. const holeIndices = []; // array of hole indices
  20960. const faces = []; // final array of vertex indices like [ [ a,b,d ], [ b,c,d ] ]
  20961. removeDupEndPts( contour );
  20962. addContour( vertices, contour );
  20963. //
  20964. let holeIndex = contour.length;
  20965. holes.forEach( removeDupEndPts );
  20966. for ( let i = 0; i < holes.length; i ++ ) {
  20967. holeIndices.push( holeIndex );
  20968. holeIndex += holes[ i ].length;
  20969. addContour( vertices, holes[ i ] );
  20970. }
  20971. //
  20972. const triangles = Earcut.triangulate( vertices, holeIndices );
  20973. //
  20974. for ( let i = 0; i < triangles.length; i += 3 ) {
  20975. faces.push( triangles.slice( i, i + 3 ) );
  20976. }
  20977. return faces;
  20978. }
  20979. }
  20980. function removeDupEndPts( points ) {
  20981. const l = points.length;
  20982. if ( l > 2 && points[ l - 1 ].equals( points[ 0 ] ) ) {
  20983. points.pop();
  20984. }
  20985. }
  20986. function addContour( vertices, contour ) {
  20987. for ( let i = 0; i < contour.length; i ++ ) {
  20988. vertices.push( contour[ i ].x );
  20989. vertices.push( contour[ i ].y );
  20990. }
  20991. }
  20992. /**
  20993. * Creates extruded geometry from a path shape.
  20994. *
  20995. * parameters = {
  20996. *
  20997. * curveSegments: <int>, // number of points on the curves
  20998. * steps: <int>, // number of points for z-side extrusions / used for subdividing segments of extrude spline too
  20999. * depth: <float>, // Depth to extrude the shape
  21000. *
  21001. * bevelEnabled: <bool>, // turn on bevel
  21002. * bevelThickness: <float>, // how deep into the original shape bevel goes
  21003. * bevelSize: <float>, // how far from shape outline (including bevelOffset) is bevel
  21004. * bevelOffset: <float>, // how far from shape outline does bevel start
  21005. * bevelSegments: <int>, // number of bevel layers
  21006. *
  21007. * extrudePath: <THREE.Curve> // curve to extrude shape along
  21008. *
  21009. * UVGenerator: <Object> // object that provides UV generator functions
  21010. *
  21011. * }
  21012. */
  21013. class ExtrudeGeometry extends BufferGeometry {
  21014. 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 = {} ) {
  21015. super();
  21016. this.type = 'ExtrudeGeometry';
  21017. this.parameters = {
  21018. shapes: shapes,
  21019. options: options
  21020. };
  21021. shapes = Array.isArray( shapes ) ? shapes : [ shapes ];
  21022. const scope = this;
  21023. const verticesArray = [];
  21024. const uvArray = [];
  21025. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  21026. const shape = shapes[ i ];
  21027. addShape( shape );
  21028. }
  21029. // build geometry
  21030. this.setAttribute( 'position', new Float32BufferAttribute( verticesArray, 3 ) );
  21031. this.setAttribute( 'uv', new Float32BufferAttribute( uvArray, 2 ) );
  21032. this.computeVertexNormals();
  21033. // functions
  21034. function addShape( shape ) {
  21035. const placeholder = [];
  21036. // options
  21037. const curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  21038. const steps = options.steps !== undefined ? options.steps : 1;
  21039. const depth = options.depth !== undefined ? options.depth : 1;
  21040. let bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true;
  21041. let bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 0.2;
  21042. let bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 0.1;
  21043. let bevelOffset = options.bevelOffset !== undefined ? options.bevelOffset : 0;
  21044. let bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3;
  21045. const extrudePath = options.extrudePath;
  21046. const uvgen = options.UVGenerator !== undefined ? options.UVGenerator : WorldUVGenerator;
  21047. //
  21048. let extrudePts, extrudeByPath = false;
  21049. let splineTube, binormal, normal, position2;
  21050. if ( extrudePath ) {
  21051. extrudePts = extrudePath.getSpacedPoints( steps );
  21052. extrudeByPath = true;
  21053. bevelEnabled = false; // bevels not supported for path extrusion
  21054. // SETUP TNB variables
  21055. // TODO1 - have a .isClosed in spline?
  21056. splineTube = extrudePath.computeFrenetFrames( steps, false );
  21057. // console.log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length);
  21058. binormal = new Vector3();
  21059. normal = new Vector3();
  21060. position2 = new Vector3();
  21061. }
  21062. // Safeguards if bevels are not enabled
  21063. if ( ! bevelEnabled ) {
  21064. bevelSegments = 0;
  21065. bevelThickness = 0;
  21066. bevelSize = 0;
  21067. bevelOffset = 0;
  21068. }
  21069. // Variables initialization
  21070. const shapePoints = shape.extractPoints( curveSegments );
  21071. let vertices = shapePoints.shape;
  21072. const holes = shapePoints.holes;
  21073. const reverse = ! ShapeUtils.isClockWise( vertices );
  21074. if ( reverse ) {
  21075. vertices = vertices.reverse();
  21076. // Maybe we should also check if holes are in the opposite direction, just to be safe ...
  21077. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  21078. const ahole = holes[ h ];
  21079. if ( ShapeUtils.isClockWise( ahole ) ) {
  21080. holes[ h ] = ahole.reverse();
  21081. }
  21082. }
  21083. }
  21084. const faces = ShapeUtils.triangulateShape( vertices, holes );
  21085. /* Vertices */
  21086. const contour = vertices; // vertices has all points but contour has only points of circumference
  21087. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  21088. const ahole = holes[ h ];
  21089. vertices = vertices.concat( ahole );
  21090. }
  21091. function scalePt2( pt, vec, size ) {
  21092. if ( ! vec ) console.error( 'THREE.ExtrudeGeometry: vec does not exist' );
  21093. return vec.clone().multiplyScalar( size ).add( pt );
  21094. }
  21095. const vlen = vertices.length, flen = faces.length;
  21096. // Find directions for point movement
  21097. function getBevelVec( inPt, inPrev, inNext ) {
  21098. // computes for inPt the corresponding point inPt' on a new contour
  21099. // shifted by 1 unit (length of normalized vector) to the left
  21100. // if we walk along contour clockwise, this new contour is outside the old one
  21101. //
  21102. // inPt' is the intersection of the two lines parallel to the two
  21103. // adjacent edges of inPt at a distance of 1 unit on the left side.
  21104. let v_trans_x, v_trans_y, shrink_by; // resulting translation vector for inPt
  21105. // good reading for geometry algorithms (here: line-line intersection)
  21106. // http://geomalgorithms.com/a05-_intersect-1.html
  21107. const v_prev_x = inPt.x - inPrev.x,
  21108. v_prev_y = inPt.y - inPrev.y;
  21109. const v_next_x = inNext.x - inPt.x,
  21110. v_next_y = inNext.y - inPt.y;
  21111. const v_prev_lensq = ( v_prev_x * v_prev_x + v_prev_y * v_prev_y );
  21112. // check for collinear edges
  21113. const collinear0 = ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  21114. if ( Math.abs( collinear0 ) > Number.EPSILON ) {
  21115. // not collinear
  21116. // length of vectors for normalizing
  21117. const v_prev_len = Math.sqrt( v_prev_lensq );
  21118. const v_next_len = Math.sqrt( v_next_x * v_next_x + v_next_y * v_next_y );
  21119. // shift adjacent points by unit vectors to the left
  21120. const ptPrevShift_x = ( inPrev.x - v_prev_y / v_prev_len );
  21121. const ptPrevShift_y = ( inPrev.y + v_prev_x / v_prev_len );
  21122. const ptNextShift_x = ( inNext.x - v_next_y / v_next_len );
  21123. const ptNextShift_y = ( inNext.y + v_next_x / v_next_len );
  21124. // scaling factor for v_prev to intersection point
  21125. const sf = ( ( ptNextShift_x - ptPrevShift_x ) * v_next_y -
  21126. ( ptNextShift_y - ptPrevShift_y ) * v_next_x ) /
  21127. ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  21128. // vector from inPt to intersection point
  21129. v_trans_x = ( ptPrevShift_x + v_prev_x * sf - inPt.x );
  21130. v_trans_y = ( ptPrevShift_y + v_prev_y * sf - inPt.y );
  21131. // Don't normalize!, otherwise sharp corners become ugly
  21132. // but prevent crazy spikes
  21133. const v_trans_lensq = ( v_trans_x * v_trans_x + v_trans_y * v_trans_y );
  21134. if ( v_trans_lensq <= 2 ) {
  21135. return new Vector2( v_trans_x, v_trans_y );
  21136. } else {
  21137. shrink_by = Math.sqrt( v_trans_lensq / 2 );
  21138. }
  21139. } else {
  21140. // handle special case of collinear edges
  21141. let direction_eq = false; // assumes: opposite
  21142. if ( v_prev_x > Number.EPSILON ) {
  21143. if ( v_next_x > Number.EPSILON ) {
  21144. direction_eq = true;
  21145. }
  21146. } else {
  21147. if ( v_prev_x < - Number.EPSILON ) {
  21148. if ( v_next_x < - Number.EPSILON ) {
  21149. direction_eq = true;
  21150. }
  21151. } else {
  21152. if ( Math.sign( v_prev_y ) === Math.sign( v_next_y ) ) {
  21153. direction_eq = true;
  21154. }
  21155. }
  21156. }
  21157. if ( direction_eq ) {
  21158. // console.log("Warning: lines are a straight sequence");
  21159. v_trans_x = - v_prev_y;
  21160. v_trans_y = v_prev_x;
  21161. shrink_by = Math.sqrt( v_prev_lensq );
  21162. } else {
  21163. // console.log("Warning: lines are a straight spike");
  21164. v_trans_x = v_prev_x;
  21165. v_trans_y = v_prev_y;
  21166. shrink_by = Math.sqrt( v_prev_lensq / 2 );
  21167. }
  21168. }
  21169. return new Vector2( v_trans_x / shrink_by, v_trans_y / shrink_by );
  21170. }
  21171. const contourMovements = [];
  21172. for ( let i = 0, il = contour.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  21173. if ( j === il ) j = 0;
  21174. if ( k === il ) k = 0;
  21175. // (j)---(i)---(k)
  21176. // console.log('i,j,k', i, j , k)
  21177. contourMovements[ i ] = getBevelVec( contour[ i ], contour[ j ], contour[ k ] );
  21178. }
  21179. const holesMovements = [];
  21180. let oneHoleMovements, verticesMovements = contourMovements.concat();
  21181. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  21182. const ahole = holes[ h ];
  21183. oneHoleMovements = [];
  21184. for ( let i = 0, il = ahole.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  21185. if ( j === il ) j = 0;
  21186. if ( k === il ) k = 0;
  21187. // (j)---(i)---(k)
  21188. oneHoleMovements[ i ] = getBevelVec( ahole[ i ], ahole[ j ], ahole[ k ] );
  21189. }
  21190. holesMovements.push( oneHoleMovements );
  21191. verticesMovements = verticesMovements.concat( oneHoleMovements );
  21192. }
  21193. // Loop bevelSegments, 1 for the front, 1 for the back
  21194. for ( let b = 0; b < bevelSegments; b ++ ) {
  21195. //for ( b = bevelSegments; b > 0; b -- ) {
  21196. const t = b / bevelSegments;
  21197. const z = bevelThickness * Math.cos( t * Math.PI / 2 );
  21198. const bs = bevelSize * Math.sin( t * Math.PI / 2 ) + bevelOffset;
  21199. // contract shape
  21200. for ( let i = 0, il = contour.length; i < il; i ++ ) {
  21201. const vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  21202. v( vert.x, vert.y, - z );
  21203. }
  21204. // expand holes
  21205. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  21206. const ahole = holes[ h ];
  21207. oneHoleMovements = holesMovements[ h ];
  21208. for ( let i = 0, il = ahole.length; i < il; i ++ ) {
  21209. const vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  21210. v( vert.x, vert.y, - z );
  21211. }
  21212. }
  21213. }
  21214. const bs = bevelSize + bevelOffset;
  21215. // Back facing vertices
  21216. for ( let i = 0; i < vlen; i ++ ) {
  21217. const vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  21218. if ( ! extrudeByPath ) {
  21219. v( vert.x, vert.y, 0 );
  21220. } else {
  21221. // v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x );
  21222. normal.copy( splineTube.normals[ 0 ] ).multiplyScalar( vert.x );
  21223. binormal.copy( splineTube.binormals[ 0 ] ).multiplyScalar( vert.y );
  21224. position2.copy( extrudePts[ 0 ] ).add( normal ).add( binormal );
  21225. v( position2.x, position2.y, position2.z );
  21226. }
  21227. }
  21228. // Add stepped vertices...
  21229. // Including front facing vertices
  21230. for ( let s = 1; s <= steps; s ++ ) {
  21231. for ( let i = 0; i < vlen; i ++ ) {
  21232. const vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  21233. if ( ! extrudeByPath ) {
  21234. v( vert.x, vert.y, depth / steps * s );
  21235. } else {
  21236. // v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x );
  21237. normal.copy( splineTube.normals[ s ] ).multiplyScalar( vert.x );
  21238. binormal.copy( splineTube.binormals[ s ] ).multiplyScalar( vert.y );
  21239. position2.copy( extrudePts[ s ] ).add( normal ).add( binormal );
  21240. v( position2.x, position2.y, position2.z );
  21241. }
  21242. }
  21243. }
  21244. // Add bevel segments planes
  21245. //for ( b = 1; b <= bevelSegments; b ++ ) {
  21246. for ( let b = bevelSegments - 1; b >= 0; b -- ) {
  21247. const t = b / bevelSegments;
  21248. const z = bevelThickness * Math.cos( t * Math.PI / 2 );
  21249. const bs = bevelSize * Math.sin( t * Math.PI / 2 ) + bevelOffset;
  21250. // contract shape
  21251. for ( let i = 0, il = contour.length; i < il; i ++ ) {
  21252. const vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  21253. v( vert.x, vert.y, depth + z );
  21254. }
  21255. // expand holes
  21256. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  21257. const ahole = holes[ h ];
  21258. oneHoleMovements = holesMovements[ h ];
  21259. for ( let i = 0, il = ahole.length; i < il; i ++ ) {
  21260. const vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  21261. if ( ! extrudeByPath ) {
  21262. v( vert.x, vert.y, depth + z );
  21263. } else {
  21264. v( vert.x, vert.y + extrudePts[ steps - 1 ].y, extrudePts[ steps - 1 ].x + z );
  21265. }
  21266. }
  21267. }
  21268. }
  21269. /* Faces */
  21270. // Top and bottom faces
  21271. buildLidFaces();
  21272. // Sides faces
  21273. buildSideFaces();
  21274. ///// Internal functions
  21275. function buildLidFaces() {
  21276. const start = verticesArray.length / 3;
  21277. if ( bevelEnabled ) {
  21278. let layer = 0; // steps + 1
  21279. let offset = vlen * layer;
  21280. // Bottom faces
  21281. for ( let i = 0; i < flen; i ++ ) {
  21282. const face = faces[ i ];
  21283. f3( face[ 2 ] + offset, face[ 1 ] + offset, face[ 0 ] + offset );
  21284. }
  21285. layer = steps + bevelSegments * 2;
  21286. offset = vlen * layer;
  21287. // Top faces
  21288. for ( let i = 0; i < flen; i ++ ) {
  21289. const face = faces[ i ];
  21290. f3( face[ 0 ] + offset, face[ 1 ] + offset, face[ 2 ] + offset );
  21291. }
  21292. } else {
  21293. // Bottom faces
  21294. for ( let i = 0; i < flen; i ++ ) {
  21295. const face = faces[ i ];
  21296. f3( face[ 2 ], face[ 1 ], face[ 0 ] );
  21297. }
  21298. // Top faces
  21299. for ( let i = 0; i < flen; i ++ ) {
  21300. const face = faces[ i ];
  21301. f3( face[ 0 ] + vlen * steps, face[ 1 ] + vlen * steps, face[ 2 ] + vlen * steps );
  21302. }
  21303. }
  21304. scope.addGroup( start, verticesArray.length / 3 - start, 0 );
  21305. }
  21306. // Create faces for the z-sides of the shape
  21307. function buildSideFaces() {
  21308. const start = verticesArray.length / 3;
  21309. let layeroffset = 0;
  21310. sidewalls( contour, layeroffset );
  21311. layeroffset += contour.length;
  21312. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  21313. const ahole = holes[ h ];
  21314. sidewalls( ahole, layeroffset );
  21315. //, true
  21316. layeroffset += ahole.length;
  21317. }
  21318. scope.addGroup( start, verticesArray.length / 3 - start, 1 );
  21319. }
  21320. function sidewalls( contour, layeroffset ) {
  21321. let i = contour.length;
  21322. while ( -- i >= 0 ) {
  21323. const j = i;
  21324. let k = i - 1;
  21325. if ( k < 0 ) k = contour.length - 1;
  21326. //console.log('b', i,j, i-1, k,vertices.length);
  21327. for ( let s = 0, sl = ( steps + bevelSegments * 2 ); s < sl; s ++ ) {
  21328. const slen1 = vlen * s;
  21329. const slen2 = vlen * ( s + 1 );
  21330. const a = layeroffset + j + slen1,
  21331. b = layeroffset + k + slen1,
  21332. c = layeroffset + k + slen2,
  21333. d = layeroffset + j + slen2;
  21334. f4( a, b, c, d );
  21335. }
  21336. }
  21337. }
  21338. function v( x, y, z ) {
  21339. placeholder.push( x );
  21340. placeholder.push( y );
  21341. placeholder.push( z );
  21342. }
  21343. function f3( a, b, c ) {
  21344. addVertex( a );
  21345. addVertex( b );
  21346. addVertex( c );
  21347. const nextIndex = verticesArray.length / 3;
  21348. const uvs = uvgen.generateTopUV( scope, verticesArray, nextIndex - 3, nextIndex - 2, nextIndex - 1 );
  21349. addUV( uvs[ 0 ] );
  21350. addUV( uvs[ 1 ] );
  21351. addUV( uvs[ 2 ] );
  21352. }
  21353. function f4( a, b, c, d ) {
  21354. addVertex( a );
  21355. addVertex( b );
  21356. addVertex( d );
  21357. addVertex( b );
  21358. addVertex( c );
  21359. addVertex( d );
  21360. const nextIndex = verticesArray.length / 3;
  21361. const uvs = uvgen.generateSideWallUV( scope, verticesArray, nextIndex - 6, nextIndex - 3, nextIndex - 2, nextIndex - 1 );
  21362. addUV( uvs[ 0 ] );
  21363. addUV( uvs[ 1 ] );
  21364. addUV( uvs[ 3 ] );
  21365. addUV( uvs[ 1 ] );
  21366. addUV( uvs[ 2 ] );
  21367. addUV( uvs[ 3 ] );
  21368. }
  21369. function addVertex( index ) {
  21370. verticesArray.push( placeholder[ index * 3 + 0 ] );
  21371. verticesArray.push( placeholder[ index * 3 + 1 ] );
  21372. verticesArray.push( placeholder[ index * 3 + 2 ] );
  21373. }
  21374. function addUV( vector2 ) {
  21375. uvArray.push( vector2.x );
  21376. uvArray.push( vector2.y );
  21377. }
  21378. }
  21379. }
  21380. toJSON() {
  21381. const data = super.toJSON();
  21382. const shapes = this.parameters.shapes;
  21383. const options = this.parameters.options;
  21384. return toJSON$1( shapes, options, data );
  21385. }
  21386. static fromJSON( data, shapes ) {
  21387. const geometryShapes = [];
  21388. for ( let j = 0, jl = data.shapes.length; j < jl; j ++ ) {
  21389. const shape = shapes[ data.shapes[ j ] ];
  21390. geometryShapes.push( shape );
  21391. }
  21392. const extrudePath = data.options.extrudePath;
  21393. if ( extrudePath !== undefined ) {
  21394. data.options.extrudePath = new Curves[ extrudePath.type ]().fromJSON( extrudePath );
  21395. }
  21396. return new ExtrudeGeometry( geometryShapes, data.options );
  21397. }
  21398. }
  21399. const WorldUVGenerator = {
  21400. generateTopUV: function ( geometry, vertices, indexA, indexB, indexC ) {
  21401. const a_x = vertices[ indexA * 3 ];
  21402. const a_y = vertices[ indexA * 3 + 1 ];
  21403. const b_x = vertices[ indexB * 3 ];
  21404. const b_y = vertices[ indexB * 3 + 1 ];
  21405. const c_x = vertices[ indexC * 3 ];
  21406. const c_y = vertices[ indexC * 3 + 1 ];
  21407. return [
  21408. new Vector2( a_x, a_y ),
  21409. new Vector2( b_x, b_y ),
  21410. new Vector2( c_x, c_y )
  21411. ];
  21412. },
  21413. generateSideWallUV: function ( geometry, vertices, indexA, indexB, indexC, indexD ) {
  21414. const a_x = vertices[ indexA * 3 ];
  21415. const a_y = vertices[ indexA * 3 + 1 ];
  21416. const a_z = vertices[ indexA * 3 + 2 ];
  21417. const b_x = vertices[ indexB * 3 ];
  21418. const b_y = vertices[ indexB * 3 + 1 ];
  21419. const b_z = vertices[ indexB * 3 + 2 ];
  21420. const c_x = vertices[ indexC * 3 ];
  21421. const c_y = vertices[ indexC * 3 + 1 ];
  21422. const c_z = vertices[ indexC * 3 + 2 ];
  21423. const d_x = vertices[ indexD * 3 ];
  21424. const d_y = vertices[ indexD * 3 + 1 ];
  21425. const d_z = vertices[ indexD * 3 + 2 ];
  21426. if ( Math.abs( a_y - b_y ) < Math.abs( a_x - b_x ) ) {
  21427. return [
  21428. new Vector2( a_x, 1 - a_z ),
  21429. new Vector2( b_x, 1 - b_z ),
  21430. new Vector2( c_x, 1 - c_z ),
  21431. new Vector2( d_x, 1 - d_z )
  21432. ];
  21433. } else {
  21434. return [
  21435. new Vector2( a_y, 1 - a_z ),
  21436. new Vector2( b_y, 1 - b_z ),
  21437. new Vector2( c_y, 1 - c_z ),
  21438. new Vector2( d_y, 1 - d_z )
  21439. ];
  21440. }
  21441. }
  21442. };
  21443. function toJSON$1( shapes, options, data ) {
  21444. data.shapes = [];
  21445. if ( Array.isArray( shapes ) ) {
  21446. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  21447. const shape = shapes[ i ];
  21448. data.shapes.push( shape.uuid );
  21449. }
  21450. } else {
  21451. data.shapes.push( shapes.uuid );
  21452. }
  21453. data.options = Object.assign( {}, options );
  21454. if ( options.extrudePath !== undefined ) data.options.extrudePath = options.extrudePath.toJSON();
  21455. return data;
  21456. }
  21457. class IcosahedronGeometry extends PolyhedronGeometry {
  21458. constructor( radius = 1, detail = 0 ) {
  21459. const t = ( 1 + Math.sqrt( 5 ) ) / 2;
  21460. const vertices = [
  21461. - 1, t, 0, 1, t, 0, - 1, - t, 0, 1, - t, 0,
  21462. 0, - 1, t, 0, 1, t, 0, - 1, - t, 0, 1, - t,
  21463. t, 0, - 1, t, 0, 1, - t, 0, - 1, - t, 0, 1
  21464. ];
  21465. const indices = [
  21466. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 0, 10, 11,
  21467. 1, 5, 9, 5, 11, 4, 11, 10, 2, 10, 7, 6, 7, 1, 8,
  21468. 3, 9, 4, 3, 4, 2, 3, 2, 6, 3, 6, 8, 3, 8, 9,
  21469. 4, 9, 5, 2, 4, 11, 6, 2, 10, 8, 6, 7, 9, 8, 1
  21470. ];
  21471. super( vertices, indices, radius, detail );
  21472. this.type = 'IcosahedronGeometry';
  21473. this.parameters = {
  21474. radius: radius,
  21475. detail: detail
  21476. };
  21477. }
  21478. static fromJSON( data ) {
  21479. return new IcosahedronGeometry( data.radius, data.detail );
  21480. }
  21481. }
  21482. class OctahedronGeometry extends PolyhedronGeometry {
  21483. constructor( radius = 1, detail = 0 ) {
  21484. const vertices = [
  21485. 1, 0, 0, - 1, 0, 0, 0, 1, 0,
  21486. 0, - 1, 0, 0, 0, 1, 0, 0, - 1
  21487. ];
  21488. const indices = [
  21489. 0, 2, 4, 0, 4, 3, 0, 3, 5,
  21490. 0, 5, 2, 1, 2, 5, 1, 5, 3,
  21491. 1, 3, 4, 1, 4, 2
  21492. ];
  21493. super( vertices, indices, radius, detail );
  21494. this.type = 'OctahedronGeometry';
  21495. this.parameters = {
  21496. radius: radius,
  21497. detail: detail
  21498. };
  21499. }
  21500. static fromJSON( data ) {
  21501. return new OctahedronGeometry( data.radius, data.detail );
  21502. }
  21503. }
  21504. class RingGeometry extends BufferGeometry {
  21505. constructor( innerRadius = 0.5, outerRadius = 1, thetaSegments = 32, phiSegments = 1, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  21506. super();
  21507. this.type = 'RingGeometry';
  21508. this.parameters = {
  21509. innerRadius: innerRadius,
  21510. outerRadius: outerRadius,
  21511. thetaSegments: thetaSegments,
  21512. phiSegments: phiSegments,
  21513. thetaStart: thetaStart,
  21514. thetaLength: thetaLength
  21515. };
  21516. thetaSegments = Math.max( 3, thetaSegments );
  21517. phiSegments = Math.max( 1, phiSegments );
  21518. // buffers
  21519. const indices = [];
  21520. const vertices = [];
  21521. const normals = [];
  21522. const uvs = [];
  21523. // some helper variables
  21524. let radius = innerRadius;
  21525. const radiusStep = ( ( outerRadius - innerRadius ) / phiSegments );
  21526. const vertex = new Vector3();
  21527. const uv = new Vector2();
  21528. // generate vertices, normals and uvs
  21529. for ( let j = 0; j <= phiSegments; j ++ ) {
  21530. for ( let i = 0; i <= thetaSegments; i ++ ) {
  21531. // values are generate from the inside of the ring to the outside
  21532. const segment = thetaStart + i / thetaSegments * thetaLength;
  21533. // vertex
  21534. vertex.x = radius * Math.cos( segment );
  21535. vertex.y = radius * Math.sin( segment );
  21536. vertices.push( vertex.x, vertex.y, vertex.z );
  21537. // normal
  21538. normals.push( 0, 0, 1 );
  21539. // uv
  21540. uv.x = ( vertex.x / outerRadius + 1 ) / 2;
  21541. uv.y = ( vertex.y / outerRadius + 1 ) / 2;
  21542. uvs.push( uv.x, uv.y );
  21543. }
  21544. // increase the radius for next row of vertices
  21545. radius += radiusStep;
  21546. }
  21547. // indices
  21548. for ( let j = 0; j < phiSegments; j ++ ) {
  21549. const thetaSegmentLevel = j * ( thetaSegments + 1 );
  21550. for ( let i = 0; i < thetaSegments; i ++ ) {
  21551. const segment = i + thetaSegmentLevel;
  21552. const a = segment;
  21553. const b = segment + thetaSegments + 1;
  21554. const c = segment + thetaSegments + 2;
  21555. const d = segment + 1;
  21556. // faces
  21557. indices.push( a, b, d );
  21558. indices.push( b, c, d );
  21559. }
  21560. }
  21561. // build geometry
  21562. this.setIndex( indices );
  21563. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  21564. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  21565. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  21566. }
  21567. static fromJSON( data ) {
  21568. return new RingGeometry( data.innerRadius, data.outerRadius, data.thetaSegments, data.phiSegments, data.thetaStart, data.thetaLength );
  21569. }
  21570. }
  21571. class ShapeGeometry extends BufferGeometry {
  21572. constructor( shapes = new Shape( [ new Vector2( 0, 0.5 ), new Vector2( - 0.5, - 0.5 ), new Vector2( 0.5, - 0.5 ) ] ), curveSegments = 12 ) {
  21573. super();
  21574. this.type = 'ShapeGeometry';
  21575. this.parameters = {
  21576. shapes: shapes,
  21577. curveSegments: curveSegments
  21578. };
  21579. // buffers
  21580. const indices = [];
  21581. const vertices = [];
  21582. const normals = [];
  21583. const uvs = [];
  21584. // helper variables
  21585. let groupStart = 0;
  21586. let groupCount = 0;
  21587. // allow single and array values for "shapes" parameter
  21588. if ( Array.isArray( shapes ) === false ) {
  21589. addShape( shapes );
  21590. } else {
  21591. for ( let i = 0; i < shapes.length; i ++ ) {
  21592. addShape( shapes[ i ] );
  21593. this.addGroup( groupStart, groupCount, i ); // enables MultiMaterial support
  21594. groupStart += groupCount;
  21595. groupCount = 0;
  21596. }
  21597. }
  21598. // build geometry
  21599. this.setIndex( indices );
  21600. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  21601. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  21602. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  21603. // helper functions
  21604. function addShape( shape ) {
  21605. const indexOffset = vertices.length / 3;
  21606. const points = shape.extractPoints( curveSegments );
  21607. let shapeVertices = points.shape;
  21608. const shapeHoles = points.holes;
  21609. // check direction of vertices
  21610. if ( ShapeUtils.isClockWise( shapeVertices ) === false ) {
  21611. shapeVertices = shapeVertices.reverse();
  21612. }
  21613. for ( let i = 0, l = shapeHoles.length; i < l; i ++ ) {
  21614. const shapeHole = shapeHoles[ i ];
  21615. if ( ShapeUtils.isClockWise( shapeHole ) === true ) {
  21616. shapeHoles[ i ] = shapeHole.reverse();
  21617. }
  21618. }
  21619. const faces = ShapeUtils.triangulateShape( shapeVertices, shapeHoles );
  21620. // join vertices of inner and outer paths to a single array
  21621. for ( let i = 0, l = shapeHoles.length; i < l; i ++ ) {
  21622. const shapeHole = shapeHoles[ i ];
  21623. shapeVertices = shapeVertices.concat( shapeHole );
  21624. }
  21625. // vertices, normals, uvs
  21626. for ( let i = 0, l = shapeVertices.length; i < l; i ++ ) {
  21627. const vertex = shapeVertices[ i ];
  21628. vertices.push( vertex.x, vertex.y, 0 );
  21629. normals.push( 0, 0, 1 );
  21630. uvs.push( vertex.x, vertex.y ); // world uvs
  21631. }
  21632. // indices
  21633. for ( let i = 0, l = faces.length; i < l; i ++ ) {
  21634. const face = faces[ i ];
  21635. const a = face[ 0 ] + indexOffset;
  21636. const b = face[ 1 ] + indexOffset;
  21637. const c = face[ 2 ] + indexOffset;
  21638. indices.push( a, b, c );
  21639. groupCount += 3;
  21640. }
  21641. }
  21642. }
  21643. toJSON() {
  21644. const data = super.toJSON();
  21645. const shapes = this.parameters.shapes;
  21646. return toJSON( shapes, data );
  21647. }
  21648. static fromJSON( data, shapes ) {
  21649. const geometryShapes = [];
  21650. for ( let j = 0, jl = data.shapes.length; j < jl; j ++ ) {
  21651. const shape = shapes[ data.shapes[ j ] ];
  21652. geometryShapes.push( shape );
  21653. }
  21654. return new ShapeGeometry( geometryShapes, data.curveSegments );
  21655. }
  21656. }
  21657. function toJSON( shapes, data ) {
  21658. data.shapes = [];
  21659. if ( Array.isArray( shapes ) ) {
  21660. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  21661. const shape = shapes[ i ];
  21662. data.shapes.push( shape.uuid );
  21663. }
  21664. } else {
  21665. data.shapes.push( shapes.uuid );
  21666. }
  21667. return data;
  21668. }
  21669. class SphereGeometry extends BufferGeometry {
  21670. constructor( radius = 1, widthSegments = 32, heightSegments = 16, phiStart = 0, phiLength = Math.PI * 2, thetaStart = 0, thetaLength = Math.PI ) {
  21671. super();
  21672. this.type = 'SphereGeometry';
  21673. this.parameters = {
  21674. radius: radius,
  21675. widthSegments: widthSegments,
  21676. heightSegments: heightSegments,
  21677. phiStart: phiStart,
  21678. phiLength: phiLength,
  21679. thetaStart: thetaStart,
  21680. thetaLength: thetaLength
  21681. };
  21682. widthSegments = Math.max( 3, Math.floor( widthSegments ) );
  21683. heightSegments = Math.max( 2, Math.floor( heightSegments ) );
  21684. const thetaEnd = Math.min( thetaStart + thetaLength, Math.PI );
  21685. let index = 0;
  21686. const grid = [];
  21687. const vertex = new Vector3();
  21688. const normal = new Vector3();
  21689. // buffers
  21690. const indices = [];
  21691. const vertices = [];
  21692. const normals = [];
  21693. const uvs = [];
  21694. // generate vertices, normals and uvs
  21695. for ( let iy = 0; iy <= heightSegments; iy ++ ) {
  21696. const verticesRow = [];
  21697. const v = iy / heightSegments;
  21698. // special case for the poles
  21699. let uOffset = 0;
  21700. if ( iy == 0 && thetaStart == 0 ) {
  21701. uOffset = 0.5 / widthSegments;
  21702. } else if ( iy == heightSegments && thetaEnd == Math.PI ) {
  21703. uOffset = - 0.5 / widthSegments;
  21704. }
  21705. for ( let ix = 0; ix <= widthSegments; ix ++ ) {
  21706. const u = ix / widthSegments;
  21707. // vertex
  21708. vertex.x = - radius * Math.cos( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  21709. vertex.y = radius * Math.cos( thetaStart + v * thetaLength );
  21710. vertex.z = radius * Math.sin( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  21711. vertices.push( vertex.x, vertex.y, vertex.z );
  21712. // normal
  21713. normal.copy( vertex ).normalize();
  21714. normals.push( normal.x, normal.y, normal.z );
  21715. // uv
  21716. uvs.push( u + uOffset, 1 - v );
  21717. verticesRow.push( index ++ );
  21718. }
  21719. grid.push( verticesRow );
  21720. }
  21721. // indices
  21722. for ( let iy = 0; iy < heightSegments; iy ++ ) {
  21723. for ( let ix = 0; ix < widthSegments; ix ++ ) {
  21724. const a = grid[ iy ][ ix + 1 ];
  21725. const b = grid[ iy ][ ix ];
  21726. const c = grid[ iy + 1 ][ ix ];
  21727. const d = grid[ iy + 1 ][ ix + 1 ];
  21728. if ( iy !== 0 || thetaStart > 0 ) indices.push( a, b, d );
  21729. if ( iy !== heightSegments - 1 || thetaEnd < Math.PI ) indices.push( b, c, d );
  21730. }
  21731. }
  21732. // build geometry
  21733. this.setIndex( indices );
  21734. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  21735. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  21736. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  21737. }
  21738. static fromJSON( data ) {
  21739. return new SphereGeometry( data.radius, data.widthSegments, data.heightSegments, data.phiStart, data.phiLength, data.thetaStart, data.thetaLength );
  21740. }
  21741. }
  21742. class TetrahedronGeometry extends PolyhedronGeometry {
  21743. constructor( radius = 1, detail = 0 ) {
  21744. const vertices = [
  21745. 1, 1, 1, - 1, - 1, 1, - 1, 1, - 1, 1, - 1, - 1
  21746. ];
  21747. const indices = [
  21748. 2, 1, 0, 0, 3, 2, 1, 3, 0, 2, 3, 1
  21749. ];
  21750. super( vertices, indices, radius, detail );
  21751. this.type = 'TetrahedronGeometry';
  21752. this.parameters = {
  21753. radius: radius,
  21754. detail: detail
  21755. };
  21756. }
  21757. static fromJSON( data ) {
  21758. return new TetrahedronGeometry( data.radius, data.detail );
  21759. }
  21760. }
  21761. class TorusGeometry extends BufferGeometry {
  21762. constructor( radius = 1, tube = 0.4, radialSegments = 12, tubularSegments = 48, arc = Math.PI * 2 ) {
  21763. super();
  21764. this.type = 'TorusGeometry';
  21765. this.parameters = {
  21766. radius: radius,
  21767. tube: tube,
  21768. radialSegments: radialSegments,
  21769. tubularSegments: tubularSegments,
  21770. arc: arc
  21771. };
  21772. radialSegments = Math.floor( radialSegments );
  21773. tubularSegments = Math.floor( tubularSegments );
  21774. // buffers
  21775. const indices = [];
  21776. const vertices = [];
  21777. const normals = [];
  21778. const uvs = [];
  21779. // helper variables
  21780. const center = new Vector3();
  21781. const vertex = new Vector3();
  21782. const normal = new Vector3();
  21783. // generate vertices, normals and uvs
  21784. for ( let j = 0; j <= radialSegments; j ++ ) {
  21785. for ( let i = 0; i <= tubularSegments; i ++ ) {
  21786. const u = i / tubularSegments * arc;
  21787. const v = j / radialSegments * Math.PI * 2;
  21788. // vertex
  21789. vertex.x = ( radius + tube * Math.cos( v ) ) * Math.cos( u );
  21790. vertex.y = ( radius + tube * Math.cos( v ) ) * Math.sin( u );
  21791. vertex.z = tube * Math.sin( v );
  21792. vertices.push( vertex.x, vertex.y, vertex.z );
  21793. // normal
  21794. center.x = radius * Math.cos( u );
  21795. center.y = radius * Math.sin( u );
  21796. normal.subVectors( vertex, center ).normalize();
  21797. normals.push( normal.x, normal.y, normal.z );
  21798. // uv
  21799. uvs.push( i / tubularSegments );
  21800. uvs.push( j / radialSegments );
  21801. }
  21802. }
  21803. // generate indices
  21804. for ( let j = 1; j <= radialSegments; j ++ ) {
  21805. for ( let i = 1; i <= tubularSegments; i ++ ) {
  21806. // indices
  21807. const a = ( tubularSegments + 1 ) * j + i - 1;
  21808. const b = ( tubularSegments + 1 ) * ( j - 1 ) + i - 1;
  21809. const c = ( tubularSegments + 1 ) * ( j - 1 ) + i;
  21810. const d = ( tubularSegments + 1 ) * j + i;
  21811. // faces
  21812. indices.push( a, b, d );
  21813. indices.push( b, c, d );
  21814. }
  21815. }
  21816. // build geometry
  21817. this.setIndex( indices );
  21818. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  21819. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  21820. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  21821. }
  21822. static fromJSON( data ) {
  21823. return new TorusGeometry( data.radius, data.tube, data.radialSegments, data.tubularSegments, data.arc );
  21824. }
  21825. }
  21826. class TorusKnotGeometry extends BufferGeometry {
  21827. constructor( radius = 1, tube = 0.4, tubularSegments = 64, radialSegments = 8, p = 2, q = 3 ) {
  21828. super();
  21829. this.type = 'TorusKnotGeometry';
  21830. this.parameters = {
  21831. radius: radius,
  21832. tube: tube,
  21833. tubularSegments: tubularSegments,
  21834. radialSegments: radialSegments,
  21835. p: p,
  21836. q: q
  21837. };
  21838. tubularSegments = Math.floor( tubularSegments );
  21839. radialSegments = Math.floor( radialSegments );
  21840. // buffers
  21841. const indices = [];
  21842. const vertices = [];
  21843. const normals = [];
  21844. const uvs = [];
  21845. // helper variables
  21846. const vertex = new Vector3();
  21847. const normal = new Vector3();
  21848. const P1 = new Vector3();
  21849. const P2 = new Vector3();
  21850. const B = new Vector3();
  21851. const T = new Vector3();
  21852. const N = new Vector3();
  21853. // generate vertices, normals and uvs
  21854. for ( let i = 0; i <= tubularSegments; ++ i ) {
  21855. // the radian "u" is used to calculate the position on the torus curve of the current tubular segment
  21856. const u = i / tubularSegments * p * Math.PI * 2;
  21857. // now we calculate two points. P1 is our current position on the curve, P2 is a little farther ahead.
  21858. // these points are used to create a special "coordinate space", which is necessary to calculate the correct vertex positions
  21859. calculatePositionOnCurve( u, p, q, radius, P1 );
  21860. calculatePositionOnCurve( u + 0.01, p, q, radius, P2 );
  21861. // calculate orthonormal basis
  21862. T.subVectors( P2, P1 );
  21863. N.addVectors( P2, P1 );
  21864. B.crossVectors( T, N );
  21865. N.crossVectors( B, T );
  21866. // normalize B, N. T can be ignored, we don't use it
  21867. B.normalize();
  21868. N.normalize();
  21869. for ( let j = 0; j <= radialSegments; ++ j ) {
  21870. // now calculate the vertices. they are nothing more than an extrusion of the torus curve.
  21871. // because we extrude a shape in the xy-plane, there is no need to calculate a z-value.
  21872. const v = j / radialSegments * Math.PI * 2;
  21873. const cx = - tube * Math.cos( v );
  21874. const cy = tube * Math.sin( v );
  21875. // now calculate the final vertex position.
  21876. // first we orient the extrusion with our basis vectors, then we add it to the current position on the curve
  21877. vertex.x = P1.x + ( cx * N.x + cy * B.x );
  21878. vertex.y = P1.y + ( cx * N.y + cy * B.y );
  21879. vertex.z = P1.z + ( cx * N.z + cy * B.z );
  21880. vertices.push( vertex.x, vertex.y, vertex.z );
  21881. // normal (P1 is always the center/origin of the extrusion, thus we can use it to calculate the normal)
  21882. normal.subVectors( vertex, P1 ).normalize();
  21883. normals.push( normal.x, normal.y, normal.z );
  21884. // uv
  21885. uvs.push( i / tubularSegments );
  21886. uvs.push( j / radialSegments );
  21887. }
  21888. }
  21889. // generate indices
  21890. for ( let j = 1; j <= tubularSegments; j ++ ) {
  21891. for ( let i = 1; i <= radialSegments; i ++ ) {
  21892. // indices
  21893. const a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 );
  21894. const b = ( radialSegments + 1 ) * j + ( i - 1 );
  21895. const c = ( radialSegments + 1 ) * j + i;
  21896. const d = ( radialSegments + 1 ) * ( j - 1 ) + i;
  21897. // faces
  21898. indices.push( a, b, d );
  21899. indices.push( b, c, d );
  21900. }
  21901. }
  21902. // build geometry
  21903. this.setIndex( indices );
  21904. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  21905. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  21906. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  21907. // this function calculates the current position on the torus curve
  21908. function calculatePositionOnCurve( u, p, q, radius, position ) {
  21909. const cu = Math.cos( u );
  21910. const su = Math.sin( u );
  21911. const quOverP = q / p * u;
  21912. const cs = Math.cos( quOverP );
  21913. position.x = radius * ( 2 + cs ) * 0.5 * cu;
  21914. position.y = radius * ( 2 + cs ) * su * 0.5;
  21915. position.z = radius * Math.sin( quOverP ) * 0.5;
  21916. }
  21917. }
  21918. static fromJSON( data ) {
  21919. return new TorusKnotGeometry( data.radius, data.tube, data.tubularSegments, data.radialSegments, data.p, data.q );
  21920. }
  21921. }
  21922. class TubeGeometry extends BufferGeometry {
  21923. 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 ) {
  21924. super();
  21925. this.type = 'TubeGeometry';
  21926. this.parameters = {
  21927. path: path,
  21928. tubularSegments: tubularSegments,
  21929. radius: radius,
  21930. radialSegments: radialSegments,
  21931. closed: closed
  21932. };
  21933. const frames = path.computeFrenetFrames( tubularSegments, closed );
  21934. // expose internals
  21935. this.tangents = frames.tangents;
  21936. this.normals = frames.normals;
  21937. this.binormals = frames.binormals;
  21938. // helper variables
  21939. const vertex = new Vector3();
  21940. const normal = new Vector3();
  21941. const uv = new Vector2();
  21942. let P = new Vector3();
  21943. // buffer
  21944. const vertices = [];
  21945. const normals = [];
  21946. const uvs = [];
  21947. const indices = [];
  21948. // create buffer data
  21949. generateBufferData();
  21950. // build geometry
  21951. this.setIndex( indices );
  21952. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  21953. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  21954. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  21955. // functions
  21956. function generateBufferData() {
  21957. for ( let i = 0; i < tubularSegments; i ++ ) {
  21958. generateSegment( i );
  21959. }
  21960. // if the geometry is not closed, generate the last row of vertices and normals
  21961. // at the regular position on the given path
  21962. //
  21963. // if the geometry is closed, duplicate the first row of vertices and normals (uvs will differ)
  21964. generateSegment( ( closed === false ) ? tubularSegments : 0 );
  21965. // uvs are generated in a separate function.
  21966. // this makes it easy compute correct values for closed geometries
  21967. generateUVs();
  21968. // finally create faces
  21969. generateIndices();
  21970. }
  21971. function generateSegment( i ) {
  21972. // we use getPointAt to sample evenly distributed points from the given path
  21973. P = path.getPointAt( i / tubularSegments, P );
  21974. // retrieve corresponding normal and binormal
  21975. const N = frames.normals[ i ];
  21976. const B = frames.binormals[ i ];
  21977. // generate normals and vertices for the current segment
  21978. for ( let j = 0; j <= radialSegments; j ++ ) {
  21979. const v = j / radialSegments * Math.PI * 2;
  21980. const sin = Math.sin( v );
  21981. const cos = - Math.cos( v );
  21982. // normal
  21983. normal.x = ( cos * N.x + sin * B.x );
  21984. normal.y = ( cos * N.y + sin * B.y );
  21985. normal.z = ( cos * N.z + sin * B.z );
  21986. normal.normalize();
  21987. normals.push( normal.x, normal.y, normal.z );
  21988. // vertex
  21989. vertex.x = P.x + radius * normal.x;
  21990. vertex.y = P.y + radius * normal.y;
  21991. vertex.z = P.z + radius * normal.z;
  21992. vertices.push( vertex.x, vertex.y, vertex.z );
  21993. }
  21994. }
  21995. function generateIndices() {
  21996. for ( let j = 1; j <= tubularSegments; j ++ ) {
  21997. for ( let i = 1; i <= radialSegments; i ++ ) {
  21998. const a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 );
  21999. const b = ( radialSegments + 1 ) * j + ( i - 1 );
  22000. const c = ( radialSegments + 1 ) * j + i;
  22001. const d = ( radialSegments + 1 ) * ( j - 1 ) + i;
  22002. // faces
  22003. indices.push( a, b, d );
  22004. indices.push( b, c, d );
  22005. }
  22006. }
  22007. }
  22008. function generateUVs() {
  22009. for ( let i = 0; i <= tubularSegments; i ++ ) {
  22010. for ( let j = 0; j <= radialSegments; j ++ ) {
  22011. uv.x = i / tubularSegments;
  22012. uv.y = j / radialSegments;
  22013. uvs.push( uv.x, uv.y );
  22014. }
  22015. }
  22016. }
  22017. }
  22018. toJSON() {
  22019. const data = super.toJSON();
  22020. data.path = this.parameters.path.toJSON();
  22021. return data;
  22022. }
  22023. static fromJSON( data ) {
  22024. // This only works for built-in curves (e.g. CatmullRomCurve3).
  22025. // User defined curves or instances of CurvePath will not be deserialized.
  22026. return new TubeGeometry(
  22027. new Curves[ data.path.type ]().fromJSON( data.path ),
  22028. data.tubularSegments,
  22029. data.radius,
  22030. data.radialSegments,
  22031. data.closed
  22032. );
  22033. }
  22034. }
  22035. class WireframeGeometry extends BufferGeometry {
  22036. constructor( geometry = null ) {
  22037. super();
  22038. this.type = 'WireframeGeometry';
  22039. this.parameters = {
  22040. geometry: geometry
  22041. };
  22042. if ( geometry !== null ) {
  22043. // buffer
  22044. const vertices = [];
  22045. const edges = new Set();
  22046. // helper variables
  22047. const start = new Vector3();
  22048. const end = new Vector3();
  22049. if ( geometry.index !== null ) {
  22050. // indexed BufferGeometry
  22051. const position = geometry.attributes.position;
  22052. const indices = geometry.index;
  22053. let groups = geometry.groups;
  22054. if ( groups.length === 0 ) {
  22055. groups = [ { start: 0, count: indices.count, materialIndex: 0 } ];
  22056. }
  22057. // create a data structure that contains all edges without duplicates
  22058. for ( let o = 0, ol = groups.length; o < ol; ++ o ) {
  22059. const group = groups[ o ];
  22060. const groupStart = group.start;
  22061. const groupCount = group.count;
  22062. for ( let i = groupStart, l = ( groupStart + groupCount ); i < l; i += 3 ) {
  22063. for ( let j = 0; j < 3; j ++ ) {
  22064. const index1 = indices.getX( i + j );
  22065. const index2 = indices.getX( i + ( j + 1 ) % 3 );
  22066. start.fromBufferAttribute( position, index1 );
  22067. end.fromBufferAttribute( position, index2 );
  22068. if ( isUniqueEdge( start, end, edges ) === true ) {
  22069. vertices.push( start.x, start.y, start.z );
  22070. vertices.push( end.x, end.y, end.z );
  22071. }
  22072. }
  22073. }
  22074. }
  22075. } else {
  22076. // non-indexed BufferGeometry
  22077. const position = geometry.attributes.position;
  22078. for ( let i = 0, l = ( position.count / 3 ); i < l; i ++ ) {
  22079. for ( let j = 0; j < 3; j ++ ) {
  22080. // three edges per triangle, an edge is represented as (index1, index2)
  22081. // e.g. the first triangle has the following edges: (0,1),(1,2),(2,0)
  22082. const index1 = 3 * i + j;
  22083. const index2 = 3 * i + ( ( j + 1 ) % 3 );
  22084. start.fromBufferAttribute( position, index1 );
  22085. end.fromBufferAttribute( position, index2 );
  22086. if ( isUniqueEdge( start, end, edges ) === true ) {
  22087. vertices.push( start.x, start.y, start.z );
  22088. vertices.push( end.x, end.y, end.z );
  22089. }
  22090. }
  22091. }
  22092. }
  22093. // build geometry
  22094. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  22095. }
  22096. }
  22097. }
  22098. function isUniqueEdge( start, end, edges ) {
  22099. const hash1 = `${start.x},${start.y},${start.z}-${end.x},${end.y},${end.z}`;
  22100. const hash2 = `${end.x},${end.y},${end.z}-${start.x},${start.y},${start.z}`; // coincident edge
  22101. if ( edges.has( hash1 ) === true || edges.has( hash2 ) === true ) {
  22102. return false;
  22103. } else {
  22104. edges.add( hash1 );
  22105. edges.add( hash2 );
  22106. return true;
  22107. }
  22108. }
  22109. var Geometries = /*#__PURE__*/Object.freeze({
  22110. __proto__: null,
  22111. BoxGeometry: BoxGeometry,
  22112. CapsuleGeometry: CapsuleGeometry,
  22113. CircleGeometry: CircleGeometry,
  22114. ConeGeometry: ConeGeometry,
  22115. CylinderGeometry: CylinderGeometry,
  22116. DodecahedronGeometry: DodecahedronGeometry,
  22117. EdgesGeometry: EdgesGeometry,
  22118. ExtrudeGeometry: ExtrudeGeometry,
  22119. IcosahedronGeometry: IcosahedronGeometry,
  22120. LatheGeometry: LatheGeometry,
  22121. OctahedronGeometry: OctahedronGeometry,
  22122. PlaneGeometry: PlaneGeometry,
  22123. PolyhedronGeometry: PolyhedronGeometry,
  22124. RingGeometry: RingGeometry,
  22125. ShapeGeometry: ShapeGeometry,
  22126. SphereGeometry: SphereGeometry,
  22127. TetrahedronGeometry: TetrahedronGeometry,
  22128. TorusGeometry: TorusGeometry,
  22129. TorusKnotGeometry: TorusKnotGeometry,
  22130. TubeGeometry: TubeGeometry,
  22131. WireframeGeometry: WireframeGeometry
  22132. });
  22133. class ShadowMaterial extends Material {
  22134. constructor( parameters ) {
  22135. super();
  22136. this.isShadowMaterial = true;
  22137. this.type = 'ShadowMaterial';
  22138. this.color = new Color( 0x000000 );
  22139. this.transparent = true;
  22140. this.fog = true;
  22141. this.setValues( parameters );
  22142. }
  22143. copy( source ) {
  22144. super.copy( source );
  22145. this.color.copy( source.color );
  22146. this.fog = source.fog;
  22147. return this;
  22148. }
  22149. }
  22150. class RawShaderMaterial extends ShaderMaterial {
  22151. constructor( parameters ) {
  22152. super( parameters );
  22153. this.isRawShaderMaterial = true;
  22154. this.type = 'RawShaderMaterial';
  22155. }
  22156. }
  22157. class MeshStandardMaterial extends Material {
  22158. constructor( parameters ) {
  22159. super();
  22160. this.isMeshStandardMaterial = true;
  22161. this.defines = { 'STANDARD': '' };
  22162. this.type = 'MeshStandardMaterial';
  22163. this.color = new Color( 0xffffff ); // diffuse
  22164. this.roughness = 1.0;
  22165. this.metalness = 0.0;
  22166. this.map = null;
  22167. this.lightMap = null;
  22168. this.lightMapIntensity = 1.0;
  22169. this.aoMap = null;
  22170. this.aoMapIntensity = 1.0;
  22171. this.emissive = new Color( 0x000000 );
  22172. this.emissiveIntensity = 1.0;
  22173. this.emissiveMap = null;
  22174. this.bumpMap = null;
  22175. this.bumpScale = 1;
  22176. this.normalMap = null;
  22177. this.normalMapType = TangentSpaceNormalMap;
  22178. this.normalScale = new Vector2( 1, 1 );
  22179. this.displacementMap = null;
  22180. this.displacementScale = 1;
  22181. this.displacementBias = 0;
  22182. this.roughnessMap = null;
  22183. this.metalnessMap = null;
  22184. this.alphaMap = null;
  22185. this.envMap = null;
  22186. this.envMapIntensity = 1.0;
  22187. this.wireframe = false;
  22188. this.wireframeLinewidth = 1;
  22189. this.wireframeLinecap = 'round';
  22190. this.wireframeLinejoin = 'round';
  22191. this.flatShading = false;
  22192. this.fog = true;
  22193. this.setValues( parameters );
  22194. }
  22195. copy( source ) {
  22196. super.copy( source );
  22197. this.defines = { 'STANDARD': '' };
  22198. this.color.copy( source.color );
  22199. this.roughness = source.roughness;
  22200. this.metalness = source.metalness;
  22201. this.map = source.map;
  22202. this.lightMap = source.lightMap;
  22203. this.lightMapIntensity = source.lightMapIntensity;
  22204. this.aoMap = source.aoMap;
  22205. this.aoMapIntensity = source.aoMapIntensity;
  22206. this.emissive.copy( source.emissive );
  22207. this.emissiveMap = source.emissiveMap;
  22208. this.emissiveIntensity = source.emissiveIntensity;
  22209. this.bumpMap = source.bumpMap;
  22210. this.bumpScale = source.bumpScale;
  22211. this.normalMap = source.normalMap;
  22212. this.normalMapType = source.normalMapType;
  22213. this.normalScale.copy( source.normalScale );
  22214. this.displacementMap = source.displacementMap;
  22215. this.displacementScale = source.displacementScale;
  22216. this.displacementBias = source.displacementBias;
  22217. this.roughnessMap = source.roughnessMap;
  22218. this.metalnessMap = source.metalnessMap;
  22219. this.alphaMap = source.alphaMap;
  22220. this.envMap = source.envMap;
  22221. this.envMapIntensity = source.envMapIntensity;
  22222. this.wireframe = source.wireframe;
  22223. this.wireframeLinewidth = source.wireframeLinewidth;
  22224. this.wireframeLinecap = source.wireframeLinecap;
  22225. this.wireframeLinejoin = source.wireframeLinejoin;
  22226. this.flatShading = source.flatShading;
  22227. this.fog = source.fog;
  22228. return this;
  22229. }
  22230. }
  22231. class MeshPhysicalMaterial extends MeshStandardMaterial {
  22232. constructor( parameters ) {
  22233. super();
  22234. this.isMeshPhysicalMaterial = true;
  22235. this.defines = {
  22236. 'STANDARD': '',
  22237. 'PHYSICAL': ''
  22238. };
  22239. this.type = 'MeshPhysicalMaterial';
  22240. this.clearcoatMap = null;
  22241. this.clearcoatRoughness = 0.0;
  22242. this.clearcoatRoughnessMap = null;
  22243. this.clearcoatNormalScale = new Vector2( 1, 1 );
  22244. this.clearcoatNormalMap = null;
  22245. this.ior = 1.5;
  22246. Object.defineProperty( this, 'reflectivity', {
  22247. get: function () {
  22248. return ( clamp( 2.5 * ( this.ior - 1 ) / ( this.ior + 1 ), 0, 1 ) );
  22249. },
  22250. set: function ( reflectivity ) {
  22251. this.ior = ( 1 + 0.4 * reflectivity ) / ( 1 - 0.4 * reflectivity );
  22252. }
  22253. } );
  22254. this.iridescenceMap = null;
  22255. this.iridescenceIOR = 1.3;
  22256. this.iridescenceThicknessRange = [ 100, 400 ];
  22257. this.iridescenceThicknessMap = null;
  22258. this.sheenColor = new Color( 0x000000 );
  22259. this.sheenColorMap = null;
  22260. this.sheenRoughness = 1.0;
  22261. this.sheenRoughnessMap = null;
  22262. this.transmissionMap = null;
  22263. this.thickness = 0;
  22264. this.thicknessMap = null;
  22265. this.attenuationDistance = Infinity;
  22266. this.attenuationColor = new Color( 1, 1, 1 );
  22267. this.specularIntensity = 1.0;
  22268. this.specularIntensityMap = null;
  22269. this.specularColor = new Color( 1, 1, 1 );
  22270. this.specularColorMap = null;
  22271. this._sheen = 0.0;
  22272. this._clearcoat = 0;
  22273. this._iridescence = 0;
  22274. this._transmission = 0;
  22275. this.setValues( parameters );
  22276. }
  22277. get sheen() {
  22278. return this._sheen;
  22279. }
  22280. set sheen( value ) {
  22281. if ( this._sheen > 0 !== value > 0 ) {
  22282. this.version ++;
  22283. }
  22284. this._sheen = value;
  22285. }
  22286. get clearcoat() {
  22287. return this._clearcoat;
  22288. }
  22289. set clearcoat( value ) {
  22290. if ( this._clearcoat > 0 !== value > 0 ) {
  22291. this.version ++;
  22292. }
  22293. this._clearcoat = value;
  22294. }
  22295. get iridescence() {
  22296. return this._iridescence;
  22297. }
  22298. set iridescence( value ) {
  22299. if ( this._iridescence > 0 !== value > 0 ) {
  22300. this.version ++;
  22301. }
  22302. this._iridescence = value;
  22303. }
  22304. get transmission() {
  22305. return this._transmission;
  22306. }
  22307. set transmission( value ) {
  22308. if ( this._transmission > 0 !== value > 0 ) {
  22309. this.version ++;
  22310. }
  22311. this._transmission = value;
  22312. }
  22313. copy( source ) {
  22314. super.copy( source );
  22315. this.defines = {
  22316. 'STANDARD': '',
  22317. 'PHYSICAL': ''
  22318. };
  22319. this.clearcoat = source.clearcoat;
  22320. this.clearcoatMap = source.clearcoatMap;
  22321. this.clearcoatRoughness = source.clearcoatRoughness;
  22322. this.clearcoatRoughnessMap = source.clearcoatRoughnessMap;
  22323. this.clearcoatNormalMap = source.clearcoatNormalMap;
  22324. this.clearcoatNormalScale.copy( source.clearcoatNormalScale );
  22325. this.ior = source.ior;
  22326. this.iridescence = source.iridescence;
  22327. this.iridescenceMap = source.iridescenceMap;
  22328. this.iridescenceIOR = source.iridescenceIOR;
  22329. this.iridescenceThicknessRange = [ ...source.iridescenceThicknessRange ];
  22330. this.iridescenceThicknessMap = source.iridescenceThicknessMap;
  22331. this.sheen = source.sheen;
  22332. this.sheenColor.copy( source.sheenColor );
  22333. this.sheenColorMap = source.sheenColorMap;
  22334. this.sheenRoughness = source.sheenRoughness;
  22335. this.sheenRoughnessMap = source.sheenRoughnessMap;
  22336. this.transmission = source.transmission;
  22337. this.transmissionMap = source.transmissionMap;
  22338. this.thickness = source.thickness;
  22339. this.thicknessMap = source.thicknessMap;
  22340. this.attenuationDistance = source.attenuationDistance;
  22341. this.attenuationColor.copy( source.attenuationColor );
  22342. this.specularIntensity = source.specularIntensity;
  22343. this.specularIntensityMap = source.specularIntensityMap;
  22344. this.specularColor.copy( source.specularColor );
  22345. this.specularColorMap = source.specularColorMap;
  22346. return this;
  22347. }
  22348. }
  22349. class MeshPhongMaterial extends Material {
  22350. constructor( parameters ) {
  22351. super();
  22352. this.isMeshPhongMaterial = true;
  22353. this.type = 'MeshPhongMaterial';
  22354. this.color = new Color( 0xffffff ); // diffuse
  22355. this.specular = new Color( 0x111111 );
  22356. this.shininess = 30;
  22357. this.map = null;
  22358. this.lightMap = null;
  22359. this.lightMapIntensity = 1.0;
  22360. this.aoMap = null;
  22361. this.aoMapIntensity = 1.0;
  22362. this.emissive = new Color( 0x000000 );
  22363. this.emissiveIntensity = 1.0;
  22364. this.emissiveMap = null;
  22365. this.bumpMap = null;
  22366. this.bumpScale = 1;
  22367. this.normalMap = null;
  22368. this.normalMapType = TangentSpaceNormalMap;
  22369. this.normalScale = new Vector2( 1, 1 );
  22370. this.displacementMap = null;
  22371. this.displacementScale = 1;
  22372. this.displacementBias = 0;
  22373. this.specularMap = null;
  22374. this.alphaMap = null;
  22375. this.envMap = null;
  22376. this.combine = MultiplyOperation;
  22377. this.reflectivity = 1;
  22378. this.refractionRatio = 0.98;
  22379. this.wireframe = false;
  22380. this.wireframeLinewidth = 1;
  22381. this.wireframeLinecap = 'round';
  22382. this.wireframeLinejoin = 'round';
  22383. this.flatShading = false;
  22384. this.fog = true;
  22385. this.setValues( parameters );
  22386. }
  22387. copy( source ) {
  22388. super.copy( source );
  22389. this.color.copy( source.color );
  22390. this.specular.copy( source.specular );
  22391. this.shininess = source.shininess;
  22392. this.map = source.map;
  22393. this.lightMap = source.lightMap;
  22394. this.lightMapIntensity = source.lightMapIntensity;
  22395. this.aoMap = source.aoMap;
  22396. this.aoMapIntensity = source.aoMapIntensity;
  22397. this.emissive.copy( source.emissive );
  22398. this.emissiveMap = source.emissiveMap;
  22399. this.emissiveIntensity = source.emissiveIntensity;
  22400. this.bumpMap = source.bumpMap;
  22401. this.bumpScale = source.bumpScale;
  22402. this.normalMap = source.normalMap;
  22403. this.normalMapType = source.normalMapType;
  22404. this.normalScale.copy( source.normalScale );
  22405. this.displacementMap = source.displacementMap;
  22406. this.displacementScale = source.displacementScale;
  22407. this.displacementBias = source.displacementBias;
  22408. this.specularMap = source.specularMap;
  22409. this.alphaMap = source.alphaMap;
  22410. this.envMap = source.envMap;
  22411. this.combine = source.combine;
  22412. this.reflectivity = source.reflectivity;
  22413. this.refractionRatio = source.refractionRatio;
  22414. this.wireframe = source.wireframe;
  22415. this.wireframeLinewidth = source.wireframeLinewidth;
  22416. this.wireframeLinecap = source.wireframeLinecap;
  22417. this.wireframeLinejoin = source.wireframeLinejoin;
  22418. this.flatShading = source.flatShading;
  22419. this.fog = source.fog;
  22420. return this;
  22421. }
  22422. }
  22423. class MeshToonMaterial extends Material {
  22424. constructor( parameters ) {
  22425. super();
  22426. this.isMeshToonMaterial = true;
  22427. this.defines = { 'TOON': '' };
  22428. this.type = 'MeshToonMaterial';
  22429. this.color = new Color( 0xffffff );
  22430. this.map = null;
  22431. this.gradientMap = null;
  22432. this.lightMap = null;
  22433. this.lightMapIntensity = 1.0;
  22434. this.aoMap = null;
  22435. this.aoMapIntensity = 1.0;
  22436. this.emissive = new Color( 0x000000 );
  22437. this.emissiveIntensity = 1.0;
  22438. this.emissiveMap = null;
  22439. this.bumpMap = null;
  22440. this.bumpScale = 1;
  22441. this.normalMap = null;
  22442. this.normalMapType = TangentSpaceNormalMap;
  22443. this.normalScale = new Vector2( 1, 1 );
  22444. this.displacementMap = null;
  22445. this.displacementScale = 1;
  22446. this.displacementBias = 0;
  22447. this.alphaMap = null;
  22448. this.wireframe = false;
  22449. this.wireframeLinewidth = 1;
  22450. this.wireframeLinecap = 'round';
  22451. this.wireframeLinejoin = 'round';
  22452. this.fog = true;
  22453. this.setValues( parameters );
  22454. }
  22455. copy( source ) {
  22456. super.copy( source );
  22457. this.color.copy( source.color );
  22458. this.map = source.map;
  22459. this.gradientMap = source.gradientMap;
  22460. this.lightMap = source.lightMap;
  22461. this.lightMapIntensity = source.lightMapIntensity;
  22462. this.aoMap = source.aoMap;
  22463. this.aoMapIntensity = source.aoMapIntensity;
  22464. this.emissive.copy( source.emissive );
  22465. this.emissiveMap = source.emissiveMap;
  22466. this.emissiveIntensity = source.emissiveIntensity;
  22467. this.bumpMap = source.bumpMap;
  22468. this.bumpScale = source.bumpScale;
  22469. this.normalMap = source.normalMap;
  22470. this.normalMapType = source.normalMapType;
  22471. this.normalScale.copy( source.normalScale );
  22472. this.displacementMap = source.displacementMap;
  22473. this.displacementScale = source.displacementScale;
  22474. this.displacementBias = source.displacementBias;
  22475. this.alphaMap = source.alphaMap;
  22476. this.wireframe = source.wireframe;
  22477. this.wireframeLinewidth = source.wireframeLinewidth;
  22478. this.wireframeLinecap = source.wireframeLinecap;
  22479. this.wireframeLinejoin = source.wireframeLinejoin;
  22480. this.fog = source.fog;
  22481. return this;
  22482. }
  22483. }
  22484. class MeshNormalMaterial extends Material {
  22485. constructor( parameters ) {
  22486. super();
  22487. this.isMeshNormalMaterial = true;
  22488. this.type = 'MeshNormalMaterial';
  22489. this.bumpMap = null;
  22490. this.bumpScale = 1;
  22491. this.normalMap = null;
  22492. this.normalMapType = TangentSpaceNormalMap;
  22493. this.normalScale = new Vector2( 1, 1 );
  22494. this.displacementMap = null;
  22495. this.displacementScale = 1;
  22496. this.displacementBias = 0;
  22497. this.wireframe = false;
  22498. this.wireframeLinewidth = 1;
  22499. this.flatShading = false;
  22500. this.setValues( parameters );
  22501. }
  22502. copy( source ) {
  22503. super.copy( source );
  22504. this.bumpMap = source.bumpMap;
  22505. this.bumpScale = source.bumpScale;
  22506. this.normalMap = source.normalMap;
  22507. this.normalMapType = source.normalMapType;
  22508. this.normalScale.copy( source.normalScale );
  22509. this.displacementMap = source.displacementMap;
  22510. this.displacementScale = source.displacementScale;
  22511. this.displacementBias = source.displacementBias;
  22512. this.wireframe = source.wireframe;
  22513. this.wireframeLinewidth = source.wireframeLinewidth;
  22514. this.flatShading = source.flatShading;
  22515. return this;
  22516. }
  22517. }
  22518. class MeshLambertMaterial extends Material {
  22519. constructor( parameters ) {
  22520. super();
  22521. this.isMeshLambertMaterial = true;
  22522. this.type = 'MeshLambertMaterial';
  22523. this.color = new Color( 0xffffff ); // diffuse
  22524. this.map = null;
  22525. this.lightMap = null;
  22526. this.lightMapIntensity = 1.0;
  22527. this.aoMap = null;
  22528. this.aoMapIntensity = 1.0;
  22529. this.emissive = new Color( 0x000000 );
  22530. this.emissiveIntensity = 1.0;
  22531. this.emissiveMap = null;
  22532. this.bumpMap = null;
  22533. this.bumpScale = 1;
  22534. this.normalMap = null;
  22535. this.normalMapType = TangentSpaceNormalMap;
  22536. this.normalScale = new Vector2( 1, 1 );
  22537. this.displacementMap = null;
  22538. this.displacementScale = 1;
  22539. this.displacementBias = 0;
  22540. this.specularMap = null;
  22541. this.alphaMap = null;
  22542. this.envMap = null;
  22543. this.combine = MultiplyOperation;
  22544. this.reflectivity = 1;
  22545. this.refractionRatio = 0.98;
  22546. this.wireframe = false;
  22547. this.wireframeLinewidth = 1;
  22548. this.wireframeLinecap = 'round';
  22549. this.wireframeLinejoin = 'round';
  22550. this.flatShading = false;
  22551. this.fog = true;
  22552. this.setValues( parameters );
  22553. }
  22554. copy( source ) {
  22555. super.copy( source );
  22556. this.color.copy( source.color );
  22557. this.map = source.map;
  22558. this.lightMap = source.lightMap;
  22559. this.lightMapIntensity = source.lightMapIntensity;
  22560. this.aoMap = source.aoMap;
  22561. this.aoMapIntensity = source.aoMapIntensity;
  22562. this.emissive.copy( source.emissive );
  22563. this.emissiveMap = source.emissiveMap;
  22564. this.emissiveIntensity = source.emissiveIntensity;
  22565. this.bumpMap = source.bumpMap;
  22566. this.bumpScale = source.bumpScale;
  22567. this.normalMap = source.normalMap;
  22568. this.normalMapType = source.normalMapType;
  22569. this.normalScale.copy( source.normalScale );
  22570. this.displacementMap = source.displacementMap;
  22571. this.displacementScale = source.displacementScale;
  22572. this.displacementBias = source.displacementBias;
  22573. this.specularMap = source.specularMap;
  22574. this.alphaMap = source.alphaMap;
  22575. this.envMap = source.envMap;
  22576. this.combine = source.combine;
  22577. this.reflectivity = source.reflectivity;
  22578. this.refractionRatio = source.refractionRatio;
  22579. this.wireframe = source.wireframe;
  22580. this.wireframeLinewidth = source.wireframeLinewidth;
  22581. this.wireframeLinecap = source.wireframeLinecap;
  22582. this.wireframeLinejoin = source.wireframeLinejoin;
  22583. this.flatShading = source.flatShading;
  22584. this.fog = source.fog;
  22585. return this;
  22586. }
  22587. }
  22588. class MeshMatcapMaterial extends Material {
  22589. constructor( parameters ) {
  22590. super();
  22591. this.isMeshMatcapMaterial = true;
  22592. this.defines = { 'MATCAP': '' };
  22593. this.type = 'MeshMatcapMaterial';
  22594. this.color = new Color( 0xffffff ); // diffuse
  22595. this.matcap = null;
  22596. this.map = null;
  22597. this.bumpMap = null;
  22598. this.bumpScale = 1;
  22599. this.normalMap = null;
  22600. this.normalMapType = TangentSpaceNormalMap;
  22601. this.normalScale = new Vector2( 1, 1 );
  22602. this.displacementMap = null;
  22603. this.displacementScale = 1;
  22604. this.displacementBias = 0;
  22605. this.alphaMap = null;
  22606. this.flatShading = false;
  22607. this.fog = true;
  22608. this.setValues( parameters );
  22609. }
  22610. copy( source ) {
  22611. super.copy( source );
  22612. this.defines = { 'MATCAP': '' };
  22613. this.color.copy( source.color );
  22614. this.matcap = source.matcap;
  22615. this.map = source.map;
  22616. this.bumpMap = source.bumpMap;
  22617. this.bumpScale = source.bumpScale;
  22618. this.normalMap = source.normalMap;
  22619. this.normalMapType = source.normalMapType;
  22620. this.normalScale.copy( source.normalScale );
  22621. this.displacementMap = source.displacementMap;
  22622. this.displacementScale = source.displacementScale;
  22623. this.displacementBias = source.displacementBias;
  22624. this.alphaMap = source.alphaMap;
  22625. this.flatShading = source.flatShading;
  22626. this.fog = source.fog;
  22627. return this;
  22628. }
  22629. }
  22630. class LineDashedMaterial extends LineBasicMaterial {
  22631. constructor( parameters ) {
  22632. super();
  22633. this.isLineDashedMaterial = true;
  22634. this.type = 'LineDashedMaterial';
  22635. this.scale = 1;
  22636. this.dashSize = 3;
  22637. this.gapSize = 1;
  22638. this.setValues( parameters );
  22639. }
  22640. copy( source ) {
  22641. super.copy( source );
  22642. this.scale = source.scale;
  22643. this.dashSize = source.dashSize;
  22644. this.gapSize = source.gapSize;
  22645. return this;
  22646. }
  22647. }
  22648. // same as Array.prototype.slice, but also works on typed arrays
  22649. function arraySlice( array, from, to ) {
  22650. if ( isTypedArray( array ) ) {
  22651. // in ios9 array.subarray(from, undefined) will return empty array
  22652. // but array.subarray(from) or array.subarray(from, len) is correct
  22653. return new array.constructor( array.subarray( from, to !== undefined ? to : array.length ) );
  22654. }
  22655. return array.slice( from, to );
  22656. }
  22657. // converts an array to a specific type
  22658. function convertArray( array, type, forceClone ) {
  22659. if ( ! array || // let 'undefined' and 'null' pass
  22660. ! forceClone && array.constructor === type ) return array;
  22661. if ( typeof type.BYTES_PER_ELEMENT === 'number' ) {
  22662. return new type( array ); // create typed array
  22663. }
  22664. return Array.prototype.slice.call( array ); // create Array
  22665. }
  22666. function isTypedArray( object ) {
  22667. return ArrayBuffer.isView( object ) &&
  22668. ! ( object instanceof DataView );
  22669. }
  22670. // returns an array by which times and values can be sorted
  22671. function getKeyframeOrder( times ) {
  22672. function compareTime( i, j ) {
  22673. return times[ i ] - times[ j ];
  22674. }
  22675. const n = times.length;
  22676. const result = new Array( n );
  22677. for ( let i = 0; i !== n; ++ i ) result[ i ] = i;
  22678. result.sort( compareTime );
  22679. return result;
  22680. }
  22681. // uses the array previously returned by 'getKeyframeOrder' to sort data
  22682. function sortedArray( values, stride, order ) {
  22683. const nValues = values.length;
  22684. const result = new values.constructor( nValues );
  22685. for ( let i = 0, dstOffset = 0; dstOffset !== nValues; ++ i ) {
  22686. const srcOffset = order[ i ] * stride;
  22687. for ( let j = 0; j !== stride; ++ j ) {
  22688. result[ dstOffset ++ ] = values[ srcOffset + j ];
  22689. }
  22690. }
  22691. return result;
  22692. }
  22693. // function for parsing AOS keyframe formats
  22694. function flattenJSON( jsonKeys, times, values, valuePropertyName ) {
  22695. let i = 1, key = jsonKeys[ 0 ];
  22696. while ( key !== undefined && key[ valuePropertyName ] === undefined ) {
  22697. key = jsonKeys[ i ++ ];
  22698. }
  22699. if ( key === undefined ) return; // no data
  22700. let value = key[ valuePropertyName ];
  22701. if ( value === undefined ) return; // no data
  22702. if ( Array.isArray( value ) ) {
  22703. do {
  22704. value = key[ valuePropertyName ];
  22705. if ( value !== undefined ) {
  22706. times.push( key.time );
  22707. values.push.apply( values, value ); // push all elements
  22708. }
  22709. key = jsonKeys[ i ++ ];
  22710. } while ( key !== undefined );
  22711. } else if ( value.toArray !== undefined ) {
  22712. // ...assume THREE.Math-ish
  22713. do {
  22714. value = key[ valuePropertyName ];
  22715. if ( value !== undefined ) {
  22716. times.push( key.time );
  22717. value.toArray( values, values.length );
  22718. }
  22719. key = jsonKeys[ i ++ ];
  22720. } while ( key !== undefined );
  22721. } else {
  22722. // otherwise push as-is
  22723. do {
  22724. value = key[ valuePropertyName ];
  22725. if ( value !== undefined ) {
  22726. times.push( key.time );
  22727. values.push( value );
  22728. }
  22729. key = jsonKeys[ i ++ ];
  22730. } while ( key !== undefined );
  22731. }
  22732. }
  22733. function subclip( sourceClip, name, startFrame, endFrame, fps = 30 ) {
  22734. const clip = sourceClip.clone();
  22735. clip.name = name;
  22736. const tracks = [];
  22737. for ( let i = 0; i < clip.tracks.length; ++ i ) {
  22738. const track = clip.tracks[ i ];
  22739. const valueSize = track.getValueSize();
  22740. const times = [];
  22741. const values = [];
  22742. for ( let j = 0; j < track.times.length; ++ j ) {
  22743. const frame = track.times[ j ] * fps;
  22744. if ( frame < startFrame || frame >= endFrame ) continue;
  22745. times.push( track.times[ j ] );
  22746. for ( let k = 0; k < valueSize; ++ k ) {
  22747. values.push( track.values[ j * valueSize + k ] );
  22748. }
  22749. }
  22750. if ( times.length === 0 ) continue;
  22751. track.times = convertArray( times, track.times.constructor );
  22752. track.values = convertArray( values, track.values.constructor );
  22753. tracks.push( track );
  22754. }
  22755. clip.tracks = tracks;
  22756. // find minimum .times value across all tracks in the trimmed clip
  22757. let minStartTime = Infinity;
  22758. for ( let i = 0; i < clip.tracks.length; ++ i ) {
  22759. if ( minStartTime > clip.tracks[ i ].times[ 0 ] ) {
  22760. minStartTime = clip.tracks[ i ].times[ 0 ];
  22761. }
  22762. }
  22763. // shift all tracks such that clip begins at t=0
  22764. for ( let i = 0; i < clip.tracks.length; ++ i ) {
  22765. clip.tracks[ i ].shift( - 1 * minStartTime );
  22766. }
  22767. clip.resetDuration();
  22768. return clip;
  22769. }
  22770. function makeClipAdditive( targetClip, referenceFrame = 0, referenceClip = targetClip, fps = 30 ) {
  22771. if ( fps <= 0 ) fps = 30;
  22772. const numTracks = referenceClip.tracks.length;
  22773. const referenceTime = referenceFrame / fps;
  22774. // Make each track's values relative to the values at the reference frame
  22775. for ( let i = 0; i < numTracks; ++ i ) {
  22776. const referenceTrack = referenceClip.tracks[ i ];
  22777. const referenceTrackType = referenceTrack.ValueTypeName;
  22778. // Skip this track if it's non-numeric
  22779. if ( referenceTrackType === 'bool' || referenceTrackType === 'string' ) continue;
  22780. // Find the track in the target clip whose name and type matches the reference track
  22781. const targetTrack = targetClip.tracks.find( function ( track ) {
  22782. return track.name === referenceTrack.name
  22783. && track.ValueTypeName === referenceTrackType;
  22784. } );
  22785. if ( targetTrack === undefined ) continue;
  22786. let referenceOffset = 0;
  22787. const referenceValueSize = referenceTrack.getValueSize();
  22788. if ( referenceTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline ) {
  22789. referenceOffset = referenceValueSize / 3;
  22790. }
  22791. let targetOffset = 0;
  22792. const targetValueSize = targetTrack.getValueSize();
  22793. if ( targetTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline ) {
  22794. targetOffset = targetValueSize / 3;
  22795. }
  22796. const lastIndex = referenceTrack.times.length - 1;
  22797. let referenceValue;
  22798. // Find the value to subtract out of the track
  22799. if ( referenceTime <= referenceTrack.times[ 0 ] ) {
  22800. // Reference frame is earlier than the first keyframe, so just use the first keyframe
  22801. const startIndex = referenceOffset;
  22802. const endIndex = referenceValueSize - referenceOffset;
  22803. referenceValue = arraySlice( referenceTrack.values, startIndex, endIndex );
  22804. } else if ( referenceTime >= referenceTrack.times[ lastIndex ] ) {
  22805. // Reference frame is after the last keyframe, so just use the last keyframe
  22806. const startIndex = lastIndex * referenceValueSize + referenceOffset;
  22807. const endIndex = startIndex + referenceValueSize - referenceOffset;
  22808. referenceValue = arraySlice( referenceTrack.values, startIndex, endIndex );
  22809. } else {
  22810. // Interpolate to the reference value
  22811. const interpolant = referenceTrack.createInterpolant();
  22812. const startIndex = referenceOffset;
  22813. const endIndex = referenceValueSize - referenceOffset;
  22814. interpolant.evaluate( referenceTime );
  22815. referenceValue = arraySlice( interpolant.resultBuffer, startIndex, endIndex );
  22816. }
  22817. // Conjugate the quaternion
  22818. if ( referenceTrackType === 'quaternion' ) {
  22819. const referenceQuat = new Quaternion().fromArray( referenceValue ).normalize().conjugate();
  22820. referenceQuat.toArray( referenceValue );
  22821. }
  22822. // Subtract the reference value from all of the track values
  22823. const numTimes = targetTrack.times.length;
  22824. for ( let j = 0; j < numTimes; ++ j ) {
  22825. const valueStart = j * targetValueSize + targetOffset;
  22826. if ( referenceTrackType === 'quaternion' ) {
  22827. // Multiply the conjugate for quaternion track types
  22828. Quaternion.multiplyQuaternionsFlat(
  22829. targetTrack.values,
  22830. valueStart,
  22831. referenceValue,
  22832. 0,
  22833. targetTrack.values,
  22834. valueStart
  22835. );
  22836. } else {
  22837. const valueEnd = targetValueSize - targetOffset * 2;
  22838. // Subtract each value for all other numeric track types
  22839. for ( let k = 0; k < valueEnd; ++ k ) {
  22840. targetTrack.values[ valueStart + k ] -= referenceValue[ k ];
  22841. }
  22842. }
  22843. }
  22844. }
  22845. targetClip.blendMode = AdditiveAnimationBlendMode;
  22846. return targetClip;
  22847. }
  22848. var AnimationUtils = /*#__PURE__*/Object.freeze({
  22849. __proto__: null,
  22850. arraySlice: arraySlice,
  22851. convertArray: convertArray,
  22852. flattenJSON: flattenJSON,
  22853. getKeyframeOrder: getKeyframeOrder,
  22854. isTypedArray: isTypedArray,
  22855. makeClipAdditive: makeClipAdditive,
  22856. sortedArray: sortedArray,
  22857. subclip: subclip
  22858. });
  22859. /**
  22860. * Abstract base class of interpolants over parametric samples.
  22861. *
  22862. * The parameter domain is one dimensional, typically the time or a path
  22863. * along a curve defined by the data.
  22864. *
  22865. * The sample values can have any dimensionality and derived classes may
  22866. * apply special interpretations to the data.
  22867. *
  22868. * This class provides the interval seek in a Template Method, deferring
  22869. * the actual interpolation to derived classes.
  22870. *
  22871. * Time complexity is O(1) for linear access crossing at most two points
  22872. * and O(log N) for random access, where N is the number of positions.
  22873. *
  22874. * References:
  22875. *
  22876. * http://www.oodesign.com/template-method-pattern.html
  22877. *
  22878. */
  22879. class Interpolant {
  22880. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  22881. this.parameterPositions = parameterPositions;
  22882. this._cachedIndex = 0;
  22883. this.resultBuffer = resultBuffer !== undefined ?
  22884. resultBuffer : new sampleValues.constructor( sampleSize );
  22885. this.sampleValues = sampleValues;
  22886. this.valueSize = sampleSize;
  22887. this.settings = null;
  22888. this.DefaultSettings_ = {};
  22889. }
  22890. evaluate( t ) {
  22891. const pp = this.parameterPositions;
  22892. let i1 = this._cachedIndex,
  22893. t1 = pp[ i1 ],
  22894. t0 = pp[ i1 - 1 ];
  22895. validate_interval: {
  22896. seek: {
  22897. let right;
  22898. linear_scan: {
  22899. //- See http://jsperf.com/comparison-to-undefined/3
  22900. //- slower code:
  22901. //-
  22902. //- if ( t >= t1 || t1 === undefined ) {
  22903. forward_scan: if ( ! ( t < t1 ) ) {
  22904. for ( let giveUpAt = i1 + 2; ; ) {
  22905. if ( t1 === undefined ) {
  22906. if ( t < t0 ) break forward_scan;
  22907. // after end
  22908. i1 = pp.length;
  22909. this._cachedIndex = i1;
  22910. return this.copySampleValue_( i1 - 1 );
  22911. }
  22912. if ( i1 === giveUpAt ) break; // this loop
  22913. t0 = t1;
  22914. t1 = pp[ ++ i1 ];
  22915. if ( t < t1 ) {
  22916. // we have arrived at the sought interval
  22917. break seek;
  22918. }
  22919. }
  22920. // prepare binary search on the right side of the index
  22921. right = pp.length;
  22922. break linear_scan;
  22923. }
  22924. //- slower code:
  22925. //- if ( t < t0 || t0 === undefined ) {
  22926. if ( ! ( t >= t0 ) ) {
  22927. // looping?
  22928. const t1global = pp[ 1 ];
  22929. if ( t < t1global ) {
  22930. i1 = 2; // + 1, using the scan for the details
  22931. t0 = t1global;
  22932. }
  22933. // linear reverse scan
  22934. for ( let giveUpAt = i1 - 2; ; ) {
  22935. if ( t0 === undefined ) {
  22936. // before start
  22937. this._cachedIndex = 0;
  22938. return this.copySampleValue_( 0 );
  22939. }
  22940. if ( i1 === giveUpAt ) break; // this loop
  22941. t1 = t0;
  22942. t0 = pp[ -- i1 - 1 ];
  22943. if ( t >= t0 ) {
  22944. // we have arrived at the sought interval
  22945. break seek;
  22946. }
  22947. }
  22948. // prepare binary search on the left side of the index
  22949. right = i1;
  22950. i1 = 0;
  22951. break linear_scan;
  22952. }
  22953. // the interval is valid
  22954. break validate_interval;
  22955. } // linear scan
  22956. // binary search
  22957. while ( i1 < right ) {
  22958. const mid = ( i1 + right ) >>> 1;
  22959. if ( t < pp[ mid ] ) {
  22960. right = mid;
  22961. } else {
  22962. i1 = mid + 1;
  22963. }
  22964. }
  22965. t1 = pp[ i1 ];
  22966. t0 = pp[ i1 - 1 ];
  22967. // check boundary cases, again
  22968. if ( t0 === undefined ) {
  22969. this._cachedIndex = 0;
  22970. return this.copySampleValue_( 0 );
  22971. }
  22972. if ( t1 === undefined ) {
  22973. i1 = pp.length;
  22974. this._cachedIndex = i1;
  22975. return this.copySampleValue_( i1 - 1 );
  22976. }
  22977. } // seek
  22978. this._cachedIndex = i1;
  22979. this.intervalChanged_( i1, t0, t1 );
  22980. } // validate_interval
  22981. return this.interpolate_( i1, t0, t, t1 );
  22982. }
  22983. getSettings_() {
  22984. return this.settings || this.DefaultSettings_;
  22985. }
  22986. copySampleValue_( index ) {
  22987. // copies a sample value to the result buffer
  22988. const result = this.resultBuffer,
  22989. values = this.sampleValues,
  22990. stride = this.valueSize,
  22991. offset = index * stride;
  22992. for ( let i = 0; i !== stride; ++ i ) {
  22993. result[ i ] = values[ offset + i ];
  22994. }
  22995. return result;
  22996. }
  22997. // Template methods for derived classes:
  22998. interpolate_( /* i1, t0, t, t1 */ ) {
  22999. throw new Error( 'call to abstract method' );
  23000. // implementations shall return this.resultBuffer
  23001. }
  23002. intervalChanged_( /* i1, t0, t1 */ ) {
  23003. // empty
  23004. }
  23005. }
  23006. /**
  23007. * Fast and simple cubic spline interpolant.
  23008. *
  23009. * It was derived from a Hermitian construction setting the first derivative
  23010. * at each sample position to the linear slope between neighboring positions
  23011. * over their parameter interval.
  23012. */
  23013. class CubicInterpolant extends Interpolant {
  23014. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  23015. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  23016. this._weightPrev = - 0;
  23017. this._offsetPrev = - 0;
  23018. this._weightNext = - 0;
  23019. this._offsetNext = - 0;
  23020. this.DefaultSettings_ = {
  23021. endingStart: ZeroCurvatureEnding,
  23022. endingEnd: ZeroCurvatureEnding
  23023. };
  23024. }
  23025. intervalChanged_( i1, t0, t1 ) {
  23026. const pp = this.parameterPositions;
  23027. let iPrev = i1 - 2,
  23028. iNext = i1 + 1,
  23029. tPrev = pp[ iPrev ],
  23030. tNext = pp[ iNext ];
  23031. if ( tPrev === undefined ) {
  23032. switch ( this.getSettings_().endingStart ) {
  23033. case ZeroSlopeEnding:
  23034. // f'(t0) = 0
  23035. iPrev = i1;
  23036. tPrev = 2 * t0 - t1;
  23037. break;
  23038. case WrapAroundEnding:
  23039. // use the other end of the curve
  23040. iPrev = pp.length - 2;
  23041. tPrev = t0 + pp[ iPrev ] - pp[ iPrev + 1 ];
  23042. break;
  23043. default: // ZeroCurvatureEnding
  23044. // f''(t0) = 0 a.k.a. Natural Spline
  23045. iPrev = i1;
  23046. tPrev = t1;
  23047. }
  23048. }
  23049. if ( tNext === undefined ) {
  23050. switch ( this.getSettings_().endingEnd ) {
  23051. case ZeroSlopeEnding:
  23052. // f'(tN) = 0
  23053. iNext = i1;
  23054. tNext = 2 * t1 - t0;
  23055. break;
  23056. case WrapAroundEnding:
  23057. // use the other end of the curve
  23058. iNext = 1;
  23059. tNext = t1 + pp[ 1 ] - pp[ 0 ];
  23060. break;
  23061. default: // ZeroCurvatureEnding
  23062. // f''(tN) = 0, a.k.a. Natural Spline
  23063. iNext = i1 - 1;
  23064. tNext = t0;
  23065. }
  23066. }
  23067. const halfDt = ( t1 - t0 ) * 0.5,
  23068. stride = this.valueSize;
  23069. this._weightPrev = halfDt / ( t0 - tPrev );
  23070. this._weightNext = halfDt / ( tNext - t1 );
  23071. this._offsetPrev = iPrev * stride;
  23072. this._offsetNext = iNext * stride;
  23073. }
  23074. interpolate_( i1, t0, t, t1 ) {
  23075. const result = this.resultBuffer,
  23076. values = this.sampleValues,
  23077. stride = this.valueSize,
  23078. o1 = i1 * stride, o0 = o1 - stride,
  23079. oP = this._offsetPrev, oN = this._offsetNext,
  23080. wP = this._weightPrev, wN = this._weightNext,
  23081. p = ( t - t0 ) / ( t1 - t0 ),
  23082. pp = p * p,
  23083. ppp = pp * p;
  23084. // evaluate polynomials
  23085. const sP = - wP * ppp + 2 * wP * pp - wP * p;
  23086. const s0 = ( 1 + wP ) * ppp + ( - 1.5 - 2 * wP ) * pp + ( - 0.5 + wP ) * p + 1;
  23087. const s1 = ( - 1 - wN ) * ppp + ( 1.5 + wN ) * pp + 0.5 * p;
  23088. const sN = wN * ppp - wN * pp;
  23089. // combine data linearly
  23090. for ( let i = 0; i !== stride; ++ i ) {
  23091. result[ i ] =
  23092. sP * values[ oP + i ] +
  23093. s0 * values[ o0 + i ] +
  23094. s1 * values[ o1 + i ] +
  23095. sN * values[ oN + i ];
  23096. }
  23097. return result;
  23098. }
  23099. }
  23100. class LinearInterpolant extends Interpolant {
  23101. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  23102. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  23103. }
  23104. interpolate_( i1, t0, t, t1 ) {
  23105. const result = this.resultBuffer,
  23106. values = this.sampleValues,
  23107. stride = this.valueSize,
  23108. offset1 = i1 * stride,
  23109. offset0 = offset1 - stride,
  23110. weight1 = ( t - t0 ) / ( t1 - t0 ),
  23111. weight0 = 1 - weight1;
  23112. for ( let i = 0; i !== stride; ++ i ) {
  23113. result[ i ] =
  23114. values[ offset0 + i ] * weight0 +
  23115. values[ offset1 + i ] * weight1;
  23116. }
  23117. return result;
  23118. }
  23119. }
  23120. /**
  23121. *
  23122. * Interpolant that evaluates to the sample value at the position preceding
  23123. * the parameter.
  23124. */
  23125. class DiscreteInterpolant extends Interpolant {
  23126. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  23127. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  23128. }
  23129. interpolate_( i1 /*, t0, t, t1 */ ) {
  23130. return this.copySampleValue_( i1 - 1 );
  23131. }
  23132. }
  23133. class KeyframeTrack {
  23134. constructor( name, times, values, interpolation ) {
  23135. if ( name === undefined ) throw new Error( 'THREE.KeyframeTrack: track name is undefined' );
  23136. if ( times === undefined || times.length === 0 ) throw new Error( 'THREE.KeyframeTrack: no keyframes in track named ' + name );
  23137. this.name = name;
  23138. this.times = convertArray( times, this.TimeBufferType );
  23139. this.values = convertArray( values, this.ValueBufferType );
  23140. this.setInterpolation( interpolation || this.DefaultInterpolation );
  23141. }
  23142. // Serialization (in static context, because of constructor invocation
  23143. // and automatic invocation of .toJSON):
  23144. static toJSON( track ) {
  23145. const trackType = track.constructor;
  23146. let json;
  23147. // derived classes can define a static toJSON method
  23148. if ( trackType.toJSON !== this.toJSON ) {
  23149. json = trackType.toJSON( track );
  23150. } else {
  23151. // by default, we assume the data can be serialized as-is
  23152. json = {
  23153. 'name': track.name,
  23154. 'times': convertArray( track.times, Array ),
  23155. 'values': convertArray( track.values, Array )
  23156. };
  23157. const interpolation = track.getInterpolation();
  23158. if ( interpolation !== track.DefaultInterpolation ) {
  23159. json.interpolation = interpolation;
  23160. }
  23161. }
  23162. json.type = track.ValueTypeName; // mandatory
  23163. return json;
  23164. }
  23165. InterpolantFactoryMethodDiscrete( result ) {
  23166. return new DiscreteInterpolant( this.times, this.values, this.getValueSize(), result );
  23167. }
  23168. InterpolantFactoryMethodLinear( result ) {
  23169. return new LinearInterpolant( this.times, this.values, this.getValueSize(), result );
  23170. }
  23171. InterpolantFactoryMethodSmooth( result ) {
  23172. return new CubicInterpolant( this.times, this.values, this.getValueSize(), result );
  23173. }
  23174. setInterpolation( interpolation ) {
  23175. let factoryMethod;
  23176. switch ( interpolation ) {
  23177. case InterpolateDiscrete:
  23178. factoryMethod = this.InterpolantFactoryMethodDiscrete;
  23179. break;
  23180. case InterpolateLinear:
  23181. factoryMethod = this.InterpolantFactoryMethodLinear;
  23182. break;
  23183. case InterpolateSmooth:
  23184. factoryMethod = this.InterpolantFactoryMethodSmooth;
  23185. break;
  23186. }
  23187. if ( factoryMethod === undefined ) {
  23188. const message = 'unsupported interpolation for ' +
  23189. this.ValueTypeName + ' keyframe track named ' + this.name;
  23190. if ( this.createInterpolant === undefined ) {
  23191. // fall back to default, unless the default itself is messed up
  23192. if ( interpolation !== this.DefaultInterpolation ) {
  23193. this.setInterpolation( this.DefaultInterpolation );
  23194. } else {
  23195. throw new Error( message ); // fatal, in this case
  23196. }
  23197. }
  23198. console.warn( 'THREE.KeyframeTrack:', message );
  23199. return this;
  23200. }
  23201. this.createInterpolant = factoryMethod;
  23202. return this;
  23203. }
  23204. getInterpolation() {
  23205. switch ( this.createInterpolant ) {
  23206. case this.InterpolantFactoryMethodDiscrete:
  23207. return InterpolateDiscrete;
  23208. case this.InterpolantFactoryMethodLinear:
  23209. return InterpolateLinear;
  23210. case this.InterpolantFactoryMethodSmooth:
  23211. return InterpolateSmooth;
  23212. }
  23213. }
  23214. getValueSize() {
  23215. return this.values.length / this.times.length;
  23216. }
  23217. // move all keyframes either forwards or backwards in time
  23218. shift( timeOffset ) {
  23219. if ( timeOffset !== 0.0 ) {
  23220. const times = this.times;
  23221. for ( let i = 0, n = times.length; i !== n; ++ i ) {
  23222. times[ i ] += timeOffset;
  23223. }
  23224. }
  23225. return this;
  23226. }
  23227. // scale all keyframe times by a factor (useful for frame <-> seconds conversions)
  23228. scale( timeScale ) {
  23229. if ( timeScale !== 1.0 ) {
  23230. const times = this.times;
  23231. for ( let i = 0, n = times.length; i !== n; ++ i ) {
  23232. times[ i ] *= timeScale;
  23233. }
  23234. }
  23235. return this;
  23236. }
  23237. // removes keyframes before and after animation without changing any values within the range [startTime, endTime].
  23238. // IMPORTANT: We do not shift around keys to the start of the track time, because for interpolated keys this will change their values
  23239. trim( startTime, endTime ) {
  23240. const times = this.times,
  23241. nKeys = times.length;
  23242. let from = 0,
  23243. to = nKeys - 1;
  23244. while ( from !== nKeys && times[ from ] < startTime ) {
  23245. ++ from;
  23246. }
  23247. while ( to !== - 1 && times[ to ] > endTime ) {
  23248. -- to;
  23249. }
  23250. ++ to; // inclusive -> exclusive bound
  23251. if ( from !== 0 || to !== nKeys ) {
  23252. // empty tracks are forbidden, so keep at least one keyframe
  23253. if ( from >= to ) {
  23254. to = Math.max( to, 1 );
  23255. from = to - 1;
  23256. }
  23257. const stride = this.getValueSize();
  23258. this.times = arraySlice( times, from, to );
  23259. this.values = arraySlice( this.values, from * stride, to * stride );
  23260. }
  23261. return this;
  23262. }
  23263. // ensure we do not get a GarbageInGarbageOut situation, make sure tracks are at least minimally viable
  23264. validate() {
  23265. let valid = true;
  23266. const valueSize = this.getValueSize();
  23267. if ( valueSize - Math.floor( valueSize ) !== 0 ) {
  23268. console.error( 'THREE.KeyframeTrack: Invalid value size in track.', this );
  23269. valid = false;
  23270. }
  23271. const times = this.times,
  23272. values = this.values,
  23273. nKeys = times.length;
  23274. if ( nKeys === 0 ) {
  23275. console.error( 'THREE.KeyframeTrack: Track is empty.', this );
  23276. valid = false;
  23277. }
  23278. let prevTime = null;
  23279. for ( let i = 0; i !== nKeys; i ++ ) {
  23280. const currTime = times[ i ];
  23281. if ( typeof currTime === 'number' && isNaN( currTime ) ) {
  23282. console.error( 'THREE.KeyframeTrack: Time is not a valid number.', this, i, currTime );
  23283. valid = false;
  23284. break;
  23285. }
  23286. if ( prevTime !== null && prevTime > currTime ) {
  23287. console.error( 'THREE.KeyframeTrack: Out of order keys.', this, i, currTime, prevTime );
  23288. valid = false;
  23289. break;
  23290. }
  23291. prevTime = currTime;
  23292. }
  23293. if ( values !== undefined ) {
  23294. if ( isTypedArray( values ) ) {
  23295. for ( let i = 0, n = values.length; i !== n; ++ i ) {
  23296. const value = values[ i ];
  23297. if ( isNaN( value ) ) {
  23298. console.error( 'THREE.KeyframeTrack: Value is not a valid number.', this, i, value );
  23299. valid = false;
  23300. break;
  23301. }
  23302. }
  23303. }
  23304. }
  23305. return valid;
  23306. }
  23307. // removes equivalent sequential keys as common in morph target sequences
  23308. // (0,0,0,0,1,1,1,0,0,0,0,0,0,0) --> (0,0,1,1,0,0)
  23309. optimize() {
  23310. // times or values may be shared with other tracks, so overwriting is unsafe
  23311. const times = arraySlice( this.times ),
  23312. values = arraySlice( this.values ),
  23313. stride = this.getValueSize(),
  23314. smoothInterpolation = this.getInterpolation() === InterpolateSmooth,
  23315. lastIndex = times.length - 1;
  23316. let writeIndex = 1;
  23317. for ( let i = 1; i < lastIndex; ++ i ) {
  23318. let keep = false;
  23319. const time = times[ i ];
  23320. const timeNext = times[ i + 1 ];
  23321. // remove adjacent keyframes scheduled at the same time
  23322. if ( time !== timeNext && ( i !== 1 || time !== times[ 0 ] ) ) {
  23323. if ( ! smoothInterpolation ) {
  23324. // remove unnecessary keyframes same as their neighbors
  23325. const offset = i * stride,
  23326. offsetP = offset - stride,
  23327. offsetN = offset + stride;
  23328. for ( let j = 0; j !== stride; ++ j ) {
  23329. const value = values[ offset + j ];
  23330. if ( value !== values[ offsetP + j ] ||
  23331. value !== values[ offsetN + j ] ) {
  23332. keep = true;
  23333. break;
  23334. }
  23335. }
  23336. } else {
  23337. keep = true;
  23338. }
  23339. }
  23340. // in-place compaction
  23341. if ( keep ) {
  23342. if ( i !== writeIndex ) {
  23343. times[ writeIndex ] = times[ i ];
  23344. const readOffset = i * stride,
  23345. writeOffset = writeIndex * stride;
  23346. for ( let j = 0; j !== stride; ++ j ) {
  23347. values[ writeOffset + j ] = values[ readOffset + j ];
  23348. }
  23349. }
  23350. ++ writeIndex;
  23351. }
  23352. }
  23353. // flush last keyframe (compaction looks ahead)
  23354. if ( lastIndex > 0 ) {
  23355. times[ writeIndex ] = times[ lastIndex ];
  23356. for ( let readOffset = lastIndex * stride, writeOffset = writeIndex * stride, j = 0; j !== stride; ++ j ) {
  23357. values[ writeOffset + j ] = values[ readOffset + j ];
  23358. }
  23359. ++ writeIndex;
  23360. }
  23361. if ( writeIndex !== times.length ) {
  23362. this.times = arraySlice( times, 0, writeIndex );
  23363. this.values = arraySlice( values, 0, writeIndex * stride );
  23364. } else {
  23365. this.times = times;
  23366. this.values = values;
  23367. }
  23368. return this;
  23369. }
  23370. clone() {
  23371. const times = arraySlice( this.times, 0 );
  23372. const values = arraySlice( this.values, 0 );
  23373. const TypedKeyframeTrack = this.constructor;
  23374. const track = new TypedKeyframeTrack( this.name, times, values );
  23375. // Interpolant argument to constructor is not saved, so copy the factory method directly.
  23376. track.createInterpolant = this.createInterpolant;
  23377. return track;
  23378. }
  23379. }
  23380. KeyframeTrack.prototype.TimeBufferType = Float32Array;
  23381. KeyframeTrack.prototype.ValueBufferType = Float32Array;
  23382. KeyframeTrack.prototype.DefaultInterpolation = InterpolateLinear;
  23383. /**
  23384. * A Track of Boolean keyframe values.
  23385. */
  23386. class BooleanKeyframeTrack extends KeyframeTrack {}
  23387. BooleanKeyframeTrack.prototype.ValueTypeName = 'bool';
  23388. BooleanKeyframeTrack.prototype.ValueBufferType = Array;
  23389. BooleanKeyframeTrack.prototype.DefaultInterpolation = InterpolateDiscrete;
  23390. BooleanKeyframeTrack.prototype.InterpolantFactoryMethodLinear = undefined;
  23391. BooleanKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  23392. /**
  23393. * A Track of keyframe values that represent color.
  23394. */
  23395. class ColorKeyframeTrack extends KeyframeTrack {}
  23396. ColorKeyframeTrack.prototype.ValueTypeName = 'color';
  23397. /**
  23398. * A Track of numeric keyframe values.
  23399. */
  23400. class NumberKeyframeTrack extends KeyframeTrack {}
  23401. NumberKeyframeTrack.prototype.ValueTypeName = 'number';
  23402. /**
  23403. * Spherical linear unit quaternion interpolant.
  23404. */
  23405. class QuaternionLinearInterpolant extends Interpolant {
  23406. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  23407. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  23408. }
  23409. interpolate_( i1, t0, t, t1 ) {
  23410. const result = this.resultBuffer,
  23411. values = this.sampleValues,
  23412. stride = this.valueSize,
  23413. alpha = ( t - t0 ) / ( t1 - t0 );
  23414. let offset = i1 * stride;
  23415. for ( let end = offset + stride; offset !== end; offset += 4 ) {
  23416. Quaternion.slerpFlat( result, 0, values, offset - stride, values, offset, alpha );
  23417. }
  23418. return result;
  23419. }
  23420. }
  23421. /**
  23422. * A Track of quaternion keyframe values.
  23423. */
  23424. class QuaternionKeyframeTrack extends KeyframeTrack {
  23425. InterpolantFactoryMethodLinear( result ) {
  23426. return new QuaternionLinearInterpolant( this.times, this.values, this.getValueSize(), result );
  23427. }
  23428. }
  23429. QuaternionKeyframeTrack.prototype.ValueTypeName = 'quaternion';
  23430. // ValueBufferType is inherited
  23431. QuaternionKeyframeTrack.prototype.DefaultInterpolation = InterpolateLinear;
  23432. QuaternionKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  23433. /**
  23434. * A Track that interpolates Strings
  23435. */
  23436. class StringKeyframeTrack extends KeyframeTrack {}
  23437. StringKeyframeTrack.prototype.ValueTypeName = 'string';
  23438. StringKeyframeTrack.prototype.ValueBufferType = Array;
  23439. StringKeyframeTrack.prototype.DefaultInterpolation = InterpolateDiscrete;
  23440. StringKeyframeTrack.prototype.InterpolantFactoryMethodLinear = undefined;
  23441. StringKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  23442. /**
  23443. * A Track of vectored keyframe values.
  23444. */
  23445. class VectorKeyframeTrack extends KeyframeTrack {}
  23446. VectorKeyframeTrack.prototype.ValueTypeName = 'vector';
  23447. class AnimationClip {
  23448. constructor( name, duration = - 1, tracks, blendMode = NormalAnimationBlendMode ) {
  23449. this.name = name;
  23450. this.tracks = tracks;
  23451. this.duration = duration;
  23452. this.blendMode = blendMode;
  23453. this.uuid = generateUUID();
  23454. // this means it should figure out its duration by scanning the tracks
  23455. if ( this.duration < 0 ) {
  23456. this.resetDuration();
  23457. }
  23458. }
  23459. static parse( json ) {
  23460. const tracks = [],
  23461. jsonTracks = json.tracks,
  23462. frameTime = 1.0 / ( json.fps || 1.0 );
  23463. for ( let i = 0, n = jsonTracks.length; i !== n; ++ i ) {
  23464. tracks.push( parseKeyframeTrack( jsonTracks[ i ] ).scale( frameTime ) );
  23465. }
  23466. const clip = new this( json.name, json.duration, tracks, json.blendMode );
  23467. clip.uuid = json.uuid;
  23468. return clip;
  23469. }
  23470. static toJSON( clip ) {
  23471. const tracks = [],
  23472. clipTracks = clip.tracks;
  23473. const json = {
  23474. 'name': clip.name,
  23475. 'duration': clip.duration,
  23476. 'tracks': tracks,
  23477. 'uuid': clip.uuid,
  23478. 'blendMode': clip.blendMode
  23479. };
  23480. for ( let i = 0, n = clipTracks.length; i !== n; ++ i ) {
  23481. tracks.push( KeyframeTrack.toJSON( clipTracks[ i ] ) );
  23482. }
  23483. return json;
  23484. }
  23485. static CreateFromMorphTargetSequence( name, morphTargetSequence, fps, noLoop ) {
  23486. const numMorphTargets = morphTargetSequence.length;
  23487. const tracks = [];
  23488. for ( let i = 0; i < numMorphTargets; i ++ ) {
  23489. let times = [];
  23490. let values = [];
  23491. times.push(
  23492. ( i + numMorphTargets - 1 ) % numMorphTargets,
  23493. i,
  23494. ( i + 1 ) % numMorphTargets );
  23495. values.push( 0, 1, 0 );
  23496. const order = getKeyframeOrder( times );
  23497. times = sortedArray( times, 1, order );
  23498. values = sortedArray( values, 1, order );
  23499. // if there is a key at the first frame, duplicate it as the
  23500. // last frame as well for perfect loop.
  23501. if ( ! noLoop && times[ 0 ] === 0 ) {
  23502. times.push( numMorphTargets );
  23503. values.push( values[ 0 ] );
  23504. }
  23505. tracks.push(
  23506. new NumberKeyframeTrack(
  23507. '.morphTargetInfluences[' + morphTargetSequence[ i ].name + ']',
  23508. times, values
  23509. ).scale( 1.0 / fps ) );
  23510. }
  23511. return new this( name, - 1, tracks );
  23512. }
  23513. static findByName( objectOrClipArray, name ) {
  23514. let clipArray = objectOrClipArray;
  23515. if ( ! Array.isArray( objectOrClipArray ) ) {
  23516. const o = objectOrClipArray;
  23517. clipArray = o.geometry && o.geometry.animations || o.animations;
  23518. }
  23519. for ( let i = 0; i < clipArray.length; i ++ ) {
  23520. if ( clipArray[ i ].name === name ) {
  23521. return clipArray[ i ];
  23522. }
  23523. }
  23524. return null;
  23525. }
  23526. static CreateClipsFromMorphTargetSequences( morphTargets, fps, noLoop ) {
  23527. const animationToMorphTargets = {};
  23528. // tested with https://regex101.com/ on trick sequences
  23529. // such flamingo_flyA_003, flamingo_run1_003, crdeath0059
  23530. const pattern = /^([\w-]*?)([\d]+)$/;
  23531. // sort morph target names into animation groups based
  23532. // patterns like Walk_001, Walk_002, Run_001, Run_002
  23533. for ( let i = 0, il = morphTargets.length; i < il; i ++ ) {
  23534. const morphTarget = morphTargets[ i ];
  23535. const parts = morphTarget.name.match( pattern );
  23536. if ( parts && parts.length > 1 ) {
  23537. const name = parts[ 1 ];
  23538. let animationMorphTargets = animationToMorphTargets[ name ];
  23539. if ( ! animationMorphTargets ) {
  23540. animationToMorphTargets[ name ] = animationMorphTargets = [];
  23541. }
  23542. animationMorphTargets.push( morphTarget );
  23543. }
  23544. }
  23545. const clips = [];
  23546. for ( const name in animationToMorphTargets ) {
  23547. clips.push( this.CreateFromMorphTargetSequence( name, animationToMorphTargets[ name ], fps, noLoop ) );
  23548. }
  23549. return clips;
  23550. }
  23551. // parse the animation.hierarchy format
  23552. static parseAnimation( animation, bones ) {
  23553. if ( ! animation ) {
  23554. console.error( 'THREE.AnimationClip: No animation in JSONLoader data.' );
  23555. return null;
  23556. }
  23557. const addNonemptyTrack = function ( trackType, trackName, animationKeys, propertyName, destTracks ) {
  23558. // only return track if there are actually keys.
  23559. if ( animationKeys.length !== 0 ) {
  23560. const times = [];
  23561. const values = [];
  23562. flattenJSON( animationKeys, times, values, propertyName );
  23563. // empty keys are filtered out, so check again
  23564. if ( times.length !== 0 ) {
  23565. destTracks.push( new trackType( trackName, times, values ) );
  23566. }
  23567. }
  23568. };
  23569. const tracks = [];
  23570. const clipName = animation.name || 'default';
  23571. const fps = animation.fps || 30;
  23572. const blendMode = animation.blendMode;
  23573. // automatic length determination in AnimationClip.
  23574. let duration = animation.length || - 1;
  23575. const hierarchyTracks = animation.hierarchy || [];
  23576. for ( let h = 0; h < hierarchyTracks.length; h ++ ) {
  23577. const animationKeys = hierarchyTracks[ h ].keys;
  23578. // skip empty tracks
  23579. if ( ! animationKeys || animationKeys.length === 0 ) continue;
  23580. // process morph targets
  23581. if ( animationKeys[ 0 ].morphTargets ) {
  23582. // figure out all morph targets used in this track
  23583. const morphTargetNames = {};
  23584. let k;
  23585. for ( k = 0; k < animationKeys.length; k ++ ) {
  23586. if ( animationKeys[ k ].morphTargets ) {
  23587. for ( let m = 0; m < animationKeys[ k ].morphTargets.length; m ++ ) {
  23588. morphTargetNames[ animationKeys[ k ].morphTargets[ m ] ] = - 1;
  23589. }
  23590. }
  23591. }
  23592. // create a track for each morph target with all zero
  23593. // morphTargetInfluences except for the keys in which
  23594. // the morphTarget is named.
  23595. for ( const morphTargetName in morphTargetNames ) {
  23596. const times = [];
  23597. const values = [];
  23598. for ( let m = 0; m !== animationKeys[ k ].morphTargets.length; ++ m ) {
  23599. const animationKey = animationKeys[ k ];
  23600. times.push( animationKey.time );
  23601. values.push( ( animationKey.morphTarget === morphTargetName ) ? 1 : 0 );
  23602. }
  23603. tracks.push( new NumberKeyframeTrack( '.morphTargetInfluence[' + morphTargetName + ']', times, values ) );
  23604. }
  23605. duration = morphTargetNames.length * fps;
  23606. } else {
  23607. // ...assume skeletal animation
  23608. const boneName = '.bones[' + bones[ h ].name + ']';
  23609. addNonemptyTrack(
  23610. VectorKeyframeTrack, boneName + '.position',
  23611. animationKeys, 'pos', tracks );
  23612. addNonemptyTrack(
  23613. QuaternionKeyframeTrack, boneName + '.quaternion',
  23614. animationKeys, 'rot', tracks );
  23615. addNonemptyTrack(
  23616. VectorKeyframeTrack, boneName + '.scale',
  23617. animationKeys, 'scl', tracks );
  23618. }
  23619. }
  23620. if ( tracks.length === 0 ) {
  23621. return null;
  23622. }
  23623. const clip = new this( clipName, duration, tracks, blendMode );
  23624. return clip;
  23625. }
  23626. resetDuration() {
  23627. const tracks = this.tracks;
  23628. let duration = 0;
  23629. for ( let i = 0, n = tracks.length; i !== n; ++ i ) {
  23630. const track = this.tracks[ i ];
  23631. duration = Math.max( duration, track.times[ track.times.length - 1 ] );
  23632. }
  23633. this.duration = duration;
  23634. return this;
  23635. }
  23636. trim() {
  23637. for ( let i = 0; i < this.tracks.length; i ++ ) {
  23638. this.tracks[ i ].trim( 0, this.duration );
  23639. }
  23640. return this;
  23641. }
  23642. validate() {
  23643. let valid = true;
  23644. for ( let i = 0; i < this.tracks.length; i ++ ) {
  23645. valid = valid && this.tracks[ i ].validate();
  23646. }
  23647. return valid;
  23648. }
  23649. optimize() {
  23650. for ( let i = 0; i < this.tracks.length; i ++ ) {
  23651. this.tracks[ i ].optimize();
  23652. }
  23653. return this;
  23654. }
  23655. clone() {
  23656. const tracks = [];
  23657. for ( let i = 0; i < this.tracks.length; i ++ ) {
  23658. tracks.push( this.tracks[ i ].clone() );
  23659. }
  23660. return new this.constructor( this.name, this.duration, tracks, this.blendMode );
  23661. }
  23662. toJSON() {
  23663. return this.constructor.toJSON( this );
  23664. }
  23665. }
  23666. function getTrackTypeForValueTypeName( typeName ) {
  23667. switch ( typeName.toLowerCase() ) {
  23668. case 'scalar':
  23669. case 'double':
  23670. case 'float':
  23671. case 'number':
  23672. case 'integer':
  23673. return NumberKeyframeTrack;
  23674. case 'vector':
  23675. case 'vector2':
  23676. case 'vector3':
  23677. case 'vector4':
  23678. return VectorKeyframeTrack;
  23679. case 'color':
  23680. return ColorKeyframeTrack;
  23681. case 'quaternion':
  23682. return QuaternionKeyframeTrack;
  23683. case 'bool':
  23684. case 'boolean':
  23685. return BooleanKeyframeTrack;
  23686. case 'string':
  23687. return StringKeyframeTrack;
  23688. }
  23689. throw new Error( 'THREE.KeyframeTrack: Unsupported typeName: ' + typeName );
  23690. }
  23691. function parseKeyframeTrack( json ) {
  23692. if ( json.type === undefined ) {
  23693. throw new Error( 'THREE.KeyframeTrack: track type undefined, can not parse' );
  23694. }
  23695. const trackType = getTrackTypeForValueTypeName( json.type );
  23696. if ( json.times === undefined ) {
  23697. const times = [], values = [];
  23698. flattenJSON( json.keys, times, values, 'value' );
  23699. json.times = times;
  23700. json.values = values;
  23701. }
  23702. // derived classes can define a static parse method
  23703. if ( trackType.parse !== undefined ) {
  23704. return trackType.parse( json );
  23705. } else {
  23706. // by default, we assume a constructor compatible with the base
  23707. return new trackType( json.name, json.times, json.values, json.interpolation );
  23708. }
  23709. }
  23710. const Cache = {
  23711. enabled: false,
  23712. files: {},
  23713. add: function ( key, file ) {
  23714. if ( this.enabled === false ) return;
  23715. // console.log( 'THREE.Cache', 'Adding key:', key );
  23716. this.files[ key ] = file;
  23717. },
  23718. get: function ( key ) {
  23719. if ( this.enabled === false ) return;
  23720. // console.log( 'THREE.Cache', 'Checking key:', key );
  23721. return this.files[ key ];
  23722. },
  23723. remove: function ( key ) {
  23724. delete this.files[ key ];
  23725. },
  23726. clear: function () {
  23727. this.files = {};
  23728. }
  23729. };
  23730. class LoadingManager {
  23731. constructor( onLoad, onProgress, onError ) {
  23732. const scope = this;
  23733. let isLoading = false;
  23734. let itemsLoaded = 0;
  23735. let itemsTotal = 0;
  23736. let urlModifier = undefined;
  23737. const handlers = [];
  23738. // Refer to #5689 for the reason why we don't set .onStart
  23739. // in the constructor
  23740. this.onStart = undefined;
  23741. this.onLoad = onLoad;
  23742. this.onProgress = onProgress;
  23743. this.onError = onError;
  23744. this.itemStart = function ( url ) {
  23745. itemsTotal ++;
  23746. if ( isLoading === false ) {
  23747. if ( scope.onStart !== undefined ) {
  23748. scope.onStart( url, itemsLoaded, itemsTotal );
  23749. }
  23750. }
  23751. isLoading = true;
  23752. };
  23753. this.itemEnd = function ( url ) {
  23754. itemsLoaded ++;
  23755. if ( scope.onProgress !== undefined ) {
  23756. scope.onProgress( url, itemsLoaded, itemsTotal );
  23757. }
  23758. if ( itemsLoaded === itemsTotal ) {
  23759. isLoading = false;
  23760. if ( scope.onLoad !== undefined ) {
  23761. scope.onLoad();
  23762. }
  23763. }
  23764. };
  23765. this.itemError = function ( url ) {
  23766. if ( scope.onError !== undefined ) {
  23767. scope.onError( url );
  23768. }
  23769. };
  23770. this.resolveURL = function ( url ) {
  23771. if ( urlModifier ) {
  23772. return urlModifier( url );
  23773. }
  23774. return url;
  23775. };
  23776. this.setURLModifier = function ( transform ) {
  23777. urlModifier = transform;
  23778. return this;
  23779. };
  23780. this.addHandler = function ( regex, loader ) {
  23781. handlers.push( regex, loader );
  23782. return this;
  23783. };
  23784. this.removeHandler = function ( regex ) {
  23785. const index = handlers.indexOf( regex );
  23786. if ( index !== - 1 ) {
  23787. handlers.splice( index, 2 );
  23788. }
  23789. return this;
  23790. };
  23791. this.getHandler = function ( file ) {
  23792. for ( let i = 0, l = handlers.length; i < l; i += 2 ) {
  23793. const regex = handlers[ i ];
  23794. const loader = handlers[ i + 1 ];
  23795. if ( regex.global ) regex.lastIndex = 0; // see #17920
  23796. if ( regex.test( file ) ) {
  23797. return loader;
  23798. }
  23799. }
  23800. return null;
  23801. };
  23802. }
  23803. }
  23804. const DefaultLoadingManager = /*@__PURE__*/ new LoadingManager();
  23805. class Loader {
  23806. constructor( manager ) {
  23807. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  23808. this.crossOrigin = 'anonymous';
  23809. this.withCredentials = false;
  23810. this.path = '';
  23811. this.resourcePath = '';
  23812. this.requestHeader = {};
  23813. }
  23814. load( /* url, onLoad, onProgress, onError */ ) {}
  23815. loadAsync( url, onProgress ) {
  23816. const scope = this;
  23817. return new Promise( function ( resolve, reject ) {
  23818. scope.load( url, resolve, onProgress, reject );
  23819. } );
  23820. }
  23821. parse( /* data */ ) {}
  23822. setCrossOrigin( crossOrigin ) {
  23823. this.crossOrigin = crossOrigin;
  23824. return this;
  23825. }
  23826. setWithCredentials( value ) {
  23827. this.withCredentials = value;
  23828. return this;
  23829. }
  23830. setPath( path ) {
  23831. this.path = path;
  23832. return this;
  23833. }
  23834. setResourcePath( resourcePath ) {
  23835. this.resourcePath = resourcePath;
  23836. return this;
  23837. }
  23838. setRequestHeader( requestHeader ) {
  23839. this.requestHeader = requestHeader;
  23840. return this;
  23841. }
  23842. }
  23843. const loading = {};
  23844. class HttpError extends Error {
  23845. constructor( message, response ) {
  23846. super( message );
  23847. this.response = response;
  23848. }
  23849. }
  23850. class FileLoader extends Loader {
  23851. constructor( manager ) {
  23852. super( manager );
  23853. }
  23854. load( url, onLoad, onProgress, onError ) {
  23855. if ( url === undefined ) url = '';
  23856. if ( this.path !== undefined ) url = this.path + url;
  23857. url = this.manager.resolveURL( url );
  23858. const cached = Cache.get( url );
  23859. if ( cached !== undefined ) {
  23860. this.manager.itemStart( url );
  23861. setTimeout( () => {
  23862. if ( onLoad ) onLoad( cached );
  23863. this.manager.itemEnd( url );
  23864. }, 0 );
  23865. return cached;
  23866. }
  23867. // Check if request is duplicate
  23868. if ( loading[ url ] !== undefined ) {
  23869. loading[ url ].push( {
  23870. onLoad: onLoad,
  23871. onProgress: onProgress,
  23872. onError: onError
  23873. } );
  23874. return;
  23875. }
  23876. // Initialise array for duplicate requests
  23877. loading[ url ] = [];
  23878. loading[ url ].push( {
  23879. onLoad: onLoad,
  23880. onProgress: onProgress,
  23881. onError: onError,
  23882. } );
  23883. // create request
  23884. const req = new Request( url, {
  23885. headers: new Headers( this.requestHeader ),
  23886. credentials: this.withCredentials ? 'include' : 'same-origin',
  23887. // An abort controller could be added within a future PR
  23888. } );
  23889. // record states ( avoid data race )
  23890. const mimeType = this.mimeType;
  23891. const responseType = this.responseType;
  23892. // start the fetch
  23893. fetch( req )
  23894. .then( response => {
  23895. if ( response.status === 200 || response.status === 0 ) {
  23896. // Some browsers return HTTP Status 0 when using non-http protocol
  23897. // e.g. 'file://' or 'data://'. Handle as success.
  23898. if ( response.status === 0 ) {
  23899. console.warn( 'THREE.FileLoader: HTTP Status 0 received.' );
  23900. }
  23901. // Workaround: Checking if response.body === undefined for Alipay browser #23548
  23902. if ( typeof ReadableStream === 'undefined' || response.body === undefined || response.body.getReader === undefined ) {
  23903. return response;
  23904. }
  23905. const callbacks = loading[ url ];
  23906. const reader = response.body.getReader();
  23907. // Nginx needs X-File-Size check
  23908. // https://serverfault.com/questions/482875/why-does-nginx-remove-content-length-header-for-chunked-content
  23909. const contentLength = response.headers.get( 'Content-Length' ) || response.headers.get( 'X-File-Size' );
  23910. const total = contentLength ? parseInt( contentLength ) : 0;
  23911. const lengthComputable = total !== 0;
  23912. let loaded = 0;
  23913. // periodically read data into the new stream tracking while download progress
  23914. const stream = new ReadableStream( {
  23915. start( controller ) {
  23916. readData();
  23917. function readData() {
  23918. reader.read().then( ( { done, value } ) => {
  23919. if ( done ) {
  23920. controller.close();
  23921. } else {
  23922. loaded += value.byteLength;
  23923. const event = new ProgressEvent( 'progress', { lengthComputable, loaded, total } );
  23924. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  23925. const callback = callbacks[ i ];
  23926. if ( callback.onProgress ) callback.onProgress( event );
  23927. }
  23928. controller.enqueue( value );
  23929. readData();
  23930. }
  23931. } );
  23932. }
  23933. }
  23934. } );
  23935. return new Response( stream );
  23936. } else {
  23937. throw new HttpError( `fetch for "${response.url}" responded with ${response.status}: ${response.statusText}`, response );
  23938. }
  23939. } )
  23940. .then( response => {
  23941. switch ( responseType ) {
  23942. case 'arraybuffer':
  23943. return response.arrayBuffer();
  23944. case 'blob':
  23945. return response.blob();
  23946. case 'document':
  23947. return response.text()
  23948. .then( text => {
  23949. const parser = new DOMParser();
  23950. return parser.parseFromString( text, mimeType );
  23951. } );
  23952. case 'json':
  23953. return response.json();
  23954. default:
  23955. if ( mimeType === undefined ) {
  23956. return response.text();
  23957. } else {
  23958. // sniff encoding
  23959. const re = /charset="?([^;"\s]*)"?/i;
  23960. const exec = re.exec( mimeType );
  23961. const label = exec && exec[ 1 ] ? exec[ 1 ].toLowerCase() : undefined;
  23962. const decoder = new TextDecoder( label );
  23963. return response.arrayBuffer().then( ab => decoder.decode( ab ) );
  23964. }
  23965. }
  23966. } )
  23967. .then( data => {
  23968. // Add to cache only on HTTP success, so that we do not cache
  23969. // error response bodies as proper responses to requests.
  23970. Cache.add( url, data );
  23971. const callbacks = loading[ url ];
  23972. delete loading[ url ];
  23973. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  23974. const callback = callbacks[ i ];
  23975. if ( callback.onLoad ) callback.onLoad( data );
  23976. }
  23977. } )
  23978. .catch( err => {
  23979. // Abort errors and other errors are handled the same
  23980. const callbacks = loading[ url ];
  23981. if ( callbacks === undefined ) {
  23982. // When onLoad was called and url was deleted in `loading`
  23983. this.manager.itemError( url );
  23984. throw err;
  23985. }
  23986. delete loading[ url ];
  23987. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  23988. const callback = callbacks[ i ];
  23989. if ( callback.onError ) callback.onError( err );
  23990. }
  23991. this.manager.itemError( url );
  23992. } )
  23993. .finally( () => {
  23994. this.manager.itemEnd( url );
  23995. } );
  23996. this.manager.itemStart( url );
  23997. }
  23998. setResponseType( value ) {
  23999. this.responseType = value;
  24000. return this;
  24001. }
  24002. setMimeType( value ) {
  24003. this.mimeType = value;
  24004. return this;
  24005. }
  24006. }
  24007. class AnimationLoader extends Loader {
  24008. constructor( manager ) {
  24009. super( manager );
  24010. }
  24011. load( url, onLoad, onProgress, onError ) {
  24012. const scope = this;
  24013. const loader = new FileLoader( this.manager );
  24014. loader.setPath( this.path );
  24015. loader.setRequestHeader( this.requestHeader );
  24016. loader.setWithCredentials( this.withCredentials );
  24017. loader.load( url, function ( text ) {
  24018. try {
  24019. onLoad( scope.parse( JSON.parse( text ) ) );
  24020. } catch ( e ) {
  24021. if ( onError ) {
  24022. onError( e );
  24023. } else {
  24024. console.error( e );
  24025. }
  24026. scope.manager.itemError( url );
  24027. }
  24028. }, onProgress, onError );
  24029. }
  24030. parse( json ) {
  24031. const animations = [];
  24032. for ( let i = 0; i < json.length; i ++ ) {
  24033. const clip = AnimationClip.parse( json[ i ] );
  24034. animations.push( clip );
  24035. }
  24036. return animations;
  24037. }
  24038. }
  24039. /**
  24040. * Abstract Base class to block based textures loader (dds, pvr, ...)
  24041. *
  24042. * Sub classes have to implement the parse() method which will be used in load().
  24043. */
  24044. class CompressedTextureLoader extends Loader {
  24045. constructor( manager ) {
  24046. super( manager );
  24047. }
  24048. load( url, onLoad, onProgress, onError ) {
  24049. const scope = this;
  24050. const images = [];
  24051. const texture = new CompressedTexture();
  24052. const loader = new FileLoader( this.manager );
  24053. loader.setPath( this.path );
  24054. loader.setResponseType( 'arraybuffer' );
  24055. loader.setRequestHeader( this.requestHeader );
  24056. loader.setWithCredentials( scope.withCredentials );
  24057. let loaded = 0;
  24058. function loadTexture( i ) {
  24059. loader.load( url[ i ], function ( buffer ) {
  24060. const texDatas = scope.parse( buffer, true );
  24061. images[ i ] = {
  24062. width: texDatas.width,
  24063. height: texDatas.height,
  24064. format: texDatas.format,
  24065. mipmaps: texDatas.mipmaps
  24066. };
  24067. loaded += 1;
  24068. if ( loaded === 6 ) {
  24069. if ( texDatas.mipmapCount === 1 ) texture.minFilter = LinearFilter;
  24070. texture.image = images;
  24071. texture.format = texDatas.format;
  24072. texture.needsUpdate = true;
  24073. if ( onLoad ) onLoad( texture );
  24074. }
  24075. }, onProgress, onError );
  24076. }
  24077. if ( Array.isArray( url ) ) {
  24078. for ( let i = 0, il = url.length; i < il; ++ i ) {
  24079. loadTexture( i );
  24080. }
  24081. } else {
  24082. // compressed cubemap texture stored in a single DDS file
  24083. loader.load( url, function ( buffer ) {
  24084. const texDatas = scope.parse( buffer, true );
  24085. if ( texDatas.isCubemap ) {
  24086. const faces = texDatas.mipmaps.length / texDatas.mipmapCount;
  24087. for ( let f = 0; f < faces; f ++ ) {
  24088. images[ f ] = { mipmaps: [] };
  24089. for ( let i = 0; i < texDatas.mipmapCount; i ++ ) {
  24090. images[ f ].mipmaps.push( texDatas.mipmaps[ f * texDatas.mipmapCount + i ] );
  24091. images[ f ].format = texDatas.format;
  24092. images[ f ].width = texDatas.width;
  24093. images[ f ].height = texDatas.height;
  24094. }
  24095. }
  24096. texture.image = images;
  24097. } else {
  24098. texture.image.width = texDatas.width;
  24099. texture.image.height = texDatas.height;
  24100. texture.mipmaps = texDatas.mipmaps;
  24101. }
  24102. if ( texDatas.mipmapCount === 1 ) {
  24103. texture.minFilter = LinearFilter;
  24104. }
  24105. texture.format = texDatas.format;
  24106. texture.needsUpdate = true;
  24107. if ( onLoad ) onLoad( texture );
  24108. }, onProgress, onError );
  24109. }
  24110. return texture;
  24111. }
  24112. }
  24113. class ImageLoader extends Loader {
  24114. constructor( manager ) {
  24115. super( manager );
  24116. }
  24117. load( url, onLoad, onProgress, onError ) {
  24118. if ( this.path !== undefined ) url = this.path + url;
  24119. url = this.manager.resolveURL( url );
  24120. const scope = this;
  24121. const cached = Cache.get( url );
  24122. if ( cached !== undefined ) {
  24123. scope.manager.itemStart( url );
  24124. setTimeout( function () {
  24125. if ( onLoad ) onLoad( cached );
  24126. scope.manager.itemEnd( url );
  24127. }, 0 );
  24128. return cached;
  24129. }
  24130. const image = createElementNS( 'img' );
  24131. function onImageLoad() {
  24132. removeEventListeners();
  24133. Cache.add( url, this );
  24134. if ( onLoad ) onLoad( this );
  24135. scope.manager.itemEnd( url );
  24136. }
  24137. function onImageError( event ) {
  24138. removeEventListeners();
  24139. if ( onError ) onError( event );
  24140. scope.manager.itemError( url );
  24141. scope.manager.itemEnd( url );
  24142. }
  24143. function removeEventListeners() {
  24144. image.removeEventListener( 'load', onImageLoad, false );
  24145. image.removeEventListener( 'error', onImageError, false );
  24146. }
  24147. image.addEventListener( 'load', onImageLoad, false );
  24148. image.addEventListener( 'error', onImageError, false );
  24149. if ( url.slice( 0, 5 ) !== 'data:' ) {
  24150. if ( this.crossOrigin !== undefined ) image.crossOrigin = this.crossOrigin;
  24151. }
  24152. scope.manager.itemStart( url );
  24153. image.src = url;
  24154. return image;
  24155. }
  24156. }
  24157. class CubeTextureLoader extends Loader {
  24158. constructor( manager ) {
  24159. super( manager );
  24160. }
  24161. load( urls, onLoad, onProgress, onError ) {
  24162. const texture = new CubeTexture();
  24163. const loader = new ImageLoader( this.manager );
  24164. loader.setCrossOrigin( this.crossOrigin );
  24165. loader.setPath( this.path );
  24166. let loaded = 0;
  24167. function loadTexture( i ) {
  24168. loader.load( urls[ i ], function ( image ) {
  24169. texture.images[ i ] = image;
  24170. loaded ++;
  24171. if ( loaded === 6 ) {
  24172. texture.needsUpdate = true;
  24173. if ( onLoad ) onLoad( texture );
  24174. }
  24175. }, undefined, onError );
  24176. }
  24177. for ( let i = 0; i < urls.length; ++ i ) {
  24178. loadTexture( i );
  24179. }
  24180. return texture;
  24181. }
  24182. }
  24183. /**
  24184. * Abstract Base class to load generic binary textures formats (rgbe, hdr, ...)
  24185. *
  24186. * Sub classes have to implement the parse() method which will be used in load().
  24187. */
  24188. class DataTextureLoader extends Loader {
  24189. constructor( manager ) {
  24190. super( manager );
  24191. }
  24192. load( url, onLoad, onProgress, onError ) {
  24193. const scope = this;
  24194. const texture = new DataTexture();
  24195. const loader = new FileLoader( this.manager );
  24196. loader.setResponseType( 'arraybuffer' );
  24197. loader.setRequestHeader( this.requestHeader );
  24198. loader.setPath( this.path );
  24199. loader.setWithCredentials( scope.withCredentials );
  24200. loader.load( url, function ( buffer ) {
  24201. const texData = scope.parse( buffer );
  24202. if ( ! texData ) return;
  24203. if ( texData.image !== undefined ) {
  24204. texture.image = texData.image;
  24205. } else if ( texData.data !== undefined ) {
  24206. texture.image.width = texData.width;
  24207. texture.image.height = texData.height;
  24208. texture.image.data = texData.data;
  24209. }
  24210. texture.wrapS = texData.wrapS !== undefined ? texData.wrapS : ClampToEdgeWrapping;
  24211. texture.wrapT = texData.wrapT !== undefined ? texData.wrapT : ClampToEdgeWrapping;
  24212. texture.magFilter = texData.magFilter !== undefined ? texData.magFilter : LinearFilter;
  24213. texture.minFilter = texData.minFilter !== undefined ? texData.minFilter : LinearFilter;
  24214. texture.anisotropy = texData.anisotropy !== undefined ? texData.anisotropy : 1;
  24215. if ( texData.encoding !== undefined ) {
  24216. texture.encoding = texData.encoding;
  24217. }
  24218. if ( texData.flipY !== undefined ) {
  24219. texture.flipY = texData.flipY;
  24220. }
  24221. if ( texData.format !== undefined ) {
  24222. texture.format = texData.format;
  24223. }
  24224. if ( texData.type !== undefined ) {
  24225. texture.type = texData.type;
  24226. }
  24227. if ( texData.mipmaps !== undefined ) {
  24228. texture.mipmaps = texData.mipmaps;
  24229. texture.minFilter = LinearMipmapLinearFilter; // presumably...
  24230. }
  24231. if ( texData.mipmapCount === 1 ) {
  24232. texture.minFilter = LinearFilter;
  24233. }
  24234. if ( texData.generateMipmaps !== undefined ) {
  24235. texture.generateMipmaps = texData.generateMipmaps;
  24236. }
  24237. texture.needsUpdate = true;
  24238. if ( onLoad ) onLoad( texture, texData );
  24239. }, onProgress, onError );
  24240. return texture;
  24241. }
  24242. }
  24243. class TextureLoader extends Loader {
  24244. constructor( manager ) {
  24245. super( manager );
  24246. }
  24247. load( url, onLoad, onProgress, onError ) {
  24248. const texture = new Texture();
  24249. const loader = new ImageLoader( this.manager );
  24250. loader.setCrossOrigin( this.crossOrigin );
  24251. loader.setPath( this.path );
  24252. loader.load( url, function ( image ) {
  24253. texture.image = image;
  24254. texture.needsUpdate = true;
  24255. if ( onLoad !== undefined ) {
  24256. onLoad( texture );
  24257. }
  24258. }, onProgress, onError );
  24259. return texture;
  24260. }
  24261. }
  24262. class Light extends Object3D {
  24263. constructor( color, intensity = 1 ) {
  24264. super();
  24265. this.isLight = true;
  24266. this.type = 'Light';
  24267. this.color = new Color( color );
  24268. this.intensity = intensity;
  24269. }
  24270. dispose() {
  24271. // Empty here in base class; some subclasses override.
  24272. }
  24273. copy( source, recursive ) {
  24274. super.copy( source, recursive );
  24275. this.color.copy( source.color );
  24276. this.intensity = source.intensity;
  24277. return this;
  24278. }
  24279. toJSON( meta ) {
  24280. const data = super.toJSON( meta );
  24281. data.object.color = this.color.getHex();
  24282. data.object.intensity = this.intensity;
  24283. if ( this.groundColor !== undefined ) data.object.groundColor = this.groundColor.getHex();
  24284. if ( this.distance !== undefined ) data.object.distance = this.distance;
  24285. if ( this.angle !== undefined ) data.object.angle = this.angle;
  24286. if ( this.decay !== undefined ) data.object.decay = this.decay;
  24287. if ( this.penumbra !== undefined ) data.object.penumbra = this.penumbra;
  24288. if ( this.shadow !== undefined ) data.object.shadow = this.shadow.toJSON();
  24289. return data;
  24290. }
  24291. }
  24292. class HemisphereLight extends Light {
  24293. constructor( skyColor, groundColor, intensity ) {
  24294. super( skyColor, intensity );
  24295. this.isHemisphereLight = true;
  24296. this.type = 'HemisphereLight';
  24297. this.position.copy( Object3D.DEFAULT_UP );
  24298. this.updateMatrix();
  24299. this.groundColor = new Color( groundColor );
  24300. }
  24301. copy( source, recursive ) {
  24302. super.copy( source, recursive );
  24303. this.groundColor.copy( source.groundColor );
  24304. return this;
  24305. }
  24306. }
  24307. const _projScreenMatrix$1 = /*@__PURE__*/ new Matrix4();
  24308. const _lightPositionWorld$1 = /*@__PURE__*/ new Vector3();
  24309. const _lookTarget$1 = /*@__PURE__*/ new Vector3();
  24310. class LightShadow {
  24311. constructor( camera ) {
  24312. this.camera = camera;
  24313. this.bias = 0;
  24314. this.normalBias = 0;
  24315. this.radius = 1;
  24316. this.blurSamples = 8;
  24317. this.mapSize = new Vector2( 512, 512 );
  24318. this.map = null;
  24319. this.mapPass = null;
  24320. this.matrix = new Matrix4();
  24321. this.autoUpdate = true;
  24322. this.needsUpdate = false;
  24323. this._frustum = new Frustum();
  24324. this._frameExtents = new Vector2( 1, 1 );
  24325. this._viewportCount = 1;
  24326. this._viewports = [
  24327. new Vector4( 0, 0, 1, 1 )
  24328. ];
  24329. }
  24330. getViewportCount() {
  24331. return this._viewportCount;
  24332. }
  24333. getFrustum() {
  24334. return this._frustum;
  24335. }
  24336. updateMatrices( light ) {
  24337. const shadowCamera = this.camera;
  24338. const shadowMatrix = this.matrix;
  24339. _lightPositionWorld$1.setFromMatrixPosition( light.matrixWorld );
  24340. shadowCamera.position.copy( _lightPositionWorld$1 );
  24341. _lookTarget$1.setFromMatrixPosition( light.target.matrixWorld );
  24342. shadowCamera.lookAt( _lookTarget$1 );
  24343. shadowCamera.updateMatrixWorld();
  24344. _projScreenMatrix$1.multiplyMatrices( shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse );
  24345. this._frustum.setFromProjectionMatrix( _projScreenMatrix$1 );
  24346. shadowMatrix.set(
  24347. 0.5, 0.0, 0.0, 0.5,
  24348. 0.0, 0.5, 0.0, 0.5,
  24349. 0.0, 0.0, 0.5, 0.5,
  24350. 0.0, 0.0, 0.0, 1.0
  24351. );
  24352. shadowMatrix.multiply( _projScreenMatrix$1 );
  24353. }
  24354. getViewport( viewportIndex ) {
  24355. return this._viewports[ viewportIndex ];
  24356. }
  24357. getFrameExtents() {
  24358. return this._frameExtents;
  24359. }
  24360. dispose() {
  24361. if ( this.map ) {
  24362. this.map.dispose();
  24363. }
  24364. if ( this.mapPass ) {
  24365. this.mapPass.dispose();
  24366. }
  24367. }
  24368. copy( source ) {
  24369. this.camera = source.camera.clone();
  24370. this.bias = source.bias;
  24371. this.radius = source.radius;
  24372. this.mapSize.copy( source.mapSize );
  24373. return this;
  24374. }
  24375. clone() {
  24376. return new this.constructor().copy( this );
  24377. }
  24378. toJSON() {
  24379. const object = {};
  24380. if ( this.bias !== 0 ) object.bias = this.bias;
  24381. if ( this.normalBias !== 0 ) object.normalBias = this.normalBias;
  24382. if ( this.radius !== 1 ) object.radius = this.radius;
  24383. if ( this.mapSize.x !== 512 || this.mapSize.y !== 512 ) object.mapSize = this.mapSize.toArray();
  24384. object.camera = this.camera.toJSON( false ).object;
  24385. delete object.camera.matrix;
  24386. return object;
  24387. }
  24388. }
  24389. class SpotLightShadow extends LightShadow {
  24390. constructor() {
  24391. super( new PerspectiveCamera( 50, 1, 0.5, 500 ) );
  24392. this.isSpotLightShadow = true;
  24393. this.focus = 1;
  24394. }
  24395. updateMatrices( light ) {
  24396. const camera = this.camera;
  24397. const fov = RAD2DEG * 2 * light.angle * this.focus;
  24398. const aspect = this.mapSize.width / this.mapSize.height;
  24399. const far = light.distance || camera.far;
  24400. if ( fov !== camera.fov || aspect !== camera.aspect || far !== camera.far ) {
  24401. camera.fov = fov;
  24402. camera.aspect = aspect;
  24403. camera.far = far;
  24404. camera.updateProjectionMatrix();
  24405. }
  24406. super.updateMatrices( light );
  24407. }
  24408. copy( source ) {
  24409. super.copy( source );
  24410. this.focus = source.focus;
  24411. return this;
  24412. }
  24413. }
  24414. class SpotLight extends Light {
  24415. constructor( color, intensity, distance = 0, angle = Math.PI / 3, penumbra = 0, decay = 2 ) {
  24416. super( color, intensity );
  24417. this.isSpotLight = true;
  24418. this.type = 'SpotLight';
  24419. this.position.copy( Object3D.DEFAULT_UP );
  24420. this.updateMatrix();
  24421. this.target = new Object3D();
  24422. this.distance = distance;
  24423. this.angle = angle;
  24424. this.penumbra = penumbra;
  24425. this.decay = decay;
  24426. this.map = null;
  24427. this.shadow = new SpotLightShadow();
  24428. }
  24429. get power() {
  24430. // compute the light's luminous power (in lumens) from its intensity (in candela)
  24431. // by convention for a spotlight, luminous power (lm) = π * luminous intensity (cd)
  24432. return this.intensity * Math.PI;
  24433. }
  24434. set power( power ) {
  24435. // set the light's intensity (in candela) from the desired luminous power (in lumens)
  24436. this.intensity = power / Math.PI;
  24437. }
  24438. dispose() {
  24439. this.shadow.dispose();
  24440. }
  24441. copy( source, recursive ) {
  24442. super.copy( source, recursive );
  24443. this.distance = source.distance;
  24444. this.angle = source.angle;
  24445. this.penumbra = source.penumbra;
  24446. this.decay = source.decay;
  24447. this.target = source.target.clone();
  24448. this.shadow = source.shadow.clone();
  24449. return this;
  24450. }
  24451. }
  24452. const _projScreenMatrix = /*@__PURE__*/ new Matrix4();
  24453. const _lightPositionWorld = /*@__PURE__*/ new Vector3();
  24454. const _lookTarget = /*@__PURE__*/ new Vector3();
  24455. class PointLightShadow extends LightShadow {
  24456. constructor() {
  24457. super( new PerspectiveCamera( 90, 1, 0.5, 500 ) );
  24458. this.isPointLightShadow = true;
  24459. this._frameExtents = new Vector2( 4, 2 );
  24460. this._viewportCount = 6;
  24461. this._viewports = [
  24462. // These viewports map a cube-map onto a 2D texture with the
  24463. // following orientation:
  24464. //
  24465. // xzXZ
  24466. // y Y
  24467. //
  24468. // X - Positive x direction
  24469. // x - Negative x direction
  24470. // Y - Positive y direction
  24471. // y - Negative y direction
  24472. // Z - Positive z direction
  24473. // z - Negative z direction
  24474. // positive X
  24475. new Vector4( 2, 1, 1, 1 ),
  24476. // negative X
  24477. new Vector4( 0, 1, 1, 1 ),
  24478. // positive Z
  24479. new Vector4( 3, 1, 1, 1 ),
  24480. // negative Z
  24481. new Vector4( 1, 1, 1, 1 ),
  24482. // positive Y
  24483. new Vector4( 3, 0, 1, 1 ),
  24484. // negative Y
  24485. new Vector4( 1, 0, 1, 1 )
  24486. ];
  24487. this._cubeDirections = [
  24488. new Vector3( 1, 0, 0 ), new Vector3( - 1, 0, 0 ), new Vector3( 0, 0, 1 ),
  24489. new Vector3( 0, 0, - 1 ), new Vector3( 0, 1, 0 ), new Vector3( 0, - 1, 0 )
  24490. ];
  24491. this._cubeUps = [
  24492. new Vector3( 0, 1, 0 ), new Vector3( 0, 1, 0 ), new Vector3( 0, 1, 0 ),
  24493. new Vector3( 0, 1, 0 ), new Vector3( 0, 0, 1 ), new Vector3( 0, 0, - 1 )
  24494. ];
  24495. }
  24496. updateMatrices( light, viewportIndex = 0 ) {
  24497. const camera = this.camera;
  24498. const shadowMatrix = this.matrix;
  24499. const far = light.distance || camera.far;
  24500. if ( far !== camera.far ) {
  24501. camera.far = far;
  24502. camera.updateProjectionMatrix();
  24503. }
  24504. _lightPositionWorld.setFromMatrixPosition( light.matrixWorld );
  24505. camera.position.copy( _lightPositionWorld );
  24506. _lookTarget.copy( camera.position );
  24507. _lookTarget.add( this._cubeDirections[ viewportIndex ] );
  24508. camera.up.copy( this._cubeUps[ viewportIndex ] );
  24509. camera.lookAt( _lookTarget );
  24510. camera.updateMatrixWorld();
  24511. shadowMatrix.makeTranslation( - _lightPositionWorld.x, - _lightPositionWorld.y, - _lightPositionWorld.z );
  24512. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  24513. this._frustum.setFromProjectionMatrix( _projScreenMatrix );
  24514. }
  24515. }
  24516. class PointLight extends Light {
  24517. constructor( color, intensity, distance = 0, decay = 2 ) {
  24518. super( color, intensity );
  24519. this.isPointLight = true;
  24520. this.type = 'PointLight';
  24521. this.distance = distance;
  24522. this.decay = decay;
  24523. this.shadow = new PointLightShadow();
  24524. }
  24525. get power() {
  24526. // compute the light's luminous power (in lumens) from its intensity (in candela)
  24527. // for an isotropic light source, luminous power (lm) = 4 π luminous intensity (cd)
  24528. return this.intensity * 4 * Math.PI;
  24529. }
  24530. set power( power ) {
  24531. // set the light's intensity (in candela) from the desired luminous power (in lumens)
  24532. this.intensity = power / ( 4 * Math.PI );
  24533. }
  24534. dispose() {
  24535. this.shadow.dispose();
  24536. }
  24537. copy( source, recursive ) {
  24538. super.copy( source, recursive );
  24539. this.distance = source.distance;
  24540. this.decay = source.decay;
  24541. this.shadow = source.shadow.clone();
  24542. return this;
  24543. }
  24544. }
  24545. class DirectionalLightShadow extends LightShadow {
  24546. constructor() {
  24547. super( new OrthographicCamera( - 5, 5, 5, - 5, 0.5, 500 ) );
  24548. this.isDirectionalLightShadow = true;
  24549. }
  24550. }
  24551. class DirectionalLight extends Light {
  24552. constructor( color, intensity ) {
  24553. super( color, intensity );
  24554. this.isDirectionalLight = true;
  24555. this.type = 'DirectionalLight';
  24556. this.position.copy( Object3D.DEFAULT_UP );
  24557. this.updateMatrix();
  24558. this.target = new Object3D();
  24559. this.shadow = new DirectionalLightShadow();
  24560. }
  24561. dispose() {
  24562. this.shadow.dispose();
  24563. }
  24564. copy( source ) {
  24565. super.copy( source );
  24566. this.target = source.target.clone();
  24567. this.shadow = source.shadow.clone();
  24568. return this;
  24569. }
  24570. }
  24571. class AmbientLight extends Light {
  24572. constructor( color, intensity ) {
  24573. super( color, intensity );
  24574. this.isAmbientLight = true;
  24575. this.type = 'AmbientLight';
  24576. }
  24577. }
  24578. class RectAreaLight extends Light {
  24579. constructor( color, intensity, width = 10, height = 10 ) {
  24580. super( color, intensity );
  24581. this.isRectAreaLight = true;
  24582. this.type = 'RectAreaLight';
  24583. this.width = width;
  24584. this.height = height;
  24585. }
  24586. get power() {
  24587. // compute the light's luminous power (in lumens) from its intensity (in nits)
  24588. return this.intensity * this.width * this.height * Math.PI;
  24589. }
  24590. set power( power ) {
  24591. // set the light's intensity (in nits) from the desired luminous power (in lumens)
  24592. this.intensity = power / ( this.width * this.height * Math.PI );
  24593. }
  24594. copy( source ) {
  24595. super.copy( source );
  24596. this.width = source.width;
  24597. this.height = source.height;
  24598. return this;
  24599. }
  24600. toJSON( meta ) {
  24601. const data = super.toJSON( meta );
  24602. data.object.width = this.width;
  24603. data.object.height = this.height;
  24604. return data;
  24605. }
  24606. }
  24607. /**
  24608. * Primary reference:
  24609. * https://graphics.stanford.edu/papers/envmap/envmap.pdf
  24610. *
  24611. * Secondary reference:
  24612. * https://www.ppsloan.org/publications/StupidSH36.pdf
  24613. */
  24614. // 3-band SH defined by 9 coefficients
  24615. class SphericalHarmonics3 {
  24616. constructor() {
  24617. this.isSphericalHarmonics3 = true;
  24618. this.coefficients = [];
  24619. for ( let i = 0; i < 9; i ++ ) {
  24620. this.coefficients.push( new Vector3() );
  24621. }
  24622. }
  24623. set( coefficients ) {
  24624. for ( let i = 0; i < 9; i ++ ) {
  24625. this.coefficients[ i ].copy( coefficients[ i ] );
  24626. }
  24627. return this;
  24628. }
  24629. zero() {
  24630. for ( let i = 0; i < 9; i ++ ) {
  24631. this.coefficients[ i ].set( 0, 0, 0 );
  24632. }
  24633. return this;
  24634. }
  24635. // get the radiance in the direction of the normal
  24636. // target is a Vector3
  24637. getAt( normal, target ) {
  24638. // normal is assumed to be unit length
  24639. const x = normal.x, y = normal.y, z = normal.z;
  24640. const coeff = this.coefficients;
  24641. // band 0
  24642. target.copy( coeff[ 0 ] ).multiplyScalar( 0.282095 );
  24643. // band 1
  24644. target.addScaledVector( coeff[ 1 ], 0.488603 * y );
  24645. target.addScaledVector( coeff[ 2 ], 0.488603 * z );
  24646. target.addScaledVector( coeff[ 3 ], 0.488603 * x );
  24647. // band 2
  24648. target.addScaledVector( coeff[ 4 ], 1.092548 * ( x * y ) );
  24649. target.addScaledVector( coeff[ 5 ], 1.092548 * ( y * z ) );
  24650. target.addScaledVector( coeff[ 6 ], 0.315392 * ( 3.0 * z * z - 1.0 ) );
  24651. target.addScaledVector( coeff[ 7 ], 1.092548 * ( x * z ) );
  24652. target.addScaledVector( coeff[ 8 ], 0.546274 * ( x * x - y * y ) );
  24653. return target;
  24654. }
  24655. // get the irradiance (radiance convolved with cosine lobe) in the direction of the normal
  24656. // target is a Vector3
  24657. // https://graphics.stanford.edu/papers/envmap/envmap.pdf
  24658. getIrradianceAt( normal, target ) {
  24659. // normal is assumed to be unit length
  24660. const x = normal.x, y = normal.y, z = normal.z;
  24661. const coeff = this.coefficients;
  24662. // band 0
  24663. target.copy( coeff[ 0 ] ).multiplyScalar( 0.886227 ); // π * 0.282095
  24664. // band 1
  24665. target.addScaledVector( coeff[ 1 ], 2.0 * 0.511664 * y ); // ( 2 * π / 3 ) * 0.488603
  24666. target.addScaledVector( coeff[ 2 ], 2.0 * 0.511664 * z );
  24667. target.addScaledVector( coeff[ 3 ], 2.0 * 0.511664 * x );
  24668. // band 2
  24669. target.addScaledVector( coeff[ 4 ], 2.0 * 0.429043 * x * y ); // ( π / 4 ) * 1.092548
  24670. target.addScaledVector( coeff[ 5 ], 2.0 * 0.429043 * y * z );
  24671. target.addScaledVector( coeff[ 6 ], 0.743125 * z * z - 0.247708 ); // ( π / 4 ) * 0.315392 * 3
  24672. target.addScaledVector( coeff[ 7 ], 2.0 * 0.429043 * x * z );
  24673. target.addScaledVector( coeff[ 8 ], 0.429043 * ( x * x - y * y ) ); // ( π / 4 ) * 0.546274
  24674. return target;
  24675. }
  24676. add( sh ) {
  24677. for ( let i = 0; i < 9; i ++ ) {
  24678. this.coefficients[ i ].add( sh.coefficients[ i ] );
  24679. }
  24680. return this;
  24681. }
  24682. addScaledSH( sh, s ) {
  24683. for ( let i = 0; i < 9; i ++ ) {
  24684. this.coefficients[ i ].addScaledVector( sh.coefficients[ i ], s );
  24685. }
  24686. return this;
  24687. }
  24688. scale( s ) {
  24689. for ( let i = 0; i < 9; i ++ ) {
  24690. this.coefficients[ i ].multiplyScalar( s );
  24691. }
  24692. return this;
  24693. }
  24694. lerp( sh, alpha ) {
  24695. for ( let i = 0; i < 9; i ++ ) {
  24696. this.coefficients[ i ].lerp( sh.coefficients[ i ], alpha );
  24697. }
  24698. return this;
  24699. }
  24700. equals( sh ) {
  24701. for ( let i = 0; i < 9; i ++ ) {
  24702. if ( ! this.coefficients[ i ].equals( sh.coefficients[ i ] ) ) {
  24703. return false;
  24704. }
  24705. }
  24706. return true;
  24707. }
  24708. copy( sh ) {
  24709. return this.set( sh.coefficients );
  24710. }
  24711. clone() {
  24712. return new this.constructor().copy( this );
  24713. }
  24714. fromArray( array, offset = 0 ) {
  24715. const coefficients = this.coefficients;
  24716. for ( let i = 0; i < 9; i ++ ) {
  24717. coefficients[ i ].fromArray( array, offset + ( i * 3 ) );
  24718. }
  24719. return this;
  24720. }
  24721. toArray( array = [], offset = 0 ) {
  24722. const coefficients = this.coefficients;
  24723. for ( let i = 0; i < 9; i ++ ) {
  24724. coefficients[ i ].toArray( array, offset + ( i * 3 ) );
  24725. }
  24726. return array;
  24727. }
  24728. // evaluate the basis functions
  24729. // shBasis is an Array[ 9 ]
  24730. static getBasisAt( normal, shBasis ) {
  24731. // normal is assumed to be unit length
  24732. const x = normal.x, y = normal.y, z = normal.z;
  24733. // band 0
  24734. shBasis[ 0 ] = 0.282095;
  24735. // band 1
  24736. shBasis[ 1 ] = 0.488603 * y;
  24737. shBasis[ 2 ] = 0.488603 * z;
  24738. shBasis[ 3 ] = 0.488603 * x;
  24739. // band 2
  24740. shBasis[ 4 ] = 1.092548 * x * y;
  24741. shBasis[ 5 ] = 1.092548 * y * z;
  24742. shBasis[ 6 ] = 0.315392 * ( 3 * z * z - 1 );
  24743. shBasis[ 7 ] = 1.092548 * x * z;
  24744. shBasis[ 8 ] = 0.546274 * ( x * x - y * y );
  24745. }
  24746. }
  24747. class LightProbe extends Light {
  24748. constructor( sh = new SphericalHarmonics3(), intensity = 1 ) {
  24749. super( undefined, intensity );
  24750. this.isLightProbe = true;
  24751. this.sh = sh;
  24752. }
  24753. copy( source ) {
  24754. super.copy( source );
  24755. this.sh.copy( source.sh );
  24756. return this;
  24757. }
  24758. fromJSON( json ) {
  24759. this.intensity = json.intensity; // TODO: Move this bit to Light.fromJSON();
  24760. this.sh.fromArray( json.sh );
  24761. return this;
  24762. }
  24763. toJSON( meta ) {
  24764. const data = super.toJSON( meta );
  24765. data.object.sh = this.sh.toArray();
  24766. return data;
  24767. }
  24768. }
  24769. class MaterialLoader extends Loader {
  24770. constructor( manager ) {
  24771. super( manager );
  24772. this.textures = {};
  24773. }
  24774. load( url, onLoad, onProgress, onError ) {
  24775. const scope = this;
  24776. const loader = new FileLoader( scope.manager );
  24777. loader.setPath( scope.path );
  24778. loader.setRequestHeader( scope.requestHeader );
  24779. loader.setWithCredentials( scope.withCredentials );
  24780. loader.load( url, function ( text ) {
  24781. try {
  24782. onLoad( scope.parse( JSON.parse( text ) ) );
  24783. } catch ( e ) {
  24784. if ( onError ) {
  24785. onError( e );
  24786. } else {
  24787. console.error( e );
  24788. }
  24789. scope.manager.itemError( url );
  24790. }
  24791. }, onProgress, onError );
  24792. }
  24793. parse( json ) {
  24794. const textures = this.textures;
  24795. function getTexture( name ) {
  24796. if ( textures[ name ] === undefined ) {
  24797. console.warn( 'THREE.MaterialLoader: Undefined texture', name );
  24798. }
  24799. return textures[ name ];
  24800. }
  24801. const material = MaterialLoader.createMaterialFromType( json.type );
  24802. if ( json.uuid !== undefined ) material.uuid = json.uuid;
  24803. if ( json.name !== undefined ) material.name = json.name;
  24804. if ( json.color !== undefined && material.color !== undefined ) material.color.setHex( json.color );
  24805. if ( json.roughness !== undefined ) material.roughness = json.roughness;
  24806. if ( json.metalness !== undefined ) material.metalness = json.metalness;
  24807. if ( json.sheen !== undefined ) material.sheen = json.sheen;
  24808. if ( json.sheenColor !== undefined ) material.sheenColor = new Color().setHex( json.sheenColor );
  24809. if ( json.sheenRoughness !== undefined ) material.sheenRoughness = json.sheenRoughness;
  24810. if ( json.emissive !== undefined && material.emissive !== undefined ) material.emissive.setHex( json.emissive );
  24811. if ( json.specular !== undefined && material.specular !== undefined ) material.specular.setHex( json.specular );
  24812. if ( json.specularIntensity !== undefined ) material.specularIntensity = json.specularIntensity;
  24813. if ( json.specularColor !== undefined && material.specularColor !== undefined ) material.specularColor.setHex( json.specularColor );
  24814. if ( json.shininess !== undefined ) material.shininess = json.shininess;
  24815. if ( json.clearcoat !== undefined ) material.clearcoat = json.clearcoat;
  24816. if ( json.clearcoatRoughness !== undefined ) material.clearcoatRoughness = json.clearcoatRoughness;
  24817. if ( json.iridescence !== undefined ) material.iridescence = json.iridescence;
  24818. if ( json.iridescenceIOR !== undefined ) material.iridescenceIOR = json.iridescenceIOR;
  24819. if ( json.iridescenceThicknessRange !== undefined ) material.iridescenceThicknessRange = json.iridescenceThicknessRange;
  24820. if ( json.transmission !== undefined ) material.transmission = json.transmission;
  24821. if ( json.thickness !== undefined ) material.thickness = json.thickness;
  24822. if ( json.attenuationDistance !== undefined ) material.attenuationDistance = json.attenuationDistance;
  24823. if ( json.attenuationColor !== undefined && material.attenuationColor !== undefined ) material.attenuationColor.setHex( json.attenuationColor );
  24824. if ( json.fog !== undefined ) material.fog = json.fog;
  24825. if ( json.flatShading !== undefined ) material.flatShading = json.flatShading;
  24826. if ( json.blending !== undefined ) material.blending = json.blending;
  24827. if ( json.combine !== undefined ) material.combine = json.combine;
  24828. if ( json.side !== undefined ) material.side = json.side;
  24829. if ( json.shadowSide !== undefined ) material.shadowSide = json.shadowSide;
  24830. if ( json.opacity !== undefined ) material.opacity = json.opacity;
  24831. if ( json.transparent !== undefined ) material.transparent = json.transparent;
  24832. if ( json.alphaTest !== undefined ) material.alphaTest = json.alphaTest;
  24833. if ( json.depthTest !== undefined ) material.depthTest = json.depthTest;
  24834. if ( json.depthWrite !== undefined ) material.depthWrite = json.depthWrite;
  24835. if ( json.colorWrite !== undefined ) material.colorWrite = json.colorWrite;
  24836. if ( json.stencilWrite !== undefined ) material.stencilWrite = json.stencilWrite;
  24837. if ( json.stencilWriteMask !== undefined ) material.stencilWriteMask = json.stencilWriteMask;
  24838. if ( json.stencilFunc !== undefined ) material.stencilFunc = json.stencilFunc;
  24839. if ( json.stencilRef !== undefined ) material.stencilRef = json.stencilRef;
  24840. if ( json.stencilFuncMask !== undefined ) material.stencilFuncMask = json.stencilFuncMask;
  24841. if ( json.stencilFail !== undefined ) material.stencilFail = json.stencilFail;
  24842. if ( json.stencilZFail !== undefined ) material.stencilZFail = json.stencilZFail;
  24843. if ( json.stencilZPass !== undefined ) material.stencilZPass = json.stencilZPass;
  24844. if ( json.wireframe !== undefined ) material.wireframe = json.wireframe;
  24845. if ( json.wireframeLinewidth !== undefined ) material.wireframeLinewidth = json.wireframeLinewidth;
  24846. if ( json.wireframeLinecap !== undefined ) material.wireframeLinecap = json.wireframeLinecap;
  24847. if ( json.wireframeLinejoin !== undefined ) material.wireframeLinejoin = json.wireframeLinejoin;
  24848. if ( json.rotation !== undefined ) material.rotation = json.rotation;
  24849. if ( json.linewidth !== 1 ) material.linewidth = json.linewidth;
  24850. if ( json.dashSize !== undefined ) material.dashSize = json.dashSize;
  24851. if ( json.gapSize !== undefined ) material.gapSize = json.gapSize;
  24852. if ( json.scale !== undefined ) material.scale = json.scale;
  24853. if ( json.polygonOffset !== undefined ) material.polygonOffset = json.polygonOffset;
  24854. if ( json.polygonOffsetFactor !== undefined ) material.polygonOffsetFactor = json.polygonOffsetFactor;
  24855. if ( json.polygonOffsetUnits !== undefined ) material.polygonOffsetUnits = json.polygonOffsetUnits;
  24856. if ( json.dithering !== undefined ) material.dithering = json.dithering;
  24857. if ( json.alphaToCoverage !== undefined ) material.alphaToCoverage = json.alphaToCoverage;
  24858. if ( json.premultipliedAlpha !== undefined ) material.premultipliedAlpha = json.premultipliedAlpha;
  24859. if ( json.forceSinglePass !== undefined ) material.forceSinglePass = json.forceSinglePass;
  24860. if ( json.visible !== undefined ) material.visible = json.visible;
  24861. if ( json.toneMapped !== undefined ) material.toneMapped = json.toneMapped;
  24862. if ( json.userData !== undefined ) material.userData = json.userData;
  24863. if ( json.vertexColors !== undefined ) {
  24864. if ( typeof json.vertexColors === 'number' ) {
  24865. material.vertexColors = ( json.vertexColors > 0 ) ? true : false;
  24866. } else {
  24867. material.vertexColors = json.vertexColors;
  24868. }
  24869. }
  24870. // Shader Material
  24871. if ( json.uniforms !== undefined ) {
  24872. for ( const name in json.uniforms ) {
  24873. const uniform = json.uniforms[ name ];
  24874. material.uniforms[ name ] = {};
  24875. switch ( uniform.type ) {
  24876. case 't':
  24877. material.uniforms[ name ].value = getTexture( uniform.value );
  24878. break;
  24879. case 'c':
  24880. material.uniforms[ name ].value = new Color().setHex( uniform.value );
  24881. break;
  24882. case 'v2':
  24883. material.uniforms[ name ].value = new Vector2().fromArray( uniform.value );
  24884. break;
  24885. case 'v3':
  24886. material.uniforms[ name ].value = new Vector3().fromArray( uniform.value );
  24887. break;
  24888. case 'v4':
  24889. material.uniforms[ name ].value = new Vector4().fromArray( uniform.value );
  24890. break;
  24891. case 'm3':
  24892. material.uniforms[ name ].value = new Matrix3().fromArray( uniform.value );
  24893. break;
  24894. case 'm4':
  24895. material.uniforms[ name ].value = new Matrix4().fromArray( uniform.value );
  24896. break;
  24897. default:
  24898. material.uniforms[ name ].value = uniform.value;
  24899. }
  24900. }
  24901. }
  24902. if ( json.defines !== undefined ) material.defines = json.defines;
  24903. if ( json.vertexShader !== undefined ) material.vertexShader = json.vertexShader;
  24904. if ( json.fragmentShader !== undefined ) material.fragmentShader = json.fragmentShader;
  24905. if ( json.glslVersion !== undefined ) material.glslVersion = json.glslVersion;
  24906. if ( json.extensions !== undefined ) {
  24907. for ( const key in json.extensions ) {
  24908. material.extensions[ key ] = json.extensions[ key ];
  24909. }
  24910. }
  24911. // for PointsMaterial
  24912. if ( json.size !== undefined ) material.size = json.size;
  24913. if ( json.sizeAttenuation !== undefined ) material.sizeAttenuation = json.sizeAttenuation;
  24914. // maps
  24915. if ( json.map !== undefined ) material.map = getTexture( json.map );
  24916. if ( json.matcap !== undefined ) material.matcap = getTexture( json.matcap );
  24917. if ( json.alphaMap !== undefined ) material.alphaMap = getTexture( json.alphaMap );
  24918. if ( json.bumpMap !== undefined ) material.bumpMap = getTexture( json.bumpMap );
  24919. if ( json.bumpScale !== undefined ) material.bumpScale = json.bumpScale;
  24920. if ( json.normalMap !== undefined ) material.normalMap = getTexture( json.normalMap );
  24921. if ( json.normalMapType !== undefined ) material.normalMapType = json.normalMapType;
  24922. if ( json.normalScale !== undefined ) {
  24923. let normalScale = json.normalScale;
  24924. if ( Array.isArray( normalScale ) === false ) {
  24925. // Blender exporter used to export a scalar. See #7459
  24926. normalScale = [ normalScale, normalScale ];
  24927. }
  24928. material.normalScale = new Vector2().fromArray( normalScale );
  24929. }
  24930. if ( json.displacementMap !== undefined ) material.displacementMap = getTexture( json.displacementMap );
  24931. if ( json.displacementScale !== undefined ) material.displacementScale = json.displacementScale;
  24932. if ( json.displacementBias !== undefined ) material.displacementBias = json.displacementBias;
  24933. if ( json.roughnessMap !== undefined ) material.roughnessMap = getTexture( json.roughnessMap );
  24934. if ( json.metalnessMap !== undefined ) material.metalnessMap = getTexture( json.metalnessMap );
  24935. if ( json.emissiveMap !== undefined ) material.emissiveMap = getTexture( json.emissiveMap );
  24936. if ( json.emissiveIntensity !== undefined ) material.emissiveIntensity = json.emissiveIntensity;
  24937. if ( json.specularMap !== undefined ) material.specularMap = getTexture( json.specularMap );
  24938. if ( json.specularIntensityMap !== undefined ) material.specularIntensityMap = getTexture( json.specularIntensityMap );
  24939. if ( json.specularColorMap !== undefined ) material.specularColorMap = getTexture( json.specularColorMap );
  24940. if ( json.envMap !== undefined ) material.envMap = getTexture( json.envMap );
  24941. if ( json.envMapIntensity !== undefined ) material.envMapIntensity = json.envMapIntensity;
  24942. if ( json.reflectivity !== undefined ) material.reflectivity = json.reflectivity;
  24943. if ( json.refractionRatio !== undefined ) material.refractionRatio = json.refractionRatio;
  24944. if ( json.lightMap !== undefined ) material.lightMap = getTexture( json.lightMap );
  24945. if ( json.lightMapIntensity !== undefined ) material.lightMapIntensity = json.lightMapIntensity;
  24946. if ( json.aoMap !== undefined ) material.aoMap = getTexture( json.aoMap );
  24947. if ( json.aoMapIntensity !== undefined ) material.aoMapIntensity = json.aoMapIntensity;
  24948. if ( json.gradientMap !== undefined ) material.gradientMap = getTexture( json.gradientMap );
  24949. if ( json.clearcoatMap !== undefined ) material.clearcoatMap = getTexture( json.clearcoatMap );
  24950. if ( json.clearcoatRoughnessMap !== undefined ) material.clearcoatRoughnessMap = getTexture( json.clearcoatRoughnessMap );
  24951. if ( json.clearcoatNormalMap !== undefined ) material.clearcoatNormalMap = getTexture( json.clearcoatNormalMap );
  24952. if ( json.clearcoatNormalScale !== undefined ) material.clearcoatNormalScale = new Vector2().fromArray( json.clearcoatNormalScale );
  24953. if ( json.iridescenceMap !== undefined ) material.iridescenceMap = getTexture( json.iridescenceMap );
  24954. if ( json.iridescenceThicknessMap !== undefined ) material.iridescenceThicknessMap = getTexture( json.iridescenceThicknessMap );
  24955. if ( json.transmissionMap !== undefined ) material.transmissionMap = getTexture( json.transmissionMap );
  24956. if ( json.thicknessMap !== undefined ) material.thicknessMap = getTexture( json.thicknessMap );
  24957. if ( json.sheenColorMap !== undefined ) material.sheenColorMap = getTexture( json.sheenColorMap );
  24958. if ( json.sheenRoughnessMap !== undefined ) material.sheenRoughnessMap = getTexture( json.sheenRoughnessMap );
  24959. return material;
  24960. }
  24961. setTextures( value ) {
  24962. this.textures = value;
  24963. return this;
  24964. }
  24965. static createMaterialFromType( type ) {
  24966. const materialLib = {
  24967. ShadowMaterial,
  24968. SpriteMaterial,
  24969. RawShaderMaterial,
  24970. ShaderMaterial,
  24971. PointsMaterial,
  24972. MeshPhysicalMaterial,
  24973. MeshStandardMaterial,
  24974. MeshPhongMaterial,
  24975. MeshToonMaterial,
  24976. MeshNormalMaterial,
  24977. MeshLambertMaterial,
  24978. MeshDepthMaterial,
  24979. MeshDistanceMaterial,
  24980. MeshBasicMaterial,
  24981. MeshMatcapMaterial,
  24982. LineDashedMaterial,
  24983. LineBasicMaterial,
  24984. Material
  24985. };
  24986. return new materialLib[ type ]();
  24987. }
  24988. }
  24989. class LoaderUtils {
  24990. static decodeText( array ) {
  24991. if ( typeof TextDecoder !== 'undefined' ) {
  24992. return new TextDecoder().decode( array );
  24993. }
  24994. // Avoid the String.fromCharCode.apply(null, array) shortcut, which
  24995. // throws a "maximum call stack size exceeded" error for large arrays.
  24996. let s = '';
  24997. for ( let i = 0, il = array.length; i < il; i ++ ) {
  24998. // Implicitly assumes little-endian.
  24999. s += String.fromCharCode( array[ i ] );
  25000. }
  25001. try {
  25002. // merges multi-byte utf-8 characters.
  25003. return decodeURIComponent( escape( s ) );
  25004. } catch ( e ) { // see #16358
  25005. return s;
  25006. }
  25007. }
  25008. static extractUrlBase( url ) {
  25009. const index = url.lastIndexOf( '/' );
  25010. if ( index === - 1 ) return './';
  25011. return url.slice( 0, index + 1 );
  25012. }
  25013. static resolveURL( url, path ) {
  25014. // Invalid URL
  25015. if ( typeof url !== 'string' || url === '' ) return '';
  25016. // Host Relative URL
  25017. if ( /^https?:\/\//i.test( path ) && /^\//.test( url ) ) {
  25018. path = path.replace( /(^https?:\/\/[^\/]+).*/i, '$1' );
  25019. }
  25020. // Absolute URL http://,https://,//
  25021. if ( /^(https?:)?\/\//i.test( url ) ) return url;
  25022. // Data URI
  25023. if ( /^data:.*,.*$/i.test( url ) ) return url;
  25024. // Blob URL
  25025. if ( /^blob:.*$/i.test( url ) ) return url;
  25026. // Relative URL
  25027. return path + url;
  25028. }
  25029. }
  25030. class InstancedBufferGeometry extends BufferGeometry {
  25031. constructor() {
  25032. super();
  25033. this.isInstancedBufferGeometry = true;
  25034. this.type = 'InstancedBufferGeometry';
  25035. this.instanceCount = Infinity;
  25036. }
  25037. copy( source ) {
  25038. super.copy( source );
  25039. this.instanceCount = source.instanceCount;
  25040. return this;
  25041. }
  25042. toJSON() {
  25043. const data = super.toJSON();
  25044. data.instanceCount = this.instanceCount;
  25045. data.isInstancedBufferGeometry = true;
  25046. return data;
  25047. }
  25048. }
  25049. class BufferGeometryLoader extends Loader {
  25050. constructor( manager ) {
  25051. super( manager );
  25052. }
  25053. load( url, onLoad, onProgress, onError ) {
  25054. const scope = this;
  25055. const loader = new FileLoader( scope.manager );
  25056. loader.setPath( scope.path );
  25057. loader.setRequestHeader( scope.requestHeader );
  25058. loader.setWithCredentials( scope.withCredentials );
  25059. loader.load( url, function ( text ) {
  25060. try {
  25061. onLoad( scope.parse( JSON.parse( text ) ) );
  25062. } catch ( e ) {
  25063. if ( onError ) {
  25064. onError( e );
  25065. } else {
  25066. console.error( e );
  25067. }
  25068. scope.manager.itemError( url );
  25069. }
  25070. }, onProgress, onError );
  25071. }
  25072. parse( json ) {
  25073. const interleavedBufferMap = {};
  25074. const arrayBufferMap = {};
  25075. function getInterleavedBuffer( json, uuid ) {
  25076. if ( interleavedBufferMap[ uuid ] !== undefined ) return interleavedBufferMap[ uuid ];
  25077. const interleavedBuffers = json.interleavedBuffers;
  25078. const interleavedBuffer = interleavedBuffers[ uuid ];
  25079. const buffer = getArrayBuffer( json, interleavedBuffer.buffer );
  25080. const array = getTypedArray( interleavedBuffer.type, buffer );
  25081. const ib = new InterleavedBuffer( array, interleavedBuffer.stride );
  25082. ib.uuid = interleavedBuffer.uuid;
  25083. interleavedBufferMap[ uuid ] = ib;
  25084. return ib;
  25085. }
  25086. function getArrayBuffer( json, uuid ) {
  25087. if ( arrayBufferMap[ uuid ] !== undefined ) return arrayBufferMap[ uuid ];
  25088. const arrayBuffers = json.arrayBuffers;
  25089. const arrayBuffer = arrayBuffers[ uuid ];
  25090. const ab = new Uint32Array( arrayBuffer ).buffer;
  25091. arrayBufferMap[ uuid ] = ab;
  25092. return ab;
  25093. }
  25094. const geometry = json.isInstancedBufferGeometry ? new InstancedBufferGeometry() : new BufferGeometry();
  25095. const index = json.data.index;
  25096. if ( index !== undefined ) {
  25097. const typedArray = getTypedArray( index.type, index.array );
  25098. geometry.setIndex( new BufferAttribute( typedArray, 1 ) );
  25099. }
  25100. const attributes = json.data.attributes;
  25101. for ( const key in attributes ) {
  25102. const attribute = attributes[ key ];
  25103. let bufferAttribute;
  25104. if ( attribute.isInterleavedBufferAttribute ) {
  25105. const interleavedBuffer = getInterleavedBuffer( json.data, attribute.data );
  25106. bufferAttribute = new InterleavedBufferAttribute( interleavedBuffer, attribute.itemSize, attribute.offset, attribute.normalized );
  25107. } else {
  25108. const typedArray = getTypedArray( attribute.type, attribute.array );
  25109. const bufferAttributeConstr = attribute.isInstancedBufferAttribute ? InstancedBufferAttribute : BufferAttribute;
  25110. bufferAttribute = new bufferAttributeConstr( typedArray, attribute.itemSize, attribute.normalized );
  25111. }
  25112. if ( attribute.name !== undefined ) bufferAttribute.name = attribute.name;
  25113. if ( attribute.usage !== undefined ) bufferAttribute.setUsage( attribute.usage );
  25114. if ( attribute.updateRange !== undefined ) {
  25115. bufferAttribute.updateRange.offset = attribute.updateRange.offset;
  25116. bufferAttribute.updateRange.count = attribute.updateRange.count;
  25117. }
  25118. geometry.setAttribute( key, bufferAttribute );
  25119. }
  25120. const morphAttributes = json.data.morphAttributes;
  25121. if ( morphAttributes ) {
  25122. for ( const key in morphAttributes ) {
  25123. const attributeArray = morphAttributes[ key ];
  25124. const array = [];
  25125. for ( let i = 0, il = attributeArray.length; i < il; i ++ ) {
  25126. const attribute = attributeArray[ i ];
  25127. let bufferAttribute;
  25128. if ( attribute.isInterleavedBufferAttribute ) {
  25129. const interleavedBuffer = getInterleavedBuffer( json.data, attribute.data );
  25130. bufferAttribute = new InterleavedBufferAttribute( interleavedBuffer, attribute.itemSize, attribute.offset, attribute.normalized );
  25131. } else {
  25132. const typedArray = getTypedArray( attribute.type, attribute.array );
  25133. bufferAttribute = new BufferAttribute( typedArray, attribute.itemSize, attribute.normalized );
  25134. }
  25135. if ( attribute.name !== undefined ) bufferAttribute.name = attribute.name;
  25136. array.push( bufferAttribute );
  25137. }
  25138. geometry.morphAttributes[ key ] = array;
  25139. }
  25140. }
  25141. const morphTargetsRelative = json.data.morphTargetsRelative;
  25142. if ( morphTargetsRelative ) {
  25143. geometry.morphTargetsRelative = true;
  25144. }
  25145. const groups = json.data.groups || json.data.drawcalls || json.data.offsets;
  25146. if ( groups !== undefined ) {
  25147. for ( let i = 0, n = groups.length; i !== n; ++ i ) {
  25148. const group = groups[ i ];
  25149. geometry.addGroup( group.start, group.count, group.materialIndex );
  25150. }
  25151. }
  25152. const boundingSphere = json.data.boundingSphere;
  25153. if ( boundingSphere !== undefined ) {
  25154. const center = new Vector3();
  25155. if ( boundingSphere.center !== undefined ) {
  25156. center.fromArray( boundingSphere.center );
  25157. }
  25158. geometry.boundingSphere = new Sphere( center, boundingSphere.radius );
  25159. }
  25160. if ( json.name ) geometry.name = json.name;
  25161. if ( json.userData ) geometry.userData = json.userData;
  25162. return geometry;
  25163. }
  25164. }
  25165. class ObjectLoader extends Loader {
  25166. constructor( manager ) {
  25167. super( manager );
  25168. }
  25169. load( url, onLoad, onProgress, onError ) {
  25170. const scope = this;
  25171. const path = ( this.path === '' ) ? LoaderUtils.extractUrlBase( url ) : this.path;
  25172. this.resourcePath = this.resourcePath || path;
  25173. const loader = new FileLoader( this.manager );
  25174. loader.setPath( this.path );
  25175. loader.setRequestHeader( this.requestHeader );
  25176. loader.setWithCredentials( this.withCredentials );
  25177. loader.load( url, function ( text ) {
  25178. let json = null;
  25179. try {
  25180. json = JSON.parse( text );
  25181. } catch ( error ) {
  25182. if ( onError !== undefined ) onError( error );
  25183. console.error( 'THREE:ObjectLoader: Can\'t parse ' + url + '.', error.message );
  25184. return;
  25185. }
  25186. const metadata = json.metadata;
  25187. if ( metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry' ) {
  25188. if ( onError !== undefined ) onError( new Error( 'THREE.ObjectLoader: Can\'t load ' + url ) );
  25189. console.error( 'THREE.ObjectLoader: Can\'t load ' + url );
  25190. return;
  25191. }
  25192. scope.parse( json, onLoad );
  25193. }, onProgress, onError );
  25194. }
  25195. async loadAsync( url, onProgress ) {
  25196. const scope = this;
  25197. const path = ( this.path === '' ) ? LoaderUtils.extractUrlBase( url ) : this.path;
  25198. this.resourcePath = this.resourcePath || path;
  25199. const loader = new FileLoader( this.manager );
  25200. loader.setPath( this.path );
  25201. loader.setRequestHeader( this.requestHeader );
  25202. loader.setWithCredentials( this.withCredentials );
  25203. const text = await loader.loadAsync( url, onProgress );
  25204. const json = JSON.parse( text );
  25205. const metadata = json.metadata;
  25206. if ( metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry' ) {
  25207. throw new Error( 'THREE.ObjectLoader: Can\'t load ' + url );
  25208. }
  25209. return await scope.parseAsync( json );
  25210. }
  25211. parse( json, onLoad ) {
  25212. const animations = this.parseAnimations( json.animations );
  25213. const shapes = this.parseShapes( json.shapes );
  25214. const geometries = this.parseGeometries( json.geometries, shapes );
  25215. const images = this.parseImages( json.images, function () {
  25216. if ( onLoad !== undefined ) onLoad( object );
  25217. } );
  25218. const textures = this.parseTextures( json.textures, images );
  25219. const materials = this.parseMaterials( json.materials, textures );
  25220. const object = this.parseObject( json.object, geometries, materials, textures, animations );
  25221. const skeletons = this.parseSkeletons( json.skeletons, object );
  25222. this.bindSkeletons( object, skeletons );
  25223. //
  25224. if ( onLoad !== undefined ) {
  25225. let hasImages = false;
  25226. for ( const uuid in images ) {
  25227. if ( images[ uuid ].data instanceof HTMLImageElement ) {
  25228. hasImages = true;
  25229. break;
  25230. }
  25231. }
  25232. if ( hasImages === false ) onLoad( object );
  25233. }
  25234. return object;
  25235. }
  25236. async parseAsync( json ) {
  25237. const animations = this.parseAnimations( json.animations );
  25238. const shapes = this.parseShapes( json.shapes );
  25239. const geometries = this.parseGeometries( json.geometries, shapes );
  25240. const images = await this.parseImagesAsync( json.images );
  25241. const textures = this.parseTextures( json.textures, images );
  25242. const materials = this.parseMaterials( json.materials, textures );
  25243. const object = this.parseObject( json.object, geometries, materials, textures, animations );
  25244. const skeletons = this.parseSkeletons( json.skeletons, object );
  25245. this.bindSkeletons( object, skeletons );
  25246. return object;
  25247. }
  25248. parseShapes( json ) {
  25249. const shapes = {};
  25250. if ( json !== undefined ) {
  25251. for ( let i = 0, l = json.length; i < l; i ++ ) {
  25252. const shape = new Shape().fromJSON( json[ i ] );
  25253. shapes[ shape.uuid ] = shape;
  25254. }
  25255. }
  25256. return shapes;
  25257. }
  25258. parseSkeletons( json, object ) {
  25259. const skeletons = {};
  25260. const bones = {};
  25261. // generate bone lookup table
  25262. object.traverse( function ( child ) {
  25263. if ( child.isBone ) bones[ child.uuid ] = child;
  25264. } );
  25265. // create skeletons
  25266. if ( json !== undefined ) {
  25267. for ( let i = 0, l = json.length; i < l; i ++ ) {
  25268. const skeleton = new Skeleton().fromJSON( json[ i ], bones );
  25269. skeletons[ skeleton.uuid ] = skeleton;
  25270. }
  25271. }
  25272. return skeletons;
  25273. }
  25274. parseGeometries( json, shapes ) {
  25275. const geometries = {};
  25276. if ( json !== undefined ) {
  25277. const bufferGeometryLoader = new BufferGeometryLoader();
  25278. for ( let i = 0, l = json.length; i < l; i ++ ) {
  25279. let geometry;
  25280. const data = json[ i ];
  25281. switch ( data.type ) {
  25282. case 'BufferGeometry':
  25283. case 'InstancedBufferGeometry':
  25284. geometry = bufferGeometryLoader.parse( data );
  25285. break;
  25286. default:
  25287. if ( data.type in Geometries ) {
  25288. geometry = Geometries[ data.type ].fromJSON( data, shapes );
  25289. } else {
  25290. console.warn( `THREE.ObjectLoader: Unsupported geometry type "${ data.type }"` );
  25291. }
  25292. }
  25293. geometry.uuid = data.uuid;
  25294. if ( data.name !== undefined ) geometry.name = data.name;
  25295. if ( geometry.isBufferGeometry === true && data.userData !== undefined ) geometry.userData = data.userData;
  25296. geometries[ data.uuid ] = geometry;
  25297. }
  25298. }
  25299. return geometries;
  25300. }
  25301. parseMaterials( json, textures ) {
  25302. const cache = {}; // MultiMaterial
  25303. const materials = {};
  25304. if ( json !== undefined ) {
  25305. const loader = new MaterialLoader();
  25306. loader.setTextures( textures );
  25307. for ( let i = 0, l = json.length; i < l; i ++ ) {
  25308. const data = json[ i ];
  25309. if ( cache[ data.uuid ] === undefined ) {
  25310. cache[ data.uuid ] = loader.parse( data );
  25311. }
  25312. materials[ data.uuid ] = cache[ data.uuid ];
  25313. }
  25314. }
  25315. return materials;
  25316. }
  25317. parseAnimations( json ) {
  25318. const animations = {};
  25319. if ( json !== undefined ) {
  25320. for ( let i = 0; i < json.length; i ++ ) {
  25321. const data = json[ i ];
  25322. const clip = AnimationClip.parse( data );
  25323. animations[ clip.uuid ] = clip;
  25324. }
  25325. }
  25326. return animations;
  25327. }
  25328. parseImages( json, onLoad ) {
  25329. const scope = this;
  25330. const images = {};
  25331. let loader;
  25332. function loadImage( url ) {
  25333. scope.manager.itemStart( url );
  25334. return loader.load( url, function () {
  25335. scope.manager.itemEnd( url );
  25336. }, undefined, function () {
  25337. scope.manager.itemError( url );
  25338. scope.manager.itemEnd( url );
  25339. } );
  25340. }
  25341. function deserializeImage( image ) {
  25342. if ( typeof image === 'string' ) {
  25343. const url = image;
  25344. const path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test( url ) ? url : scope.resourcePath + url;
  25345. return loadImage( path );
  25346. } else {
  25347. if ( image.data ) {
  25348. return {
  25349. data: getTypedArray( image.type, image.data ),
  25350. width: image.width,
  25351. height: image.height
  25352. };
  25353. } else {
  25354. return null;
  25355. }
  25356. }
  25357. }
  25358. if ( json !== undefined && json.length > 0 ) {
  25359. const manager = new LoadingManager( onLoad );
  25360. loader = new ImageLoader( manager );
  25361. loader.setCrossOrigin( this.crossOrigin );
  25362. for ( let i = 0, il = json.length; i < il; i ++ ) {
  25363. const image = json[ i ];
  25364. const url = image.url;
  25365. if ( Array.isArray( url ) ) {
  25366. // load array of images e.g CubeTexture
  25367. const imageArray = [];
  25368. for ( let j = 0, jl = url.length; j < jl; j ++ ) {
  25369. const currentUrl = url[ j ];
  25370. const deserializedImage = deserializeImage( currentUrl );
  25371. if ( deserializedImage !== null ) {
  25372. if ( deserializedImage instanceof HTMLImageElement ) {
  25373. imageArray.push( deserializedImage );
  25374. } else {
  25375. // special case: handle array of data textures for cube textures
  25376. imageArray.push( new DataTexture( deserializedImage.data, deserializedImage.width, deserializedImage.height ) );
  25377. }
  25378. }
  25379. }
  25380. images[ image.uuid ] = new Source( imageArray );
  25381. } else {
  25382. // load single image
  25383. const deserializedImage = deserializeImage( image.url );
  25384. images[ image.uuid ] = new Source( deserializedImage );
  25385. }
  25386. }
  25387. }
  25388. return images;
  25389. }
  25390. async parseImagesAsync( json ) {
  25391. const scope = this;
  25392. const images = {};
  25393. let loader;
  25394. async function deserializeImage( image ) {
  25395. if ( typeof image === 'string' ) {
  25396. const url = image;
  25397. const path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test( url ) ? url : scope.resourcePath + url;
  25398. return await loader.loadAsync( path );
  25399. } else {
  25400. if ( image.data ) {
  25401. return {
  25402. data: getTypedArray( image.type, image.data ),
  25403. width: image.width,
  25404. height: image.height
  25405. };
  25406. } else {
  25407. return null;
  25408. }
  25409. }
  25410. }
  25411. if ( json !== undefined && json.length > 0 ) {
  25412. loader = new ImageLoader( this.manager );
  25413. loader.setCrossOrigin( this.crossOrigin );
  25414. for ( let i = 0, il = json.length; i < il; i ++ ) {
  25415. const image = json[ i ];
  25416. const url = image.url;
  25417. if ( Array.isArray( url ) ) {
  25418. // load array of images e.g CubeTexture
  25419. const imageArray = [];
  25420. for ( let j = 0, jl = url.length; j < jl; j ++ ) {
  25421. const currentUrl = url[ j ];
  25422. const deserializedImage = await deserializeImage( currentUrl );
  25423. if ( deserializedImage !== null ) {
  25424. if ( deserializedImage instanceof HTMLImageElement ) {
  25425. imageArray.push( deserializedImage );
  25426. } else {
  25427. // special case: handle array of data textures for cube textures
  25428. imageArray.push( new DataTexture( deserializedImage.data, deserializedImage.width, deserializedImage.height ) );
  25429. }
  25430. }
  25431. }
  25432. images[ image.uuid ] = new Source( imageArray );
  25433. } else {
  25434. // load single image
  25435. const deserializedImage = await deserializeImage( image.url );
  25436. images[ image.uuid ] = new Source( deserializedImage );
  25437. }
  25438. }
  25439. }
  25440. return images;
  25441. }
  25442. parseTextures( json, images ) {
  25443. function parseConstant( value, type ) {
  25444. if ( typeof value === 'number' ) return value;
  25445. console.warn( 'THREE.ObjectLoader.parseTexture: Constant should be in numeric form.', value );
  25446. return type[ value ];
  25447. }
  25448. const textures = {};
  25449. if ( json !== undefined ) {
  25450. for ( let i = 0, l = json.length; i < l; i ++ ) {
  25451. const data = json[ i ];
  25452. if ( data.image === undefined ) {
  25453. console.warn( 'THREE.ObjectLoader: No "image" specified for', data.uuid );
  25454. }
  25455. if ( images[ data.image ] === undefined ) {
  25456. console.warn( 'THREE.ObjectLoader: Undefined image', data.image );
  25457. }
  25458. const source = images[ data.image ];
  25459. const image = source.data;
  25460. let texture;
  25461. if ( Array.isArray( image ) ) {
  25462. texture = new CubeTexture();
  25463. if ( image.length === 6 ) texture.needsUpdate = true;
  25464. } else {
  25465. if ( image && image.data ) {
  25466. texture = new DataTexture();
  25467. } else {
  25468. texture = new Texture();
  25469. }
  25470. if ( image ) texture.needsUpdate = true; // textures can have undefined image data
  25471. }
  25472. texture.source = source;
  25473. texture.uuid = data.uuid;
  25474. if ( data.name !== undefined ) texture.name = data.name;
  25475. if ( data.mapping !== undefined ) texture.mapping = parseConstant( data.mapping, TEXTURE_MAPPING );
  25476. if ( data.offset !== undefined ) texture.offset.fromArray( data.offset );
  25477. if ( data.repeat !== undefined ) texture.repeat.fromArray( data.repeat );
  25478. if ( data.center !== undefined ) texture.center.fromArray( data.center );
  25479. if ( data.rotation !== undefined ) texture.rotation = data.rotation;
  25480. if ( data.wrap !== undefined ) {
  25481. texture.wrapS = parseConstant( data.wrap[ 0 ], TEXTURE_WRAPPING );
  25482. texture.wrapT = parseConstant( data.wrap[ 1 ], TEXTURE_WRAPPING );
  25483. }
  25484. if ( data.format !== undefined ) texture.format = data.format;
  25485. if ( data.type !== undefined ) texture.type = data.type;
  25486. if ( data.encoding !== undefined ) texture.encoding = data.encoding;
  25487. if ( data.minFilter !== undefined ) texture.minFilter = parseConstant( data.minFilter, TEXTURE_FILTER );
  25488. if ( data.magFilter !== undefined ) texture.magFilter = parseConstant( data.magFilter, TEXTURE_FILTER );
  25489. if ( data.anisotropy !== undefined ) texture.anisotropy = data.anisotropy;
  25490. if ( data.flipY !== undefined ) texture.flipY = data.flipY;
  25491. if ( data.generateMipmaps !== undefined ) texture.generateMipmaps = data.generateMipmaps;
  25492. if ( data.premultiplyAlpha !== undefined ) texture.premultiplyAlpha = data.premultiplyAlpha;
  25493. if ( data.unpackAlignment !== undefined ) texture.unpackAlignment = data.unpackAlignment;
  25494. if ( data.userData !== undefined ) texture.userData = data.userData;
  25495. textures[ data.uuid ] = texture;
  25496. }
  25497. }
  25498. return textures;
  25499. }
  25500. parseObject( data, geometries, materials, textures, animations ) {
  25501. let object;
  25502. function getGeometry( name ) {
  25503. if ( geometries[ name ] === undefined ) {
  25504. console.warn( 'THREE.ObjectLoader: Undefined geometry', name );
  25505. }
  25506. return geometries[ name ];
  25507. }
  25508. function getMaterial( name ) {
  25509. if ( name === undefined ) return undefined;
  25510. if ( Array.isArray( name ) ) {
  25511. const array = [];
  25512. for ( let i = 0, l = name.length; i < l; i ++ ) {
  25513. const uuid = name[ i ];
  25514. if ( materials[ uuid ] === undefined ) {
  25515. console.warn( 'THREE.ObjectLoader: Undefined material', uuid );
  25516. }
  25517. array.push( materials[ uuid ] );
  25518. }
  25519. return array;
  25520. }
  25521. if ( materials[ name ] === undefined ) {
  25522. console.warn( 'THREE.ObjectLoader: Undefined material', name );
  25523. }
  25524. return materials[ name ];
  25525. }
  25526. function getTexture( uuid ) {
  25527. if ( textures[ uuid ] === undefined ) {
  25528. console.warn( 'THREE.ObjectLoader: Undefined texture', uuid );
  25529. }
  25530. return textures[ uuid ];
  25531. }
  25532. let geometry, material;
  25533. switch ( data.type ) {
  25534. case 'Scene':
  25535. object = new Scene();
  25536. if ( data.background !== undefined ) {
  25537. if ( Number.isInteger( data.background ) ) {
  25538. object.background = new Color( data.background );
  25539. } else {
  25540. object.background = getTexture( data.background );
  25541. }
  25542. }
  25543. if ( data.environment !== undefined ) {
  25544. object.environment = getTexture( data.environment );
  25545. }
  25546. if ( data.fog !== undefined ) {
  25547. if ( data.fog.type === 'Fog' ) {
  25548. object.fog = new Fog( data.fog.color, data.fog.near, data.fog.far );
  25549. } else if ( data.fog.type === 'FogExp2' ) {
  25550. object.fog = new FogExp2( data.fog.color, data.fog.density );
  25551. }
  25552. }
  25553. if ( data.backgroundBlurriness !== undefined ) object.backgroundBlurriness = data.backgroundBlurriness;
  25554. if ( data.backgroundIntensity !== undefined ) object.backgroundIntensity = data.backgroundIntensity;
  25555. break;
  25556. case 'PerspectiveCamera':
  25557. object = new PerspectiveCamera( data.fov, data.aspect, data.near, data.far );
  25558. if ( data.focus !== undefined ) object.focus = data.focus;
  25559. if ( data.zoom !== undefined ) object.zoom = data.zoom;
  25560. if ( data.filmGauge !== undefined ) object.filmGauge = data.filmGauge;
  25561. if ( data.filmOffset !== undefined ) object.filmOffset = data.filmOffset;
  25562. if ( data.view !== undefined ) object.view = Object.assign( {}, data.view );
  25563. break;
  25564. case 'OrthographicCamera':
  25565. object = new OrthographicCamera( data.left, data.right, data.top, data.bottom, data.near, data.far );
  25566. if ( data.zoom !== undefined ) object.zoom = data.zoom;
  25567. if ( data.view !== undefined ) object.view = Object.assign( {}, data.view );
  25568. break;
  25569. case 'AmbientLight':
  25570. object = new AmbientLight( data.color, data.intensity );
  25571. break;
  25572. case 'DirectionalLight':
  25573. object = new DirectionalLight( data.color, data.intensity );
  25574. break;
  25575. case 'PointLight':
  25576. object = new PointLight( data.color, data.intensity, data.distance, data.decay );
  25577. break;
  25578. case 'RectAreaLight':
  25579. object = new RectAreaLight( data.color, data.intensity, data.width, data.height );
  25580. break;
  25581. case 'SpotLight':
  25582. object = new SpotLight( data.color, data.intensity, data.distance, data.angle, data.penumbra, data.decay );
  25583. break;
  25584. case 'HemisphereLight':
  25585. object = new HemisphereLight( data.color, data.groundColor, data.intensity );
  25586. break;
  25587. case 'LightProbe':
  25588. object = new LightProbe().fromJSON( data );
  25589. break;
  25590. case 'SkinnedMesh':
  25591. geometry = getGeometry( data.geometry );
  25592. material = getMaterial( data.material );
  25593. object = new SkinnedMesh( geometry, material );
  25594. if ( data.bindMode !== undefined ) object.bindMode = data.bindMode;
  25595. if ( data.bindMatrix !== undefined ) object.bindMatrix.fromArray( data.bindMatrix );
  25596. if ( data.skeleton !== undefined ) object.skeleton = data.skeleton;
  25597. break;
  25598. case 'Mesh':
  25599. geometry = getGeometry( data.geometry );
  25600. material = getMaterial( data.material );
  25601. object = new Mesh( geometry, material );
  25602. break;
  25603. case 'InstancedMesh':
  25604. geometry = getGeometry( data.geometry );
  25605. material = getMaterial( data.material );
  25606. const count = data.count;
  25607. const instanceMatrix = data.instanceMatrix;
  25608. const instanceColor = data.instanceColor;
  25609. object = new InstancedMesh( geometry, material, count );
  25610. object.instanceMatrix = new InstancedBufferAttribute( new Float32Array( instanceMatrix.array ), 16 );
  25611. if ( instanceColor !== undefined ) object.instanceColor = new InstancedBufferAttribute( new Float32Array( instanceColor.array ), instanceColor.itemSize );
  25612. break;
  25613. case 'LOD':
  25614. object = new LOD();
  25615. break;
  25616. case 'Line':
  25617. object = new Line( getGeometry( data.geometry ), getMaterial( data.material ) );
  25618. break;
  25619. case 'LineLoop':
  25620. object = new LineLoop( getGeometry( data.geometry ), getMaterial( data.material ) );
  25621. break;
  25622. case 'LineSegments':
  25623. object = new LineSegments( getGeometry( data.geometry ), getMaterial( data.material ) );
  25624. break;
  25625. case 'PointCloud':
  25626. case 'Points':
  25627. object = new Points( getGeometry( data.geometry ), getMaterial( data.material ) );
  25628. break;
  25629. case 'Sprite':
  25630. object = new Sprite( getMaterial( data.material ) );
  25631. break;
  25632. case 'Group':
  25633. object = new Group();
  25634. break;
  25635. case 'Bone':
  25636. object = new Bone();
  25637. break;
  25638. default:
  25639. object = new Object3D();
  25640. }
  25641. object.uuid = data.uuid;
  25642. if ( data.name !== undefined ) object.name = data.name;
  25643. if ( data.matrix !== undefined ) {
  25644. object.matrix.fromArray( data.matrix );
  25645. if ( data.matrixAutoUpdate !== undefined ) object.matrixAutoUpdate = data.matrixAutoUpdate;
  25646. if ( object.matrixAutoUpdate ) object.matrix.decompose( object.position, object.quaternion, object.scale );
  25647. } else {
  25648. if ( data.position !== undefined ) object.position.fromArray( data.position );
  25649. if ( data.rotation !== undefined ) object.rotation.fromArray( data.rotation );
  25650. if ( data.quaternion !== undefined ) object.quaternion.fromArray( data.quaternion );
  25651. if ( data.scale !== undefined ) object.scale.fromArray( data.scale );
  25652. }
  25653. if ( data.castShadow !== undefined ) object.castShadow = data.castShadow;
  25654. if ( data.receiveShadow !== undefined ) object.receiveShadow = data.receiveShadow;
  25655. if ( data.shadow ) {
  25656. if ( data.shadow.bias !== undefined ) object.shadow.bias = data.shadow.bias;
  25657. if ( data.shadow.normalBias !== undefined ) object.shadow.normalBias = data.shadow.normalBias;
  25658. if ( data.shadow.radius !== undefined ) object.shadow.radius = data.shadow.radius;
  25659. if ( data.shadow.mapSize !== undefined ) object.shadow.mapSize.fromArray( data.shadow.mapSize );
  25660. if ( data.shadow.camera !== undefined ) object.shadow.camera = this.parseObject( data.shadow.camera );
  25661. }
  25662. if ( data.visible !== undefined ) object.visible = data.visible;
  25663. if ( data.frustumCulled !== undefined ) object.frustumCulled = data.frustumCulled;
  25664. if ( data.renderOrder !== undefined ) object.renderOrder = data.renderOrder;
  25665. if ( data.userData !== undefined ) object.userData = data.userData;
  25666. if ( data.layers !== undefined ) object.layers.mask = data.layers;
  25667. if ( data.children !== undefined ) {
  25668. const children = data.children;
  25669. for ( let i = 0; i < children.length; i ++ ) {
  25670. object.add( this.parseObject( children[ i ], geometries, materials, textures, animations ) );
  25671. }
  25672. }
  25673. if ( data.animations !== undefined ) {
  25674. const objectAnimations = data.animations;
  25675. for ( let i = 0; i < objectAnimations.length; i ++ ) {
  25676. const uuid = objectAnimations[ i ];
  25677. object.animations.push( animations[ uuid ] );
  25678. }
  25679. }
  25680. if ( data.type === 'LOD' ) {
  25681. if ( data.autoUpdate !== undefined ) object.autoUpdate = data.autoUpdate;
  25682. const levels = data.levels;
  25683. for ( let l = 0; l < levels.length; l ++ ) {
  25684. const level = levels[ l ];
  25685. const child = object.getObjectByProperty( 'uuid', level.object );
  25686. if ( child !== undefined ) {
  25687. object.addLevel( child, level.distance, level.hysteresis );
  25688. }
  25689. }
  25690. }
  25691. return object;
  25692. }
  25693. bindSkeletons( object, skeletons ) {
  25694. if ( Object.keys( skeletons ).length === 0 ) return;
  25695. object.traverse( function ( child ) {
  25696. if ( child.isSkinnedMesh === true && child.skeleton !== undefined ) {
  25697. const skeleton = skeletons[ child.skeleton ];
  25698. if ( skeleton === undefined ) {
  25699. console.warn( 'THREE.ObjectLoader: No skeleton found with UUID:', child.skeleton );
  25700. } else {
  25701. child.bind( skeleton, child.bindMatrix );
  25702. }
  25703. }
  25704. } );
  25705. }
  25706. }
  25707. const TEXTURE_MAPPING = {
  25708. UVMapping: UVMapping,
  25709. CubeReflectionMapping: CubeReflectionMapping,
  25710. CubeRefractionMapping: CubeRefractionMapping,
  25711. EquirectangularReflectionMapping: EquirectangularReflectionMapping,
  25712. EquirectangularRefractionMapping: EquirectangularRefractionMapping,
  25713. CubeUVReflectionMapping: CubeUVReflectionMapping
  25714. };
  25715. const TEXTURE_WRAPPING = {
  25716. RepeatWrapping: RepeatWrapping,
  25717. ClampToEdgeWrapping: ClampToEdgeWrapping,
  25718. MirroredRepeatWrapping: MirroredRepeatWrapping
  25719. };
  25720. const TEXTURE_FILTER = {
  25721. NearestFilter: NearestFilter,
  25722. NearestMipmapNearestFilter: NearestMipmapNearestFilter,
  25723. NearestMipmapLinearFilter: NearestMipmapLinearFilter,
  25724. LinearFilter: LinearFilter,
  25725. LinearMipmapNearestFilter: LinearMipmapNearestFilter,
  25726. LinearMipmapLinearFilter: LinearMipmapLinearFilter
  25727. };
  25728. class ImageBitmapLoader extends Loader {
  25729. constructor( manager ) {
  25730. super( manager );
  25731. this.isImageBitmapLoader = true;
  25732. if ( typeof createImageBitmap === 'undefined' ) {
  25733. console.warn( 'THREE.ImageBitmapLoader: createImageBitmap() not supported.' );
  25734. }
  25735. if ( typeof fetch === 'undefined' ) {
  25736. console.warn( 'THREE.ImageBitmapLoader: fetch() not supported.' );
  25737. }
  25738. this.options = { premultiplyAlpha: 'none' };
  25739. }
  25740. setOptions( options ) {
  25741. this.options = options;
  25742. return this;
  25743. }
  25744. load( url, onLoad, onProgress, onError ) {
  25745. if ( url === undefined ) url = '';
  25746. if ( this.path !== undefined ) url = this.path + url;
  25747. url = this.manager.resolveURL( url );
  25748. const scope = this;
  25749. const cached = Cache.get( url );
  25750. if ( cached !== undefined ) {
  25751. scope.manager.itemStart( url );
  25752. setTimeout( function () {
  25753. if ( onLoad ) onLoad( cached );
  25754. scope.manager.itemEnd( url );
  25755. }, 0 );
  25756. return cached;
  25757. }
  25758. const fetchOptions = {};
  25759. fetchOptions.credentials = ( this.crossOrigin === 'anonymous' ) ? 'same-origin' : 'include';
  25760. fetchOptions.headers = this.requestHeader;
  25761. fetch( url, fetchOptions ).then( function ( res ) {
  25762. return res.blob();
  25763. } ).then( function ( blob ) {
  25764. return createImageBitmap( blob, Object.assign( scope.options, { colorSpaceConversion: 'none' } ) );
  25765. } ).then( function ( imageBitmap ) {
  25766. Cache.add( url, imageBitmap );
  25767. if ( onLoad ) onLoad( imageBitmap );
  25768. scope.manager.itemEnd( url );
  25769. } ).catch( function ( e ) {
  25770. if ( onError ) onError( e );
  25771. scope.manager.itemError( url );
  25772. scope.manager.itemEnd( url );
  25773. } );
  25774. scope.manager.itemStart( url );
  25775. }
  25776. }
  25777. let _context;
  25778. class AudioContext {
  25779. static getContext() {
  25780. if ( _context === undefined ) {
  25781. _context = new ( window.AudioContext || window.webkitAudioContext )();
  25782. }
  25783. return _context;
  25784. }
  25785. static setContext( value ) {
  25786. _context = value;
  25787. }
  25788. }
  25789. class AudioLoader extends Loader {
  25790. constructor( manager ) {
  25791. super( manager );
  25792. }
  25793. load( url, onLoad, onProgress, onError ) {
  25794. const scope = this;
  25795. const loader = new FileLoader( this.manager );
  25796. loader.setResponseType( 'arraybuffer' );
  25797. loader.setPath( this.path );
  25798. loader.setRequestHeader( this.requestHeader );
  25799. loader.setWithCredentials( this.withCredentials );
  25800. loader.load( url, function ( buffer ) {
  25801. try {
  25802. // Create a copy of the buffer. The `decodeAudioData` method
  25803. // detaches the buffer when complete, preventing reuse.
  25804. const bufferCopy = buffer.slice( 0 );
  25805. const context = AudioContext.getContext();
  25806. context.decodeAudioData( bufferCopy, function ( audioBuffer ) {
  25807. onLoad( audioBuffer );
  25808. } );
  25809. } catch ( e ) {
  25810. if ( onError ) {
  25811. onError( e );
  25812. } else {
  25813. console.error( e );
  25814. }
  25815. scope.manager.itemError( url );
  25816. }
  25817. }, onProgress, onError );
  25818. }
  25819. }
  25820. class HemisphereLightProbe extends LightProbe {
  25821. constructor( skyColor, groundColor, intensity = 1 ) {
  25822. super( undefined, intensity );
  25823. this.isHemisphereLightProbe = true;
  25824. const color1 = new Color().set( skyColor );
  25825. const color2 = new Color().set( groundColor );
  25826. const sky = new Vector3( color1.r, color1.g, color1.b );
  25827. const ground = new Vector3( color2.r, color2.g, color2.b );
  25828. // without extra factor of PI in the shader, should = 1 / Math.sqrt( Math.PI );
  25829. const c0 = Math.sqrt( Math.PI );
  25830. const c1 = c0 * Math.sqrt( 0.75 );
  25831. this.sh.coefficients[ 0 ].copy( sky ).add( ground ).multiplyScalar( c0 );
  25832. this.sh.coefficients[ 1 ].copy( sky ).sub( ground ).multiplyScalar( c1 );
  25833. }
  25834. }
  25835. class AmbientLightProbe extends LightProbe {
  25836. constructor( color, intensity = 1 ) {
  25837. super( undefined, intensity );
  25838. this.isAmbientLightProbe = true;
  25839. const color1 = new Color().set( color );
  25840. // without extra factor of PI in the shader, would be 2 / Math.sqrt( Math.PI );
  25841. this.sh.coefficients[ 0 ].set( color1.r, color1.g, color1.b ).multiplyScalar( 2 * Math.sqrt( Math.PI ) );
  25842. }
  25843. }
  25844. const _eyeRight = /*@__PURE__*/ new Matrix4();
  25845. const _eyeLeft = /*@__PURE__*/ new Matrix4();
  25846. const _projectionMatrix = /*@__PURE__*/ new Matrix4();
  25847. class StereoCamera {
  25848. constructor() {
  25849. this.type = 'StereoCamera';
  25850. this.aspect = 1;
  25851. this.eyeSep = 0.064;
  25852. this.cameraL = new PerspectiveCamera();
  25853. this.cameraL.layers.enable( 1 );
  25854. this.cameraL.matrixAutoUpdate = false;
  25855. this.cameraR = new PerspectiveCamera();
  25856. this.cameraR.layers.enable( 2 );
  25857. this.cameraR.matrixAutoUpdate = false;
  25858. this._cache = {
  25859. focus: null,
  25860. fov: null,
  25861. aspect: null,
  25862. near: null,
  25863. far: null,
  25864. zoom: null,
  25865. eyeSep: null
  25866. };
  25867. }
  25868. update( camera ) {
  25869. const cache = this._cache;
  25870. const needsUpdate = cache.focus !== camera.focus || cache.fov !== camera.fov ||
  25871. cache.aspect !== camera.aspect * this.aspect || cache.near !== camera.near ||
  25872. cache.far !== camera.far || cache.zoom !== camera.zoom || cache.eyeSep !== this.eyeSep;
  25873. if ( needsUpdate ) {
  25874. cache.focus = camera.focus;
  25875. cache.fov = camera.fov;
  25876. cache.aspect = camera.aspect * this.aspect;
  25877. cache.near = camera.near;
  25878. cache.far = camera.far;
  25879. cache.zoom = camera.zoom;
  25880. cache.eyeSep = this.eyeSep;
  25881. // Off-axis stereoscopic effect based on
  25882. // http://paulbourke.net/stereographics/stereorender/
  25883. _projectionMatrix.copy( camera.projectionMatrix );
  25884. const eyeSepHalf = cache.eyeSep / 2;
  25885. const eyeSepOnProjection = eyeSepHalf * cache.near / cache.focus;
  25886. const ymax = ( cache.near * Math.tan( DEG2RAD * cache.fov * 0.5 ) ) / cache.zoom;
  25887. let xmin, xmax;
  25888. // translate xOffset
  25889. _eyeLeft.elements[ 12 ] = - eyeSepHalf;
  25890. _eyeRight.elements[ 12 ] = eyeSepHalf;
  25891. // for left eye
  25892. xmin = - ymax * cache.aspect + eyeSepOnProjection;
  25893. xmax = ymax * cache.aspect + eyeSepOnProjection;
  25894. _projectionMatrix.elements[ 0 ] = 2 * cache.near / ( xmax - xmin );
  25895. _projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin );
  25896. this.cameraL.projectionMatrix.copy( _projectionMatrix );
  25897. // for right eye
  25898. xmin = - ymax * cache.aspect - eyeSepOnProjection;
  25899. xmax = ymax * cache.aspect - eyeSepOnProjection;
  25900. _projectionMatrix.elements[ 0 ] = 2 * cache.near / ( xmax - xmin );
  25901. _projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin );
  25902. this.cameraR.projectionMatrix.copy( _projectionMatrix );
  25903. }
  25904. this.cameraL.matrixWorld.copy( camera.matrixWorld ).multiply( _eyeLeft );
  25905. this.cameraR.matrixWorld.copy( camera.matrixWorld ).multiply( _eyeRight );
  25906. }
  25907. }
  25908. class Clock {
  25909. constructor( autoStart = true ) {
  25910. this.autoStart = autoStart;
  25911. this.startTime = 0;
  25912. this.oldTime = 0;
  25913. this.elapsedTime = 0;
  25914. this.running = false;
  25915. }
  25916. start() {
  25917. this.startTime = now();
  25918. this.oldTime = this.startTime;
  25919. this.elapsedTime = 0;
  25920. this.running = true;
  25921. }
  25922. stop() {
  25923. this.getElapsedTime();
  25924. this.running = false;
  25925. this.autoStart = false;
  25926. }
  25927. getElapsedTime() {
  25928. this.getDelta();
  25929. return this.elapsedTime;
  25930. }
  25931. getDelta() {
  25932. let diff = 0;
  25933. if ( this.autoStart && ! this.running ) {
  25934. this.start();
  25935. return 0;
  25936. }
  25937. if ( this.running ) {
  25938. const newTime = now();
  25939. diff = ( newTime - this.oldTime ) / 1000;
  25940. this.oldTime = newTime;
  25941. this.elapsedTime += diff;
  25942. }
  25943. return diff;
  25944. }
  25945. }
  25946. function now() {
  25947. return ( typeof performance === 'undefined' ? Date : performance ).now(); // see #10732
  25948. }
  25949. const _position$1 = /*@__PURE__*/ new Vector3();
  25950. const _quaternion$1 = /*@__PURE__*/ new Quaternion();
  25951. const _scale$1 = /*@__PURE__*/ new Vector3();
  25952. const _orientation$1 = /*@__PURE__*/ new Vector3();
  25953. class AudioListener extends Object3D {
  25954. constructor() {
  25955. super();
  25956. this.type = 'AudioListener';
  25957. this.context = AudioContext.getContext();
  25958. this.gain = this.context.createGain();
  25959. this.gain.connect( this.context.destination );
  25960. this.filter = null;
  25961. this.timeDelta = 0;
  25962. // private
  25963. this._clock = new Clock();
  25964. }
  25965. getInput() {
  25966. return this.gain;
  25967. }
  25968. removeFilter() {
  25969. if ( this.filter !== null ) {
  25970. this.gain.disconnect( this.filter );
  25971. this.filter.disconnect( this.context.destination );
  25972. this.gain.connect( this.context.destination );
  25973. this.filter = null;
  25974. }
  25975. return this;
  25976. }
  25977. getFilter() {
  25978. return this.filter;
  25979. }
  25980. setFilter( value ) {
  25981. if ( this.filter !== null ) {
  25982. this.gain.disconnect( this.filter );
  25983. this.filter.disconnect( this.context.destination );
  25984. } else {
  25985. this.gain.disconnect( this.context.destination );
  25986. }
  25987. this.filter = value;
  25988. this.gain.connect( this.filter );
  25989. this.filter.connect( this.context.destination );
  25990. return this;
  25991. }
  25992. getMasterVolume() {
  25993. return this.gain.gain.value;
  25994. }
  25995. setMasterVolume( value ) {
  25996. this.gain.gain.setTargetAtTime( value, this.context.currentTime, 0.01 );
  25997. return this;
  25998. }
  25999. updateMatrixWorld( force ) {
  26000. super.updateMatrixWorld( force );
  26001. const listener = this.context.listener;
  26002. const up = this.up;
  26003. this.timeDelta = this._clock.getDelta();
  26004. this.matrixWorld.decompose( _position$1, _quaternion$1, _scale$1 );
  26005. _orientation$1.set( 0, 0, - 1 ).applyQuaternion( _quaternion$1 );
  26006. if ( listener.positionX ) {
  26007. // code path for Chrome (see #14393)
  26008. const endTime = this.context.currentTime + this.timeDelta;
  26009. listener.positionX.linearRampToValueAtTime( _position$1.x, endTime );
  26010. listener.positionY.linearRampToValueAtTime( _position$1.y, endTime );
  26011. listener.positionZ.linearRampToValueAtTime( _position$1.z, endTime );
  26012. listener.forwardX.linearRampToValueAtTime( _orientation$1.x, endTime );
  26013. listener.forwardY.linearRampToValueAtTime( _orientation$1.y, endTime );
  26014. listener.forwardZ.linearRampToValueAtTime( _orientation$1.z, endTime );
  26015. listener.upX.linearRampToValueAtTime( up.x, endTime );
  26016. listener.upY.linearRampToValueAtTime( up.y, endTime );
  26017. listener.upZ.linearRampToValueAtTime( up.z, endTime );
  26018. } else {
  26019. listener.setPosition( _position$1.x, _position$1.y, _position$1.z );
  26020. listener.setOrientation( _orientation$1.x, _orientation$1.y, _orientation$1.z, up.x, up.y, up.z );
  26021. }
  26022. }
  26023. }
  26024. class Audio extends Object3D {
  26025. constructor( listener ) {
  26026. super();
  26027. this.type = 'Audio';
  26028. this.listener = listener;
  26029. this.context = listener.context;
  26030. this.gain = this.context.createGain();
  26031. this.gain.connect( listener.getInput() );
  26032. this.autoplay = false;
  26033. this.buffer = null;
  26034. this.detune = 0;
  26035. this.loop = false;
  26036. this.loopStart = 0;
  26037. this.loopEnd = 0;
  26038. this.offset = 0;
  26039. this.duration = undefined;
  26040. this.playbackRate = 1;
  26041. this.isPlaying = false;
  26042. this.hasPlaybackControl = true;
  26043. this.source = null;
  26044. this.sourceType = 'empty';
  26045. this._startedAt = 0;
  26046. this._progress = 0;
  26047. this._connected = false;
  26048. this.filters = [];
  26049. }
  26050. getOutput() {
  26051. return this.gain;
  26052. }
  26053. setNodeSource( audioNode ) {
  26054. this.hasPlaybackControl = false;
  26055. this.sourceType = 'audioNode';
  26056. this.source = audioNode;
  26057. this.connect();
  26058. return this;
  26059. }
  26060. setMediaElementSource( mediaElement ) {
  26061. this.hasPlaybackControl = false;
  26062. this.sourceType = 'mediaNode';
  26063. this.source = this.context.createMediaElementSource( mediaElement );
  26064. this.connect();
  26065. return this;
  26066. }
  26067. setMediaStreamSource( mediaStream ) {
  26068. this.hasPlaybackControl = false;
  26069. this.sourceType = 'mediaStreamNode';
  26070. this.source = this.context.createMediaStreamSource( mediaStream );
  26071. this.connect();
  26072. return this;
  26073. }
  26074. setBuffer( audioBuffer ) {
  26075. this.buffer = audioBuffer;
  26076. this.sourceType = 'buffer';
  26077. if ( this.autoplay ) this.play();
  26078. return this;
  26079. }
  26080. play( delay = 0 ) {
  26081. if ( this.isPlaying === true ) {
  26082. console.warn( 'THREE.Audio: Audio is already playing.' );
  26083. return;
  26084. }
  26085. if ( this.hasPlaybackControl === false ) {
  26086. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  26087. return;
  26088. }
  26089. this._startedAt = this.context.currentTime + delay;
  26090. const source = this.context.createBufferSource();
  26091. source.buffer = this.buffer;
  26092. source.loop = this.loop;
  26093. source.loopStart = this.loopStart;
  26094. source.loopEnd = this.loopEnd;
  26095. source.onended = this.onEnded.bind( this );
  26096. source.start( this._startedAt, this._progress + this.offset, this.duration );
  26097. this.isPlaying = true;
  26098. this.source = source;
  26099. this.setDetune( this.detune );
  26100. this.setPlaybackRate( this.playbackRate );
  26101. return this.connect();
  26102. }
  26103. pause() {
  26104. if ( this.hasPlaybackControl === false ) {
  26105. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  26106. return;
  26107. }
  26108. if ( this.isPlaying === true ) {
  26109. // update current progress
  26110. this._progress += Math.max( this.context.currentTime - this._startedAt, 0 ) * this.playbackRate;
  26111. if ( this.loop === true ) {
  26112. // ensure _progress does not exceed duration with looped audios
  26113. this._progress = this._progress % ( this.duration || this.buffer.duration );
  26114. }
  26115. this.source.stop();
  26116. this.source.onended = null;
  26117. this.isPlaying = false;
  26118. }
  26119. return this;
  26120. }
  26121. stop() {
  26122. if ( this.hasPlaybackControl === false ) {
  26123. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  26124. return;
  26125. }
  26126. this._progress = 0;
  26127. this.source.stop();
  26128. this.source.onended = null;
  26129. this.isPlaying = false;
  26130. return this;
  26131. }
  26132. connect() {
  26133. if ( this.filters.length > 0 ) {
  26134. this.source.connect( this.filters[ 0 ] );
  26135. for ( let i = 1, l = this.filters.length; i < l; i ++ ) {
  26136. this.filters[ i - 1 ].connect( this.filters[ i ] );
  26137. }
  26138. this.filters[ this.filters.length - 1 ].connect( this.getOutput() );
  26139. } else {
  26140. this.source.connect( this.getOutput() );
  26141. }
  26142. this._connected = true;
  26143. return this;
  26144. }
  26145. disconnect() {
  26146. if ( this.filters.length > 0 ) {
  26147. this.source.disconnect( this.filters[ 0 ] );
  26148. for ( let i = 1, l = this.filters.length; i < l; i ++ ) {
  26149. this.filters[ i - 1 ].disconnect( this.filters[ i ] );
  26150. }
  26151. this.filters[ this.filters.length - 1 ].disconnect( this.getOutput() );
  26152. } else {
  26153. this.source.disconnect( this.getOutput() );
  26154. }
  26155. this._connected = false;
  26156. return this;
  26157. }
  26158. getFilters() {
  26159. return this.filters;
  26160. }
  26161. setFilters( value ) {
  26162. if ( ! value ) value = [];
  26163. if ( this._connected === true ) {
  26164. this.disconnect();
  26165. this.filters = value.slice();
  26166. this.connect();
  26167. } else {
  26168. this.filters = value.slice();
  26169. }
  26170. return this;
  26171. }
  26172. setDetune( value ) {
  26173. this.detune = value;
  26174. if ( this.source.detune === undefined ) return; // only set detune when available
  26175. if ( this.isPlaying === true ) {
  26176. this.source.detune.setTargetAtTime( this.detune, this.context.currentTime, 0.01 );
  26177. }
  26178. return this;
  26179. }
  26180. getDetune() {
  26181. return this.detune;
  26182. }
  26183. getFilter() {
  26184. return this.getFilters()[ 0 ];
  26185. }
  26186. setFilter( filter ) {
  26187. return this.setFilters( filter ? [ filter ] : [] );
  26188. }
  26189. setPlaybackRate( value ) {
  26190. if ( this.hasPlaybackControl === false ) {
  26191. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  26192. return;
  26193. }
  26194. this.playbackRate = value;
  26195. if ( this.isPlaying === true ) {
  26196. this.source.playbackRate.setTargetAtTime( this.playbackRate, this.context.currentTime, 0.01 );
  26197. }
  26198. return this;
  26199. }
  26200. getPlaybackRate() {
  26201. return this.playbackRate;
  26202. }
  26203. onEnded() {
  26204. this.isPlaying = false;
  26205. }
  26206. getLoop() {
  26207. if ( this.hasPlaybackControl === false ) {
  26208. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  26209. return false;
  26210. }
  26211. return this.loop;
  26212. }
  26213. setLoop( value ) {
  26214. if ( this.hasPlaybackControl === false ) {
  26215. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  26216. return;
  26217. }
  26218. this.loop = value;
  26219. if ( this.isPlaying === true ) {
  26220. this.source.loop = this.loop;
  26221. }
  26222. return this;
  26223. }
  26224. setLoopStart( value ) {
  26225. this.loopStart = value;
  26226. return this;
  26227. }
  26228. setLoopEnd( value ) {
  26229. this.loopEnd = value;
  26230. return this;
  26231. }
  26232. getVolume() {
  26233. return this.gain.gain.value;
  26234. }
  26235. setVolume( value ) {
  26236. this.gain.gain.setTargetAtTime( value, this.context.currentTime, 0.01 );
  26237. return this;
  26238. }
  26239. }
  26240. const _position = /*@__PURE__*/ new Vector3();
  26241. const _quaternion = /*@__PURE__*/ new Quaternion();
  26242. const _scale = /*@__PURE__*/ new Vector3();
  26243. const _orientation = /*@__PURE__*/ new Vector3();
  26244. class PositionalAudio extends Audio {
  26245. constructor( listener ) {
  26246. super( listener );
  26247. this.panner = this.context.createPanner();
  26248. this.panner.panningModel = 'HRTF';
  26249. this.panner.connect( this.gain );
  26250. }
  26251. disconnect() {
  26252. super.disconnect();
  26253. this.panner.disconnect( this.gain );
  26254. }
  26255. getOutput() {
  26256. return this.panner;
  26257. }
  26258. getRefDistance() {
  26259. return this.panner.refDistance;
  26260. }
  26261. setRefDistance( value ) {
  26262. this.panner.refDistance = value;
  26263. return this;
  26264. }
  26265. getRolloffFactor() {
  26266. return this.panner.rolloffFactor;
  26267. }
  26268. setRolloffFactor( value ) {
  26269. this.panner.rolloffFactor = value;
  26270. return this;
  26271. }
  26272. getDistanceModel() {
  26273. return this.panner.distanceModel;
  26274. }
  26275. setDistanceModel( value ) {
  26276. this.panner.distanceModel = value;
  26277. return this;
  26278. }
  26279. getMaxDistance() {
  26280. return this.panner.maxDistance;
  26281. }
  26282. setMaxDistance( value ) {
  26283. this.panner.maxDistance = value;
  26284. return this;
  26285. }
  26286. setDirectionalCone( coneInnerAngle, coneOuterAngle, coneOuterGain ) {
  26287. this.panner.coneInnerAngle = coneInnerAngle;
  26288. this.panner.coneOuterAngle = coneOuterAngle;
  26289. this.panner.coneOuterGain = coneOuterGain;
  26290. return this;
  26291. }
  26292. updateMatrixWorld( force ) {
  26293. super.updateMatrixWorld( force );
  26294. if ( this.hasPlaybackControl === true && this.isPlaying === false ) return;
  26295. this.matrixWorld.decompose( _position, _quaternion, _scale );
  26296. _orientation.set( 0, 0, 1 ).applyQuaternion( _quaternion );
  26297. const panner = this.panner;
  26298. if ( panner.positionX ) {
  26299. // code path for Chrome and Firefox (see #14393)
  26300. const endTime = this.context.currentTime + this.listener.timeDelta;
  26301. panner.positionX.linearRampToValueAtTime( _position.x, endTime );
  26302. panner.positionY.linearRampToValueAtTime( _position.y, endTime );
  26303. panner.positionZ.linearRampToValueAtTime( _position.z, endTime );
  26304. panner.orientationX.linearRampToValueAtTime( _orientation.x, endTime );
  26305. panner.orientationY.linearRampToValueAtTime( _orientation.y, endTime );
  26306. panner.orientationZ.linearRampToValueAtTime( _orientation.z, endTime );
  26307. } else {
  26308. panner.setPosition( _position.x, _position.y, _position.z );
  26309. panner.setOrientation( _orientation.x, _orientation.y, _orientation.z );
  26310. }
  26311. }
  26312. }
  26313. class AudioAnalyser {
  26314. constructor( audio, fftSize = 2048 ) {
  26315. this.analyser = audio.context.createAnalyser();
  26316. this.analyser.fftSize = fftSize;
  26317. this.data = new Uint8Array( this.analyser.frequencyBinCount );
  26318. audio.getOutput().connect( this.analyser );
  26319. }
  26320. getFrequencyData() {
  26321. this.analyser.getByteFrequencyData( this.data );
  26322. return this.data;
  26323. }
  26324. getAverageFrequency() {
  26325. let value = 0;
  26326. const data = this.getFrequencyData();
  26327. for ( let i = 0; i < data.length; i ++ ) {
  26328. value += data[ i ];
  26329. }
  26330. return value / data.length;
  26331. }
  26332. }
  26333. class PropertyMixer {
  26334. constructor( binding, typeName, valueSize ) {
  26335. this.binding = binding;
  26336. this.valueSize = valueSize;
  26337. let mixFunction,
  26338. mixFunctionAdditive,
  26339. setIdentity;
  26340. // buffer layout: [ incoming | accu0 | accu1 | orig | addAccu | (optional work) ]
  26341. //
  26342. // interpolators can use .buffer as their .result
  26343. // the data then goes to 'incoming'
  26344. //
  26345. // 'accu0' and 'accu1' are used frame-interleaved for
  26346. // the cumulative result and are compared to detect
  26347. // changes
  26348. //
  26349. // 'orig' stores the original state of the property
  26350. //
  26351. // 'add' is used for additive cumulative results
  26352. //
  26353. // 'work' is optional and is only present for quaternion types. It is used
  26354. // to store intermediate quaternion multiplication results
  26355. switch ( typeName ) {
  26356. case 'quaternion':
  26357. mixFunction = this._slerp;
  26358. mixFunctionAdditive = this._slerpAdditive;
  26359. setIdentity = this._setAdditiveIdentityQuaternion;
  26360. this.buffer = new Float64Array( valueSize * 6 );
  26361. this._workIndex = 5;
  26362. break;
  26363. case 'string':
  26364. case 'bool':
  26365. mixFunction = this._select;
  26366. // Use the regular mix function and for additive on these types,
  26367. // additive is not relevant for non-numeric types
  26368. mixFunctionAdditive = this._select;
  26369. setIdentity = this._setAdditiveIdentityOther;
  26370. this.buffer = new Array( valueSize * 5 );
  26371. break;
  26372. default:
  26373. mixFunction = this._lerp;
  26374. mixFunctionAdditive = this._lerpAdditive;
  26375. setIdentity = this._setAdditiveIdentityNumeric;
  26376. this.buffer = new Float64Array( valueSize * 5 );
  26377. }
  26378. this._mixBufferRegion = mixFunction;
  26379. this._mixBufferRegionAdditive = mixFunctionAdditive;
  26380. this._setIdentity = setIdentity;
  26381. this._origIndex = 3;
  26382. this._addIndex = 4;
  26383. this.cumulativeWeight = 0;
  26384. this.cumulativeWeightAdditive = 0;
  26385. this.useCount = 0;
  26386. this.referenceCount = 0;
  26387. }
  26388. // accumulate data in the 'incoming' region into 'accu<i>'
  26389. accumulate( accuIndex, weight ) {
  26390. // note: happily accumulating nothing when weight = 0, the caller knows
  26391. // the weight and shouldn't have made the call in the first place
  26392. const buffer = this.buffer,
  26393. stride = this.valueSize,
  26394. offset = accuIndex * stride + stride;
  26395. let currentWeight = this.cumulativeWeight;
  26396. if ( currentWeight === 0 ) {
  26397. // accuN := incoming * weight
  26398. for ( let i = 0; i !== stride; ++ i ) {
  26399. buffer[ offset + i ] = buffer[ i ];
  26400. }
  26401. currentWeight = weight;
  26402. } else {
  26403. // accuN := accuN + incoming * weight
  26404. currentWeight += weight;
  26405. const mix = weight / currentWeight;
  26406. this._mixBufferRegion( buffer, offset, 0, mix, stride );
  26407. }
  26408. this.cumulativeWeight = currentWeight;
  26409. }
  26410. // accumulate data in the 'incoming' region into 'add'
  26411. accumulateAdditive( weight ) {
  26412. const buffer = this.buffer,
  26413. stride = this.valueSize,
  26414. offset = stride * this._addIndex;
  26415. if ( this.cumulativeWeightAdditive === 0 ) {
  26416. // add = identity
  26417. this._setIdentity();
  26418. }
  26419. // add := add + incoming * weight
  26420. this._mixBufferRegionAdditive( buffer, offset, 0, weight, stride );
  26421. this.cumulativeWeightAdditive += weight;
  26422. }
  26423. // apply the state of 'accu<i>' to the binding when accus differ
  26424. apply( accuIndex ) {
  26425. const stride = this.valueSize,
  26426. buffer = this.buffer,
  26427. offset = accuIndex * stride + stride,
  26428. weight = this.cumulativeWeight,
  26429. weightAdditive = this.cumulativeWeightAdditive,
  26430. binding = this.binding;
  26431. this.cumulativeWeight = 0;
  26432. this.cumulativeWeightAdditive = 0;
  26433. if ( weight < 1 ) {
  26434. // accuN := accuN + original * ( 1 - cumulativeWeight )
  26435. const originalValueOffset = stride * this._origIndex;
  26436. this._mixBufferRegion(
  26437. buffer, offset, originalValueOffset, 1 - weight, stride );
  26438. }
  26439. if ( weightAdditive > 0 ) {
  26440. // accuN := accuN + additive accuN
  26441. this._mixBufferRegionAdditive( buffer, offset, this._addIndex * stride, 1, stride );
  26442. }
  26443. for ( let i = stride, e = stride + stride; i !== e; ++ i ) {
  26444. if ( buffer[ i ] !== buffer[ i + stride ] ) {
  26445. // value has changed -> update scene graph
  26446. binding.setValue( buffer, offset );
  26447. break;
  26448. }
  26449. }
  26450. }
  26451. // remember the state of the bound property and copy it to both accus
  26452. saveOriginalState() {
  26453. const binding = this.binding;
  26454. const buffer = this.buffer,
  26455. stride = this.valueSize,
  26456. originalValueOffset = stride * this._origIndex;
  26457. binding.getValue( buffer, originalValueOffset );
  26458. // accu[0..1] := orig -- initially detect changes against the original
  26459. for ( let i = stride, e = originalValueOffset; i !== e; ++ i ) {
  26460. buffer[ i ] = buffer[ originalValueOffset + ( i % stride ) ];
  26461. }
  26462. // Add to identity for additive
  26463. this._setIdentity();
  26464. this.cumulativeWeight = 0;
  26465. this.cumulativeWeightAdditive = 0;
  26466. }
  26467. // apply the state previously taken via 'saveOriginalState' to the binding
  26468. restoreOriginalState() {
  26469. const originalValueOffset = this.valueSize * 3;
  26470. this.binding.setValue( this.buffer, originalValueOffset );
  26471. }
  26472. _setAdditiveIdentityNumeric() {
  26473. const startIndex = this._addIndex * this.valueSize;
  26474. const endIndex = startIndex + this.valueSize;
  26475. for ( let i = startIndex; i < endIndex; i ++ ) {
  26476. this.buffer[ i ] = 0;
  26477. }
  26478. }
  26479. _setAdditiveIdentityQuaternion() {
  26480. this._setAdditiveIdentityNumeric();
  26481. this.buffer[ this._addIndex * this.valueSize + 3 ] = 1;
  26482. }
  26483. _setAdditiveIdentityOther() {
  26484. const startIndex = this._origIndex * this.valueSize;
  26485. const targetIndex = this._addIndex * this.valueSize;
  26486. for ( let i = 0; i < this.valueSize; i ++ ) {
  26487. this.buffer[ targetIndex + i ] = this.buffer[ startIndex + i ];
  26488. }
  26489. }
  26490. // mix functions
  26491. _select( buffer, dstOffset, srcOffset, t, stride ) {
  26492. if ( t >= 0.5 ) {
  26493. for ( let i = 0; i !== stride; ++ i ) {
  26494. buffer[ dstOffset + i ] = buffer[ srcOffset + i ];
  26495. }
  26496. }
  26497. }
  26498. _slerp( buffer, dstOffset, srcOffset, t ) {
  26499. Quaternion.slerpFlat( buffer, dstOffset, buffer, dstOffset, buffer, srcOffset, t );
  26500. }
  26501. _slerpAdditive( buffer, dstOffset, srcOffset, t, stride ) {
  26502. const workOffset = this._workIndex * stride;
  26503. // Store result in intermediate buffer offset
  26504. Quaternion.multiplyQuaternionsFlat( buffer, workOffset, buffer, dstOffset, buffer, srcOffset );
  26505. // Slerp to the intermediate result
  26506. Quaternion.slerpFlat( buffer, dstOffset, buffer, dstOffset, buffer, workOffset, t );
  26507. }
  26508. _lerp( buffer, dstOffset, srcOffset, t, stride ) {
  26509. const s = 1 - t;
  26510. for ( let i = 0; i !== stride; ++ i ) {
  26511. const j = dstOffset + i;
  26512. buffer[ j ] = buffer[ j ] * s + buffer[ srcOffset + i ] * t;
  26513. }
  26514. }
  26515. _lerpAdditive( buffer, dstOffset, srcOffset, t, stride ) {
  26516. for ( let i = 0; i !== stride; ++ i ) {
  26517. const j = dstOffset + i;
  26518. buffer[ j ] = buffer[ j ] + buffer[ srcOffset + i ] * t;
  26519. }
  26520. }
  26521. }
  26522. // Characters [].:/ are reserved for track binding syntax.
  26523. const _RESERVED_CHARS_RE = '\\[\\]\\.:\\/';
  26524. const _reservedRe = new RegExp( '[' + _RESERVED_CHARS_RE + ']', 'g' );
  26525. // Attempts to allow node names from any language. ES5's `\w` regexp matches
  26526. // only latin characters, and the unicode \p{L} is not yet supported. So
  26527. // instead, we exclude reserved characters and match everything else.
  26528. const _wordChar = '[^' + _RESERVED_CHARS_RE + ']';
  26529. const _wordCharOrDot = '[^' + _RESERVED_CHARS_RE.replace( '\\.', '' ) + ']';
  26530. // Parent directories, delimited by '/' or ':'. Currently unused, but must
  26531. // be matched to parse the rest of the track name.
  26532. const _directoryRe = /*@__PURE__*/ /((?:WC+[\/:])*)/.source.replace( 'WC', _wordChar );
  26533. // Target node. May contain word characters (a-zA-Z0-9_) and '.' or '-'.
  26534. const _nodeRe = /*@__PURE__*/ /(WCOD+)?/.source.replace( 'WCOD', _wordCharOrDot );
  26535. // Object on target node, and accessor. May not contain reserved
  26536. // characters. Accessor may contain any character except closing bracket.
  26537. const _objectRe = /*@__PURE__*/ /(?:\.(WC+)(?:\[(.+)\])?)?/.source.replace( 'WC', _wordChar );
  26538. // Property and accessor. May not contain reserved characters. Accessor may
  26539. // contain any non-bracket characters.
  26540. const _propertyRe = /*@__PURE__*/ /\.(WC+)(?:\[(.+)\])?/.source.replace( 'WC', _wordChar );
  26541. const _trackRe = new RegExp( ''
  26542. + '^'
  26543. + _directoryRe
  26544. + _nodeRe
  26545. + _objectRe
  26546. + _propertyRe
  26547. + '$'
  26548. );
  26549. const _supportedObjectNames = [ 'material', 'materials', 'bones', 'map' ];
  26550. class Composite {
  26551. constructor( targetGroup, path, optionalParsedPath ) {
  26552. const parsedPath = optionalParsedPath || PropertyBinding.parseTrackName( path );
  26553. this._targetGroup = targetGroup;
  26554. this._bindings = targetGroup.subscribe_( path, parsedPath );
  26555. }
  26556. getValue( array, offset ) {
  26557. this.bind(); // bind all binding
  26558. const firstValidIndex = this._targetGroup.nCachedObjects_,
  26559. binding = this._bindings[ firstValidIndex ];
  26560. // and only call .getValue on the first
  26561. if ( binding !== undefined ) binding.getValue( array, offset );
  26562. }
  26563. setValue( array, offset ) {
  26564. const bindings = this._bindings;
  26565. for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  26566. bindings[ i ].setValue( array, offset );
  26567. }
  26568. }
  26569. bind() {
  26570. const bindings = this._bindings;
  26571. for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  26572. bindings[ i ].bind();
  26573. }
  26574. }
  26575. unbind() {
  26576. const bindings = this._bindings;
  26577. for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  26578. bindings[ i ].unbind();
  26579. }
  26580. }
  26581. }
  26582. // Note: This class uses a State pattern on a per-method basis:
  26583. // 'bind' sets 'this.getValue' / 'setValue' and shadows the
  26584. // prototype version of these methods with one that represents
  26585. // the bound state. When the property is not found, the methods
  26586. // become no-ops.
  26587. class PropertyBinding {
  26588. constructor( rootNode, path, parsedPath ) {
  26589. this.path = path;
  26590. this.parsedPath = parsedPath || PropertyBinding.parseTrackName( path );
  26591. this.node = PropertyBinding.findNode( rootNode, this.parsedPath.nodeName ) || rootNode;
  26592. this.rootNode = rootNode;
  26593. // initial state of these methods that calls 'bind'
  26594. this.getValue = this._getValue_unbound;
  26595. this.setValue = this._setValue_unbound;
  26596. }
  26597. static create( root, path, parsedPath ) {
  26598. if ( ! ( root && root.isAnimationObjectGroup ) ) {
  26599. return new PropertyBinding( root, path, parsedPath );
  26600. } else {
  26601. return new PropertyBinding.Composite( root, path, parsedPath );
  26602. }
  26603. }
  26604. /**
  26605. * Replaces spaces with underscores and removes unsupported characters from
  26606. * node names, to ensure compatibility with parseTrackName().
  26607. *
  26608. * @param {string} name Node name to be sanitized.
  26609. * @return {string}
  26610. */
  26611. static sanitizeNodeName( name ) {
  26612. return name.replace( /\s/g, '_' ).replace( _reservedRe, '' );
  26613. }
  26614. static parseTrackName( trackName ) {
  26615. const matches = _trackRe.exec( trackName );
  26616. if ( matches === null ) {
  26617. throw new Error( 'PropertyBinding: Cannot parse trackName: ' + trackName );
  26618. }
  26619. const results = {
  26620. // directoryName: matches[ 1 ], // (tschw) currently unused
  26621. nodeName: matches[ 2 ],
  26622. objectName: matches[ 3 ],
  26623. objectIndex: matches[ 4 ],
  26624. propertyName: matches[ 5 ], // required
  26625. propertyIndex: matches[ 6 ]
  26626. };
  26627. const lastDot = results.nodeName && results.nodeName.lastIndexOf( '.' );
  26628. if ( lastDot !== undefined && lastDot !== - 1 ) {
  26629. const objectName = results.nodeName.substring( lastDot + 1 );
  26630. // Object names must be checked against an allowlist. Otherwise, there
  26631. // is no way to parse 'foo.bar.baz': 'baz' must be a property, but
  26632. // 'bar' could be the objectName, or part of a nodeName (which can
  26633. // include '.' characters).
  26634. if ( _supportedObjectNames.indexOf( objectName ) !== - 1 ) {
  26635. results.nodeName = results.nodeName.substring( 0, lastDot );
  26636. results.objectName = objectName;
  26637. }
  26638. }
  26639. if ( results.propertyName === null || results.propertyName.length === 0 ) {
  26640. throw new Error( 'PropertyBinding: can not parse propertyName from trackName: ' + trackName );
  26641. }
  26642. return results;
  26643. }
  26644. static findNode( root, nodeName ) {
  26645. if ( nodeName === undefined || nodeName === '' || nodeName === '.' || nodeName === - 1 || nodeName === root.name || nodeName === root.uuid ) {
  26646. return root;
  26647. }
  26648. // search into skeleton bones.
  26649. if ( root.skeleton ) {
  26650. const bone = root.skeleton.getBoneByName( nodeName );
  26651. if ( bone !== undefined ) {
  26652. return bone;
  26653. }
  26654. }
  26655. // search into node subtree.
  26656. if ( root.children ) {
  26657. const searchNodeSubtree = function ( children ) {
  26658. for ( let i = 0; i < children.length; i ++ ) {
  26659. const childNode = children[ i ];
  26660. if ( childNode.name === nodeName || childNode.uuid === nodeName ) {
  26661. return childNode;
  26662. }
  26663. const result = searchNodeSubtree( childNode.children );
  26664. if ( result ) return result;
  26665. }
  26666. return null;
  26667. };
  26668. const subTreeNode = searchNodeSubtree( root.children );
  26669. if ( subTreeNode ) {
  26670. return subTreeNode;
  26671. }
  26672. }
  26673. return null;
  26674. }
  26675. // these are used to "bind" a nonexistent property
  26676. _getValue_unavailable() {}
  26677. _setValue_unavailable() {}
  26678. // Getters
  26679. _getValue_direct( buffer, offset ) {
  26680. buffer[ offset ] = this.targetObject[ this.propertyName ];
  26681. }
  26682. _getValue_array( buffer, offset ) {
  26683. const source = this.resolvedProperty;
  26684. for ( let i = 0, n = source.length; i !== n; ++ i ) {
  26685. buffer[ offset ++ ] = source[ i ];
  26686. }
  26687. }
  26688. _getValue_arrayElement( buffer, offset ) {
  26689. buffer[ offset ] = this.resolvedProperty[ this.propertyIndex ];
  26690. }
  26691. _getValue_toArray( buffer, offset ) {
  26692. this.resolvedProperty.toArray( buffer, offset );
  26693. }
  26694. // Direct
  26695. _setValue_direct( buffer, offset ) {
  26696. this.targetObject[ this.propertyName ] = buffer[ offset ];
  26697. }
  26698. _setValue_direct_setNeedsUpdate( buffer, offset ) {
  26699. this.targetObject[ this.propertyName ] = buffer[ offset ];
  26700. this.targetObject.needsUpdate = true;
  26701. }
  26702. _setValue_direct_setMatrixWorldNeedsUpdate( buffer, offset ) {
  26703. this.targetObject[ this.propertyName ] = buffer[ offset ];
  26704. this.targetObject.matrixWorldNeedsUpdate = true;
  26705. }
  26706. // EntireArray
  26707. _setValue_array( buffer, offset ) {
  26708. const dest = this.resolvedProperty;
  26709. for ( let i = 0, n = dest.length; i !== n; ++ i ) {
  26710. dest[ i ] = buffer[ offset ++ ];
  26711. }
  26712. }
  26713. _setValue_array_setNeedsUpdate( buffer, offset ) {
  26714. const dest = this.resolvedProperty;
  26715. for ( let i = 0, n = dest.length; i !== n; ++ i ) {
  26716. dest[ i ] = buffer[ offset ++ ];
  26717. }
  26718. this.targetObject.needsUpdate = true;
  26719. }
  26720. _setValue_array_setMatrixWorldNeedsUpdate( buffer, offset ) {
  26721. const dest = this.resolvedProperty;
  26722. for ( let i = 0, n = dest.length; i !== n; ++ i ) {
  26723. dest[ i ] = buffer[ offset ++ ];
  26724. }
  26725. this.targetObject.matrixWorldNeedsUpdate = true;
  26726. }
  26727. // ArrayElement
  26728. _setValue_arrayElement( buffer, offset ) {
  26729. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  26730. }
  26731. _setValue_arrayElement_setNeedsUpdate( buffer, offset ) {
  26732. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  26733. this.targetObject.needsUpdate = true;
  26734. }
  26735. _setValue_arrayElement_setMatrixWorldNeedsUpdate( buffer, offset ) {
  26736. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  26737. this.targetObject.matrixWorldNeedsUpdate = true;
  26738. }
  26739. // HasToFromArray
  26740. _setValue_fromArray( buffer, offset ) {
  26741. this.resolvedProperty.fromArray( buffer, offset );
  26742. }
  26743. _setValue_fromArray_setNeedsUpdate( buffer, offset ) {
  26744. this.resolvedProperty.fromArray( buffer, offset );
  26745. this.targetObject.needsUpdate = true;
  26746. }
  26747. _setValue_fromArray_setMatrixWorldNeedsUpdate( buffer, offset ) {
  26748. this.resolvedProperty.fromArray( buffer, offset );
  26749. this.targetObject.matrixWorldNeedsUpdate = true;
  26750. }
  26751. _getValue_unbound( targetArray, offset ) {
  26752. this.bind();
  26753. this.getValue( targetArray, offset );
  26754. }
  26755. _setValue_unbound( sourceArray, offset ) {
  26756. this.bind();
  26757. this.setValue( sourceArray, offset );
  26758. }
  26759. // create getter / setter pair for a property in the scene graph
  26760. bind() {
  26761. let targetObject = this.node;
  26762. const parsedPath = this.parsedPath;
  26763. const objectName = parsedPath.objectName;
  26764. const propertyName = parsedPath.propertyName;
  26765. let propertyIndex = parsedPath.propertyIndex;
  26766. if ( ! targetObject ) {
  26767. targetObject = PropertyBinding.findNode( this.rootNode, parsedPath.nodeName ) || this.rootNode;
  26768. this.node = targetObject;
  26769. }
  26770. // set fail state so we can just 'return' on error
  26771. this.getValue = this._getValue_unavailable;
  26772. this.setValue = this._setValue_unavailable;
  26773. // ensure there is a value node
  26774. if ( ! targetObject ) {
  26775. console.error( 'THREE.PropertyBinding: Trying to update node for track: ' + this.path + ' but it wasn\'t found.' );
  26776. return;
  26777. }
  26778. if ( objectName ) {
  26779. let objectIndex = parsedPath.objectIndex;
  26780. // special cases were we need to reach deeper into the hierarchy to get the face materials....
  26781. switch ( objectName ) {
  26782. case 'materials':
  26783. if ( ! targetObject.material ) {
  26784. console.error( 'THREE.PropertyBinding: Can not bind to material as node does not have a material.', this );
  26785. return;
  26786. }
  26787. if ( ! targetObject.material.materials ) {
  26788. console.error( 'THREE.PropertyBinding: Can not bind to material.materials as node.material does not have a materials array.', this );
  26789. return;
  26790. }
  26791. targetObject = targetObject.material.materials;
  26792. break;
  26793. case 'bones':
  26794. if ( ! targetObject.skeleton ) {
  26795. console.error( 'THREE.PropertyBinding: Can not bind to bones as node does not have a skeleton.', this );
  26796. return;
  26797. }
  26798. // potential future optimization: skip this if propertyIndex is already an integer
  26799. // and convert the integer string to a true integer.
  26800. targetObject = targetObject.skeleton.bones;
  26801. // support resolving morphTarget names into indices.
  26802. for ( let i = 0; i < targetObject.length; i ++ ) {
  26803. if ( targetObject[ i ].name === objectIndex ) {
  26804. objectIndex = i;
  26805. break;
  26806. }
  26807. }
  26808. break;
  26809. case 'map':
  26810. if ( 'map' in targetObject ) {
  26811. targetObject = targetObject.map;
  26812. break;
  26813. }
  26814. if ( ! targetObject.material ) {
  26815. console.error( 'THREE.PropertyBinding: Can not bind to material as node does not have a material.', this );
  26816. return;
  26817. }
  26818. if ( ! targetObject.material.map ) {
  26819. console.error( 'THREE.PropertyBinding: Can not bind to material.map as node.material does not have a map.', this );
  26820. return;
  26821. }
  26822. targetObject = targetObject.material.map;
  26823. break;
  26824. default:
  26825. if ( targetObject[ objectName ] === undefined ) {
  26826. console.error( 'THREE.PropertyBinding: Can not bind to objectName of node undefined.', this );
  26827. return;
  26828. }
  26829. targetObject = targetObject[ objectName ];
  26830. }
  26831. if ( objectIndex !== undefined ) {
  26832. if ( targetObject[ objectIndex ] === undefined ) {
  26833. console.error( 'THREE.PropertyBinding: Trying to bind to objectIndex of objectName, but is undefined.', this, targetObject );
  26834. return;
  26835. }
  26836. targetObject = targetObject[ objectIndex ];
  26837. }
  26838. }
  26839. // resolve property
  26840. const nodeProperty = targetObject[ propertyName ];
  26841. if ( nodeProperty === undefined ) {
  26842. const nodeName = parsedPath.nodeName;
  26843. console.error( 'THREE.PropertyBinding: Trying to update property for track: ' + nodeName +
  26844. '.' + propertyName + ' but it wasn\'t found.', targetObject );
  26845. return;
  26846. }
  26847. // determine versioning scheme
  26848. let versioning = this.Versioning.None;
  26849. this.targetObject = targetObject;
  26850. if ( targetObject.needsUpdate !== undefined ) { // material
  26851. versioning = this.Versioning.NeedsUpdate;
  26852. } else if ( targetObject.matrixWorldNeedsUpdate !== undefined ) { // node transform
  26853. versioning = this.Versioning.MatrixWorldNeedsUpdate;
  26854. }
  26855. // determine how the property gets bound
  26856. let bindingType = this.BindingType.Direct;
  26857. if ( propertyIndex !== undefined ) {
  26858. // access a sub element of the property array (only primitives are supported right now)
  26859. if ( propertyName === 'morphTargetInfluences' ) {
  26860. // potential optimization, skip this if propertyIndex is already an integer, and convert the integer string to a true integer.
  26861. // support resolving morphTarget names into indices.
  26862. if ( ! targetObject.geometry ) {
  26863. console.error( 'THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.', this );
  26864. return;
  26865. }
  26866. if ( ! targetObject.geometry.morphAttributes ) {
  26867. console.error( 'THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.morphAttributes.', this );
  26868. return;
  26869. }
  26870. if ( targetObject.morphTargetDictionary[ propertyIndex ] !== undefined ) {
  26871. propertyIndex = targetObject.morphTargetDictionary[ propertyIndex ];
  26872. }
  26873. }
  26874. bindingType = this.BindingType.ArrayElement;
  26875. this.resolvedProperty = nodeProperty;
  26876. this.propertyIndex = propertyIndex;
  26877. } else if ( nodeProperty.fromArray !== undefined && nodeProperty.toArray !== undefined ) {
  26878. // must use copy for Object3D.Euler/Quaternion
  26879. bindingType = this.BindingType.HasFromToArray;
  26880. this.resolvedProperty = nodeProperty;
  26881. } else if ( Array.isArray( nodeProperty ) ) {
  26882. bindingType = this.BindingType.EntireArray;
  26883. this.resolvedProperty = nodeProperty;
  26884. } else {
  26885. this.propertyName = propertyName;
  26886. }
  26887. // select getter / setter
  26888. this.getValue = this.GetterByBindingType[ bindingType ];
  26889. this.setValue = this.SetterByBindingTypeAndVersioning[ bindingType ][ versioning ];
  26890. }
  26891. unbind() {
  26892. this.node = null;
  26893. // back to the prototype version of getValue / setValue
  26894. // note: avoiding to mutate the shape of 'this' via 'delete'
  26895. this.getValue = this._getValue_unbound;
  26896. this.setValue = this._setValue_unbound;
  26897. }
  26898. }
  26899. PropertyBinding.Composite = Composite;
  26900. PropertyBinding.prototype.BindingType = {
  26901. Direct: 0,
  26902. EntireArray: 1,
  26903. ArrayElement: 2,
  26904. HasFromToArray: 3
  26905. };
  26906. PropertyBinding.prototype.Versioning = {
  26907. None: 0,
  26908. NeedsUpdate: 1,
  26909. MatrixWorldNeedsUpdate: 2
  26910. };
  26911. PropertyBinding.prototype.GetterByBindingType = [
  26912. PropertyBinding.prototype._getValue_direct,
  26913. PropertyBinding.prototype._getValue_array,
  26914. PropertyBinding.prototype._getValue_arrayElement,
  26915. PropertyBinding.prototype._getValue_toArray,
  26916. ];
  26917. PropertyBinding.prototype.SetterByBindingTypeAndVersioning = [
  26918. [
  26919. // Direct
  26920. PropertyBinding.prototype._setValue_direct,
  26921. PropertyBinding.prototype._setValue_direct_setNeedsUpdate,
  26922. PropertyBinding.prototype._setValue_direct_setMatrixWorldNeedsUpdate,
  26923. ], [
  26924. // EntireArray
  26925. PropertyBinding.prototype._setValue_array,
  26926. PropertyBinding.prototype._setValue_array_setNeedsUpdate,
  26927. PropertyBinding.prototype._setValue_array_setMatrixWorldNeedsUpdate,
  26928. ], [
  26929. // ArrayElement
  26930. PropertyBinding.prototype._setValue_arrayElement,
  26931. PropertyBinding.prototype._setValue_arrayElement_setNeedsUpdate,
  26932. PropertyBinding.prototype._setValue_arrayElement_setMatrixWorldNeedsUpdate,
  26933. ], [
  26934. // HasToFromArray
  26935. PropertyBinding.prototype._setValue_fromArray,
  26936. PropertyBinding.prototype._setValue_fromArray_setNeedsUpdate,
  26937. PropertyBinding.prototype._setValue_fromArray_setMatrixWorldNeedsUpdate,
  26938. ]
  26939. ];
  26940. /**
  26941. *
  26942. * A group of objects that receives a shared animation state.
  26943. *
  26944. * Usage:
  26945. *
  26946. * - Add objects you would otherwise pass as 'root' to the
  26947. * constructor or the .clipAction method of AnimationMixer.
  26948. *
  26949. * - Instead pass this object as 'root'.
  26950. *
  26951. * - You can also add and remove objects later when the mixer
  26952. * is running.
  26953. *
  26954. * Note:
  26955. *
  26956. * Objects of this class appear as one object to the mixer,
  26957. * so cache control of the individual objects must be done
  26958. * on the group.
  26959. *
  26960. * Limitation:
  26961. *
  26962. * - The animated properties must be compatible among the
  26963. * all objects in the group.
  26964. *
  26965. * - A single property can either be controlled through a
  26966. * target group or directly, but not both.
  26967. */
  26968. class AnimationObjectGroup {
  26969. constructor() {
  26970. this.isAnimationObjectGroup = true;
  26971. this.uuid = generateUUID();
  26972. // cached objects followed by the active ones
  26973. this._objects = Array.prototype.slice.call( arguments );
  26974. this.nCachedObjects_ = 0; // threshold
  26975. // note: read by PropertyBinding.Composite
  26976. const indices = {};
  26977. this._indicesByUUID = indices; // for bookkeeping
  26978. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  26979. indices[ arguments[ i ].uuid ] = i;
  26980. }
  26981. this._paths = []; // inside: string
  26982. this._parsedPaths = []; // inside: { we don't care, here }
  26983. this._bindings = []; // inside: Array< PropertyBinding >
  26984. this._bindingsIndicesByPath = {}; // inside: indices in these arrays
  26985. const scope = this;
  26986. this.stats = {
  26987. objects: {
  26988. get total() {
  26989. return scope._objects.length;
  26990. },
  26991. get inUse() {
  26992. return this.total - scope.nCachedObjects_;
  26993. }
  26994. },
  26995. get bindingsPerObject() {
  26996. return scope._bindings.length;
  26997. }
  26998. };
  26999. }
  27000. add() {
  27001. const objects = this._objects,
  27002. indicesByUUID = this._indicesByUUID,
  27003. paths = this._paths,
  27004. parsedPaths = this._parsedPaths,
  27005. bindings = this._bindings,
  27006. nBindings = bindings.length;
  27007. let knownObject = undefined,
  27008. nObjects = objects.length,
  27009. nCachedObjects = this.nCachedObjects_;
  27010. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  27011. const object = arguments[ i ],
  27012. uuid = object.uuid;
  27013. let index = indicesByUUID[ uuid ];
  27014. if ( index === undefined ) {
  27015. // unknown object -> add it to the ACTIVE region
  27016. index = nObjects ++;
  27017. indicesByUUID[ uuid ] = index;
  27018. objects.push( object );
  27019. // accounting is done, now do the same for all bindings
  27020. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  27021. bindings[ j ].push( new PropertyBinding( object, paths[ j ], parsedPaths[ j ] ) );
  27022. }
  27023. } else if ( index < nCachedObjects ) {
  27024. knownObject = objects[ index ];
  27025. // move existing object to the ACTIVE region
  27026. const firstActiveIndex = -- nCachedObjects,
  27027. lastCachedObject = objects[ firstActiveIndex ];
  27028. indicesByUUID[ lastCachedObject.uuid ] = index;
  27029. objects[ index ] = lastCachedObject;
  27030. indicesByUUID[ uuid ] = firstActiveIndex;
  27031. objects[ firstActiveIndex ] = object;
  27032. // accounting is done, now do the same for all bindings
  27033. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  27034. const bindingsForPath = bindings[ j ],
  27035. lastCached = bindingsForPath[ firstActiveIndex ];
  27036. let binding = bindingsForPath[ index ];
  27037. bindingsForPath[ index ] = lastCached;
  27038. if ( binding === undefined ) {
  27039. // since we do not bother to create new bindings
  27040. // for objects that are cached, the binding may
  27041. // or may not exist
  27042. binding = new PropertyBinding( object, paths[ j ], parsedPaths[ j ] );
  27043. }
  27044. bindingsForPath[ firstActiveIndex ] = binding;
  27045. }
  27046. } else if ( objects[ index ] !== knownObject ) {
  27047. console.error( 'THREE.AnimationObjectGroup: Different objects with the same UUID ' +
  27048. 'detected. Clean the caches or recreate your infrastructure when reloading scenes.' );
  27049. } // else the object is already where we want it to be
  27050. } // for arguments
  27051. this.nCachedObjects_ = nCachedObjects;
  27052. }
  27053. remove() {
  27054. const objects = this._objects,
  27055. indicesByUUID = this._indicesByUUID,
  27056. bindings = this._bindings,
  27057. nBindings = bindings.length;
  27058. let nCachedObjects = this.nCachedObjects_;
  27059. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  27060. const object = arguments[ i ],
  27061. uuid = object.uuid,
  27062. index = indicesByUUID[ uuid ];
  27063. if ( index !== undefined && index >= nCachedObjects ) {
  27064. // move existing object into the CACHED region
  27065. const lastCachedIndex = nCachedObjects ++,
  27066. firstActiveObject = objects[ lastCachedIndex ];
  27067. indicesByUUID[ firstActiveObject.uuid ] = index;
  27068. objects[ index ] = firstActiveObject;
  27069. indicesByUUID[ uuid ] = lastCachedIndex;
  27070. objects[ lastCachedIndex ] = object;
  27071. // accounting is done, now do the same for all bindings
  27072. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  27073. const bindingsForPath = bindings[ j ],
  27074. firstActive = bindingsForPath[ lastCachedIndex ],
  27075. binding = bindingsForPath[ index ];
  27076. bindingsForPath[ index ] = firstActive;
  27077. bindingsForPath[ lastCachedIndex ] = binding;
  27078. }
  27079. }
  27080. } // for arguments
  27081. this.nCachedObjects_ = nCachedObjects;
  27082. }
  27083. // remove & forget
  27084. uncache() {
  27085. const objects = this._objects,
  27086. indicesByUUID = this._indicesByUUID,
  27087. bindings = this._bindings,
  27088. nBindings = bindings.length;
  27089. let nCachedObjects = this.nCachedObjects_,
  27090. nObjects = objects.length;
  27091. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  27092. const object = arguments[ i ],
  27093. uuid = object.uuid,
  27094. index = indicesByUUID[ uuid ];
  27095. if ( index !== undefined ) {
  27096. delete indicesByUUID[ uuid ];
  27097. if ( index < nCachedObjects ) {
  27098. // object is cached, shrink the CACHED region
  27099. const firstActiveIndex = -- nCachedObjects,
  27100. lastCachedObject = objects[ firstActiveIndex ],
  27101. lastIndex = -- nObjects,
  27102. lastObject = objects[ lastIndex ];
  27103. // last cached object takes this object's place
  27104. indicesByUUID[ lastCachedObject.uuid ] = index;
  27105. objects[ index ] = lastCachedObject;
  27106. // last object goes to the activated slot and pop
  27107. indicesByUUID[ lastObject.uuid ] = firstActiveIndex;
  27108. objects[ firstActiveIndex ] = lastObject;
  27109. objects.pop();
  27110. // accounting is done, now do the same for all bindings
  27111. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  27112. const bindingsForPath = bindings[ j ],
  27113. lastCached = bindingsForPath[ firstActiveIndex ],
  27114. last = bindingsForPath[ lastIndex ];
  27115. bindingsForPath[ index ] = lastCached;
  27116. bindingsForPath[ firstActiveIndex ] = last;
  27117. bindingsForPath.pop();
  27118. }
  27119. } else {
  27120. // object is active, just swap with the last and pop
  27121. const lastIndex = -- nObjects,
  27122. lastObject = objects[ lastIndex ];
  27123. if ( lastIndex > 0 ) {
  27124. indicesByUUID[ lastObject.uuid ] = index;
  27125. }
  27126. objects[ index ] = lastObject;
  27127. objects.pop();
  27128. // accounting is done, now do the same for all bindings
  27129. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  27130. const bindingsForPath = bindings[ j ];
  27131. bindingsForPath[ index ] = bindingsForPath[ lastIndex ];
  27132. bindingsForPath.pop();
  27133. }
  27134. } // cached or active
  27135. } // if object is known
  27136. } // for arguments
  27137. this.nCachedObjects_ = nCachedObjects;
  27138. }
  27139. // Internal interface used by befriended PropertyBinding.Composite:
  27140. subscribe_( path, parsedPath ) {
  27141. // returns an array of bindings for the given path that is changed
  27142. // according to the contained objects in the group
  27143. const indicesByPath = this._bindingsIndicesByPath;
  27144. let index = indicesByPath[ path ];
  27145. const bindings = this._bindings;
  27146. if ( index !== undefined ) return bindings[ index ];
  27147. const paths = this._paths,
  27148. parsedPaths = this._parsedPaths,
  27149. objects = this._objects,
  27150. nObjects = objects.length,
  27151. nCachedObjects = this.nCachedObjects_,
  27152. bindingsForPath = new Array( nObjects );
  27153. index = bindings.length;
  27154. indicesByPath[ path ] = index;
  27155. paths.push( path );
  27156. parsedPaths.push( parsedPath );
  27157. bindings.push( bindingsForPath );
  27158. for ( let i = nCachedObjects, n = objects.length; i !== n; ++ i ) {
  27159. const object = objects[ i ];
  27160. bindingsForPath[ i ] = new PropertyBinding( object, path, parsedPath );
  27161. }
  27162. return bindingsForPath;
  27163. }
  27164. unsubscribe_( path ) {
  27165. // tells the group to forget about a property path and no longer
  27166. // update the array previously obtained with 'subscribe_'
  27167. const indicesByPath = this._bindingsIndicesByPath,
  27168. index = indicesByPath[ path ];
  27169. if ( index !== undefined ) {
  27170. const paths = this._paths,
  27171. parsedPaths = this._parsedPaths,
  27172. bindings = this._bindings,
  27173. lastBindingsIndex = bindings.length - 1,
  27174. lastBindings = bindings[ lastBindingsIndex ],
  27175. lastBindingsPath = path[ lastBindingsIndex ];
  27176. indicesByPath[ lastBindingsPath ] = index;
  27177. bindings[ index ] = lastBindings;
  27178. bindings.pop();
  27179. parsedPaths[ index ] = parsedPaths[ lastBindingsIndex ];
  27180. parsedPaths.pop();
  27181. paths[ index ] = paths[ lastBindingsIndex ];
  27182. paths.pop();
  27183. }
  27184. }
  27185. }
  27186. class AnimationAction {
  27187. constructor( mixer, clip, localRoot = null, blendMode = clip.blendMode ) {
  27188. this._mixer = mixer;
  27189. this._clip = clip;
  27190. this._localRoot = localRoot;
  27191. this.blendMode = blendMode;
  27192. const tracks = clip.tracks,
  27193. nTracks = tracks.length,
  27194. interpolants = new Array( nTracks );
  27195. const interpolantSettings = {
  27196. endingStart: ZeroCurvatureEnding,
  27197. endingEnd: ZeroCurvatureEnding
  27198. };
  27199. for ( let i = 0; i !== nTracks; ++ i ) {
  27200. const interpolant = tracks[ i ].createInterpolant( null );
  27201. interpolants[ i ] = interpolant;
  27202. interpolant.settings = interpolantSettings;
  27203. }
  27204. this._interpolantSettings = interpolantSettings;
  27205. this._interpolants = interpolants; // bound by the mixer
  27206. // inside: PropertyMixer (managed by the mixer)
  27207. this._propertyBindings = new Array( nTracks );
  27208. this._cacheIndex = null; // for the memory manager
  27209. this._byClipCacheIndex = null; // for the memory manager
  27210. this._timeScaleInterpolant = null;
  27211. this._weightInterpolant = null;
  27212. this.loop = LoopRepeat;
  27213. this._loopCount = - 1;
  27214. // global mixer time when the action is to be started
  27215. // it's set back to 'null' upon start of the action
  27216. this._startTime = null;
  27217. // scaled local time of the action
  27218. // gets clamped or wrapped to 0..clip.duration according to loop
  27219. this.time = 0;
  27220. this.timeScale = 1;
  27221. this._effectiveTimeScale = 1;
  27222. this.weight = 1;
  27223. this._effectiveWeight = 1;
  27224. this.repetitions = Infinity; // no. of repetitions when looping
  27225. this.paused = false; // true -> zero effective time scale
  27226. this.enabled = true; // false -> zero effective weight
  27227. this.clampWhenFinished = false;// keep feeding the last frame?
  27228. this.zeroSlopeAtStart = true;// for smooth interpolation w/o separate
  27229. this.zeroSlopeAtEnd = true;// clips for start, loop and end
  27230. }
  27231. // State & Scheduling
  27232. play() {
  27233. this._mixer._activateAction( this );
  27234. return this;
  27235. }
  27236. stop() {
  27237. this._mixer._deactivateAction( this );
  27238. return this.reset();
  27239. }
  27240. reset() {
  27241. this.paused = false;
  27242. this.enabled = true;
  27243. this.time = 0; // restart clip
  27244. this._loopCount = - 1;// forget previous loops
  27245. this._startTime = null;// forget scheduling
  27246. return this.stopFading().stopWarping();
  27247. }
  27248. isRunning() {
  27249. return this.enabled && ! this.paused && this.timeScale !== 0 &&
  27250. this._startTime === null && this._mixer._isActiveAction( this );
  27251. }
  27252. // return true when play has been called
  27253. isScheduled() {
  27254. return this._mixer._isActiveAction( this );
  27255. }
  27256. startAt( time ) {
  27257. this._startTime = time;
  27258. return this;
  27259. }
  27260. setLoop( mode, repetitions ) {
  27261. this.loop = mode;
  27262. this.repetitions = repetitions;
  27263. return this;
  27264. }
  27265. // Weight
  27266. // set the weight stopping any scheduled fading
  27267. // although .enabled = false yields an effective weight of zero, this
  27268. // method does *not* change .enabled, because it would be confusing
  27269. setEffectiveWeight( weight ) {
  27270. this.weight = weight;
  27271. // note: same logic as when updated at runtime
  27272. this._effectiveWeight = this.enabled ? weight : 0;
  27273. return this.stopFading();
  27274. }
  27275. // return the weight considering fading and .enabled
  27276. getEffectiveWeight() {
  27277. return this._effectiveWeight;
  27278. }
  27279. fadeIn( duration ) {
  27280. return this._scheduleFading( duration, 0, 1 );
  27281. }
  27282. fadeOut( duration ) {
  27283. return this._scheduleFading( duration, 1, 0 );
  27284. }
  27285. crossFadeFrom( fadeOutAction, duration, warp ) {
  27286. fadeOutAction.fadeOut( duration );
  27287. this.fadeIn( duration );
  27288. if ( warp ) {
  27289. const fadeInDuration = this._clip.duration,
  27290. fadeOutDuration = fadeOutAction._clip.duration,
  27291. startEndRatio = fadeOutDuration / fadeInDuration,
  27292. endStartRatio = fadeInDuration / fadeOutDuration;
  27293. fadeOutAction.warp( 1.0, startEndRatio, duration );
  27294. this.warp( endStartRatio, 1.0, duration );
  27295. }
  27296. return this;
  27297. }
  27298. crossFadeTo( fadeInAction, duration, warp ) {
  27299. return fadeInAction.crossFadeFrom( this, duration, warp );
  27300. }
  27301. stopFading() {
  27302. const weightInterpolant = this._weightInterpolant;
  27303. if ( weightInterpolant !== null ) {
  27304. this._weightInterpolant = null;
  27305. this._mixer._takeBackControlInterpolant( weightInterpolant );
  27306. }
  27307. return this;
  27308. }
  27309. // Time Scale Control
  27310. // set the time scale stopping any scheduled warping
  27311. // although .paused = true yields an effective time scale of zero, this
  27312. // method does *not* change .paused, because it would be confusing
  27313. setEffectiveTimeScale( timeScale ) {
  27314. this.timeScale = timeScale;
  27315. this._effectiveTimeScale = this.paused ? 0 : timeScale;
  27316. return this.stopWarping();
  27317. }
  27318. // return the time scale considering warping and .paused
  27319. getEffectiveTimeScale() {
  27320. return this._effectiveTimeScale;
  27321. }
  27322. setDuration( duration ) {
  27323. this.timeScale = this._clip.duration / duration;
  27324. return this.stopWarping();
  27325. }
  27326. syncWith( action ) {
  27327. this.time = action.time;
  27328. this.timeScale = action.timeScale;
  27329. return this.stopWarping();
  27330. }
  27331. halt( duration ) {
  27332. return this.warp( this._effectiveTimeScale, 0, duration );
  27333. }
  27334. warp( startTimeScale, endTimeScale, duration ) {
  27335. const mixer = this._mixer,
  27336. now = mixer.time,
  27337. timeScale = this.timeScale;
  27338. let interpolant = this._timeScaleInterpolant;
  27339. if ( interpolant === null ) {
  27340. interpolant = mixer._lendControlInterpolant();
  27341. this._timeScaleInterpolant = interpolant;
  27342. }
  27343. const times = interpolant.parameterPositions,
  27344. values = interpolant.sampleValues;
  27345. times[ 0 ] = now;
  27346. times[ 1 ] = now + duration;
  27347. values[ 0 ] = startTimeScale / timeScale;
  27348. values[ 1 ] = endTimeScale / timeScale;
  27349. return this;
  27350. }
  27351. stopWarping() {
  27352. const timeScaleInterpolant = this._timeScaleInterpolant;
  27353. if ( timeScaleInterpolant !== null ) {
  27354. this._timeScaleInterpolant = null;
  27355. this._mixer._takeBackControlInterpolant( timeScaleInterpolant );
  27356. }
  27357. return this;
  27358. }
  27359. // Object Accessors
  27360. getMixer() {
  27361. return this._mixer;
  27362. }
  27363. getClip() {
  27364. return this._clip;
  27365. }
  27366. getRoot() {
  27367. return this._localRoot || this._mixer._root;
  27368. }
  27369. // Interna
  27370. _update( time, deltaTime, timeDirection, accuIndex ) {
  27371. // called by the mixer
  27372. if ( ! this.enabled ) {
  27373. // call ._updateWeight() to update ._effectiveWeight
  27374. this._updateWeight( time );
  27375. return;
  27376. }
  27377. const startTime = this._startTime;
  27378. if ( startTime !== null ) {
  27379. // check for scheduled start of action
  27380. const timeRunning = ( time - startTime ) * timeDirection;
  27381. if ( timeRunning < 0 || timeDirection === 0 ) {
  27382. deltaTime = 0;
  27383. } else {
  27384. this._startTime = null; // unschedule
  27385. deltaTime = timeDirection * timeRunning;
  27386. }
  27387. }
  27388. // apply time scale and advance time
  27389. deltaTime *= this._updateTimeScale( time );
  27390. const clipTime = this._updateTime( deltaTime );
  27391. // note: _updateTime may disable the action resulting in
  27392. // an effective weight of 0
  27393. const weight = this._updateWeight( time );
  27394. if ( weight > 0 ) {
  27395. const interpolants = this._interpolants;
  27396. const propertyMixers = this._propertyBindings;
  27397. switch ( this.blendMode ) {
  27398. case AdditiveAnimationBlendMode:
  27399. for ( let j = 0, m = interpolants.length; j !== m; ++ j ) {
  27400. interpolants[ j ].evaluate( clipTime );
  27401. propertyMixers[ j ].accumulateAdditive( weight );
  27402. }
  27403. break;
  27404. case NormalAnimationBlendMode:
  27405. default:
  27406. for ( let j = 0, m = interpolants.length; j !== m; ++ j ) {
  27407. interpolants[ j ].evaluate( clipTime );
  27408. propertyMixers[ j ].accumulate( accuIndex, weight );
  27409. }
  27410. }
  27411. }
  27412. }
  27413. _updateWeight( time ) {
  27414. let weight = 0;
  27415. if ( this.enabled ) {
  27416. weight = this.weight;
  27417. const interpolant = this._weightInterpolant;
  27418. if ( interpolant !== null ) {
  27419. const interpolantValue = interpolant.evaluate( time )[ 0 ];
  27420. weight *= interpolantValue;
  27421. if ( time > interpolant.parameterPositions[ 1 ] ) {
  27422. this.stopFading();
  27423. if ( interpolantValue === 0 ) {
  27424. // faded out, disable
  27425. this.enabled = false;
  27426. }
  27427. }
  27428. }
  27429. }
  27430. this._effectiveWeight = weight;
  27431. return weight;
  27432. }
  27433. _updateTimeScale( time ) {
  27434. let timeScale = 0;
  27435. if ( ! this.paused ) {
  27436. timeScale = this.timeScale;
  27437. const interpolant = this._timeScaleInterpolant;
  27438. if ( interpolant !== null ) {
  27439. const interpolantValue = interpolant.evaluate( time )[ 0 ];
  27440. timeScale *= interpolantValue;
  27441. if ( time > interpolant.parameterPositions[ 1 ] ) {
  27442. this.stopWarping();
  27443. if ( timeScale === 0 ) {
  27444. // motion has halted, pause
  27445. this.paused = true;
  27446. } else {
  27447. // warp done - apply final time scale
  27448. this.timeScale = timeScale;
  27449. }
  27450. }
  27451. }
  27452. }
  27453. this._effectiveTimeScale = timeScale;
  27454. return timeScale;
  27455. }
  27456. _updateTime( deltaTime ) {
  27457. const duration = this._clip.duration;
  27458. const loop = this.loop;
  27459. let time = this.time + deltaTime;
  27460. let loopCount = this._loopCount;
  27461. const pingPong = ( loop === LoopPingPong );
  27462. if ( deltaTime === 0 ) {
  27463. if ( loopCount === - 1 ) return time;
  27464. return ( pingPong && ( loopCount & 1 ) === 1 ) ? duration - time : time;
  27465. }
  27466. if ( loop === LoopOnce ) {
  27467. if ( loopCount === - 1 ) {
  27468. // just started
  27469. this._loopCount = 0;
  27470. this._setEndings( true, true, false );
  27471. }
  27472. handle_stop: {
  27473. if ( time >= duration ) {
  27474. time = duration;
  27475. } else if ( time < 0 ) {
  27476. time = 0;
  27477. } else {
  27478. this.time = time;
  27479. break handle_stop;
  27480. }
  27481. if ( this.clampWhenFinished ) this.paused = true;
  27482. else this.enabled = false;
  27483. this.time = time;
  27484. this._mixer.dispatchEvent( {
  27485. type: 'finished', action: this,
  27486. direction: deltaTime < 0 ? - 1 : 1
  27487. } );
  27488. }
  27489. } else { // repetitive Repeat or PingPong
  27490. if ( loopCount === - 1 ) {
  27491. // just started
  27492. if ( deltaTime >= 0 ) {
  27493. loopCount = 0;
  27494. this._setEndings( true, this.repetitions === 0, pingPong );
  27495. } else {
  27496. // when looping in reverse direction, the initial
  27497. // transition through zero counts as a repetition,
  27498. // so leave loopCount at -1
  27499. this._setEndings( this.repetitions === 0, true, pingPong );
  27500. }
  27501. }
  27502. if ( time >= duration || time < 0 ) {
  27503. // wrap around
  27504. const loopDelta = Math.floor( time / duration ); // signed
  27505. time -= duration * loopDelta;
  27506. loopCount += Math.abs( loopDelta );
  27507. const pending = this.repetitions - loopCount;
  27508. if ( pending <= 0 ) {
  27509. // have to stop (switch state, clamp time, fire event)
  27510. if ( this.clampWhenFinished ) this.paused = true;
  27511. else this.enabled = false;
  27512. time = deltaTime > 0 ? duration : 0;
  27513. this.time = time;
  27514. this._mixer.dispatchEvent( {
  27515. type: 'finished', action: this,
  27516. direction: deltaTime > 0 ? 1 : - 1
  27517. } );
  27518. } else {
  27519. // keep running
  27520. if ( pending === 1 ) {
  27521. // entering the last round
  27522. const atStart = deltaTime < 0;
  27523. this._setEndings( atStart, ! atStart, pingPong );
  27524. } else {
  27525. this._setEndings( false, false, pingPong );
  27526. }
  27527. this._loopCount = loopCount;
  27528. this.time = time;
  27529. this._mixer.dispatchEvent( {
  27530. type: 'loop', action: this, loopDelta: loopDelta
  27531. } );
  27532. }
  27533. } else {
  27534. this.time = time;
  27535. }
  27536. if ( pingPong && ( loopCount & 1 ) === 1 ) {
  27537. // invert time for the "pong round"
  27538. return duration - time;
  27539. }
  27540. }
  27541. return time;
  27542. }
  27543. _setEndings( atStart, atEnd, pingPong ) {
  27544. const settings = this._interpolantSettings;
  27545. if ( pingPong ) {
  27546. settings.endingStart = ZeroSlopeEnding;
  27547. settings.endingEnd = ZeroSlopeEnding;
  27548. } else {
  27549. // assuming for LoopOnce atStart == atEnd == true
  27550. if ( atStart ) {
  27551. settings.endingStart = this.zeroSlopeAtStart ? ZeroSlopeEnding : ZeroCurvatureEnding;
  27552. } else {
  27553. settings.endingStart = WrapAroundEnding;
  27554. }
  27555. if ( atEnd ) {
  27556. settings.endingEnd = this.zeroSlopeAtEnd ? ZeroSlopeEnding : ZeroCurvatureEnding;
  27557. } else {
  27558. settings.endingEnd = WrapAroundEnding;
  27559. }
  27560. }
  27561. }
  27562. _scheduleFading( duration, weightNow, weightThen ) {
  27563. const mixer = this._mixer, now = mixer.time;
  27564. let interpolant = this._weightInterpolant;
  27565. if ( interpolant === null ) {
  27566. interpolant = mixer._lendControlInterpolant();
  27567. this._weightInterpolant = interpolant;
  27568. }
  27569. const times = interpolant.parameterPositions,
  27570. values = interpolant.sampleValues;
  27571. times[ 0 ] = now;
  27572. values[ 0 ] = weightNow;
  27573. times[ 1 ] = now + duration;
  27574. values[ 1 ] = weightThen;
  27575. return this;
  27576. }
  27577. }
  27578. const _controlInterpolantsResultBuffer = new Float32Array( 1 );
  27579. class AnimationMixer extends EventDispatcher {
  27580. constructor( root ) {
  27581. super();
  27582. this._root = root;
  27583. this._initMemoryManager();
  27584. this._accuIndex = 0;
  27585. this.time = 0;
  27586. this.timeScale = 1.0;
  27587. }
  27588. _bindAction( action, prototypeAction ) {
  27589. const root = action._localRoot || this._root,
  27590. tracks = action._clip.tracks,
  27591. nTracks = tracks.length,
  27592. bindings = action._propertyBindings,
  27593. interpolants = action._interpolants,
  27594. rootUuid = root.uuid,
  27595. bindingsByRoot = this._bindingsByRootAndName;
  27596. let bindingsByName = bindingsByRoot[ rootUuid ];
  27597. if ( bindingsByName === undefined ) {
  27598. bindingsByName = {};
  27599. bindingsByRoot[ rootUuid ] = bindingsByName;
  27600. }
  27601. for ( let i = 0; i !== nTracks; ++ i ) {
  27602. const track = tracks[ i ],
  27603. trackName = track.name;
  27604. let binding = bindingsByName[ trackName ];
  27605. if ( binding !== undefined ) {
  27606. ++ binding.referenceCount;
  27607. bindings[ i ] = binding;
  27608. } else {
  27609. binding = bindings[ i ];
  27610. if ( binding !== undefined ) {
  27611. // existing binding, make sure the cache knows
  27612. if ( binding._cacheIndex === null ) {
  27613. ++ binding.referenceCount;
  27614. this._addInactiveBinding( binding, rootUuid, trackName );
  27615. }
  27616. continue;
  27617. }
  27618. const path = prototypeAction && prototypeAction.
  27619. _propertyBindings[ i ].binding.parsedPath;
  27620. binding = new PropertyMixer(
  27621. PropertyBinding.create( root, trackName, path ),
  27622. track.ValueTypeName, track.getValueSize() );
  27623. ++ binding.referenceCount;
  27624. this._addInactiveBinding( binding, rootUuid, trackName );
  27625. bindings[ i ] = binding;
  27626. }
  27627. interpolants[ i ].resultBuffer = binding.buffer;
  27628. }
  27629. }
  27630. _activateAction( action ) {
  27631. if ( ! this._isActiveAction( action ) ) {
  27632. if ( action._cacheIndex === null ) {
  27633. // this action has been forgotten by the cache, but the user
  27634. // appears to be still using it -> rebind
  27635. const rootUuid = ( action._localRoot || this._root ).uuid,
  27636. clipUuid = action._clip.uuid,
  27637. actionsForClip = this._actionsByClip[ clipUuid ];
  27638. this._bindAction( action,
  27639. actionsForClip && actionsForClip.knownActions[ 0 ] );
  27640. this._addInactiveAction( action, clipUuid, rootUuid );
  27641. }
  27642. const bindings = action._propertyBindings;
  27643. // increment reference counts / sort out state
  27644. for ( let i = 0, n = bindings.length; i !== n; ++ i ) {
  27645. const binding = bindings[ i ];
  27646. if ( binding.useCount ++ === 0 ) {
  27647. this._lendBinding( binding );
  27648. binding.saveOriginalState();
  27649. }
  27650. }
  27651. this._lendAction( action );
  27652. }
  27653. }
  27654. _deactivateAction( action ) {
  27655. if ( this._isActiveAction( action ) ) {
  27656. const bindings = action._propertyBindings;
  27657. // decrement reference counts / sort out state
  27658. for ( let i = 0, n = bindings.length; i !== n; ++ i ) {
  27659. const binding = bindings[ i ];
  27660. if ( -- binding.useCount === 0 ) {
  27661. binding.restoreOriginalState();
  27662. this._takeBackBinding( binding );
  27663. }
  27664. }
  27665. this._takeBackAction( action );
  27666. }
  27667. }
  27668. // Memory manager
  27669. _initMemoryManager() {
  27670. this._actions = []; // 'nActiveActions' followed by inactive ones
  27671. this._nActiveActions = 0;
  27672. this._actionsByClip = {};
  27673. // inside:
  27674. // {
  27675. // knownActions: Array< AnimationAction > - used as prototypes
  27676. // actionByRoot: AnimationAction - lookup
  27677. // }
  27678. this._bindings = []; // 'nActiveBindings' followed by inactive ones
  27679. this._nActiveBindings = 0;
  27680. this._bindingsByRootAndName = {}; // inside: Map< name, PropertyMixer >
  27681. this._controlInterpolants = []; // same game as above
  27682. this._nActiveControlInterpolants = 0;
  27683. const scope = this;
  27684. this.stats = {
  27685. actions: {
  27686. get total() {
  27687. return scope._actions.length;
  27688. },
  27689. get inUse() {
  27690. return scope._nActiveActions;
  27691. }
  27692. },
  27693. bindings: {
  27694. get total() {
  27695. return scope._bindings.length;
  27696. },
  27697. get inUse() {
  27698. return scope._nActiveBindings;
  27699. }
  27700. },
  27701. controlInterpolants: {
  27702. get total() {
  27703. return scope._controlInterpolants.length;
  27704. },
  27705. get inUse() {
  27706. return scope._nActiveControlInterpolants;
  27707. }
  27708. }
  27709. };
  27710. }
  27711. // Memory management for AnimationAction objects
  27712. _isActiveAction( action ) {
  27713. const index = action._cacheIndex;
  27714. return index !== null && index < this._nActiveActions;
  27715. }
  27716. _addInactiveAction( action, clipUuid, rootUuid ) {
  27717. const actions = this._actions,
  27718. actionsByClip = this._actionsByClip;
  27719. let actionsForClip = actionsByClip[ clipUuid ];
  27720. if ( actionsForClip === undefined ) {
  27721. actionsForClip = {
  27722. knownActions: [ action ],
  27723. actionByRoot: {}
  27724. };
  27725. action._byClipCacheIndex = 0;
  27726. actionsByClip[ clipUuid ] = actionsForClip;
  27727. } else {
  27728. const knownActions = actionsForClip.knownActions;
  27729. action._byClipCacheIndex = knownActions.length;
  27730. knownActions.push( action );
  27731. }
  27732. action._cacheIndex = actions.length;
  27733. actions.push( action );
  27734. actionsForClip.actionByRoot[ rootUuid ] = action;
  27735. }
  27736. _removeInactiveAction( action ) {
  27737. const actions = this._actions,
  27738. lastInactiveAction = actions[ actions.length - 1 ],
  27739. cacheIndex = action._cacheIndex;
  27740. lastInactiveAction._cacheIndex = cacheIndex;
  27741. actions[ cacheIndex ] = lastInactiveAction;
  27742. actions.pop();
  27743. action._cacheIndex = null;
  27744. const clipUuid = action._clip.uuid,
  27745. actionsByClip = this._actionsByClip,
  27746. actionsForClip = actionsByClip[ clipUuid ],
  27747. knownActionsForClip = actionsForClip.knownActions,
  27748. lastKnownAction =
  27749. knownActionsForClip[ knownActionsForClip.length - 1 ],
  27750. byClipCacheIndex = action._byClipCacheIndex;
  27751. lastKnownAction._byClipCacheIndex = byClipCacheIndex;
  27752. knownActionsForClip[ byClipCacheIndex ] = lastKnownAction;
  27753. knownActionsForClip.pop();
  27754. action._byClipCacheIndex = null;
  27755. const actionByRoot = actionsForClip.actionByRoot,
  27756. rootUuid = ( action._localRoot || this._root ).uuid;
  27757. delete actionByRoot[ rootUuid ];
  27758. if ( knownActionsForClip.length === 0 ) {
  27759. delete actionsByClip[ clipUuid ];
  27760. }
  27761. this._removeInactiveBindingsForAction( action );
  27762. }
  27763. _removeInactiveBindingsForAction( action ) {
  27764. const bindings = action._propertyBindings;
  27765. for ( let i = 0, n = bindings.length; i !== n; ++ i ) {
  27766. const binding = bindings[ i ];
  27767. if ( -- binding.referenceCount === 0 ) {
  27768. this._removeInactiveBinding( binding );
  27769. }
  27770. }
  27771. }
  27772. _lendAction( action ) {
  27773. // [ active actions | inactive actions ]
  27774. // [ active actions >| inactive actions ]
  27775. // s a
  27776. // <-swap->
  27777. // a s
  27778. const actions = this._actions,
  27779. prevIndex = action._cacheIndex,
  27780. lastActiveIndex = this._nActiveActions ++,
  27781. firstInactiveAction = actions[ lastActiveIndex ];
  27782. action._cacheIndex = lastActiveIndex;
  27783. actions[ lastActiveIndex ] = action;
  27784. firstInactiveAction._cacheIndex = prevIndex;
  27785. actions[ prevIndex ] = firstInactiveAction;
  27786. }
  27787. _takeBackAction( action ) {
  27788. // [ active actions | inactive actions ]
  27789. // [ active actions |< inactive actions ]
  27790. // a s
  27791. // <-swap->
  27792. // s a
  27793. const actions = this._actions,
  27794. prevIndex = action._cacheIndex,
  27795. firstInactiveIndex = -- this._nActiveActions,
  27796. lastActiveAction = actions[ firstInactiveIndex ];
  27797. action._cacheIndex = firstInactiveIndex;
  27798. actions[ firstInactiveIndex ] = action;
  27799. lastActiveAction._cacheIndex = prevIndex;
  27800. actions[ prevIndex ] = lastActiveAction;
  27801. }
  27802. // Memory management for PropertyMixer objects
  27803. _addInactiveBinding( binding, rootUuid, trackName ) {
  27804. const bindingsByRoot = this._bindingsByRootAndName,
  27805. bindings = this._bindings;
  27806. let bindingByName = bindingsByRoot[ rootUuid ];
  27807. if ( bindingByName === undefined ) {
  27808. bindingByName = {};
  27809. bindingsByRoot[ rootUuid ] = bindingByName;
  27810. }
  27811. bindingByName[ trackName ] = binding;
  27812. binding._cacheIndex = bindings.length;
  27813. bindings.push( binding );
  27814. }
  27815. _removeInactiveBinding( binding ) {
  27816. const bindings = this._bindings,
  27817. propBinding = binding.binding,
  27818. rootUuid = propBinding.rootNode.uuid,
  27819. trackName = propBinding.path,
  27820. bindingsByRoot = this._bindingsByRootAndName,
  27821. bindingByName = bindingsByRoot[ rootUuid ],
  27822. lastInactiveBinding = bindings[ bindings.length - 1 ],
  27823. cacheIndex = binding._cacheIndex;
  27824. lastInactiveBinding._cacheIndex = cacheIndex;
  27825. bindings[ cacheIndex ] = lastInactiveBinding;
  27826. bindings.pop();
  27827. delete bindingByName[ trackName ];
  27828. if ( Object.keys( bindingByName ).length === 0 ) {
  27829. delete bindingsByRoot[ rootUuid ];
  27830. }
  27831. }
  27832. _lendBinding( binding ) {
  27833. const bindings = this._bindings,
  27834. prevIndex = binding._cacheIndex,
  27835. lastActiveIndex = this._nActiveBindings ++,
  27836. firstInactiveBinding = bindings[ lastActiveIndex ];
  27837. binding._cacheIndex = lastActiveIndex;
  27838. bindings[ lastActiveIndex ] = binding;
  27839. firstInactiveBinding._cacheIndex = prevIndex;
  27840. bindings[ prevIndex ] = firstInactiveBinding;
  27841. }
  27842. _takeBackBinding( binding ) {
  27843. const bindings = this._bindings,
  27844. prevIndex = binding._cacheIndex,
  27845. firstInactiveIndex = -- this._nActiveBindings,
  27846. lastActiveBinding = bindings[ firstInactiveIndex ];
  27847. binding._cacheIndex = firstInactiveIndex;
  27848. bindings[ firstInactiveIndex ] = binding;
  27849. lastActiveBinding._cacheIndex = prevIndex;
  27850. bindings[ prevIndex ] = lastActiveBinding;
  27851. }
  27852. // Memory management of Interpolants for weight and time scale
  27853. _lendControlInterpolant() {
  27854. const interpolants = this._controlInterpolants,
  27855. lastActiveIndex = this._nActiveControlInterpolants ++;
  27856. let interpolant = interpolants[ lastActiveIndex ];
  27857. if ( interpolant === undefined ) {
  27858. interpolant = new LinearInterpolant(
  27859. new Float32Array( 2 ), new Float32Array( 2 ),
  27860. 1, _controlInterpolantsResultBuffer );
  27861. interpolant.__cacheIndex = lastActiveIndex;
  27862. interpolants[ lastActiveIndex ] = interpolant;
  27863. }
  27864. return interpolant;
  27865. }
  27866. _takeBackControlInterpolant( interpolant ) {
  27867. const interpolants = this._controlInterpolants,
  27868. prevIndex = interpolant.__cacheIndex,
  27869. firstInactiveIndex = -- this._nActiveControlInterpolants,
  27870. lastActiveInterpolant = interpolants[ firstInactiveIndex ];
  27871. interpolant.__cacheIndex = firstInactiveIndex;
  27872. interpolants[ firstInactiveIndex ] = interpolant;
  27873. lastActiveInterpolant.__cacheIndex = prevIndex;
  27874. interpolants[ prevIndex ] = lastActiveInterpolant;
  27875. }
  27876. // return an action for a clip optionally using a custom root target
  27877. // object (this method allocates a lot of dynamic memory in case a
  27878. // previously unknown clip/root combination is specified)
  27879. clipAction( clip, optionalRoot, blendMode ) {
  27880. const root = optionalRoot || this._root,
  27881. rootUuid = root.uuid;
  27882. let clipObject = typeof clip === 'string' ? AnimationClip.findByName( root, clip ) : clip;
  27883. const clipUuid = clipObject !== null ? clipObject.uuid : clip;
  27884. const actionsForClip = this._actionsByClip[ clipUuid ];
  27885. let prototypeAction = null;
  27886. if ( blendMode === undefined ) {
  27887. if ( clipObject !== null ) {
  27888. blendMode = clipObject.blendMode;
  27889. } else {
  27890. blendMode = NormalAnimationBlendMode;
  27891. }
  27892. }
  27893. if ( actionsForClip !== undefined ) {
  27894. const existingAction = actionsForClip.actionByRoot[ rootUuid ];
  27895. if ( existingAction !== undefined && existingAction.blendMode === blendMode ) {
  27896. return existingAction;
  27897. }
  27898. // we know the clip, so we don't have to parse all
  27899. // the bindings again but can just copy
  27900. prototypeAction = actionsForClip.knownActions[ 0 ];
  27901. // also, take the clip from the prototype action
  27902. if ( clipObject === null )
  27903. clipObject = prototypeAction._clip;
  27904. }
  27905. // clip must be known when specified via string
  27906. if ( clipObject === null ) return null;
  27907. // allocate all resources required to run it
  27908. const newAction = new AnimationAction( this, clipObject, optionalRoot, blendMode );
  27909. this._bindAction( newAction, prototypeAction );
  27910. // and make the action known to the memory manager
  27911. this._addInactiveAction( newAction, clipUuid, rootUuid );
  27912. return newAction;
  27913. }
  27914. // get an existing action
  27915. existingAction( clip, optionalRoot ) {
  27916. const root = optionalRoot || this._root,
  27917. rootUuid = root.uuid,
  27918. clipObject = typeof clip === 'string' ?
  27919. AnimationClip.findByName( root, clip ) : clip,
  27920. clipUuid = clipObject ? clipObject.uuid : clip,
  27921. actionsForClip = this._actionsByClip[ clipUuid ];
  27922. if ( actionsForClip !== undefined ) {
  27923. return actionsForClip.actionByRoot[ rootUuid ] || null;
  27924. }
  27925. return null;
  27926. }
  27927. // deactivates all previously scheduled actions
  27928. stopAllAction() {
  27929. const actions = this._actions,
  27930. nActions = this._nActiveActions;
  27931. for ( let i = nActions - 1; i >= 0; -- i ) {
  27932. actions[ i ].stop();
  27933. }
  27934. return this;
  27935. }
  27936. // advance the time and update apply the animation
  27937. update( deltaTime ) {
  27938. deltaTime *= this.timeScale;
  27939. const actions = this._actions,
  27940. nActions = this._nActiveActions,
  27941. time = this.time += deltaTime,
  27942. timeDirection = Math.sign( deltaTime ),
  27943. accuIndex = this._accuIndex ^= 1;
  27944. // run active actions
  27945. for ( let i = 0; i !== nActions; ++ i ) {
  27946. const action = actions[ i ];
  27947. action._update( time, deltaTime, timeDirection, accuIndex );
  27948. }
  27949. // update scene graph
  27950. const bindings = this._bindings,
  27951. nBindings = this._nActiveBindings;
  27952. for ( let i = 0; i !== nBindings; ++ i ) {
  27953. bindings[ i ].apply( accuIndex );
  27954. }
  27955. return this;
  27956. }
  27957. // Allows you to seek to a specific time in an animation.
  27958. setTime( timeInSeconds ) {
  27959. this.time = 0; // Zero out time attribute for AnimationMixer object;
  27960. for ( let i = 0; i < this._actions.length; i ++ ) {
  27961. this._actions[ i ].time = 0; // Zero out time attribute for all associated AnimationAction objects.
  27962. }
  27963. return this.update( timeInSeconds ); // Update used to set exact time. Returns "this" AnimationMixer object.
  27964. }
  27965. // return this mixer's root target object
  27966. getRoot() {
  27967. return this._root;
  27968. }
  27969. // free all resources specific to a particular clip
  27970. uncacheClip( clip ) {
  27971. const actions = this._actions,
  27972. clipUuid = clip.uuid,
  27973. actionsByClip = this._actionsByClip,
  27974. actionsForClip = actionsByClip[ clipUuid ];
  27975. if ( actionsForClip !== undefined ) {
  27976. // note: just calling _removeInactiveAction would mess up the
  27977. // iteration state and also require updating the state we can
  27978. // just throw away
  27979. const actionsToRemove = actionsForClip.knownActions;
  27980. for ( let i = 0, n = actionsToRemove.length; i !== n; ++ i ) {
  27981. const action = actionsToRemove[ i ];
  27982. this._deactivateAction( action );
  27983. const cacheIndex = action._cacheIndex,
  27984. lastInactiveAction = actions[ actions.length - 1 ];
  27985. action._cacheIndex = null;
  27986. action._byClipCacheIndex = null;
  27987. lastInactiveAction._cacheIndex = cacheIndex;
  27988. actions[ cacheIndex ] = lastInactiveAction;
  27989. actions.pop();
  27990. this._removeInactiveBindingsForAction( action );
  27991. }
  27992. delete actionsByClip[ clipUuid ];
  27993. }
  27994. }
  27995. // free all resources specific to a particular root target object
  27996. uncacheRoot( root ) {
  27997. const rootUuid = root.uuid,
  27998. actionsByClip = this._actionsByClip;
  27999. for ( const clipUuid in actionsByClip ) {
  28000. const actionByRoot = actionsByClip[ clipUuid ].actionByRoot,
  28001. action = actionByRoot[ rootUuid ];
  28002. if ( action !== undefined ) {
  28003. this._deactivateAction( action );
  28004. this._removeInactiveAction( action );
  28005. }
  28006. }
  28007. const bindingsByRoot = this._bindingsByRootAndName,
  28008. bindingByName = bindingsByRoot[ rootUuid ];
  28009. if ( bindingByName !== undefined ) {
  28010. for ( const trackName in bindingByName ) {
  28011. const binding = bindingByName[ trackName ];
  28012. binding.restoreOriginalState();
  28013. this._removeInactiveBinding( binding );
  28014. }
  28015. }
  28016. }
  28017. // remove a targeted clip from the cache
  28018. uncacheAction( clip, optionalRoot ) {
  28019. const action = this.existingAction( clip, optionalRoot );
  28020. if ( action !== null ) {
  28021. this._deactivateAction( action );
  28022. this._removeInactiveAction( action );
  28023. }
  28024. }
  28025. }
  28026. class Uniform {
  28027. constructor( value ) {
  28028. this.value = value;
  28029. }
  28030. clone() {
  28031. return new Uniform( this.value.clone === undefined ? this.value : this.value.clone() );
  28032. }
  28033. }
  28034. let id = 0;
  28035. class UniformsGroup extends EventDispatcher {
  28036. constructor() {
  28037. super();
  28038. this.isUniformsGroup = true;
  28039. Object.defineProperty( this, 'id', { value: id ++ } );
  28040. this.name = '';
  28041. this.usage = StaticDrawUsage;
  28042. this.uniforms = [];
  28043. }
  28044. add( uniform ) {
  28045. this.uniforms.push( uniform );
  28046. return this;
  28047. }
  28048. remove( uniform ) {
  28049. const index = this.uniforms.indexOf( uniform );
  28050. if ( index !== - 1 ) this.uniforms.splice( index, 1 );
  28051. return this;
  28052. }
  28053. setName( name ) {
  28054. this.name = name;
  28055. return this;
  28056. }
  28057. setUsage( value ) {
  28058. this.usage = value;
  28059. return this;
  28060. }
  28061. dispose() {
  28062. this.dispatchEvent( { type: 'dispose' } );
  28063. return this;
  28064. }
  28065. copy( source ) {
  28066. this.name = source.name;
  28067. this.usage = source.usage;
  28068. const uniformsSource = source.uniforms;
  28069. this.uniforms.length = 0;
  28070. for ( let i = 0, l = uniformsSource.length; i < l; i ++ ) {
  28071. this.uniforms.push( uniformsSource[ i ].clone() );
  28072. }
  28073. return this;
  28074. }
  28075. clone() {
  28076. return new this.constructor().copy( this );
  28077. }
  28078. }
  28079. class InstancedInterleavedBuffer extends InterleavedBuffer {
  28080. constructor( array, stride, meshPerAttribute = 1 ) {
  28081. super( array, stride );
  28082. this.isInstancedInterleavedBuffer = true;
  28083. this.meshPerAttribute = meshPerAttribute;
  28084. }
  28085. copy( source ) {
  28086. super.copy( source );
  28087. this.meshPerAttribute = source.meshPerAttribute;
  28088. return this;
  28089. }
  28090. clone( data ) {
  28091. const ib = super.clone( data );
  28092. ib.meshPerAttribute = this.meshPerAttribute;
  28093. return ib;
  28094. }
  28095. toJSON( data ) {
  28096. const json = super.toJSON( data );
  28097. json.isInstancedInterleavedBuffer = true;
  28098. json.meshPerAttribute = this.meshPerAttribute;
  28099. return json;
  28100. }
  28101. }
  28102. class GLBufferAttribute {
  28103. constructor( buffer, type, itemSize, elementSize, count ) {
  28104. this.isGLBufferAttribute = true;
  28105. this.name = '';
  28106. this.buffer = buffer;
  28107. this.type = type;
  28108. this.itemSize = itemSize;
  28109. this.elementSize = elementSize;
  28110. this.count = count;
  28111. this.version = 0;
  28112. }
  28113. set needsUpdate( value ) {
  28114. if ( value === true ) this.version ++;
  28115. }
  28116. setBuffer( buffer ) {
  28117. this.buffer = buffer;
  28118. return this;
  28119. }
  28120. setType( type, elementSize ) {
  28121. this.type = type;
  28122. this.elementSize = elementSize;
  28123. return this;
  28124. }
  28125. setItemSize( itemSize ) {
  28126. this.itemSize = itemSize;
  28127. return this;
  28128. }
  28129. setCount( count ) {
  28130. this.count = count;
  28131. return this;
  28132. }
  28133. }
  28134. class Raycaster {
  28135. constructor( origin, direction, near = 0, far = Infinity ) {
  28136. this.ray = new Ray( origin, direction );
  28137. // direction is assumed to be normalized (for accurate distance calculations)
  28138. this.near = near;
  28139. this.far = far;
  28140. this.camera = null;
  28141. this.layers = new Layers();
  28142. this.params = {
  28143. Mesh: {},
  28144. Line: { threshold: 1 },
  28145. LOD: {},
  28146. Points: { threshold: 1 },
  28147. Sprite: {}
  28148. };
  28149. }
  28150. set( origin, direction ) {
  28151. // direction is assumed to be normalized (for accurate distance calculations)
  28152. this.ray.set( origin, direction );
  28153. }
  28154. setFromCamera( coords, camera ) {
  28155. if ( camera.isPerspectiveCamera ) {
  28156. this.ray.origin.setFromMatrixPosition( camera.matrixWorld );
  28157. this.ray.direction.set( coords.x, coords.y, 0.5 ).unproject( camera ).sub( this.ray.origin ).normalize();
  28158. this.camera = camera;
  28159. } else if ( camera.isOrthographicCamera ) {
  28160. this.ray.origin.set( coords.x, coords.y, ( camera.near + camera.far ) / ( camera.near - camera.far ) ).unproject( camera ); // set origin in plane of camera
  28161. this.ray.direction.set( 0, 0, - 1 ).transformDirection( camera.matrixWorld );
  28162. this.camera = camera;
  28163. } else {
  28164. console.error( 'THREE.Raycaster: Unsupported camera type: ' + camera.type );
  28165. }
  28166. }
  28167. intersectObject( object, recursive = true, intersects = [] ) {
  28168. intersectObject( object, this, intersects, recursive );
  28169. intersects.sort( ascSort );
  28170. return intersects;
  28171. }
  28172. intersectObjects( objects, recursive = true, intersects = [] ) {
  28173. for ( let i = 0, l = objects.length; i < l; i ++ ) {
  28174. intersectObject( objects[ i ], this, intersects, recursive );
  28175. }
  28176. intersects.sort( ascSort );
  28177. return intersects;
  28178. }
  28179. }
  28180. function ascSort( a, b ) {
  28181. return a.distance - b.distance;
  28182. }
  28183. function intersectObject( object, raycaster, intersects, recursive ) {
  28184. if ( object.layers.test( raycaster.layers ) ) {
  28185. object.raycast( raycaster, intersects );
  28186. }
  28187. if ( recursive === true ) {
  28188. const children = object.children;
  28189. for ( let i = 0, l = children.length; i < l; i ++ ) {
  28190. intersectObject( children[ i ], raycaster, intersects, true );
  28191. }
  28192. }
  28193. }
  28194. /**
  28195. * Ref: https://en.wikipedia.org/wiki/Spherical_coordinate_system
  28196. *
  28197. * The polar angle (phi) is measured from the positive y-axis. The positive y-axis is up.
  28198. * The azimuthal angle (theta) is measured from the positive z-axis.
  28199. */
  28200. class Spherical {
  28201. constructor( radius = 1, phi = 0, theta = 0 ) {
  28202. this.radius = radius;
  28203. this.phi = phi; // polar angle
  28204. this.theta = theta; // azimuthal angle
  28205. return this;
  28206. }
  28207. set( radius, phi, theta ) {
  28208. this.radius = radius;
  28209. this.phi = phi;
  28210. this.theta = theta;
  28211. return this;
  28212. }
  28213. copy( other ) {
  28214. this.radius = other.radius;
  28215. this.phi = other.phi;
  28216. this.theta = other.theta;
  28217. return this;
  28218. }
  28219. // restrict phi to be between EPS and PI-EPS
  28220. makeSafe() {
  28221. const EPS = 0.000001;
  28222. this.phi = Math.max( EPS, Math.min( Math.PI - EPS, this.phi ) );
  28223. return this;
  28224. }
  28225. setFromVector3( v ) {
  28226. return this.setFromCartesianCoords( v.x, v.y, v.z );
  28227. }
  28228. setFromCartesianCoords( x, y, z ) {
  28229. this.radius = Math.sqrt( x * x + y * y + z * z );
  28230. if ( this.radius === 0 ) {
  28231. this.theta = 0;
  28232. this.phi = 0;
  28233. } else {
  28234. this.theta = Math.atan2( x, z );
  28235. this.phi = Math.acos( clamp( y / this.radius, - 1, 1 ) );
  28236. }
  28237. return this;
  28238. }
  28239. clone() {
  28240. return new this.constructor().copy( this );
  28241. }
  28242. }
  28243. /**
  28244. * Ref: https://en.wikipedia.org/wiki/Cylindrical_coordinate_system
  28245. */
  28246. class Cylindrical {
  28247. constructor( radius = 1, theta = 0, y = 0 ) {
  28248. this.radius = radius; // distance from the origin to a point in the x-z plane
  28249. this.theta = theta; // counterclockwise angle in the x-z plane measured in radians from the positive z-axis
  28250. this.y = y; // height above the x-z plane
  28251. return this;
  28252. }
  28253. set( radius, theta, y ) {
  28254. this.radius = radius;
  28255. this.theta = theta;
  28256. this.y = y;
  28257. return this;
  28258. }
  28259. copy( other ) {
  28260. this.radius = other.radius;
  28261. this.theta = other.theta;
  28262. this.y = other.y;
  28263. return this;
  28264. }
  28265. setFromVector3( v ) {
  28266. return this.setFromCartesianCoords( v.x, v.y, v.z );
  28267. }
  28268. setFromCartesianCoords( x, y, z ) {
  28269. this.radius = Math.sqrt( x * x + z * z );
  28270. this.theta = Math.atan2( x, z );
  28271. this.y = y;
  28272. return this;
  28273. }
  28274. clone() {
  28275. return new this.constructor().copy( this );
  28276. }
  28277. }
  28278. const _vector$4 = /*@__PURE__*/ new Vector2();
  28279. class Box2 {
  28280. constructor( min = new Vector2( + Infinity, + Infinity ), max = new Vector2( - Infinity, - Infinity ) ) {
  28281. this.isBox2 = true;
  28282. this.min = min;
  28283. this.max = max;
  28284. }
  28285. set( min, max ) {
  28286. this.min.copy( min );
  28287. this.max.copy( max );
  28288. return this;
  28289. }
  28290. setFromPoints( points ) {
  28291. this.makeEmpty();
  28292. for ( let i = 0, il = points.length; i < il; i ++ ) {
  28293. this.expandByPoint( points[ i ] );
  28294. }
  28295. return this;
  28296. }
  28297. setFromCenterAndSize( center, size ) {
  28298. const halfSize = _vector$4.copy( size ).multiplyScalar( 0.5 );
  28299. this.min.copy( center ).sub( halfSize );
  28300. this.max.copy( center ).add( halfSize );
  28301. return this;
  28302. }
  28303. clone() {
  28304. return new this.constructor().copy( this );
  28305. }
  28306. copy( box ) {
  28307. this.min.copy( box.min );
  28308. this.max.copy( box.max );
  28309. return this;
  28310. }
  28311. makeEmpty() {
  28312. this.min.x = this.min.y = + Infinity;
  28313. this.max.x = this.max.y = - Infinity;
  28314. return this;
  28315. }
  28316. isEmpty() {
  28317. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  28318. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y );
  28319. }
  28320. getCenter( target ) {
  28321. return this.isEmpty() ? target.set( 0, 0 ) : target.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  28322. }
  28323. getSize( target ) {
  28324. return this.isEmpty() ? target.set( 0, 0 ) : target.subVectors( this.max, this.min );
  28325. }
  28326. expandByPoint( point ) {
  28327. this.min.min( point );
  28328. this.max.max( point );
  28329. return this;
  28330. }
  28331. expandByVector( vector ) {
  28332. this.min.sub( vector );
  28333. this.max.add( vector );
  28334. return this;
  28335. }
  28336. expandByScalar( scalar ) {
  28337. this.min.addScalar( - scalar );
  28338. this.max.addScalar( scalar );
  28339. return this;
  28340. }
  28341. containsPoint( point ) {
  28342. return point.x < this.min.x || point.x > this.max.x ||
  28343. point.y < this.min.y || point.y > this.max.y ? false : true;
  28344. }
  28345. containsBox( box ) {
  28346. return this.min.x <= box.min.x && box.max.x <= this.max.x &&
  28347. this.min.y <= box.min.y && box.max.y <= this.max.y;
  28348. }
  28349. getParameter( point, target ) {
  28350. // This can potentially have a divide by zero if the box
  28351. // has a size dimension of 0.
  28352. return target.set(
  28353. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  28354. ( point.y - this.min.y ) / ( this.max.y - this.min.y )
  28355. );
  28356. }
  28357. intersectsBox( box ) {
  28358. // using 4 splitting planes to rule out intersections
  28359. return box.max.x < this.min.x || box.min.x > this.max.x ||
  28360. box.max.y < this.min.y || box.min.y > this.max.y ? false : true;
  28361. }
  28362. clampPoint( point, target ) {
  28363. return target.copy( point ).clamp( this.min, this.max );
  28364. }
  28365. distanceToPoint( point ) {
  28366. const clampedPoint = _vector$4.copy( point ).clamp( this.min, this.max );
  28367. return clampedPoint.sub( point ).length();
  28368. }
  28369. intersect( box ) {
  28370. this.min.max( box.min );
  28371. this.max.min( box.max );
  28372. return this;
  28373. }
  28374. union( box ) {
  28375. this.min.min( box.min );
  28376. this.max.max( box.max );
  28377. return this;
  28378. }
  28379. translate( offset ) {
  28380. this.min.add( offset );
  28381. this.max.add( offset );
  28382. return this;
  28383. }
  28384. equals( box ) {
  28385. return box.min.equals( this.min ) && box.max.equals( this.max );
  28386. }
  28387. }
  28388. const _startP = /*@__PURE__*/ new Vector3();
  28389. const _startEnd = /*@__PURE__*/ new Vector3();
  28390. class Line3 {
  28391. constructor( start = new Vector3(), end = new Vector3() ) {
  28392. this.start = start;
  28393. this.end = end;
  28394. }
  28395. set( start, end ) {
  28396. this.start.copy( start );
  28397. this.end.copy( end );
  28398. return this;
  28399. }
  28400. copy( line ) {
  28401. this.start.copy( line.start );
  28402. this.end.copy( line.end );
  28403. return this;
  28404. }
  28405. getCenter( target ) {
  28406. return target.addVectors( this.start, this.end ).multiplyScalar( 0.5 );
  28407. }
  28408. delta( target ) {
  28409. return target.subVectors( this.end, this.start );
  28410. }
  28411. distanceSq() {
  28412. return this.start.distanceToSquared( this.end );
  28413. }
  28414. distance() {
  28415. return this.start.distanceTo( this.end );
  28416. }
  28417. at( t, target ) {
  28418. return this.delta( target ).multiplyScalar( t ).add( this.start );
  28419. }
  28420. closestPointToPointParameter( point, clampToLine ) {
  28421. _startP.subVectors( point, this.start );
  28422. _startEnd.subVectors( this.end, this.start );
  28423. const startEnd2 = _startEnd.dot( _startEnd );
  28424. const startEnd_startP = _startEnd.dot( _startP );
  28425. let t = startEnd_startP / startEnd2;
  28426. if ( clampToLine ) {
  28427. t = clamp( t, 0, 1 );
  28428. }
  28429. return t;
  28430. }
  28431. closestPointToPoint( point, clampToLine, target ) {
  28432. const t = this.closestPointToPointParameter( point, clampToLine );
  28433. return this.delta( target ).multiplyScalar( t ).add( this.start );
  28434. }
  28435. applyMatrix4( matrix ) {
  28436. this.start.applyMatrix4( matrix );
  28437. this.end.applyMatrix4( matrix );
  28438. return this;
  28439. }
  28440. equals( line ) {
  28441. return line.start.equals( this.start ) && line.end.equals( this.end );
  28442. }
  28443. clone() {
  28444. return new this.constructor().copy( this );
  28445. }
  28446. }
  28447. const _vector$3 = /*@__PURE__*/ new Vector3();
  28448. class SpotLightHelper extends Object3D {
  28449. constructor( light, color ) {
  28450. super();
  28451. this.light = light;
  28452. this.matrix = light.matrixWorld;
  28453. this.matrixAutoUpdate = false;
  28454. this.color = color;
  28455. this.type = 'SpotLightHelper';
  28456. const geometry = new BufferGeometry();
  28457. const positions = [
  28458. 0, 0, 0, 0, 0, 1,
  28459. 0, 0, 0, 1, 0, 1,
  28460. 0, 0, 0, - 1, 0, 1,
  28461. 0, 0, 0, 0, 1, 1,
  28462. 0, 0, 0, 0, - 1, 1
  28463. ];
  28464. for ( let i = 0, j = 1, l = 32; i < l; i ++, j ++ ) {
  28465. const p1 = ( i / l ) * Math.PI * 2;
  28466. const p2 = ( j / l ) * Math.PI * 2;
  28467. positions.push(
  28468. Math.cos( p1 ), Math.sin( p1 ), 1,
  28469. Math.cos( p2 ), Math.sin( p2 ), 1
  28470. );
  28471. }
  28472. geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  28473. const material = new LineBasicMaterial( { fog: false, toneMapped: false } );
  28474. this.cone = new LineSegments( geometry, material );
  28475. this.add( this.cone );
  28476. this.update();
  28477. }
  28478. dispose() {
  28479. this.cone.geometry.dispose();
  28480. this.cone.material.dispose();
  28481. }
  28482. update() {
  28483. this.light.updateWorldMatrix( true, false );
  28484. this.light.target.updateWorldMatrix( true, false );
  28485. const coneLength = this.light.distance ? this.light.distance : 1000;
  28486. const coneWidth = coneLength * Math.tan( this.light.angle );
  28487. this.cone.scale.set( coneWidth, coneWidth, coneLength );
  28488. _vector$3.setFromMatrixPosition( this.light.target.matrixWorld );
  28489. this.cone.lookAt( _vector$3 );
  28490. if ( this.color !== undefined ) {
  28491. this.cone.material.color.set( this.color );
  28492. } else {
  28493. this.cone.material.color.copy( this.light.color );
  28494. }
  28495. }
  28496. }
  28497. const _vector$2 = /*@__PURE__*/ new Vector3();
  28498. const _boneMatrix = /*@__PURE__*/ new Matrix4();
  28499. const _matrixWorldInv = /*@__PURE__*/ new Matrix4();
  28500. class SkeletonHelper extends LineSegments {
  28501. constructor( object ) {
  28502. const bones = getBoneList( object );
  28503. const geometry = new BufferGeometry();
  28504. const vertices = [];
  28505. const colors = [];
  28506. const color1 = new Color( 0, 0, 1 );
  28507. const color2 = new Color( 0, 1, 0 );
  28508. for ( let i = 0; i < bones.length; i ++ ) {
  28509. const bone = bones[ i ];
  28510. if ( bone.parent && bone.parent.isBone ) {
  28511. vertices.push( 0, 0, 0 );
  28512. vertices.push( 0, 0, 0 );
  28513. colors.push( color1.r, color1.g, color1.b );
  28514. colors.push( color2.r, color2.g, color2.b );
  28515. }
  28516. }
  28517. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  28518. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  28519. const material = new LineBasicMaterial( { vertexColors: true, depthTest: false, depthWrite: false, toneMapped: false, transparent: true } );
  28520. super( geometry, material );
  28521. this.isSkeletonHelper = true;
  28522. this.type = 'SkeletonHelper';
  28523. this.root = object;
  28524. this.bones = bones;
  28525. this.matrix = object.matrixWorld;
  28526. this.matrixAutoUpdate = false;
  28527. }
  28528. updateMatrixWorld( force ) {
  28529. const bones = this.bones;
  28530. const geometry = this.geometry;
  28531. const position = geometry.getAttribute( 'position' );
  28532. _matrixWorldInv.copy( this.root.matrixWorld ).invert();
  28533. for ( let i = 0, j = 0; i < bones.length; i ++ ) {
  28534. const bone = bones[ i ];
  28535. if ( bone.parent && bone.parent.isBone ) {
  28536. _boneMatrix.multiplyMatrices( _matrixWorldInv, bone.matrixWorld );
  28537. _vector$2.setFromMatrixPosition( _boneMatrix );
  28538. position.setXYZ( j, _vector$2.x, _vector$2.y, _vector$2.z );
  28539. _boneMatrix.multiplyMatrices( _matrixWorldInv, bone.parent.matrixWorld );
  28540. _vector$2.setFromMatrixPosition( _boneMatrix );
  28541. position.setXYZ( j + 1, _vector$2.x, _vector$2.y, _vector$2.z );
  28542. j += 2;
  28543. }
  28544. }
  28545. geometry.getAttribute( 'position' ).needsUpdate = true;
  28546. super.updateMatrixWorld( force );
  28547. }
  28548. dispose() {
  28549. this.geometry.dispose();
  28550. this.material.dispose();
  28551. }
  28552. }
  28553. function getBoneList( object ) {
  28554. const boneList = [];
  28555. if ( object.isBone === true ) {
  28556. boneList.push( object );
  28557. }
  28558. for ( let i = 0; i < object.children.length; i ++ ) {
  28559. boneList.push.apply( boneList, getBoneList( object.children[ i ] ) );
  28560. }
  28561. return boneList;
  28562. }
  28563. class PointLightHelper extends Mesh {
  28564. constructor( light, sphereSize, color ) {
  28565. const geometry = new SphereGeometry( sphereSize, 4, 2 );
  28566. const material = new MeshBasicMaterial( { wireframe: true, fog: false, toneMapped: false } );
  28567. super( geometry, material );
  28568. this.light = light;
  28569. this.color = color;
  28570. this.type = 'PointLightHelper';
  28571. this.matrix = this.light.matrixWorld;
  28572. this.matrixAutoUpdate = false;
  28573. this.update();
  28574. /*
  28575. // TODO: delete this comment?
  28576. const distanceGeometry = new THREE.IcosahedronGeometry( 1, 2 );
  28577. const distanceMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false, wireframe: true, opacity: 0.1, transparent: true } );
  28578. this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial );
  28579. this.lightDistance = new THREE.Mesh( distanceGeometry, distanceMaterial );
  28580. const d = light.distance;
  28581. if ( d === 0.0 ) {
  28582. this.lightDistance.visible = false;
  28583. } else {
  28584. this.lightDistance.scale.set( d, d, d );
  28585. }
  28586. this.add( this.lightDistance );
  28587. */
  28588. }
  28589. dispose() {
  28590. this.geometry.dispose();
  28591. this.material.dispose();
  28592. }
  28593. update() {
  28594. this.light.updateWorldMatrix( true, false );
  28595. if ( this.color !== undefined ) {
  28596. this.material.color.set( this.color );
  28597. } else {
  28598. this.material.color.copy( this.light.color );
  28599. }
  28600. /*
  28601. const d = this.light.distance;
  28602. if ( d === 0.0 ) {
  28603. this.lightDistance.visible = false;
  28604. } else {
  28605. this.lightDistance.visible = true;
  28606. this.lightDistance.scale.set( d, d, d );
  28607. }
  28608. */
  28609. }
  28610. }
  28611. const _vector$1 = /*@__PURE__*/ new Vector3();
  28612. const _color1 = /*@__PURE__*/ new Color();
  28613. const _color2 = /*@__PURE__*/ new Color();
  28614. class HemisphereLightHelper extends Object3D {
  28615. constructor( light, size, color ) {
  28616. super();
  28617. this.light = light;
  28618. this.matrix = light.matrixWorld;
  28619. this.matrixAutoUpdate = false;
  28620. this.color = color;
  28621. this.type = 'HemisphereLightHelper';
  28622. const geometry = new OctahedronGeometry( size );
  28623. geometry.rotateY( Math.PI * 0.5 );
  28624. this.material = new MeshBasicMaterial( { wireframe: true, fog: false, toneMapped: false } );
  28625. if ( this.color === undefined ) this.material.vertexColors = true;
  28626. const position = geometry.getAttribute( 'position' );
  28627. const colors = new Float32Array( position.count * 3 );
  28628. geometry.setAttribute( 'color', new BufferAttribute( colors, 3 ) );
  28629. this.add( new Mesh( geometry, this.material ) );
  28630. this.update();
  28631. }
  28632. dispose() {
  28633. this.children[ 0 ].geometry.dispose();
  28634. this.children[ 0 ].material.dispose();
  28635. }
  28636. update() {
  28637. const mesh = this.children[ 0 ];
  28638. if ( this.color !== undefined ) {
  28639. this.material.color.set( this.color );
  28640. } else {
  28641. const colors = mesh.geometry.getAttribute( 'color' );
  28642. _color1.copy( this.light.color );
  28643. _color2.copy( this.light.groundColor );
  28644. for ( let i = 0, l = colors.count; i < l; i ++ ) {
  28645. const color = ( i < ( l / 2 ) ) ? _color1 : _color2;
  28646. colors.setXYZ( i, color.r, color.g, color.b );
  28647. }
  28648. colors.needsUpdate = true;
  28649. }
  28650. this.light.updateWorldMatrix( true, false );
  28651. mesh.lookAt( _vector$1.setFromMatrixPosition( this.light.matrixWorld ).negate() );
  28652. }
  28653. }
  28654. class GridHelper extends LineSegments {
  28655. constructor( size = 10, divisions = 10, color1 = 0x444444, color2 = 0x888888 ) {
  28656. color1 = new Color( color1 );
  28657. color2 = new Color( color2 );
  28658. const center = divisions / 2;
  28659. const step = size / divisions;
  28660. const halfSize = size / 2;
  28661. const vertices = [], colors = [];
  28662. for ( let i = 0, j = 0, k = - halfSize; i <= divisions; i ++, k += step ) {
  28663. vertices.push( - halfSize, 0, k, halfSize, 0, k );
  28664. vertices.push( k, 0, - halfSize, k, 0, halfSize );
  28665. const color = i === center ? color1 : color2;
  28666. color.toArray( colors, j ); j += 3;
  28667. color.toArray( colors, j ); j += 3;
  28668. color.toArray( colors, j ); j += 3;
  28669. color.toArray( colors, j ); j += 3;
  28670. }
  28671. const geometry = new BufferGeometry();
  28672. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  28673. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  28674. const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
  28675. super( geometry, material );
  28676. this.type = 'GridHelper';
  28677. }
  28678. dispose() {
  28679. this.geometry.dispose();
  28680. this.material.dispose();
  28681. }
  28682. }
  28683. class PolarGridHelper extends LineSegments {
  28684. constructor( radius = 10, sectors = 16, rings = 8, divisions = 64, color1 = 0x444444, color2 = 0x888888 ) {
  28685. color1 = new Color( color1 );
  28686. color2 = new Color( color2 );
  28687. const vertices = [];
  28688. const colors = [];
  28689. // create the sectors
  28690. if ( sectors > 1 ) {
  28691. for ( let i = 0; i < sectors; i ++ ) {
  28692. const v = ( i / sectors ) * ( Math.PI * 2 );
  28693. const x = Math.sin( v ) * radius;
  28694. const z = Math.cos( v ) * radius;
  28695. vertices.push( 0, 0, 0 );
  28696. vertices.push( x, 0, z );
  28697. const color = ( i & 1 ) ? color1 : color2;
  28698. colors.push( color.r, color.g, color.b );
  28699. colors.push( color.r, color.g, color.b );
  28700. }
  28701. }
  28702. // create the rings
  28703. for ( let i = 0; i < rings; i ++ ) {
  28704. const color = ( i & 1 ) ? color1 : color2;
  28705. const r = radius - ( radius / rings * i );
  28706. for ( let j = 0; j < divisions; j ++ ) {
  28707. // first vertex
  28708. let v = ( j / divisions ) * ( Math.PI * 2 );
  28709. let x = Math.sin( v ) * r;
  28710. let z = Math.cos( v ) * r;
  28711. vertices.push( x, 0, z );
  28712. colors.push( color.r, color.g, color.b );
  28713. // second vertex
  28714. v = ( ( j + 1 ) / divisions ) * ( Math.PI * 2 );
  28715. x = Math.sin( v ) * r;
  28716. z = Math.cos( v ) * r;
  28717. vertices.push( x, 0, z );
  28718. colors.push( color.r, color.g, color.b );
  28719. }
  28720. }
  28721. const geometry = new BufferGeometry();
  28722. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  28723. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  28724. const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
  28725. super( geometry, material );
  28726. this.type = 'PolarGridHelper';
  28727. }
  28728. dispose() {
  28729. this.geometry.dispose();
  28730. this.material.dispose();
  28731. }
  28732. }
  28733. const _v1 = /*@__PURE__*/ new Vector3();
  28734. const _v2 = /*@__PURE__*/ new Vector3();
  28735. const _v3 = /*@__PURE__*/ new Vector3();
  28736. class DirectionalLightHelper extends Object3D {
  28737. constructor( light, size, color ) {
  28738. super();
  28739. this.light = light;
  28740. this.matrix = light.matrixWorld;
  28741. this.matrixAutoUpdate = false;
  28742. this.color = color;
  28743. this.type = 'DirectionalLightHelper';
  28744. if ( size === undefined ) size = 1;
  28745. let geometry = new BufferGeometry();
  28746. geometry.setAttribute( 'position', new Float32BufferAttribute( [
  28747. - size, size, 0,
  28748. size, size, 0,
  28749. size, - size, 0,
  28750. - size, - size, 0,
  28751. - size, size, 0
  28752. ], 3 ) );
  28753. const material = new LineBasicMaterial( { fog: false, toneMapped: false } );
  28754. this.lightPlane = new Line( geometry, material );
  28755. this.add( this.lightPlane );
  28756. geometry = new BufferGeometry();
  28757. geometry.setAttribute( 'position', new Float32BufferAttribute( [ 0, 0, 0, 0, 0, 1 ], 3 ) );
  28758. this.targetLine = new Line( geometry, material );
  28759. this.add( this.targetLine );
  28760. this.update();
  28761. }
  28762. dispose() {
  28763. this.lightPlane.geometry.dispose();
  28764. this.lightPlane.material.dispose();
  28765. this.targetLine.geometry.dispose();
  28766. this.targetLine.material.dispose();
  28767. }
  28768. update() {
  28769. this.light.updateWorldMatrix( true, false );
  28770. this.light.target.updateWorldMatrix( true, false );
  28771. _v1.setFromMatrixPosition( this.light.matrixWorld );
  28772. _v2.setFromMatrixPosition( this.light.target.matrixWorld );
  28773. _v3.subVectors( _v2, _v1 );
  28774. this.lightPlane.lookAt( _v2 );
  28775. if ( this.color !== undefined ) {
  28776. this.lightPlane.material.color.set( this.color );
  28777. this.targetLine.material.color.set( this.color );
  28778. } else {
  28779. this.lightPlane.material.color.copy( this.light.color );
  28780. this.targetLine.material.color.copy( this.light.color );
  28781. }
  28782. this.targetLine.lookAt( _v2 );
  28783. this.targetLine.scale.z = _v3.length();
  28784. }
  28785. }
  28786. const _vector = /*@__PURE__*/ new Vector3();
  28787. const _camera = /*@__PURE__*/ new Camera();
  28788. /**
  28789. * - shows frustum, line of sight and up of the camera
  28790. * - suitable for fast updates
  28791. * - based on frustum visualization in lightgl.js shadowmap example
  28792. * https://github.com/evanw/lightgl.js/blob/master/tests/shadowmap.html
  28793. */
  28794. class CameraHelper extends LineSegments {
  28795. constructor( camera ) {
  28796. const geometry = new BufferGeometry();
  28797. const material = new LineBasicMaterial( { color: 0xffffff, vertexColors: true, toneMapped: false } );
  28798. const vertices = [];
  28799. const colors = [];
  28800. const pointMap = {};
  28801. // near
  28802. addLine( 'n1', 'n2' );
  28803. addLine( 'n2', 'n4' );
  28804. addLine( 'n4', 'n3' );
  28805. addLine( 'n3', 'n1' );
  28806. // far
  28807. addLine( 'f1', 'f2' );
  28808. addLine( 'f2', 'f4' );
  28809. addLine( 'f4', 'f3' );
  28810. addLine( 'f3', 'f1' );
  28811. // sides
  28812. addLine( 'n1', 'f1' );
  28813. addLine( 'n2', 'f2' );
  28814. addLine( 'n3', 'f3' );
  28815. addLine( 'n4', 'f4' );
  28816. // cone
  28817. addLine( 'p', 'n1' );
  28818. addLine( 'p', 'n2' );
  28819. addLine( 'p', 'n3' );
  28820. addLine( 'p', 'n4' );
  28821. // up
  28822. addLine( 'u1', 'u2' );
  28823. addLine( 'u2', 'u3' );
  28824. addLine( 'u3', 'u1' );
  28825. // target
  28826. addLine( 'c', 't' );
  28827. addLine( 'p', 'c' );
  28828. // cross
  28829. addLine( 'cn1', 'cn2' );
  28830. addLine( 'cn3', 'cn4' );
  28831. addLine( 'cf1', 'cf2' );
  28832. addLine( 'cf3', 'cf4' );
  28833. function addLine( a, b ) {
  28834. addPoint( a );
  28835. addPoint( b );
  28836. }
  28837. function addPoint( id ) {
  28838. vertices.push( 0, 0, 0 );
  28839. colors.push( 0, 0, 0 );
  28840. if ( pointMap[ id ] === undefined ) {
  28841. pointMap[ id ] = [];
  28842. }
  28843. pointMap[ id ].push( ( vertices.length / 3 ) - 1 );
  28844. }
  28845. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  28846. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  28847. super( geometry, material );
  28848. this.type = 'CameraHelper';
  28849. this.camera = camera;
  28850. if ( this.camera.updateProjectionMatrix ) this.camera.updateProjectionMatrix();
  28851. this.matrix = camera.matrixWorld;
  28852. this.matrixAutoUpdate = false;
  28853. this.pointMap = pointMap;
  28854. this.update();
  28855. // colors
  28856. const colorFrustum = new Color( 0xffaa00 );
  28857. const colorCone = new Color( 0xff0000 );
  28858. const colorUp = new Color( 0x00aaff );
  28859. const colorTarget = new Color( 0xffffff );
  28860. const colorCross = new Color( 0x333333 );
  28861. this.setColors( colorFrustum, colorCone, colorUp, colorTarget, colorCross );
  28862. }
  28863. setColors( frustum, cone, up, target, cross ) {
  28864. const geometry = this.geometry;
  28865. const colorAttribute = geometry.getAttribute( 'color' );
  28866. // near
  28867. colorAttribute.setXYZ( 0, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 1, frustum.r, frustum.g, frustum.b ); // n1, n2
  28868. colorAttribute.setXYZ( 2, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 3, frustum.r, frustum.g, frustum.b ); // n2, n4
  28869. colorAttribute.setXYZ( 4, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 5, frustum.r, frustum.g, frustum.b ); // n4, n3
  28870. colorAttribute.setXYZ( 6, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 7, frustum.r, frustum.g, frustum.b ); // n3, n1
  28871. // far
  28872. colorAttribute.setXYZ( 8, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 9, frustum.r, frustum.g, frustum.b ); // f1, f2
  28873. colorAttribute.setXYZ( 10, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 11, frustum.r, frustum.g, frustum.b ); // f2, f4
  28874. colorAttribute.setXYZ( 12, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 13, frustum.r, frustum.g, frustum.b ); // f4, f3
  28875. colorAttribute.setXYZ( 14, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 15, frustum.r, frustum.g, frustum.b ); // f3, f1
  28876. // sides
  28877. colorAttribute.setXYZ( 16, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 17, frustum.r, frustum.g, frustum.b ); // n1, f1
  28878. colorAttribute.setXYZ( 18, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 19, frustum.r, frustum.g, frustum.b ); // n2, f2
  28879. colorAttribute.setXYZ( 20, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 21, frustum.r, frustum.g, frustum.b ); // n3, f3
  28880. colorAttribute.setXYZ( 22, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 23, frustum.r, frustum.g, frustum.b ); // n4, f4
  28881. // cone
  28882. colorAttribute.setXYZ( 24, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 25, cone.r, cone.g, cone.b ); // p, n1
  28883. colorAttribute.setXYZ( 26, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 27, cone.r, cone.g, cone.b ); // p, n2
  28884. colorAttribute.setXYZ( 28, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 29, cone.r, cone.g, cone.b ); // p, n3
  28885. colorAttribute.setXYZ( 30, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 31, cone.r, cone.g, cone.b ); // p, n4
  28886. // up
  28887. colorAttribute.setXYZ( 32, up.r, up.g, up.b ); colorAttribute.setXYZ( 33, up.r, up.g, up.b ); // u1, u2
  28888. colorAttribute.setXYZ( 34, up.r, up.g, up.b ); colorAttribute.setXYZ( 35, up.r, up.g, up.b ); // u2, u3
  28889. colorAttribute.setXYZ( 36, up.r, up.g, up.b ); colorAttribute.setXYZ( 37, up.r, up.g, up.b ); // u3, u1
  28890. // target
  28891. colorAttribute.setXYZ( 38, target.r, target.g, target.b ); colorAttribute.setXYZ( 39, target.r, target.g, target.b ); // c, t
  28892. colorAttribute.setXYZ( 40, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 41, cross.r, cross.g, cross.b ); // p, c
  28893. // cross
  28894. colorAttribute.setXYZ( 42, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 43, cross.r, cross.g, cross.b ); // cn1, cn2
  28895. colorAttribute.setXYZ( 44, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 45, cross.r, cross.g, cross.b ); // cn3, cn4
  28896. colorAttribute.setXYZ( 46, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 47, cross.r, cross.g, cross.b ); // cf1, cf2
  28897. colorAttribute.setXYZ( 48, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 49, cross.r, cross.g, cross.b ); // cf3, cf4
  28898. colorAttribute.needsUpdate = true;
  28899. }
  28900. update() {
  28901. const geometry = this.geometry;
  28902. const pointMap = this.pointMap;
  28903. const w = 1, h = 1;
  28904. // we need just camera projection matrix inverse
  28905. // world matrix must be identity
  28906. _camera.projectionMatrixInverse.copy( this.camera.projectionMatrixInverse );
  28907. // center / target
  28908. setPoint( 'c', pointMap, geometry, _camera, 0, 0, - 1 );
  28909. setPoint( 't', pointMap, geometry, _camera, 0, 0, 1 );
  28910. // near
  28911. setPoint( 'n1', pointMap, geometry, _camera, - w, - h, - 1 );
  28912. setPoint( 'n2', pointMap, geometry, _camera, w, - h, - 1 );
  28913. setPoint( 'n3', pointMap, geometry, _camera, - w, h, - 1 );
  28914. setPoint( 'n4', pointMap, geometry, _camera, w, h, - 1 );
  28915. // far
  28916. setPoint( 'f1', pointMap, geometry, _camera, - w, - h, 1 );
  28917. setPoint( 'f2', pointMap, geometry, _camera, w, - h, 1 );
  28918. setPoint( 'f3', pointMap, geometry, _camera, - w, h, 1 );
  28919. setPoint( 'f4', pointMap, geometry, _camera, w, h, 1 );
  28920. // up
  28921. setPoint( 'u1', pointMap, geometry, _camera, w * 0.7, h * 1.1, - 1 );
  28922. setPoint( 'u2', pointMap, geometry, _camera, - w * 0.7, h * 1.1, - 1 );
  28923. setPoint( 'u3', pointMap, geometry, _camera, 0, h * 2, - 1 );
  28924. // cross
  28925. setPoint( 'cf1', pointMap, geometry, _camera, - w, 0, 1 );
  28926. setPoint( 'cf2', pointMap, geometry, _camera, w, 0, 1 );
  28927. setPoint( 'cf3', pointMap, geometry, _camera, 0, - h, 1 );
  28928. setPoint( 'cf4', pointMap, geometry, _camera, 0, h, 1 );
  28929. setPoint( 'cn1', pointMap, geometry, _camera, - w, 0, - 1 );
  28930. setPoint( 'cn2', pointMap, geometry, _camera, w, 0, - 1 );
  28931. setPoint( 'cn3', pointMap, geometry, _camera, 0, - h, - 1 );
  28932. setPoint( 'cn4', pointMap, geometry, _camera, 0, h, - 1 );
  28933. geometry.getAttribute( 'position' ).needsUpdate = true;
  28934. }
  28935. dispose() {
  28936. this.geometry.dispose();
  28937. this.material.dispose();
  28938. }
  28939. }
  28940. function setPoint( point, pointMap, geometry, camera, x, y, z ) {
  28941. _vector.set( x, y, z ).unproject( camera );
  28942. const points = pointMap[ point ];
  28943. if ( points !== undefined ) {
  28944. const position = geometry.getAttribute( 'position' );
  28945. for ( let i = 0, l = points.length; i < l; i ++ ) {
  28946. position.setXYZ( points[ i ], _vector.x, _vector.y, _vector.z );
  28947. }
  28948. }
  28949. }
  28950. const _box = /*@__PURE__*/ new Box3();
  28951. class BoxHelper extends LineSegments {
  28952. constructor( object, color = 0xffff00 ) {
  28953. 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 ] );
  28954. const positions = new Float32Array( 8 * 3 );
  28955. const geometry = new BufferGeometry();
  28956. geometry.setIndex( new BufferAttribute( indices, 1 ) );
  28957. geometry.setAttribute( 'position', new BufferAttribute( positions, 3 ) );
  28958. super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  28959. this.object = object;
  28960. this.type = 'BoxHelper';
  28961. this.matrixAutoUpdate = false;
  28962. this.update();
  28963. }
  28964. update( object ) {
  28965. if ( object !== undefined ) {
  28966. console.warn( 'THREE.BoxHelper: .update() has no longer arguments.' );
  28967. }
  28968. if ( this.object !== undefined ) {
  28969. _box.setFromObject( this.object );
  28970. }
  28971. if ( _box.isEmpty() ) return;
  28972. const min = _box.min;
  28973. const max = _box.max;
  28974. /*
  28975. 5____4
  28976. 1/___0/|
  28977. | 6__|_7
  28978. 2/___3/
  28979. 0: max.x, max.y, max.z
  28980. 1: min.x, max.y, max.z
  28981. 2: min.x, min.y, max.z
  28982. 3: max.x, min.y, max.z
  28983. 4: max.x, max.y, min.z
  28984. 5: min.x, max.y, min.z
  28985. 6: min.x, min.y, min.z
  28986. 7: max.x, min.y, min.z
  28987. */
  28988. const position = this.geometry.attributes.position;
  28989. const array = position.array;
  28990. array[ 0 ] = max.x; array[ 1 ] = max.y; array[ 2 ] = max.z;
  28991. array[ 3 ] = min.x; array[ 4 ] = max.y; array[ 5 ] = max.z;
  28992. array[ 6 ] = min.x; array[ 7 ] = min.y; array[ 8 ] = max.z;
  28993. array[ 9 ] = max.x; array[ 10 ] = min.y; array[ 11 ] = max.z;
  28994. array[ 12 ] = max.x; array[ 13 ] = max.y; array[ 14 ] = min.z;
  28995. array[ 15 ] = min.x; array[ 16 ] = max.y; array[ 17 ] = min.z;
  28996. array[ 18 ] = min.x; array[ 19 ] = min.y; array[ 20 ] = min.z;
  28997. array[ 21 ] = max.x; array[ 22 ] = min.y; array[ 23 ] = min.z;
  28998. position.needsUpdate = true;
  28999. this.geometry.computeBoundingSphere();
  29000. }
  29001. setFromObject( object ) {
  29002. this.object = object;
  29003. this.update();
  29004. return this;
  29005. }
  29006. copy( source, recursive ) {
  29007. super.copy( source, recursive );
  29008. this.object = source.object;
  29009. return this;
  29010. }
  29011. dispose() {
  29012. this.geometry.dispose();
  29013. this.material.dispose();
  29014. }
  29015. }
  29016. class Box3Helper extends LineSegments {
  29017. constructor( box, color = 0xffff00 ) {
  29018. 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 ] );
  29019. 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 ];
  29020. const geometry = new BufferGeometry();
  29021. geometry.setIndex( new BufferAttribute( indices, 1 ) );
  29022. geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  29023. super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  29024. this.box = box;
  29025. this.type = 'Box3Helper';
  29026. this.geometry.computeBoundingSphere();
  29027. }
  29028. updateMatrixWorld( force ) {
  29029. const box = this.box;
  29030. if ( box.isEmpty() ) return;
  29031. box.getCenter( this.position );
  29032. box.getSize( this.scale );
  29033. this.scale.multiplyScalar( 0.5 );
  29034. super.updateMatrixWorld( force );
  29035. }
  29036. dispose() {
  29037. this.geometry.dispose();
  29038. this.material.dispose();
  29039. }
  29040. }
  29041. class PlaneHelper extends Line {
  29042. constructor( plane, size = 1, hex = 0xffff00 ) {
  29043. const color = hex;
  29044. 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 ];
  29045. const geometry = new BufferGeometry();
  29046. geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  29047. geometry.computeBoundingSphere();
  29048. super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  29049. this.type = 'PlaneHelper';
  29050. this.plane = plane;
  29051. this.size = size;
  29052. const positions2 = [ 1, 1, 0, - 1, 1, 0, - 1, - 1, 0, 1, 1, 0, - 1, - 1, 0, 1, - 1, 0 ];
  29053. const geometry2 = new BufferGeometry();
  29054. geometry2.setAttribute( 'position', new Float32BufferAttribute( positions2, 3 ) );
  29055. geometry2.computeBoundingSphere();
  29056. this.add( new Mesh( geometry2, new MeshBasicMaterial( { color: color, opacity: 0.2, transparent: true, depthWrite: false, toneMapped: false } ) ) );
  29057. }
  29058. updateMatrixWorld( force ) {
  29059. this.position.set( 0, 0, 0 );
  29060. this.scale.set( 0.5 * this.size, 0.5 * this.size, 1 );
  29061. this.lookAt( this.plane.normal );
  29062. this.translateZ( - this.plane.constant );
  29063. super.updateMatrixWorld( force );
  29064. }
  29065. dispose() {
  29066. this.geometry.dispose();
  29067. this.material.dispose();
  29068. this.children[ 0 ].geometry.dispose();
  29069. this.children[ 0 ].material.dispose();
  29070. }
  29071. }
  29072. const _axis = /*@__PURE__*/ new Vector3();
  29073. let _lineGeometry, _coneGeometry;
  29074. class ArrowHelper extends Object3D {
  29075. // dir is assumed to be normalized
  29076. 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 ) {
  29077. super();
  29078. this.type = 'ArrowHelper';
  29079. if ( _lineGeometry === undefined ) {
  29080. _lineGeometry = new BufferGeometry();
  29081. _lineGeometry.setAttribute( 'position', new Float32BufferAttribute( [ 0, 0, 0, 0, 1, 0 ], 3 ) );
  29082. _coneGeometry = new CylinderGeometry( 0, 0.5, 1, 5, 1 );
  29083. _coneGeometry.translate( 0, - 0.5, 0 );
  29084. }
  29085. this.position.copy( origin );
  29086. this.line = new Line( _lineGeometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  29087. this.line.matrixAutoUpdate = false;
  29088. this.add( this.line );
  29089. this.cone = new Mesh( _coneGeometry, new MeshBasicMaterial( { color: color, toneMapped: false } ) );
  29090. this.cone.matrixAutoUpdate = false;
  29091. this.add( this.cone );
  29092. this.setDirection( dir );
  29093. this.setLength( length, headLength, headWidth );
  29094. }
  29095. setDirection( dir ) {
  29096. // dir is assumed to be normalized
  29097. if ( dir.y > 0.99999 ) {
  29098. this.quaternion.set( 0, 0, 0, 1 );
  29099. } else if ( dir.y < - 0.99999 ) {
  29100. this.quaternion.set( 1, 0, 0, 0 );
  29101. } else {
  29102. _axis.set( dir.z, 0, - dir.x ).normalize();
  29103. const radians = Math.acos( dir.y );
  29104. this.quaternion.setFromAxisAngle( _axis, radians );
  29105. }
  29106. }
  29107. setLength( length, headLength = length * 0.2, headWidth = headLength * 0.2 ) {
  29108. this.line.scale.set( 1, Math.max( 0.0001, length - headLength ), 1 ); // see #17458
  29109. this.line.updateMatrix();
  29110. this.cone.scale.set( headWidth, headLength, headWidth );
  29111. this.cone.position.y = length;
  29112. this.cone.updateMatrix();
  29113. }
  29114. setColor( color ) {
  29115. this.line.material.color.set( color );
  29116. this.cone.material.color.set( color );
  29117. }
  29118. copy( source ) {
  29119. super.copy( source, false );
  29120. this.line.copy( source.line );
  29121. this.cone.copy( source.cone );
  29122. return this;
  29123. }
  29124. dispose() {
  29125. this.line.geometry.dispose();
  29126. this.line.material.dispose();
  29127. this.cone.geometry.dispose();
  29128. this.cone.material.dispose();
  29129. }
  29130. }
  29131. class AxesHelper extends LineSegments {
  29132. constructor( size = 1 ) {
  29133. const vertices = [
  29134. 0, 0, 0, size, 0, 0,
  29135. 0, 0, 0, 0, size, 0,
  29136. 0, 0, 0, 0, 0, size
  29137. ];
  29138. const colors = [
  29139. 1, 0, 0, 1, 0.6, 0,
  29140. 0, 1, 0, 0.6, 1, 0,
  29141. 0, 0, 1, 0, 0.6, 1
  29142. ];
  29143. const geometry = new BufferGeometry();
  29144. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  29145. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  29146. const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
  29147. super( geometry, material );
  29148. this.type = 'AxesHelper';
  29149. }
  29150. setColors( xAxisColor, yAxisColor, zAxisColor ) {
  29151. const color = new Color();
  29152. const array = this.geometry.attributes.color.array;
  29153. color.set( xAxisColor );
  29154. color.toArray( array, 0 );
  29155. color.toArray( array, 3 );
  29156. color.set( yAxisColor );
  29157. color.toArray( array, 6 );
  29158. color.toArray( array, 9 );
  29159. color.set( zAxisColor );
  29160. color.toArray( array, 12 );
  29161. color.toArray( array, 15 );
  29162. this.geometry.attributes.color.needsUpdate = true;
  29163. return this;
  29164. }
  29165. dispose() {
  29166. this.geometry.dispose();
  29167. this.material.dispose();
  29168. }
  29169. }
  29170. class ShapePath {
  29171. constructor() {
  29172. this.type = 'ShapePath';
  29173. this.color = new Color();
  29174. this.subPaths = [];
  29175. this.currentPath = null;
  29176. }
  29177. moveTo( x, y ) {
  29178. this.currentPath = new Path();
  29179. this.subPaths.push( this.currentPath );
  29180. this.currentPath.moveTo( x, y );
  29181. return this;
  29182. }
  29183. lineTo( x, y ) {
  29184. this.currentPath.lineTo( x, y );
  29185. return this;
  29186. }
  29187. quadraticCurveTo( aCPx, aCPy, aX, aY ) {
  29188. this.currentPath.quadraticCurveTo( aCPx, aCPy, aX, aY );
  29189. return this;
  29190. }
  29191. bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) {
  29192. this.currentPath.bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY );
  29193. return this;
  29194. }
  29195. splineThru( pts ) {
  29196. this.currentPath.splineThru( pts );
  29197. return this;
  29198. }
  29199. toShapes( isCCW ) {
  29200. function toShapesNoHoles( inSubpaths ) {
  29201. const shapes = [];
  29202. for ( let i = 0, l = inSubpaths.length; i < l; i ++ ) {
  29203. const tmpPath = inSubpaths[ i ];
  29204. const tmpShape = new Shape();
  29205. tmpShape.curves = tmpPath.curves;
  29206. shapes.push( tmpShape );
  29207. }
  29208. return shapes;
  29209. }
  29210. function isPointInsidePolygon( inPt, inPolygon ) {
  29211. const polyLen = inPolygon.length;
  29212. // inPt on polygon contour => immediate success or
  29213. // toggling of inside/outside at every single! intersection point of an edge
  29214. // with the horizontal line through inPt, left of inPt
  29215. // not counting lowerY endpoints of edges and whole edges on that line
  29216. let inside = false;
  29217. for ( let p = polyLen - 1, q = 0; q < polyLen; p = q ++ ) {
  29218. let edgeLowPt = inPolygon[ p ];
  29219. let edgeHighPt = inPolygon[ q ];
  29220. let edgeDx = edgeHighPt.x - edgeLowPt.x;
  29221. let edgeDy = edgeHighPt.y - edgeLowPt.y;
  29222. if ( Math.abs( edgeDy ) > Number.EPSILON ) {
  29223. // not parallel
  29224. if ( edgeDy < 0 ) {
  29225. edgeLowPt = inPolygon[ q ]; edgeDx = - edgeDx;
  29226. edgeHighPt = inPolygon[ p ]; edgeDy = - edgeDy;
  29227. }
  29228. if ( ( inPt.y < edgeLowPt.y ) || ( inPt.y > edgeHighPt.y ) ) continue;
  29229. if ( inPt.y === edgeLowPt.y ) {
  29230. if ( inPt.x === edgeLowPt.x ) return true; // inPt is on contour ?
  29231. // continue; // no intersection or edgeLowPt => doesn't count !!!
  29232. } else {
  29233. const perpEdge = edgeDy * ( inPt.x - edgeLowPt.x ) - edgeDx * ( inPt.y - edgeLowPt.y );
  29234. if ( perpEdge === 0 ) return true; // inPt is on contour ?
  29235. if ( perpEdge < 0 ) continue;
  29236. inside = ! inside; // true intersection left of inPt
  29237. }
  29238. } else {
  29239. // parallel or collinear
  29240. if ( inPt.y !== edgeLowPt.y ) continue; // parallel
  29241. // edge lies on the same horizontal line as inPt
  29242. if ( ( ( edgeHighPt.x <= inPt.x ) && ( inPt.x <= edgeLowPt.x ) ) ||
  29243. ( ( edgeLowPt.x <= inPt.x ) && ( inPt.x <= edgeHighPt.x ) ) ) return true; // inPt: Point on contour !
  29244. // continue;
  29245. }
  29246. }
  29247. return inside;
  29248. }
  29249. const isClockWise = ShapeUtils.isClockWise;
  29250. const subPaths = this.subPaths;
  29251. if ( subPaths.length === 0 ) return [];
  29252. let solid, tmpPath, tmpShape;
  29253. const shapes = [];
  29254. if ( subPaths.length === 1 ) {
  29255. tmpPath = subPaths[ 0 ];
  29256. tmpShape = new Shape();
  29257. tmpShape.curves = tmpPath.curves;
  29258. shapes.push( tmpShape );
  29259. return shapes;
  29260. }
  29261. let holesFirst = ! isClockWise( subPaths[ 0 ].getPoints() );
  29262. holesFirst = isCCW ? ! holesFirst : holesFirst;
  29263. // console.log("Holes first", holesFirst);
  29264. const betterShapeHoles = [];
  29265. const newShapes = [];
  29266. let newShapeHoles = [];
  29267. let mainIdx = 0;
  29268. let tmpPoints;
  29269. newShapes[ mainIdx ] = undefined;
  29270. newShapeHoles[ mainIdx ] = [];
  29271. for ( let i = 0, l = subPaths.length; i < l; i ++ ) {
  29272. tmpPath = subPaths[ i ];
  29273. tmpPoints = tmpPath.getPoints();
  29274. solid = isClockWise( tmpPoints );
  29275. solid = isCCW ? ! solid : solid;
  29276. if ( solid ) {
  29277. if ( ( ! holesFirst ) && ( newShapes[ mainIdx ] ) ) mainIdx ++;
  29278. newShapes[ mainIdx ] = { s: new Shape(), p: tmpPoints };
  29279. newShapes[ mainIdx ].s.curves = tmpPath.curves;
  29280. if ( holesFirst ) mainIdx ++;
  29281. newShapeHoles[ mainIdx ] = [];
  29282. //console.log('cw', i);
  29283. } else {
  29284. newShapeHoles[ mainIdx ].push( { h: tmpPath, p: tmpPoints[ 0 ] } );
  29285. //console.log('ccw', i);
  29286. }
  29287. }
  29288. // only Holes? -> probably all Shapes with wrong orientation
  29289. if ( ! newShapes[ 0 ] ) return toShapesNoHoles( subPaths );
  29290. if ( newShapes.length > 1 ) {
  29291. let ambiguous = false;
  29292. let toChange = 0;
  29293. for ( let sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) {
  29294. betterShapeHoles[ sIdx ] = [];
  29295. }
  29296. for ( let sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) {
  29297. const sho = newShapeHoles[ sIdx ];
  29298. for ( let hIdx = 0; hIdx < sho.length; hIdx ++ ) {
  29299. const ho = sho[ hIdx ];
  29300. let hole_unassigned = true;
  29301. for ( let s2Idx = 0; s2Idx < newShapes.length; s2Idx ++ ) {
  29302. if ( isPointInsidePolygon( ho.p, newShapes[ s2Idx ].p ) ) {
  29303. if ( sIdx !== s2Idx ) toChange ++;
  29304. if ( hole_unassigned ) {
  29305. hole_unassigned = false;
  29306. betterShapeHoles[ s2Idx ].push( ho );
  29307. } else {
  29308. ambiguous = true;
  29309. }
  29310. }
  29311. }
  29312. if ( hole_unassigned ) {
  29313. betterShapeHoles[ sIdx ].push( ho );
  29314. }
  29315. }
  29316. }
  29317. if ( toChange > 0 && ambiguous === false ) {
  29318. newShapeHoles = betterShapeHoles;
  29319. }
  29320. }
  29321. let tmpHoles;
  29322. for ( let i = 0, il = newShapes.length; i < il; i ++ ) {
  29323. tmpShape = newShapes[ i ].s;
  29324. shapes.push( tmpShape );
  29325. tmpHoles = newShapeHoles[ i ];
  29326. for ( let j = 0, jl = tmpHoles.length; j < jl; j ++ ) {
  29327. tmpShape.holes.push( tmpHoles[ j ].h );
  29328. }
  29329. }
  29330. //console.log("shape", shapes);
  29331. return shapes;
  29332. }
  29333. }
  29334. // Fast Half Float Conversions, http://www.fox-toolkit.org/ftp/fasthalffloatconversion.pdf
  29335. const _tables = /*@__PURE__*/ _generateTables();
  29336. function _generateTables() {
  29337. // float32 to float16 helpers
  29338. const buffer = new ArrayBuffer( 4 );
  29339. const floatView = new Float32Array( buffer );
  29340. const uint32View = new Uint32Array( buffer );
  29341. const baseTable = new Uint32Array( 512 );
  29342. const shiftTable = new Uint32Array( 512 );
  29343. for ( let i = 0; i < 256; ++ i ) {
  29344. const e = i - 127;
  29345. // very small number (0, -0)
  29346. if ( e < - 27 ) {
  29347. baseTable[ i ] = 0x0000;
  29348. baseTable[ i | 0x100 ] = 0x8000;
  29349. shiftTable[ i ] = 24;
  29350. shiftTable[ i | 0x100 ] = 24;
  29351. // small number (denorm)
  29352. } else if ( e < - 14 ) {
  29353. baseTable[ i ] = 0x0400 >> ( - e - 14 );
  29354. baseTable[ i | 0x100 ] = ( 0x0400 >> ( - e - 14 ) ) | 0x8000;
  29355. shiftTable[ i ] = - e - 1;
  29356. shiftTable[ i | 0x100 ] = - e - 1;
  29357. // normal number
  29358. } else if ( e <= 15 ) {
  29359. baseTable[ i ] = ( e + 15 ) << 10;
  29360. baseTable[ i | 0x100 ] = ( ( e + 15 ) << 10 ) | 0x8000;
  29361. shiftTable[ i ] = 13;
  29362. shiftTable[ i | 0x100 ] = 13;
  29363. // large number (Infinity, -Infinity)
  29364. } else if ( e < 128 ) {
  29365. baseTable[ i ] = 0x7c00;
  29366. baseTable[ i | 0x100 ] = 0xfc00;
  29367. shiftTable[ i ] = 24;
  29368. shiftTable[ i | 0x100 ] = 24;
  29369. // stay (NaN, Infinity, -Infinity)
  29370. } else {
  29371. baseTable[ i ] = 0x7c00;
  29372. baseTable[ i | 0x100 ] = 0xfc00;
  29373. shiftTable[ i ] = 13;
  29374. shiftTable[ i | 0x100 ] = 13;
  29375. }
  29376. }
  29377. // float16 to float32 helpers
  29378. const mantissaTable = new Uint32Array( 2048 );
  29379. const exponentTable = new Uint32Array( 64 );
  29380. const offsetTable = new Uint32Array( 64 );
  29381. for ( let i = 1; i < 1024; ++ i ) {
  29382. let m = i << 13; // zero pad mantissa bits
  29383. let e = 0; // zero exponent
  29384. // normalized
  29385. while ( ( m & 0x00800000 ) === 0 ) {
  29386. m <<= 1;
  29387. e -= 0x00800000; // decrement exponent
  29388. }
  29389. m &= ~ 0x00800000; // clear leading 1 bit
  29390. e += 0x38800000; // adjust bias
  29391. mantissaTable[ i ] = m | e;
  29392. }
  29393. for ( let i = 1024; i < 2048; ++ i ) {
  29394. mantissaTable[ i ] = 0x38000000 + ( ( i - 1024 ) << 13 );
  29395. }
  29396. for ( let i = 1; i < 31; ++ i ) {
  29397. exponentTable[ i ] = i << 23;
  29398. }
  29399. exponentTable[ 31 ] = 0x47800000;
  29400. exponentTable[ 32 ] = 0x80000000;
  29401. for ( let i = 33; i < 63; ++ i ) {
  29402. exponentTable[ i ] = 0x80000000 + ( ( i - 32 ) << 23 );
  29403. }
  29404. exponentTable[ 63 ] = 0xc7800000;
  29405. for ( let i = 1; i < 64; ++ i ) {
  29406. if ( i !== 32 ) {
  29407. offsetTable[ i ] = 1024;
  29408. }
  29409. }
  29410. return {
  29411. floatView: floatView,
  29412. uint32View: uint32View,
  29413. baseTable: baseTable,
  29414. shiftTable: shiftTable,
  29415. mantissaTable: mantissaTable,
  29416. exponentTable: exponentTable,
  29417. offsetTable: offsetTable
  29418. };
  29419. }
  29420. // float32 to float16
  29421. function toHalfFloat( val ) {
  29422. if ( Math.abs( val ) > 65504 ) console.warn( 'THREE.DataUtils.toHalfFloat(): Value out of range.' );
  29423. val = clamp( val, - 65504, 65504 );
  29424. _tables.floatView[ 0 ] = val;
  29425. const f = _tables.uint32View[ 0 ];
  29426. const e = ( f >> 23 ) & 0x1ff;
  29427. return _tables.baseTable[ e ] + ( ( f & 0x007fffff ) >> _tables.shiftTable[ e ] );
  29428. }
  29429. // float16 to float32
  29430. function fromHalfFloat( val ) {
  29431. const m = val >> 10;
  29432. _tables.uint32View[ 0 ] = _tables.mantissaTable[ _tables.offsetTable[ m ] + ( val & 0x3ff ) ] + _tables.exponentTable[ m ];
  29433. return _tables.floatView[ 0 ];
  29434. }
  29435. var DataUtils = /*#__PURE__*/Object.freeze({
  29436. __proto__: null,
  29437. fromHalfFloat: fromHalfFloat,
  29438. toHalfFloat: toHalfFloat
  29439. });
  29440. // r144
  29441. class BoxBufferGeometry extends BoxGeometry {
  29442. constructor( width, height, depth, widthSegments, heightSegments, depthSegments ) {
  29443. console.warn( 'THREE.BoxBufferGeometry has been renamed to THREE.BoxGeometry.' );
  29444. super( width, height, depth, widthSegments, heightSegments, depthSegments );
  29445. }
  29446. }
  29447. // r144
  29448. class CapsuleBufferGeometry extends CapsuleGeometry {
  29449. constructor( radius, length, capSegments, radialSegments ) {
  29450. console.warn( 'THREE.CapsuleBufferGeometry has been renamed to THREE.CapsuleGeometry.' );
  29451. super( radius, length, capSegments, radialSegments );
  29452. }
  29453. }
  29454. // r144
  29455. class CircleBufferGeometry extends CircleGeometry {
  29456. constructor( radius, segments, thetaStart, thetaLength ) {
  29457. console.warn( 'THREE.CircleBufferGeometry has been renamed to THREE.CircleGeometry.' );
  29458. super( radius, segments, thetaStart, thetaLength );
  29459. }
  29460. }
  29461. // r144
  29462. class ConeBufferGeometry extends ConeGeometry {
  29463. constructor( radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) {
  29464. console.warn( 'THREE.ConeBufferGeometry has been renamed to THREE.ConeGeometry.' );
  29465. super( radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength );
  29466. }
  29467. }
  29468. // r144
  29469. class CylinderBufferGeometry extends CylinderGeometry {
  29470. constructor( radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) {
  29471. console.warn( 'THREE.CylinderBufferGeometry has been renamed to THREE.CylinderGeometry.' );
  29472. super( radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength );
  29473. }
  29474. }
  29475. // r144
  29476. class DodecahedronBufferGeometry extends DodecahedronGeometry {
  29477. constructor( radius, detail ) {
  29478. console.warn( 'THREE.DodecahedronBufferGeometry has been renamed to THREE.DodecahedronGeometry.' );
  29479. super( radius, detail );
  29480. }
  29481. }
  29482. // r144
  29483. class ExtrudeBufferGeometry extends ExtrudeGeometry {
  29484. constructor( shapes, options ) {
  29485. console.warn( 'THREE.ExtrudeBufferGeometry has been renamed to THREE.ExtrudeGeometry.' );
  29486. super( shapes, options );
  29487. }
  29488. }
  29489. // r144
  29490. class IcosahedronBufferGeometry extends IcosahedronGeometry {
  29491. constructor( radius, detail ) {
  29492. console.warn( 'THREE.IcosahedronBufferGeometry has been renamed to THREE.IcosahedronGeometry.' );
  29493. super( radius, detail );
  29494. }
  29495. }
  29496. // r144
  29497. class LatheBufferGeometry extends LatheGeometry {
  29498. constructor( points, segments, phiStart, phiLength ) {
  29499. console.warn( 'THREE.LatheBufferGeometry has been renamed to THREE.LatheGeometry.' );
  29500. super( points, segments, phiStart, phiLength );
  29501. }
  29502. }
  29503. // r144
  29504. class OctahedronBufferGeometry extends OctahedronGeometry {
  29505. constructor( radius, detail ) {
  29506. console.warn( 'THREE.OctahedronBufferGeometry has been renamed to THREE.OctahedronGeometry.' );
  29507. super( radius, detail );
  29508. }
  29509. }
  29510. // r144
  29511. class PlaneBufferGeometry extends PlaneGeometry {
  29512. constructor( width, height, widthSegments, heightSegments ) {
  29513. console.warn( 'THREE.PlaneBufferGeometry has been renamed to THREE.PlaneGeometry.' );
  29514. super( width, height, widthSegments, heightSegments );
  29515. }
  29516. }
  29517. // r144
  29518. class PolyhedronBufferGeometry extends PolyhedronGeometry {
  29519. constructor( vertices, indices, radius, detail ) {
  29520. console.warn( 'THREE.PolyhedronBufferGeometry has been renamed to THREE.PolyhedronGeometry.' );
  29521. super( vertices, indices, radius, detail );
  29522. }
  29523. }
  29524. // r144
  29525. class RingBufferGeometry extends RingGeometry {
  29526. constructor( innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength ) {
  29527. console.warn( 'THREE.RingBufferGeometry has been renamed to THREE.RingGeometry.' );
  29528. super( innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength );
  29529. }
  29530. }
  29531. // r144
  29532. class ShapeBufferGeometry extends ShapeGeometry {
  29533. constructor( shapes, curveSegments ) {
  29534. console.warn( 'THREE.ShapeBufferGeometry has been renamed to THREE.ShapeGeometry.' );
  29535. super( shapes, curveSegments );
  29536. }
  29537. }
  29538. // r144
  29539. class SphereBufferGeometry extends SphereGeometry {
  29540. constructor( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ) {
  29541. console.warn( 'THREE.SphereBufferGeometry has been renamed to THREE.SphereGeometry.' );
  29542. super( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength );
  29543. }
  29544. }
  29545. // r144
  29546. class TetrahedronBufferGeometry extends TetrahedronGeometry {
  29547. constructor( radius, detail ) {
  29548. console.warn( 'THREE.TetrahedronBufferGeometry has been renamed to THREE.TetrahedronGeometry.' );
  29549. super( radius, detail );
  29550. }
  29551. }
  29552. // r144
  29553. class TorusBufferGeometry extends TorusGeometry {
  29554. constructor( radius, tube, radialSegments, tubularSegments, arc ) {
  29555. console.warn( 'THREE.TorusBufferGeometry has been renamed to THREE.TorusGeometry.' );
  29556. super( radius, tube, radialSegments, tubularSegments, arc );
  29557. }
  29558. }
  29559. // r144
  29560. class TorusKnotBufferGeometry extends TorusKnotGeometry {
  29561. constructor( radius, tube, tubularSegments, radialSegments, p, q ) {
  29562. console.warn( 'THREE.TorusKnotBufferGeometry has been renamed to THREE.TorusKnotGeometry.' );
  29563. super( radius, tube, tubularSegments, radialSegments, p, q );
  29564. }
  29565. }
  29566. // r144
  29567. class TubeBufferGeometry extends TubeGeometry {
  29568. constructor( path, tubularSegments, radius, radialSegments, closed ) {
  29569. console.warn( 'THREE.TubeBufferGeometry has been renamed to THREE.TubeGeometry.' );
  29570. super( path, tubularSegments, radius, radialSegments, closed );
  29571. }
  29572. }
  29573. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  29574. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'register', { detail: {
  29575. revision: REVISION,
  29576. } } ) );
  29577. }
  29578. if ( typeof window !== 'undefined' ) {
  29579. if ( window.__THREE__ ) {
  29580. console.warn( 'WARNING: Multiple instances of Three.js being imported.' );
  29581. } else {
  29582. window.__THREE__ = REVISION;
  29583. }
  29584. }
  29585. exports.ACESFilmicToneMapping = ACESFilmicToneMapping;
  29586. exports.AddEquation = AddEquation;
  29587. exports.AddOperation = AddOperation;
  29588. exports.AdditiveAnimationBlendMode = AdditiveAnimationBlendMode;
  29589. exports.AdditiveBlending = AdditiveBlending;
  29590. exports.AlphaFormat = AlphaFormat;
  29591. exports.AlwaysDepth = AlwaysDepth;
  29592. exports.AlwaysStencilFunc = AlwaysStencilFunc;
  29593. exports.AmbientLight = AmbientLight;
  29594. exports.AmbientLightProbe = AmbientLightProbe;
  29595. exports.AnimationClip = AnimationClip;
  29596. exports.AnimationLoader = AnimationLoader;
  29597. exports.AnimationMixer = AnimationMixer;
  29598. exports.AnimationObjectGroup = AnimationObjectGroup;
  29599. exports.AnimationUtils = AnimationUtils;
  29600. exports.ArcCurve = ArcCurve;
  29601. exports.ArrayCamera = ArrayCamera;
  29602. exports.ArrowHelper = ArrowHelper;
  29603. exports.Audio = Audio;
  29604. exports.AudioAnalyser = AudioAnalyser;
  29605. exports.AudioContext = AudioContext;
  29606. exports.AudioListener = AudioListener;
  29607. exports.AudioLoader = AudioLoader;
  29608. exports.AxesHelper = AxesHelper;
  29609. exports.BackSide = BackSide;
  29610. exports.BasicDepthPacking = BasicDepthPacking;
  29611. exports.BasicShadowMap = BasicShadowMap;
  29612. exports.Bone = Bone;
  29613. exports.BooleanKeyframeTrack = BooleanKeyframeTrack;
  29614. exports.Box2 = Box2;
  29615. exports.Box3 = Box3;
  29616. exports.Box3Helper = Box3Helper;
  29617. exports.BoxBufferGeometry = BoxBufferGeometry;
  29618. exports.BoxGeometry = BoxGeometry;
  29619. exports.BoxHelper = BoxHelper;
  29620. exports.BufferAttribute = BufferAttribute;
  29621. exports.BufferGeometry = BufferGeometry;
  29622. exports.BufferGeometryLoader = BufferGeometryLoader;
  29623. exports.ByteType = ByteType;
  29624. exports.Cache = Cache;
  29625. exports.Camera = Camera;
  29626. exports.CameraHelper = CameraHelper;
  29627. exports.CanvasTexture = CanvasTexture;
  29628. exports.CapsuleBufferGeometry = CapsuleBufferGeometry;
  29629. exports.CapsuleGeometry = CapsuleGeometry;
  29630. exports.CatmullRomCurve3 = CatmullRomCurve3;
  29631. exports.CineonToneMapping = CineonToneMapping;
  29632. exports.CircleBufferGeometry = CircleBufferGeometry;
  29633. exports.CircleGeometry = CircleGeometry;
  29634. exports.ClampToEdgeWrapping = ClampToEdgeWrapping;
  29635. exports.Clock = Clock;
  29636. exports.Color = Color;
  29637. exports.ColorKeyframeTrack = ColorKeyframeTrack;
  29638. exports.ColorManagement = ColorManagement;
  29639. exports.CompressedArrayTexture = CompressedArrayTexture;
  29640. exports.CompressedTexture = CompressedTexture;
  29641. exports.CompressedTextureLoader = CompressedTextureLoader;
  29642. exports.ConeBufferGeometry = ConeBufferGeometry;
  29643. exports.ConeGeometry = ConeGeometry;
  29644. exports.CubeCamera = CubeCamera;
  29645. exports.CubeReflectionMapping = CubeReflectionMapping;
  29646. exports.CubeRefractionMapping = CubeRefractionMapping;
  29647. exports.CubeTexture = CubeTexture;
  29648. exports.CubeTextureLoader = CubeTextureLoader;
  29649. exports.CubeUVReflectionMapping = CubeUVReflectionMapping;
  29650. exports.CubicBezierCurve = CubicBezierCurve;
  29651. exports.CubicBezierCurve3 = CubicBezierCurve3;
  29652. exports.CubicInterpolant = CubicInterpolant;
  29653. exports.CullFaceBack = CullFaceBack;
  29654. exports.CullFaceFront = CullFaceFront;
  29655. exports.CullFaceFrontBack = CullFaceFrontBack;
  29656. exports.CullFaceNone = CullFaceNone;
  29657. exports.Curve = Curve;
  29658. exports.CurvePath = CurvePath;
  29659. exports.CustomBlending = CustomBlending;
  29660. exports.CustomToneMapping = CustomToneMapping;
  29661. exports.CylinderBufferGeometry = CylinderBufferGeometry;
  29662. exports.CylinderGeometry = CylinderGeometry;
  29663. exports.Cylindrical = Cylindrical;
  29664. exports.Data3DTexture = Data3DTexture;
  29665. exports.DataArrayTexture = DataArrayTexture;
  29666. exports.DataTexture = DataTexture;
  29667. exports.DataTextureLoader = DataTextureLoader;
  29668. exports.DataUtils = DataUtils;
  29669. exports.DecrementStencilOp = DecrementStencilOp;
  29670. exports.DecrementWrapStencilOp = DecrementWrapStencilOp;
  29671. exports.DefaultLoadingManager = DefaultLoadingManager;
  29672. exports.DepthFormat = DepthFormat;
  29673. exports.DepthStencilFormat = DepthStencilFormat;
  29674. exports.DepthTexture = DepthTexture;
  29675. exports.DirectionalLight = DirectionalLight;
  29676. exports.DirectionalLightHelper = DirectionalLightHelper;
  29677. exports.DiscreteInterpolant = DiscreteInterpolant;
  29678. exports.DodecahedronBufferGeometry = DodecahedronBufferGeometry;
  29679. exports.DodecahedronGeometry = DodecahedronGeometry;
  29680. exports.DoubleSide = DoubleSide;
  29681. exports.DstAlphaFactor = DstAlphaFactor;
  29682. exports.DstColorFactor = DstColorFactor;
  29683. exports.DynamicCopyUsage = DynamicCopyUsage;
  29684. exports.DynamicDrawUsage = DynamicDrawUsage;
  29685. exports.DynamicReadUsage = DynamicReadUsage;
  29686. exports.EdgesGeometry = EdgesGeometry;
  29687. exports.EllipseCurve = EllipseCurve;
  29688. exports.EqualDepth = EqualDepth;
  29689. exports.EqualStencilFunc = EqualStencilFunc;
  29690. exports.EquirectangularReflectionMapping = EquirectangularReflectionMapping;
  29691. exports.EquirectangularRefractionMapping = EquirectangularRefractionMapping;
  29692. exports.Euler = Euler;
  29693. exports.EventDispatcher = EventDispatcher;
  29694. exports.ExtrudeBufferGeometry = ExtrudeBufferGeometry;
  29695. exports.ExtrudeGeometry = ExtrudeGeometry;
  29696. exports.FileLoader = FileLoader;
  29697. exports.Float16BufferAttribute = Float16BufferAttribute;
  29698. exports.Float32BufferAttribute = Float32BufferAttribute;
  29699. exports.Float64BufferAttribute = Float64BufferAttribute;
  29700. exports.FloatType = FloatType;
  29701. exports.Fog = Fog;
  29702. exports.FogExp2 = FogExp2;
  29703. exports.FramebufferTexture = FramebufferTexture;
  29704. exports.FrontSide = FrontSide;
  29705. exports.Frustum = Frustum;
  29706. exports.GLBufferAttribute = GLBufferAttribute;
  29707. exports.GLSL1 = GLSL1;
  29708. exports.GLSL3 = GLSL3;
  29709. exports.GreaterDepth = GreaterDepth;
  29710. exports.GreaterEqualDepth = GreaterEqualDepth;
  29711. exports.GreaterEqualStencilFunc = GreaterEqualStencilFunc;
  29712. exports.GreaterStencilFunc = GreaterStencilFunc;
  29713. exports.GridHelper = GridHelper;
  29714. exports.Group = Group;
  29715. exports.HalfFloatType = HalfFloatType;
  29716. exports.HemisphereLight = HemisphereLight;
  29717. exports.HemisphereLightHelper = HemisphereLightHelper;
  29718. exports.HemisphereLightProbe = HemisphereLightProbe;
  29719. exports.IcosahedronBufferGeometry = IcosahedronBufferGeometry;
  29720. exports.IcosahedronGeometry = IcosahedronGeometry;
  29721. exports.ImageBitmapLoader = ImageBitmapLoader;
  29722. exports.ImageLoader = ImageLoader;
  29723. exports.ImageUtils = ImageUtils;
  29724. exports.IncrementStencilOp = IncrementStencilOp;
  29725. exports.IncrementWrapStencilOp = IncrementWrapStencilOp;
  29726. exports.InstancedBufferAttribute = InstancedBufferAttribute;
  29727. exports.InstancedBufferGeometry = InstancedBufferGeometry;
  29728. exports.InstancedInterleavedBuffer = InstancedInterleavedBuffer;
  29729. exports.InstancedMesh = InstancedMesh;
  29730. exports.Int16BufferAttribute = Int16BufferAttribute;
  29731. exports.Int32BufferAttribute = Int32BufferAttribute;
  29732. exports.Int8BufferAttribute = Int8BufferAttribute;
  29733. exports.IntType = IntType;
  29734. exports.InterleavedBuffer = InterleavedBuffer;
  29735. exports.InterleavedBufferAttribute = InterleavedBufferAttribute;
  29736. exports.Interpolant = Interpolant;
  29737. exports.InterpolateDiscrete = InterpolateDiscrete;
  29738. exports.InterpolateLinear = InterpolateLinear;
  29739. exports.InterpolateSmooth = InterpolateSmooth;
  29740. exports.InvertStencilOp = InvertStencilOp;
  29741. exports.KeepStencilOp = KeepStencilOp;
  29742. exports.KeyframeTrack = KeyframeTrack;
  29743. exports.LOD = LOD;
  29744. exports.LatheBufferGeometry = LatheBufferGeometry;
  29745. exports.LatheGeometry = LatheGeometry;
  29746. exports.Layers = Layers;
  29747. exports.LessDepth = LessDepth;
  29748. exports.LessEqualDepth = LessEqualDepth;
  29749. exports.LessEqualStencilFunc = LessEqualStencilFunc;
  29750. exports.LessStencilFunc = LessStencilFunc;
  29751. exports.Light = Light;
  29752. exports.LightProbe = LightProbe;
  29753. exports.Line = Line;
  29754. exports.Line3 = Line3;
  29755. exports.LineBasicMaterial = LineBasicMaterial;
  29756. exports.LineCurve = LineCurve;
  29757. exports.LineCurve3 = LineCurve3;
  29758. exports.LineDashedMaterial = LineDashedMaterial;
  29759. exports.LineLoop = LineLoop;
  29760. exports.LineSegments = LineSegments;
  29761. exports.LinearEncoding = LinearEncoding;
  29762. exports.LinearFilter = LinearFilter;
  29763. exports.LinearInterpolant = LinearInterpolant;
  29764. exports.LinearMipMapLinearFilter = LinearMipMapLinearFilter;
  29765. exports.LinearMipMapNearestFilter = LinearMipMapNearestFilter;
  29766. exports.LinearMipmapLinearFilter = LinearMipmapLinearFilter;
  29767. exports.LinearMipmapNearestFilter = LinearMipmapNearestFilter;
  29768. exports.LinearSRGBColorSpace = LinearSRGBColorSpace;
  29769. exports.LinearToneMapping = LinearToneMapping;
  29770. exports.Loader = Loader;
  29771. exports.LoaderUtils = LoaderUtils;
  29772. exports.LoadingManager = LoadingManager;
  29773. exports.LoopOnce = LoopOnce;
  29774. exports.LoopPingPong = LoopPingPong;
  29775. exports.LoopRepeat = LoopRepeat;
  29776. exports.LuminanceAlphaFormat = LuminanceAlphaFormat;
  29777. exports.LuminanceFormat = LuminanceFormat;
  29778. exports.MOUSE = MOUSE;
  29779. exports.Material = Material;
  29780. exports.MaterialLoader = MaterialLoader;
  29781. exports.MathUtils = MathUtils;
  29782. exports.Matrix3 = Matrix3;
  29783. exports.Matrix4 = Matrix4;
  29784. exports.MaxEquation = MaxEquation;
  29785. exports.Mesh = Mesh;
  29786. exports.MeshBasicMaterial = MeshBasicMaterial;
  29787. exports.MeshDepthMaterial = MeshDepthMaterial;
  29788. exports.MeshDistanceMaterial = MeshDistanceMaterial;
  29789. exports.MeshLambertMaterial = MeshLambertMaterial;
  29790. exports.MeshMatcapMaterial = MeshMatcapMaterial;
  29791. exports.MeshNormalMaterial = MeshNormalMaterial;
  29792. exports.MeshPhongMaterial = MeshPhongMaterial;
  29793. exports.MeshPhysicalMaterial = MeshPhysicalMaterial;
  29794. exports.MeshStandardMaterial = MeshStandardMaterial;
  29795. exports.MeshToonMaterial = MeshToonMaterial;
  29796. exports.MinEquation = MinEquation;
  29797. exports.MirroredRepeatWrapping = MirroredRepeatWrapping;
  29798. exports.MixOperation = MixOperation;
  29799. exports.MultiplyBlending = MultiplyBlending;
  29800. exports.MultiplyOperation = MultiplyOperation;
  29801. exports.NearestFilter = NearestFilter;
  29802. exports.NearestMipMapLinearFilter = NearestMipMapLinearFilter;
  29803. exports.NearestMipMapNearestFilter = NearestMipMapNearestFilter;
  29804. exports.NearestMipmapLinearFilter = NearestMipmapLinearFilter;
  29805. exports.NearestMipmapNearestFilter = NearestMipmapNearestFilter;
  29806. exports.NeverDepth = NeverDepth;
  29807. exports.NeverStencilFunc = NeverStencilFunc;
  29808. exports.NoBlending = NoBlending;
  29809. exports.NoColorSpace = NoColorSpace;
  29810. exports.NoToneMapping = NoToneMapping;
  29811. exports.NormalAnimationBlendMode = NormalAnimationBlendMode;
  29812. exports.NormalBlending = NormalBlending;
  29813. exports.NotEqualDepth = NotEqualDepth;
  29814. exports.NotEqualStencilFunc = NotEqualStencilFunc;
  29815. exports.NumberKeyframeTrack = NumberKeyframeTrack;
  29816. exports.Object3D = Object3D;
  29817. exports.ObjectLoader = ObjectLoader;
  29818. exports.ObjectSpaceNormalMap = ObjectSpaceNormalMap;
  29819. exports.OctahedronBufferGeometry = OctahedronBufferGeometry;
  29820. exports.OctahedronGeometry = OctahedronGeometry;
  29821. exports.OneFactor = OneFactor;
  29822. exports.OneMinusDstAlphaFactor = OneMinusDstAlphaFactor;
  29823. exports.OneMinusDstColorFactor = OneMinusDstColorFactor;
  29824. exports.OneMinusSrcAlphaFactor = OneMinusSrcAlphaFactor;
  29825. exports.OneMinusSrcColorFactor = OneMinusSrcColorFactor;
  29826. exports.OrthographicCamera = OrthographicCamera;
  29827. exports.PCFShadowMap = PCFShadowMap;
  29828. exports.PCFSoftShadowMap = PCFSoftShadowMap;
  29829. exports.PMREMGenerator = PMREMGenerator;
  29830. exports.Path = Path;
  29831. exports.PerspectiveCamera = PerspectiveCamera;
  29832. exports.Plane = Plane;
  29833. exports.PlaneBufferGeometry = PlaneBufferGeometry;
  29834. exports.PlaneGeometry = PlaneGeometry;
  29835. exports.PlaneHelper = PlaneHelper;
  29836. exports.PointLight = PointLight;
  29837. exports.PointLightHelper = PointLightHelper;
  29838. exports.Points = Points;
  29839. exports.PointsMaterial = PointsMaterial;
  29840. exports.PolarGridHelper = PolarGridHelper;
  29841. exports.PolyhedronBufferGeometry = PolyhedronBufferGeometry;
  29842. exports.PolyhedronGeometry = PolyhedronGeometry;
  29843. exports.PositionalAudio = PositionalAudio;
  29844. exports.PropertyBinding = PropertyBinding;
  29845. exports.PropertyMixer = PropertyMixer;
  29846. exports.QuadraticBezierCurve = QuadraticBezierCurve;
  29847. exports.QuadraticBezierCurve3 = QuadraticBezierCurve3;
  29848. exports.Quaternion = Quaternion;
  29849. exports.QuaternionKeyframeTrack = QuaternionKeyframeTrack;
  29850. exports.QuaternionLinearInterpolant = QuaternionLinearInterpolant;
  29851. exports.RED_GREEN_RGTC2_Format = RED_GREEN_RGTC2_Format;
  29852. exports.RED_RGTC1_Format = RED_RGTC1_Format;
  29853. exports.REVISION = REVISION;
  29854. exports.RGBADepthPacking = RGBADepthPacking;
  29855. exports.RGBAFormat = RGBAFormat;
  29856. exports.RGBAIntegerFormat = RGBAIntegerFormat;
  29857. exports.RGBA_ASTC_10x10_Format = RGBA_ASTC_10x10_Format;
  29858. exports.RGBA_ASTC_10x5_Format = RGBA_ASTC_10x5_Format;
  29859. exports.RGBA_ASTC_10x6_Format = RGBA_ASTC_10x6_Format;
  29860. exports.RGBA_ASTC_10x8_Format = RGBA_ASTC_10x8_Format;
  29861. exports.RGBA_ASTC_12x10_Format = RGBA_ASTC_12x10_Format;
  29862. exports.RGBA_ASTC_12x12_Format = RGBA_ASTC_12x12_Format;
  29863. exports.RGBA_ASTC_4x4_Format = RGBA_ASTC_4x4_Format;
  29864. exports.RGBA_ASTC_5x4_Format = RGBA_ASTC_5x4_Format;
  29865. exports.RGBA_ASTC_5x5_Format = RGBA_ASTC_5x5_Format;
  29866. exports.RGBA_ASTC_6x5_Format = RGBA_ASTC_6x5_Format;
  29867. exports.RGBA_ASTC_6x6_Format = RGBA_ASTC_6x6_Format;
  29868. exports.RGBA_ASTC_8x5_Format = RGBA_ASTC_8x5_Format;
  29869. exports.RGBA_ASTC_8x6_Format = RGBA_ASTC_8x6_Format;
  29870. exports.RGBA_ASTC_8x8_Format = RGBA_ASTC_8x8_Format;
  29871. exports.RGBA_BPTC_Format = RGBA_BPTC_Format;
  29872. exports.RGBA_ETC2_EAC_Format = RGBA_ETC2_EAC_Format;
  29873. exports.RGBA_PVRTC_2BPPV1_Format = RGBA_PVRTC_2BPPV1_Format;
  29874. exports.RGBA_PVRTC_4BPPV1_Format = RGBA_PVRTC_4BPPV1_Format;
  29875. exports.RGBA_S3TC_DXT1_Format = RGBA_S3TC_DXT1_Format;
  29876. exports.RGBA_S3TC_DXT3_Format = RGBA_S3TC_DXT3_Format;
  29877. exports.RGBA_S3TC_DXT5_Format = RGBA_S3TC_DXT5_Format;
  29878. exports.RGB_ETC1_Format = RGB_ETC1_Format;
  29879. exports.RGB_ETC2_Format = RGB_ETC2_Format;
  29880. exports.RGB_PVRTC_2BPPV1_Format = RGB_PVRTC_2BPPV1_Format;
  29881. exports.RGB_PVRTC_4BPPV1_Format = RGB_PVRTC_4BPPV1_Format;
  29882. exports.RGB_S3TC_DXT1_Format = RGB_S3TC_DXT1_Format;
  29883. exports.RGFormat = RGFormat;
  29884. exports.RGIntegerFormat = RGIntegerFormat;
  29885. exports.RawShaderMaterial = RawShaderMaterial;
  29886. exports.Ray = Ray;
  29887. exports.Raycaster = Raycaster;
  29888. exports.RectAreaLight = RectAreaLight;
  29889. exports.RedFormat = RedFormat;
  29890. exports.RedIntegerFormat = RedIntegerFormat;
  29891. exports.ReinhardToneMapping = ReinhardToneMapping;
  29892. exports.RepeatWrapping = RepeatWrapping;
  29893. exports.ReplaceStencilOp = ReplaceStencilOp;
  29894. exports.ReverseSubtractEquation = ReverseSubtractEquation;
  29895. exports.RingBufferGeometry = RingBufferGeometry;
  29896. exports.RingGeometry = RingGeometry;
  29897. exports.SIGNED_RED_GREEN_RGTC2_Format = SIGNED_RED_GREEN_RGTC2_Format;
  29898. exports.SIGNED_RED_RGTC1_Format = SIGNED_RED_RGTC1_Format;
  29899. exports.SRGBColorSpace = SRGBColorSpace;
  29900. exports.Scene = Scene;
  29901. exports.ShaderChunk = ShaderChunk;
  29902. exports.ShaderLib = ShaderLib;
  29903. exports.ShaderMaterial = ShaderMaterial;
  29904. exports.ShadowMaterial = ShadowMaterial;
  29905. exports.Shape = Shape;
  29906. exports.ShapeBufferGeometry = ShapeBufferGeometry;
  29907. exports.ShapeGeometry = ShapeGeometry;
  29908. exports.ShapePath = ShapePath;
  29909. exports.ShapeUtils = ShapeUtils;
  29910. exports.ShortType = ShortType;
  29911. exports.Skeleton = Skeleton;
  29912. exports.SkeletonHelper = SkeletonHelper;
  29913. exports.SkinnedMesh = SkinnedMesh;
  29914. exports.Source = Source;
  29915. exports.Sphere = Sphere;
  29916. exports.SphereBufferGeometry = SphereBufferGeometry;
  29917. exports.SphereGeometry = SphereGeometry;
  29918. exports.Spherical = Spherical;
  29919. exports.SphericalHarmonics3 = SphericalHarmonics3;
  29920. exports.SplineCurve = SplineCurve;
  29921. exports.SpotLight = SpotLight;
  29922. exports.SpotLightHelper = SpotLightHelper;
  29923. exports.Sprite = Sprite;
  29924. exports.SpriteMaterial = SpriteMaterial;
  29925. exports.SrcAlphaFactor = SrcAlphaFactor;
  29926. exports.SrcAlphaSaturateFactor = SrcAlphaSaturateFactor;
  29927. exports.SrcColorFactor = SrcColorFactor;
  29928. exports.StaticCopyUsage = StaticCopyUsage;
  29929. exports.StaticDrawUsage = StaticDrawUsage;
  29930. exports.StaticReadUsage = StaticReadUsage;
  29931. exports.StereoCamera = StereoCamera;
  29932. exports.StreamCopyUsage = StreamCopyUsage;
  29933. exports.StreamDrawUsage = StreamDrawUsage;
  29934. exports.StreamReadUsage = StreamReadUsage;
  29935. exports.StringKeyframeTrack = StringKeyframeTrack;
  29936. exports.SubtractEquation = SubtractEquation;
  29937. exports.SubtractiveBlending = SubtractiveBlending;
  29938. exports.TOUCH = TOUCH;
  29939. exports.TangentSpaceNormalMap = TangentSpaceNormalMap;
  29940. exports.TetrahedronBufferGeometry = TetrahedronBufferGeometry;
  29941. exports.TetrahedronGeometry = TetrahedronGeometry;
  29942. exports.Texture = Texture;
  29943. exports.TextureLoader = TextureLoader;
  29944. exports.TorusBufferGeometry = TorusBufferGeometry;
  29945. exports.TorusGeometry = TorusGeometry;
  29946. exports.TorusKnotBufferGeometry = TorusKnotBufferGeometry;
  29947. exports.TorusKnotGeometry = TorusKnotGeometry;
  29948. exports.Triangle = Triangle;
  29949. exports.TriangleFanDrawMode = TriangleFanDrawMode;
  29950. exports.TriangleStripDrawMode = TriangleStripDrawMode;
  29951. exports.TrianglesDrawMode = TrianglesDrawMode;
  29952. exports.TubeBufferGeometry = TubeBufferGeometry;
  29953. exports.TubeGeometry = TubeGeometry;
  29954. exports.TwoPassDoubleSide = TwoPassDoubleSide;
  29955. exports.UVMapping = UVMapping;
  29956. exports.Uint16BufferAttribute = Uint16BufferAttribute;
  29957. exports.Uint32BufferAttribute = Uint32BufferAttribute;
  29958. exports.Uint8BufferAttribute = Uint8BufferAttribute;
  29959. exports.Uint8ClampedBufferAttribute = Uint8ClampedBufferAttribute;
  29960. exports.Uniform = Uniform;
  29961. exports.UniformsGroup = UniformsGroup;
  29962. exports.UniformsLib = UniformsLib;
  29963. exports.UniformsUtils = UniformsUtils;
  29964. exports.UnsignedByteType = UnsignedByteType;
  29965. exports.UnsignedInt248Type = UnsignedInt248Type;
  29966. exports.UnsignedIntType = UnsignedIntType;
  29967. exports.UnsignedShort4444Type = UnsignedShort4444Type;
  29968. exports.UnsignedShort5551Type = UnsignedShort5551Type;
  29969. exports.UnsignedShortType = UnsignedShortType;
  29970. exports.VSMShadowMap = VSMShadowMap;
  29971. exports.Vector2 = Vector2;
  29972. exports.Vector3 = Vector3;
  29973. exports.Vector4 = Vector4;
  29974. exports.VectorKeyframeTrack = VectorKeyframeTrack;
  29975. exports.VideoTexture = VideoTexture;
  29976. exports.WebGL1Renderer = WebGL1Renderer;
  29977. exports.WebGL3DRenderTarget = WebGL3DRenderTarget;
  29978. exports.WebGLArrayRenderTarget = WebGLArrayRenderTarget;
  29979. exports.WebGLCubeRenderTarget = WebGLCubeRenderTarget;
  29980. exports.WebGLMultipleRenderTargets = WebGLMultipleRenderTargets;
  29981. exports.WebGLRenderTarget = WebGLRenderTarget;
  29982. exports.WebGLRenderer = WebGLRenderer;
  29983. exports.WebGLUtils = WebGLUtils;
  29984. exports.WireframeGeometry = WireframeGeometry;
  29985. exports.WrapAroundEnding = WrapAroundEnding;
  29986. exports.ZeroCurvatureEnding = ZeroCurvatureEnding;
  29987. exports.ZeroFactor = ZeroFactor;
  29988. exports.ZeroSlopeEnding = ZeroSlopeEnding;
  29989. exports.ZeroStencilOp = ZeroStencilOp;
  29990. exports._SRGBAFormat = _SRGBAFormat;
  29991. exports.sRGBEncoding = sRGBEncoding;
  29992. }));